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;
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__));
71 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
74 $bContinue = $aResult['import-all'];
75 while ($bContinue || $bFirst)
79 if ($aResult['import-hourly'])
81 // Mirror the hourly diffs
82 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
83 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
84 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
85 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
88 if ($aResult['import-daily'])
90 // Mirror the daily diffs
91 exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
92 $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
93 $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
94 $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
97 if (isset($aResult['import-diff']))
99 // import diff directly (e.g. from osmosis --rri)
100 $sNextFile = $aResult['import-diff'];
101 if (!file_exists($sNextFile))
103 echo "Cannot open $nextFile\n";
106 // Don't update the import status - we don't know what this file contains
107 $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
110 // Missing file is not an error - it might not be created yet
111 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
114 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sNextFile;
116 exec($sCMD, $sJunk, $iErrorLevel);
120 echo "Error from osm2pgsql, $iErrorLevel\n";
124 // Move the date onwards
125 $oDB->query($sUpdateSQL);
135 if (isset($aResult['import-file']) && $aResult['import-file'])
139 if (isset($aResult['import-node']) && $aResult['import-node'])
142 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
144 if (isset($aResult['import-way']) && $aResult['import-way'])
147 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
149 if (isset($aResult['import-relation']) && $aResult['import-relation'])
152 $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
156 // derive change from normal osm file with osmosis
157 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
158 if (isset($aResult['import-file']) && $aResult['import-file'])
160 $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
162 exec($sCMD, $sJunk, $iErrorLevel);
165 echo "Error converting osm to osc, osmosis returned: $iErrorLevel\n";
172 0 => array("pipe", "r"), // stdin
173 1 => array("pipe", "w"), // stdout
174 2 => array("pipe", "w") // stderr
176 $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
178 $hProc = proc_open($sCMD, $aSpec, $aPipes);
179 if (!is_resource($hProc))
181 echo "Error converting osm to osc, osmosis failed\n";
184 fwrite($aPipes[0], $sModifyXMLstr);
186 $sOut = stream_get_contents($aPipes[1]);
187 if ($aResult['verbose']) echo $sOut;
189 $sErrors = stream_get_contents($aPipes[2]);
190 if ($aResult['verbose']) echo $sErrors;
192 if ($iError = proc_close($hProc))
194 echo "Error converting osm to osc, osmosis returned: $iError\n";
201 // import generated change file
202 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sTemporaryFile;
204 exec($sCMD, $sJunk, $iErrorLevel);
207 echo "osm2pgsql exited with error level $iErrorLevel\n";
212 if ($aResult['deduplicate'])
215 $sSQL = 'select partition from country_name order by country_code';
216 $aPartitions = $oDB->getCol($sSQL);
217 if (PEAR::isError($aPartitions))
219 fail($aPartitions->getMessage());
223 $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";
224 $aDuplicateTokens = $oDB->getAll($sSQL);
225 foreach($aDuplicateTokens as $aToken)
227 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
228 echo "Deduping ".$aToken['word_token']."\n";
229 $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";
230 $aTokenSet = $oDB->getAll($sSQL);
231 if (PEAR::isError($aTokenSet))
233 var_dump($aTokenSet, $sSQL);
237 $aKeep = array_shift($aTokenSet);
238 $iKeepID = $aKeep['word_id'];
240 foreach($aTokenSet as $aRemove)
242 $sSQL = "update search_name set";
243 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
244 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
245 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
246 $x = $oDB->query($sSQL);
247 if (PEAR::isError($x))
253 $sSQL = "update search_name set";
254 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
255 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
256 $x = $oDB->query($sSQL);
257 if (PEAR::isError($x))
263 $sSQL = "update location_area_country set";
264 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
265 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
266 $x = $oDB->query($sSQL);
267 if (PEAR::isError($x))
273 foreach ($aPartitions as $sPartition)
275 $sSQL = "update search_name_".$sPartition." set";
276 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
277 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
278 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
279 $x = $oDB->query($sSQL);
280 if (PEAR::isError($x))
286 $sSQL = "update search_name_".$sPartition." set";
287 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
288 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
289 $x = $oDB->query($sSQL);
290 if (PEAR::isError($x))
296 $sSQL = "update location_area_country set";
297 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
298 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
299 $x = $oDB->query($sSQL);
300 if (PEAR::isError($x))
307 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
308 $x = $oDB->query($sSQL);
309 if (PEAR::isError($x))
319 if ($aResult['index'])
321 passthru(CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
324 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
326 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
327 $sOsmosisCMD = CONST_Osmosis_Binary;
328 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
329 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
330 $sCMDImport = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sImportFile;
331 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -t '.$aResult['index-instances'];
332 if (!$aResult['no-npi']) {
337 $fStartTime = time();
340 // Logic behind this is that osm2pgsql locks the database quite a bit
341 // So it is better to import lots of small files
342 // But indexing works most efficiently on large amounts of data
343 // So do lots of small imports and a BIG index
345 // while($aResult['import-osmosis-all'] && $iFileSize > 1000)
347 if (!file_exists($sImportFile))
349 // Use osmosis to download the file
350 $fCMDStartTime = time();
351 echo $sCMDDownload."\n";
352 exec($sCMDDownload, $sJunk, $iErrorLevel);
353 while ($iErrorLevel == 1)
355 echo "Error: $iErrorLevel\n";
357 echo 'Re-trying: '.$sCMDDownload."\n";
358 exec($sCMDDownload, $sJunk, $iErrorLevel);
360 $iFileSize = filesize($sImportFile);
361 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
362 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
363 $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')";
367 $iFileSize = filesize($sImportFile);
368 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
371 $fCMDStartTime = time();
372 echo $sCMDImport."\n";
373 exec($sCMDImport, $sJunk, $iErrorLevel);
376 echo "Error: $iErrorLevel\n";
379 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
380 $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')";
384 // Archive for debug?
385 unlink($sImportFile);
388 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
391 $sThisIndexCmd = $sCMDIndex;
393 if (!$aResult['no-npi'])
395 $fCMDStartTime = time();
396 $iFileID = $oDB->getOne('select nextval(\'file\')');
397 if (PEAR::isError($iFileID))
399 echo $iFileID->getMessage()."\n";
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 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
407 $sThisIndexCmd .= $sFileDir;
408 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
409 $sThisIndexCmd .= ".npi.out";
411 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
412 $sFileDir = CONST_BasePath.'/export/index/';
413 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
415 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
416 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
419 if (!$aResult['no-index'])
421 echo "$sThisIndexCmd\n";
422 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
425 echo "Error: $iErrorLevel\n";
429 if (!$aResult['no-npi'])
431 $sFileDir = CONST_BasePath.'/export/diff/';
432 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
433 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
435 $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
436 echo "$sThisIndexCmd\n";
437 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
440 echo "Error: $iErrorLevel\n";
444 rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
445 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
449 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
450 $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')";
453 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
456 $fDuration = time() - $fStartTime;
457 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
458 if (!$aResult['import-osmosis-all']) exit;
460 echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
461 sleep(max(0,60-$fDuration));
466 if ($aResult['import-npi-all'])
468 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
469 if (PEAR::isError($iNPIID))
474 $sConfigDirectory = CONST_BasePath.'/settings';
475 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
478 $fStartTime = time();
482 $sImportFile = CONST_BasePath.'/export/diff/';
483 $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
484 $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
485 $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
486 $sImportFile .= ".npi";
487 while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
489 echo "sleep (waiting for $sImportFile)\n";
492 if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
494 $iFileSize = filesize($sImportFile);
497 $fCMDStartTime = time();
498 $sCMDImport = $sCMDImportTemplate . $sImportFile;
499 echo $sCMDImport."\n";
500 exec($sCMDImport, $sJunk, $iErrorLevel);
503 echo "Error: $iErrorLevel\n";
506 $sBatchEnd = $iNPIID;
507 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
508 $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')";
515 function getosmosistimestamp($sOsmosisConfigDirectory)
517 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
518 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
519 return str_replace('\:',':',$aResult[1]);