/
annotate.go
193 lines (152 loc) · 5.16 KB
/
annotate.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package siderolink
import (
"context"
"fmt"
"net/netip"
"sync"
"time"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
sidero "github.com/siderolabs/sidero/app/caps-controller-manager/api/v1alpha3"
)
// Annotation describes the source server by SideroLink IP address.
type Annotation struct {
ServerUUID string
Namespace string
MetalMachineName string
MachineName string
ClusterName string
}
// Annotator keeps a cache of annotations per SideroLink IP address.
type Annotator struct {
logger *zap.Logger
metalClient runtimeclient.Client
kubeconfig *rest.Config
nodesMu sync.Mutex
nodes map[string]Annotation
}
// NewAnnotator initializes new server.
func NewAnnotator(metalClient runtimeclient.Client, kubeconfig *rest.Config, logger *zap.Logger) *Annotator {
return &Annotator{
logger: logger,
kubeconfig: kubeconfig,
metalClient: metalClient,
nodes: map[string]Annotation{},
}
}
// Run the watch loop on ServerBindings to build the annotation database.
//
//nolint:dupl
func (a *Annotator) Run(ctx context.Context) error {
dc, err := dynamic.NewForConfig(a.kubeconfig)
if err != nil {
return err
}
// Create a factory object that can generate informers for resource types
factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dc, 10*time.Minute, "", nil)
informerFactory := factory.ForResource(sidero.GroupVersion.WithResource("serverbindings"))
informer := informerFactory.Informer()
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(new interface{}) { a.notify(nil, new) },
UpdateFunc: a.notify,
DeleteFunc: func(old interface{}) { a.notify(old, nil) },
})
informer.Run(ctx.Done())
return nil
}
func (a *Annotator) Get(addr string) (Annotation, bool) {
a.nodesMu.Lock()
defer a.nodesMu.Unlock()
annotation, exists := a.nodes[addr]
return annotation, exists
}
func (a *Annotator) notify(old, new interface{}) {
var oldServerBinding, newServerBinding *sidero.ServerBinding
if old != nil {
oldServerBinding = &sidero.ServerBinding{}
err := runtime.DefaultUnstructuredConverter.
FromUnstructured(old.(*unstructured.Unstructured).UnstructuredContent(), oldServerBinding)
if err != nil {
a.logger.Error("failed converting old event object", zap.Error(err))
return
}
}
if new != nil {
newServerBinding = &sidero.ServerBinding{}
err := runtime.DefaultUnstructuredConverter.
FromUnstructured(new.(*unstructured.Unstructured).UnstructuredContent(), newServerBinding)
if err != nil {
a.logger.Error("failed converting new event object", zap.Error(err))
return
}
}
a.nodesMu.Lock()
defer a.nodesMu.Unlock()
if new == nil {
delete(a.nodes, oldServerBinding.Spec.SideroLink.NodeAddress)
} else {
if oldServerBinding != nil && oldServerBinding.Spec.SideroLink.NodeAddress == newServerBinding.Spec.SideroLink.NodeAddress {
// no change to the node address
return
}
address := newServerBinding.Spec.SideroLink.NodeAddress
if address == "" {
return
}
ipPrefix, err := netip.ParsePrefix(address)
if err != nil {
a.logger.Error("failure parsing siderolink address", zap.Error(err))
return
}
address = ipPrefix.Addr().String()
if oldServerBinding != nil {
delete(a.nodes, oldServerBinding.Spec.SideroLink.NodeAddress)
}
annotation, err := a.buildAnnotation(newServerBinding)
if err != nil {
a.logger.Error("failure building annotation", zap.Error(err))
}
a.nodes[address] = annotation
a.logger.Debug("new node mapping", zap.String("ip", address), zap.Any("annotation", annotation))
}
}
func (a *Annotator) buildAnnotation(serverBinding *sidero.ServerBinding) (annotation Annotation, err error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
annotation.ServerUUID = serverBinding.Name
annotation.Namespace = serverBinding.Spec.MetalMachineRef.Namespace
annotation.MetalMachineName = serverBinding.Spec.MetalMachineRef.Name
annotation.ClusterName = serverBinding.Labels[clusterv1.ClusterNameLabel]
var metalMachine sidero.MetalMachine
if err = a.metalClient.Get(ctx,
types.NamespacedName{
Namespace: serverBinding.Spec.MetalMachineRef.Namespace,
Name: serverBinding.Spec.MetalMachineRef.Name,
},
&metalMachine); err != nil {
return annotation, fmt.Errorf("error getting metal machine: %w", err)
}
for _, ref := range metalMachine.OwnerReferences {
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
continue
}
if ref.Kind == "Machine" && gv.Group == clusterv1.GroupVersion.Group {
annotation.MachineName = ref.Name
break
}
}
return annotation, nil
}