4 require_once dirname(dirname(__FILE__)) . '/settings/settings.php';
5 require_once CONST_BasePath . '/lib/init-cmd.php';
6 require_once CONST_BasePath . '/lib/setup_functions.php';
7 require_once CONST_BasePath . '/lib/SetupClass.php';
8 ini_set('memory_limit', '800M');
10 use Nominatim\Setup\SetupFunctions as SetupFunctions;
12 $aCMDOptions = createUpdateArgvArray();
14 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
16 if (!isset($aResult['index-instances'])) {
17 $aResult['index-instances'] = 1;
20 if (!isset($aResult['index-rank'])) {
21 $aResult['index-rank'] = 0;
24 date_default_timezone_set('Etc/UTC');
28 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
29 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) {
30 $aDSNInfo['port'] = 5432;
33 // cache memory to be used by osm2pgsql, should not be more than the available memory
34 $iCacheMemory = (isset($aResult['osm2pgsql-cache']) ? $aResult['osm2pgsql-cache'] : 2000);
35 if ($iCacheMemory + 500 > getTotalMemoryMB()) {
36 $iCacheMemory = getCacheMemoryMB();
37 echo "WARNING: resetting cache memory to $iCacheMemory\n";
39 $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary . ' -klas --number-processes 1 -C ' . $iCacheMemory . ' -O gazetteer -d ' . $aDSNInfo['database'] . ' -P ' . $aDSNInfo['port'];
40 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
41 $sOsm2pgsqlCmd .= ' -U ' . $aDSNInfo['username'];
43 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
44 $sOsm2pgsqlCmd .= ' -H ' . $aDSNInfo['hostspec'];
47 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
48 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
51 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
52 $sOsm2pgsqlCmd .= ' --flat-nodes ' . CONST_Osm2pgsql_Flatnode_File;
55 if ($aResult['init-updates']) {
56 // sanity check that the replication URL is correct
57 $sBaseState = file_get_contents(CONST_Replication_Url . '/state.txt');
58 if ($sBaseState === false) {
59 echo "\nCannot find state.txt file at the configured replication URL.\n";
60 echo "Does the URL point to a directory containing OSM update data?\n\n";
61 fail('replication URL not reachable.');
63 // sanity check for pyosmium-get-changes
64 if (!CONST_Pyosmium_Binary) {
65 echo "\nCONST_Pyosmium_Binary not configured.\n";
66 echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
67 echo "in your local settings file.\n\n";
68 fail('CONST_Pyosmium_Binary not configured');
71 $sCmd = CONST_Pyosmium_Binary . ' --help';
72 exec($sCmd, $aOutput, $iRet);
74 echo "Cannot execute pyosmium-get-changes.\n";
75 echo "Make sure you have pyosmium installed correctly\n";
76 echo "and have set up CONST_Pyosmium_Binary to point to pyosmium-get-changes.\n";
77 fail('pyosmium-get-changes not found or not usable');
80 if (!$aResult['no-update-functions']) {
81 // instatiate setupClass to use the function therein
82 // instantiate Setup class
83 $cSetup = new SetupFunctions($aResult);
84 $cSetup->createFunctions();
87 $sDatabaseDate = getDatabaseDate($oDB);
88 if ($sDatabaseDate === false) {
89 fail('Cannot determine date of database.');
91 $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3 * 60 * 60));
93 // get the appropriate state id
95 $sCmd = CONST_Pyosmium_Binary . ' -D ' . $sWindBack . ' --server ' . CONST_Replication_Url;
96 exec($sCmd, $aOutput, $iRet);
97 if ($iRet != 0 || $aOutput[0] == 'None') {
98 fail('Error running pyosmium tools');
101 pg_query($oDB->connection, 'TRUNCATE import_status');
102 $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
103 $sSQL .= $sDatabaseDate . "'," . $aOutput[0] . ', true)';
104 if (!pg_query($oDB->connection, $sSQL)) {
105 fail('Could not enter sequence into database.');
108 echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
111 if ($aResult['check-for-updates']) {
112 $aLastState = chksql($oDB->getRow('SELECT sequence_id FROM import_status'));
114 if (!$aLastState['sequence_id']) {
115 fail('Updates not set up. Please run ./utils/update.php --init-updates.');
118 system(CONST_BasePath . '/utils/check_server_for_updates.py ' . CONST_Replication_Url . ' ' . $aLastState['sequence_id'], $iRet);
122 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
123 // import diffs and files directly (e.g. from osmosis --rri)
124 $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
126 if (!file_exists($sNextFile)) {
127 fail("Cannot open $sNextFile\n");
131 $sCMD = $sOsm2pgsqlCmd . ' ' . $sNextFile;
133 $iErrorLevel = runWithEnv($sCMD, $aProcEnv);
136 fail("Error from osm2pgsql, $iErrorLevel\n");
139 // Don't update the import status - we don't know what this file contains
142 if ($aResult['calculate-postcodes']) {
143 info('Update postcodes centroids');
144 $sTemplate = file_get_contents(CONST_BasePath . '/sql/update-postcodes.sql');
145 runSQLScript($sTemplate, true, true);
148 $sTemporaryFile = CONST_BasePath . '/data/osmosischange.osc';
150 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
152 if (isset($aResult['import-node']) && $aResult['import-node']) {
154 $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/' . $aResult['import-node'];
156 $sContentURL = 'https://overpass-api.de/api/interpreter?data=node(' . $aResult['import-node'] . ');out%20meta;';
160 if (isset($aResult['import-way']) && $aResult['import-way']) {
162 $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/' . $aResult['import-way'] . '/full';
164 $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way(' . $aResult['import-way'] . ');node(w););out%20meta;';
168 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
170 $sContentURLsModifyXMLstr = 'https://www.openstreetmap.org/api/0.6/relation/' . $aResult['import-relation'] . '/full';
172 $sContentURL = 'https://overpass-api.de/api/interpreter?data=((rel(' . $aResult['import-relation'] . ');way(r);node(w));node(r));out%20meta;';
177 file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
182 // import generated change file
183 $sCMD = $sOsm2pgsqlCmd . ' ' . $sTemporaryFile;
185 $iErrorLevel = runWithEnv($sCMD, $aProcEnv);
187 fail("osm2pgsql exited with error level $iErrorLevel\n");
191 if ($aResult['deduplicate']) {
194 if (getPostgresVersion($oDB) < 9.3) {
195 fail('ERROR: deduplicate is only currently supported in postgresql 9.3');
198 $sSQL = 'select partition from country_name order by country_code';
199 $aPartitions = chksql($oDB->getCol($sSQL));
202 // we don't care about empty search_name_* partitions, they can't contain mentions of duplicates
203 foreach ($aPartitions as $i => $sPartition) {
204 $sSQL = 'select count(*) from search_name_' . $sPartition;
205 $nEntries = chksql($oDB->getOne($sSQL));
206 if ($nEntries == 0) {
207 unset($aPartitions[$i]);
211 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' '";
212 $sSQL .= ' and class is null and type is null and country_code is null';
213 $sSQL .= ' group by word_token having count(*) > 1 order by word_token';
214 $aDuplicateTokens = chksql($oDB->getAll($sSQL));
215 foreach ($aDuplicateTokens as $aToken) {
216 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') {
220 echo 'Deduping ' . $aToken['word_token'] . "\n";
221 $sSQL = 'select word_id,';
222 $sSQL .= ' (select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num';
223 $sSQL .= " from word where word_token = '" . $aToken['word_token'];
224 $sSQL .= "' and class is null and type is null and country_code is null order by num desc";
225 $aTokenSet = chksql($oDB->getAll($sSQL));
227 $aKeep = array_shift($aTokenSet);
228 $iKeepID = $aKeep['word_id'];
230 foreach ($aTokenSet as $aRemove) {
231 $sSQL = 'update search_name set';
232 $sSQL .= ' name_vector = array_replace(name_vector,' . $aRemove['word_id'] . ',' . $iKeepID . '),';
233 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,' . $aRemove['word_id'] . ',' . $iKeepID . ')';
234 $sSQL .= ' where name_vector @> ARRAY[' . $aRemove['word_id'] . ']';
235 chksql($oDB->query($sSQL));
237 $sSQL = 'update search_name set';
238 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,' . $aRemove['word_id'] . ',' . $iKeepID . ')';
239 $sSQL .= ' where nameaddress_vector @> ARRAY[' . $aRemove['word_id'] . ']';
240 chksql($oDB->query($sSQL));
242 $sSQL = 'update location_area_country set';
243 $sSQL .= ' keywords = array_replace(keywords,' . $aRemove['word_id'] . ',' . $iKeepID . ')';
244 $sSQL .= ' where keywords @> ARRAY[' . $aRemove['word_id'] . ']';
245 chksql($oDB->query($sSQL));
247 foreach ($aPartitions as $sPartition) {
248 $sSQL = 'update search_name_' . $sPartition . ' set';
249 $sSQL .= ' name_vector = array_replace(name_vector,' . $aRemove['word_id'] . ',' . $iKeepID . ')';
250 $sSQL .= ' where name_vector @> ARRAY[' . $aRemove['word_id'] . ']';
251 chksql($oDB->query($sSQL));
253 $sSQL = 'update location_area_country set';
254 $sSQL .= ' keywords = array_replace(keywords,' . $aRemove['word_id'] . ',' . $iKeepID . ')';
255 $sSQL .= ' where keywords @> ARRAY[' . $aRemove['word_id'] . ']';
256 chksql($oDB->query($sSQL));
259 $sSQL = 'delete from word where word_id = ' . $aRemove['word_id'];
260 chksql($oDB->query($sSQL));
265 if ($aResult['recompute-word-counts']) {
266 info('Recompute frequency of full-word search terms');
267 $sTemplate = file_get_contents(CONST_BasePath . '/sql/words_from_search_name.sql');
268 runSQLScript($sTemplate, true, true);
271 if ($aResult['index']) {
272 $sCmd = CONST_InstallPath . '/nominatim/nominatim -i -d ' . $aDSNInfo['database'] . ' -P ' . $aDSNInfo['port'] . ' -t ' . $aResult['index-instances'] . ' -r ' . $aResult['index-rank'];
273 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
274 $sCmd .= ' -H ' . $aDSNInfo['hostspec'];
276 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
277 $sCmd .= ' -U ' . $aDSNInfo['username'];
280 runWithEnv($sCmd, $aProcEnv);
283 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
285 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
286 fail('Error: Update interval too low for download.geofabrik.de. ' .
287 "Please check install documentation (http://nominatim.org/release-docs/latest/Import-and-Update#setting-up-the-update-process)\n");
290 $sImportFile = CONST_InstallPath . '/osmosischange.osc';
291 $sCMDDownload = CONST_Pyosmium_Binary . ' --server ' . CONST_Replication_Url . ' -o ' . $sImportFile . ' -s ' . CONST_Replication_Max_Diff_size;
292 $sCMDImport = $sOsm2pgsqlCmd . ' ' . $sImportFile;
293 $sCMDIndex = CONST_InstallPath . '/nominatim/nominatim -i -d ' . $aDSNInfo['database'] . ' -P ' . $aDSNInfo['port'] . ' -t ' . $aResult['index-instances'];
294 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
295 $sCMDIndex .= ' -H ' . $aDSNInfo['hostspec'];
297 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
298 $sCMDIndex .= ' -U ' . $aDSNInfo['username'];
302 $fStartTime = time();
303 $aLastState = chksql($oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status'));
305 if (!$aLastState['sequence_id']) {
306 echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
310 echo 'Currently at sequence ' . $aLastState['sequence_id'] . ' (' . $aLastState['lastimportdate'] . ') - ' . $aLastState['indexed'] . " indexed\n";
312 $sBatchEnd = $aLastState['lastimportdate'];
313 $iEndSequence = $aLastState['sequence_id'];
315 if ($aLastState['indexed'] == 't') {
316 // Sleep if the update interval has not yet been reached.
317 $fNextUpdate = $aLastState['unix_ts'] + CONST_Replication_Update_Interval;
318 if ($fNextUpdate > $fStartTime) {
319 $iSleepTime = $fNextUpdate - $fStartTime;
320 echo "Waiting for next update for $iSleepTime sec.";
324 // Download the next batch of changes.
326 $fCMDStartTime = time();
327 $iNextSeq = (int) $aLastState['sequence_id'];
329 echo "$sCMDDownload -I $iNextSeq\n";
330 if (file_exists($sImportFile)) {
331 unlink($sImportFile);
333 exec($sCMDDownload . ' -I ' . $iNextSeq, $aOutput, $iResult);
336 echo 'No new updates. Sleeping for ' . CONST_Replication_Recheck_Interval . " sec.\n";
337 sleep(CONST_Replication_Recheck_Interval);
338 } elseif ($iResult != 0) {
339 echo 'ERROR: updates failed.';
342 $iEndSequence = (int) $aOutput[0];
346 // get the newest object from the diff file
349 exec(CONST_BasePath . '/utils/osm_file_date.py ' . $sImportFile, $sBatchEnd, $iRet);
351 echo "Diff file is empty. skipping import.\n";
352 if (!$aResult['import-osmosis-all']) {
359 fail('Error getting date from diff file.');
361 $sBatchEnd = $sBatchEnd[0];
364 $fCMDStartTime = time();
365 echo $sCMDImport . "\n";
367 $iErrorLevel = runWithEnv($sCMDImport, $aProcEnv);
369 echo "Error executing osm2pgsql: $iErrorLevel\n";
373 // write the update logs
374 $iFileSize = filesize($sImportFile);
375 $sSQL = 'INSERT INTO import_osmosis_log';
376 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
377 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
378 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime) . "','";
379 $sSQL .= date('Y-m-d H:i:s') . "','import')";
381 chksql($oDB->query($sSQL));
384 $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
386 chksql($oDB->query($sSQL));
387 echo date('Y-m-d H:i:s') . " Completed download step for $sBatchEnd in " . round((time() - $fCMDStartTime) / 60, 2) . " minutes\n";
391 if (!$aResult['no-index']) {
392 $sThisIndexCmd = $sCMDIndex;
393 $fCMDStartTime = time();
395 echo "$sThisIndexCmd\n";
396 $iErrorLevel = runWithEnv($sThisIndexCmd, $aProcEnv);
398 echo "Error: $iErrorLevel\n";
402 $sSQL = 'INSERT INTO import_osmosis_log';
403 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
404 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
405 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime) . "','";
406 $sSQL .= date('Y-m-d H:i:s') . "','index')";
409 echo date('Y-m-d H:i:s') . " Completed index step for $sBatchEnd in " . round((time() - $fCMDStartTime) / 60, 2) . " minutes\n";
411 $sSQL = 'update import_status set indexed = true';
415 $fDuration = time() - $fStartTime;
416 echo date('Y-m-d H:i:s') . " Completed all for $sBatchEnd in " . round($fDuration / 60, 2) . " minutes\n";
417 if (!$aResult['import-osmosis-all']) {