3 require_once(CONST_LibDir.'/init-cmd.php');
4 require_once(CONST_LibDir.'/setup_functions.php');
5 require_once(CONST_LibDir.'/setup/SetupClass.php');
6 require_once(CONST_LibDir.'/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('recompute-word-counts', '', 0, 1, 0, 0, 'bool', 'Compute frequency of full-word search terms'),
43 array('update-address-levels', '', 0, 1, 0, 0, 'bool', 'Reimport address level configuration (EXPERT)'),
44 array('recompute-importance', '', 0, 1, 0, 0, 'bool', 'Recompute place importances')
47 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();
58 $fPostgresVersion = $oDB->getPostgresVersion();
60 $aDSNInfo = Nominatim\DB::parseDSN(CONST_Database_DSN);
61 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
63 // cache memory to be used by osm2pgsql, should not be more than the available memory
64 $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
65 if ($iCacheMemory + 500 > getTotalMemoryMB()) {
66 $iCacheMemory = getCacheMemoryMB();
67 echo "WARNING: resetting cache memory to $iCacheMemory\n";
70 $oOsm2pgsqlCmd = (new \Nominatim\Shell(CONST_Osm2pgsql_Binary))
71 ->addParams('--hstore')
72 ->addParams('--latlong')
73 ->addParams('--append')
75 ->addParams('--with-forward-dependencies', 'false')
76 ->addParams('--log-progress', 'true')
77 ->addParams('--number-processes', 1)
78 ->addParams('--cache', $iCacheMemory)
79 ->addParams('--output', 'gazetteer')
80 ->addParams('--style', CONST_Import_Style)
81 ->addParams('--database', $aDSNInfo['database'])
82 ->addParams('--port', $aDSNInfo['port']);
84 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
85 $oOsm2pgsqlCmd->addParams('--host', $aDSNInfo['hostspec']);
87 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
88 $oOsm2pgsqlCmd->addParams('--user', $aDSNInfo['username']);
90 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
91 $oOsm2pgsqlCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
93 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
94 $oOsm2pgsqlCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
96 if ($fPostgresVersion >= 11.0) {
97 $oOsm2pgsqlCmd->addEnvPair(
99 '-c jit=off -c max_parallel_workers_per_gather=0'
104 $oIndexCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
105 ->addParams('--database', $aDSNInfo['database'])
106 ->addParams('--port', $aDSNInfo['port'])
107 ->addParams('--threads', $aResult['index-instances']);
108 if (!$aResult['quiet']) {
109 $oIndexCmd->addParams('--verbose');
111 if ($aResult['verbose']) {
112 $oIndexCmd->addParams('--verbose');
114 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
115 $oIndexCmd->addParams('--host', $aDSNInfo['hostspec']);
117 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
118 $oIndexCmd->addParams('--username', $aDSNInfo['username']);
120 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
121 $oIndexCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
125 if ($aResult['init-updates']) {
126 // sanity check that the replication URL is correct
127 $sBaseState = file_get_contents(CONST_Replication_Url.'/state.txt');
128 if ($sBaseState === false) {
129 echo "\nCannot find state.txt file at the configured replication URL.\n";
130 echo "Does the URL point to a directory containing OSM update data?\n\n";
131 fail('replication URL not reachable.');
133 // sanity check for pyosmium-get-changes
134 if (!CONST_Pyosmium_Binary) {
135 echo "\nCONST_Pyosmium_Binary not configured.\n";
136 echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
137 echo "in your local settings file.\n\n";
138 fail('CONST_Pyosmium_Binary not configured');
142 $oCMD = new \Nominatim\Shell(CONST_Pyosmium_Binary, '--help');
143 exec($oCMD->escapedCmd(), $aOutput, $iRet);
146 echo "Cannot execute pyosmium-get-changes.\n";
147 echo "Make sure you have pyosmium installed correctly\n";
148 echo "and have set up CONST_Pyosmium_Binary to point to pyosmium-get-changes.\n";
149 fail('pyosmium-get-changes not found or not usable');
152 if (!$aResult['no-update-functions']) {
153 // instantiate setupClass to use the function therein
154 $cSetup = new SetupFunctions(array(
155 'enable-diff-updates' => true,
156 'verbose' => $aResult['verbose']
158 $cSetup->createFunctions();
161 $sDatabaseDate = getDatabaseDate($oDB);
162 if (!$sDatabaseDate) {
163 fail('Cannot determine date of database.');
165 $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3*60*60));
167 // get the appropriate state id
169 $oCMD = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
170 ->addParams('--start-date', $sWindBack)
171 ->addParams('--server', CONST_Replication_Url);
173 exec($oCMD->escapedCmd(), $aOutput, $iRet);
174 if ($iRet != 0 || $aOutput[0] == 'None') {
175 fail('Error running pyosmium tools');
178 $oDB->exec('TRUNCATE import_status');
179 $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
180 $sSQL .= $sDatabaseDate."',".$aOutput[0].', true)';
184 } catch (\Nominatim\DatabaseError $e) {
185 fail('Could not enter sequence into database.');
188 echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
191 if ($aResult['check-for-updates']) {
192 $aLastState = $oDB->getRow('SELECT sequence_id FROM import_status');
194 if (!$aLastState['sequence_id']) {
195 fail('Updates not set up. Please run ./utils/update.php --init-updates.');
198 $oCmd = (new \Nominatim\Shell(CONST_BinDir.'/check_server_for_updates.py'))
199 ->addParams(CONST_Replication_Url)
200 ->addParams($aLastState['sequence_id']);
201 $iRet = $oCmd->run();
206 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
207 // import diffs and files directly (e.g. from osmosis --rri)
208 $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
210 if (!file_exists($sNextFile)) {
211 fail("Cannot open $sNextFile\n");
215 $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sNextFile);
216 echo $oCMD->escapedCmd()."\n";
217 $iRet = $oCMD->run();
220 fail("Error from osm2pgsql, $iRet\n");
223 // Don't update the import status - we don't know what this file contains
226 if ($aResult['calculate-postcodes']) {
227 info('Update postcodes centroids');
228 $sTemplate = file_get_contents(CONST_DataDir.'/sql/update-postcodes.sql');
229 runSQLScript($sTemplate, true, true);
232 $sTemporaryFile = CONST_InstallDir.'/osmosischange.osc';
234 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
236 if (isset($aResult['import-node']) && $aResult['import-node']) {
238 $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
240 $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
244 if (isset($aResult['import-way']) && $aResult['import-way']) {
246 $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
248 $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');%3E;);out%20meta;';
252 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
254 $sContentURL = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
256 $sContentURL = 'https://overpass-api.de/api/interpreter?data=(rel(id:'.$aResult['import-relation'].');%3E;);out%20meta;';
261 file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
266 // import generated change file
268 $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sTemporaryFile);
269 echo $oCMD->escapedCmd()."\n";
271 $iRet = $oCMD->run();
273 fail("osm2pgsql exited with error level $iRet\n");
277 if ($aResult['recompute-word-counts']) {
278 info('Recompute frequency of full-word search terms');
279 $sTemplate = file_get_contents(CONST_DataDir.'/sql/words_from_search_name.sql');
280 runSQLScript($sTemplate, true, true);
283 if ($aResult['index']) {
284 $oCmd = (clone $oIndexCmd)
285 ->addParams('--minrank', $aResult['index-rank'], '-b');
288 $oCmd = (clone $oIndexCmd)
289 ->addParams('--minrank', $aResult['index-rank']);
292 $oDB->exec('update import_status set indexed = true');
295 if ($aResult['update-address-levels']) {
296 echo 'Updating address levels from '.CONST_Address_Level_Config.".\n";
297 $oAlParser = new \Nominatim\Setup\AddressLevelParser(CONST_Address_Level_Config);
298 $oAlParser->createTable($oDB, 'address_levels');
301 if ($aResult['recompute-importance']) {
302 echo "Updating importance values for database.\n";
303 $oDB = new Nominatim\DB();
306 $sSQL = 'ALTER TABLE placex DISABLE TRIGGER ALL;';
307 $sSQL .= 'UPDATE placex SET (wikipedia, importance) =';
308 $sSQL .= ' (SELECT wikipedia, importance';
309 $sSQL .= ' FROM compute_importance(extratags, country_code, osm_type, osm_id));';
310 $sSQL .= 'UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance';
311 $sSQL .= ' FROM placex d';
312 $sSQL .= ' WHERE s.place_id = d.linked_place_id and d.wikipedia is not null';
313 $sSQL .= ' and (s.wikipedia is null or s.importance < d.importance);';
314 $sSQL .= 'ALTER TABLE placex ENABLE TRIGGER ALL;';
318 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
320 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
321 fail('Error: Update interval too low for download.geofabrik.de. ' .
322 "Please check install documentation (https://nominatim.org/release-docs/latest/admin/Import-and-Update#setting-up-the-update-process)\n");
325 $sImportFile = CONST_InstallDir.'/osmosischange.osc';
327 $oCMDDownload = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
328 ->addParams('--server', CONST_Replication_Url)
329 ->addParams('--outfile', $sImportFile)
330 ->addParams('--size', CONST_Replication_Max_Diff_size);
332 $oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
335 $fStartTime = time();
336 $aLastState = $oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status');
338 if (!$aLastState['sequence_id']) {
339 echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
343 echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
345 $sBatchEnd = $aLastState['lastimportdate'];
346 $iEndSequence = $aLastState['sequence_id'];
348 if ($aLastState['indexed']) {
349 // Sleep if the update interval has not yet been reached.
350 $fNextUpdate = $aLastState['unix_ts'] + CONST_Replication_Update_Interval;
351 if ($fNextUpdate > $fStartTime) {
352 $iSleepTime = $fNextUpdate - $fStartTime;
353 echo "Waiting for next update for $iSleepTime sec.";
357 // Download the next batch of changes.
359 $fCMDStartTime = time();
360 $iNextSeq = (int) $aLastState['sequence_id'];
363 $oCMD = (clone $oCMDDownload)->addParams('--start-id', $iNextSeq);
364 echo $oCMD->escapedCmd()."\n";
365 if (file_exists($sImportFile)) {
366 unlink($sImportFile);
368 exec($oCMD->escapedCmd(), $aOutput, $iResult);
371 echo 'No new updates. Sleeping for '.CONST_Replication_Recheck_Interval." sec.\n";
372 sleep(CONST_Replication_Recheck_Interval);
373 } elseif ($iResult != 0) {
374 echo 'ERROR: updates failed.';
377 $iEndSequence = (int)$aOutput[0];
381 // get the newest object from the diff file
384 $oCMD = new \Nominatim\Shell(CONST_BinDir.'/osm_file_date.py', $sImportFile);
385 exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
387 echo "Diff file is empty. skipping import.\n";
388 if (!$aResult['import-osmosis-all']) {
395 fail('Error getting date from diff file.');
397 $sBatchEnd = $sBatchEnd[0];
400 $fCMDStartTime = time();
403 echo $oCMDImport->escapedCmd()."\n";
405 $iErrorLevel = $oCMDImport->run();
407 echo "Error executing osm2pgsql: $iErrorLevel\n";
411 // write the update logs
412 $iFileSize = filesize($sImportFile);
413 $sSQL = 'INSERT INTO import_osmosis_log';
414 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
415 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
416 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
417 $sSQL .= date('Y-m-d H:i:s')."','import')";
422 $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
425 echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
429 if (!$aResult['no-index']) {
430 $fCMDStartTime = time();
432 $oThisIndexCmd = clone($oIndexCmd);
433 $oThisIndexCmd->addParams('-b');
434 echo $oThisIndexCmd->escapedCmd()."\n";
435 $iErrorLevel = $oThisIndexCmd->run();
437 echo "Error: $iErrorLevel\n";
441 $oThisIndexCmd = clone($oIndexCmd);
442 echo $oThisIndexCmd->escapedCmd()."\n";
443 $iErrorLevel = $oThisIndexCmd->run();
445 echo "Error: $iErrorLevel\n";
449 $sSQL = 'INSERT INTO import_osmosis_log';
450 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
451 $sSQL .= " values ('$sBatchEnd',$iEndSequence,NULL,'";
452 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
453 $sSQL .= date('Y-m-d H:i:s')."','index')";
456 echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
458 $sSQL = 'update import_status set indexed = true';
461 if ($aResult['import-osmosis-all']) {
462 echo "Error: --no-index cannot be used with continuous imports (--import-osmosis-all).\n";
467 $fDuration = time() - $fStartTime;
468 echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60, 2)." minutes\n";
469 if (!$aResult['import-osmosis-all']) exit(0);