2 Functions for updating a database from a replication source.
9 from osmium.replication.server import ReplicationServer
10 from osmium import WriteHandler
12 from ..db import status
13 from .exec_utils import run_osm2pgsql
14 from ..errors import UsageError
16 LOG = logging.getLogger()
18 def init_replication(conn, base_url):
19 """ Set up replication for the server at the given base URL.
21 LOG.info("Using replication source: %s", base_url)
22 date = status.compute_database_date(conn)
24 # margin of error to make sure we get all data
25 date -= dt.timedelta(hours=3)
27 repl = ReplicationServer(base_url)
29 seq = repl.timestamp_to_sequence(date)
32 LOG.fatal("Cannot reach the configured replication service '%s'.\n"
33 "Does the URL point to a directory containing OSM update data?",
35 raise UsageError("Failed to reach replication service")
37 status.set_status(conn, date=date, seq=seq)
39 LOG.warning("Updates intialised at sequence %s (%s)", seq, date)
42 def check_for_updates(conn, base_url):
43 """ Check if new data is available from the replication service at the
46 _, seq, _ = status.get_status(conn)
49 LOG.error("Replication not set up. "
50 "Please run 'nominatim replication --init' first.")
53 state = ReplicationServer(base_url).get_state_info()
56 LOG.error("Cannot get state for URL %s.", base_url)
59 if state.sequence <= seq:
60 LOG.warning("Database is up to date.")
63 LOG.warning("New data available (%i => %i).", seq, state.sequence)
66 class UpdateState(Enum):
67 """ Possible states after an update has run.
75 def update(conn, options):
76 """ Update database from the next batch of data. Returns the state of
77 updates according to `UpdateState`.
79 startdate, startseq, indexed = status.get_status(conn)
82 LOG.error("Replication not set up. "
83 "Please run 'nominatim replication --init' first.")
84 raise UsageError("Replication not set up.")
86 if not indexed and options['indexed_only']:
87 LOG.info("Skipping update. There is data that needs indexing.")
88 return UpdateState.MORE_PENDING
90 last_since_update = dt.datetime.now(dt.timezone.utc) - startdate
91 update_interval = dt.timedelta(seconds=options['update_interval'])
92 if last_since_update < update_interval:
93 duration = (update_interval - last_since_update).seconds
94 LOG.warning("Sleeping for %s sec before next update.", duration)
97 if options['import_file'].exists():
98 options['import_file'].unlink()
100 # Read updates into file.
101 repl = ReplicationServer(options['base_url'])
103 outhandler = WriteHandler(str(options['import_file']))
104 endseq = repl.apply_diffs(outhandler, startseq + 1,
105 max_size=options['max_diff_size'] * 1024)
109 return UpdateState.NO_CHANGES
111 # Consume updates with osm2pgsql.
112 options['append'] = True
113 run_osm2pgsql(options)
115 # Write the current status to the file
116 endstate = repl.get_state_info(endseq)
117 status.set_status(conn, endstate.timestamp, seq=endseq, indexed=False)
119 return UpdateState.UP_TO_DATE