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/classes/SetupClass.php');
9 ini_set('memory_limit', '800M');
11 use Nominatim\Setup\SetupFunctions as SetupFunctions;
13 $aCMDOptions = createUpdateArgvArray();
14 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
16 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
17 if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
19 date_default_timezone_set('Etc/UTC');
23 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
24 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
26 // cache memory to be used by osm2pgsql, should not be more than the available memory
27 $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
28 if ($iCacheMemory + 500 > getTotalMemoryMB()) {
29 $iCacheMemory = getCacheMemoryMB();
30 echo "WARNING: resetting cache memory to $iCacheMemory\n";
32 $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas --number-processes 1 -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
33 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
34 $sOsm2pgsqlCmd .= ' -U ' . $aDSNInfo['username'];
36 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
37 $sOsm2pgsqlCmd .= ' -H ' . $aDSNInfo['hostspec'];
40 if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
41 $aProcEnv = array_merge(array('PGPASSWORD' => $aDSNInfo['password']), $_ENV);
44 if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
45 $sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
48 if ($aResult['init-updates']) {
49 // sanity check that the replication URL is correct
50 $sBaseState = file_get_contents(CONST_Replication_Url.'/state.txt');
51 if ($sBaseState === false) {
52 echo "\nCannot find state.txt file at the configured replication URL.\n";
53 echo "Does the URL point to a directory containing OSM update data?\n\n";
54 fail('replication URL not reachable.');
56 // sanity check for pyosmium-get-changes
57 if (!CONST_Pyosmium_Binary) {
58 echo "\nCONST_Pyosmium_Binary not configured.\n";
59 echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
60 echo "in your local settings file.\n\n";
61 fail('CONST_Pyosmium_Binary not configured');
64 $sCmd = CONST_Pyosmium_Binary.' --help';
65 exec($sCmd, $aOutput, $iRet);
67 echo "Cannot execute pyosmium-get-changes.\n";
68 echo "Make sure you have pyosmium installed correctly\n";
69 echo "and have set up CONST_Pyosmium_Binary to point to pyosmium-get-changes.\n";
70 fail('pyosmium-get-changes not found or not usable');
73 if (!$aResult['no-update-functions']) {
74 // Try accessing the C module,
75 if (!checkModulePresence()) {
76 fail('error loading nominatim.so module');
78 // instantiate setupClass to use the function therein
79 $cSetup = new SetupFunctions($aResult);
80 $cSetup->createFunctions();
83 $sDatabaseDate = getDatabaseDate($oDB);
84 if ($sDatabaseDate === false) {
85 fail('Cannot determine date of database.');
87 $sWindBack = strftime('%Y-%m-%dT%H:%M:%SZ', strtotime($sDatabaseDate) - (3*60*60));
89 // get the appropriate state id
91 $sCmd = CONST_Pyosmium_Binary.' -D '.$sWindBack.' --server '.CONST_Replication_Url;
92 exec($sCmd, $aOutput, $iRet);
93 if ($iRet != 0 || $aOutput[0] == 'None') {
94 fail('Error running pyosmium tools');
97 pg_query($oDB->connection, 'TRUNCATE import_status');
98 $sSQL = "INSERT INTO import_status (lastimportdate, sequence_id, indexed) VALUES('";
99 $sSQL .= $sDatabaseDate."',".$aOutput[0].', true)';
100 if (!pg_query($oDB->connection, $sSQL)) {
101 fail('Could not enter sequence into database.');
104 echo "Done. Database updates will start at sequence $aOutput[0] ($sWindBack)\n";
107 if ($aResult['check-for-updates']) {
108 $aLastState = chksql($oDB->getRow('SELECT sequence_id FROM import_status'));
110 if (!$aLastState['sequence_id']) {
111 fail('Updates not set up. Please run ./utils/update.php --init-updates.');
114 system(CONST_BasePath.'/utils/check_server_for_updates.py '.CONST_Replication_Url.' '.$aLastState['sequence_id'], $iRet);
118 if (isset($aResult['import-diff']) || isset($aResult['import-file'])) {
119 // import diffs and files directly (e.g. from osmosis --rri)
120 $sNextFile = isset($aResult['import-diff']) ? $aResult['import-diff'] : $aResult['import-file'];
122 if (!file_exists($sNextFile)) {
123 fail("Cannot open $sNextFile\n");
127 $sCMD = $sOsm2pgsqlCmd.' '.$sNextFile;
129 $iErrorLevel = runWithEnv($sCMD, $aProcEnv);
132 fail("Error from osm2pgsql, $iErrorLevel\n");
135 // Don't update the import status - we don't know what this file contains
138 if ($aResult['calculate-postcodes']) {
139 info('Update postcodes centroids');
140 $sTemplate = file_get_contents(CONST_BasePath.'/sql/update-postcodes.sql');
141 runSQLScript($sTemplate, true, true);
144 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
146 $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
148 if (isset($aResult['import-node']) && $aResult['import-node']) {
150 $sContentURL = 'https://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node'];
152 $sContentURL = 'https://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;';
156 if (isset($aResult['import-way']) && $aResult['import-way']) {
158 $sContentURL = 'https://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
160 $sContentURL = 'https://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
164 if (isset($aResult['import-relation']) && $aResult['import-relation']) {
166 $sContentURLsModifyXMLstr = 'https://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full';
168 $sContentURL = 'https://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;';
173 file_put_contents($sTemporaryFile, file_get_contents($sContentURL));
178 // import generated change file
179 $sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
181 $iErrorLevel = runWithEnv($sCMD, $aProcEnv);
183 fail("osm2pgsql exited with error level $iErrorLevel\n");
187 if ($aResult['deduplicate']) {
190 if (getPostgresVersion($oDB) < 9.3) {
191 fail('ERROR: deduplicate is only currently supported in postgresql 9.3');
194 $sSQL = 'select partition from country_name order by country_code';
195 $aPartitions = chksql($oDB->getCol($sSQL));
198 // we don't care about empty search_name_* partitions, they can't contain mentions of duplicates
199 foreach ($aPartitions as $i => $sPartition) {
200 $sSQL = 'select count(*) from search_name_'.$sPartition;
201 $nEntries = chksql($oDB->getOne($sSQL));
202 if ($nEntries == 0) {
203 unset($aPartitions[$i]);
207 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' '";
208 $sSQL .= ' and class is null and type is null and country_code is null';
209 $sSQL .= ' group by word_token having count(*) > 1 order by word_token';
210 $aDuplicateTokens = chksql($oDB->getAll($sSQL));
211 foreach ($aDuplicateTokens as $aToken) {
212 if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
213 echo 'Deduping '.$aToken['word_token']."\n";
214 $sSQL = 'select word_id,';
215 $sSQL .= ' (select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num';
216 $sSQL .= " from word where word_token = '".$aToken['word_token'];
217 $sSQL .= "' and class is null and type is null and country_code is null order by num desc";
218 $aTokenSet = chksql($oDB->getAll($sSQL));
220 $aKeep = array_shift($aTokenSet);
221 $iKeepID = $aKeep['word_id'];
223 foreach ($aTokenSet as $aRemove) {
224 $sSQL = 'update search_name set';
225 $sSQL .= ' name_vector = array_replace(name_vector,'.$aRemove['word_id'].','.$iKeepID.'),';
226 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,'.$aRemove['word_id'].','.$iKeepID.')';
227 $sSQL .= ' where name_vector @> ARRAY['.$aRemove['word_id'].']';
228 chksql($oDB->query($sSQL));
230 $sSQL = 'update search_name set';
231 $sSQL .= ' nameaddress_vector = array_replace(nameaddress_vector,'.$aRemove['word_id'].','.$iKeepID.')';
232 $sSQL .= ' where nameaddress_vector @> ARRAY['.$aRemove['word_id'].']';
233 chksql($oDB->query($sSQL));
235 $sSQL = 'update location_area_country set';
236 $sSQL .= ' keywords = array_replace(keywords,'.$aRemove['word_id'].','.$iKeepID.')';
237 $sSQL .= ' where keywords @> ARRAY['.$aRemove['word_id'].']';
238 chksql($oDB->query($sSQL));
240 foreach ($aPartitions as $sPartition) {
241 $sSQL = 'update search_name_'.$sPartition.' set';
242 $sSQL .= ' name_vector = array_replace(name_vector,'.$aRemove['word_id'].','.$iKeepID.')';
243 $sSQL .= ' where name_vector @> ARRAY['.$aRemove['word_id'].']';
244 chksql($oDB->query($sSQL));
246 $sSQL = 'update location_area_country set';
247 $sSQL .= ' keywords = array_replace(keywords,'.$aRemove['word_id'].','.$iKeepID.')';
248 $sSQL .= ' where keywords @> ARRAY['.$aRemove['word_id'].']';
249 chksql($oDB->query($sSQL));
252 $sSQL = 'delete from word where word_id = '.$aRemove['word_id'];
253 chksql($oDB->query($sSQL));
258 if ($aResult['recompute-word-counts']) {
259 info('Recompute frequency of full-word search terms');
260 $sTemplate = file_get_contents(CONST_BasePath.'/sql/words_from_search_name.sql');
261 runSQLScript($sTemplate, true, true);
264 if ($aResult['index']) {
265 $sCmd = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank'];
266 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
267 $sCmd .= ' -H ' . $aDSNInfo['hostspec'];
269 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
270 $sCmd .= ' -U ' . $aDSNInfo['username'];
273 runWithEnv($sCmd, $aProcEnv);
276 if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
278 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
279 fail('Error: Update interval too low for download.geofabrik.de. ' .
280 "Please check install documentation (http://nominatim.org/release-docs/latest/Import-and-Update#setting-up-the-update-process)\n");
283 $sImportFile = CONST_InstallPath.'/osmosischange.osc';
284 $sCMDDownload = CONST_Pyosmium_Binary.' --server '.CONST_Replication_Url.' -o '.$sImportFile.' -s '.CONST_Replication_Max_Diff_size;
285 $sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile;
286 $sCMDIndex = CONST_InstallPath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'];
287 if (isset($aDSNInfo['hostspec']) && $aDSNInfo['hostspec']) {
288 $sCMDIndex .= ' -H ' . $aDSNInfo['hostspec'];
290 if (isset($aDSNInfo['username']) && $aDSNInfo['username']) {
291 $sCMDIndex .= ' -U ' . $aDSNInfo['username'];
295 $fStartTime = time();
296 $aLastState = chksql($oDB->getRow('SELECT *, EXTRACT (EPOCH FROM lastimportdate) as unix_ts FROM import_status'));
298 if (!$aLastState['sequence_id']) {
299 echo "Updates not set up. Please run ./utils/update.php --init-updates.\n";
303 echo 'Currently at sequence '.$aLastState['sequence_id'].' ('.$aLastState['lastimportdate'].') - '.$aLastState['indexed']." indexed\n";
305 $sBatchEnd = $aLastState['lastimportdate'];
306 $iEndSequence = $aLastState['sequence_id'];
308 if ($aLastState['indexed'] == 't') {
309 // Sleep if the update interval has not yet been reached.
310 $fNextUpdate = $aLastState['unix_ts'] + CONST_Replication_Update_Interval;
311 if ($fNextUpdate > $fStartTime) {
312 $iSleepTime = $fNextUpdate - $fStartTime;
313 echo "Waiting for next update for $iSleepTime sec.";
317 // Download the next batch of changes.
319 $fCMDStartTime = time();
320 $iNextSeq = (int) $aLastState['sequence_id'];
322 echo "$sCMDDownload -I $iNextSeq\n";
323 if (file_exists($sImportFile)) {
324 unlink($sImportFile);
326 exec($sCMDDownload.' -I '.$iNextSeq, $aOutput, $iResult);
329 echo 'No new updates. Sleeping for '.CONST_Replication_Recheck_Interval." sec.\n";
330 sleep(CONST_Replication_Recheck_Interval);
331 } elseif ($iResult != 0) {
332 echo 'ERROR: updates failed.';
335 $iEndSequence = (int)$aOutput[0];
339 // get the newest object from the diff file
342 exec(CONST_BasePath.'/utils/osm_file_date.py '.$sImportFile, $sBatchEnd, $iRet);
344 echo "Diff file is empty. skipping import.\n";
345 if (!$aResult['import-osmosis-all']) {
352 fail('Error getting date from diff file.');
354 $sBatchEnd = $sBatchEnd[0];
357 $fCMDStartTime = time();
358 echo $sCMDImport."\n";
360 $iErrorLevel = runWithEnv($sCMDImport, $aProcEnv);
362 echo "Error executing osm2pgsql: $iErrorLevel\n";
366 // write the update logs
367 $iFileSize = filesize($sImportFile);
368 $sSQL = 'INSERT INTO import_osmosis_log';
369 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
370 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
371 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
372 $sSQL .= date('Y-m-d H:i:s')."','import')";
374 chksql($oDB->query($sSQL));
377 $sSQL = "UPDATE import_status SET lastimportdate = '$sBatchEnd', indexed=false, sequence_id = $iEndSequence";
379 chksql($oDB->query($sSQL));
380 echo date('Y-m-d H:i:s')." Completed download step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
384 if (!$aResult['no-index']) {
385 $sThisIndexCmd = $sCMDIndex;
386 $fCMDStartTime = time();
388 echo "$sThisIndexCmd\n";
389 $iErrorLevel = runWithEnv($sThisIndexCmd, $aProcEnv);
391 echo "Error: $iErrorLevel\n";
395 $sSQL = 'INSERT INTO import_osmosis_log';
396 $sSQL .= '(batchend, batchseq, batchsize, starttime, endtime, event)';
397 $sSQL .= " values ('$sBatchEnd',$iEndSequence,$iFileSize,'";
398 $sSQL .= date('Y-m-d H:i:s', $fCMDStartTime)."','";
399 $sSQL .= date('Y-m-d H:i:s')."','index')";
402 echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60, 2)." minutes\n";
404 $sSQL = 'update import_status set indexed = true';
408 $fDuration = time() - $fStartTime;
409 echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60, 2)." minutes\n";
410 if (!$aResult['import-osmosis-all']) exit(0);