2 Helper functions for executing external programs.
7 import urllib.request as urlrequest
8 from urllib.parse import urlencode
10 from psycopg2.extensions import parse_dsn
12 from ..version import NOMINATIM_VERSION
14 LOG = logging.getLogger()
16 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
17 """ Run a Nominatim PHP script with the given arguments.
19 Returns the exit code of the script. If `throw_on_fail` is True
20 then throw a `CalledProcessError` on a non-zero exit.
22 cmd = ['/usr/bin/env', 'php', '-Cq',
23 nominatim_env.phplib_dir / 'admin' / script]
24 cmd.extend([str(a) for a in args])
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
33 proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
36 return proc.returncode
38 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
40 """ Execute a Nominiatim API function.
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.
46 Returns the exit code of the script.
48 log = logging.getLogger()
49 webdir = str(project_dir / 'website')
50 query_string = urlencode(params or {})
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',
62 SERVER_PROTOCOL='HTTP/1.1',
63 GATEWAY_INTERFACE='CGI/1.1',
64 REDIRECT_STATUS='CGI')
69 if phpcgi_bin is None:
70 cmd = ['/usr/bin/env', 'php-cgi']
72 cmd = [str(phpcgi_bin)]
74 proc = subprocess.run(cmd, cwd=str(project_dir), env=env, capture_output=True,
77 if proc.returncode != 0 or proc.stderr:
79 log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
81 log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
82 return proc.returncode or 1
84 result = proc.stdout.decode('utf-8')
85 content_start = result.find('\r\n\r\n')
87 print(result[content_start + 4:].replace('\\n', '\n'))
92 def run_php_server(server_address, base_dir):
93 """ Run the built-in server from the given directory.
95 subprocess.run(['/usr/bin/env', 'php', '-S', server_address],
96 cwd=str(base_dir), check=True)
99 def run_osm2pgsql(options):
100 """ Run osm2pgsql with the given options.
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'])
112 if options['append']:
113 cmd.append('--append')
115 if options['flatnode_file']:
116 cmd.extend(('--flat-nodes', options['flatnode_file']))
118 dsn = parse_dsn(options['dsn'])
119 if 'password' in dsn:
120 env['PGPASSWORD'] = dsn['password']
122 cmd.extend(('-d', dsn['dbname']))
124 cmd.extend(('--username', dsn['user']))
125 for param in ('host', 'port'):
127 cmd.extend(('--' + param, dsn[param]))
129 cmd.append(str(options['import_file']))
131 subprocess.run(cmd, cwd=options.get('cwd', '.'), env=env, check=True)
135 """ Get the contents from the given URL and return it as a UTF-8 string.
137 headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
140 with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
141 return response.read().decode('utf-8')
143 LOG.fatal('Failed to load URL: %s', url)