]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
adapt settings for poldi
[nominatim.git] / utils / update.php
1 #!/usr/bin/php -Cq
2 <?php
3
4         require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5         ini_set('memory_limit', '800M');
6
7         $aCMDOptions = array(
8                 "Import / update / index osm data",
9                 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
10                 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
11                 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
12
13                 array('max-load', '', 0, 1, 1, 1, 'float', 'Maximum load average - indexing is paused if this is exceeded'),
14                 array('max-blocking', '', 0, 1, 1, 1, 'int', 'Maximum blocking processes - indexing is aborted / paused if this is exceeded'),
15
16                 array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'),
17                 array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'),
18
19                 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
20
21                 array('import-hourly', '', 0, 1, 0, 0, 'bool', 'Import hourly diffs'),
22                 array('import-daily', '', 0, 1, 0, 0, 'bool', 'Import daily diffs'),
23                 array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
24
25                 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
26                 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
27
28                 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
29                 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
30                 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
31
32                 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
33                 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
34                 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
35                 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
36
37                 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
38                 array('no-npi', '', 0, 1, 0, 0, 'bool', 'Do not write npi index files'),
39         );
40         getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
41
42         if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
43         {
44                 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
45         }
46
47         if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
48 /*
49         // Lock to prevent multiple copies running
50         if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
51         {
52                 echo "Copy already running\n";
53                 exit;
54         }
55         if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
56         if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
57         if (getBlockingProcesses() > $aResult['max-blocking'])
58         {
59                 echo "Too many blocking processes for import\n";
60                 exit;
61         }
62 */
63
64         // Assume osm2pgsql is in the folder above
65         $sBasePath = dirname(dirname(__FILE__));
66
67         $oDB =& getDB();
68
69         $bFirst = true;
70         $bContinue = $aResult['import-all'];
71         while ($bContinue || $bFirst)
72         {
73                 $bFirst = false;
74
75                 if ($aResult['import-hourly'])
76                 {
77                         // Mirror the hourly diffs
78                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
79                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
80                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
81                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
82                 }
83
84                 if ($aResult['import-daily'])
85                 {
86                         // Mirror the daily diffs
87                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
88                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
89                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
90                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
91                 }
92                 
93                 if (isset($aResult['import-diff']))
94                 {
95                         // import diff directly (e.g. from osmosis --rri)
96                         $sNextFile = $aResult['import-diff'];
97                         if (!file_exists($nextFile))
98                         {
99                                 echo "Cannot open $nextFile\n";
100                                 exit;
101                         }
102                         // Don't update the import status - we don't know what this file contains
103                         $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
104                 }
105
106                 // Missing file is not an error - it might not be created yet
107                 if (($aResult['import-hourly'] || $aResult['import-daily']) && file_exists($sNextFile))
108                 {
109                         // Import the file
110                         $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sNextFile;
111                         echo $sCMD."\n";
112                         exec($sCMD, $sJunk, $iErrorLevel);
113
114                         if ($iErrorLevel)
115                         {
116                                 echo "Error from osm2pgsql, $iErrorLevel\n";
117                                 exit;
118                         }
119         
120                         // Move the date onwards
121                         $oDB->query($sUpdateSQL);
122                 }
123                 else
124                 {
125                         $bContinue = false;
126                 }
127         }
128
129         $sModifyXML = false;
130         if (isset($aResult['import-file']) && $aResult['import-file'])
131         {
132                 $sModifyXML = file_get_contents($aResult['import-file']);
133         }
134         if (isset($aResult['import-node']) && $aResult['import-node'])
135         {
136                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
137         }
138         if (isset($aResult['import-way']) && $aResult['import-way'])
139         {
140                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full');
141         }
142         if (isset($aResult['import-relation']) && $aResult['import-relation'])
143         {
144                 $sModifyXML = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
145         }
146         if ($sModifyXML)
147         {
148                 // Hack into a modify request
149                 $sModifyXML = str_replace('<osm version="0.6" generator="OpenStreetMap server">',
150                         '<osmChange version="0.6" generator="OpenStreetMap server"><modify>', $sModifyXML);
151                 $sModifyXML = str_replace('</osm>', '</modify></osmChange>', $sModifyXML);
152
153                 // Outputing this is too verbose
154                 if ($aResult['verbose'] && false) var_dump($sModifyXML);
155
156                 $sDatabaseName = 'nominatim';
157                 $aSpec = array(
158                         0 => array("pipe", "r"),  // stdin
159                         1 => array("pipe", "w"),  // stdout
160                         2 => array("pipe", "w") // stderr
161                 );
162                 $aPipes = array();
163                 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' -';
164                 echo $sCMD."\n";
165                 $hProc = proc_open($sCMD, $aSpec, $aPipes);
166                 if (!is_resource($hProc))
167                 {
168                         echo "$sBasePath/osm2pgsql failed\n";
169                         exit;   
170                 }
171                 fwrite($aPipes[0], $sModifyXML);
172                 fclose($aPipes[0]);
173                 $sOut = stream_get_contents($aPipes[1]);
174                 if ($aResult['verbose']) echo $sOut;
175                 fclose($aPipes[1]);
176                 $sErrors = stream_get_contents($aPipes[2]);
177                 if ($aResult['verbose']) echo $sErrors;
178                 fclose($aPipes[2]);
179                 if ($iError = proc_close($hProc))
180                 {
181                         echo "osm2pgsql existed with error level $iError\n";
182                         echo $sOut;
183                         echo $sErrors;
184                         exit;
185                 }
186         }
187
188         if ($aResult['deduplicate'])
189         {
190                 $oDB =& getDB();
191                 $sSQL = 'select partition from country_name order by country_code';
192                 $aPartitions = $oDB->getCol($sSQL);
193                 if (PEAR::isError($aPartitions))
194                 {
195                         fail($aPartitions->getMessage());
196                 }
197                 $aPartitions[] = 0;
198
199                 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token";
200                 $aDuplicateTokens = $oDB->getAll($sSQL);
201                 foreach($aDuplicateTokens as $aToken)
202                 {
203                         if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
204                         echo "Deduping ".$aToken['word_token']."\n";
205                         $sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc";
206                         $aTokenSet = $oDB->getAll($sSQL);
207                         if (PEAR::isError($aTokenSet))
208                         {
209                                 var_dump($aTokenSet, $sSQL);
210                                 exit;
211                         }
212                         
213                         $aKeep = array_shift($aTokenSet);
214                         $iKeepID = $aKeep['word_id'];
215
216                         foreach($aTokenSet as $aRemove)
217                         {
218                                 $sSQL = "update search_name set";
219                                 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
220                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
221                                 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
222                                 $x = $oDB->query($sSQL);
223                                 if (PEAR::isError($x))
224                                 {
225                                         var_dump($x);
226                                         exit;
227                                 }
228
229                                 $sSQL = "update search_name set";
230                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
231                                 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
232                                 $x = $oDB->query($sSQL);
233                                 if (PEAR::isError($x))
234                                 {
235                                         var_dump($x);
236                                         exit;
237                                 }
238
239                                 $sSQL = "update location_area_country set";
240                                 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
241                                 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
242                                 $x = $oDB->query($sSQL);
243                                 if (PEAR::isError($x))
244                                 {
245                                         var_dump($x);
246                                         exit;
247                                 }
248
249                                 foreach ($aPartitions as $sPartition)
250                                 {
251                                         $sSQL = "update search_name_".$sPartition." set";
252                                         $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
253                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
254                                         $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
255                                         $x = $oDB->query($sSQL);
256                                         if (PEAR::isError($x))
257                                         {
258                                                 var_dump($x);
259                                                 exit;
260                                         }
261
262                                         $sSQL = "update search_name_".$sPartition." set";
263                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
264                                         $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
265                                         $x = $oDB->query($sSQL);
266                                         if (PEAR::isError($x))
267                                         {
268                                                 var_dump($x);
269                                                 exit;
270                                         }
271
272                                         $sSQL = "update location_area_country set";
273                                         $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
274                                         $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
275                                         $x = $oDB->query($sSQL);
276                                         if (PEAR::isError($x))
277                                         {
278                                                 var_dump($x);
279                                                 exit;
280                                         }
281                                 }
282
283                                 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
284                                 $x = $oDB->query($sSQL);
285                                 if (PEAR::isError($x))
286                                 {
287                                         var_dump($x);
288                                         exit;
289                                 }
290                         }
291
292                 }
293         }
294
295         if ($aResult['index'])
296         {
297                 index($aResult, $sDatabaseDSN);
298         }
299
300         if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
301         {
302                 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
303                 $sOsmosisCMD = CONST_Osmosis_Binary;
304                 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
305                 $sDatabaseName = 'nominatim';
306                 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
307                 $sCMDImport = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$sDatabaseName.' '.$sImportFile;
308                 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -t '.$aResult['index-instances'];
309                 if (!$aResult['no-npi']) {
310                         $sCMDIndex .= '-F ';
311                 }
312                 while(true)
313                 {
314                         $fStartTime = time();
315                         $iFileSize = 1001;
316
317                         // Logic behind this is that osm2pgsql locks the database quite a bit
318                         // So it is better to import lots of small files
319                         // But indexing works most efficiently on large amounts of data
320                         // So do lots of small imports and a BIG index
321
322 //                      while($aResult['import-osmosis-all'] && $iFileSize > 1000)
323 //                      {
324                                 if (!file_exists($sImportFile))
325                                 {
326                                         // Use osmosis to download the file
327                                         $fCMDStartTime = time();
328                                         echo $sCMDDownload."\n";
329                                         exec($sCMDDownload, $sJunk, $iErrorLevel);
330                                         while ($iErrorLevel == 1)
331                                         {
332                                                 echo "Error: $iErrorLevel\n";
333                                                 sleep(60);
334                                                 echo 'Re-trying: '.$sCMDDownload."\n";
335                                                 exec($sCMDDownload, $sJunk, $iErrorLevel);
336                                         }
337                                         $iFileSize = filesize($sImportFile);
338                                         $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
339                                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
340                                         $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')";
341                                         $oDB->query($sSQL);
342                                 }
343
344                                 $iFileSize = filesize($sImportFile);
345                                 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
346                 
347                                 // Import the file
348                                 $fCMDStartTime = time();
349                                 echo $sCMDImport."\n";
350                                 exec($sCMDImport, $sJunk, $iErrorLevel);
351                                 if ($iErrorLevel)
352                                 {
353                                         echo "Error: $iErrorLevel\n";
354                                         exit;
355                                 }
356                                 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
357                                 $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
358                                 var_Dump($sSQL);
359                                 $oDB->query($sSQL);
360
361                                 // Archive for debug?
362                                 unlink($sImportFile);
363
364                                 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
365
366                                 // Index file
367                                 $fCMDStartTime = time();
368                                 $iFileID = $oDB->getOne('select nextval(\'file\')');
369                                 if (PEAR::isError($iFileID))
370                                 {
371                                         echo $iFileID->getMessage()."\n";
372                                         exit;
373                                 } 
374                                 $sFileDir = CONST_BasePath.'/export/diff/';
375                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
376                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
377
378                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
379                                 $sThisIndexCmd = $sCMDIndex;
380                                 if (!$aResult['no-npi']) {
381                                         $sThisIndexCmd .= $sFileDir;
382                                         $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
383                                         $sThisIndexCmd .= ".npi.out";
384
385                                         preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
386                                         $sFileDir = CONST_BasePath.'/export/index/';
387                                         $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
388
389                                         if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
390                                         file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
391                                 }
392
393                                 echo "$sThisIndexCmd\n";
394                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
395                                 if ($iErrorLevel)
396                                 {
397                                         echo "Error: $iErrorLevel\n";
398                                         exit;
399                                 }
400
401                                 if (!$aResult['no-npi']) {
402                                         $sFileDir = CONST_BasePath.'/export/diff/';
403                                         $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
404                                         $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
405
406                                         $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
407                                         echo "$sThisIndexCmd\n";
408                                         exec($sThisIndexCmd, $sJunk, $iErrorLevel);
409                                         if ($iErrorLevel)
410                                         {
411                                                 echo "Error: $iErrorLevel\n";
412                                                 exit;
413                                         }
414
415                                         rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
416                                                 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
417                                 }
418
419                                 echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
420                                 $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')";
421                                 $oDB->query($sSQL);
422
423                                 $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
424                                 $oDB->query($sSQL);
425
426
427                                 $fDuration = time() - $fStartTime;
428                                 echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
429                                 if (!$aResult['import-osmosis-all']) exit;
430 //                      }
431                         echo "Sleeping ".max(0,60-$fDuration)." seconds\n";
432                         sleep(max(0,60-$fDuration));
433                 }
434                 
435         }
436
437         if ($aResult['import-npi-all'])
438         {
439                 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
440                 if (PEAR::isError($iNPIID))
441                 {
442                         var_dump($iNPIID);
443                         exit;
444                 }
445                 $sConfigDirectory = CONST_BasePath.'/settings';
446                 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
447                 while(true)
448                 {
449                         $fStartTime = time();
450
451                         $iNPIID++;
452
453                         $sImportFile = CONST_BasePath.'/export/diff/';
454                         $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
455                         $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
456                         $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
457                         $sImportFile .= ".npi";
458                         while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
459                         {
460                                 echo "sleep (waiting for $sImportFile)\n";
461                                 sleep(10);
462                         }
463                         if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
464
465                         $iFileSize = filesize($sImportFile);
466                 
467                         // Import the file
468                         $fCMDStartTime = time();
469                         $sCMDImport = $sCMDImportTemplate . $sImportFile;
470                         echo $sCMDImport."\n";
471                         exec($sCMDImport, $sJunk, $iErrorLevel);
472                         if ($iErrorLevel)
473                         {
474                                 echo "Error: $iErrorLevel\n";
475                                 exit;
476                         }
477                         $sBatchEnd = $iNPIID;
478                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
479                         $sSQL = "INSERT INTO import_npi_log values ($iNPIID, null, $iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','import')";
480                         var_Dump($sSQL);
481                         $oDB->query($sSQL);
482                 }
483                 
484         }
485
486         function getosmosistimestamp($sOsmosisConfigDirectory)
487         {
488                 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
489                 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
490                 return str_replace('\:',':',$aResult[1]);
491         }