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'),
19 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
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'),
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'),
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'),
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)'),
37 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
38 array('no-npi', '', 0, 1, 0, 0, 'bool', 'Do not write npi index files'),
40 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
42 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
44 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
47 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
49 // Lock to prevent multiple copies running
50 if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
52 echo "Copy already running\n";
55 if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
56 if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
57 if (getBlockingProcesses() > $aResult['max-blocking'])
59 echo "Too many blocking processes for import\n";
64 // Assume osm2pgsql is in the folder above
65 $sBasePath = dirname(dirname(__FILE__));
70 $bContinue = $aResult['import-all'];
71 while ($bContinue || $bFirst)
75 if ($aResult['import-hourly'])
77 // Mirror the hourly diffs
78 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
79 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
80 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
81 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
84 if ($aResult['import-daily'])
86 // Mirror the daily diffs
87 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
88 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
89 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
90 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
93 if (isset($aResult['import-diff']))
95 // import diff directly (e.g. from osmosis --rri)
96 $sNextFile = $aResult['import-diff'];
97 if (!file_exists($nextFile))
99 echo "Cannot open $nextFile\n";
102 // Don't update the import status - we don't know what this file contains
103 $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
106 // Missing file is not an error - it might not be created yet
107 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
110 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
112 exec($sCMD, $sJunk, $iErrorLevel);
116 echo "Error from osm2pgsql, $iErrorLevel\n";
120 // Move the date onwards
121 $oDB->query($sUpdateSQL);
130 if (isset($aResult['import-file']) && $aResult['import-file'])
132 $sModifyXML = file_get_contents($aResult['import-file']);
134 if (isset($aResult['import-node']) && $aResult['import-node'])
136 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
138 if (isset($aResult['import-way']) && $aResult['import-way'])
140 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
142 if (isset($aResult['import-relation']) && $aResult['import-relation'])
144 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
148 // Hack into a modify request
149 $sModifyXML = str_replace('<osm version="0.6" generator="OpenStreetMap server">',
150 '<osmChange version="0.6" generator="OpenStreetMap server"><modify>', $sModifyXML);
151 $sModifyXML = str_replace('</osm>', '</modify></osmChange>', $sModifyXML);
153 // Outputing this is too verbose
154 if ($aResult['verbose'] && false) var_dump($sModifyXML);
156 $sDatabaseName = 'nominatim';
158 0 => array("pipe", "r"), // stdin
159 1 => array("pipe", "w"), // stdout
160 2 => array("pipe", "w") // stderr
163 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
165 $hProc = proc_open($sCMD, $aSpec, $aPipes);
166 if (!is_resource($hProc))
168 echo "$sBasePath/osm2pgsql failed\n";
171 fwrite($aPipes[0], $sModifyXML);
173 $sOut = stream_get_contents($aPipes[1]);
174 if ($aResult['verbose']) echo $sOut;
176 $sErrors = stream_get_contents($aPipes[2]);
177 if ($aResult['verbose']) echo $sErrors;
179 if ($iError = proc_close($hProc))
181 echo "osm2pgsql existed with error level $iError\n";
188 if ($aResult['deduplicate'])
191 $sSQL = 'select partition from country_name order by country_code';
192 $aPartitions = $oDB->getCol($sSQL);
193 if (PEAR::isError($aPartitions))
195 fail($aPartitions->getMessage());
199 $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";
200 $aDuplicateTokens = $oDB->getAll($sSQL);
201 foreach($aDuplicateTokens as $aToken)
203 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
204 echo "Deduping ".$aToken['word_token']."\n";
205 $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";
206 $aTokenSet = $oDB->getAll($sSQL);
207 if (PEAR::isError($aTokenSet))
209 var_dump($aTokenSet, $sSQL);
213 $aKeep = array_shift($aTokenSet);
214 $iKeepID = $aKeep['word_id'];
216 foreach($aTokenSet as $aRemove)
218 $sSQL = "update search_name set";
219 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
220 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
221 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
222 $x = $oDB->query($sSQL);
223 if (PEAR::isError($x))
229 $sSQL = "update search_name set";
230 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
231 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
232 $x = $oDB->query($sSQL);
233 if (PEAR::isError($x))
239 $sSQL = "update location_area_country set";
240 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
241 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
242 $x = $oDB->query($sSQL);
243 if (PEAR::isError($x))
249 foreach ($aPartitions as $sPartition)
251 $sSQL = "update search_name_".$sPartition." set";
252 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
253 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
254 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
255 $x = $oDB->query($sSQL);
256 if (PEAR::isError($x))
262 $sSQL = "update search_name_".$sPartition." set";
263 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
264 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
265 $x = $oDB->query($sSQL);
266 if (PEAR::isError($x))
272 $sSQL = "update location_area_country set";
273 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
274 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
275 $x = $oDB->query($sSQL);
276 if (PEAR::isError($x))
283 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
284 $x = $oDB->query($sSQL);
285 if (PEAR::isError($x))
295 if ($aResult['index'])
297 index($aResult, $sDatabaseDSN);
300 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
302 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
303 $sOsmosisCMD = CONST_Osmosis_Binary;
304 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
305 $sDatabaseName = 'nominatim';
306 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
307 $sCMDImport = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sImportFile;
308 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -t '.$aResult['index-instances'];
309 if (!$aResult['no-npi']) {
314 $fStartTime = time();
317 // Logic behind this is that osm2pgsql locks the database quite a bit
318 // So it is better to import lots of small files
319 // But indexing works most efficiently on large amounts of data
320 // So do lots of small imports and a BIG index
322 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
324 if (!file_exists($sImportFile))
326 // Use osmosis to download the file
327 $fCMDStartTime = time();
328 echo $sCMDDownload."\n";
329 exec($sCMDDownload, $sJunk, $iErrorLevel);
330 while ($iErrorLevel == 1)
332 echo "Error: $iErrorLevel\n";
334 echo 'Re-trying: '.$sCMDDownload."\n";
335 exec($sCMDDownload, $sJunk, $iErrorLevel);
337 $iFileSize = filesize($sImportFile);
338 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
339 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
340 $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')";
344 $iFileSize = filesize($sImportFile);
345 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
348 $fCMDStartTime = time();
349 echo $sCMDImport."\n";
350 exec($sCMDImport, $sJunk, $iErrorLevel);
353 echo "Error: $iErrorLevel\n";
356 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
357 $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')";
361 // Archive for debug?
362 unlink($sImportFile);
364 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
367 $fCMDStartTime = time();
368 $iFileID = $oDB->getOne('select nextval(\'file\')');
369 if (PEAR::isError($iFileID))
371 echo $iFileID->getMessage()."\n";
374 $sFileDir = CONST_BasePath.'/export/diff/';
375 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
376 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
378 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
379 $sThisIndexCmd = $sCMDIndex;
380 if (!$aResult['no-npi']) {
381 $sThisIndexCmd .= $sFileDir;
382 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
383 $sThisIndexCmd .= ".npi.out";
385 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
386 $sFileDir = CONST_BasePath.'/export/index/';
387 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
389 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
390 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
393 echo "$sThisIndexCmd\n";
394 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
397 echo "Error: $iErrorLevel\n";
401 if (!$aResult['no-npi']) {
402 $sFileDir = CONST_BasePath.'/export/diff/';
403 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
404 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
406 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
407 echo "$sThisIndexCmd\n";
408 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
411 echo "Error: $iErrorLevel\n";
415 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
416 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
419 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
420 $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')";
423 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
427 $fDuration = time() - $fStartTime;
428 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
429 if (!$aResult['import-osmosis-all']) exit;
431 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
432 sleep(max(0,60-$fDuration));
437 if ($aResult['import-npi-all'])
439 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
440 if (PEAR::isError($iNPIID))
445 $sConfigDirectory = CONST_BasePath.'/settings';
446 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
449 $fStartTime = time();
453 $sImportFile = CONST_BasePath.'/export/diff/';
454 $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
455 $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
456 $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
457 $sImportFile .= ".npi";
458 while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
460 echo "sleep (waiting for $sImportFile)\n";
463 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
465 $iFileSize = filesize($sImportFile);
468 $fCMDStartTime = time();
469 $sCMDImport = $sCMDImportTemplate . $sImportFile;
470 echo $sCMDImport."\n";
471 exec($sCMDImport, $sJunk, $iErrorLevel);
474 echo "Error: $iErrorLevel\n";
477 $sBatchEnd = $iNPIID;
478 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
479 $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')";
486 function getosmosistimestamp($sOsmosisConfigDirectory)
488 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
489 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
490 return str_replace('\:',':',$aResult[1]);