]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/clicmd/replication.py
f8417bd10faf21cdc9f4ef1cc2f3efc29cd720b3
[nominatim.git] / nominatim / clicmd / replication.py
1 """
2 Implementation of the 'replication' sub-command.
3 """
4 import datetime as dt
5 import logging
6 import socket
7 import time
8
9 from nominatim.db import status
10 from nominatim.db.connection import connect
11 from nominatim.errors import UsageError
12
13 LOG = logging.getLogger()
14
15 # Do not repeat documentation of subcommand classes.
16 # pylint: disable=C0111
17 # Using non-top-level imports to make pyosmium optional for replication only.
18 # pylint: disable=E0012,C0415
19
20 class UpdateReplication:
21     """\
22     Update the database using an online replication service.
23     """
24
25     @staticmethod
26     def add_args(parser):
27         group = parser.add_argument_group('Arguments for initialisation')
28         group.add_argument('--init', action='store_true',
29                            help='Initialise the update process')
30         group.add_argument('--no-update-functions', dest='update_functions',
31                            action='store_false',
32                            help=("Do not update the trigger function to "
33                                  "support differential updates."))
34         group = parser.add_argument_group('Arguments for updates')
35         group.add_argument('--check-for-updates', action='store_true',
36                            help='Check if new updates are available and exit')
37         group.add_argument('--once', action='store_true',
38                            help=("Download and apply updates only once. When "
39                                  "not set, updates are continuously applied"))
40         group.add_argument('--no-index', action='store_false', dest='do_index',
41                            help=("Do not index the new data. Only applicable "
42                                  "together with --once"))
43         group.add_argument('--osm2pgsql-cache', metavar='SIZE', type=int,
44                            help='Size of cache to be used by osm2pgsql (in MB)')
45         group = parser.add_argument_group('Download parameters')
46         group.add_argument('--socket-timeout', dest='socket_timeout', type=int, default=60,
47                            help='Set timeout for file downloads.')
48
49     @staticmethod
50     def _init_replication(args):
51         from ..tools import replication, refresh
52
53         LOG.warning("Initialising replication updates")
54         with connect(args.config.get_libpq_dsn()) as conn:
55             replication.init_replication(conn, base_url=args.config.REPLICATION_URL)
56             if args.update_functions:
57                 LOG.warning("Create functions")
58                 refresh.create_functions(conn, args.config, args.sqllib_dir,
59                                          True, False)
60         return 0
61
62
63     @staticmethod
64     def _check_for_updates(args):
65         from ..tools import replication
66
67         with connect(args.config.get_libpq_dsn()) as conn:
68             return replication.check_for_updates(conn, base_url=args.config.REPLICATION_URL)
69
70     @staticmethod
71     def _report_update(batchdate, start_import, start_index):
72         def round_time(delta):
73             return dt.timedelta(seconds=int(delta.total_seconds()))
74
75         end = dt.datetime.now(dt.timezone.utc)
76         LOG.warning("Update completed. Import: %s. %sTotal: %s. Remaining backlog: %s.",
77                     round_time((start_index or end) - start_import),
78                     "Indexing: {} ".format(round_time(end - start_index))
79                     if start_index else '',
80                     round_time(end - start_import),
81                     round_time(end - batchdate))
82
83     @staticmethod
84     def _update(args):
85         from ..tools import replication
86         from ..indexer.indexer import Indexer
87
88         params = args.osm2pgsql_options(default_cache=2000, default_threads=1)
89         params.update(base_url=args.config.REPLICATION_URL,
90                       update_interval=args.config.get_int('REPLICATION_UPDATE_INTERVAL'),
91                       import_file=args.project_dir / 'osmosischange.osc',
92                       max_diff_size=args.config.get_int('REPLICATION_MAX_DIFF'),
93                       indexed_only=not args.once)
94
95         # Sanity check to not overwhelm the Geofabrik servers.
96         if 'download.geofabrik.de'in params['base_url']\
97            and params['update_interval'] < 86400:
98             LOG.fatal("Update interval too low for download.geofabrik.de.\n"
99                       "Please check install documentation "
100                       "(https://nominatim.org/release-docs/latest/admin/Import-and-Update#"
101                       "setting-up-the-update-process).")
102             raise UsageError("Invalid replication update interval setting.")
103
104         if not args.once:
105             if not args.do_index:
106                 LOG.fatal("Indexing cannot be disabled when running updates continuously.")
107                 raise UsageError("Bad argument '--no-index'.")
108             recheck_interval = args.config.get_int('REPLICATION_RECHECK_INTERVAL')
109
110         while True:
111             with connect(args.config.get_libpq_dsn()) as conn:
112                 start = dt.datetime.now(dt.timezone.utc)
113                 state = replication.update(conn, params)
114                 if state is not replication.UpdateState.NO_CHANGES:
115                     status.log_status(conn, start, 'import')
116                 batchdate, _, _ = status.get_status(conn)
117
118             if state is not replication.UpdateState.NO_CHANGES and args.do_index:
119                 index_start = dt.datetime.now(dt.timezone.utc)
120                 indexer = Indexer(args.config.get_libpq_dsn(),
121                                   args.threads or 1)
122                 indexer.index_boundaries(0, 30)
123                 indexer.index_by_rank(0, 30)
124
125                 with connect(args.config.get_libpq_dsn()) as conn:
126                     status.set_indexed(conn, True)
127                     status.log_status(conn, index_start, 'index')
128             else:
129                 index_start = None
130
131             if LOG.isEnabledFor(logging.WARNING):
132                 UpdateReplication._report_update(batchdate, start, index_start)
133
134             if args.once:
135                 break
136
137             if state is replication.UpdateState.NO_CHANGES:
138                 LOG.warning("No new changes. Sleeping for %d sec.", recheck_interval)
139                 time.sleep(recheck_interval)
140
141
142     @staticmethod
143     def run(args):
144         socket.setdefaulttimeout(args.socket_timeout)
145
146         if args.init:
147             return UpdateReplication._init_replication(args)
148
149         if args.check_for_updates:
150             return UpdateReplication._check_for_updates(args)
151
152         UpdateReplication._update(args)
153         return 0