]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
hack to handle state abreviations that overlap with 'the' in various non-english...
[nominatim.git] / utils / update.php
1 #!/usr/bin/php -Cq
2 <?php
3
4         require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5         ini_set('memory_limit', '800M');
6
7         $aCMDOptions = array(
8                 "Import / update / index osm data",
9                 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
10                 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
11                 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
12
13                 array('max-load', '', 0, 1, 1, 1, 'float', 'Maximum load average - indexing is paused if this is exceeded'),
14                 array('max-blocking', '', 0, 1, 1, 1, 'int', 'Maximum blocking processes - indexing is aborted / paused if this is exceeded'),
15
16                 array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'),
17                 array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'),
18
19                 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
20
21                 array('import-hourly', '', 0, 1, 0, 0, 'bool', 'Import hourly diffs'),
22                 array('import-daily', '', 0, 1, 0, 0, 'bool', 'Import daily diffs'),
23                 array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
24
25                 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
26                 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
27
28                 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
29                 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
30                 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
31
32                 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
33                 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
34                 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
35                 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
36
37                 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
38         );
39         getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
40
41         if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
42         {
43                 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
44         }
45
46         if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
47 /*
48         // Lock to prevent multiple copies running
49         if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
50         {
51                 echo "Copy already running\n";
52                 exit;
53         }
54         if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
55         if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
56         if (getBlockingProcesses() > $aResult['max-blocking'])
57         {
58                 echo "Too many blocking processes for import\n";
59                 exit;
60         }
61 */
62
63         // Assume osm2pgsql is in the folder above
64         $sBasePath = dirname(dirname(__FILE__));
65
66         $oDB =& getDB();
67
68         $bFirst = true;
69         $bContinue = $aResult['import-all'];
70         while ($bContinue || $bFirst)
71         {
72                 $bFirst = false;
73
74                 if ($aResult['import-hourly'])
75                 {
76                         // Mirror the hourly diffs
77                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
78                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
79                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
80                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
81                 }
82
83                 if ($aResult['import-daily'])
84                 {
85                         // Mirror the daily diffs
86                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
87                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
88                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
89                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
90                 }
91                 
92                 if (isset($aResult['import-diff']))
93                 {
94                         // import diff directly (e.g. from osmosis --rri)
95                         $sNextFile = $aResult['import-diff'];
96                         if (!file_exists($nextFile))
97                         {
98                                 echo "Cannot open $nextFile\n";
99                                 exit;
100                         }
101                         // Don't update the import status - we don't know what this file contains
102                         $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
103                 }
104
105                 // Missing file is not an error - it might not be created yet
106                 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
107                 {
108                         // Import the file
109                         $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
110                         echo $sCMD."\n";
111                         exec($sCMD, $sJunk, $iErrorLevel);
112
113                         if ($iErrorLevel)
114                         {
115                                 echo "Error from osm2pgsql, $iErrorLevel\n";
116                                 exit;
117                         }
118         
119                         // Move the date onwards
120                         $oDB->query($sUpdateSQL);
121                 }
122                 else
123                 {
124                         $bContinue = false;
125                 }
126         }
127
128         $sModifyXML = false;
129         if (isset($aResult['import-file']) && $aResult['import-file'])
130         {
131                 $sModifyXML = file_get_contents($aResult['import-file']);
132         }
133         if (isset($aResult['import-node']) && $aResult['import-node'])
134         {
135                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
136         }
137         if (isset($aResult['import-way']) && $aResult['import-way'])
138         {
139                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
140         }
141         if (isset($aResult['import-relation']) && $aResult['import-relation'])
142         {
143                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
144         }
145         if ($sModifyXML)
146         {
147                 // Hack into a modify request
148                 $sModifyXML = str_replace('<osm version="0.6" generator="OpenStreetMap server">',
149                         '<osmChange version="0.6" generator="OpenStreetMap server"><modify>', $sModifyXML);
150                 $sModifyXML = str_replace('</osm>', '</modify></osmChange>', $sModifyXML);
151
152                 // Outputing this is too verbose
153                 if ($aResult['verbose'] && false) var_dump($sModifyXML);
154
155                 $sDatabaseName = 'nominatim';
156                 $aSpec = array(
157                         0 => array("pipe", "r"),  // stdin
158                         1 => array("pipe", "w"),  // stdout
159                         2 => array("pipe", "w") // stderr
160                 );
161                 $aPipes = array();
162                 $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
163                 echo $sCMD."\n";
164                 $hProc = proc_open($sCMD, $aSpec, $aPipes);
165                 if (!is_resource($hProc))
166                 {
167                         echo "$sBasePath/osm2pgsql failed\n";
168                         exit;   
169                 }
170                 fwrite($aPipes[0], $sModifyXML);
171                 fclose($aPipes[0]);
172                 $sOut = stream_get_contents($aPipes[1]);
173                 if ($aResult['verbose']) echo $sOut;
174                 fclose($aPipes[1]);
175                 $sErrors = stream_get_contents($aPipes[2]);
176                 if ($aResult['verbose']) echo $sErrors;
177                 fclose($aPipes[2]);
178                 if ($iError = proc_close($hProc))
179                 {
180                         echo "osm2pgsql existed with error level $iError\n";
181                         echo $sOut;
182                         echo $sErrors;
183                         exit;
184                 }
185         }
186
187         if ($aResult['deduplicate'])
188         {
189                 $oDB =& getDB();
190                 $sSQL = 'select partition from country_name order by country_code';
191                 $aPartitions = $oDB->getCol($sSQL);
192                 if (PEAR::isError($aPartitions))
193                 {
194                         fail($aPartitions->getMessage());
195                 }
196                 $aPartitions[] = 0;
197
198                 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token";
199                 $aDuplicateTokens = $oDB->getAll($sSQL);
200                 foreach($aDuplicateTokens as $aToken)
201                 {
202                         if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
203                         echo "Deduping ".$aToken['word_token']."\n";
204                         $sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc";
205                         $aTokenSet = $oDB->getAll($sSQL);
206                         if (PEAR::isError($aTokenSet))
207                         {
208                                 var_dump($aTokenSet, $sSQL);
209                                 exit;
210                         }
211                         
212                         $aKeep = array_shift($aTokenSet);
213                         $iKeepID = $aKeep['word_id'];
214
215                         foreach($aTokenSet as $aRemove)
216                         {
217                                 $sSQL = "update search_name set";
218                                 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
219                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
220                                 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
221                                 $x = $oDB->query($sSQL);
222                                 if (PEAR::isError($x))
223                                 {
224                                         var_dump($x);
225                                         exit;
226                                 }
227
228                                 $sSQL = "update search_name set";
229                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
230                                 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
231                                 $x = $oDB->query($sSQL);
232                                 if (PEAR::isError($x))
233                                 {
234                                         var_dump($x);
235                                         exit;
236                                 }
237
238                                 $sSQL = "update location_area_country set";
239                                 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
240                                 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
241                                 $x = $oDB->query($sSQL);
242                                 if (PEAR::isError($x))
243                                 {
244                                         var_dump($x);
245                                         exit;
246                                 }
247
248                                 foreach ($aPartitions as $sPartition)
249                                 {
250                                         $sSQL = "update search_name_".$sPartition." set";
251                                         $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
252                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
253                                         $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
254                                         $x = $oDB->query($sSQL);
255                                         if (PEAR::isError($x))
256                                         {
257                                                 var_dump($x);
258                                                 exit;
259                                         }
260
261                                         $sSQL = "update search_name_".$sPartition." set";
262                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
263                                         $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
264                                         $x = $oDB->query($sSQL);
265                                         if (PEAR::isError($x))
266                                         {
267                                                 var_dump($x);
268                                                 exit;
269                                         }
270
271                                         $sSQL = "update location_area_country set";
272                                         $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
273                                         $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
274                                         $x = $oDB->query($sSQL);
275                                         if (PEAR::isError($x))
276                                         {
277                                                 var_dump($x);
278                                                 exit;
279                                         }
280                                 }
281
282                                 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
283                                 $x = $oDB->query($sSQL);
284                                 if (PEAR::isError($x))
285                                 {
286                                         var_dump($x);
287                                         exit;
288                                 }
289                         }
290
291                 }
292         }
293
294         if ($aResult['index'])
295         {
296                 index($aResult, $sDatabaseDSN);
297         }
298
299         if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
300         {
301                 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
302                 $sOsmosisCMD = CONST_BasePath.'/osmosis-0.38/bin/osmosis';
303                 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
304                 $sDatabaseName = 'nominatim';
305                 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
306                 $sCMDImport = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sImportFile;
307                 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -t 15 -F ';
308 //              $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -t 15 ';
309                 while(true)
310                 {
311                         $fStartTime = time();
312                         $iFileSize = 1001;
313
314                         // Logic behind this is that osm2pgsql locks the database quite a bit
315                         // So it is better to import lots of small files
316                         // But indexing works most efficiently on large amounts of data
317                         // So do lots of small imports and a BIG index
318
319 //                      while($aResult['import-osmosis-all'] && $iFileSize > 1000)
320 //                      {
321                                 if (!file_exists($sImportFile))
322                                 {
323                                         // Use osmosis to download the file
324                                         $fCMDStartTime = time();
325                                         echo $sCMDDownload."\n";
326                                         exec($sCMDDownload, $sJunk, $iErrorLevel);
327                                         while ($iErrorLevel == 1)
328                                         {
329                                                 echo "Error: $iErrorLevel\n";
330                                                 sleep(60);
331                                                 echo 'Re-trying: '.$sCMDDownload."\n";
332                                                 exec($sCMDDownload, $sJunk, $iErrorLevel);
333                                         }
334                                         $iFileSize = filesize($sImportFile);
335                                         $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
336                                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
337                                         $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')";
338                                         $oDB->query($sSQL);
339                                 }
340
341                                 $iFileSize = filesize($sImportFile);
342                                 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
343                 
344                                 // Import the file
345                                 $fCMDStartTime = time();
346                                 echo $sCMDImport."\n";
347                                 exec($sCMDImport, $sJunk, $iErrorLevel);
348                                 if ($iErrorLevel)
349                                 {
350                                         echo "Error: $iErrorLevel\n";
351                                         exit;
352                                 }
353                                 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
354                                 $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
355                                 var_Dump($sSQL);
356                                 $oDB->query($sSQL);
357
358                                 // Archive for debug?
359                                 unlink($sImportFile);
360
361                                 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
362
363                                 // Index file
364                                 $fCMDStartTime = time();
365                                 $iFileID = $oDB->getOne('select nextval(\'file\')');
366                                 if (PEAR::isError($iFileID))
367                                 {
368                                         echo $oDB->getMessage()."\n";
369                                         exit;
370                                 } 
371                                 $sFileDir = CONST_BasePath.'/export/diff/';
372                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
373                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
374
375                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
376                                 $sThisIndexCmd = $sCMDIndex;
377                                 $sThisIndexCmd .= $sFileDir;
378                                 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
379                                 $sThisIndexCmd .= ".npi.out";
380                                 echo "$sThisIndexCmd\n";
381
382                                 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
383                                 $sFileDir = CONST_BasePath.'/export/index/';
384                                 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
385
386                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
387                                 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
388
389                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
390                                 if ($iErrorLevel)
391                                 {
392                                         echo "Error: $iErrorLevel\n";
393                                         exit;
394                                 }
395
396                                 $sFileDir = CONST_BasePath.'/export/diff/';
397                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
398                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
399
400                                 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
401                                 echo "$sThisIndexCmd\n";
402                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
403                                 if ($iErrorLevel)
404                                 {
405                                         echo "Error: $iErrorLevel\n";
406                                         exit;
407                                 }
408
409                                 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
410                                         $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
411
412                                 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
413                                 $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')";
414                                 $oDB->query($sSQL);
415
416                                 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
417                                 $oDB->query($sSQL);
418
419
420                                 $fDuration = time() - $fStartTime;
421                                 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
422                                 if (!$aResult['import-osmosis-all']) exit;
423 //                      }
424                         echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
425                         sleep(max(0,60-$fDuration));
426                 }
427                 
428         }
429
430         if ($aResult['import-npi-all'])
431         {
432                 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
433                 if (PEAR::isError($iNPIID))
434                 {
435                         var_dump($iNPIID);
436                         exit;
437                 }
438                 $sConfigDirectory = CONST_BasePath.'/settings';
439                 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
440                 while(true)
441                 {
442                         $fStartTime = time();
443
444                         $iNPIID++;
445
446                         $sImportFile = CONST_BasePath.'/export/diff/';
447                         $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
448                         $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
449                         $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
450                         $sImportFile .= ".npi";
451                         while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
452                         {
453                                 echo "sleep (waiting for $sImportFile)\n";
454                                 sleep(10);
455                         }
456                         if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
457
458                         $iFileSize = filesize($sImportFile);
459                 
460                         // Import the file
461                         $fCMDStartTime = time();
462                         $sCMDImport = $sCMDImportTemplate . $sImportFile;
463                         echo $sCMDImport."\n";
464                         exec($sCMDImport, $sJunk, $iErrorLevel);
465                         if ($iErrorLevel)
466                         {
467                                 echo "Error: $iErrorLevel\n";
468                                 exit;
469                         }
470                         $sBatchEnd = $iNPIID;
471                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
472                         $sSQL = "INSERT INTO import_npi_log values ($iNPIID, null, $iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','import')";
473                         var_Dump($sSQL);
474                         $oDB->query($sSQL);
475                 }
476                 
477         }
478
479         function getosmosistimestamp($sOsmosisConfigDirectory)
480         {
481                 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
482                 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
483                 return str_replace('\:',':',$aResult[1]);
484         }