Skip to content

Commit

Permalink
refactor: use refresh interface
Browse files Browse the repository at this point in the history
  • Loading branch information
duffney committed Jul 24, 2024
1 parent c57748b commit 7f195ad
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 367 deletions.
3 changes: 3 additions & 0 deletions api/v1beta1/namespacedkeymanagementprovider_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ type NamespacedKeyManagementProviderSpec struct {
// Name of the key management provider
Type string `json:"type,omitempty"`

// +kubebuilder:default="1m"
Interval string `json:"interval,omitempty"`

// +kubebuilder:pruning:PreserveUnknownFields
// Parameters of the key management provider
Parameters runtime.RawExtension `json:"parameters,omitempty"`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ spec:
description: NamespacedKeyManagementProviderSpec defines the desired state
of NamespacedKeyManagementProvider
properties:
interval:
default: 1m
type: string
parameters:
description: Parameters of the key management provider
type: object
Expand Down
118 changes: 9 additions & 109 deletions pkg/controllers/namespaceresource/keymanagementprovider_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,17 @@ package namespaceresource

import (
"context"
"encoding/json"
"fmt"
"maps"

"github.com/ratify-project/ratify/internal/constants"
_ "github.com/ratify-project/ratify/pkg/keymanagementprovider/azurekeyvault" // register azure key vault key management provider
_ "github.com/ratify-project/ratify/pkg/keymanagementprovider/inline" // register inline key management provider
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/ratify-project/ratify/pkg/keymanagementprovider/refresh"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/predicate"

configv1beta1 "github.com/ratify-project/ratify/api/v1beta1"
cutils "github.com/ratify-project/ratify/pkg/controllers/utils"
kmp "github.com/ratify-project/ratify/pkg/keymanagementprovider"
"github.com/sirupsen/logrus"
)

// KeyManagementProviderReconciler reconciles a KeyManagementProvider object
Expand All @@ -48,72 +41,22 @@ type KeyManagementProviderReconciler struct {
// +kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=namespacedkeymanagementproviders/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=namespacedkeymanagementproviders/finalizers,verbs=update
func (r *KeyManagementProviderReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := logrus.WithContext(ctx)

var resource = req.NamespacedName.String()
var keyManagementProvider configv1beta1.NamespacedKeyManagementProvider

logger.Infof("reconciling namespaced key management provider '%v'", resource)

if err := r.Get(ctx, req.NamespacedName, &keyManagementProvider); err != nil {
if apierrors.IsNotFound(err) {
logger.Infof("deletion detected, removing key management provider %v", resource)
kmp.DeleteCertificatesFromMap(resource)
kmp.DeleteKeysFromMap(resource)
} else {
logger.Error(err, "unable to fetch key management provider")
}

return ctrl.Result{}, client.IgnoreNotFound(err)
kr := refresh.KubeRefresher{
Client: r.Client,
Request: req,

Check warning on line 46 in pkg/controllers/namespaceresource/keymanagementprovider_controller.go

View check run for this annotation

Codecov / codecov/patch

pkg/controllers/namespaceresource/keymanagementprovider_controller.go#L44-L46

Added lines #L44 - L46 were not covered by tests
}

lastFetchedTime := metav1.Now()
isFetchSuccessful := false

// get certificate store list to check if certificate store is configured
// TODO: remove check in v2.0.0+
var certificateStoreList configv1beta1.CertificateStoreList
if err := r.List(ctx, &certificateStoreList); err != nil {
logger.Error(err, "unable to list certificate stores")
return ctrl.Result{}, err
}
// if certificate store is configured, return error. Only one of certificate store and key management provider can be configured
if len(certificateStoreList.Items) > 0 {
// Note: for backwards compatibility in upgrade scenarios, Ratify will only log a warning statement.
logger.Warn("Certificate Store already exists. Key management provider and certificate store should not be configured together. Please migrate to key management provider and delete certificate store.")
// check if kr.client is nil
if kr.Client == nil {
return ctrl.Result{}, fmt.Errorf("client is nil")

Check warning on line 51 in pkg/controllers/namespaceresource/keymanagementprovider_controller.go

View check run for this annotation

Codecov / codecov/patch

pkg/controllers/namespaceresource/keymanagementprovider_controller.go#L50-L51

Added lines #L50 - L51 were not covered by tests
}

provider, err := cutils.SpecToKeyManagementProvider(keyManagementProvider.Spec.Parameters.Raw, keyManagementProvider.Spec.Type)
err := kr.Refresh(ctx)

Check warning on line 54 in pkg/controllers/namespaceresource/keymanagementprovider_controller.go

View check run for this annotation

Codecov / codecov/patch

pkg/controllers/namespaceresource/keymanagementprovider_controller.go#L54

Added line #L54 was not covered by tests
if err != nil {
writeKMProviderStatus(ctx, r, &keyManagementProvider, logger, isFetchSuccessful, err.Error(), lastFetchedTime, nil)
return ctrl.Result{}, err
}

// fetch certificates and store in map
certificates, certAttributes, err := provider.GetCertificates(ctx)
if err != nil {
writeKMProviderStatus(ctx, r, &keyManagementProvider, logger, isFetchSuccessful, err.Error(), lastFetchedTime, nil)
return ctrl.Result{}, fmt.Errorf("Error fetching certificates in KMProvider %v with %v provider, error: %w", resource, keyManagementProvider.Spec.Type, err)
}

// fetch keys and store in map
keys, keyAttributes, err := provider.GetKeys(ctx)
if err != nil {
writeKMProviderStatus(ctx, r, &keyManagementProvider, logger, isFetchSuccessful, err.Error(), lastFetchedTime, nil)
return ctrl.Result{}, fmt.Errorf("Error fetching keys in KMProvider %v with %v provider, error: %w", resource, keyManagementProvider.Spec.Type, err)
}
kmp.SetCertificatesInMap(resource, certificates)
kmp.SetKeysInMap(resource, keyManagementProvider.Spec.Type, keys)
// merge certificates and keys status into one
maps.Copy(keyAttributes, certAttributes)
isFetchSuccessful = true
emptyErrorString := ""
writeKMProviderStatus(ctx, r, &keyManagementProvider, logger, isFetchSuccessful, emptyErrorString, lastFetchedTime, keyAttributes)

logger.Infof("%v certificate(s) & %v key(s) fetched for key management provider %v", len(certificates), len(keys), resource)

// returning empty result and no error to indicate we’ve successfully reconciled this object
return ctrl.Result{}, nil
return kr.Result, nil

Check warning on line 59 in pkg/controllers/namespaceresource/keymanagementprovider_controller.go

View check run for this annotation

Codecov / codecov/patch

pkg/controllers/namespaceresource/keymanagementprovider_controller.go#L59

Added line #L59 was not covered by tests
}

// SetupWithManager sets up the controller with the Manager.
Expand All @@ -127,46 +70,3 @@ func (r *KeyManagementProviderReconciler) SetupWithManager(mgr ctrl.Manager) err
For(&configv1beta1.NamespacedKeyManagementProvider{}).WithEventFilter(pred).
Complete(r)
}

// writeKMProviderStatus updates the status of the key management provider resource
func writeKMProviderStatus(ctx context.Context, r client.StatusClient, keyManagementProvider *configv1beta1.NamespacedKeyManagementProvider, logger *logrus.Entry, isSuccess bool, errorString string, operationTime metav1.Time, kmProviderStatus kmp.KeyManagementProviderStatus) {
if isSuccess {
updateKMProviderSuccessStatus(keyManagementProvider, &operationTime, kmProviderStatus)
} else {
updateKMProviderErrorStatus(keyManagementProvider, errorString, &operationTime)
}
if statusErr := r.Status().Update(ctx, keyManagementProvider); statusErr != nil {
logger.Error(statusErr, ",unable to update key management provider error status")
}
}

// updateKMProviderErrorStatus updates the key management provider status with error, brief error and last fetched time
func updateKMProviderErrorStatus(keyManagementProvider *configv1beta1.NamespacedKeyManagementProvider, errorString string, operationTime *metav1.Time) {
// truncate brief error string to maxBriefErrLength
briefErr := errorString
if len(errorString) > constants.MaxBriefErrLength {
briefErr = fmt.Sprintf("%s...", errorString[:constants.MaxBriefErrLength])
}
keyManagementProvider.Status.IsSuccess = false
keyManagementProvider.Status.Error = errorString
keyManagementProvider.Status.BriefError = briefErr
keyManagementProvider.Status.LastFetchedTime = operationTime
}

// updateKMProviderSuccessStatus updates the key management provider status if status argument is non nil
// Success status includes last fetched time and other provider-specific properties
func updateKMProviderSuccessStatus(keyManagementProvider *configv1beta1.NamespacedKeyManagementProvider, lastOperationTime *metav1.Time, kmProviderStatus kmp.KeyManagementProviderStatus) {
keyManagementProvider.Status.IsSuccess = true
keyManagementProvider.Status.Error = ""
keyManagementProvider.Status.BriefError = ""
keyManagementProvider.Status.LastFetchedTime = lastOperationTime

if kmProviderStatus != nil {
jsonString, _ := json.Marshal(kmProviderStatus)

raw := runtime.RawExtension{
Raw: jsonString,
}
keyManagementProvider.Status.Properties = raw
}
}
Loading

0 comments on commit 7f195ad

Please sign in to comment.