2023-06-21 03:29:52 -06:00
|
|
|
package notifier
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2023-06-29 04:20:22 -06:00
|
|
|
"github.com/juanfont/headscale/hscontrol/types"
|
2023-06-21 03:29:52 -06:00
|
|
|
"github.com/juanfont/headscale/hscontrol/util"
|
2023-07-24 00:58:51 -06:00
|
|
|
"github.com/rs/zerolog/log"
|
2023-06-21 03:29:52 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
type Notifier struct {
|
2023-07-26 09:54:19 -06:00
|
|
|
l sync.Mutex
|
2023-06-29 04:20:22 -06:00
|
|
|
nodes map[string]chan<- types.StateUpdate
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewNotifier() *Notifier {
|
|
|
|
return &Notifier{}
|
|
|
|
}
|
|
|
|
|
2023-06-29 04:20:22 -06:00
|
|
|
func (n *Notifier) AddNode(machineKey string, c chan<- types.StateUpdate) {
|
2023-06-21 03:29:52 -06:00
|
|
|
n.l.Lock()
|
|
|
|
defer n.l.Unlock()
|
|
|
|
|
|
|
|
if n.nodes == nil {
|
2023-06-29 04:20:22 -06:00
|
|
|
n.nodes = make(map[string]chan<- types.StateUpdate)
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
n.nodes[machineKey] = c
|
2023-07-24 00:58:51 -06:00
|
|
|
|
|
|
|
log.Trace().
|
|
|
|
Str("machine_key", machineKey).
|
|
|
|
Int("open_chans", len(n.nodes)).
|
|
|
|
Msg("Added new channel")
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Notifier) RemoveNode(machineKey string) {
|
|
|
|
n.l.Lock()
|
|
|
|
defer n.l.Unlock()
|
|
|
|
|
|
|
|
if n.nodes == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(n.nodes, machineKey)
|
2023-07-24 00:58:51 -06:00
|
|
|
|
|
|
|
log.Trace().
|
|
|
|
Str("machine_key", machineKey).
|
|
|
|
Int("open_chans", len(n.nodes)).
|
|
|
|
Msg("Removed channel")
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
|
2023-06-29 04:20:22 -06:00
|
|
|
func (n *Notifier) NotifyAll(update types.StateUpdate) {
|
|
|
|
n.NotifyWithIgnore(update)
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
|
2023-06-29 04:20:22 -06:00
|
|
|
func (n *Notifier) NotifyWithIgnore(update types.StateUpdate, ignore ...string) {
|
2023-07-26 09:54:19 -06:00
|
|
|
n.l.Lock()
|
|
|
|
defer n.l.Unlock()
|
2023-06-21 03:29:52 -06:00
|
|
|
|
|
|
|
for key, c := range n.nodes {
|
|
|
|
if util.IsStringInSlice(ignore, key) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-06-29 04:20:22 -06:00
|
|
|
c <- update
|
2023-06-21 03:29:52 -06:00
|
|
|
}
|
|
|
|
}
|