4 require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5 ini_set('memory_limit', '800M');
8 "Create and setup nominatim search system",
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'),
13 array('osm-file', '', 0, 1, 1, 1, 'realpath', 'File to import'),
14 array('threads', '', 0, 1, 1, 1, 'int', 'Number of threads (where possible)'),
16 array('all', '', 0, 1, 0, 0, 'bool', 'Do the complete process'),
18 array('create-db', '', 0, 1, 0, 0, 'bool', 'Create nominatim db'),
19 array('setup-db', '', 0, 1, 0, 0, 'bool', 'Build a blank nominatim db'),
20 array('import-data', '', 0, 1, 0, 0, 'bool', 'Import a osm file'),
21 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
22 array('create-functions', '', 0, 1, 0, 0, 'bool', 'Create functions'),
23 array('create-minimal-tables', '', 0, 1, 0, 0, 'bool', 'Create minimal main tables'),
24 array('create-tables', '', 0, 1, 0, 0, 'bool', 'Create main tables'),
25 array('create-partitions', '', 0, 1, 0, 0, 'bool', 'Create required partition tables and triggers'),
26 array('load-data', '', 0, 1, 0, 0, 'bool', 'Copy data to live tables from import table'),
27 array('import-tiger-data', '', 0, 1, 0, 0, 'bool', 'Import tiger data (not included in \'all\')'),
28 array('calculate-postcodes', '', 0, 1, 0, 0, 'bool', 'Calculate postcode centroids'),
29 array('create-roads', '', 0, 1, 0, 0, 'bool', 'Calculate postcode centroids'),
30 array('osmosis-init', '', 0, 1, 0, 0, 'bool', 'Generate default osmosis configuration'),
31 array('osmosis-init-date', '', 0, 1, 1, 1, 'string', 'Generate default osmosis configuration'),
32 array('index', '', 0, 1, 0, 0, 'bool', 'Index the data'),
33 array('index-output', '', 0, 1, 1, 1, 'string', 'File to dump index information to'),
34 array('create-search-indices', '', 0, 1, 0, 0, 'bool', 'Create additional indices required for search and update'),
35 array('create-website', '', 0, 1, 1, 1, 'realpath', 'Create symlinks to setup web directory'),
37 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
39 $bDidSomething = false;
41 // This is a pretty hard core defult - the number of processors in the box - 1
42 $iInstances = isset($aCMDResult['threads'])?$aCMDResult['threads']:(getProcessorCount()-1);
46 echo "WARNING: resetting threads to $iInstances\n";
48 if ($iInstances > getProcessorCount())
50 $iInstances = getProcessorCount();
51 echo "WARNING: resetting threads to $iInstances\n";
54 // Assume we can steal all the cache memory in the box (unless told otherwise)
55 $iCacheMemory = (isset($aCMDResult['osm2pgsql-cache'])?$aCMDResult['osm2pgsql-cache']:getCacheMemoryMB());
56 if ($iCacheMemory > getTotalMemoryMB())
58 $iCacheMemory = getCacheMemoryMB();
59 echo "WARNING: resetting cache memory to $iCacheMemory\n";
62 if (isset($aCMDResult['osm-file']) && !isset($aCMDResult['osmosis-init-date']))
64 $sBaseFile = basename($aCMDResult['osm-file']);
65 if (preg_match('#^planet-([0-9]{2})([0-9]{2})([0-9]{2})[.]#', $sBaseFile, $aMatch))
67 $iTime = mktime(0, 0, 0, $aMatch[2], $aMatch[3], '20'.$aMatch[1]);
69 $aCMDResult['osmosis-init-date'] = date('Y-m-d', $iTime).'T22:00:00Z';
72 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
73 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
75 if ($aCMDResult['create-db'] || $aCMDResult['all'])
78 $bDidSomething = true;
79 $oDB =& DB::connect(CONST_Database_DSN, false);
80 if (!PEAR::isError($oDB))
82 fail('database already exists ('.CONST_Database_DSN.')');
84 passthru('createdb -E UTF-8 '.$aDSNInfo['database']);
87 if ($aCMDResult['create-db'] || $aCMDResult['all'])
89 echo "Create DB (2)\n";
90 $bDidSomething = true;
91 // TODO: path detection, detection memory, etc.
94 passthru('createlang plpgsql '.$aDSNInfo['database']);
95 $pgver = (float) CONST_Postgresql_Version;
97 pgsqlRunScriptFile(CONST_Path_Postgresql_Contrib.'/hstore.sql');
99 pgsqlRunScript('CREATE EXTENSION hstore');
101 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/postgis.sql');
102 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/spatial_ref_sys.sql');
103 pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
104 pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
105 pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql');
106 pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode.sql');
107 pgsqlRunScriptFile(CONST_BasePath.'/data/us_statecounty.sql');
108 pgsqlRunScriptFile(CONST_BasePath.'/data/us_state.sql');
109 pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
110 pgsqlRunScriptFile(CONST_BasePath.'/data/worldboundaries.sql');
113 if ($aCMDResult['import-data'] || $aCMDResult['all'])
116 $bDidSomething = true;
118 $osm2pgsql = CONST_Osm2pgsql_Binary;
119 if (!file_exists($osm2pgsql)) fail("please download and build osm2pgsql");
120 $osm2pgsql .= ' -lsc -O gazetteer --hstore';
121 $osm2pgsql .= ' -C '.$iCacheMemory;
122 $osm2pgsql .= ' -d '.$aDSNInfo['database'].' '.$aCMDResult['osm-file'];
123 passthru($osm2pgsql);
126 $x = $oDB->getRow('select * from place limit 1');
127 if (PEAR::isError($x)) {
128 fail($x->getMessage());
130 if (!$x) fail('No Data');
133 if ($aCMDResult['create-functions'] || $aCMDResult['all'])
136 $bDidSomething = true;
137 if (!file_exists(CONST_BasePath.'/module/nominatim.so')) fail("nominatim module not built");
138 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
139 $sTemplate = str_replace('{modulepath}',CONST_BasePath.'/module', $sTemplate);
140 pgsqlRunScript($sTemplate);
143 if ($aCMDResult['create-minimal-tables'])
145 echo "Minimal Tables\n";
146 $bDidSomething = true;
147 pgsqlRunScriptFile(CONST_BasePath.'/sql/tables-minimal.sql');
151 // Backstop the import process - easliest possible import id
152 $sScript .= "insert into import_npi_log values (18022);\n";
154 $hFile = @fopen(CONST_BasePath.'/settings/partitionedtags.def', "r");
155 if (!$hFile) fail('unable to open list of partitions: '.CONST_BasePath.'/settings/partitionedtags.def');
157 while (($sLine = fgets($hFile, 4096)) !== false && $sLine && substr($sLine,0,1) !='#')
159 list($sClass, $sType) = explode(' ', trim($sLine));
160 $sScript .= "create table place_classtype_".$sClass."_".$sType." as ";
161 $sScript .= "select place_id as place_id,geometry as centroid from placex limit 0;\n";
163 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_centroid ";
164 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING GIST (centroid);\n";
166 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_place_id ";
167 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING btree(place_id);\n";
170 pgsqlRunScript($sScript);
173 if ($aCMDResult['create-tables'] || $aCMDResult['all'])
176 $bDidSomething = true;
177 pgsqlRunScriptFile(CONST_BasePath.'/sql/tables.sql');
179 // re-run the functions
180 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
181 $sTemplate = str_replace('{modulepath}',CONST_BasePath.'/module', $sTemplate);
182 pgsqlRunScript($sTemplate);
185 if ($aCMDResult['create-partitions'] || $aCMDResult['all'])
188 $bDidSomething = true;
190 $sSQL = 'select partition from country_name order by country_code';
191 $aPartitions = $oDB->getCol($sSQL);
192 if (PEAR::isError($aPartitions))
194 fail($aPartitions->getMessage());
198 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partitions.src.sql');
199 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
200 foreach($aMatches as $aMatch)
203 foreach($aPartitions as $sPartitionName)
205 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
207 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
210 pgsqlRunScript($sTemplate);
213 if ($aCMDResult['load-data'] || $aCMDResult['all'])
216 $bDidSomething = true;
219 if (!pg_query($oDB->connection, 'TRUNCATE word')) fail(pg_last_error($oDB->connection));
221 if (!pg_query($oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($oDB->connection));
223 if (!pg_query($oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($oDB->connection));
225 if (!pg_query($oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($oDB->connection));
227 if (!pg_query($oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($oDB->connection));
229 if (!pg_query($oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($oDB->connection));
231 if (!pg_query($oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($oDB->connection));
233 if (!pg_query($oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($oDB->connection));
235 if (!pg_query($oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($oDB->connection));
238 $aDBInstances = array();
239 for($i = 0; $i < $iInstances; $i++)
241 $aDBInstances[$i] =& getDB(true);
242 $sSQL = 'insert into placex (osm_type, osm_id, class, type, name, admin_level, ';
243 $sSQL .= 'housenumber, street, isin, postcode, country_code, extratags, ';
244 $sSQL .= 'geometry) select * from place where osm_id % '.$iInstances.' = '.$i;
245 if ($aCMDResult['verbose']) echo "$sSQL\n";
246 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
252 for($i = 0; $i < $iInstances; $i++)
254 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
260 echo "Reanalysing database...\n";
261 pgsqlRunScript('ANALYSE');
264 if ($aCMDResult['create-roads'])
266 $bDidSomething = true;
269 $aDBInstances = array();
270 for($i = 0; $i < $iInstances; $i++)
272 $aDBInstances[$i] =& getDB(true);
273 if (!pg_query($aDBInstances[$i]->connection, 'set enable_bitmapscan = off')) fail(pg_last_error($oDB->connection));
274 $sSQL = 'select count(*) from (select insertLocationRoad(partition, place_id, country_code, geometry) from ';
275 $sSQL .= 'placex where osm_id % '.$iInstances.' = '.$i.' and rank_search between 26 and 27 and class = \'highway\') as x ';
276 if ($aCMDResult['verbose']) echo "$sSQL\n";
277 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
283 for($i = 0; $i < $iInstances; $i++)
285 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
293 if ($aCMDResult['import-tiger-data'])
295 $bDidSomething = true;
297 $aDBInstances = array();
298 for($i = 0; $i < $iInstances; $i++)
300 $aDBInstances[$i] =& getDB(true);
303 foreach(glob(CONST_BasePath.'/data/tiger2011/*.sql') as $sFile)
306 $hFile = fopen($sFile, "r");
307 $sSQL = fgets($hFile, 100000);
312 for($i = 0; $i < $iInstances; $i++)
314 if (!pg_connection_busy($aDBInstances[$i]->connection))
316 while(pg_get_result($aDBInstances[$i]->connection));
317 $sSQL = fgets($hFile, 100000);
319 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
337 for($i = 0; $i < $iInstances; $i++)
339 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
347 if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all'])
349 $bDidSomething = true;
351 if (!pg_query($oDB->connection, 'DELETE from placex where osm_type=\'P\'')) fail(pg_last_error($oDB->connection));
352 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,country_code,geometry) ";
353 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,country_code,";
354 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from (select country_code,postcode,";
355 $sSQL .= "avg(st_x(st_centroid(geometry))) as x,avg(st_y(st_centroid(geometry))) as y ";
356 $sSQL .= "from placex where postcode is not null group by country_code,postcode) as x";
357 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
359 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,country_code,geometry) ";
360 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,'us',";
361 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from us_postcode";
362 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
365 if (($aCMDResult['osmosis-init'] || $aCMDResult['all']) && isset($aCMDResult['osmosis-init-date']))
367 $bDidSomething = true;
370 if (!file_exists(CONST_Osmosis_Binary)) fail("please download osmosis");
371 if (file_exists(CONST_BasePath.'/settings/configuration.txt')) echo "settings/configuration.txt already exists\n";
372 else passthru(CONST_Osmosis_Binary.' --read-replication-interval-init '.CONST_BasePath.'/settings');
374 $sDate = $aCMDResult['osmosis-init-date'];
375 $aDate = date_parse_from_format("Y-m-d\TH-i", $sDate);
376 $sURL = 'http://toolserver.org/~mazder/replicate-sequences/?';
377 $sURL .= 'Y='.$aDate['year'].'&m='.$aDate['month'].'&d='.$aDate['day'];
378 $sURL .= '&H='.$aDate['hour'].'&i='.$aDate['minute'].'&s=0';
379 $sURL .= '&stream=minute';
380 echo "Getting state file: $sURL\n";
381 $sStateFile = file_get_contents($sURL);
382 if (!$sStateFile || strlen($sStateFile) > 1000) fail("unable to obtain state file");
383 file_put_contents(CONST_BasePath.'/settings/state.txt', $sStateFile);
384 echo "Updating DB status\n";
385 pg_query($oDB->connection, 'TRUNCATE import_status');
386 $sSQL = "INSERT INTO import_status VALUES('".$sDate."')";
387 pg_query($oDB->connection, $sSQL);
391 if ($aCMDResult['index'] || $aCMDResult['all'])
393 $bDidSomething = true;
395 if (isset($aCMDResult['index-output'])) $sOutputFile = ' -F '.$aCMDResult['index-output'];
396 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -t '.$iInstances.$sOutputFile;
397 passthru($sBaseCmd.' -R 4');
398 pgsqlRunScript('ANALYSE');
399 passthru($sBaseCmd.' -r 5 -R 25');
400 pgsqlRunScript('ANALYSE');
401 passthru($sBaseCmd.' -r 26');
404 if ($aCMDResult['create-search-indices'] || $aCMDResult['all'])
406 echo "Search indices\n";
407 $bDidSomething = true;
409 $sSQL = 'select partition from country_name order by country_code';
410 $aPartitions = $oDB->getCol($sSQL);
411 if (PEAR::isError($aPartitions))
413 fail($aPartitions->getMessage());
417 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
418 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
419 foreach($aMatches as $aMatch)
422 foreach($aPartitions as $sPartitionName)
424 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
426 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
429 pgsqlRunScript($sTemplate);
432 if (isset($aCMDResult['create-website']))
434 $bDidSomething = true;
435 $sTargetDir = $aCMDResult['create-website'];
436 if (!is_dir($sTargetDir)) fail('please specify a directory to setup');
437 @symlink(CONST_BasePath.'/website/details.php', $sTargetDir.'/details.php');
438 @symlink(CONST_BasePath.'/website/reverse.php', $sTargetDir.'/reverse.php');
439 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/search.php');
440 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/index.php');
441 @symlink(CONST_BasePath.'/website/images', $sTargetDir.'/images');
442 @symlink(CONST_BasePath.'/website/js', $sTargetDir.'/js');
443 echo "Symlinks created\n";
448 showUsage($aCMDOptions, true);
451 function pgsqlRunScriptFile($sFilename)
453 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
455 // Convert database DSN to psql paramaters
456 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
457 $sCMD = 'psql -f '.$sFilename.' '.$aDSNInfo['database'];
459 $aDescriptors = array(
460 0 => array('pipe', 'r'),
461 1 => array('pipe', 'w'),
462 2 => array('file', '/dev/null', 'a')
465 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
466 if (!is_resource($hProcess)) fail('unable to start pgsql');
470 // TODO: error checking
471 while(!feof($ahPipes[1]))
473 echo fread($ahPipes[1], 4096);
477 proc_close($hProcess);
480 function pgsqlRunScript($sScript)
482 // Convert database DSN to psql paramaters
483 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
484 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
485 $sCMD = 'psql -p '.$aDSNInfo['port'].' '.$aDSNInfo['database'];
486 $aDescriptors = array(
487 0 => array('pipe', 'r'),
492 $hProcess = @proc_open($sCMD, $aDescriptors, $ahPipes);
493 if (!is_resource($hProcess)) fail('unable to start pgsql');
495 while(strlen($sScript))
497 $written = fwrite($ahPipes[0], $sScript);
498 $sScript = substr($sScript, $written);
501 proc_close($hProcess);