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