Created
June 22, 2016 22:53
-
-
Save cgueret/959cd0265b8dbe39dd7d9ad6322972da to your computer and use it in GitHub Desktop.
Look for loops in the trigger data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
""" | |
Detects loops in the triggers | |
Heavily based on https://git.bbcarchdev.net/res/docker/blob/master/graphite/collect.py | |
""" | |
import logging | |
logging.basicConfig(level=logging.INFO) | |
import psycopg2 | |
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT | |
DSN = 'host=192.168.99.100 dbname=spindle user=postgres port=32768' | |
QUERY = 'SELECT * FROM "triggers"' | |
# Connect to the DB | |
db = psycopg2.connect(DSN) | |
db.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) | |
logging.info("Database connection established") | |
def find_loop(edges, visited_ids): | |
current_id = visited_ids[-1] | |
logging.debug('Visited ids: {}'.format(visited_ids)) | |
if current_id in edges: | |
for next_id in edges[current_id]: | |
new_path = [visited_id for visited_id in visited_ids] | |
new_path.append(next_id) | |
if next_id in visited_ids: | |
logging.info('Found a loop: {}'.format(new_path)) | |
else: | |
find_loop(edges, new_path) | |
try: | |
# Get all the data | |
curs = db.cursor() | |
curs.execute(QUERY) | |
values = curs.fetchall() | |
# Extract a list of edges | |
trigger_ids = set() | |
edges = {} | |
for (target_id, trigger_uri, trigger_id, flags) in values: | |
# Create the edge | |
if trigger_id != None: | |
edges.setdefault(trigger_id, set()) | |
if target_id in edges[trigger_id]: | |
logging.warning("Duplicate trigger for {} ({})".format(trigger_uri, trigger_id)) | |
if target_id == trigger_id: | |
logging.warning("Self trigger for {} ({})".format(trigger_uri, trigger_id)) | |
if target_id != trigger_id: | |
edges[trigger_id].add(target_id) | |
# Add the ids to the set | |
trigger_ids.add(trigger_id) | |
trigger_ids.add(target_id) | |
logging.info("Got {} edges".format(len(edges))) | |
# Compose all the paths | |
logging.info("Will check {} starting point".format(len(trigger_ids))) | |
for trigger_id in trigger_ids: | |
logging.debug("=== {} ===".format(trigger_id)) | |
find_loop(edges, [trigger_id]) | |
except Exception as e: | |
logging.error(e) | |
finally: | |
logging.info("Closing database connection") | |
db.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment