5
0
mirror of https://github.com/cwinfo/yggdrasil-map synced 2024-11-14 17:50:27 +00:00
yggdrasil-map/web/database.py

81 lines
2.5 KiB
Python
Raw Normal View History

import MySQLdb as mdb
from graph import Node, Edge
import time
class NodeDB:
2015-11-21 11:47:21 +00:00
def __init__(self, config):
self.con = mdb.connect(
config['MYSQL_DATABASE_HOST'],
config['MYSQL_DATABASE_USER'],
config['MYSQL_DATABASE_PASSWORD'],
config['MYSQL_DATABASE_DB'])
self.cur = self.con.cursor()
2015-11-21 11:47:21 +00:00
def __enter__(self):
return self
2015-11-21 11:47:21 +00:00
def __exit__(self, type, value, traceback):
self.con.commit()
self.con.close()
2015-11-21 11:47:21 +00:00
def insert_node(self, node):
now = int(time.time())
self.cur.execute('''
INSERT INTO nodes (ip, name, version, first_seen, last_seen)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY
UPDATE name = %s, version = %s, last_seen = %s''', (
node.ip, node.label, node.version, now, now,
node.label, node.version, now))
2015-11-21 12:03:19 +00:00
def insert_edge(self, edge, uploaded_by):
2015-11-21 11:47:21 +00:00
now = int(time.time())
self.cur.execute('''
2015-11-21 11:44:45 +00:00
INSERT INTO edges (a, b, first_seen, last_seen, uploaded_by)
VALUES (%s, %s, %s, %s, %s)
2015-11-21 11:47:21 +00:00
ON DUPLICATE KEY
UPDATE last_seen = %s''', (
2015-11-21 11:44:45 +00:00
edge.a.ip, edge.b.ip, now, now, uploaded_by,
now))
2015-11-21 12:03:19 +00:00
def insert_graph(self, nodes, edges, uploaded_by):
2015-11-21 11:47:21 +00:00
for n in nodes.itervalues():
self.insert_node(n)
2015-11-21 11:47:21 +00:00
for e in edges:
2015-11-21 11:44:45 +00:00
self.insert_edge(e, uploaded_by)
2015-11-21 11:47:21 +00:00
def get_nodes(self, time_limit):
since = int(time.time() - time_limit)
cur = self.con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT ip, version, name FROM nodes WHERE last_seen > %s", (since,))
db_nodes = cur.fetchall()
2015-11-21 11:47:21 +00:00
nodes = dict()
for n in db_nodes:
nodes[n['ip']] = Node(n['ip'], n['version'], n['name'])
2015-11-21 11:47:21 +00:00
return nodes
2015-11-21 11:47:21 +00:00
def get_edges(self, nodes, time_limit):
since = int(time.time() - time_limit)
cur = self.con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT a, b FROM edges WHERE last_seen > %s", (since,))
db_edges = cur.fetchall()
2015-11-21 11:47:21 +00:00
edges = []
for e in db_edges:
try:
edges.append(Edge(nodes[e['a']], nodes[e['b']]))
except KeyError:
pass
return edges
2015-11-21 11:47:21 +00:00
def get_graph(self, time_limit):
nodes = self.get_nodes(time_limit)
edges = self.get_edges(nodes, time_limit)
return (nodes, edges)