workflow_controller.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package workflow
  13. import (
  14. "context"
  15. "fmt"
  16. "time"
  17. "github.com/go-logr/logr"
  18. v1 "k8s.io/api/core/v1"
  19. apierrors "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/client-go/tools/record"
  23. ctrl "sigs.k8s.io/controller-runtime"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. esapi "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  26. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore"
  27. )
  28. const (
  29. errFailedGetSecret = "could not get source secret"
  30. errPatchStatus = "error merging"
  31. errGetSecretStore = "could not get SecretStore %q, %w"
  32. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  33. errSetSecretFailed = "could not write remote ref %v to target secretstore %v: %v"
  34. errFailedSetSecret = "set secret failed: %v"
  35. errConvert = "could not apply conversion strategy to keys: %v"
  36. pushSecretFinalizer = "pushsecret.externalsecrets.io/finalizer"
  37. )
  38. type Reconciler struct {
  39. client.Client
  40. Log logr.Logger
  41. Scheme *runtime.Scheme
  42. recorder record.EventRecorder
  43. RequeueInterval time.Duration
  44. ControllerClass string
  45. }
  46. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
  47. r.recorder = mgr.GetEventRecorderFor("workflow")
  48. return ctrl.NewControllerManagedBy(mgr).
  49. For(&esapi.Workflow{}).
  50. Complete(r)
  51. }
  52. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
  53. log := r.Log.WithValues("workflow", req.NamespacedName)
  54. var workflow esapi.Workflow
  55. mgr := secretstore.NewManager(r.Client, r.ControllerClass, false)
  56. defer mgr.Close(ctx)
  57. if err := r.Get(ctx, req.NamespacedName, &workflow); err != nil {
  58. if apierrors.IsNotFound(err) {
  59. return ctrl.Result{}, nil
  60. }
  61. msg := "unable to get Workflow"
  62. r.recorder.Event(&workflow, v1.EventTypeWarning, esapi.ReasonErrored, msg)
  63. log.Error(err, msg)
  64. return ctrl.Result{}, fmt.Errorf("get resource: %w", err)
  65. }
  66. refreshInt := r.RequeueInterval
  67. if workflow.Spec.RefreshInterval != nil {
  68. refreshInt = workflow.Spec.RefreshInterval.Duration
  69. }
  70. p := client.MergeFrom(workflow.DeepCopy())
  71. defer func() {
  72. if err := r.Client.Status().Patch(ctx, &workflow, p); err != nil {
  73. log.Error(err, errPatchStatus)
  74. }
  75. }()
  76. err := NewWorkflowRunner(ctx, r.Client, workflow.Namespace, workflow.Spec.Workflows, log).Run()
  77. if err != nil {
  78. r.markAsFailed(workflow, err)
  79. return ctrl.Result{RequeueAfter: refreshInt}, nil
  80. }
  81. r.markAsDone(&workflow)
  82. return ctrl.Result{RequeueAfter: refreshInt}, nil
  83. }
  84. func (r *Reconciler) markAsFailed(workflow esapi.Workflow, err error) {
  85. msg := err.Error()
  86. r.recorder.Event(&workflow, v1.EventTypeWarning, esapi.ReasonErrored, msg)
  87. r.Log.Error(err, msg)
  88. cond := newWorkflowCondition(esapi.WorkflowReady, v1.ConditionFalse, esapi.ReasonErrored, msg)
  89. setWorkflowCondition(&workflow, *cond)
  90. }
  91. func (r *Reconciler) markAsDone(workflow *esapi.Workflow) {
  92. msg := "Workflow ran successfully"
  93. cond := newWorkflowCondition(esapi.WorkflowReady, v1.ConditionTrue, esapi.ReasonSynced, msg)
  94. setWorkflowCondition(workflow, *cond)
  95. r.recorder.Event(workflow, v1.EventTypeNormal, esapi.ReasonSynced, msg)
  96. }
  97. func newWorkflowCondition(condType esapi.WorkflowConditionType, status v1.ConditionStatus, reason, message string) *esapi.WorkflowStatusCondition {
  98. return &esapi.WorkflowStatusCondition{
  99. Type: condType,
  100. Status: status,
  101. LastTransitionTime: metav1.Now(),
  102. Reason: reason,
  103. Message: message,
  104. }
  105. }
  106. func setWorkflowCondition(workflow *esapi.Workflow, condition esapi.WorkflowStatusCondition) {
  107. currentCond := getWorkflowCondition(workflow.Status, condition.Type)
  108. if currentCond != nil && currentCond.Status == condition.Status &&
  109. currentCond.Reason == condition.Reason && currentCond.Message == condition.Message {
  110. return
  111. }
  112. // Do not update lastTransitionTime if the status of the condition doesn't change.
  113. if currentCond != nil && currentCond.Status == condition.Status {
  114. condition.LastTransitionTime = currentCond.LastTransitionTime
  115. }
  116. workflow.Status.Conditions = append(filterOutCondition(workflow.Status.Conditions, condition.Type), condition)
  117. }
  118. // filterOutCondition returns an empty set of conditions with the provided type.
  119. func filterOutCondition(conditions []esapi.WorkflowStatusCondition, condType esapi.WorkflowConditionType) []esapi.WorkflowStatusCondition {
  120. newConditions := make([]esapi.WorkflowStatusCondition, 0, len(conditions))
  121. for _, c := range conditions {
  122. if c.Type == condType {
  123. continue
  124. }
  125. newConditions = append(newConditions, c)
  126. }
  127. return newConditions
  128. }
  129. // getWorkflowCondition returns the condition with the provided type.
  130. func getWorkflowCondition(status esapi.WorkflowStatus, condType esapi.WorkflowConditionType) *esapi.WorkflowStatusCondition {
  131. for i := range status.Conditions {
  132. c := status.Conditions[i]
  133. if c.Type == condType {
  134. return &c
  135. }
  136. }
  137. return nil
  138. }