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'),
39 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
41 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
43 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
46 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
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)
51 echo "Copy already running\n";
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'])
58 echo "Too many blocking processes for import\n";
63 // Assume osm2pgsql is in the folder above
64 $sBasePath = dirname(dirname(__FILE__));
69 $bContinue = $aResult['import-all'];
70 while ($bContinue || $bFirst)
74 if ($aResult['import-hourly'])
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';
83 if ($aResult['import-daily'])
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';
92 if (isset($aResult['import-diff']))
94 // import diff directly (e.g. from osmosis --rri)
95 $sNextFile = $aResult['import-diff'];
96 if (!file_exists($nextFile))
98 echo "Cannot open $nextFile\n";
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';
105 // Missing file is not an error - it might not be created yet
106 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
109 $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
111 exec($sCMD, $sJunk, $iErrorLevel);
115 echo "Error from osm2pgsql, $iErrorLevel\n";
119 // Move the date onwards
120 $oDB->query($sUpdateSQL);
129 if (isset($aResult['import-file']) && $aResult['import-file'])
131 $sModifyXML = file_get_contents($aResult['import-file']);
133 if (isset($aResult['import-node']) && $aResult['import-node'])
135 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
137 if (isset($aResult['import-way']) && $aResult['import-way'])
139 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
141 if (isset($aResult['import-relation']) && $aResult['import-relation'])
143 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
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);
152 // Outputing this is too verbose
153 if ($aResult['verbose'] && false) var_dump($sModifyXML);
155 $sDatabaseName = 'nominatim';
157 0 => array("pipe", "r"), // stdin
158 1 => array("pipe", "w"), // stdout
159 2 => array("pipe", "w") // stderr
162 $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
164 $hProc = proc_open($sCMD, $aSpec, $aPipes);
165 if (!is_resource($hProc))
167 echo "$sBasePath/osm2pgsql failed\n";
170 fwrite($aPipes[0], $sModifyXML);
172 $sOut = stream_get_contents($aPipes[1]);
173 if ($aResult['verbose']) echo $sOut;
175 $sErrors = stream_get_contents($aPipes[2]);
176 if ($aResult['verbose']) echo $sErrors;
178 if ($iError = proc_close($hProc))
180 echo "osm2pgsql existed with error level $iError\n";
187 if ($aResult['deduplicate'])
190 $sSQL = 'select partition from country_name order by country_code';
191 $aPartitions = $oDB->getCol($sSQL);
192 if (PEAR::isError($aPartitions))
194 fail($aPartitions->getMessage());
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)
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))
208 var_dump($aTokenSet, $sSQL);
212 $aKeep = array_shift($aTokenSet);
213 $iKeepID = $aKeep['word_id'];
215 foreach($aTokenSet as $aRemove)
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))
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))
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))
248 foreach ($aPartitions as $sPartition)
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))
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))
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))
282 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
283 $x = $oDB->query($sSQL);
284 if (PEAR::isError($x))
294 if ($aResult['index'])
296 index($aResult, $sDatabaseDSN);
299 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
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 ';
311 $fStartTime = time();
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
319 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
321 if (!file_exists($sImportFile))
323 // Use osmosis to download the file
324 $fCMDStartTime = time();
325 echo $sCMDDownload."\n";
326 exec($sCMDDownload, $sJunk, $iErrorLevel);
327 while ($iErrorLevel == 1)
329 echo "Error: $iErrorLevel\n";
331 echo 'Re-trying: '.$sCMDDownload."\n";
332 exec($sCMDDownload, $sJunk, $iErrorLevel);
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')";
341 $iFileSize = filesize($sImportFile);
342 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
345 $fCMDStartTime = time();
346 echo $sCMDImport."\n";
347 exec($sCMDImport, $sJunk, $iErrorLevel);
350 echo "Error: $iErrorLevel\n";
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')";
358 // Archive for debug?
359 unlink($sImportFile);
361 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
364 $fCMDStartTime = time();
365 $iFileID = $oDB->getOne('select nextval(\'file\')');
366 if (PEAR::isError($iFileID))
368 echo $oDB->getMessage()."\n";
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);
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";
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];
386 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
387 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
389 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
392 echo "Error: $iErrorLevel\n";
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);
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);
405 echo "Error: $iErrorLevel\n";
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");
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')";
416 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
420 $fDuration = time() - $fStartTime;
421 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
422 if (!$aResult['import-osmosis-all']) exit;
424 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
425 sleep(max(0,60-$fDuration));
430 if ($aResult['import-npi-all'])
432 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
433 if (PEAR::isError($iNPIID))
438 $sConfigDirectory = CONST_BasePath.'/settings';
439 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
442 $fStartTime = time();
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'))
453 echo "sleep (waiting for $sImportFile)\n";
456 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
458 $iFileSize = filesize($sImportFile);
461 $fCMDStartTime = time();
462 $sCMDImport = $sCMDImportTemplate . $sImportFile;
463 echo $sCMDImport."\n";
464 exec($sCMDImport, $sJunk, $iErrorLevel);
467 echo "Error: $iErrorLevel\n";
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')";
479 function getosmosistimestamp($sOsmosisConfigDirectory)
481 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
482 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
483 return str_replace('\:',':',$aResult[1]);