2 Helper functions for executing external programs.
6 import urllib.request as urlrequest
7 from urllib.parse import urlencode
9 from nominatim.version import NOMINATIM_VERSION
10 from nominatim.db.connection import get_pg_env
12 LOG = logging.getLogger()
14 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
15 """ Run a Nominatim PHP script with the given arguments.
17 Returns the exit code of the script. If `throw_on_fail` is True
18 then throw a `CalledProcessError` on a non-zero exit.
20 cmd = ['/usr/bin/env', 'php', '-Cq',
21 str(nominatim_env.phplib_dir / 'admin' / script)]
22 cmd.extend([str(a) for a in args])
24 env = nominatim_env.config.get_os_env()
25 env['NOMINATIM_DATADIR'] = str(nominatim_env.data_dir)
26 env['NOMINATIM_SQLDIR'] = str(nominatim_env.sqllib_dir)
27 env['NOMINATIM_CONFIGDIR'] = str(nominatim_env.config_dir)
28 env['NOMINATIM_DATABASE_MODULE_SRC_PATH'] = str(nominatim_env.module_dir)
29 if not env['NOMINATIM_OSM2PGSQL_BINARY']:
30 env['NOMINATIM_OSM2PGSQL_BINARY'] = str(nominatim_env.osm2pgsql_path)
32 proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
35 return proc.returncode
37 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
39 """ Execute a Nominiatim API function.
41 The function needs a project directory that contains the website
42 directory with the scripts to be executed. The scripts will be run
43 using php_cgi. Query parameters can be added as named arguments.
45 Returns the exit code of the script.
47 log = logging.getLogger()
48 webdir = str(project_dir / 'website')
49 query_string = urlencode(params or {})
51 env = dict(QUERY_STRING=query_string,
52 SCRIPT_NAME='/{}.php'.format(endpoint),
53 REQUEST_URI='/{}.php?{}'.format(endpoint, query_string),
54 CONTEXT_DOCUMENT_ROOT=webdir,
55 SCRIPT_FILENAME='{}/{}.php'.format(webdir, endpoint),
56 HTTP_HOST='localhost',
57 HTTP_USER_AGENT='nominatim-tool',
58 REMOTE_ADDR='0.0.0.0',
61 SERVER_PROTOCOL='HTTP/1.1',
62 GATEWAY_INTERFACE='CGI/1.1',
63 REDIRECT_STATUS='CGI')
68 if phpcgi_bin is None:
69 cmd = ['/usr/bin/env', 'php-cgi']
71 cmd = [str(phpcgi_bin)]
73 proc = subprocess.run(cmd, cwd=str(project_dir), env=env,
74 stdout=subprocess.PIPE,
75 stderr=subprocess.PIPE,
78 if proc.returncode != 0 or proc.stderr:
80 log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
82 log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
83 return proc.returncode or 1
85 result = proc.stdout.decode('utf-8')
86 content_start = result.find('\r\n\r\n')
88 print(result[content_start + 4:].replace('\\n', '\n'))
93 def run_php_server(server_address, base_dir):
94 """ Run the built-in server from the given directory.
96 subprocess.run(['/usr/bin/env', 'php', '-S', server_address],
97 cwd=str(base_dir), check=True)
100 def run_osm2pgsql(options):
101 """ Run osm2pgsql with the given options.
103 env = get_pg_env(options['dsn'])
104 cmd = [str(options['osm2pgsql']),
105 '--hstore', '--latlon', '--slim',
106 '--with-forward-dependencies', 'false',
107 '--log-progress', 'true',
108 '--number-processes', str(options['threads']),
109 '--cache', str(options['osm2pgsql_cache']),
110 '--output', 'gazetteer',
111 '--style', str(options['osm2pgsql_style'])
113 if options['append']:
114 cmd.append('--append')
116 cmd.append('--create')
118 if options['flatnode_file']:
119 cmd.extend(('--flat-nodes', options['flatnode_file']))
121 for key, param in (('slim_data', '--tablespace-slim-data'),
122 ('slim_index', '--tablespace-slim-index'),
123 ('main_data', '--tablespace-main-data'),
124 ('main_index', '--tablespace-main-index')):
125 if options['tablespaces'][key]:
126 cmd.extend((param, options['tablespaces'][key]))
128 if options.get('disable_jit', False):
129 env['PGOPTIONS'] = '-c jit=off -c max_parallel_workers_per_gather=0'
131 if 'import_data' in options:
132 cmd.extend(('-r', 'xml', '-'))
134 cmd.append(str(options['import_file']))
136 subprocess.run(cmd, cwd=options.get('cwd', '.'),
137 input=options.get('import_data'),
142 """ Get the contents from the given URL and return it as a UTF-8 string.
144 headers = {"User-Agent": "Nominatim/{0[0]}.{0[1]}.{0[2]}-{0[3]}".format(NOMINATIM_VERSION)}
147 with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
148 return response.read().decode('utf-8')
150 LOG.fatal('Failed to load URL: %s', url)