3 require_once(CONST_BasePath.'/lib/init-cmd.php');
4 require_once(CONST_BasePath.'/lib/setup_functions.php');
5 require_once(CONST_BasePath.'/lib/setup/SetupClass.php');
6 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
8 ini_set('memory_limit', '800M');
10 use Nominatim\Setup\SetupFunctions as SetupFunctions;
12 // (long-opt, short-opt, min-occurs, max-occurs, num-arguments, num-arguments, type, help)
15 'Import / update / index osm data',
16 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
17 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
18 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
20 array('init-updates', '', 0, 1, 0, 0, 'bool', 'Set up database for updating'),
21 array('check-for-updates', '', 0, 1, 0, 0, 'bool', 'Check if new updates are available'),
22 array('no-update-functions', '', 0, 1, 0, 0, 'bool', 'Do not update trigger functions to support differential updates (assuming the diff update logic is already present)'),
23 array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import updates once'),
24 array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import updates forever'),
25 array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'),
27 array('calculate-postcodes', '', 0, 1, 0, 0, 'bool', 'Update postcode centroid table'),
29 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
30 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
31 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
33 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
34 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
35 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
36 array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
38 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
39 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
40 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
42 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
43 array('recompute-word-counts', '', 0, 1, 0, 0, 'bool', 'Compute frequency of full-word search terms'),
44 array('update-address-levels', '', 0, 1, 0, 0, 'bool', 'Reimport address level configuration (EXPERT)'),
45 array('recompute-importance', '', 0, 1, 0, 0, 'bool', 'Recompute place importances'),
46 array('no-npi', '', 0, 1, 0, 0, 'bool', '(obsolete)'),
49 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
51 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
52 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
54 date_default_timezone_set('Etc/UTC');
56 $oDB = new Nominatim\DB();
59 $aDSNInfo = Nominatim\DB::parseDSN(CONST_Database_DSN);
60 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
62 // cache memory to be used by osm2pgsql, should not be more than the available memory
63 $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
64 if ($iCacheMemory + 500 > getTotalMemoryMB()) {
65 $iCacheMemory = getCacheMemoryMB();
66 echo "WARNING: resetting cache memory to $iCacheMemory\n";
69 $oOsm2pgsqlCmd = (new \Nominatim\Shell(CONST_Osm2pgsql_Binary))
70 ->addParams('--hstore')
71 ->addParams('--latlong')
72 ->addParams('--append')
74 ->addParams('--number-processes', 1)
75 ->addParams('--cache', $iCacheMemory)
76 ->addParams('--output', 'gazetteer')
77 ->addParams('--style', CONST_Import_Style)
78 ->addParams('--database', $aDSNInfo['database'])
79 ->addParams('--port', $aDSNInfo['port']);
81 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
82 $oOsm2pgsqlCmd->addParams('--host', $aDSNInfo['hostspec']);
84 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
85 $oOsm2pgsqlCmd->addParams('--user', $aDSNInfo['username']);
87 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
88 $oOsm2pgsqlCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
90 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
91 $oOsm2pgsqlCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
95 $oIndexCmd = (new \Nominatim\Shell(CONST_BasePath.'/nominatim/nominatim.py'))
96 ->addParams('--database', $aDSNInfo['database'])
97 ->addParams('--port', $aDSNInfo['port'])
98 ->addParams('--threads', $aResult['index-instances']);
100 if ($aResult['verbose']) {
101 $oIndexCmd->addParams('--verbose');
103 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
104 $oIndexCmd->addParams('--host', $aDSNInfo['hostspec']);
106 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
107 $oIndexCmd->addParams('--username', $aDSNInfo['username']);
109 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
110 $oIndexCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
114 if ($aResult['init-updates']) {
115 // sanity check that the replication URL is correct
116 $sBaseState = file_get_contents(CONST_Replication_Url.'/state.txt');
117 if ($sBaseState === false) {
118 echo "\nCannot find state.txt file at the configured replication URL.\n";
119 echo "Does the URL point to a directory containing OSM update data?\n\n";
120 fail('replication URL not reachable.');
122 // sanity check for pyosmium-get-changes
123 if (!CONST_Pyosmium_Binary) {
124 echo "\nCONST_Pyosmium_Binary not configured.\n";
125 echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
126 echo "in your local settings file.\n\n";
127 fail('CONST_Pyosmium_Binary not configured');
131 $oCMD = new \Nominatim\Shell(CONST_Pyosmium_Binary, '--help');
132 exec($oCMD->escapedCmd(), $aOutput, $iRet);
135 echo "Cannot execute pyosmium-get-changes.\n";
136 echo "Make sure you have pyosmium installed correctly\n";
137 echo "and have set up CONST_Pyosmium_Binary to point to pyosmium-get-changes.\n";
138 fail('pyosmium-get-changes not found or not usable');
141 if (!$aResult['no-update-functions']) {
142 // instantiate setupClass to use the function therein
143 $cSetup = new SetupFunctions(array(
144 'enable-diff-updates' => true,
145 'verbose' => $aResult['verbose']
148 $cSetup->createFunctions();
151 $sDatabaseDate = getDatabaseDate($oDB);
152 if (!$sDatabaseDate) {
153 fail('Cannot determine date of database.');
155 $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3*60*60));
157 // get the appropriate state id
159 $oCMD = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
160 ->addParams('--start-date', $sWindBack)
161 ->addParams('--server', CONST_Replication_Url);
163 exec($oCMD->escapedCmd(), $aOutput, $iRet);
164 if ($iRet != 0 || $aOutput[0] == 'None') {
165 fail('Error running pyosmium tools');
168 $oDB->exec('TRUNCATE import_status');
169 $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
170 $sSQL .= $sDatabaseDate."',".$aOutput[0].', true)';
174 } catch (\Nominatim\DatabaseError $e) {
175 fail('Could not enter sequence into database.');
178 echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
181 if ($aResult['check-for-updates']) {
182 $aLastState = $oDB->getRow('SELECT sequence_id FROM import_status');
184 if (!$aLastState['sequence_id']) {
185 fail('Updates not set up. Please run ./utils/update.php --init-updates.');
188 $oCmd = (new \Nominatim\Shell(CONST_BasePath.'/utils/check_server_for_updates.py'))
189 ->addParams(CONST_Replication_Url)
190 ->addParams($aLastState['sequence_id']);
191 $iRet = $oCmd->run();
196 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
197 // import diffs and files directly (e.g. from osmosis --rri)
198 $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
200 if (!file_exists($sNextFile)) {
201 fail("Cannot open $sNextFile\n");
205 $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sNextFile);
206 echo $oCMD->escapedCmd()."\n";
207 $iRet = $oCMD->run();
210 fail("Error from osm2pgsql, $iRet\n");
213 // Don't update the import status - we don't know what this file contains
216 if ($aResult['calculate-postcodes']) {
217 info('Update postcodes centroids');
218 $sTemplate = file_get_contents(CONST_BasePath.'/sql/update-postcodes.sql');
219 runSQLScript($sTemplate, true, true);
222 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
224 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
226 if (isset($aResult['import-node']) && $aResult['import-node']) {
228 $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
230 $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
234 if (isset($aResult['import-way']) && $aResult['import-way']) {
236 $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
238 $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
242 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
244 $sContentURLsModifyXMLstr = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
246 $sContentURL = 'https://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;';
251 file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
256 // import generated change file
258 $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sTemporaryFile);
259 echo $oCMD->escapedCmd()."\n";
261 $iRet = $oCMD->run();
263 fail("osm2pgsql exited with error level $iRet\n");
267 if ($aResult['deduplicate']) {
268 $oDB = new Nominatim\DB();
271 if ($oDB->getPostgresVersion() < 9.3) {
272 fail('ERROR: deduplicate is only currently supported in postgresql 9.3');
275 $sSQL = 'select partition from country_name order by country_code';
276 $aPartitions = $oDB->getCol($sSQL);
279 // we don't care about empty search_name_* partitions, they can't contain mentions of duplicates
280 foreach ($aPartitions as $i => $sPartition) {
281 $sSQL = 'select count(*) from search_name_'.$sPartition;
282 $nEntries = $oDB->getOne($sSQL);
283 if ($nEntries == 0) {
284 unset($aPartitions[$i]);
288 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' '";
289 $sSQL .= ' and class is null and type is null and country_code is null';
290 $sSQL .= ' group by word_token having count(*) > 1 order by word_token';
291 $aDuplicateTokens = $oDB->getAll($sSQL);
292 foreach ($aDuplicateTokens as $aToken) {
293 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
294 echo 'Deduping '.$aToken['word_token']."\n";
295 $sSQL = 'select word_id,';
296 $sSQL .= ' (select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num';
297 $sSQL .= " from word where word_token = '".$aToken['word_token'];
298 $sSQL .= "' and class is null and type is null and country_code is null order by num desc";
299 $aTokenSet = $oDB->getAll($sSQL);
301 $aKeep = array_shift($aTokenSet);
302 $iKeepID = $aKeep['word_id'];
304 foreach ($aTokenSet as $aRemove) {
305 $sSQL = 'update search_name set';
306 $sSQL .= ' name_vector = array_replace(name_vector,'.$aRemove['word_id'].','.$iKeepID.'),';
307 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,'.$aRemove['word_id'].','.$iKeepID.')';
308 $sSQL .= ' where name_vector @> ARRAY['.$aRemove['word_id'].']';
311 $sSQL = 'update search_name set';
312 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,'.$aRemove['word_id'].','.$iKeepID.')';
313 $sSQL .= ' where nameaddress_vector @> ARRAY['.$aRemove['word_id'].']';
316 $sSQL = 'update location_area_country set';
317 $sSQL .= ' keywords = array_replace(keywords,'.$aRemove['word_id'].','.$iKeepID.')';
318 $sSQL .= ' where keywords @> ARRAY['.$aRemove['word_id'].']';
321 foreach ($aPartitions as $sPartition) {
322 $sSQL = 'update search_name_'.$sPartition.' set';
323 $sSQL .= ' name_vector = array_replace(name_vector,'.$aRemove['word_id'].','.$iKeepID.')';
324 $sSQL .= ' where name_vector @> ARRAY['.$aRemove['word_id'].']';
327 $sSQL = 'update location_area_country set';
328 $sSQL .= ' keywords = array_replace(keywords,'.$aRemove['word_id'].','.$iKeepID.')';
329 $sSQL .= ' where keywords @> ARRAY['.$aRemove['word_id'].']';
333 $sSQL = 'delete from word where word_id = '.$aRemove['word_id'];
339 if ($aResult['recompute-word-counts']) {
340 info('Recompute frequency of full-word search terms');
341 $sTemplate = file_get_contents(CONST_BasePath.'/sql/words_from_search_name.sql');
342 runSQLScript($sTemplate, true, true);
345 if ($aResult['index']) {
346 $oCmd = (clone $oIndexCmd)
347 ->addParams('--minrank', $aResult['index-rank']);
349 // echo $oCmd->escapedCmd()."\n";
352 $oDB->exec('update import_status set indexed = true');
355 if ($aResult['update-address-levels']) {
356 echo 'Updating address levels from '.CONST_Address_Level_Config.".\n";
357 $oAlParser = new \Nominatim\Setup\AddressLevelParser(CONST_Address_Level_Config);
358 $oAlParser->createTable($oDB, 'address_levels');
361 if ($aResult['recompute-importance']) {
362 echo "Updating importance values for database.\n";
363 $oDB = new Nominatim\DB();
366 $sSQL = 'ALTER TABLE placex DISABLE TRIGGER ALL;';
367 $sSQL .= 'UPDATE placex SET (wikipedia, importance) =';
368 $sSQL .= ' (SELECT wikipedia, importance';
369 $sSQL .= ' FROM compute_importance(extratags, country_code, osm_type, osm_id));';
370 $sSQL .= 'UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance';
371 $sSQL .= ' FROM placex d';
372 $sSQL .= ' WHERE s.place_id = d.linked_place_id and d.wikipedia is not null';
373 $sSQL .= ' and (s.wikipedia is null or s.importance < d.importance);';
374 $sSQL .= 'ALTER TABLE placex ENABLE TRIGGER ALL;';
378 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
380 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
381 fail('Error: Update interval too low for download.geofabrik.de. ' .
382 "Please check install documentation (https://nominatim.org/release-docs/latest/admin/Import-and-Update#setting-up-the-update-process)\n");
385 $sImportFile = CONST_InstallPath.'/osmosischange.osc';
387 $oCMDDownload = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
388 ->addParams('--server', CONST_Replication_Url)
389 ->addParams('--outfile', $sImportFile)
390 ->addParams('--size', CONST_Replication_Max_Diff_size);
392 $oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
395 $fStartTime = time();
396 $aLastState = $oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status');
398 if (!$aLastState['sequence_id']) {
399 echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
403 echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
405 $sBatchEnd = $aLastState['lastimportdate'];
406 $iEndSequence = $aLastState['sequence_id'];
408 if ($aLastState['indexed']) {
409 // Sleep if the update interval has not yet been reached.
410 $fNextUpdate = $aLastState['unix_ts'] + CONST_Replication_Update_Interval;
411 if ($fNextUpdate > $fStartTime) {
412 $iSleepTime = $fNextUpdate - $fStartTime;
413 echo "Waiting for next update for $iSleepTime sec.";
417 // Download the next batch of changes.
419 $fCMDStartTime = time();
420 $iNextSeq = (int) $aLastState['sequence_id'];
423 $oCMD = (clone $oCMDDownload)->addParams('--start-id', $iNextSeq);
424 echo $oCMD->escapedCmd()."\n";
425 if (file_exists($sImportFile)) {
426 unlink($sImportFile);
428 exec($oCMD->escapedCmd(), $aOutput, $iResult);
431 echo 'No new updates. Sleeping for '.CONST_Replication_Recheck_Interval." sec.\n";
432 sleep(CONST_Replication_Recheck_Interval);
433 } elseif ($iResult != 0) {
434 echo 'ERROR: updates failed.';
437 $iEndSequence = (int)$aOutput[0];
441 // get the newest object from the diff file
444 $oCMD = new \Nominatim\Shell(CONST_BasePath.'/utils/osm_file_date.py', $sImportFile);
445 exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
447 echo "Diff file is empty. skipping import.\n";
448 if (!$aResult['import-osmosis-all']) {
455 fail('Error getting date from diff file.');
457 $sBatchEnd = $sBatchEnd[0];
460 $fCMDStartTime = time();
463 echo $oCMDImport->escapedCmd()."\n";
465 $iErrorLevel = $oCMDImport->run();
467 echo "Error executing osm2pgsql: $iErrorLevel\n";
471 // write the update logs
472 $iFileSize = filesize($sImportFile);
473 $sSQL = 'INSERT INTO import_osmosis_log';
474 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
475 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
476 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
477 $sSQL .= date('Y-m-d H:i:s')."','import')";
482 $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
485 echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
489 if (!$aResult['no-index']) {
490 $oThisIndexCmd = clone($oIndexCmd);
491 $fCMDStartTime = time();
493 echo $oThisIndexCmd->escapedCmd()."\n";
494 $iErrorLevel = $oThisIndexCmd->run();
496 echo "Error: $iErrorLevel\n";
500 $sSQL = 'INSERT INTO import_osmosis_log';
501 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
502 $sSQL .= " values ('$sBatchEnd',$iEndSequence,NULL,'";
503 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
504 $sSQL .= date('Y-m-d H:i:s')."','index')";
507 echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
509 $sSQL = 'update import_status set indexed = true';
512 if ($aResult['import-osmosis-all']) {
513 echo "Error: --no-index cannot be used with continuous imports (--import-osmosis-all).\n";
518 $fDuration = time() - $fStartTime;
519 echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60, 2)." minutes\n";
520 if (!$aResult['import-osmosis-all']) exit(0);