2014-05-28 16:48:46 +00:00
|
|
|
import json
|
2014-05-30 14:34:00 +00:00
|
|
|
from database import NodeDB
|
|
|
|
from graph import Node, Edge
|
2014-05-28 16:48:46 +00:00
|
|
|
|
2014-05-30 14:34:00 +00:00
|
|
|
def insert_graph_data(config, json_str):
|
2014-05-28 16:48:46 +00:00
|
|
|
try:
|
|
|
|
graph_data = json.loads(json_str)
|
|
|
|
except ValueError:
|
2014-06-04 18:41:33 +00:00
|
|
|
return 'Invalid JSON'
|
2014-05-28 16:48:46 +00:00
|
|
|
|
2014-05-30 14:34:00 +00:00
|
|
|
nodes = dict()
|
|
|
|
edges = []
|
|
|
|
|
|
|
|
try:
|
|
|
|
for n in graph_data['nodes']:
|
2014-06-04 18:41:33 +00:00
|
|
|
try:
|
|
|
|
node = Node(n['ip'], version=n['version'])
|
|
|
|
nodes[n['ip']] = node
|
|
|
|
except Exception:
|
|
|
|
pass
|
2014-05-30 14:34:00 +00:00
|
|
|
|
|
|
|
for e in graph_data['edges']:
|
2014-06-04 18:41:33 +00:00
|
|
|
try:
|
|
|
|
edge = Edge(nodes[e['a']], nodes[e['b']])
|
|
|
|
edges.append(edge)
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
except Exception:
|
|
|
|
return 'Invalid JSON nodes'
|
2014-05-30 14:34:00 +00:00
|
|
|
|
2014-06-04 18:41:33 +00:00
|
|
|
print "Accepted %d nodes and %d links." % (len(nodes), len(edges))
|
2014-05-30 14:34:00 +00:00
|
|
|
|
2014-06-04 18:41:33 +00:00
|
|
|
if len(nodes) == 0 or len(edges) == 0:
|
|
|
|
return 'No valid nodes or edges'
|
2014-05-30 14:34:00 +00:00
|
|
|
|
2014-06-04 18:41:33 +00:00
|
|
|
try:
|
|
|
|
with NodeDB(config) as db:
|
|
|
|
db.insert_graph(nodes, edges)
|
|
|
|
except Exception:
|
|
|
|
return 'Database failure'
|
2014-05-30 14:34:00 +00:00
|
|
|
|
2014-06-04 18:41:33 +00:00
|
|
|
return None
|