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.
15 from nominatim.db import status
16 from nominatim.tools.exec_utils import run_osm2pgsql
17 from nominatim.errors import UsageError
20 from osmium.replication.server import ReplicationServer
21 from osmium import WriteHandler
22 except ImportError as exc:
23 logging.getLogger().fatal("pyosmium not installed. Replication functions not available.\n"
24 "To install pyosmium via pip: pip3 install osmium")
25 raise UsageError("replication tools not available") from exc
27 LOG = logging.getLogger()
29 def init_replication(conn, base_url):
30 """ Set up replication for the server at the given base URL.
32 LOG.info("Using replication source: %s", base_url)
33 date = status.compute_database_date(conn)
35 # margin of error to make sure we get all data
36 date -= dt.timedelta(hours=3)
38 repl = ReplicationServer(base_url)
40 seq = repl.timestamp_to_sequence(date)
43 LOG.fatal("Cannot reach the configured replication service '%s'.\n"
44 "Does the URL point to a directory containing OSM update data?",
46 raise UsageError("Failed to reach replication service")
48 status.set_status(conn, date=date, seq=seq)
50 LOG.warning("Updates initialised at sequence %s (%s)", seq, date)
53 def check_for_updates(conn, base_url):
54 """ Check if new data is available from the replication service at the
57 _, seq, _ = status.get_status(conn)
60 LOG.error("Replication not set up. "
61 "Please run 'nominatim replication --init' first.")
64 state = ReplicationServer(base_url).get_state_info()
67 LOG.error("Cannot get state for URL %s.", base_url)
70 if state.sequence <= seq:
71 LOG.warning("Database is up to date.")
74 LOG.warning("New data available (%i => %i).", seq, state.sequence)
77 class UpdateState(Enum):
78 """ Possible states after an update has run.
86 def update(conn, options):
87 """ Update database from the next batch of data. Returns the state of
88 updates according to `UpdateState`.
90 startdate, startseq, indexed = status.get_status(conn)
93 LOG.error("Replication not set up. "
94 "Please run 'nominatim replication --init' first.")
95 raise UsageError("Replication not set up.")
97 if not indexed and options['indexed_only']:
98 LOG.info("Skipping update. There is data that needs indexing.")
99 return UpdateState.MORE_PENDING
101 last_since_update = dt.datetime.now(dt.timezone.utc) - startdate
102 update_interval = dt.timedelta(seconds=options['update_interval'])
103 if last_since_update < update_interval:
104 duration = (update_interval - last_since_update).seconds
105 LOG.warning("Sleeping for %s sec before next update.", duration)
108 if options['import_file'].exists():
109 options['import_file'].unlink()
111 # Read updates into file.
112 repl = ReplicationServer(options['base_url'])
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