1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Functions for updating a database from a replication source.
10 from contextlib import contextmanager
16 from nominatim.db import status
17 from nominatim.tools.exec_utils import run_osm2pgsql
18 from nominatim.errors import UsageError
21 from osmium.replication.server import ReplicationServer
22 from osmium import WriteHandler
23 except ImportError as exc:
24 logging.getLogger().critical("pyosmium not installed. Replication functions not available.\n"
25 "To install pyosmium via pip: pip3 install osmium")
26 raise UsageError("replication tools not available") from exc
28 LOG = logging.getLogger()
30 def init_replication(conn, base_url):
31 """ Set up replication for the server at the given base URL.
33 LOG.info("Using replication source: %s", base_url)
34 date = status.compute_database_date(conn)
36 # margin of error to make sure we get all data
37 date -= dt.timedelta(hours=3)
39 repl = ReplicationServer(base_url)
41 seq = repl.timestamp_to_sequence(date)
44 LOG.fatal("Cannot reach the configured replication service '%s'.\n"
45 "Does the URL point to a directory containing OSM update data?",
47 raise UsageError("Failed to reach replication service")
49 status.set_status(conn, date=date, seq=seq)
51 LOG.warning("Updates initialised at sequence %s (%s)", seq, date)
54 def check_for_updates(conn, base_url):
55 """ Check if new data is available from the replication service at the
58 _, seq, _ = status.get_status(conn)
61 LOG.error("Replication not set up. "
62 "Please run 'nominatim replication --init' first.")
65 state = ReplicationServer(base_url).get_state_info()
68 LOG.error("Cannot get state for URL %s.", base_url)
71 if state.sequence <= seq:
72 LOG.warning("Database is up to date.")
75 LOG.warning("New data available (%i => %i).", seq, state.sequence)
78 class UpdateState(Enum):
79 """ Possible states after an update has run.
87 def update(conn, options):
88 """ Update database from the next batch of data. Returns the state of
89 updates according to `UpdateState`.
91 startdate, startseq, indexed = status.get_status(conn)
94 LOG.error("Replication not set up. "
95 "Please run 'nominatim replication --init' first.")
96 raise UsageError("Replication not set up.")
98 if not indexed and options['indexed_only']:
99 LOG.info("Skipping update. There is data that needs indexing.")
100 return UpdateState.MORE_PENDING
102 last_since_update = dt.datetime.now(dt.timezone.utc) - startdate
103 update_interval = dt.timedelta(seconds=options['update_interval'])
104 if last_since_update < update_interval:
105 duration = (update_interval - last_since_update).seconds
106 LOG.warning("Sleeping for %s sec before next update.", duration)
109 if options['import_file'].exists():
110 options['import_file'].unlink()
112 # Read updates into file.
113 with _make_replication_server(options['base_url']) as repl:
114 outhandler = WriteHandler(str(options['import_file']))
115 endseq = repl.apply_diffs(outhandler, startseq + 1,
116 max_size=options['max_diff_size'] * 1024)
120 return UpdateState.NO_CHANGES
122 # Consume updates with osm2pgsql.
123 options['append'] = True
124 options['disable_jit'] = conn.server_version_tuple() >= (11, 0)
125 run_osm2pgsql(options)
127 # Write the current status to the file
128 endstate = repl.get_state_info(endseq)
129 status.set_status(conn, endstate.timestamp if endstate else None,
130 seq=endseq, indexed=False)
132 return UpdateState.UP_TO_DATE
135 def _make_replication_server(url):
136 """ Returns a ReplicationServer in form of a context manager.
138 Creates a light wrapper around older versions of pyosmium that did
139 not support the context manager interface.
141 if hasattr(ReplicationServer, '__enter__'):
142 return ReplicationServer(url)
146 yield ReplicationServer(url)