]> git.openstreetmap.org Git - nominatim.git/blob - lib/admin/update.php
04eb7019acd2b8ecda7aeff06f68b911f440f237
[nominatim.git] / lib / admin / update.php
1 <?php
2 @define('CONST_LibDir', dirname(dirname(__FILE__)));
3
4 require_once(CONST_LibDir.'/init-cmd.php');
5 require_once(CONST_LibDir.'/setup_functions.php');
6 require_once(CONST_LibDir.'/setup/SetupClass.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 $oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
107 if ($aResult['quiet']) {
108     $oNominatimCmd->addParams('--quiet');
109 }
110 if ($aResult['verbose']) {
111     $oNominatimCmd->addParams('--verbose');
112 }
113
114 $sPyosmiumBin = getSetting('PYOSMIUM_BINARY');
115 $sBaseURL = getSetting('REPLICATION_URL');
116
117
118 if ($aResult['init-updates']) {
119     $oCmd = (clone($oNominatimCmd))->addParams('replication', '--init');
120
121     if ($aResult['no-update-functions']) {
122         $oCmd->addParams('--no-update-functions');
123     }
124
125     $oCmd->run();
126 }
127
128 if ($aResult['check-for-updates']) {
129     $aLastState = $oDB->getRow('SELECT sequence_id FROM import_status');
130
131     if (!$aLastState['sequence_id']) {
132         fail('Updates not set up. Please run ./utils/update.php --init-updates.');
133     }
134
135     $oCmd = (new \Nominatim\Shell(CONST_BinDir.'/check_server_for_updates.py'))
136             ->addParams($sBaseURL)
137             ->addParams($aLastState['sequence_id']);
138     $iRet = $oCmd->run();
139
140     exit($iRet);
141 }
142
143 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
144     // import diffs and files directly (e.g. from osmosis --rri)
145     $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
146
147     if (!file_exists($sNextFile)) {
148         fail("Cannot open $sNextFile\n");
149     }
150
151     // Import the file
152     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sNextFile);
153     echo $oCMD->escapedCmd()."\n";
154     $iRet = $oCMD->run();
155
156     if ($iRet) {
157         fail("Error from osm2pgsql, $iRet\n");
158     }
159
160     // Don't update the import status - we don't know what this file contains
161 }
162
163 if ($aResult['calculate-postcodes']) {
164     (clone($oNominatimCmd))->addParams('refresh', '--postcodes')->run();
165 }
166
167 $sTemporaryFile = CONST_InstallDir.'/osmosischange.osc';
168 $bHaveDiff = false;
169 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
170 $sContentURL = '';
171 if (isset($aResult['import-node']) && $aResult['import-node']) {
172     if ($bUseOSMApi) {
173         $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
174     } else {
175         $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
176     }
177 }
178
179 if (isset($aResult['import-way']) && $aResult['import-way']) {
180     if ($bUseOSMApi) {
181         $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
182     } else {
183         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');%3E;);out%20meta;';
184     }
185 }
186
187 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
188     if ($bUseOSMApi) {
189         $sContentURL = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
190     } else {
191         $sContentURL = 'https://overpass-api.de/api/interpreter?data=(rel(id:'.$aResult['import-relation'].');%3E;);out%20meta;';
192     }
193 }
194
195 if ($sContentURL) {
196     file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
197     $bHaveDiff = true;
198 }
199
200 if ($bHaveDiff) {
201     // import generated change file
202
203     $oCMD = (clone $oOsm2pgsqlCmd)->addParams($sTemporaryFile);
204     echo $oCMD->escapedCmd()."\n";
205
206     $iRet = $oCMD->run();
207     if ($iRet) {
208         fail("osm2pgsql exited with error level $iRet\n");
209     }
210 }
211
212 if ($aResult['recompute-word-counts']) {
213     (clone($oNominatimCmd))->addParams('refresh', '--word-counts')->run();
214 }
215
216 if ($aResult['index']) {
217     (clone $oNominatimCmd)->addParams('index', '--minrank', $aResult['index-rank'])->run();
218 }
219
220 if ($aResult['update-address-levels']) {
221     (clone($oNominatimCmd))->addParams('refresh', '--address-levels')->run();
222 }
223
224 if ($aResult['recompute-importance']) {
225     echo "Updating importance values for database.\n";
226     $oDB = new Nominatim\DB();
227     $oDB->connect();
228
229     $sSQL = 'ALTER TABLE placex DISABLE TRIGGER ALL;';
230     $sSQL .= 'UPDATE placex SET (wikipedia, importance) =';
231     $sSQL .= '   (SELECT wikipedia, importance';
232     $sSQL .= '    FROM compute_importance(extratags, country_code, osm_type, osm_id));';
233     $sSQL .= 'UPDATE placex s SET wikipedia = d.wikipedia, importance = d.importance';
234     $sSQL .= ' FROM placex d';
235     $sSQL .= ' WHERE s.place_id = d.linked_place_id and d.wikipedia is not null';
236     $sSQL .= '       and (s.wikipedia is null or s.importance < d.importance);';
237     $sSQL .= 'ALTER TABLE placex ENABLE TRIGGER ALL;';
238     $oDB->exec($sSQL);
239 }
240
241 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
242     //
243     if (strpos($sBaseURL, 'download.geofabrik.de') !== false && getSetting('REPLICATION_UPDATE_INTERVAL') < 86400) {
244         fail('Error: Update interval too low for download.geofabrik.de. ' .
245              "Please check install documentation (https://nominatim.org/release-docs/latest/admin/Import-and-Update#setting-up-the-update-process)\n");
246     }
247
248     $sImportFile = CONST_InstallDir.'/osmosischange.osc';
249
250     $oCMDDownload = (new \Nominatim\Shell($sPyosmiumBin))
251                     ->addParams('--server', $sBaseURL)
252                     ->addParams('--outfile', $sImportFile)
253                     ->addParams('--size', getSetting('REPLICATION_MAX_DIFF'));
254
255     $oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
256
257     while (true) {
258         $fStartTime = time();
259         $aLastState = $oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status');
260
261         if (!$aLastState['sequence_id']) {
262             echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
263             exit(1);
264         }
265
266         echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
267
268         $sBatchEnd = $aLastState['lastimportdate'];
269         $iEndSequence = $aLastState['sequence_id'];
270
271         if ($aLastState['indexed']) {
272             // Sleep if the update interval has not yet been reached.
273             $fNextUpdate = $aLastState['unix_ts'] + getSetting('REPLICATION_UPDATE_INTERVAL');
274             if ($fNextUpdate > $fStartTime) {
275                 $iSleepTime = $fNextUpdate - $fStartTime;
276                 echo "Waiting for next update for $iSleepTime sec.";
277                 sleep($iSleepTime);
278             }
279
280             // Download the next batch of changes.
281             do {
282                 $fCMDStartTime = time();
283                 $iNextSeq = (int) $aLastState['sequence_id'];
284                 unset($aOutput);
285
286                 $oCMD = (clone $oCMDDownload)->addParams('--start-id', $iNextSeq);
287                 echo $oCMD->escapedCmd()."\n";
288                 if (file_exists($sImportFile)) {
289                     unlink($sImportFile);
290                 }
291                 exec($oCMD->escapedCmd(), $aOutput, $iResult);
292
293                 if ($iResult == 3) {
294                     $sSleep = getSetting('REPLICATION_RECHECK_INTERVAL');
295                     echo 'No new updates. Sleeping for '.$sSleep." sec.\n";
296                     sleep($sSleep);
297                 } elseif ($iResult != 0) {
298                     echo 'ERROR: updates failed.';
299                     exit($iResult);
300                 } else {
301                     $iEndSequence = (int)$aOutput[0];
302                 }
303             } while ($iResult);
304
305             // get the newest object from the diff file
306             $sBatchEnd = 0;
307             $iRet = 0;
308             $oCMD = new \Nominatim\Shell(CONST_BinDir.'/osm_file_date.py', $sImportFile);
309             exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
310             if ($iRet == 5) {
311                 echo "Diff file is empty. skipping import.\n";
312                 if (!$aResult['import-osmosis-all']) {
313                     exit(0);
314                 } else {
315                     continue;
316                 }
317             }
318             if ($iRet != 0) {
319                 fail('Error getting date from diff file.');
320             }
321             $sBatchEnd = $sBatchEnd[0];
322
323             // Import the file
324             $fCMDStartTime = time();
325
326
327             echo $oCMDImport->escapedCmd()."\n";
328             unset($sJunk);
329             $iErrorLevel = $oCMDImport->run();
330             if ($iErrorLevel) {
331                 echo "Error executing osm2pgsql: $iErrorLevel\n";
332                 exit($iErrorLevel);
333             }
334
335             // write the update logs
336             $iFileSize = filesize($sImportFile);
337             $sSQL = 'INSERT INTO import_osmosis_log';
338             $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
339             $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
340             $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
341             $sSQL .= date('Y-m-d H:i:s')."','import')";
342             var_Dump($sSQL);
343             $oDB->exec($sSQL);
344
345             // update the status
346             $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
347             var_Dump($sSQL);
348             $oDB->exec($sSQL);
349             echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
350         }
351
352         // Index file
353         if (!$aResult['no-index']) {
354             $fCMDStartTime = time();
355
356             $oThisIndexCmd = clone($oNominatimCmd);
357             $oThisIndexCmd->addParams('index');
358             echo $oThisIndexCmd->escapedCmd()."\n";
359             $iErrorLevel = $oThisIndexCmd->run();
360             if ($iErrorLevel) {
361                 echo "Error: $iErrorLevel\n";
362                 exit($iErrorLevel);
363             }
364
365             $sSQL = 'INSERT INTO import_osmosis_log';
366             $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
367             $sSQL .= " values ('$sBatchEnd',$iEndSequence,NULL,'";
368             $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
369             $sSQL .= date('Y-m-d H:i:s')."','index')";
370             var_Dump($sSQL);
371             $oDB->exec($sSQL);
372             echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
373         } else {
374             if ($aResult['import-osmosis-all']) {
375                 echo "Error: --no-index cannot be used with continuous imports (--import-osmosis-all).\n";
376                 exit(1);
377             }
378         }
379
380         $fDuration = time() - $fStartTime;
381         echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60, 2)." minutes\n";
382         if (!$aResult['import-osmosis-all']) exit(0);
383     }
384 }