forked from openstack-k8s-operators/ovn-operator
/
ovncontroller_controller.go
666 lines (587 loc) · 24 KB
/
ovncontroller_controller.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"sort"
"time"
"github.com/go-logr/logr"
netattdefv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/fernandoroyosanchez/ovn-operator/api/v1beta1"
"github.com/fernandoroyosanchez/ovn-operator/pkg/ovncontroller"
"github.com/openstack-k8s-operators/lib-common/modules/common"
"github.com/openstack-k8s-operators/lib-common/modules/common/condition"
"github.com/openstack-k8s-operators/lib-common/modules/common/configmap"
"github.com/openstack-k8s-operators/lib-common/modules/common/daemonset"
"github.com/openstack-k8s-operators/lib-common/modules/common/env"
"github.com/openstack-k8s-operators/lib-common/modules/common/helper"
"github.com/openstack-k8s-operators/lib-common/modules/common/job"
"github.com/openstack-k8s-operators/lib-common/modules/common/labels"
nad "github.com/openstack-k8s-operators/lib-common/modules/common/networkattachment"
common_rbac "github.com/openstack-k8s-operators/lib-common/modules/common/rbac"
"github.com/openstack-k8s-operators/lib-common/modules/common/util"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
)
const (
// TunnelNetworkAttachment is the name of the network attachment
// that will be used for overlay tenant networking. If present in
// the list of attachments, OvnEncapIP is set to this interface's
// IP.
TunnelNetworkAttachmentName = "tenant"
)
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
// getlog returns a logger object with a prefix of "conroller.name" and aditional controller context fields
func (r *OVNControllerReconciler) GetLogger(ctx context.Context) logr.Logger {
return log.FromContext(ctx).WithName("Controllers").WithName("OVNController")
}
// OVNControllerReconciler reconciles a OVNController object
type OVNControllerReconciler struct {
client.Client
Kclient kubernetes.Interface
Scheme *runtime.Scheme
}
// GetClient -
func (r *OVNControllerReconciler) GetClient() client.Client {
return r.Client
}
//+kubebuilder:rbac:groups=ovn.openstack.org,resources=ovncontrollers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=ovn.openstack.org,resources=ovncontrollers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=ovn.openstack.org,resources=ovncontrollers/finalizers,verbs=update
//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete;
//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;
//+kubebuilder:rbac:groups=apps,resources=daemonsets,verbs=create;delete;get;list;patch;update;watch
//+kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;patch;update;delete;
//+kubebuilder:rbac:groups=ovn.openstack.org,resources=ovndbclusters,verbs=get;list;watch;
//+kubebuilder:rbac:groups=k8s.cni.cncf.io,resources=network-attachment-definitions,verbs=create;delete;get;list;patch;update;watch
// service account, role, rolebinding
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=get;list;watch;create;update
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=get;list;watch;create;update
// service account permissions that are needed to grant permission to the above
// +kubebuilder:rbac:groups="security.openshift.io",resourceNames=anyuid;privileged,resources=securitycontextconstraints,verbs=use
// +kubebuilder:rbac:groups="",resources=pods,verbs=create;delete;get;list;patch;update;watch
func (r *OVNControllerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, _err error) {
Log := r.GetLogger(ctx)
// Fetch OVNController instance
instance := &v1beta1.OVNController{}
err := r.Client.Get(ctx, req.NamespacedName, instance)
if err != nil {
if k8s_errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected.
// For additional cleanup logic use finalizers. Return and don't requeue.
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
return ctrl.Result{}, err
}
helper, err := helper.NewHelper(
instance,
r.Client,
r.Kclient,
r.Scheme,
Log,
)
if err != nil {
return ctrl.Result{}, err
}
// Always patch the instance status when exiting this function so we can persist any changes.
defer func() {
// update the Ready condition based on the sub conditions
if instance.Status.Conditions.AllSubConditionIsTrue() {
instance.Status.Conditions.MarkTrue(
condition.ReadyCondition, condition.ReadyMessage)
} else {
// something is not ready so reset the Ready condition
instance.Status.Conditions.MarkUnknown(
condition.ReadyCondition, condition.InitReason, condition.ReadyInitMessage)
// and recalculate it based on the state of the rest of the conditions
instance.Status.Conditions.Set(
instance.Status.Conditions.Mirror(condition.ReadyCondition))
}
err := helper.PatchInstance(ctx, instance)
if err != nil {
_err = err
return
}
}()
// If we're not deleting this and the service object doesn't have our finalizer, add it.
if instance.DeletionTimestamp.IsZero() && controllerutil.AddFinalizer(instance, helper.GetFinalizer()) {
return ctrl.Result{}, nil
}
//
// initialize status
//
if instance.Status.Conditions == nil {
instance.Status.Conditions = condition.Conditions{}
// initialize conditions used later as Status=Unknown
cl := condition.CreateList(
condition.UnknownCondition(condition.InputReadyCondition, condition.InitReason, condition.InputReadyInitMessage),
condition.UnknownCondition(condition.ServiceConfigReadyCondition, condition.InitReason, condition.ServiceConfigReadyInitMessage),
condition.UnknownCondition(condition.NetworkAttachmentsReadyCondition, condition.InitReason, condition.NetworkAttachmentsReadyInitMessage),
condition.UnknownCondition(condition.DeploymentReadyCondition, condition.InitReason, condition.DeploymentReadyInitMessage),
condition.UnknownCondition(condition.ServiceAccountReadyCondition, condition.InitReason, condition.ServiceAccountReadyInitMessage),
condition.UnknownCondition(condition.RoleReadyCondition, condition.InitReason, condition.RoleReadyInitMessage),
condition.UnknownCondition(condition.RoleBindingReadyCondition, condition.InitReason, condition.RoleBindingReadyInitMessage),
)
instance.Status.Conditions.Init(&cl)
// Register overall status immediately to have an early feedback e.g. in the cli
return ctrl.Result{}, nil
}
if instance.Status.Hash == nil {
instance.Status.Hash = map[string]string{}
}
if instance.Status.NetworkAttachments == nil {
instance.Status.NetworkAttachments = map[string][]string{}
}
// Handle service delete
if !instance.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, instance, helper)
}
// Handle non-deleted clusters
return r.reconcileNormal(ctx, instance, helper)
}
// SetupWithManager sets up the controller with the Manager.
func (r *OVNControllerReconciler) SetupWithManager(mgr ctrl.Manager, ctx context.Context) error {
crs := &v1beta1.OVNControllerList{}
return ctrl.NewControllerManagedBy(mgr).
For(&v1beta1.OVNController{}).
Owns(&corev1.ConfigMap{}).
Owns(&batchv1.Job{}).
Owns(&netattdefv1.NetworkAttachmentDefinition{}).
Owns(&appsv1.DaemonSet{}).
Owns(&corev1.ServiceAccount{}).
Owns(&rbacv1.Role{}).
Owns(&rbacv1.RoleBinding{}).
Watches(&source.Kind{Type: &v1beta1.OVNDBCluster{}}, handler.EnqueueRequestsFromMapFunc(v1beta1.OVNDBClusterNamespaceMapFunc(crs, mgr.GetClient(), r.GetLogger(ctx)))).
Complete(r)
}
func (r *OVNControllerReconciler) reconcileDelete(ctx context.Context, instance *v1beta1.OVNController, helper *helper.Helper) (ctrl.Result, error) {
Log := r.GetLogger(ctx)
Log.Info("Reconciling Service delete")
// Service is deleted so remove the finalizer.
controllerutil.RemoveFinalizer(instance, helper.GetFinalizer())
Log.Info("Reconciled Service delete successfully")
return ctrl.Result{}, nil
}
func (r *OVNControllerReconciler) reconcileInit(
ctx context.Context,
instance *v1beta1.OVNController,
helper *helper.Helper,
) (ctrl.Result, error) {
Log := r.GetLogger(ctx)
Log.Info("Reconciling Service init")
//TODO(slaweq):
// * read status of the external IDs
// * if external IDs are different than required once, change them
Log.Info("Reconciled Service init successfully")
return ctrl.Result{}, nil
}
func (r *OVNControllerReconciler) reconcileUpdate(ctx context.Context, instance *v1beta1.OVNController, helper *helper.Helper) (ctrl.Result, error) {
Log := r.GetLogger(ctx)
Log.Info("Reconciling Service update")
Log.Info("Reconciled Service update successfully")
return ctrl.Result{}, nil
}
func (r *OVNControllerReconciler) reconcileUpgrade(ctx context.Context, instance *v1beta1.OVNController, helper *helper.Helper) (ctrl.Result, error) {
Log := r.GetLogger(ctx)
Log.Info("Reconciling Service upgrade")
Log.Info("Reconciled Service upgrade successfully")
return ctrl.Result{}, nil
}
func (r *OVNControllerReconciler) reconcileNormal(ctx context.Context, instance *v1beta1.OVNController, helper *helper.Helper) (ctrl.Result, error) {
Log := r.GetLogger(ctx)
Log.Info("Reconciling Service")
// Service account, role, binding
rbacRules := []rbacv1.PolicyRule{
{
APIGroups: []string{"security.openshift.io"},
ResourceNames: []string{"anyuid", "privileged"},
Resources: []string{"securitycontextconstraints"},
Verbs: []string{"use"},
},
{
APIGroups: []string{""},
Resources: []string{"pods"},
Verbs: []string{"create", "get", "list", "watch", "update", "patch", "delete"},
},
}
rbacResult, err := common_rbac.ReconcileRbac(ctx, helper, instance, rbacRules)
if err != nil {
return rbacResult, err
} else if (rbacResult != ctrl.Result{}) {
return rbacResult, nil
}
// ConfigMap
configMapVars := make(map[string]env.Setter)
instance.Status.Conditions.MarkTrue(condition.InputReadyCondition, condition.InputReadyMessage)
//
// create Configmap required for OVNController input
// - %-scripts configmap holding scripts to e.g. bootstrap the service
//
err = r.generateServiceConfigMaps(ctx, helper, instance, &configMapVars)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
condition.ServiceConfigReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.ServiceConfigReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
//
// create hash over all the different input resources to identify if any those changed
// and a restart/recreate is required.
//
inputHash, hashChanged, err := r.createHashOfInputHashes(ctx, instance, configMapVars)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
condition.ServiceConfigReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.ServiceConfigReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
} else if hashChanged {
// Hash changed and instance status should be updated (which will be done by main defer func),
// so we need to return and reconcile again
return ctrl.Result{}, nil
}
// TODO(slaweq): configure service (ovn controller and ovs settings)
instance.Status.Conditions.MarkTrue(condition.ServiceConfigReadyCondition, condition.ServiceConfigReadyMessage)
//
// TODO check when/if Init, Update, or Upgrade should/could be skipped
//
serviceLabels := map[string]string{
common.AppSelector: ovncontroller.ServiceName,
}
// Create additional Physical Network Attachments
networkAttachments, err := ovncontroller.CreateAdditionalNetworks(ctx, helper, instance, serviceLabels)
if err != nil {
Log.Info(fmt.Sprintf("Failed to create additional networks: %s", err))
return ctrl.Result{}, err
}
networkAttachmentsNoPhysNet := []string{}
if instance.Spec.NetworkAttachments != nil && len(instance.Spec.NetworkAttachments) > 0 {
networkAttachmentsNoPhysNet = append(networkAttachmentsNoPhysNet, instance.Spec.NetworkAttachments...)
}
if instance.Spec.NetworkAttachment != "" && !contains(networkAttachmentsNoPhysNet, instance.Spec.NetworkAttachment) {
networkAttachmentsNoPhysNet = append(networkAttachmentsNoPhysNet, instance.Spec.NetworkAttachment)
}
networkAttachments = append(networkAttachments, networkAttachmentsNoPhysNet...)
sort.Strings(networkAttachments)
for _, netAtt := range networkAttachments {
_, err = nad.GetNADWithName(ctx, helper, netAtt, instance.Namespace)
if err != nil {
if k8s_errors.IsNotFound(err) {
instance.Status.Conditions.Set(condition.FalseCondition(
condition.NetworkAttachmentsReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
condition.NetworkAttachmentsReadyWaitingMessage,
netAtt))
return ctrl.Result{RequeueAfter: time.Second * 10}, fmt.Errorf("network-attachment-definition %s not found", netAtt)
}
instance.Status.Conditions.Set(condition.FalseCondition(
condition.NetworkAttachmentsReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.NetworkAttachmentsReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
}
serviceAnnotations, err := nad.CreateNetworksAnnotation(instance.Namespace, networkAttachments)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to create network annotation from %s: %w",
networkAttachments, err)
}
// Handle service init
ctrlResult, err := r.reconcileInit(ctx, instance, helper)
if err != nil {
return ctrlResult, err
} else if (ctrlResult != ctrl.Result{}) {
return ctrlResult, nil
}
// Handle service update
ctrlResult, err = r.reconcileUpdate(ctx, instance, helper)
if err != nil {
return ctrlResult, err
} else if (ctrlResult != ctrl.Result{}) {
return ctrlResult, nil
}
// Handle service upgrade
ctrlResult, err = r.reconcileUpgrade(ctx, instance, helper)
if err != nil {
return ctrlResult, err
} else if (ctrlResult != ctrl.Result{}) {
return ctrlResult, nil
}
// Define a new DaemonSet object
ovnDaemonSet, err := ovncontroller.DaemonSet(instance, inputHash, serviceLabels, serviceAnnotations)
if err != nil {
Log.Error(err, "Failed to create OVNController DaemonSet")
return ctrl.Result{}, err
}
dset := daemonset.NewDaemonSet(
ovnDaemonSet,
time.Duration(5)*time.Second,
)
ctrlResult, err = dset.CreateOrPatch(ctx, helper)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
condition.DeploymentReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.DeploymentReadyErrorMessage,
err.Error()))
return ctrlResult, err
} else if (ctrlResult != ctrl.Result{}) {
instance.Status.Conditions.Set(condition.FalseCondition(
condition.DeploymentReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
condition.DeploymentReadyRunningMessage))
return ctrlResult, nil
}
instance.Status.DesiredNumberScheduled = dset.GetDaemonSet().Status.DesiredNumberScheduled
instance.Status.NumberReady = dset.GetDaemonSet().Status.NumberReady
// verify if network attachment matches expectations
networkReady, networkAttachmentStatus, err := nad.VerifyNetworkStatusFromAnnotation(ctx, helper, networkAttachmentsNoPhysNet, serviceLabels, instance.Status.NumberReady)
if err != nil {
return ctrl.Result{}, err
}
instance.Status.NetworkAttachments = networkAttachmentStatus
if networkReady {
instance.Status.Conditions.MarkTrue(condition.NetworkAttachmentsReadyCondition, condition.NetworkAttachmentsReadyMessage)
} else {
err := fmt.Errorf("not all pods have interfaces with ips as configured in NetworkAttachments: %v", networkAttachmentsNoPhysNet)
instance.Status.Conditions.Set(condition.FalseCondition(
condition.NetworkAttachmentsReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.NetworkAttachmentsReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
if instance.Status.NumberReady == instance.Status.DesiredNumberScheduled {
instance.Status.Conditions.MarkTrue(condition.DeploymentReadyCondition, condition.DeploymentReadyMessage)
}
// create DaemonSet - end
sbCluster, err := v1beta1.GetDBClusterByType(ctx, helper, instance.Namespace, map[string]string{}, v1beta1.SBDBType)
if err != nil {
Log.Info("No SB OVNDBCluster defined, deleting external ConfigMap")
cleanupConfigMapErr := r.deleteExternalConfigMaps(ctx, helper, instance)
if cleanupConfigMapErr != nil {
Log.Error(cleanupConfigMapErr, "Failed to delete external ConfigMap")
return ctrl.Result{}, cleanupConfigMapErr
}
return ctrl.Result{}, nil
}
ep, err := sbCluster.GetExternalEndpoint()
if err != nil || ep == "" {
Log.Info("No external endpoint defined for SB OVNDBCluster, deleting external ConfigMap")
cleanupConfigMapErr := r.deleteExternalConfigMaps(ctx, helper, instance)
if cleanupConfigMapErr != nil {
Log.Error(cleanupConfigMapErr, "Failed to delete external ConfigMap")
return ctrl.Result{}, cleanupConfigMapErr
}
}
if sbCluster.Spec.NetworkAttachment != "" {
// Create ConfigMap for external dataplane consumption
// TODO(ihar) - is there any hashing mechanism for EDP config? do we trigger deploy somehow?
err = r.generateExternalConfigMaps(ctx, helper, instance, sbCluster, &configMapVars)
if err != nil {
Log.Error(err, "Failed to generate external ConfigMap")
return ctrl.Result{}, err
}
}
// create OVN Config Job - start
if instance.Status.NumberReady == instance.Status.DesiredNumberScheduled {
jobsDef, err := ovncontroller.ConfigJob(ctx, helper, r.Client, instance, sbCluster, serviceLabels)
if err != nil {
Log.Error(err, "Failed to create OVN controller configuration Job")
return ctrl.Result{}, err
}
for _, jobDef := range jobsDef {
configHashKey := v1beta1.OvnConfigHash + "-" + jobDef.Spec.Template.Spec.NodeName
configHash := instance.Status.Hash[configHashKey]
configJob := job.NewJob(
jobDef,
configHashKey,
false,
time.Duration(5)*time.Second,
configHash,
)
ctrlResult, err = configJob.DoJob(ctx, helper)
if (ctrlResult != ctrl.Result{}) {
instance.Status.Conditions.Set(
condition.FalseCondition(
condition.ServiceConfigReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
condition.ServiceConfigReadyMessage,
),
)
return ctrlResult, nil
}
if err != nil {
Log.Error(err, "Failed to configure OVN controller")
instance.Status.Conditions.Set(
condition.FalseCondition(
condition.ServiceConfigReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
condition.ServiceConfigReadyErrorMessage,
err.Error(),
),
)
return ctrl.Result{}, err
}
if configJob.HasChanged() {
instance.Status.Hash[configHashKey] = configJob.GetHash()
Log.Info(fmt.Sprintf("Job %s hash added - %s", jobDef.Name, instance.Status.Hash[configHashKey]))
}
}
instance.Status.Conditions.MarkTrue(condition.ServiceConfigReadyCondition, condition.ServiceConfigReadyMessage)
} else {
Log.Info("OVNController DaemonSet not ready yet. Configuration job cannot be started.")
return ctrl.Result{Requeue: true}, nil
}
// create OVN Config Job - end
Log.Info("Reconciled Service successfully")
return ctrl.Result{}, nil
}
// generateServiceConfigMaps - create configmaps which hold scripts and service configuration
func (r *OVNControllerReconciler) generateServiceConfigMaps(
ctx context.Context,
h *helper.Helper,
instance *v1beta1.OVNController,
envVars *map[string]env.Setter,
) error {
// Create/update configmaps from templates
cmLabels := labels.GetLabels(instance, labels.GetGroupLabel(ovncontroller.ServiceName), map[string]string{})
templateParameters := make(map[string]interface{})
if contains(instance.Spec.NetworkAttachments, TunnelNetworkAttachmentName) {
templateParameters["OvnEncapNIC"] = nad.GetNetworkIFName(TunnelNetworkAttachmentName)
} else if instance.Spec.NetworkAttachment != "" {
templateParameters["OvnEncapNIC"] = nad.GetNetworkIFName(instance.Spec.NetworkAttachment)
} else {
templateParameters["OvnEncapNIC"] = "eth0"
}
cms := []util.Template{
// ScriptsConfigMap
{
Name: fmt.Sprintf("%s-scripts", instance.Name),
Namespace: instance.Namespace,
Type: util.TemplateTypeScripts,
InstanceType: instance.Kind,
Labels: cmLabels,
ConfigOptions: templateParameters,
},
}
return configmap.EnsureConfigMaps(ctx, h, instance, cms, envVars)
}
// generateExternalConfigMaps - create configmaps for external dataplane consumption
func (r *OVNControllerReconciler) generateExternalConfigMaps(
ctx context.Context,
h *helper.Helper,
instance *v1beta1.OVNController,
sbCluster *v1beta1.OVNDBCluster,
envVars *map[string]env.Setter,
) error {
// Create/update configmaps from templates
cmLabels := labels.GetLabels(instance, labels.GetGroupLabel(ovncontroller.ServiceName), map[string]string{})
externalEndpoint, err := sbCluster.GetExternalEndpoint()
if err != nil {
return err
}
externalTemplateParameters := make(map[string]interface{})
externalTemplateParameters["OvnRemote"] = externalEndpoint
externalTemplateParameters["OvnEncapType"] = instance.Spec.ExternalIDS.OvnEncapType
cms := []util.Template{
// EDP ConfigMap
{
Name: fmt.Sprintf("%s-config", instance.Name),
Namespace: instance.Namespace,
Type: util.TemplateTypeConfig,
InstanceType: instance.Kind,
Labels: cmLabels,
ConfigOptions: externalTemplateParameters,
},
}
return configmap.EnsureConfigMaps(ctx, h, instance, cms, envVars)
}
// TODO(ihar) this function could live in lib-common
// deleteExternalConfigMaps - delete obsolete configmaps for external dataplane consumption
func (r *OVNControllerReconciler) deleteExternalConfigMaps(
ctx context.Context,
h *helper.Helper,
instance *v1beta1.OVNController,
) error {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-config", instance.Name),
Namespace: instance.Namespace,
},
}
err := h.GetClient().Delete(ctx, cm)
if err != nil && !k8s_errors.IsNotFound(err) {
return fmt.Errorf("error deleting external config map %s: %w", cm.Name, err)
}
return nil
}
// createHashOfInputHashes - creates a hash of hashes which gets added to the resources which requires a restart
// if any of the input resources change, like configs, passwords, ...
//
// returns the hash, whether the hash changed (as a bool) and any error
func (r *OVNControllerReconciler) createHashOfInputHashes(
ctx context.Context,
instance *v1beta1.OVNController,
envVars map[string]env.Setter,
) (string, bool, error) {
Log := r.GetLogger(ctx)
var hashMap map[string]string
changed := false
mergedMapVars := env.MergeEnvs([]corev1.EnvVar{}, envVars)
hash, err := util.ObjectHash(mergedMapVars)
if err != nil {
return hash, changed, err
}
if hashMap, changed = util.SetHash(instance.Status.Hash, common.InputHashName, hash); changed {
instance.Status.Hash = hashMap
Log.Info(fmt.Sprintf("Input maps hash %s - %s", common.InputHashName, hash))
}
return hash, changed, nil
}