Skip to content

Commit

Permalink
wip: signing key controller
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Dec 8, 2024
1 parent daac9a8 commit 57ba9b4
Show file tree
Hide file tree
Showing 9 changed files with 685 additions and 24 deletions.
3 changes: 2 additions & 1 deletion api/v1alpha1/common_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const (
)

const (
FinalizerName = "natz.zeiss.com/finalizer"
FinalizerName = "natz.zeiss.com/finalizer"
OwnerAnnotation = "natz.zeiss.com/owner"
)

// SecretValueFromSource represents the source of a secret value
Expand Down
2 changes: 1 addition & 1 deletion api/v1alpha1/nats_operator_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type NatsOperatorSpec struct {
// PublicKey is the public key that should be used to verify the JWT
PublicKey corev1.SecretReference `json:"public_key,omitempty"`
// SigningKeys is a list of references to secrets that contain the signing keys
SigningKeys []corev1.SecretReference `json:"signing_keys,omitempty"`
SigningKeys []NatsSigningKey `json:"signing_keys,omitempty"`
}

type NatsOperatorStatus struct {
Expand Down
60 changes: 60 additions & 0 deletions api/v1alpha1/nats_signing_key_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package v1alpha1

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type SigningKeyPhase string

const (
SigningKeyPhaseNone SigningKeyPhase = ""
SigningKeyPhasePending SigningKeyPhase = "Pending"
SigningKeyPhaseCreating SigningKeyPhase = "Creating"
SigningKeyPhaseSynchronized SigningKeyPhase = "Synchronized"
SigningKeyPhaseFailed SigningKeyPhase = "Failed"
)

// NatsSigningKeySpec defines the desired state of SigningKey
type NatsSigningKeySpec struct {
// DeleteSecret is a flag that indicates if the secret should be deleted.
DeleteSecret bool `json:"deleteSecret,omitempty"`
}

// NatsSigningKeyStatus defines the observed state of SigningKey
type NatsSigningKeyStatus struct {
// Conditions is an array of conditions that the operator is currently in.
Conditions []metav1.Condition `json:"conditions,omitempty" optional:"true"`
// Phase is the current phase of the operator.
//
// +kubebuilder:validation:Enum={None,Pending,Creating,Synchronized,Failed}
Phase SigningKeyPhase `json:"phase"`
// ControlPaused is a flag that indicates if the operator is paused.
ControlPaused bool `json:"controlPaused,omitempty" optional:"true"`
// LastUpdate is the timestamp of the last update.
LastUpdate metav1.Time `json:"lastUpdate,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status

// NatsSigningKey is the Schema for the natssigningkeys API
type NatsSigningKey struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

Spec NatsSigningKeySpec `json:"spec,omitempty"`
Status NatsSigningKeyStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true

// NatsSigningKeyList contains a list of NatsSigningKey
type NatsSigningKeyList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []NatsSigningKey `json:"items"`
}

func init() {
SchemeBuilder.Register(&NatsSigningKey{}, &NatsSigningKeyList{})
}
103 changes: 101 additions & 2 deletions api/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 152 additions & 0 deletions controllers/natssigningkey_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package controllers

import (
"context"

"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"

natsv1alpha1 "github.com/zeiss/natz-operator/api/v1alpha1"
"github.com/zeiss/natz-operator/pkg/status"
"github.com/zeiss/pkg/conv"
"github.com/zeiss/pkg/slices"
"github.com/zeiss/pkg/utilx"
corev1 "k8s.io/api/core/v1"
)

// NatsSigningKeyReconciler ...
type NatsSigningKeyReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
}

// NewNatsSigningKeyReconciler ...
func NewNatsSigningKeyReconciler(mgr ctrl.Manager) *NatsSigningKeyReconciler {
return &NatsSigningKeyReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Recorder: mgr.GetEventRecorderFor(EventRecorderLabel),
}
}

//+kubebuilder:rbac:groups=natz.zeiss.com,resources=natssigningkeys,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=natz.zeiss.com,resources=natssigningkeys/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=natz.zeiss.com,resources=natssigningkeys/finalizers,verbs=update
//+kubebuilder:rbac:groups=,resources=secrets,verbs=get;list;watch;create;update;patch;delete

// Reconcile ...
// nolint:gocyclo
func (r *NatsSigningKeyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)

log.Info("reconcile signing key", "name", req.Name, "namespace", req.Namespace)

sk := &natsv1alpha1.NatsSigningKey{}
if err := r.Get(ctx, req.NamespacedName, sk); err != nil {
// Request object not found, could have been deleted after reconcile request.
return ctrl.Result{}, client.IgnoreNotFound(err)
}

if !sk.ObjectMeta.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, sk)
}

return r.reconcileResources(ctx, sk)
}

func (r *NatsSigningKeyReconciler) reconcileResources(ctx context.Context, sk *natsv1alpha1.NatsSigningKey) (ctrl.Result, error) {
log := log.FromContext(ctx)

err := r.reconcileStatus(ctx, sk)
if err != nil {
log.Error(err, "failed to reconcile status", "name", sk.Name, "namespace", sk.Namespace)
return ctrl.Result{}, err
}

return r.ManageSuccess(ctx, sk)
}

func (r *NatsSigningKeyReconciler) reconcileStatus(ctx context.Context, sk *natsv1alpha1.NatsSigningKey) error {
log := log.FromContext(ctx)

log.Info("reconcile status", "name", sk.Name, "namespace", sk.Namespace)

phase := natsv1alpha1.SigningKeyPhaseSynchronized

if sk.Status.Phase != phase {
sk.Status.Phase = phase

return r.Status().Update(ctx, sk)
}

return nil
}

func (r *NatsSigningKeyReconciler) reconcileDelete(ctx context.Context, sk *natsv1alpha1.NatsSigningKey) (ctrl.Result, error) {
// Remove our finalizer from the list.
controllerutil.RemoveFinalizer(sk, natsv1alpha1.FinalizerName)

if !sk.DeletionTimestamp.IsZero() {
// Remove our finalizer from the list.
controllerutil.RemoveFinalizer(sk, natsv1alpha1.FinalizerName)

// Stop reconciliation as the object is being deleted.
return ctrl.Result{}, r.Update(ctx, sk)
}

return ctrl.Result{Requeue: true}, nil
}

// IsCreating ...
func (r *NatsSigningKeyReconciler) IsCreating(obj *natsv1alpha1.NatsSigningKey) bool {
return utilx.Or(obj.Status.Conditions == nil, slices.Len(obj.Status.Conditions) == 0)
}

// IsSynchronized ...
func (r *NatsSigningKeyReconciler) IsSynchronized(obj *natsv1alpha1.NatsSigningKey) bool {
return obj.Status.Phase == natsv1alpha1.SigningKeyPhaseSynchronized
}

// ManageSuccess ...
func (r *NatsSigningKeyReconciler) ManageSuccess(ctx context.Context, obj *natsv1alpha1.NatsSigningKey) (ctrl.Result, error) {
if r.IsSynchronized(obj) {
return ctrl.Result{}, nil
}

status.SetNatzSigningKeyCondition(obj, status.NewSigningKeySychronizedCondition(obj))

if r.IsCreating(obj) {
return ctrl.Result{Requeue: true}, nil
}

if err := r.Client.Status().Update(ctx, obj); err != nil {
return ctrl.Result{}, err
}

if !obj.ObjectMeta.DeletionTimestamp.IsZero() {
return ctrl.Result{Requeue: true}, nil
}

if r.IsCreating(obj) {
return ctrl.Result{Requeue: true}, nil
}

r.Recorder.Event(obj, corev1.EventTypeNormal, conv.String(EventReasonOperatorSynchronized), "operator synchronized")

return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *NatsSigningKeyReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&natsv1alpha1.NatsSigningKey{}).
Owns(&corev1.Secret{}).
WithEventFilter(predicate.Or(predicate.GenerationChangedPredicate{}, predicate.LabelChangedPredicate{})).
Complete(r)
}
Loading

0 comments on commit 57ba9b4

Please sign in to comment.