2023-11-17 20:05:21 +01:00
|
|
|
package mesh
|
|
|
|
|
2023-11-17 23:13:51 +01:00
|
|
|
type OnChange = func([]MeshNode)
|
2023-11-17 20:05:21 +01:00
|
|
|
|
|
|
|
type MeshMonitor interface {
|
2023-11-17 23:13:51 +01:00
|
|
|
AddUpdateCallback(cb OnChange)
|
|
|
|
AddRemoveCallback(cb OnChange)
|
|
|
|
Trigger() error
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type MeshMonitorImpl struct {
|
2023-11-17 23:13:51 +01:00
|
|
|
updateCbs []OnChange
|
|
|
|
removeCbs []OnChange
|
|
|
|
nodes map[string]MeshNode
|
|
|
|
manager MeshManager
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
|
|
|
|
2023-11-17 23:13:51 +01:00
|
|
|
// Trigger causes the mesh monitor to trigger all of
|
|
|
|
// the callbacks.
|
|
|
|
func (m *MeshMonitorImpl) Trigger() error {
|
|
|
|
changedNodes := make([]MeshNode, 0)
|
|
|
|
removedNodes := make([]MeshNode, 0)
|
|
|
|
|
|
|
|
nodes := make(map[string]MeshNode)
|
|
|
|
|
|
|
|
for _, mesh := range m.manager.GetMeshes() {
|
|
|
|
snapshot, err := mesh.GetMesh()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range snapshot.GetNodes() {
|
|
|
|
previous, exists := m.nodes[node.GetWgHost().String()]
|
|
|
|
|
|
|
|
if !exists || !NodeEquals(previous, node) {
|
|
|
|
changedNodes = append(changedNodes, node)
|
|
|
|
}
|
|
|
|
|
|
|
|
nodes[node.GetWgHost().String()] = node
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, previous := range m.nodes {
|
|
|
|
_, ok := nodes[previous.GetWgHost().String()]
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
removedNodes = append(removedNodes, previous)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(removedNodes) > 0 {
|
|
|
|
for _, cb := range m.removeCbs {
|
|
|
|
cb(removedNodes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(changedNodes) > 0 {
|
|
|
|
for _, cb := range m.updateCbs {
|
|
|
|
cb(changedNodes)
|
|
|
|
}
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
2023-11-17 23:13:51 +01:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MeshMonitorImpl) AddUpdateCallback(cb OnChange) {
|
|
|
|
m.updateCbs = append(m.updateCbs, cb)
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
|
|
|
|
2023-11-17 23:13:51 +01:00
|
|
|
func (m *MeshMonitorImpl) AddRemoveCallback(cb OnChange) {
|
|
|
|
m.removeCbs = append(m.removeCbs, cb)
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
|
|
|
|
2023-11-17 23:13:51 +01:00
|
|
|
func NewMeshMonitor(manager MeshManager) MeshMonitor {
|
2023-11-17 20:05:21 +01:00
|
|
|
return &MeshMonitorImpl{
|
2023-11-17 23:13:51 +01:00
|
|
|
updateCbs: make([]OnChange, 0),
|
|
|
|
nodes: make(map[string]MeshNode),
|
|
|
|
manager: manager,
|
2023-11-17 20:05:21 +01:00
|
|
|
}
|
|
|
|
}
|