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