]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/setup.py
b4dde6fe862939c804fae590c62486a0b85cc362
[nominatim.git] / nominatim / clicmd / setup.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 Implementation of the 'import' subcommand.
9 """
10 from typing import Optional
11 import argparse
12 import logging
13 from pathlib import Path
14
15 import psutil
16
17 from nominatim.config import Configuration
18 from nominatim.db.connection import connect, Connection
19 from nominatim.db import status, properties
20 from nominatim.tokenizer.base import AbstractTokenizer
21 from nominatim.version import version_str
22 from nominatim.clicmd.args import NominatimArgs
23 from nominatim.errors import UsageError
24
25 # Do not repeat documentation of subcommand classes.
26 # pylint: disable=C0111
27 # Using non-top-level imports to avoid eventually unused imports.
28 # pylint: disable=C0415
29
30 LOG = logging.getLogger()
31
32 class SetupAll:
33     """\
34     Create a new Nominatim database from an OSM file.
35
36     This sub-command sets up a new Nominatim database from scratch starting
37     with creating a new database in Postgresql. The user running this command
38     needs superuser rights on the database.
39     """
40
41     def add_args(self, parser: argparse.ArgumentParser) -> None:
42         group_name = parser.add_argument_group('Required arguments')
43         group1 = group_name.add_mutually_exclusive_group(required=True)
44         group1.add_argument('--osm-file', metavar='FILE', action='append',
45                            help='OSM file to be imported'
46                                 ' (repeat for importing multiple files)')
47         group1.add_argument('--continue', dest='continue_at',
48                            choices=['load-data', 'indexing', 'db-postprocess'],
49                            help='Continue an import that was interrupted')
50         group2 = parser.add_argument_group('Optional arguments')
51         group2.add_argument('--osm2pgsql-cache', metavar='SIZE', type=int,
52                            help='Size of cache to be used by osm2pgsql (in MB)')
53         group2.add_argument('--reverse-only', action='store_true',
54                            help='Do not create tables and indexes for searching')
55         group2.add_argument('--no-partitions', action='store_true',
56                            help=("Do not partition search indices "
57                                  "(speeds up import of single country extracts)"))
58         group2.add_argument('--no-updates', action='store_true',
59                            help="Do not keep tables that are only needed for "
60                                 "updating the database later")
61         group2.add_argument('--offline', action='store_true',
62                            help="Do not attempt to load any additional data from the internet")
63         group3 = parser.add_argument_group('Expert options')
64         group3.add_argument('--ignore-errors', action='store_true',
65                            help='Continue import even when errors in SQL are present')
66         group3.add_argument('--index-noanalyse', action='store_true',
67                            help='Do not perform analyse operations during index (expert only)')
68
69
70     def run(self, args: NominatimArgs) -> int: # pylint: disable=too-many-statements
71         from ..data import country_info
72         from ..tools import database_import, refresh, postcodes, freeze
73         from ..indexer.indexer import Indexer
74
75         num_threads = args.threads or psutil.cpu_count() or 1
76
77         country_info.setup_country_config(args.config)
78
79         if args.continue_at is None:
80             files = args.get_osm_file_list()
81             if not files:
82                 raise UsageError("No input files (use --osm-file).")
83
84             LOG.warning('Creating database')
85             database_import.setup_database_skeleton(args.config.get_libpq_dsn(),
86                                                     rouser=args.config.DATABASE_WEBUSER)
87
88             LOG.warning('Setting up country tables')
89             country_info.setup_country_tables(args.config.get_libpq_dsn(),
90                                               args.data_dir,
91                                               args.no_partitions)
92
93             LOG.warning('Importing OSM data file')
94             database_import.import_osm_data(files,
95                                             args.osm2pgsql_options(0, 1),
96                                             drop=args.no_updates,
97                                             ignore_errors=args.ignore_errors)
98
99             self._setup_tables(args.config, args.reverse_only)
100
101             LOG.warning('Importing wikipedia importance data')
102             data_path = Path(args.config.WIKIPEDIA_DATA_PATH or args.project_dir)
103             if refresh.import_wikipedia_articles(args.config.get_libpq_dsn(),
104                                                  data_path) > 0:
105                 LOG.error('Wikipedia importance dump file not found. '
106                           'Will be using default importances.')
107
108         if args.continue_at is None or args.continue_at == 'load-data':
109             LOG.warning('Initialise tables')
110             with connect(args.config.get_libpq_dsn()) as conn:
111                 database_import.truncate_data_tables(conn)
112
113             LOG.warning('Load data into placex table')
114             database_import.load_data(args.config.get_libpq_dsn(), num_threads)
115
116         LOG.warning("Setting up tokenizer")
117         tokenizer = self._get_tokenizer(args.continue_at, args.config)
118
119         if args.continue_at is None or args.continue_at == 'load-data':
120             LOG.warning('Calculate postcodes')
121             postcodes.update_postcodes(args.config.get_libpq_dsn(),
122                                        args.project_dir, tokenizer)
123
124         if args.continue_at is None or args.continue_at in ('load-data', 'indexing'):
125             if args.continue_at is not None and args.continue_at != 'load-data':
126                 with connect(args.config.get_libpq_dsn()) as conn:
127                     self._create_pending_index(conn, args.config.TABLESPACE_ADDRESS_INDEX)
128             LOG.warning('Indexing places')
129             indexer = Indexer(args.config.get_libpq_dsn(), tokenizer, num_threads)
130             indexer.index_full(analyse=not args.index_noanalyse)
131
132         LOG.warning('Post-process tables')
133         with connect(args.config.get_libpq_dsn()) as conn:
134             database_import.create_search_indices(conn, args.config,
135                                                   drop=args.no_updates,
136                                                   threads=num_threads)
137             LOG.warning('Create search index for default country names.')
138             country_info.create_country_names(conn, tokenizer,
139                                               args.config.get_str_list('LANGUAGES'))
140             if args.no_updates:
141                 freeze.drop_update_tables(conn)
142         tokenizer.finalize_import(args.config)
143
144         LOG.warning('Recompute word counts')
145         tokenizer.update_statistics()
146
147         webdir = args.project_dir / 'website'
148         LOG.warning('Setup website at %s', webdir)
149         with connect(args.config.get_libpq_dsn()) as conn:
150             refresh.setup_website(webdir, args.config, conn)
151
152         self._finalize_database(args.config.get_libpq_dsn(), args.offline)
153
154         return 0
155
156
157     def _setup_tables(self, config: Configuration, reverse_only: bool) -> None:
158         """ Set up the basic database layout: tables, indexes and functions.
159         """
160         from ..tools import database_import, refresh
161
162         with connect(config.get_libpq_dsn()) as conn:
163             LOG.warning('Create functions (1st pass)')
164             refresh.create_functions(conn, config, False, False)
165             LOG.warning('Create tables')
166             database_import.create_tables(conn, config, reverse_only=reverse_only)
167             refresh.load_address_levels_from_config(conn, config)
168             LOG.warning('Create functions (2nd pass)')
169             refresh.create_functions(conn, config, False, False)
170             LOG.warning('Create table triggers')
171             database_import.create_table_triggers(conn, config)
172             LOG.warning('Create partition tables')
173             database_import.create_partition_tables(conn, config)
174             LOG.warning('Create functions (3rd pass)')
175             refresh.create_functions(conn, config, False, False)
176
177
178     def _get_tokenizer(self, continue_at: Optional[str],
179                        config: Configuration) -> AbstractTokenizer:
180         """ Set up a new tokenizer or load an already initialised one.
181         """
182         from ..tokenizer import factory as tokenizer_factory
183
184         if continue_at is None or continue_at == 'load-data':
185             # (re)initialise the tokenizer data
186             return tokenizer_factory.create_tokenizer(config)
187
188         # just load the tokenizer
189         return tokenizer_factory.get_tokenizer_for_db(config)
190
191
192     def _create_pending_index(self, conn: Connection, tablespace: str) -> None:
193         """ Add a supporting index for finding places still to be indexed.
194
195             This index is normally created at the end of the import process
196             for later updates. When indexing was partially done, then this
197             index can greatly improve speed going through already indexed data.
198         """
199         if conn.index_exists('idx_placex_pendingsector'):
200             return
201
202         with conn.cursor() as cur:
203             LOG.warning('Creating support index')
204             if tablespace:
205                 tablespace = 'TABLESPACE ' + tablespace
206             cur.execute(f"""CREATE INDEX idx_placex_pendingsector
207                             ON placex USING BTREE (rank_address,geometry_sector)
208                             {tablespace} WHERE indexed_status > 0
209                          """)
210         conn.commit()
211
212
213     def _finalize_database(self, dsn: str, offline: bool) -> None:
214         """ Determine the database date and set the status accordingly.
215         """
216         with connect(dsn) as conn:
217             if not offline:
218                 try:
219                     dbdate = status.compute_database_date(conn)
220                     status.set_status(conn, dbdate)
221                     LOG.info('Database is at %s.', dbdate)
222                 except Exception as exc: # pylint: disable=broad-except
223                     LOG.error('Cannot determine date of database: %s', exc)
224
225             properties.set_property(conn, 'database_version', version_str())