]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/exec_utils.py
Merge pull request #2173 from lonvia/penality-for-housenumberless-places
[nominatim.git] / nominatim / tools / exec_utils.py
1 """
2 Helper functions for executing external programs.
3 """
4 import logging
5 import os
6 import subprocess
7 import urllib.request as urlrequest
8 from urllib.parse import urlencode
9
10 from psycopg2.extensions import parse_dsn
11
12 from ..version import NOMINATIM_VERSION
13
14 LOG = logging.getLogger()
15
16 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
17     """ Run a Nominatim PHP script with the given arguments.
18
19         Returns the exit code of the script. If `throw_on_fail` is True
20         then throw a `CalledProcessError` on a non-zero exit.
21     """
22     cmd = ['/usr/bin/env', 'php', '-Cq',
23            nominatim_env.phplib_dir / 'admin' / script]
24     cmd.extend([str(a) for a in args])
25
26     env = nominatim_env.config.get_os_env()
27     env['NOMINATIM_DATADIR'] = str(nominatim_env.data_dir)
28     env['NOMINATIM_SQLDIR'] = str(nominatim_env.sqllib_dir)
29     env['NOMINATIM_CONFIGDIR'] = str(nominatim_env.config_dir)
30     env['NOMINATIM_DATABASE_MODULE_SRC_PATH'] = nominatim_env.module_dir
31     if not env['NOMINATIM_OSM2PGSQL_BINARY']:
32         env['NOMINATIM_OSM2PGSQL_BINARY'] = nominatim_env.osm2pgsql_path
33
34     proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
35                           check=throw_on_fail)
36
37     return proc.returncode
38
39 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
40                    params=None):
41     """ Execute a Nominiatim API function.
42
43         The function needs a project directory that contains the website
44         directory with the scripts to be executed. The scripts will be run
45         using php_cgi. Query parameters can be added as named arguments.
46
47         Returns the exit code of the script.
48     """
49     log = logging.getLogger()
50     webdir = str(project_dir / 'website')
51     query_string = urlencode(params or {})
52
53     env = dict(QUERY_STRING=query_string,
54                SCRIPT_NAME='/{}.php'.format(endpoint),
55                REQUEST_URI='/{}.php?{}'.format(endpoint, query_string),
56                CONTEXT_DOCUMENT_ROOT=webdir,
57                SCRIPT_FILENAME='{}/{}.php'.format(webdir, endpoint),
58                HTTP_HOST='localhost',
59                HTTP_USER_AGENT='nominatim-tool',
60                REMOTE_ADDR='0.0.0.0',
61                DOCUMENT_ROOT=webdir,
62                REQUEST_METHOD='GET',
63                SERVER_PROTOCOL='HTTP/1.1',
64                GATEWAY_INTERFACE='CGI/1.1',
65                REDIRECT_STATUS='CGI')
66
67     if extra_env:
68         env.update(extra_env)
69
70     if phpcgi_bin is None:
71         cmd = ['/usr/bin/env', 'php-cgi']
72     else:
73         cmd = [str(phpcgi_bin)]
74
75     proc = subprocess.run(cmd, cwd=str(project_dir), env=env, capture_output=True,
76                           check=False)
77
78     if proc.returncode != 0 or proc.stderr:
79         if proc.stderr:
80             log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
81         else:
82             log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
83         return proc.returncode or 1
84
85     result = proc.stdout.decode('utf-8')
86     content_start = result.find('\r\n\r\n')
87
88     print(result[content_start + 4:].replace('\\n', '\n'))
89
90     return 0
91
92
93 def run_php_server(server_address, base_dir):
94     """ Run the built-in server from the given directory.
95     """
96     subprocess.run(['/usr/bin/env', 'php', '-S', server_address],
97                    cwd=str(base_dir), check=True)
98
99
100 def run_osm2pgsql(options):
101     """ Run osm2pgsql with the given options.
102     """
103     env = os.environ
104     cmd = [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'])
112           ]
113     if options['append']:
114         cmd.append('--append')
115
116     if options['flatnode_file']:
117         cmd.extend(('--flat-nodes', options['flatnode_file']))
118
119     dsn = parse_dsn(options['dsn'])
120     if 'password' in dsn:
121         env['PGPASSWORD'] = dsn['password']
122     if 'dbname' in dsn:
123         cmd.extend(('-d', dsn['dbname']))
124     if 'user' in dsn:
125         cmd.extend(('--username', dsn['user']))
126     for param in ('host', 'port'):
127         if param in dsn:
128             cmd.extend(('--' + param, dsn[param]))
129
130     if options.get('disable_jit', False):
131         env['PGOPTIONS'] = '-c jit=off -c max_parallel_workers_per_gather=0'
132
133     cmd.append(str(options['import_file']))
134
135     subprocess.run(cmd, cwd=options.get('cwd', '.'), env=env, check=True)
136
137
138 def get_url(url):
139     """ Get the contents from the given URL and return it as a UTF-8 string.
140     """
141     headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
142
143     try:
144         with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
145             return response.read().decode('utf-8')
146     except:
147         LOG.fatal('Failed to load URL: %s', url)
148         raise