]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/exec_utils.py
port replication initialisation to Python
[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 ..version import NOMINATIM_VERSION
10
11 LOG = logging.getLogger()
12
13 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
14     """ Run a Nominatim PHP script with the given arguments.
15
16         Returns the exit code of the script. If `throw_on_fail` is True
17         then throw a `CalledProcessError` on a non-zero exit.
18     """
19     cmd = ['/usr/bin/env', 'php', '-Cq',
20            nominatim_env.phplib_dir / 'admin' / script]
21     cmd.extend([str(a) for a in args])
22
23     env = nominatim_env.config.get_os_env()
24     env['NOMINATIM_DATADIR'] = str(nominatim_env.data_dir)
25     env['NOMINATIM_BINDIR'] = str(nominatim_env.data_dir / 'utils')
26     if not env['NOMINATIM_DATABASE_MODULE_PATH']:
27         env['NOMINATIM_DATABASE_MODULE_PATH'] = nominatim_env.module_dir
28     if not env['NOMINATIM_OSM2PGSQL_BINARY']:
29         env['NOMINATIM_OSM2PGSQL_BINARY'] = nominatim_env.osm2pgsql_path
30
31     proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
32                           check=throw_on_fail)
33
34     return proc.returncode
35
36 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
37                    params=None):
38     """ Execute a Nominiatim API function.
39
40         The function needs a project directory that contains the website
41         directory with the scripts to be executed. The scripts will be run
42         using php_cgi. Query parameters can be added as named arguments.
43
44         Returns the exit code of the script.
45     """
46     log = logging.getLogger()
47     webdir = str(project_dir / 'website')
48     query_string = urlencode(params or {})
49
50     env = dict(QUERY_STRING=query_string,
51                SCRIPT_NAME='/{}.php'.format(endpoint),
52                REQUEST_URI='/{}.php?{}'.format(endpoint, query_string),
53                CONTEXT_DOCUMENT_ROOT=webdir,
54                SCRIPT_FILENAME='{}/{}.php'.format(webdir, endpoint),
55                HTTP_HOST='localhost',
56                HTTP_USER_AGENT='nominatim-tool',
57                REMOTE_ADDR='0.0.0.0',
58                DOCUMENT_ROOT=webdir,
59                REQUEST_METHOD='GET',
60                SERVER_PROTOCOL='HTTP/1.1',
61                GATEWAY_INTERFACE='CGI/1.1',
62                REDIRECT_STATUS='CGI')
63
64     if extra_env:
65         env.update(extra_env)
66
67     if phpcgi_bin is None:
68         cmd = ['/usr/bin/env', 'php-cgi']
69     else:
70         cmd = [str(phpcgi_bin)]
71
72     proc = subprocess.run(cmd, cwd=str(project_dir), env=env, capture_output=True,
73                           check=False)
74
75     if proc.returncode != 0 or proc.stderr:
76         if proc.stderr:
77             log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
78         else:
79             log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
80         return proc.returncode or 1
81
82     result = proc.stdout.decode('utf-8')
83     content_start = result.find('\r\n\r\n')
84
85     print(result[content_start + 4:].replace('\\n', '\n'))
86
87     return 0
88
89
90 def get_url(url):
91     """ Get the contents from the given URL and return it as a UTF-8 string.
92     """
93     headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
94
95     try:
96         with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
97             return response.read().decode('utf-8')
98     except:
99         LOG.fatal('Failed to load URL: %s', url)
100         raise