[OOM-K8S-CERT-EXTERNAL-PROVIDER] Refactoring & code improvements
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / updater / cmpv2_issuer_status_updater.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (c) 2019 Smallstep Labs, Inc.
6  * Modifications copyright (C) 2020 Nokia. All rights reserved.
7  * ================================================================================
8  * This source code was copied from the following git repository:
9  * https://github.com/smallstep/step-issuer
10  * The source code was modified for usage in the ONAP project.
11  * ================================================================================
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  *
16  *      http://www.apache.org/licenses/LICENSE-2.0
17  *
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  * ============LICENSE_END=========================================================
24  */
25
26 package updater
27
28 import (
29         "context"
30         "fmt"
31
32         meta "k8s.io/apimachinery/pkg/apis/meta/v1"
33         "k8s.io/client-go/tools/record"
34         "k8s.io/utils/clock"
35         "sigs.k8s.io/controller-runtime/pkg/client"
36
37         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
38         "onap.org/oom-certservice/k8s-external-provider/src/leveledlogger"
39 )
40
41 type CMPv2IssuerStatusUpdater struct {
42         client   client.Client
43         recorder record.EventRecorder
44         issuer   *cmpv2api.CMPv2Issuer
45         clock    clock.Clock
46         logger   leveledlogger.Logger
47 }
48
49 func NewCMPv2IssuerStatusUpdater(client client.Client, recorder record.EventRecorder, issuer *cmpv2api.CMPv2Issuer, clock clock.Clock, log leveledlogger.Logger) *CMPv2IssuerStatusUpdater {
50         return &CMPv2IssuerStatusUpdater{
51                 client:   client,
52                 recorder: recorder,
53                 issuer:   issuer,
54                 clock:    clock,
55                 logger:   log,
56         }
57 }
58
59 func (instance *CMPv2IssuerStatusUpdater) Update(ctx context.Context, status cmpv2api.ConditionStatus, reason, message string, args ...interface{}) error {
60         completeMessage := fmt.Sprintf(message, args...)
61         instance.setCondition(status, reason, completeMessage)
62
63         FireEventIssuer(instance.recorder, instance.issuer, status, reason, completeMessage)
64
65         return instance.client.Update(ctx, instance.issuer)
66 }
67
68 func (instance *CMPv2IssuerStatusUpdater) UpdateNoError(ctx context.Context, status cmpv2api.ConditionStatus, reason, message string, args ...interface{}) {
69         if err := instance.Update(ctx, status, reason, message, args...); err != nil {
70                 instance.logger.Error(err, "failed to update", "status", status, "reason", reason)
71         }
72 }
73
74 // setCondition will set a 'condition' on the given cmpv2api.CMPv2Issuer resource.
75 //
76 // - If no condition of the same type already exists, the condition will be
77 //   inserted with the LastTransitionTime set to the current time.
78 // - If a condition of the same type and state already exists, the condition
79 //   will be updated but the LastTransitionTime will not be modified.
80 // - If a condition of the same type and different state already exists, the
81 //   condition will be updated and the LastTransitionTime set to the current
82 //   time.
83 func (instance *CMPv2IssuerStatusUpdater) setCondition(status cmpv2api.ConditionStatus, reason, message string) {
84         now := meta.NewTime(instance.clock.Now())
85         issuerCondition := cmpv2api.CMPv2IssuerCondition{
86                 Type:               cmpv2api.ConditionReady,
87                 Status:             status,
88                 Reason:             reason,
89                 Message:            message,
90                 LastTransitionTime: &now,
91         }
92
93         // Search through existing conditions
94         for i, condition := range instance.issuer.Status.Conditions {
95                 // Skip unrelated conditions
96                 if condition.Type != cmpv2api.ConditionReady {
97                         continue
98                 }
99
100                 // If this update doesn't contain a state transition, we don't update
101                 // the conditions LastTransitionTime to Now()
102                 if condition.Status == status {
103                         issuerCondition.LastTransitionTime = condition.LastTransitionTime
104                 } else {
105                         instance.logger.Info("found status change for CMPv2Issuer condition; setting lastTransitionTime", "condition", condition.Type, "old_status", condition.Status, "new_status", status, "time", now.Time)
106                 }
107
108                 // Overwrite the existing condition
109                 instance.issuer.Status.Conditions[i] = issuerCondition
110                 return
111         }
112
113         // If we've not found an existing condition of this type, we simply insert
114         // the new condition into the slice.
115         instance.issuer.Status.Conditions = append(instance.issuer.Status.Conditions, issuerCondition)
116         instance.logger.Info("setting lastTransitionTime for CMPv2Issuer condition", "condition", cmpv2api.ConditionReady, "time", now.Time)
117 }