4 require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5 ini_set('memory_limit', '800M');
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'),
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'),
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 array('no-npi', '', 0, 1, 0, 0, 'bool', 'Do not write npi index files'),
19 array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'),
21 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
23 array('import-hourly', '', 0, 1, 0, 0, 'bool', 'Import hourly diffs'),
24 array('import-daily', '', 0, 1, 0, 0, 'bool', 'Import daily diffs'),
25 array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
27 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
28 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
29 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
31 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
32 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
33 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
34 array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
36 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
37 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
38 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
39 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
41 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
43 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
45 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
47 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
50 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
53 // Lock to prevent multiple copies running
54 if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
56 echo "Copy already running\n";
59 if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
60 if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
61 if (getBlockingProcesses() > $aResult['max-blocking'])
63 echo "Too many blocking processes for import\n";
68 // Assume osm2pgsql is in the folder above
69 $sBasePath = dirname(dirname(__FILE__));
71 date_default_timezone_set('Etc/UTC');
75 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
76 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
78 // cache memory to be used by osm2pgsql, should not be more than the available memory
79 $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
80 if ($iCacheMemory + 500 > getTotalMemoryMB())
82 $iCacheMemory = getCacheMemoryMB();
83 echo "WARNING: resetting cache memory to $iCacheMemory\n";
85 $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
86 if (!is_null(CONST_Osm2pgsql_Flatnode_File))
88 $sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
93 $bContinue = $aResult['import-all'];
94 while ($bContinue || $bFirst)
98 if ($aResult['import-hourly'])
100 // Mirror the hourly diffs
101 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
102 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
103 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
104 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
107 if ($aResult['import-daily'])
109 // Mirror the daily diffs
110 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
111 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
112 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
113 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
116 if (isset($aResult['import-diff']))
118 // import diff directly (e.g. from osmosis --rri)
119 $sNextFile = $aResult['import-diff'];
120 if (!file_exists($sNextFile))
122 echo "Cannot open $sNextFile\n";
125 // Don't update the import status - we don't know what this file contains
126 $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
129 // Missing file is not an error - it might not be created yet
130 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
133 $sCMD = $sOsm2pgsqlCmd.' '.$sNextFile;
135 exec($sCMD, $sJunk, $iErrorLevel);
139 echo "Error from osm2pgsql, $iErrorLevel\n";
143 // Move the date onwards
144 $oDB->query($sUpdateSQL);
154 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
155 if (isset($aResult['import-file']) && $aResult['import-file'])
159 if (isset($aResult['import-node']) && $aResult['import-node'])
164 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
168 $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;');
171 if (isset($aResult['import-way']) && $aResult['import-way'])
176 $sCmd = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
180 $sCmd = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
182 $sModifyXMLstr = file_get_contents($sCmd);
184 if (isset($aResult['import-relation']) && $aResult['import-relation'])
189 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
193 $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;');
198 // derive change from normal osm file with osmosis
199 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
200 if (isset($aResult['import-file']) && $aResult['import-file'])
202 $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
204 exec($sCMD, $sJunk, $iErrorLevel);
207 echo "Error converting osm to osc, osmosis returned: $iErrorLevel\n";
214 0 => array("pipe", "r"), // stdin
215 1 => array("pipe", "w"), // stdout
216 2 => array("pipe", "w") // stderr
218 $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
220 $hProc = proc_open($sCMD, $aSpec, $aPipes);
221 if (!is_resource($hProc))
223 echo "Error converting osm to osc, osmosis failed\n";
226 fwrite($aPipes[0], $sModifyXMLstr);
228 $sOut = stream_get_contents($aPipes[1]);
229 if ($aResult['verbose']) echo $sOut;
231 $sErrors = stream_get_contents($aPipes[2]);
232 if ($aResult['verbose']) echo $sErrors;
234 if ($iError = proc_close($hProc))
236 echo "Error converting osm to osc, osmosis returned: $iError\n";
243 // import generated change file
244 $sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
246 exec($sCMD, $sJunk, $iErrorLevel);
249 echo "osm2pgsql exited with error level $iErrorLevel\n";
254 if ($aResult['deduplicate'])
257 $pgver = (float) CONST_Postgresql_Version;
259 echo "ERROR: deduplicate is only currently supported in postgresql 9.3";
264 $sSQL = 'select partition from country_name order by country_code';
265 $aPartitions = $oDB->getCol($sSQL);
266 if (PEAR::isError($aPartitions))
268 fail($aPartitions->getMessage());
272 $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";
273 $aDuplicateTokens = $oDB->getAll($sSQL);
274 foreach($aDuplicateTokens as $aToken)
276 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
277 echo "Deduping ".$aToken['word_token']."\n";
278 $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";
279 $aTokenSet = $oDB->getAll($sSQL);
280 if (PEAR::isError($aTokenSet))
282 var_dump($aTokenSet, $sSQL);
286 $aKeep = array_shift($aTokenSet);
287 $iKeepID = $aKeep['word_id'];
289 foreach($aTokenSet as $aRemove)
291 $sSQL = "update search_name set";
292 $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID."),";
293 $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
294 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
295 $x = $oDB->query($sSQL);
296 if (PEAR::isError($x))
302 $sSQL = "update search_name set";
303 $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
304 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
305 $x = $oDB->query($sSQL);
306 if (PEAR::isError($x))
312 $sSQL = "update location_area_country set";
313 $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
314 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
315 $x = $oDB->query($sSQL);
316 if (PEAR::isError($x))
322 foreach ($aPartitions as $sPartition)
324 $sSQL = "update search_name_".$sPartition." set";
325 $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID.")";
326 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
327 $x = $oDB->query($sSQL);
328 if (PEAR::isError($x))
334 $sSQL = "update location_area_country set";
335 $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
336 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
337 $x = $oDB->query($sSQL);
338 if (PEAR::isError($x))
345 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
346 $x = $oDB->query($sSQL);
347 if (PEAR::isError($x))
357 if ($aResult['index'])
359 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
360 passthru(CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
363 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
366 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
367 echo "Error: Update interval too low for download.geofabrik.de. Please check install documentation (http://wiki.openstreetmap.org/wiki/Nominatim/Installation#Updates)\n";
371 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
372 $sOsmosisCMD = CONST_Osmosis_Binary;
373 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
374 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
375 $sCMDCheckReplicationLag = $sOsmosisCMD.' -q --read-replication-lag workingDirectory='.$sOsmosisConfigDirectory;
376 $sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile;
377 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
378 if (!$aResult['no-npi']) {
383 $fStartTime = time();
386 // Logic behind this is that osm2pgsql locks the database quite a bit
387 // So it is better to import lots of small files
388 // But indexing works most efficiently on large amounts of data
389 // So do lots of small imports and a BIG index
391 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
393 if (!file_exists($sImportFile))
395 // First check if there are new updates published (except for minutelies - there's always new diffs to process)
396 if ( CONST_Replication_Update_Interval > 60 )
399 unset($aReplicationLag);
400 exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel);
401 while ($iErrorLevel > 0 || $aReplicationLag[0] < 1)
405 echo "Error: $iErrorLevel. ";
406 echo "Re-trying: ".$sCMDCheckReplicationLag." in ".CONST_Replication_Recheck_Interval." secs\n";
412 sleep(CONST_Replication_Recheck_Interval);
413 unset($aReplicationLag);
414 exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel);
416 // There are new replication files - use osmosis to download the file
417 echo "\n".date('Y-m-d H:i:s')." Replication Delay is ".$aReplicationLag[0]."\n";
419 $fStartTime = time();
420 $fCMDStartTime = time();
421 echo $sCMDDownload."\n";
422 exec($sCMDDownload, $sJunk, $iErrorLevel);
423 while ($iErrorLevel > 0)
425 echo "Error: $iErrorLevel\n";
427 echo 'Re-trying: '.$sCMDDownload."\n";
428 exec($sCMDDownload, $sJunk, $iErrorLevel);
430 $iFileSize = filesize($sImportFile);
431 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
432 $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')";
435 echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
438 $iFileSize = filesize($sImportFile);
439 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
442 $fCMDStartTime = time();
443 echo $sCMDImport."\n";
444 exec($sCMDImport, $sJunk, $iErrorLevel);
447 echo "Error: $iErrorLevel\n";
450 $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')";
453 echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
455 // Archive for debug?
456 unlink($sImportFile);
459 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
462 if (!isset($aResult['index-instances']))
464 if (getLoadAverage() < 24)
465 $iIndexInstances = 2;
467 $iIndexInstances = 1;
469 $iIndexInstances = $aResult['index-instances'];
471 $sThisIndexCmd = $sCMDIndex.' -t '.$iIndexInstances;
472 $fCMDStartTime = time();
474 if (!$aResult['no-npi'])
476 $iFileID = $oDB->getOne('select nextval(\'file\')');
477 if (PEAR::isError($iFileID))
479 echo $iFileID->getMessage()."\n";
482 $sFileDir = CONST_BasePath.'/export/diff/';
483 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
484 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
486 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
487 $sThisIndexCmd .= $sFileDir;
488 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
489 $sThisIndexCmd .= ".npi.out";
491 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
492 $sFileDir = CONST_BasePath.'/export/index/';
493 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
495 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
496 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
499 if (!$aResult['no-index'])
501 echo "$sThisIndexCmd\n";
502 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
505 echo "Error: $iErrorLevel\n";
509 if (!$aResult['no-npi'])
511 $sFileDir = CONST_BasePath.'/export/diff/';
512 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
513 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
515 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
516 echo "$sThisIndexCmd\n";
517 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
520 echo "Error: $iErrorLevel\n";
524 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
525 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
529 $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')";
532 echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
534 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
537 $fDuration = time() - $fStartTime;
538 echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n";
539 if (!$aResult['import-osmosis-all']) exit;
541 if ( CONST_Replication_Update_Interval > 60 )
543 $iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
547 $iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
549 echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
555 if ($aResult['import-npi-all'])
557 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
558 if (PEAR::isError($iNPIID))
563 $sConfigDirectory = CONST_BasePath.'/settings';
564 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
567 $fStartTime = time();
571 $sImportFile = CONST_BasePath.'/export/diff/';
572 $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
573 $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
574 $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
575 $sImportFile .= ".npi";
576 while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
578 echo "sleep (waiting for $sImportFile)\n";
581 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
583 $iFileSize = filesize($sImportFile);
586 $fCMDStartTime = time();
587 $sCMDImport = $sCMDImportTemplate . $sImportFile;
588 echo $sCMDImport."\n";
589 exec($sCMDImport, $sJunk, $iErrorLevel);
592 echo "Error: $iErrorLevel\n";
595 $sBatchEnd = $iNPIID;
596 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
597 $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')";
604 function getosmosistimestamp($sOsmosisConfigDirectory)
606 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
607 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
608 return str_replace('\:',':',$aResult[1]);