2023-06-21 05:29:52 -04:00
|
|
|
package notifier
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2023-06-29 06:20:22 -04:00
|
|
|
"github.com/juanfont/headscale/hscontrol/types"
|
2023-06-21 05:29:52 -04:00
|
|
|
"github.com/juanfont/headscale/hscontrol/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Notifier struct {
|
|
|
|
l sync.RWMutex
|
2023-06-29 06:20:22 -04:00
|
|
|
nodes map[string]chan<- types.StateUpdate
|
2023-06-21 05:29:52 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewNotifier() *Notifier {
|
|
|
|
return &Notifier{}
|
|
|
|
}
|
|
|
|
|
2023-06-29 06:20:22 -04:00
|
|
|
func (n *Notifier) AddNode(machineKey string, c chan<- types.StateUpdate) {
|
2023-06-21 05:29:52 -04:00
|
|
|
n.l.Lock()
|
|
|
|
defer n.l.Unlock()
|
|
|
|
|
|
|
|
if n.nodes == nil {
|
2023-06-29 06:20:22 -04:00
|
|
|
n.nodes = make(map[string]chan<- types.StateUpdate)
|
2023-06-21 05:29:52 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
n.nodes[machineKey] = c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Notifier) RemoveNode(machineKey string) {
|
|
|
|
n.l.Lock()
|
|
|
|
defer n.l.Unlock()
|
|
|
|
|
|
|
|
if n.nodes == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(n.nodes, machineKey)
|
|
|
|
}
|
|
|
|
|
2023-06-29 06:20:22 -04:00
|
|
|
func (n *Notifier) NotifyAll(update types.StateUpdate) {
|
|
|
|
n.NotifyWithIgnore(update)
|
2023-06-21 05:29:52 -04:00
|
|
|
}
|
|
|
|
|
2023-06-29 06:20:22 -04:00
|
|
|
func (n *Notifier) NotifyWithIgnore(update types.StateUpdate, ignore ...string) {
|
2023-06-21 05:29:52 -04:00
|
|
|
n.l.RLock()
|
|
|
|
defer n.l.RUnlock()
|
|
|
|
|
|
|
|
for key, c := range n.nodes {
|
|
|
|
if util.IsStringInSlice(ignore, key) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-06-29 06:20:22 -04:00
|
|
|
c <- update
|
2023-06-21 05:29:52 -04:00
|
|
|
}
|
|
|
|
}
|