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