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