Skip to content

Commit

Permalink
Implement contollers logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jovmilan95 committed May 21, 2024
1 parent c08a533 commit 5a4fece
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 6 deletions.
4 changes: 2 additions & 2 deletions config/samples/email_v1_emailsenderconfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ metadata:
app.kubernetes.io/managed-by: kustomize
name: emailsenderconfig-sample
spec:
apiTokenSecretRef: "08c775409a7869f59eda96b11efdb2f5"
senderEmail: "[email protected]"
apiTokenSecretRef: "mailersenttoken"
senderEmail: "[email protected]"
7 changes: 7 additions & 0 deletions config/samples/mailersentsecret.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
apiVersion: v1
data:
apiToken: bWxzbi44NGMxNWUzNjI1MTgyN2NkZjVkY2QyZDc4NjcyODAwN2ZmNjEzYzllZjlmMGMwM2QxZjJjNDk0YzBmYTUwNGJm
kind: Secret
metadata:
creationTimestamp: null
name: mailersenttoken
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ require (
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/imdario/mergo v0.3.6 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailersend/mailersend-go v1.5.1 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@ github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
Expand All @@ -67,6 +70,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailersend/mailersend-go v1.5.1 h1:CRVTvzZi858V+x/bxDiNwRYve8GPP6irmjrTQzDHbF4=
github.com/mailersend/mailersend-go v1.5.1/go.mod h1:4MeiOnzmjWCsXRNdjg6NGzsijsVrmQ8E/T003/ystQU=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg=
Expand Down
97 changes: 95 additions & 2 deletions internal/controller/email_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ package controller

import (
"context"
"fmt"

"github.com/mailersend/mailersend-go"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"

emailv1 "email-operator/api/v1"
)
Expand All @@ -47,9 +53,95 @@ type EmailReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *EmailReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
logger := log.FromContext(ctx)
// Fetch the Email instance
email := &emailv1.Email{}
err := r.Get(ctx, req.NamespacedName, email)
if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}

// TODO(user): your logic here
// Log the creation or update action
if email.Generation == 1 {
logger.Info("Created new Email", "Email", email.Name)
} else {
logger.Info("Updated existing Email", "Email", email.Name)
}

// Fetch the EmailSenderConfig instance
emailSenderConfig := &emailv1.EmailSenderConfig{}
err = r.Get(ctx, types.NamespacedName{Name: email.Spec.SenderConfigRef, Namespace: req.Namespace}, emailSenderConfig)
if err != nil {
email.Status.DeliveryStatus = "Failed"
if errors.IsNotFound(err) {
email.Status.Error = fmt.Sprintf("EmailSenderConfig %s not found", email.Spec.SenderConfigRef)
} else {
email.Status.Error = fmt.Sprintf("Failed to get EmailSenderConfig: %v", err)
}
if updateErr := r.Status().Update(ctx, email); updateErr != nil {
logger.Error(updateErr, "Failed to update Email status")
return ctrl.Result{}, updateErr
}
return ctrl.Result{}, err
}

// Retrieve the API token from the secret
secret := &corev1.Secret{}
err = r.Get(ctx, types.NamespacedName{Name: emailSenderConfig.Spec.APITokenSecretRef, Namespace: req.Namespace}, secret)
if err != nil {
email.Status.DeliveryStatus = "Failed"
email.Status.Error = fmt.Sprintf("Failed to get secret: %v", err)
if updateErr := r.Status().Update(ctx, email); updateErr != nil {
logger.Error(updateErr, "Failed to update Email status")
return ctrl.Result{}, updateErr
}
return ctrl.Result{}, err
}

apiToken := string(secret.Data["apiToken"])
subject := email.Spec.Subject
text := email.Spec.Body
from := mailersend.From{
Name: emailSenderConfig.Spec.SenderEmail,
Email: emailSenderConfig.Spec.SenderEmail,
}
recipients := []mailersend.Recipient{
{
Name: email.Spec.RecipientEmail,
Email: email.Spec.RecipientEmail,
},
}
ms := mailersend.NewMailersend(apiToken)
message := ms.Email.NewMessage()
message.SetFrom(from)
message.SetRecipients(recipients)
message.SetSubject(subject)
message.SetText(text)

res, err := ms.Email.Send(ctx, message)
if err != nil {
email.Status.DeliveryStatus = "Failed"
email.Status.Error = fmt.Sprintf("Failed to send email: %v", err)
if updateErr := r.Status().Update(ctx, email); updateErr != nil {
logger.Error(updateErr, "Failed to update Email status")
return ctrl.Result{}, updateErr
}
return ctrl.Result{}, err
}
email.Status.DeliveryStatus = "Success"
email.Status.Error = ""
email.Status.MessageID = res.Header.Get("X-Message-Id")
if updateErr := r.Status().Update(ctx, email); updateErr != nil {
logger.Error(updateErr, "Failed to update Email status")
return ctrl.Result{}, updateErr
}

logger.Info("Email sent successfully",
"MessageID", email.Status.MessageID,
"Subject", email.Spec.Subject,
"From", emailSenderConfig.Spec.SenderEmail,
"To", email.Spec.RecipientEmail,
)

return ctrl.Result{}, nil
}
Expand All @@ -58,5 +150,6 @@ func (r *EmailReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl
func (r *EmailReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&emailv1.Email{}).
WithEventFilter(predicate.GenerationChangedPredicate{}).
Complete(r)
}
22 changes: 20 additions & 2 deletions internal/controller/emailsenderconfig_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,27 @@ type EmailSenderConfigReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *EmailSenderConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
logger := log.FromContext(ctx)
// Fetch the Email instance
emailSenderConfig := &emailv1.EmailSenderConfig{}
err := r.Get(ctx, req.NamespacedName, emailSenderConfig)
if err != nil {
logger.Error(err, "Failed to get EmailSenderConfig",
"EmailSenderConfig", emailSenderConfig.Name)
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Log the creation or update action
action := "Updated existing"
if emailSenderConfig.Generation == 1 {
action = "Created new"
}

// TODO(user): your logic here
logger.Info(action+" EmailSenderConfig",
"Name", emailSenderConfig.Name,
"senderEmail", emailSenderConfig.Spec.SenderEmail,
"secret", emailSenderConfig.Spec.APITokenSecretRef,
"generation", emailSenderConfig.Generation,
)

return ctrl.Result{}, nil
}
Expand Down

0 comments on commit 5a4fece

Please sign in to comment.