[OOM-K8S-CERT-EXTERNAL-PROVIDER] Mock implementaion enhanced
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / certservice-controller / certificaterequest_reconciler.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright 2019 The cert-manager authors.
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         "onap.org/oom-certservice/k8s-external-provider/src/api"
32         provisioners "onap.org/oom-certservice/k8s-external-provider/src/certservice-provisioner"
33
34         "github.com/go-logr/logr"
35         apiutil "github.com/jetstack/cert-manager/pkg/api/util"
36         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
37         cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
38         core "k8s.io/api/core/v1"
39         apierrors "k8s.io/apimachinery/pkg/api/errors"
40         "k8s.io/apimachinery/pkg/types"
41         "k8s.io/client-go/tools/record"
42         ctrl "sigs.k8s.io/controller-runtime"
43         "sigs.k8s.io/controller-runtime/pkg/client"
44 )
45
46 // CertificateRequestReconciler reconciles a CertServiceIssuer object.
47 type CertificateRequestReconciler struct {
48         client.Client
49         Log      logr.Logger
50         Recorder record.EventRecorder
51 }
52
53 // Reconcile will read and validate a CertServiceIssuer resource associated to the
54 // CertificateRequest resource, and it will sign the CertificateRequest with the
55 // provisioner in the CertServiceIssuer.
56 func (reconciler *CertificateRequestReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
57         ctx := context.Background()
58         log := reconciler.Log.WithValues("certificaterequest", req.NamespacedName)
59
60         // Fetch the CertificateRequest resource being reconciled.
61         // Just ignore the request if the certificate request has been deleted.
62         certificateRequest := new(cmapi.CertificateRequest)
63         if err := reconciler.Client.Get(ctx, req.NamespacedName, certificateRequest); err != nil {
64                 if apierrors.IsNotFound(err) {
65                         return ctrl.Result{}, nil
66                 }
67
68                 log.Error(err, "failed to retrieve CertificateRequest resource")
69                 return ctrl.Result{}, err
70         }
71
72         // Check the CertificateRequest's issuerRef and if it does not match the api
73         // group name, log a message at a debug level and stop processing.
74         if certificateRequest.Spec.IssuerRef.Group != "" && certificateRequest.Spec.IssuerRef.Group != api.GroupVersion.Group {
75                 log.V(4).Info("resource does not specify an issuerRef group name that we are responsible for", "group", certificateRequest.Spec.IssuerRef.Group)
76                 return ctrl.Result{}, nil
77         }
78
79         // If the certificate data is already set then we skip this request as it
80         // has already been completed in the past.
81         if len(certificateRequest.Status.Certificate) > 0 {
82                 log.V(4).Info("existing certificate data found in status, skipping already completed CertificateRequest")
83                 return ctrl.Result{}, nil
84         }
85
86         // Fetch the CertServiceIssuer resource
87         issuer := api.CertServiceIssuer{}
88         issuerNamespaceName := types.NamespacedName{
89                 Namespace: req.Namespace,
90                 Name:      certificateRequest.Spec.IssuerRef.Name,
91         }
92         if err := reconciler.Client.Get(ctx, issuerNamespaceName, &issuer); err != nil {
93                 log.Error(err, "failed to retrieve CertServiceIssuer resource", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
94                 _ = reconciler.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve CertServiceIssuer resource %s: %v", issuerNamespaceName, err)
95                 return ctrl.Result{}, err
96         }
97
98         // Check if the CertServiceIssuer resource has been marked Ready
99         if !certServiceIssuerHasCondition(issuer, api.CertServiceIssuerCondition{Type: api.ConditionReady, Status: api.ConditionTrue}) {
100                 err := fmt.Errorf("resource %s is not ready", issuerNamespaceName)
101                 log.Error(err, "failed to retrieve CertServiceIssuer resource", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
102                 _ = reconciler.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "CertServiceIssuer resource %s is not Ready", issuerNamespaceName)
103                 return ctrl.Result{}, err
104         }
105
106         // Load the provisioner that will sign the CertificateRequest
107         provisioner, ok := provisioners.Load(issuerNamespaceName)
108         if !ok {
109                 err := fmt.Errorf("provisioner %s not found", issuerNamespaceName)
110                 log.Error(err, "failed to provisioner for CertServiceIssuer resource")
111                 _ = reconciler.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to load provisioner for CertServiceIssuer resource %s", issuerNamespaceName)
112                 return ctrl.Result{}, err
113         }
114
115         // Sign CertificateRequest
116         signedPEM, trustedCAs, err := provisioner.Sign(ctx, certificateRequest)
117         if err != nil {
118                 log.Error(err, "failed to sign certificate request")
119                 return ctrl.Result{}, reconciler.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonFailed, "Failed to sign certificate request: %v", err)
120         }
121         certificateRequest.Status.Certificate = signedPEM
122         certificateRequest.Status.CA = trustedCAs
123
124         return ctrl.Result{}, reconciler.setStatus(ctx, certificateRequest, cmmeta.ConditionTrue, cmapi.CertificateRequestReasonIssued, "Certificate issued")
125 }
126
127 // SetupWithManager initializes the CertificateRequest controller into the
128 // controller runtime.
129 func (reconciler *CertificateRequestReconciler) SetupWithManager(manager ctrl.Manager) error {
130         return ctrl.NewControllerManagedBy(manager).
131                 For(&cmapi.CertificateRequest{}).
132                 Complete(reconciler)
133 }
134
135 // certServiceIssuerHasCondition will return true if the given CertServiceIssuer resource has
136 // a condition matching the provided CertServiceIssuerCondition. Only the Type and
137 // Status field will be used in the comparison, meaning that this function will
138 // return 'true' even if the Reason, Message and LastTransitionTime fields do
139 // not match.
140 func certServiceIssuerHasCondition(issuer api.CertServiceIssuer, condition api.CertServiceIssuerCondition) bool {
141         existingConditions := issuer.Status.Conditions
142         for _, cond := range existingConditions {
143                 if condition.Type == cond.Type && condition.Status == cond.Status {
144                         return true
145                 }
146         }
147         return false
148 }
149
150 func (reconciler *CertificateRequestReconciler) setStatus(ctx context.Context, certificateRequest *cmapi.CertificateRequest, status cmmeta.ConditionStatus, reason, message string, args ...interface{}) error {
151         completeMessage := fmt.Sprintf(message, args...)
152         apiutil.SetCertificateRequestCondition(certificateRequest, cmapi.CertificateRequestConditionReady, status, reason, completeMessage)
153
154         // Fire an Event to additionally inform users of the change
155         eventType := core.EventTypeNormal
156         if status == cmmeta.ConditionFalse {
157                 eventType = core.EventTypeWarning
158         }
159         reconciler.Recorder.Event(certificateRequest, eventType, reason, completeMessage)
160
161         return reconciler.Client.Status().Update(ctx, certificateRequest)
162 }