]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/setup.py
8f717cbb9d16ad52b3076c0aef207e16bf00b401
[nominatim.git] / nominatim / clicmd / setup.py
1 """
2 Implementation of the 'import' subcommand.
3 """
4 import logging
5 from pathlib import Path
6
7 import psutil
8
9 from ..tools.exec_utils import run_legacy_script
10 from ..db.connection import connect
11 from ..db import status
12 from ..errors import UsageError
13
14 # Do not repeat documentation of subcommand classes.
15 # pylint: disable=C0111
16 # Using non-top-level imports to avoid eventually unused imports.
17 # pylint: disable=E0012,C0415
18
19 LOG = logging.getLogger()
20
21 class SetupAll:
22     """\
23     Create a new Nominatim database from an OSM file.
24     """
25
26     @staticmethod
27     def add_args(parser):
28         group_name = parser.add_argument_group('Required arguments')
29         group = group_name.add_mutually_exclusive_group(required=True)
30         group.add_argument('--osm-file', metavar='FILE',
31                            help='OSM file to be imported.')
32         group.add_argument('--continue', dest='continue_at',
33                            choices=['load-data', 'indexing', 'db-postprocess'],
34                            help='Continue an import that was interrupted')
35         group = parser.add_argument_group('Optional arguments')
36         group.add_argument('--osm2pgsql-cache', metavar='SIZE', type=int,
37                            help='Size of cache to be used by osm2pgsql (in MB)')
38         group.add_argument('--reverse-only', action='store_true',
39                            help='Do not create tables and indexes for searching')
40         group.add_argument('--no-partitions', action='store_true',
41                            help="""Do not partition search indices
42                                    (speeds up import of single country extracts)""")
43         group.add_argument('--no-updates', action='store_true',
44                            help="""Do not keep tables that are only needed for
45                                    updating the database later""")
46         group = parser.add_argument_group('Expert options')
47         group.add_argument('--ignore-errors', action='store_true',
48                            help='Continue import even when errors in SQL are present')
49         group.add_argument('--index-noanalyse', action='store_true',
50                            help='Do not perform analyse operations during index')
51
52
53     @staticmethod
54     def run(args): # pylint: disable=too-many-statements
55         from ..tools import database_import
56         from ..tools import refresh
57         from ..indexer.indexer import Indexer
58
59         if args.osm_file and not Path(args.osm_file).is_file():
60             LOG.fatal("OSM file '%s' does not exist.", args.osm_file)
61             raise UsageError('Cannot access file.')
62
63         if args.continue_at is None:
64             database_import.setup_database_skeleton(args.config.get_libpq_dsn(),
65                                                     args.data_dir,
66                                                     args.no_partitions,
67                                                     rouser=args.config.DATABASE_WEBUSER)
68
69             LOG.warning('Installing database module')
70             with connect(args.config.get_libpq_dsn()) as conn:
71                 database_import.install_module(args.module_dir, args.project_dir,
72                                                args.config.DATABASE_MODULE_PATH,
73                                                conn=conn)
74
75             LOG.warning('Importing OSM data file')
76             database_import.import_osm_data(Path(args.osm_file),
77                                             args.osm2pgsql_options(0, 1),
78                                             drop=args.no_updates)
79
80             LOG.warning('Create functions (1st pass)')
81             with connect(args.config.get_libpq_dsn()) as conn:
82                 refresh.create_functions(conn, args.config, args.sqllib_dir,
83                                          False, False)
84
85             LOG.warning('Create tables')
86             params = ['setup.php', '--create-tables', '--create-partition-tables']
87             if args.reverse_only:
88                 params.append('--reverse-only')
89             run_legacy_script(*params, nominatim_env=args)
90
91             LOG.warning('Create functions (2nd pass)')
92             with connect(args.config.get_libpq_dsn()) as conn:
93                 refresh.create_functions(conn, args.config, args.sqllib_dir,
94                                          False, False)
95
96             LOG.warning('Importing wikipedia importance data')
97             data_path = Path(args.config.WIKIPEDIA_DATA_PATH or args.project_dir)
98             if refresh.import_wikipedia_articles(args.config.get_libpq_dsn(),
99                                                  data_path) > 0:
100                 LOG.error('Wikipedia importance dump file not found. '
101                           'Will be using default importances.')
102
103             LOG.warning('Initialise tables')
104             with connect(args.config.get_libpq_dsn()) as conn:
105                 database_import.truncate_data_tables(conn, args.config.MAX_WORD_FREQUENCY)
106
107         if args.continue_at is None or args.continue_at == 'load-data':
108             LOG.warning('Load data into placex table')
109             database_import.load_data(args.config.get_libpq_dsn(),
110                                       args.data_dir,
111                                       args.threads or psutil.cpu_count() or 1)
112
113             LOG.warning('Calculate postcodes')
114             run_legacy_script('setup.php', '--calculate-postcodes', nominatim_env=args)
115
116         if args.continue_at is None or args.continue_at in ('load-data', 'indexing'):
117             LOG.warning('Indexing places')
118             indexer = Indexer(args.config.get_libpq_dsn(),
119                               args.threads or psutil.cpu_count() or 1)
120             indexer.index_full(analyse=not args.index_noanalyse)
121
122         LOG.warning('Post-process tables')
123         params = ['setup.php', '--create-search-indices', '--create-country-names']
124         if args.no_updates:
125             params.append('--drop')
126         run_legacy_script(*params, nominatim_env=args)
127
128         webdir = args.project_dir / 'website'
129         LOG.warning('Setup website at %s', webdir)
130         refresh.setup_website(webdir, args.phplib_dir, args.config)
131
132         with connect(args.config.get_libpq_dsn()) as conn:
133             try:
134                 dbdate = status.compute_database_date(conn)
135                 status.set_status(conn, dbdate)
136                 LOG.info('Database is at %s.', dbdate)
137             except Exception as exc: # pylint: disable=broad-except
138                 LOG.error('Cannot determine date of database: %s', exc)
139
140         return 0