]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
931ca179819cd9b8577062dca3ac9785069c0c67
[nominatim.git] / utils / update.php
1 <?php
2
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');
7
8 ini_set('memory_limit', '800M');
9
10 use Nominatim\Setup\SetupFunctions as SetupFunctions;
11
12 // (long-opt, short-opt, min-occurs, max-occurs, num-arguments, num-arguments, type, help)
13 $aCMDOptions
14 = array(
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'),
19
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'),
26
27    array('calculate-postcodes', '', 0, 1, 0, 0, 'bool', 'Update postcode centroid table'),
28
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'),
32
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'),
37
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)'),
41
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'),
45
46    array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
47   );
48
49 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
50
51 loadSettings($aCMDResult['project-dir'] ?? getcwd());
52 setupHTTPProxy();
53
54 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
55 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
56
57 date_default_timezone_set('Etc/UTC');
58
59 $oDB = new Nominatim\DB();
60 $oDB->connect();
61 $fPostgresVersion = $oDB->getPostgresVersion();
62
63 $aDSNInfo = Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
64 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
65
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";
71 }
72
73 $oOsm2pgsqlCmd = (new \Nominatim\Shell(getOsm2pgsqlBinary()))
74                  ->addParams('--hstore')
75                  ->addParams('--latlong')
76                  ->addParams('--append')
77                  ->addParams('--slim')
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']);
86
87 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
88     $oOsm2pgsqlCmd->addParams('--host', $aDSNInfo['hostspec']);
89 }
90 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
91     $oOsm2pgsqlCmd->addParams('--user', $aDSNInfo['username']);
92 }
93 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
94     $oOsm2pgsqlCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
95 }
96 if (getSetting('FLATNODE_FILE')) {
97     $oOsm2pgsqlCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
98 }
99 if ($fPostgresVersion >= 11.0) {
100     $oOsm2pgsqlCmd->addEnvPair(
101         'PGOPTIONS',
102         '-c jit=off -c max_parallel_workers_per_gather=0'
103     );
104 }
105
106
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');
113 }
114 if ($aResult['verbose']) {
115     $oIndexCmd->addParams('--verbose');
116 }
117 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
118     $oIndexCmd->addParams('--host', $aDSNInfo['hostspec']);
119 }
120 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
121     $oIndexCmd->addParams('--username', $aDSNInfo['username']);
122 }
123 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
124     $oIndexCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
125 }
126
127 $sPyosmiumBin = getSetting('PYOSMIUM_BINARY');
128 $sBaseURL = getSetting('REPLICATION_URL');
129
130
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.');
138     }
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');
145     }
146
147     $aOutput = 0;
148     $oCMD = new \Nominatim\Shell($sPyosmiumBin, '--help');
149     exec($oCMD->escapedCmd(), $aOutput, $iRet);
150
151     if ($iRet != 0) {
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');
156     }
157
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']
163                                      ));
164         $cSetup->createFunctions();
165     }
166
167     $sDatabaseDate = getDatabaseDate($oDB);
168     if (!$sDatabaseDate) {
169         fail('Cannot determine date of database.');
170     }
171     $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3*60*60));
172
173     // get the appropriate state id
174     $aOutput = 0;
175     $oCMD = (new \Nominatim\Shell($sPyosmiumBin))
176             ->addParams('--start-date', $sWindBack)
177             ->addParams('--server', $sBaseURL);
178
179     exec($oCMD->escapedCmd(), $aOutput, $iRet);
180     if ($iRet != 0 || $aOutput[0] == 'None') {
181         fail('Error running pyosmium tools');
182     }
183
184     $oDB->exec('TRUNCATE import_status');
185     $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
186     $sSQL .= $sDatabaseDate."',".$aOutput[0].', true)';
187
188     try {
189         $oDB->exec($sSQL);
190     } catch (\Nominatim\DatabaseError $e) {
191         fail('Could not enter sequence into database.');
192     }
193
194     echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
195 }
196
197 if ($aResult['check-for-updates']) {
198     $aLastState = $oDB->getRow('SELECT sequence_id FROM import_status');
199
200     if (!$aLastState['sequence_id']) {
201         fail('Updates not set up. Please run ./utils/update.php --init-updates.');
202     }
203
204     $oCmd = (new \Nominatim\Shell(CONST_BinDir.'/check_server_for_updates.py'))
205             ->addParams($sBaseURL)
206             ->addParams($aLastState['sequence_id']);
207     $iRet = $oCmd->run();
208
209     exit($iRet);
210 }
211
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'];
215
216     if (!file_exists($sNextFile)) {
217         fail("Cannot open $sNextFile\n");
218     }
219
220     // Import the file
221     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sNextFile);
222     echo $oCMD->escapedCmd()."\n";
223     $iRet = $oCMD->run();
224
225     if ($iRet) {
226         fail("Error from osm2pgsql, $iRet\n");
227     }
228
229     // Don't update the import status - we don't know what this file contains
230 }
231
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);
236 }
237
238 $sTemporaryFile = CONST_InstallDir.'/osmosischange.osc';
239 $bHaveDiff = false;
240 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
241 $sContentURL = '';
242 if (isset($aResult['import-node']) && $aResult['import-node']) {
243     if ($bUseOSMApi) {
244         $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
245     } else {
246         $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
247     }
248 }
249
250 if (isset($aResult['import-way']) && $aResult['import-way']) {
251     if ($bUseOSMApi) {
252         $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
253     } else {
254         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');%3E;);out%20meta;';
255     }
256 }
257
258 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
259     if ($bUseOSMApi) {
260         $sContentURL = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
261     } else {
262         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(rel(id:'.$aResult['import-relation'].');%3E;);out%20meta;';
263     }
264 }
265
266 if ($sContentURL) {
267     file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
268     $bHaveDiff = true;
269 }
270
271 if ($bHaveDiff) {
272     // import generated change file
273
274     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sTemporaryFile);
275     echo $oCMD->escapedCmd()."\n";
276
277     $iRet = $oCMD->run();
278     if ($iRet) {
279         fail("osm2pgsql exited with error level $iRet\n");
280     }
281 }
282
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);
287 }
288
289 if ($aResult['index']) {
290     $oCmd = (clone $oIndexCmd)
291             ->addParams('--minrank', $aResult['index-rank'], '-b');
292     $oCmd->run();
293
294     $oCmd = (clone $oIndexCmd)
295             ->addParams('--minrank', $aResult['index-rank']);
296     $oCmd->run();
297
298     $oDB->exec('update import_status set indexed = true');
299 }
300
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');
306 }
307
308 if ($aResult['recompute-importance']) {
309     echo "Updating importance values for database.\n";
310     $oDB = new Nominatim\DB();
311     $oDB->connect();
312
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;';
322     $oDB->exec($sSQL);
323 }
324
325 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
326     //
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");
330     }
331
332     $sImportFile = CONST_InstallDir.'/osmosischange.osc';
333
334     $oCMDDownload = (new \Nominatim\Shell($sPyosmiumBin))
335                     ->addParams('--server', $sBaseURL)
336                     ->addParams('--outfile', $sImportFile)
337                     ->addParams('--size', getSetting('REPLICATION_MAX_DIFF'));
338
339     $oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
340
341     while (true) {
342         $fStartTime = time();
343         $aLastState = $oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status');
344
345         if (!$aLastState['sequence_id']) {
346             echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
347             exit(1);
348         }
349
350         echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
351
352         $sBatchEnd = $aLastState['lastimportdate'];
353         $iEndSequence = $aLastState['sequence_id'];
354
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.";
361                 sleep($iSleepTime);
362             }
363
364             // Download the next batch of changes.
365             do {
366                 $fCMDStartTime = time();
367                 $iNextSeq = (int) $aLastState['sequence_id'];
368                 unset($aOutput);
369
370                 $oCMD = (clone $oCMDDownload)->addParams('--start-id', $iNextSeq);
371                 echo $oCMD->escapedCmd()."\n";
372                 if (file_exists($sImportFile)) {
373                     unlink($sImportFile);
374                 }
375                 exec($oCMD->escapedCmd(), $aOutput, $iResult);
376
377                 if ($iResult == 3) {
378                     $sSleep = getSetting('REPLICATION_RECHECK_INTERVAL');
379                     echo 'No new updates. Sleeping for '.$sSleep." sec.\n";
380                     sleep($sSleep);
381                 } elseif ($iResult != 0) {
382                     echo 'ERROR: updates failed.';
383                     exit($iResult);
384                 } else {
385                     $iEndSequence = (int)$aOutput[0];
386                 }
387             } while ($iResult);
388
389             // get the newest object from the diff file
390             $sBatchEnd = 0;
391             $iRet = 0;
392             $oCMD = new \Nominatim\Shell(CONST_BinDir.'/osm_file_date.py', $sImportFile);
393             exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
394             if ($iRet == 5) {
395                 echo "Diff file is empty. skipping import.\n";
396                 if (!$aResult['import-osmosis-all']) {
397                     exit(0);
398                 } else {
399                     continue;
400                 }
401             }
402             if ($iRet != 0) {
403                 fail('Error getting date from diff file.');
404             }
405             $sBatchEnd = $sBatchEnd[0];
406
407             // Import the file
408             $fCMDStartTime = time();
409
410
411             echo $oCMDImport->escapedCmd()."\n";
412             unset($sJunk);
413             $iErrorLevel = $oCMDImport->run();
414             if ($iErrorLevel) {
415                 echo "Error executing osm2pgsql: $iErrorLevel\n";
416                 exit($iErrorLevel);
417             }
418
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')";
426             var_Dump($sSQL);
427             $oDB->exec($sSQL);
428
429             // update the status
430             $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
431             var_Dump($sSQL);
432             $oDB->exec($sSQL);
433             echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
434         }
435
436         // Index file
437         if (!$aResult['no-index']) {
438             $fCMDStartTime = time();
439
440             $oThisIndexCmd = clone($oIndexCmd);
441             $oThisIndexCmd->addParams('-b');
442             echo $oThisIndexCmd->escapedCmd()."\n";
443             $iErrorLevel = $oThisIndexCmd->run();
444             if ($iErrorLevel) {
445                 echo "Error: $iErrorLevel\n";
446                 exit($iErrorLevel);
447             }
448
449             $oThisIndexCmd = clone($oIndexCmd);
450             echo $oThisIndexCmd->escapedCmd()."\n";
451             $iErrorLevel = $oThisIndexCmd->run();
452             if ($iErrorLevel) {
453                 echo "Error: $iErrorLevel\n";
454                 exit($iErrorLevel);
455             }
456
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')";
462             var_Dump($sSQL);
463             $oDB->exec($sSQL);
464             echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
465
466             $sSQL = 'update import_status set indexed = true';
467             $oDB->exec($sSQL);
468         } else {
469             if ($aResult['import-osmosis-all']) {
470                 echo "Error: --no-index cannot be used with continuous imports (--import-osmosis-all).\n";
471                 exit(1);
472             }
473         }
474
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);
478     }
479 }