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'),
34 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
35 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
36 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
37 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
39 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
41 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
43 if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
45 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
48 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
50 // Lock to prevent multiple copies running
51 if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
53 echo "Copy already running\n";
56 if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
57 if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
58 if (getBlockingProcesses() > $aResult['max-blocking'])
60 echo "Too many blocking processes for import\n";
65 // Assume osm2pgsql is in the folder above
66 $sBasePath = dirname(dirname(__FILE__));
71 $bContinue = $aResult['import-all'];
72 while ($bContinue || $bFirst)
76 if ($aResult['import-hourly'])
78 // Mirror the hourly diffs
79 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
80 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
81 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
82 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
85 if ($aResult['import-daily'])
87 // Mirror the daily diffs
88 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
89 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
90 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
91 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
94 if (isset($aResult['import-diff']))
96 // import diff directly (e.g. from osmosis --rri)
97 $sNextFile = $aResult['import-diff'];
98 if (!file_exists($nextFile))
100 echo "Cannot open $nextFile\n";
103 // Don't update the import status - we don't know what this file contains
104 $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
107 // Missing file is not an error - it might not be created yet
108 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
111 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
113 exec($sCMD, $sJunk, $iErrorLevel);
117 echo "Error from osm2pgsql, $iErrorLevel\n";
121 // Move the date onwards
122 $oDB->query($sUpdateSQL);
131 if (isset($aResult['import-file']) && $aResult['import-file'])
133 $sModifyXML = file_get_contents($aResult['import-file']);
135 if (isset($aResult['import-node']) && $aResult['import-node'])
137 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
139 if (isset($aResult['import-way']) && $aResult['import-way'])
141 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
143 if (isset($aResult['import-relation']) && $aResult['import-relation'])
145 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
149 // Hack into a modify request
150 $sModifyXML = str_replace('<osm version="0.6" generator="OpenStreetMap server">',
151 '<osmChange version="0.6" generator="OpenStreetMap server"><modify>', $sModifyXML);
152 $sModifyXML = str_replace('<osm version=\'0.6\' upload=\'true\' generator=\'JOSM\'>',
153 '<osmChange version="0.6" generator="OpenStreetMap server"><modify>', $sModifyXML);
154 $sModifyXML = str_replace('</osm>', '</modify></osmChange>', $sModifyXML);
156 // Outputing this is too verbose
157 if ($aResult['verbose'] && false) var_dump($sModifyXML);
159 $sDatabaseName = 'nominatim';
161 0 => array("pipe", "r"), // stdin
162 1 => array("pipe", "w"), // stdout
163 2 => array("pipe", "w") // stderr
166 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
168 $hProc = proc_open($sCMD, $aSpec, $aPipes);
169 if (!is_resource($hProc))
171 echo "$sBasePath/osm2pgsql failed\n";
174 fwrite($aPipes[0], $sModifyXML);
176 $sOut = stream_get_contents($aPipes[1]);
177 if ($aResult['verbose']) echo $sOut;
179 $sErrors = stream_get_contents($aPipes[2]);
180 if ($aResult['verbose']) echo $sErrors;
182 if ($iError = proc_close($hProc))
184 echo "osm2pgsql existed with error level $iError\n";
191 if ($aResult['deduplicate'])
194 $sSQL = 'select partition from country_name order by country_code';
195 $aPartitions = $oDB->getCol($sSQL);
196 if (PEAR::isError($aPartitions))
198 fail($aPartitions->getMessage());
202 $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";
203 $aDuplicateTokens = $oDB->getAll($sSQL);
204 foreach($aDuplicateTokens as $aToken)
206 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
207 echo "Deduping ".$aToken['word_token']."\n";
208 $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";
209 $aTokenSet = $oDB->getAll($sSQL);
210 if (PEAR::isError($aTokenSet))
212 var_dump($aTokenSet, $sSQL);
216 $aKeep = array_shift($aTokenSet);
217 $iKeepID = $aKeep['word_id'];
219 foreach($aTokenSet as $aRemove)
221 $sSQL = "update search_name set";
222 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
223 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
224 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
225 $x = $oDB->query($sSQL);
226 if (PEAR::isError($x))
232 $sSQL = "update search_name set";
233 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
234 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
235 $x = $oDB->query($sSQL);
236 if (PEAR::isError($x))
242 $sSQL = "update location_area_country set";
243 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
244 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
245 $x = $oDB->query($sSQL);
246 if (PEAR::isError($x))
252 foreach ($aPartitions as $sPartition)
254 $sSQL = "update search_name_".$sPartition." set";
255 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
256 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
257 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
258 $x = $oDB->query($sSQL);
259 if (PEAR::isError($x))
265 $sSQL = "update search_name_".$sPartition." set";
266 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
267 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
268 $x = $oDB->query($sSQL);
269 if (PEAR::isError($x))
275 $sSQL = "update location_area_country set";
276 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
277 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
278 $x = $oDB->query($sSQL);
279 if (PEAR::isError($x))
286 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
287 $x = $oDB->query($sSQL);
288 if (PEAR::isError($x))
298 if ($aResult['index'])
300 index($aResult, $sDatabaseDSN);
303 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
305 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
306 $sOsmosisCMD = CONST_Osmosis_Binary;
307 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
308 $sDatabaseName = 'nominatim';
309 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
310 $sCMDImport = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sImportFile;
311 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -t '.$aResult['index-instances'];
312 if (!$aResult['no-npi']) {
317 $fStartTime = time();
320 // Logic behind this is that osm2pgsql locks the database quite a bit
321 // So it is better to import lots of small files
322 // But indexing works most efficiently on large amounts of data
323 // So do lots of small imports and a BIG index
325 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
327 if (!file_exists($sImportFile))
329 // Use osmosis to download the file
330 $fCMDStartTime = time();
331 echo $sCMDDownload."\n";
332 exec($sCMDDownload, $sJunk, $iErrorLevel);
333 while ($iErrorLevel == 1)
335 echo "Error: $iErrorLevel\n";
337 echo 'Re-trying: '.$sCMDDownload."\n";
338 exec($sCMDDownload, $sJunk, $iErrorLevel);
340 $iFileSize = filesize($sImportFile);
341 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
342 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
343 $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')";
347 $iFileSize = filesize($sImportFile);
348 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
351 $fCMDStartTime = time();
352 echo $sCMDImport."\n";
353 exec($sCMDImport, $sJunk, $iErrorLevel);
356 echo "Error: $iErrorLevel\n";
359 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
360 $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')";
364 // Archive for debug?
365 unlink($sImportFile);
368 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
371 $sThisIndexCmd = $sCMDIndex;
373 if (!$aResult['no-npi'])
375 $fCMDStartTime = time();
376 $iFileID = $oDB->getOne('select nextval(\'file\')');
377 if (PEAR::isError($iFileID))
379 echo $iFileID->getMessage()."\n";
382 $sFileDir = CONST_BasePath.'/export/diff/';
383 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
384 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
386 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
387 $sThisIndexCmd .= $sFileDir;
388 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
389 $sThisIndexCmd .= ".npi.out";
391 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
392 $sFileDir = CONST_BasePath.'/export/index/';
393 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
395 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
396 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
399 if (!$aResult['no-index'])
401 echo "$sThisIndexCmd\n";
402 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
405 echo "Error: $iErrorLevel\n";
409 if (!$aResult['no-npi'])
411 $sFileDir = CONST_BasePath.'/export/diff/';
412 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
413 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
415 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
416 echo "$sThisIndexCmd\n";
417 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
420 echo "Error: $iErrorLevel\n";
424 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
425 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
429 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
430 $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')";
433 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
436 $fDuration = time() - $fStartTime;
437 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
438 if (!$aResult['import-osmosis-all']) exit;
440 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
441 sleep(max(0,60-$fDuration));
446 if ($aResult['import-npi-all'])
448 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
449 if (PEAR::isError($iNPIID))
454 $sConfigDirectory = CONST_BasePath.'/settings';
455 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
458 $fStartTime = time();
462 $sImportFile = CONST_BasePath.'/export/diff/';
463 $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
464 $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
465 $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
466 $sImportFile .= ".npi";
467 while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
469 echo "sleep (waiting for $sImportFile)\n";
472 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
474 $iFileSize = filesize($sImportFile);
477 $fCMDStartTime = time();
478 $sCMDImport = $sCMDImportTemplate . $sImportFile;
479 echo $sCMDImport."\n";
480 exec($sCMDImport, $sJunk, $iErrorLevel);
483 echo "Error: $iErrorLevel\n";
486 $sBatchEnd = $iNPIID;
487 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
488 $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')";
495 function getosmosistimestamp($sOsmosisConfigDirectory)
497 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
498 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
499 return str_replace('\:',':',$aResult[1]);