3 require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
4 ini_set('memory_limit', '800M');
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'),
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'),
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'),
18 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
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'),
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'),
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'),
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)'),
36 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
38 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
40 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
42 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
45 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
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)
50 echo "Copy already running\n";
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'])
57 echo "Too many blocking processes for import\n";
62 // Assume osm2pgsql is in the folder above
63 $sBasePath = dirname(dirname(__FILE__));
68 $bContinue = $aResult['import-all'];
69 while ($bContinue || $bFirst)
73 if ($aResult['import-hourly'])
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';
82 if ($aResult['import-daily'])
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';
91 if (isset($aResult['import-diff']))
93 // import diff directly (e.g. from osmosis --rri)
94 $sNextFile = $aResult['import-diff'];
95 if (!file_exists($nextFile))
97 echo "Cannot open $nextFile\n";
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';
104 // Missing file is not an error - it might not be created yet
105 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
108 $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
110 exec($sCMD, $sJunk, $iErrorLevel);
114 echo "Error from osm2pgsql, $iErrorLevel\n";
118 // Move the date onwards
119 $oDB->query($sUpdateSQL);
128 if (isset($aResult['import-file']) && $aResult['import-file'])
130 $sModifyXML = file_get_contents($aResult['import-file']);
132 if (isset($aResult['import-node']) && $aResult['import-node'])
134 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
136 if (isset($aResult['import-way']) && $aResult['import-way'])
138 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
140 if (isset($aResult['import-relation']) && $aResult['import-relation'])
142 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
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);
151 // Outputing this is too verbose
152 if ($aResult['verbose'] && false) var_dump($sModifyXML);
154 $sDatabaseName = 'nominatim';
156 0 => array("pipe", "r"), // stdin
157 1 => array("pipe", "w"), // stdout
158 2 => array("pipe", "w") // stderr
161 $sCMD = $sBasePath.'/osm2pgsql/osm2pgsql -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
163 $hProc = proc_open($sCMD, $aSpec, $aPipes);
164 if (!is_resource($hProc))
166 echo "$sBasePath/osm2pgsql failed\n";
169 fwrite($aPipes[0], $sModifyXML);
171 $sOut = stream_get_contents($aPipes[1]);
172 if ($aResult['verbose']) echo $sOut;
174 $sErrors = stream_get_contents($aPipes[2]);
175 if ($aResult['verbose']) echo $sErrors;
177 if ($iError = proc_close($hProc))
179 echo "osm2pgsql existed with error level $iError\n";
186 if ($aResult['deduplicate'])
189 $sSQL = 'select partition from country_name order by country_code';
190 $aPartitions = $oDB->getCol($sSQL);
191 if (PEAR::isError($aPartitions))
193 fail($aPartitions->getMessage());
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)
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))
207 var_dump($aTokenSet, $sSQL);
211 $aKeep = array_shift($aTokenSet);
212 $iKeepID = $aKeep['word_id'];
214 foreach($aTokenSet as $aRemove)
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))
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))
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))
247 foreach ($aPartitions as $sPartition)
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))
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))
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))
281 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
282 $x = $oDB->query($sSQL);
283 if (PEAR::isError($x))
293 if ($aResult['index'])
295 index($aResult, $sDatabaseDSN);
298 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
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 ';
310 $fStartTime = time();
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
318 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
320 if (!file_exists($sImportFile))
322 // Use osmosis to download the file
323 $fCMDStartTime = time();
324 echo $sCMDDownload."\n";
325 exec($sCMDDownload, $sJunk, $iErrorLevel);
328 echo "Error: $iErrorLevel\n";
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')";
338 $iFileSize = filesize($sImportFile);
339 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
342 $fCMDStartTime = time();
343 echo $sCMDImport."\n";
344 exec($sCMDImport, $sJunk, $iErrorLevel);
347 echo "Error: $iErrorLevel\n";
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')";
355 // Archive for debug?
356 unlink($sImportFile);
358 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
361 $fCMDStartTime = time();
362 $iFileID = $oDB->getOne('select nextval(\'file\')');
363 if (PEAR::isError($iFileID))
365 echo $oDB->getMessage()."\n";
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);
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";
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];
383 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
384 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
386 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
389 echo "Error: $iErrorLevel\n";
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);
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);
402 echo "Error: $iErrorLevel\n";
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");
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')";
413 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
417 $fDuration = time() - $fStartTime;
418 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
419 if (!$aResult['import-osmosis-all']) exit;
422 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
423 sleep(max(0,60-$fDuration));
428 if ($aResult['import-npi-all'])
430 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
431 if (PEAR::isError($iNPIID))
436 $sConfigDirectory = CONST_BasePath.'/settings';
437 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
440 $fStartTime = time();
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'))
454 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
456 $iFileSize = filesize($sImportFile);
459 $fCMDStartTime = time();
460 $sCMDImport = $sCMDImportTemplate . $sImportFile;
461 echo $sCMDImport."\n";
462 exec($sCMDImport, $sJunk, $iErrorLevel);
465 echo "Error: $iErrorLevel\n";
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')";
477 function getosmosistimestamp($sOsmosisConfigDirectory)
479 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
480 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
481 return str_replace('\:',':',$aResult[1]);