-
Notifications
You must be signed in to change notification settings - Fork 6
/
machine.go
396 lines (317 loc) · 10.7 KB
/
machine.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright 2021 Weaveworks or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MPL-2.0
package scope
import (
"context"
"encoding/base64"
"fmt"
"hash/crc32"
"sort"
"strings"
"github.com/go-logr/logr"
flclient "github.com/weaveworks-liquidmetal/controller-pkg/client"
"github.com/weaveworks-liquidmetal/controller-pkg/types/microvm"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2/klogr"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/controller-runtime/pkg/client"
infrav1 "github.com/weaveworks-liquidmetal/cluster-api-provider-microvm/api/v1alpha1"
"github.com/weaveworks-liquidmetal/cluster-api-provider-microvm/internal/defaults"
)
var _ Scoper = &MachineScope{}
const ProviderPrefix = "microvm://"
const (
tlsCert = "tls.crt"
tlsKey = "tls.key"
caCert = "ca.crt"
)
type MachineScopeParams struct {
Cluster *clusterv1.Cluster
MicroVMCluster *infrav1.MicrovmCluster
Machine *clusterv1.Machine
MicroVMMachine *infrav1.MicrovmMachine
Client client.Client
Context context.Context //nolint: containedctx // don't care
}
func NewMachineScope(params MachineScopeParams, opts ...MachineScopeOption) (*MachineScope, error) {
if params.Cluster == nil {
return nil, errClusterRequired
}
if params.MicroVMCluster == nil {
return nil, errMicrovmClusterRequired
}
if params.Machine == nil {
return nil, errMachineRequired
}
if params.MicroVMMachine == nil {
return nil, errMicrovmMachineRequied
}
if params.Client == nil {
return nil, errClientRequired
}
patchHelper, err := patch.NewHelper(params.MicroVMMachine, params.Client)
if err != nil {
return nil, fmt.Errorf("creating patch helper for microvm machine: %w", err)
}
scope := &MachineScope{
Cluster: params.Cluster,
MvmCluster: params.MicroVMCluster,
Machine: params.Machine,
MvmMachine: params.MicroVMMachine,
client: params.Client,
controllerName: defaults.ManagerName,
Logger: klogr.New(),
patchHelper: patchHelper,
ctx: params.Context,
}
for _, opt := range opts {
opt(scope)
}
return scope, nil
}
type MachineScopeOption func(*MachineScope)
func WithMachineLogger(logger logr.Logger) MachineScopeOption {
return func(s *MachineScope) {
s.Logger = logger
}
}
func WithMachineControllerName(name string) MachineScopeOption {
return func(s *MachineScope) {
s.controllerName = name
}
}
type MachineScope struct {
logr.Logger
Cluster *clusterv1.Cluster
MvmCluster *infrav1.MicrovmCluster
Machine *clusterv1.Machine
MvmMachine *infrav1.MicrovmMachine
client client.Client
patchHelper *patch.Helper
controllerName string
ctx context.Context
}
// Name returns the MicrovmMachine name.
func (m *MachineScope) Name() string {
return m.MvmMachine.Name
}
// Namespace returns the namespace name.
func (m *MachineScope) Namespace() string {
return m.MvmMachine.Namespace
}
// ClusterName returns the name of the cluster.
func (m *MachineScope) ClusterName() string {
return m.Cluster.Name
}
// ControllerName returns the name of the controller that created the scope.
func (m *MachineScope) ControllerName() string {
return m.controllerName
}
// IsControlPlane returns true if the machine is a control plane.
func (m *MachineScope) IsControlPlane() bool {
return util.IsControlPlaneMachine(m.Machine)
}
// Patch persists the resource and status.
func (m *MachineScope) Patch() error {
applicableConditions := []clusterv1.ConditionType{
infrav1.MicrovmReadyCondition,
}
conditions.SetSummary(m.MvmMachine,
conditions.WithConditions(applicableConditions...),
conditions.WithStepCounterIf(m.MvmMachine.DeletionTimestamp.IsZero()),
conditions.WithStepCounter(),
)
err := m.patchHelper.Patch(
m.ctx,
m.MvmMachine,
patch.WithOwnedConditions{Conditions: []clusterv1.ConditionType{
clusterv1.ReadyCondition,
infrav1.MicrovmReadyCondition,
}})
if err != nil {
return fmt.Errorf("unable to patch machine: %w", err)
}
return nil
}
// GetMicrovmSpec returns the spec for the MicroVM.
func (m *MachineScope) GetMicrovmSpec() microvm.VMSpec {
return m.MvmMachine.Spec.VMSpec
}
// GetLabels returns any user defined or default labels for the microvm.
func (m *MachineScope) GetLabels() map[string]string {
labels := map[string]string{}
if m.MvmMachine.Spec.VMSpec.Labels != nil {
labels = m.MvmMachine.Spec.VMSpec.Labels
}
labels["cluster-name"] = m.ClusterName()
return labels
}
func (m *MachineScope) GetFailureDomain() (string, error) {
if m.Machine.Spec.FailureDomain != nil && *m.Machine.Spec.FailureDomain != "" {
return *m.Machine.Spec.FailureDomain, nil
}
providerID := m.GetProviderID()
if providerID != "" {
return m.getFailureDomainFromProviderID(providerID), nil
}
// If we've got this far then we need to work out how to get a failure domain. In the future we will make
// the strategy configurable for static placement and also add support for the scheduler.
failureDomainNames := make([]string, 0, len(m.Cluster.Status.FailureDomains))
for fdName := range m.Cluster.Status.FailureDomains {
failureDomainNames = append(failureDomainNames, fdName)
}
if len(failureDomainNames) == 0 {
return "", errFailureDomainNotFound
}
if len(failureDomainNames) == 1 {
return failureDomainNames[0], nil
}
sort.Strings(failureDomainNames)
pos := int(crc32.ChecksumIEEE([]byte(m.MvmMachine.Name))) % len(failureDomainNames)
return failureDomainNames[pos], nil
}
// GetRawBootstrapData will return the contents of the secret that has been created by the
// bootstrap provider that is being used for this cluster/machine. Initially this we will
// be using the Kubeadm bootstrap provider and so this will contain cloud-init configuration
// that will invoke kubeadm to create or join a cluster.
func (m *MachineScope) GetRawBootstrapData() (string, error) {
if m.Machine.Spec.Bootstrap.DataSecretName == nil {
return "", errMissingBootstrapDataSecret
}
bootstrapSecret := &corev1.Secret{}
secretKey := types.NamespacedName{
Namespace: m.Namespace(),
Name: *m.Machine.Spec.Bootstrap.DataSecretName,
}
if err := m.client.Get(m.ctx, secretKey, bootstrapSecret); err != nil {
return "", fmt.Errorf("getting bootstrap secret %s: %w", secretKey, err)
}
bootstrapData, ok := bootstrapSecret.Data["value"]
if !ok {
return "", errMissingBootstrapSecretKey
}
return base64.StdEncoding.EncodeToString(bootstrapData), nil
}
// SetReady sets any properties/conditions that are used to indicate that the MicrovmMachine is 'Ready'
// back to the upstream CAPI machine controllers.
func (m *MachineScope) SetReady() {
conditions.MarkTrue(m.MvmMachine, infrav1.MicrovmReadyCondition)
m.MvmMachine.Status.Ready = true
}
// SetNotReady sets any properties/conditions that are used to indicate that the MicrovmMachine is NOT 'Ready'
// back to the upstream CAPI machine controllers.
func (m *MachineScope) SetNotReady(
reason string,
severity clusterv1.ConditionSeverity,
message string,
messageArgs ...interface{},
) {
conditions.MarkFalse(m.MvmMachine, infrav1.MicrovmReadyCondition, reason, severity, message, messageArgs...)
m.MvmMachine.Status.Ready = false
}
// SetProviderID saves the unique microvm and object ID to the MvmMachine spec.
func (m *MachineScope) SetProviderID(failureDomain, mvmUID string) {
providerID := fmt.Sprintf("%s%s/%s", ProviderPrefix, failureDomain, mvmUID)
m.MvmMachine.Spec.ProviderID = &providerID
}
// GetProviderID returns the provider if for the machine. If there is no provider id
// then an empty string will be returned.
func (m *MachineScope) GetProviderID() string {
if m.MvmMachine.Spec.ProviderID != nil {
return *m.MvmMachine.Spec.ProviderID
}
return ""
}
// GetInstanceID gets the instance ID (i.e. UID) of the machine.
func (m *MachineScope) GetInstanceID() string {
parsed, err := noderefutil.NewProviderID(m.GetProviderID())
if err != nil {
return ""
}
return parsed.ID()
}
// GetSSHPublicKeys will return the SSH public keys for this machine. It will take into account
// precedence rules. If there are no keys then nil will be returned.
func (m *MachineScope) GetSSHPublicKeys() []microvm.SSHPublicKey {
if len(m.MvmMachine.Spec.SSHPublicKeys) != 0 {
return m.MvmMachine.Spec.SSHPublicKeys
}
if len(m.MvmCluster.Spec.SSHPublicKeys) != 0 {
return m.MvmCluster.Spec.SSHPublicKeys
}
return nil
}
// GetBasicAuthToken will fetch the BasicAuthSecret on the MvmCluster and
// and return the token for the given host.
// If no secret or no value is found, an empty string is returned.
func (m *MachineScope) GetBasicAuthToken(addr string) (string, error) {
placement := m.MvmCluster.Spec.Placement
if placement.StaticPool == nil || placement.StaticPool.BasicAuthSecret == "" {
return "", nil
}
tokenSecret := &corev1.Secret{}
key := types.NamespacedName{
Name: m.MvmCluster.Spec.Placement.StaticPool.BasicAuthSecret,
Namespace: m.MvmCluster.Namespace,
}
if err := m.client.Get(m.ctx, key, tokenSecret); err != nil {
return "", err
}
host := strings.Split(addr, ":")[0]
// If it's not there, that's fine; we will log and return an empty string
token := string(tokenSecret.Data[host])
if token == "" {
m.Info(
"basicAuthToken for host not found in secret", "secret", tokenSecret.Name, "host", host,
)
}
return token, nil
}
// GetTLSConfig will fetch the TLSSecretRef and CASecretRef on the MvmCluster
// and return the TLS config for the client.
// If either are not set, it will be assumed that the hosts are not
// configured will TLS and all client calls will be made without credentials.
func (m *MachineScope) GetTLSConfig() (*flclient.TLSConfig, error) {
if m.MvmCluster.Spec.TLSSecretRef == "" {
m.Info("no TLS configuration found. will create insecure connection")
return nil, nil
}
secretKey := types.NamespacedName{
Name: m.MvmCluster.Spec.TLSSecretRef,
Namespace: m.MvmCluster.Namespace,
}
tlsSecret := &corev1.Secret{}
if err := m.client.Get(context.TODO(), secretKey, tlsSecret); err != nil {
return nil, err
}
certBytes, ok := tlsSecret.Data[tlsCert]
if !ok {
return nil, &tlsError{tlsCert}
}
keyBytes, ok := tlsSecret.Data[tlsKey]
if !ok {
return nil, &tlsError{tlsKey}
}
caBytes, ok := tlsSecret.Data[caCert]
if !ok {
return nil, &tlsError{caCert}
}
return &flclient.TLSConfig{
Cert: certBytes,
Key: keyBytes,
CACert: caBytes,
}, nil
}
func (m *MachineScope) getFailureDomainFromProviderID(providerID string) string {
if providerID == "" {
return ""
}
providerID = strings.ReplaceAll(providerID, ProviderPrefix, "")
parts := strings.Split(providerID, "/")
return parts[0]
}