petter2025 commited on
Commit
34d6eec
·
verified ·
1 Parent(s): c2524ca

Create infra_graph.py

Browse files
Files changed (1) hide show
  1. infra_graph.py +47 -12
infra_graph.py CHANGED
@@ -1,7 +1,10 @@
1
- # infra_graph.py
 
 
 
2
  import logging
3
- import networkx as nx
4
- from typing import Dict, Optional
5
 
6
  logger = logging.getLogger(__name__)
7
 
@@ -12,12 +15,17 @@ class InfraGraph:
12
  try:
13
  from neo4j import GraphDatabase
14
  self.neo4j_driver = GraphDatabase.driver(uri, auth=(user, password))
 
 
 
15
  logger.info("Connected to Neo4j")
16
  except Exception as e:
17
- logger.warning(f"Neo4j connection failed, using mock: {e}")
18
- # Always create a NetworkX graph as fallback
 
 
19
  self.nx_graph = nx.DiGraph()
20
-
21
  def update_from_state(self, components: Dict):
22
  """Populate graph from simulator state."""
23
  self.nx_graph.clear()
@@ -25,17 +33,44 @@ class InfraGraph:
25
  self.nx_graph.add_node(cid, **props)
26
  for conn in props.get("connections", []):
27
  self.nx_graph.add_edge(cid, conn, relation="connects_to")
 
 
 
28
  if self.neo4j_driver:
29
  self._update_neo4j(components)
30
-
31
  def _update_neo4j(self, components):
32
- # Implementation to sync with Neo4j (Cypher queries)
33
- pass
34
-
35
- def get_failing_components(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  """Return list of components with status != 'up'."""
37
  failing = []
38
  for node, data in self.nx_graph.nodes(data=True):
39
  if data.get("status") != "up":
40
  failing.append(node)
41
- return failing
 
 
 
 
 
1
+ """
2
+ Graph manager for infrastructure topology.
3
+ Uses Neo4j if credentials provided, otherwise falls back to NetworkX.
4
+ """
5
  import logging
6
+ import os
7
+ from typing import Dict, Optional, List
8
 
9
  logger = logging.getLogger(__name__)
10
 
 
15
  try:
16
  from neo4j import GraphDatabase
17
  self.neo4j_driver = GraphDatabase.driver(uri, auth=(user, password))
18
+ # Verify connection
19
+ with self.neo4j_driver.session() as session:
20
+ session.run("RETURN 1")
21
  logger.info("Connected to Neo4j")
22
  except Exception as e:
23
+ logger.warning(f"Neo4j connection failed, using NetworkX fallback: {e}")
24
+
25
+ # Always create NetworkX graph as fallback
26
+ import networkx as nx
27
  self.nx_graph = nx.DiGraph()
28
+
29
  def update_from_state(self, components: Dict):
30
  """Populate graph from simulator state."""
31
  self.nx_graph.clear()
 
33
  self.nx_graph.add_node(cid, **props)
34
  for conn in props.get("connections", []):
35
  self.nx_graph.add_edge(cid, conn, relation="connects_to")
36
+ if "runs_on" in props:
37
+ self.nx_graph.add_edge(cid, props["runs_on"], relation="runs_on")
38
+
39
  if self.neo4j_driver:
40
  self._update_neo4j(components)
41
+
42
  def _update_neo4j(self, components):
43
+ """Sync with Neo4j (Cypher queries)."""
44
+ with self.neo4j_driver.session() as session:
45
+ # Clear existing graph
46
+ session.run("MATCH (n) DETACH DELETE n")
47
+ # Create nodes
48
+ for cid, props in components.items():
49
+ session.run(
50
+ f"CREATE (:{props['type']} {{id: $id, status: $status}})",
51
+ id=cid, status=props['status']
52
+ )
53
+ # Create relationships
54
+ for cid, props in components.items():
55
+ for conn in props.get("connections", []):
56
+ session.run(
57
+ "MATCH (a {id: $aid}), (b {id: $bid}) CREATE (a)-[:CONNECTED_TO]->(b)",
58
+ aid=cid, bid=conn
59
+ )
60
+ if "runs_on" in props:
61
+ session.run(
62
+ "MATCH (a {id: $aid}), (b {id: $bid}) CREATE (a)-[:RUNS_ON]->(b)",
63
+ aid=cid, bid=props["runs_on"]
64
+ )
65
+
66
+ def get_failing_components(self) -> List[str]:
67
  """Return list of components with status != 'up'."""
68
  failing = []
69
  for node, data in self.nx_graph.nodes(data=True):
70
  if data.get("status") != "up":
71
  failing.append(node)
72
+ return failing
73
+
74
+ def to_networkx(self):
75
+ """Return the internal NetworkX graph."""
76
+ return self.nx_graph