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'),
30 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
31 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
32 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
33 array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
35 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
36 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
37 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
38 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
40 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
42 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
44 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
46 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
49 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
51 // Lock to prevent multiple copies running
52 if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
54 echo "Copy already running\n";
57 if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
58 if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
59 if (getBlockingProcesses() > $aResult['max-blocking'])
61 echo "Too many blocking processes for import\n";
66 // Assume osm2pgsql is in the folder above
67 $sBasePath = dirname(dirname(__FILE__));
69 date_default_timezone_set('Etc/UTC');
73 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
76 $bContinue = $aResult['import-all'];
77 while ($bContinue || $bFirst)
81 if ($aResult['import-hourly'])
83 // Mirror the hourly diffs
84 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
85 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
86 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
87 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
90 if ($aResult['import-daily'])
92 // Mirror the daily diffs
93 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
94 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
95 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
96 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
99 if (isset($aResult['import-diff']))
101 // import diff directly (e.g. from osmosis --rri)
102 $sNextFile = $aResult['import-diff'];
103 if (!file_exists($sNextFile))
105 echo "Cannot open $nextFile\n";
108 // Don't update the import status - we don't know what this file contains
109 $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
112 // Missing file is not an error - it might not be created yet
113 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
116 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sNextFile;
118 exec($sCMD, $sJunk, $iErrorLevel);
122 echo "Error from osm2pgsql, $iErrorLevel\n";
126 // Move the date onwards
127 $oDB->query($sUpdateSQL);
137 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
138 if (isset($aResult['import-file']) && $aResult['import-file'])
142 if (isset($aResult['import-node']) && $aResult['import-node'])
147 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
151 $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;');
154 if (isset($aResult['import-way']) && $aResult['import-way'])
159 $sCmd = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
163 $sCmd = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
165 $sModifyXMLstr = file_get_contents($sCmd);
167 if (isset($aResult['import-relation']) && $aResult['import-relation'])
172 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
176 $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;');
181 // derive change from normal osm file with osmosis
182 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
183 if (isset($aResult['import-file']) && $aResult['import-file'])
185 $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
187 exec($sCMD, $sJunk, $iErrorLevel);
190 echo "Error converting osm to osc, osmosis returned: $iErrorLevel\n";
197 0 => array("pipe", "r"), // stdin
198 1 => array("pipe", "w"), // stdout
199 2 => array("pipe", "w") // stderr
201 $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
203 $hProc = proc_open($sCMD, $aSpec, $aPipes);
204 if (!is_resource($hProc))
206 echo "Error converting osm to osc, osmosis failed\n";
209 fwrite($aPipes[0], $sModifyXMLstr);
211 $sOut = stream_get_contents($aPipes[1]);
212 if ($aResult['verbose']) echo $sOut;
214 $sErrors = stream_get_contents($aPipes[2]);
215 if ($aResult['verbose']) echo $sErrors;
217 if ($iError = proc_close($hProc))
219 echo "Error converting osm to osc, osmosis returned: $iError\n";
226 // import generated change file
227 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sTemporaryFile;
229 exec($sCMD, $sJunk, $iErrorLevel);
232 echo "osm2pgsql exited with error level $iErrorLevel\n";
237 if ($aResult['deduplicate'])
240 $sSQL = 'select partition from country_name order by country_code';
241 $aPartitions = $oDB->getCol($sSQL);
242 if (PEAR::isError($aPartitions))
244 fail($aPartitions->getMessage());
248 $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";
249 $aDuplicateTokens = $oDB->getAll($sSQL);
250 foreach($aDuplicateTokens as $aToken)
252 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
253 echo "Deduping ".$aToken['word_token']."\n";
254 $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";
255 $aTokenSet = $oDB->getAll($sSQL);
256 if (PEAR::isError($aTokenSet))
258 var_dump($aTokenSet, $sSQL);
262 $aKeep = array_shift($aTokenSet);
263 $iKeepID = $aKeep['word_id'];
265 foreach($aTokenSet as $aRemove)
267 $sSQL = "update search_name set";
268 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
269 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
270 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
271 $x = $oDB->query($sSQL);
272 if (PEAR::isError($x))
278 $sSQL = "update search_name set";
279 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
280 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
281 $x = $oDB->query($sSQL);
282 if (PEAR::isError($x))
288 $sSQL = "update location_area_country set";
289 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
290 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
291 $x = $oDB->query($sSQL);
292 if (PEAR::isError($x))
298 foreach ($aPartitions as $sPartition)
300 $sSQL = "update search_name_".$sPartition." set";
301 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
302 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
303 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
304 $x = $oDB->query($sSQL);
305 if (PEAR::isError($x))
311 $sSQL = "update search_name_".$sPartition." set";
312 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
313 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
314 $x = $oDB->query($sSQL);
315 if (PEAR::isError($x))
321 $sSQL = "update location_area_country set";
322 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
323 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
324 $x = $oDB->query($sSQL);
325 if (PEAR::isError($x))
332 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
333 $x = $oDB->query($sSQL);
334 if (PEAR::isError($x))
344 if ($aResult['index'])
346 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
347 passthru(CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
350 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
352 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
353 $sOsmosisCMD = CONST_Osmosis_Binary;
354 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
355 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
356 $sCMDImport = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sImportFile;
357 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'];
358 if (!$aResult['no-npi']) {
363 $fStartTime = time();
366 // Logic behind this is that osm2pgsql locks the database quite a bit
367 // So it is better to import lots of small files
368 // But indexing works most efficiently on large amounts of data
369 // So do lots of small imports and a BIG index
371 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
373 if (!file_exists($sImportFile))
375 // Use osmosis to download the file
376 $fCMDStartTime = time();
377 echo $sCMDDownload."\n";
378 exec($sCMDDownload, $sJunk, $iErrorLevel);
379 while ($iErrorLevel == 1)
381 echo "Error: $iErrorLevel\n";
383 echo 'Re-trying: '.$sCMDDownload."\n";
384 exec($sCMDDownload, $sJunk, $iErrorLevel);
386 $iFileSize = filesize($sImportFile);
387 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
388 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
389 $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')";
393 $iFileSize = filesize($sImportFile);
394 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
397 $fCMDStartTime = time();
398 echo $sCMDImport."\n";
399 exec($sCMDImport, $sJunk, $iErrorLevel);
402 echo "Error: $iErrorLevel\n";
405 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
406 $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')";
410 // Archive for debug?
411 unlink($sImportFile);
414 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
417 if (!isset($aResult['index-instances']))
419 if (getLoadAverage() < 15)
420 $iIndexInstances = 2;
422 $iIndexInstances = 1;
424 $iIndexInstances = $aResult['index-instances'];
426 $sThisIndexCmd = $sCMDIndex.' -t '.$iIndexInstances;
428 if (!$aResult['no-npi'])
430 $fCMDStartTime = time();
431 $iFileID = $oDB->getOne('select nextval(\'file\')');
432 if (PEAR::isError($iFileID))
434 echo $iFileID->getMessage()."\n";
437 $sFileDir = CONST_BasePath.'/export/diff/';
438 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
439 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
441 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
442 $sThisIndexCmd .= $sFileDir;
443 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
444 $sThisIndexCmd .= ".npi.out";
446 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
447 $sFileDir = CONST_BasePath.'/export/index/';
448 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
450 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
451 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
454 if (!$aResult['no-index'])
456 echo "$sThisIndexCmd\n";
457 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
460 echo "Error: $iErrorLevel\n";
464 if (!$aResult['no-npi'])
466 $sFileDir = CONST_BasePath.'/export/diff/';
467 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
468 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
470 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
471 echo "$sThisIndexCmd\n";
472 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
475 echo "Error: $iErrorLevel\n";
479 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
480 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
484 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
485 $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')";
488 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
491 $fDuration = time() - $fStartTime;
492 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
493 if (!$aResult['import-osmosis-all']) exit;
495 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
496 sleep(max(0,60-$fDuration));
501 if ($aResult['import-npi-all'])
503 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
504 if (PEAR::isError($iNPIID))
509 $sConfigDirectory = CONST_BasePath.'/settings';
510 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
513 $fStartTime = time();
517 $sImportFile = CONST_BasePath.'/export/diff/';
518 $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
519 $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
520 $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
521 $sImportFile .= ".npi";
522 while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
524 echo "sleep (waiting for $sImportFile)\n";
527 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
529 $iFileSize = filesize($sImportFile);
532 $fCMDStartTime = time();
533 $sCMDImport = $sCMDImportTemplate . $sImportFile;
534 echo $sCMDImport."\n";
535 exec($sCMDImport, $sJunk, $iErrorLevel);
538 echo "Error: $iErrorLevel\n";
541 $sBatchEnd = $iNPIID;
542 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
543 $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')";
550 function getosmosistimestamp($sOsmosisConfigDirectory)
552 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
553 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
554 return str_replace('\:',':',$aResult[1]);