]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/exec_utils.py
Merge pull request #2393 from lonvia/fix-flake8-issues
[nominatim.git] / nominatim / tools / exec_utils.py
1 """
2 Helper functions for executing external programs.
3 """
4 import logging
5 import subprocess
6 import urllib.request as urlrequest
7 from urllib.parse import urlencode
8
9 from nominatim.version import NOMINATIM_VERSION
10 from nominatim.db.connection import get_pg_env
11
12 LOG = logging.getLogger()
13
14 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
15     """ Run a Nominatim PHP script with the given arguments.
16
17         Returns the exit code of the script. If `throw_on_fail` is True
18         then throw a `CalledProcessError` on a non-zero exit.
19     """
20     cmd = ['/usr/bin/env', 'php', '-Cq',
21            str(nominatim_env.phplib_dir / 'admin' / script)]
22     cmd.extend([str(a) for a in args])
23
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)
31
32     proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
33                           check=throw_on_fail)
34
35     return proc.returncode
36
37 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
38                    params=None):
39     """ Execute a Nominiatim API function.
40
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.
44
45         Returns the exit code of the script.
46     """
47     log = logging.getLogger()
48     webdir = str(project_dir / 'website')
49     query_string = urlencode(params or {})
50
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',
59                DOCUMENT_ROOT=webdir,
60                REQUEST_METHOD='GET',
61                SERVER_PROTOCOL='HTTP/1.1',
62                GATEWAY_INTERFACE='CGI/1.1',
63                REDIRECT_STATUS='CGI')
64
65     if extra_env:
66         env.update(extra_env)
67
68     if phpcgi_bin is None:
69         cmd = ['/usr/bin/env', 'php-cgi']
70     else:
71         cmd = [str(phpcgi_bin)]
72
73     proc = subprocess.run(cmd, cwd=str(project_dir), env=env,
74                           stdout=subprocess.PIPE,
75                           stderr=subprocess.PIPE,
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 = 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'])
112           ]
113     if options['append']:
114         cmd.append('--append')
115     else:
116         cmd.append('--create')
117
118     if options['flatnode_file']:
119         cmd.extend(('--flat-nodes', options['flatnode_file']))
120
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]))
127
128     if options.get('disable_jit', False):
129         env['PGOPTIONS'] = '-c jit=off -c max_parallel_workers_per_gather=0'
130
131     cmd.append(str(options['import_file']))
132
133     subprocess.run(cmd, cwd=options.get('cwd', '.'), env=env, check=True)
134
135
136 def get_url(url):
137     """ Get the contents from the given URL and return it as a UTF-8 string.
138     """
139     headers = {"User-Agent": "Nominatim/{0[0]}.{0[1]}.{0[2]}-{0[3]}".format(NOMINATIM_VERSION)}
140
141     try:
142         with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
143             return response.read().decode('utf-8')
144     except Exception:
145         LOG.fatal('Failed to load URL: %s', url)
146         raise