/
watch.go
60 lines (55 loc) · 1.85 KB
/
watch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package observer
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// WatchClusterHealthChange returns a Source fed with generic events targeting clusters
// whose health has changed between 2 observations.
// Aimed to be used for triggering a reconciliation.
func WatchClusterHealthChange(m *Manager) *source.Channel {
evtChan := make(chan event.GenericEvent)
m.AddObservationListener(healthChangeListener(evtChan))
return &source.Channel{
// Each event in Source will be consumed and turned into
// a reconciliation request.
Source: evtChan,
// DestBufferSize is kept at the default value (1024).
// This means we can enqueue a maximum of 1024 requests
// before blocking observers from moving on.
}
}
// healthChangeListener returns an OnObservation listener that feeds a generic
// event when a cluster's observed health has changed.
func healthChangeListener(reconciliation chan event.GenericEvent) OnObservation {
return func(cluster types.NamespacedName, previous State, new State) {
// no-op if health hasn't change
if !hasHealthChanged(previous, new) {
return
}
// trigger a reconciliation event for that cluster
evt := event.GenericEvent{
Meta: &metav1.ObjectMeta{
Namespace: cluster.Namespace,
Name: cluster.Name,
},
}
reconciliation <- evt
}
}
// hasHealthChanged returns true if previous and new contain different health.
func hasHealthChanged(previous State, new State) bool {
switch {
// both nil
case previous.ClusterStats == nil && new.ClusterStats == nil:
return false
// both equal
case previous.ClusterStats != nil && new.ClusterStats != nil &&
previous.ClusterStats.LeaderNode == new.ClusterStats.LeaderNode:
return false
// else: different
default:
return true
}
}