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_SQLDIR'] = str(nominatim_env.sqllib_dir)
29 env['NOMINATIM_CONFIGDIR'] = str(nominatim_env.config_dir)
30 env['NOMINATIM_DATABASE_MODULE_SRC_PATH'] = nominatim_env.module_dir
31 if not env['NOMINATIM_OSM2PGSQL_BINARY']:
32 env['NOMINATIM_OSM2PGSQL_BINARY'] = nominatim_env.osm2pgsql_path
34 proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
37 return proc.returncode
39 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
41 """ Execute a Nominiatim API function.
43 The function needs a project directory that contains the website
44 directory with the scripts to be executed. The scripts will be run
45 using php_cgi. Query parameters can be added as named arguments.
47 Returns the exit code of the script.
49 log = logging.getLogger()
50 webdir = str(project_dir / 'website')
51 query_string = urlencode(params or {})
53 env = dict(QUERY_STRING=query_string,
54 SCRIPT_NAME='/{}.php'.format(endpoint),
55 REQUEST_URI='/{}.php?{}'.format(endpoint, query_string),
56 CONTEXT_DOCUMENT_ROOT=webdir,
57 SCRIPT_FILENAME='{}/{}.php'.format(webdir, endpoint),
58 HTTP_HOST='localhost',
59 HTTP_USER_AGENT='nominatim-tool',
60 REMOTE_ADDR='0.0.0.0',
63 SERVER_PROTOCOL='HTTP/1.1',
64 GATEWAY_INTERFACE='CGI/1.1',
65 REDIRECT_STATUS='CGI')
70 if phpcgi_bin is None:
71 cmd = ['/usr/bin/env', 'php-cgi']
73 cmd = [str(phpcgi_bin)]
75 proc = subprocess.run(cmd, cwd=str(project_dir), env=env, capture_output=True,
78 if proc.returncode != 0 or proc.stderr:
80 log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
82 log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
83 return proc.returncode or 1
85 result = proc.stdout.decode('utf-8')
86 content_start = result.find('\r\n\r\n')
88 print(result[content_start + 4:].replace('\\n', '\n'))
93 def run_php_server(server_address, base_dir):
94 """ Run the built-in server from the given directory.
96 subprocess.run(['/usr/bin/env', 'php', '-S', server_address],
97 cwd=str(base_dir), check=True)
100 def run_osm2pgsql(options):
101 """ Run osm2pgsql with the given options.
104 cmd = [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'])
113 if options['append']:
114 cmd.append('--append')
116 if options['flatnode_file']:
117 cmd.extend(('--flat-nodes', options['flatnode_file']))
119 dsn = parse_dsn(options['dsn'])
120 if 'password' in dsn:
121 env['PGPASSWORD'] = dsn['password']
123 cmd.extend(('-d', dsn['dbname']))
125 cmd.extend(('--username', dsn['user']))
126 for param in ('host', 'port'):
128 cmd.extend(('--' + param, dsn[param]))
130 cmd.append(str(options['import_file']))
132 subprocess.run(cmd, cwd=options.get('cwd', '.'), env=env, check=True)
136 """ Get the contents from the given URL and return it as a UTF-8 string.
138 headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
141 with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
142 return response.read().decode('utf-8')
144 LOG.fatal('Failed to load URL: %s', url)