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'),
 
  46    array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
 
  49 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
 
  51 loadSettings($aCMDResult['project-dir'] ?? getcwd());
 
  54 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
 
  55 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
 
  57 date_default_timezone_set('Etc/UTC');
 
  59 $oDB = new Nominatim\DB();
 
  61 $fPostgresVersion = $oDB->getPostgresVersion();
 
  63 $aDSNInfo = Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
 
  64 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
 
  66 // cache memory to be used by osm2pgsql, should not be more than the available memory
 
  67 $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
 
  68 if ($iCacheMemory + 500 > getTotalMemoryMB()) {
 
  69     $iCacheMemory = getCacheMemoryMB();
 
  70     echo "WARNING: resetting cache memory to $iCacheMemory\n";
 
  73 $oOsm2pgsqlCmd = (new \Nominatim\Shell(getOsm2pgsqlBinary()))
 
  74                  ->addParams('--hstore')
 
  75                  ->addParams('--latlong')
 
  76                  ->addParams('--append')
 
  78                  ->addParams('--with-forward-dependencies', 'false')
 
  79                  ->addParams('--log-progress', 'true')
 
  80                  ->addParams('--number-processes', 1)
 
  81                  ->addParams('--cache', $iCacheMemory)
 
  82                  ->addParams('--output', 'gazetteer')
 
  83                  ->addParams('--style', getImportStyle())
 
  84                  ->addParams('--database', $aDSNInfo['database'])
 
  85                  ->addParams('--port', $aDSNInfo['port']);
 
  87 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
 
  88     $oOsm2pgsqlCmd->addParams('--host', $aDSNInfo['hostspec']);
 
  90 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
 
  91     $oOsm2pgsqlCmd->addParams('--user', $aDSNInfo['username']);
 
  93 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
 
  94     $oOsm2pgsqlCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
 
  96 if (getSetting('FLATNODE_FILE')) {
 
  97     $oOsm2pgsqlCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
 
  99 if ($fPostgresVersion >= 11.0) {
 
 100     $oOsm2pgsqlCmd->addEnvPair(
 
 102         '-c jit=off -c max_parallel_workers_per_gather=0'
 
 107 $oIndexCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
 
 108              ->addParams('--database', $aDSNInfo['database'])
 
 109              ->addParams('--port', $aDSNInfo['port'])
 
 110              ->addParams('--threads', $aResult['index-instances']);
 
 111 if (!$aResult['quiet']) {
 
 112     $oIndexCmd->addParams('--verbose');
 
 114 if ($aResult['verbose']) {
 
 115     $oIndexCmd->addParams('--verbose');
 
 117 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
 
 118     $oIndexCmd->addParams('--host', $aDSNInfo['hostspec']);
 
 120 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
 
 121     $oIndexCmd->addParams('--username', $aDSNInfo['username']);
 
 123 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
 
 124     $oIndexCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
 
 127 $sPyosmiumBin = getSetting('PYOSMIUM_BINARY');
 
 128 $sBaseURL = getSetting('REPLICATION_URL');
 
 131 if ($aResult['init-updates']) {
 
 132     // sanity check that the replication URL is correct
 
 133     $sBaseState = file_get_contents($sBaseURL.'/state.txt');
 
 134     if ($sBaseState === false) {
 
 135         echo "\nCannot find state.txt file at the configured replication URL.\n";
 
 136         echo "Does the URL point to a directory containing OSM update data?\n\n";
 
 137         fail('replication URL not reachable.');
 
 139     // sanity check for pyosmium-get-changes
 
 140     if (!$sPyosmiumBin) {
 
 141         echo "\nNOMINATIM_PYOSMIUM_BINARY not configured.\n";
 
 142         echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
 
 143         echo "in your local .env file.\n\n";
 
 144         fail('NOMINATIM_PYOSMIUM_BINARY not configured');
 
 148     $oCMD = new \Nominatim\Shell($sPyosmiumBin, '--help');
 
 149     exec($oCMD->escapedCmd(), $aOutput, $iRet);
 
 152         echo "Cannot execute pyosmium-get-changes.\n";
 
 153         echo "Make sure you have pyosmium installed correctly\n";
 
 154         echo "and have set up NOMINATIM_PYOSMIUM_BINARY to point to pyosmium-get-changes.\n";
 
 155         fail('pyosmium-get-changes not found or not usable');
 
 158     if (!$aResult['no-update-functions']) {
 
 159         // instantiate setupClass to use the function therein
 
 160         $cSetup = new SetupFunctions(array(
 
 161                                       'enable-diff-updates' => true,
 
 162                                       'verbose' => $aResult['verbose']
 
 164         $cSetup->createFunctions();
 
 167     $sDatabaseDate = getDatabaseDate($oDB);
 
 168     if (!$sDatabaseDate) {
 
 169         fail('Cannot determine date of database.');
 
 171     $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3*60*60));
 
 173     // get the appropriate state id
 
 175     $oCMD = (new \Nominatim\Shell($sPyosmiumBin))
 
 176             ->addParams('--start-date', $sWindBack)
 
 177             ->addParams('--server', $sBaseURL);
 
 179     exec($oCMD->escapedCmd(), $aOutput, $iRet);
 
 180     if ($iRet != 0 || $aOutput[0] == 'None') {
 
 181         fail('Error running pyosmium tools');
 
 184     $oDB->exec('TRUNCATE import_status');
 
 185     $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
 
 186     $sSQL .= $sDatabaseDate."',".$aOutput[0].', true)';
 
 190     } catch (\Nominatim\DatabaseError $e) {
 
 191         fail('Could not enter sequence into database.');
 
 194     echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
 
 197 if ($aResult['check-for-updates']) {
 
 198     $aLastState = $oDB->getRow('SELECT sequence_id FROM import_status');
 
 200     if (!$aLastState['sequence_id']) {
 
 201         fail('Updates not set up. Please run ./utils/update.php --init-updates.');
 
 204     $oCmd = (new \Nominatim\Shell(CONST_BinDir.'/check_server_for_updates.py'))
 
 205             ->addParams($sBaseURL)
 
 206             ->addParams($aLastState['sequence_id']);
 
 207     $iRet = $oCmd->run();
 
 212 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
 
 213     // import diffs and files directly (e.g. from osmosis --rri)
 
 214     $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
 
 216     if (!file_exists($sNextFile)) {
 
 217         fail("Cannot open $sNextFile\n");
 
 221     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sNextFile);
 
 222     echo $oCMD->escapedCmd()."\n";
 
 223     $iRet = $oCMD->run();
 
 226         fail("Error from osm2pgsql, $iRet\n");
 
 229     // Don't update the import status - we don't know what this file contains
 
 232 if ($aResult['calculate-postcodes']) {
 
 233     info('Update postcodes centroids');
 
 234     $sTemplate = file_get_contents(CONST_DataDir.'/sql/update-postcodes.sql');
 
 235     runSQLScript($sTemplate, true, true);
 
 238 $sTemporaryFile = CONST_InstallDir.'/osmosischange.osc';
 
 240 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
 
 242 if (isset($aResult['import-node']) && $aResult['import-node']) {
 
 244         $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
 
 246         $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
 
 250 if (isset($aResult['import-way']) && $aResult['import-way']) {
 
 252         $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
 
 254         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');%3E;);out%20meta;';
 
 258 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
 
 260         $sContentURL = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
 
 262         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(rel(id:'.$aResult['import-relation'].');%3E;);out%20meta;';
 
 267     file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
 
 272     // import generated change file
 
 274     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sTemporaryFile);
 
 275     echo $oCMD->escapedCmd()."\n";
 
 277     $iRet = $oCMD->run();
 
 279         fail("osm2pgsql exited with error level $iRet\n");
 
 283 if ($aResult['recompute-word-counts']) {
 
 284     info('Recompute frequency of full-word search terms');
 
 285     $sTemplate = file_get_contents(CONST_DataDir.'/sql/words_from_search_name.sql');
 
 286     runSQLScript($sTemplate, true, true);
 
 289 if ($aResult['index']) {
 
 290     $oCmd = (clone $oIndexCmd)
 
 291             ->addParams('--minrank', $aResult['index-rank'], '-b');
 
 294     $oCmd = (clone $oIndexCmd)
 
 295             ->addParams('--minrank', $aResult['index-rank']);
 
 298     $oDB->exec('update import_status set indexed = true');
 
 301 if ($aResult['update-address-levels']) {
 
 302     $sAddressLevelConfig = getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json');
 
 303     echo 'Updating address levels from '.$sAddressLevelConfig.".\n";
 
 304     $oAlParser = new \Nominatim\Setup\AddressLevelParser($sAddressLevelConfig);
 
 305     $oAlParser->createTable($oDB, 'address_levels');
 
 308 if ($aResult['recompute-importance']) {
 
 309     echo "Updating importance values for database.\n";
 
 310     $oDB = new Nominatim\DB();
 
 313     $sSQL = 'ALTER TABLE placex DISABLE TRIGGER ALL;';
 
 314     $sSQL .= 'UPDATE placex SET (wikipedia, importance) =';
 
 315     $sSQL .= '   (SELECT wikipedia, importance';
 
 316     $sSQL .= '    FROM compute_importance(extratags, country_code, osm_type, osm_id));';
 
 317     $sSQL .= 'UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance';
 
 318     $sSQL .= ' FROM placex d';
 
 319     $sSQL .= ' WHERE s.place_id = d.linked_place_id and d.wikipedia is not null';
 
 320     $sSQL .= '       and (s.wikipedia is null or s.importance < d.importance);';
 
 321     $sSQL .= 'ALTER TABLE placex ENABLE TRIGGER ALL;';
 
 325 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
 
 327     if (strpos($sBaseURL, 'download.geofabrik.de') !== false && getSetting('REPLICATION_UPDATE_INTERVAL') < 86400) {
 
 328         fail('Error: Update interval too low for download.geofabrik.de. ' .
 
 329              "Please check install documentation (https://nominatim.org/release-docs/latest/admin/Import-and-Update#setting-up-the-update-process)\n");
 
 332     $sImportFile = CONST_InstallDir.'/osmosischange.osc';
 
 334     $oCMDDownload = (new \Nominatim\Shell($sPyosmiumBin))
 
 335                     ->addParams('--server', $sBaseURL)
 
 336                     ->addParams('--outfile', $sImportFile)
 
 337                     ->addParams('--size', getSetting('REPLICATION_MAX_DIFF'));
 
 339     $oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
 
 342         $fStartTime = time();
 
 343         $aLastState = $oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status');
 
 345         if (!$aLastState['sequence_id']) {
 
 346             echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
 
 350         echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
 
 352         $sBatchEnd = $aLastState['lastimportdate'];
 
 353         $iEndSequence = $aLastState['sequence_id'];
 
 355         if ($aLastState['indexed']) {
 
 356             // Sleep if the update interval has not yet been reached.
 
 357             $fNextUpdate = $aLastState['unix_ts'] + getSetting('REPLICATION_UPDATE_INTERVAL');
 
 358             if ($fNextUpdate > $fStartTime) {
 
 359                 $iSleepTime = $fNextUpdate - $fStartTime;
 
 360                 echo "Waiting for next update for $iSleepTime sec.";
 
 364             // Download the next batch of changes.
 
 366                 $fCMDStartTime = time();
 
 367                 $iNextSeq = (int) $aLastState['sequence_id'];
 
 370                 $oCMD = (clone $oCMDDownload)->addParams('--start-id', $iNextSeq);
 
 371                 echo $oCMD->escapedCmd()."\n";
 
 372                 if (file_exists($sImportFile)) {
 
 373                     unlink($sImportFile);
 
 375                 exec($oCMD->escapedCmd(), $aOutput, $iResult);
 
 378                     $sSleep = getSetting('REPLICATION_RECHECK_INTERVAL');
 
 379                     echo 'No new updates. Sleeping for '.$sSleep." sec.\n";
 
 381                 } elseif ($iResult != 0) {
 
 382                     echo 'ERROR: updates failed.';
 
 385                     $iEndSequence = (int)$aOutput[0];
 
 389             // get the newest object from the diff file
 
 392             $oCMD = new \Nominatim\Shell(CONST_BinDir.'/osm_file_date.py', $sImportFile);
 
 393             exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
 
 395                 echo "Diff file is empty. skipping import.\n";
 
 396                 if (!$aResult['import-osmosis-all']) {
 
 403                 fail('Error getting date from diff file.');
 
 405             $sBatchEnd = $sBatchEnd[0];
 
 408             $fCMDStartTime = time();
 
 411             echo $oCMDImport->escapedCmd()."\n";
 
 413             $iErrorLevel = $oCMDImport->run();
 
 415                 echo "Error executing osm2pgsql: $iErrorLevel\n";
 
 419             // write the update logs
 
 420             $iFileSize = filesize($sImportFile);
 
 421             $sSQL = 'INSERT INTO import_osmosis_log';
 
 422             $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
 
 423             $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
 
 424             $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
 
 425             $sSQL .= date('Y-m-d H:i:s')."','import')";
 
 430             $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
 
 433             echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
 
 437         if (!$aResult['no-index']) {
 
 438             $fCMDStartTime = time();
 
 440             $oThisIndexCmd = clone($oIndexCmd);
 
 441             $oThisIndexCmd->addParams('-b');
 
 442             echo $oThisIndexCmd->escapedCmd()."\n";
 
 443             $iErrorLevel = $oThisIndexCmd->run();
 
 445                 echo "Error: $iErrorLevel\n";
 
 449             $oThisIndexCmd = clone($oIndexCmd);
 
 450             echo $oThisIndexCmd->escapedCmd()."\n";
 
 451             $iErrorLevel = $oThisIndexCmd->run();
 
 453                 echo "Error: $iErrorLevel\n";
 
 457             $sSQL = 'INSERT INTO import_osmosis_log';
 
 458             $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
 
 459             $sSQL .= " values ('$sBatchEnd',$iEndSequence,NULL,'";
 
 460             $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
 
 461             $sSQL .= date('Y-m-d H:i:s')."','index')";
 
 464             echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
 
 466             $sSQL = 'update import_status set indexed = true';
 
 469             if ($aResult['import-osmosis-all']) {
 
 470                 echo "Error: --no-index cannot be used with continuous imports (--import-osmosis-all).\n";
 
 475         $fDuration = time() - $fStartTime;
 
 476         echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60, 2)." minutes\n";
 
 477         if (!$aResult['import-osmosis-all']) exit(0);