diff --git a/inventory_provider/routes/jobs.py b/inventory_provider/routes/jobs.py index dc90269f868c22b2fdc5a80e513dd55acdb4c610..bc2473157e3e9a32de5ddbffe3bcfd26a1116487 100644 --- a/inventory_provider/routes/jobs.py +++ b/inventory_provider/routes/jobs.py @@ -1,5 +1,6 @@ from flask import Blueprint, current_app, jsonify from inventory_provider.tasks import worker +from inventory_provider.tasks import common as worker_common from inventory_provider.routes import common routes = Blueprint("inventory-data-job-routes", __name__) @@ -36,3 +37,27 @@ def reload_router_config(equipment_name): @common.require_accepts_json def check_task_status(task_id): return jsonify(worker.check_task_status(task_id)) + +@routes.route("latchdb", methods=['GET', 'POST']) +def latch_db(): + + config = current_app.config["INVENTORY_PROVIDER_CONFIG"] + db_ids = config['redis-databases'] + db_ids = sorted(set(db_ids)) + + r = worker_common.get_next_redis(config) + latch = worker_common.get_latch(r) + if not latch: + latch = { + 'current': db_ids[0], + 'next': db_ids[0] + } + + next_idx = db_ids.index(latch['next']) + next_idx = (next_idx + 1) % len(db_ids) + + worker_common.set_latch( + config, new_current=latch['next'], new_next=db_ids[next_idx]) + + r = worker_common.get_current_redis(config) + return jsonify(worker_common.get_latch(r)) diff --git a/inventory_provider/tasks/common.py b/inventory_provider/tasks/common.py index 5b6b7c7a729e8fc7ae8993118018a7702ba2528a..956811acad68ee86238f8cff3ef3fbed629ad7f3 100644 --- a/inventory_provider/tasks/common.py +++ b/inventory_provider/tasks/common.py @@ -35,13 +35,28 @@ def get_latch(r): return latch +def set_latch(config, new_current, new_next): + + for db in config['redis-databases']: + latch = { + 'current': new_current, + 'next': new_next, + 'this': db + } + + r = _get_redis(config, dbid=db) + r.set('db:latch', json.dumps(latch)) + + def _get_redis(config, dbid=None): if dbid is None: logger.debug('no db specified, using minimum as first guess') dbid = min(config['redis-databases']) - assert dbid in config['redis-databases'] + if dbid not in config['redis-databases']: + logger.error('tried to connect to unknown db id: {}'.format(dbid)) + dbid = min(config['redis-databases']) kwargs = { 'db': dbid, @@ -81,7 +96,7 @@ def get_next_redis(config): if latch and latch['this'] == latch['next']: return r - if latch: + if latch and latch['next'] in config['redis-databases']: next_id = latch['next'] else: logger.warning("next db not configured, deriving default value")