]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/exec_utils.py
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / nominatim / tools / exec_utils.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Helper functions for executing external programs.
9 """
10 from typing import Any, Mapping, IO
11 import logging
12 import os
13 import subprocess
14 import urllib.request as urlrequest
15
16 from nominatim.typing import StrPath
17 from nominatim.version import NOMINATIM_VERSION
18 from nominatim.db.connection import get_pg_env
19
20 LOG = logging.getLogger()
21
22 def run_php_server(server_address: str, base_dir: StrPath) -> None:
23     """ Run the built-in server from the given directory.
24     """
25     subprocess.run(['/usr/bin/env', 'php', '-S', server_address],
26                    cwd=str(base_dir), check=True)
27
28
29 def run_osm2pgsql(options: Mapping[str, Any]) -> None:
30     """ Run osm2pgsql with the given options.
31     """
32     env = get_pg_env(options['dsn'])
33     cmd = [str(options['osm2pgsql']),
34            '--slim',
35            '--log-progress', 'true',
36            '--number-processes', '1' if options['append'] else str(options['threads']),
37            '--cache', str(options['osm2pgsql_cache']),
38            '--style', str(options['osm2pgsql_style'])
39           ]
40
41     if str(options['osm2pgsql_style']).endswith('.lua'):
42         env['LUA_PATH'] = ';'.join((str(options['osm2pgsql_style_path'] / '?.lua'),
43                                     os.environ.get('LUAPATH', ';')))
44         cmd.extend(('--output', 'flex'))
45     else:
46         cmd.extend(('--output', 'gazetteer', '--hstore', '--latlon'))
47
48     cmd.append('--append' if options['append'] else '--create')
49
50     if options['flatnode_file']:
51         cmd.extend(('--flat-nodes', options['flatnode_file']))
52
53     for key, param in (('slim_data', '--tablespace-slim-data'),
54                        ('slim_index', '--tablespace-slim-index'),
55                        ('main_data', '--tablespace-main-data'),
56                        ('main_index', '--tablespace-main-index')):
57         if options['tablespaces'][key]:
58             cmd.extend((param, options['tablespaces'][key]))
59
60     if options['tablespaces']['main_data']:
61         env['NOMINATIM_TABLESPACE_PLACE_DATA'] = options['tablespaces']['main_data']
62     if options['tablespaces']['main_index']:
63         env['NOMINATIM_TABLESPACE_PLACE_INDEX'] = options['tablespaces']['main_index']
64
65     if options.get('disable_jit', False):
66         env['PGOPTIONS'] = '-c jit=off -c max_parallel_workers_per_gather=0'
67
68     if 'import_data' in options:
69         cmd.extend(('-r', 'xml', '-'))
70     elif isinstance(options['import_file'], list):
71         for fname in options['import_file']:
72             cmd.append(str(fname))
73     else:
74         cmd.append(str(options['import_file']))
75
76     subprocess.run(cmd, cwd=options.get('cwd', '.'),
77                    input=options.get('import_data'),
78                    env=env, check=True)
79
80
81 def get_url(url: str) -> str:
82     """ Get the contents from the given URL and return it as a UTF-8 string.
83     """
84     headers = {"User-Agent": f"Nominatim/{NOMINATIM_VERSION!s}"}
85
86     try:
87         request = urlrequest.Request(url, headers=headers)
88         with urlrequest.urlopen(request) as response: # type: IO[bytes]
89             return response.read().decode('utf-8')
90     except Exception:
91         LOG.fatal('Failed to load URL: %s', url)
92         raise