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