[OOM-K8S-CERT-EXTERNAL-PROVIDER] Rename variables to readable.
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / certservice-controller / certservice_issuer_reconciler.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 certservice_controller
27
28 import (
29         "context"
30         "fmt"
31         "github.com/go-logr/logr"
32         core "k8s.io/api/core/v1"
33         apierrors "k8s.io/apimachinery/pkg/api/errors"
34         "k8s.io/apimachinery/pkg/types"
35         "k8s.io/client-go/tools/record"
36         "k8s.io/utils/clock"
37         "onap.org/oom-certservice/k8s-external-provider/src/api"
38         provisioners "onap.org/oom-certservice/k8s-external-provider/src/certservice-provisioner"
39         ctrl "sigs.k8s.io/controller-runtime"
40         "sigs.k8s.io/controller-runtime/pkg/client"
41 )
42
43 // CertServiceIssuerReconciler reconciles a CertServiceIssuer object
44 type CertServiceIssuerReconciler struct {
45         client.Client
46         Log      logr.Logger
47         Clock    clock.Clock
48         Recorder record.EventRecorder
49 }
50
51 // Reconcile will read and validate the CertServiceIssuer resources, it will set the
52 // status condition ready to true if everything is right.
53 func (reconciler *CertServiceIssuerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
54         ctx := context.Background()
55         log := reconciler.Log.WithValues("certservice-issuer-controller", req.NamespacedName)
56
57         issuer := new(api.CertServiceIssuer)
58         if err := reconciler.Client.Get(ctx, req.NamespacedName, issuer); err != nil {
59                 log.Error(err, "failed to retrieve CertServiceIssuer resource")
60                 return ctrl.Result{}, client.IgnoreNotFound(err)
61         }
62
63         statusReconciler := newStatusReconciler(reconciler, issuer, log)
64         if err := validateCertServiceIssuerSpec(issuer.Spec); err != nil {
65                 log.Error(err, "failed to validate CertServiceIssuer resource")
66                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Validation", "Failed to validate resource: %v", err)
67                 return ctrl.Result{}, err
68         }
69
70         // Fetch the provisioner password
71         var secret core.Secret
72         secretNamespaceName := types.NamespacedName{
73                 Namespace: req.Namespace,
74                 Name:      issuer.Spec.KeyRef.Name,
75         }
76         if err := reconciler.Client.Get(ctx, secretNamespaceName, &secret); err != nil {
77                 log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
78                 if apierrors.IsNotFound(err) {
79                         statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
80                 } else {
81                         statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "Failed to retrieve provisioner secret: %v", err)
82                 }
83                 return ctrl.Result{}, err
84         }
85         password, ok := secret.Data[issuer.Spec.KeyRef.Key]
86         if !ok {
87                 err := fmt.Errorf("secret %s does not contain key %s", secret.Name, issuer.Spec.KeyRef.Key)
88                 log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
89                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
90                 return ctrl.Result{}, err
91         }
92
93         // Initialize and store the provisioner
94         provisioner, err := provisioners.New(issuer, password)
95         if err != nil {
96                 log.Error(err, "failed to initialize provisioner")
97                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "failed initialize provisioner")
98                 return ctrl.Result{}, err
99         }
100         provisioners.Store(req.NamespacedName, provisioner)
101
102         return ctrl.Result{}, statusReconciler.Update(ctx, api.ConditionTrue, "Verified", "CertServiceIssuer verified and ready to sign certificates")
103 }
104
105 // SetupWithManager initializes the CertServiceIssuer controller into the controller
106 // runtime.
107 func (reconciler *CertServiceIssuerReconciler) SetupWithManager(manager ctrl.Manager) error {
108         return ctrl.NewControllerManagedBy(manager).
109                 For(&api.CertServiceIssuer{}).
110                 Complete(reconciler)
111 }
112
113 func validateCertServiceIssuerSpec(issuerSpec api.CertServiceIssuerSpec) error {
114         switch {
115         case issuerSpec.URL == "":
116                 return fmt.Errorf("spec.url cannot be empty")
117         case issuerSpec.KeyRef.Name == "":
118                 return fmt.Errorf("spec.keyRef.name cannot be empty")
119         case issuerSpec.KeyRef.Key == "":
120                 return fmt.Errorf("spec.keyRef.key cannot be empty")
121         default:
122                 return nil
123         }
124 }