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 if not env['NOMINATIM_DATABASE_MODULE_PATH']:
30 env['NOMINATIM_DATABASE_MODULE_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_osm2pgsql(options):
94 """ Run osm2pgsql with the given options.
97 cmd = [options['osm2pgsql'],
98 '--hstore', '--latlon', '--slim',
99 '--with-forward-dependencies', 'false',
100 '--log-progress', 'true',
101 '--number-processes', str(options['threads']),
102 '--cache', str(options['osm2pgsql_cache']),
103 '--output', 'gazetteer',
104 '--style', str(options['osm2pgsql_style'])
106 if options['append']:
107 cmd.append('--append')
109 if options['flatnode_file']:
110 cmd.extend(('--flat-nodes', options['flatnode_file']))
112 dsn = parse_dsn(options['dsn'])
113 if 'password' in dsn:
114 env['PGPASSWORD'] = dsn['password']
116 cmd.extend(('-d', dsn['dbname']))
118 cmd.extend(('--username', dsn['user']))
119 for param in ('host', 'port'):
121 cmd.extend(('--' + param, dsn[param]))
123 cmd.append(str(options['import_file']))
125 subprocess.run(cmd, cwd=options.get('cwd', '.'), env=env, check=True)
129 """ Get the contents from the given URL and return it as a UTF-8 string.
131 headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
134 with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
135 return response.read().decode('utf-8')
137 LOG.fatal('Failed to load URL: %s', url)