blob: 35b1f230beb896b3cc0fca95816a796b98918f00 [file] [log] [blame]
Serge Bazanski28f49072018-10-06 11:31:18 +01001package graph
2
3import (
4 "fmt"
5
6 confpb "code.hackerspace.pl/q3k/topo/proto/config"
7 "github.com/golang/glog"
8)
9
10type MachinePort struct {
11 OtherEnd *SwitchPort
12 Name string
13}
14
15type SwitchPort struct {
16 OtherEnd *MachinePort
17 Name string
18}
19
20type Machine struct {
21 Name string
22 Complete bool
23
24 Ports map[string]*MachinePort
25}
26
27type Switch struct {
28 Name string
29 Complete bool
30
31 Ports map[string]*SwitchPort
32}
33
34type Graph struct {
35 Switches map[string]*Switch
36 Machines map[string]*Machine
37}
38
39func New() *Graph {
40 return &Graph{
41 Switches: make(map[string]*Switch),
42 Machines: make(map[string]*Machine),
43 }
44}
45
46func (g *Graph) RemoveMachine(name string) {
47 glog.Infof("Removed machine %q", name)
48}
49
50func (g *Graph) RemoveSwitch(name string) {
51 glog.Infof("Removed switch %q", name)
52}
53
54func (g *Graph) LoadConfig(conf *confpb.Config) error {
55 loadedMachines := make(map[string]bool)
56 loadedSwitches := make(map[string]bool)
57
58 // Add new machines and switches.
59 for _, machinepb := range conf.Machine {
60 if machinepb.Name == "" {
61 return fmt.Errorf("empty machine name")
62 }
63 machine, ok := g.Machines[machinepb.Name]
64 if !ok {
65 machine = &Machine{
66 Name: machinepb.Name,
67 Ports: make(map[string]*MachinePort),
68 }
69 for _, portpb := range machinepb.ManagedPort {
70 machine.Ports[portpb.Name] = &MachinePort{
71 Name: portpb.Name,
72 }
73 }
74 g.Machines[machinepb.Name] = machine
75 glog.Infof("Added machine %q with %d managed ports", machine.Name, len(machine.Ports))
76 }
77 machine.Complete = false
78 loadedMachines[machinepb.Name] = true
79 }
80 for _, switchpb := range conf.Switch {
81 if switchpb.Name == "" {
82 return fmt.Errorf("empty switch name")
83 }
84 sw, ok := g.Switches[switchpb.Name]
85 if !ok {
86 sw = &Switch{
87 Name: switchpb.Name,
88 Ports: make(map[string]*SwitchPort),
89 }
90 for _, portpb := range switchpb.ManagedPort {
91 sw.Ports[portpb.Name] = &SwitchPort{
92 Name: portpb.Name,
93 }
94 }
95 g.Switches[switchpb.Name] = sw
96 glog.Infof("Added switch %q with %d managed ports", sw.Name, len(sw.Ports))
97 }
98 sw.Complete = false
99 loadedSwitches[switchpb.Name] = true
100 }
101
102 // Remove old machines and switches.
103 removeMachines := make(map[string]bool)
104 removeSwitches := make(map[string]bool)
105 for name, _ := range g.Switches {
106 if !loadedSwitches[name] {
107 removeSwitches[name] = true
108 }
109 }
110 for name, _ := range g.Machines {
111 if !loadedMachines[name] {
112 removeMachines[name] = true
113 }
114 }
115 for name, _ := range removeMachines {
116 g.RemoveMachine(name)
117 }
118 for name, _ := range removeSwitches {
119 g.RemoveSwitch(name)
120 }
121 return nil
122
123}