• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

opendefensecloud / artifact-conduit / 29222879748

13 Jul 2026 03:59AM UTC coverage: 84.322% (-0.4%) from 84.746%
29222879748

Pull #437

github

web-flow
Merge b56551357 into f96a1a379
Pull Request #437: chore(deps): update golang version sync

796 of 944 relevant lines covered (84.32%)

1590.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.29
/pkg/controller/order_controller.go
1
// Copyright 2025 BWI GmbH and Artifact Conduit contributors
2
// SPDX-License-Identifier: Apache-2.0
3

4
package controller
5

6
import (
7
        "context"
8
        "crypto/sha256"
9
        "encoding/hex"
10
        "encoding/json"
11
        "fmt"
12
        "slices"
13
        "time"
14

15
        "github.com/go-logr/logr"
16
        corev1 "k8s.io/api/core/v1"
17
        apierrors "k8s.io/apimachinery/pkg/api/errors"
18
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
19
        "k8s.io/apimachinery/pkg/runtime"
20
        "k8s.io/apimachinery/pkg/types"
21
        "k8s.io/client-go/tools/events"
22
        ctrl "sigs.k8s.io/controller-runtime"
23
        "sigs.k8s.io/controller-runtime/pkg/client"
24
        "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
25

26
        arcv1alpha1 "go.opendefense.cloud/arc/api/arc/v1alpha1"
27
)
28

29
const (
30
        orderFinalizer = "arc.opendefense.cloud/order-finalizer"
31
)
32

33
// OrderReconciler reconciles a Order object
34
type OrderReconciler struct {
35
        client.Client
36
        Scheme   *runtime.Scheme
37
        Recorder events.EventRecorder
38
}
39

40
type desiredAW struct {
41
        index       int
42
        objectMeta  metav1.ObjectMeta
43
        artifact    *arcv1alpha1.OrderArtifact
44
        typeSpec    *arcv1alpha1.ArtifactTypeSpec
45
        srcEndpoint *arcv1alpha1.Endpoint
46
        dstEndpoint *arcv1alpha1.Endpoint
47
        srcSecret   *corev1.Secret
48
        dstSecret   *corev1.Secret
49
        sha         string
50
        cron        *arcv1alpha1.Cron
51
}
52

53
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=endpoints,verbs=get;list;watch
54
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=artifacttypes,verbs=get;list;watch
55
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=clusterartifacttypes,verbs=get;list;watch
56
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=artifactworkflows,verbs=get;list;watch;create;update;patch;delete
57
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=orders,verbs=get;list;watch;create;update;patch;delete
58
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=orders/status,verbs=get;update;patch
59
//+kubebuilder:rbac:groups=arc.opendefense.cloud,resources=orders/finalizers,verbs=update
60
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
61
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
62

63
// Reconcile moves the current state of the cluster closer to the desired state
64
func (r *OrderReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
4,029✔
65
        log := ctrl.LoggerFrom(ctx)
4,029✔
66
        ctrlResult := ctrl.Result{}
4,029✔
67

4,029✔
68
        // Fetch the Order instance
4,029✔
69
        order := &arcv1alpha1.Order{}
4,029✔
70
        if err := r.Get(ctx, req.NamespacedName, order); err != nil {
4,032✔
71
                if apierrors.IsNotFound(err) {
6✔
72
                        // Object not found, return. Created objects are automatically garbage collected.
3✔
73
                        return ctrlResult, nil
3✔
74
                }
3✔
75

76
                return ctrlResult, errLogAndWrap(log, err, "failed to get object")
×
77
        }
78

79
        // Update last reconcile time
80
        order.Status.LastReconcileAt = metav1.Now()
4,026✔
81

4,026✔
82
        // Handle deletion: cleanup artifact workflows, then remove finalizer
4,026✔
83
        if !order.DeletionTimestamp.IsZero() {
4,028✔
84
                log.V(1).Info("Order is being deleted")
2✔
85
                r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "Deleting", "Delete", "Order is being deleted, cleaning up artifact workflows")
2✔
86

2✔
87
                // Cleanup all artifact workflows
2✔
88
                if len(order.Status.ArtifactWorkflows) > 0 {
3✔
89
                        for sha := range order.Status.ArtifactWorkflows {
3✔
90
                                // Remove ArtifactWorkflow
2✔
91
                                aw := &arcv1alpha1.ArtifactWorkflow{
2✔
92
                                        ObjectMeta: awObjectMeta(order, sha),
2✔
93
                                }
2✔
94
                                _ = r.Delete(ctx, aw) // Ignore errors
2✔
95
                                delete(order.Status.ArtifactWorkflows, sha)
2✔
96
                        }
2✔
97
                        if err := r.Status().Update(ctx, order); err != nil {
1✔
98
                                return ctrlResult, errLogAndWrap(log, err, "failed to update order status")
×
99
                        }
×
100
                        log.V(1).Info("Order artifact workflows cleaned up")
1✔
101

1✔
102
                        // Requeue until all artifact workflows are gone
1✔
103
                        return ctrlResult, nil
1✔
104
                }
105
                // All artifact workflows are gone, remove finalizer
106
                if slices.Contains(order.Finalizers, orderFinalizer) {
2✔
107
                        log.V(1).Info("No artifact workflows, removing finalizer from Order")
1✔
108
                        order.Finalizers = slices.DeleteFunc(order.Finalizers, func(f string) bool {
2✔
109
                                return f == orderFinalizer
1✔
110
                        })
1✔
111
                        if err := r.Update(ctx, order); err != nil {
1✔
112
                                return ctrlResult, errLogAndWrap(log, err, "failed to remove finalizer")
×
113
                        }
×
114
                }
115

116
                return ctrlResult, nil
1✔
117
        }
118

119
        // Add finalizer if not present and not deleting
120
        if order.DeletionTimestamp.IsZero() {
8,048✔
121
                if !slices.Contains(order.Finalizers, orderFinalizer) {
4,044✔
122
                        log.V(1).Info("Adding finalizer to Order")
20✔
123
                        order.Finalizers = append(order.Finalizers, orderFinalizer)
20✔
124
                        if err := r.Update(ctx, order); err != nil {
20✔
125
                                return ctrlResult, errLogAndWrap(log, err, "failed to add finalizer")
×
126
                        }
×
127
                        // Return without requeue; the Update event will trigger reconciliation again
128
                        return ctrlResult, nil
20✔
129
                }
130
        }
131

132
        // Handle force reconcile annotation
133
        forceAt, err := GetForceAtAnnotationValue(order)
4,004✔
134
        if err != nil {
4,004✔
135
                log.V(1).Error(err, "Invalid force reconcile annotation, ignoring")
×
136
        }
×
137
        if !forceAt.IsZero() && (order.Status.LastForceAt.IsZero() || forceAt.After(order.Status.LastForceAt.Time)) {
4,005✔
138
                log.V(1).Info("Force reconcile requested")
1✔
139
                r.Recorder.Eventf(order, nil, corev1.EventTypeNormal, "ForceReconcile", "Reconcile", "Force reconcile requested via annotation")
1✔
140
                // Delete existing artifact workflows to force re-creation
1✔
141
                for sha := range order.Status.ArtifactWorkflows {
2✔
142
                        // Remove Secret and ArtifactWorkflow
1✔
143
                        aw := &arcv1alpha1.ArtifactWorkflow{
1✔
144
                                ObjectMeta: awObjectMeta(order, sha),
1✔
145
                        }
1✔
146
                        _ = r.Delete(ctx, aw) // Ignore errors
1✔
147
                        delete(order.Status.ArtifactWorkflows, sha)
1✔
148
                        r.Recorder.Eventf(order, aw, corev1.EventTypeNormal, "ForceReconcile", "Reconcile", "Deleted artifact workflow '%s' with sha %s", aw.Name, sha)
1✔
149
                }
1✔
150
                // Update last force time
151
                order.Status.LastForceAt = metav1.Now()
1✔
152
                if err := r.Status().Update(ctx, order); err != nil {
1✔
153
                        return ctrlResult, errLogAndWrap(log, err, "failed to update last force time")
×
154
                }
×
155
                // Return without requeue; the update event will trigger reconciliation again
156
                return ctrlResult, nil
1✔
157
        }
158

159
        // Make sure status is initialized
160
        if order.Status.ArtifactWorkflows == nil {
4,106✔
161
                order.Status.ArtifactWorkflows = map[string]arcv1alpha1.OrderArtifactWorkflowStatus{}
103✔
162
        }
103✔
163

164
        // Before we compare to our status, let's fetch all necessary information
165
        // to compute desired state:
166
        desiredAWs := map[string]desiredAW{}
4,003✔
167
        for i, artifact := range order.Spec.Artifacts {
9,716✔
168
                daw, err := r.computeDesiredAW(ctx, log, order, &artifact, i)
5,713✔
169
                if err != nil {
5,868✔
170
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "ComputationFailed", "Compute", "Failed to compute desired artifact workflow for artifact index %d: %v", i, err)
155✔
171
                        order.Status.Message = fmt.Sprintf("Failed to compute desired artifact workflow for artifact index %d: %v", i, err)
155✔
172
                        if err := r.Status().Update(ctx, order); err != nil {
155✔
173
                                return ctrlResult, errLogAndWrap(log, err, "failed to update status")
×
174
                        }
×
175

176
                        return ctrlResult, errLogAndWrap(log, err, "failed to compute desired artifact workflow")
155✔
177
                }
178
                desiredAWs[daw.sha] = *daw
5,558✔
179
        }
180
        order.Status.Message = "" // Clear any previous error message
3,848✔
181

3,848✔
182
        // List missing artifact workflows
3,848✔
183
        var createAWs []string
3,848✔
184
        for sha := range desiredAWs {
9,400✔
185
                if _, exists := order.Status.ArtifactWorkflows[sha]; exists {
11,076✔
186
                        continue
5,524✔
187
                }
188

189
                createAWs = append(createAWs, sha)
28✔
190
        }
191

192
        // Find obsolete artifact workflows
193
        var deleteAWs []string
3,848✔
194
        for sha := range order.Status.ArtifactWorkflows {
9,374✔
195
                if _, exists := desiredAWs[sha]; exists {
11,050✔
196
                        continue
5,524✔
197
                }
198

199
                deleteAWs = append(deleteAWs, sha)
2✔
200
        }
201

202
        // Find finished artifact workflows to clean up
203
        var finishedAWs []string
3,848✔
204
        for sha := range order.Status.ArtifactWorkflows {
9,374✔
205
                awStatus := order.Status.ArtifactWorkflows[sha]
5,526✔
206

5,526✔
207
                // Do not clean up ArtifactWorkflows with cron specified
5,526✔
208
                if daw, ok := desiredAWs[sha]; ok && daw.cron != nil {
5,528✔
209
                        continue
2✔
210
                }
211

212
                // Do not clean up workflows that are still running or pending
213
                switch awStatus.Phase {
5,524✔
214
                case arcv1alpha1.WorkflowSucceeded:
91✔
215
                case arcv1alpha1.WorkflowFailed:
×
216
                case arcv1alpha1.WorkflowError:
4✔
217
                default:
5,429✔
218
                        continue
5,429✔
219
                }
220

221
                // Get ArtifactWorkflow object and check TTLs.
222
                artifactWorkflow := &arcv1alpha1.ArtifactWorkflow{}
95✔
223
                if err := r.Get(ctx, types.NamespacedName{Namespace: order.Namespace, Name: awName(order, sha)}, artifactWorkflow); err != nil && !apierrors.IsNotFound(err) {
95✔
224
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "Invalid", "Fetch", "Failed to fetch ArtifactWorkflow: %v", sha)
×
225
                        return ctrlResult, errLogAndWrap(log, err, "")
×
226
                }
×
227
                if artifactWorkflow.Name != "" {
103✔
228
                        // Cleanup finished workflows if TTLAfterFinished is set.
8✔
229
                        if awStatus.Phase == arcv1alpha1.WorkflowSucceeded {
13✔
230
                                // If TTL is set, check if it has expired
5✔
231
                                if artifactWorkflow.Spec.TTLAfterFinished != nil {
8✔
232
                                        if artifactWorkflow.Spec.TTLAfterFinished.Seconds() == 0 {
3✔
233
                                                // If TTL is zero keep the workflow.
×
234
                                                continue
×
235
                                        }
236
                                        if time.Since(awStatus.CompletionTime.Time) < artifactWorkflow.Spec.TTLAfterFinished.Duration {
4✔
237
                                                // If TTL is set but not expired keep the workflow.
1✔
238
                                                // Requeue when the next TTL expires
1✔
239
                                                ctrlResult.RequeueAfter = artifactWorkflow.Spec.TTLAfterFinished.Duration - time.Since(awStatus.CompletionTime.Time)
1✔
240
                                                continue
1✔
241
                                        }
242
                                }
243
                        }
244

245
                        // Cleanup failed workflows if TTLAfterFailed is set.
246
                        if awStatus.Phase == arcv1alpha1.WorkflowFailed || awStatus.Phase == arcv1alpha1.WorkflowError {
10✔
247
                                // If TTL is set, check if it has expired
3✔
248
                                if artifactWorkflow.Spec.TTLAfterFailed != nil {
6✔
249
                                        if artifactWorkflow.Spec.TTLAfterFailed.Seconds() == 0 {
3✔
250
                                                // If TTL is zero keep the workflow.
×
251
                                                continue
×
252
                                        }
253
                                        if time.Since(awStatus.FailureTime.Time) < artifactWorkflow.Spec.TTLAfterFailed.Duration {
4✔
254
                                                // If TTL is set but not expired keep the workflow.
1✔
255
                                                ctrlResult.RequeueAfter = artifactWorkflow.Spec.TTLAfterFailed.Duration - time.Since(awStatus.FailureTime.Time)
1✔
256
                                                continue
1✔
257
                                        }
258
                                } else {
×
259
                                        // If no TTL is set keep the workflow.
×
260
                                        continue
×
261
                                }
262
                        }
263
                }
264

265
                // Cleanup finished or not existing workflows
266
                finishedAWs = append(finishedAWs, sha)
93✔
267
        }
268

269
        // Create missing artifact workflows
270
        for _, sha := range createAWs {
3,876✔
271
                daw := desiredAWs[sha]
28✔
272
                aw, err := r.hydrateArtifactWorkflow(&daw)
28✔
273
                if err != nil {
28✔
274
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "HydrationFailed", "Hydrate", "Failed to hydrate artifact workflow for artifact index %d: %v", daw.index, err)
×
275
                        return ctrlResult, errLogAndWrap(log, err, "failed to hydrate artifact workflow")
×
276
                }
×
277

278
                // Set owner references
279
                if err := controllerutil.SetControllerReference(order, aw, r.Scheme); err != nil {
28✔
280
                        r.Recorder.Eventf(order, aw, corev1.EventTypeWarning, "HydrationFailed", "Hydrate", "Failed to set controller reference for artifact workflow: %v", err)
×
281
                        return ctrlResult, errLogAndWrap(log, err, "failed to set controller reference")
×
282
                }
×
283

284
                // Create artifact workflow
285
                if err := r.Create(ctx, aw); err != nil {
33✔
286
                        if apierrors.IsAlreadyExists(err) {
10✔
287
                                // Already created by a previous reconcile — that's fine
5✔
288
                                continue
5✔
289
                        }
290
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "CreationFailed", "Create", "Failed to create artifact workflow for artifact index %d: %v", daw.index, err)
×
291

×
292
                        return ctrlResult, errLogAndWrap(log, err, "failed to create artifact workflow")
×
293
                } else {
23✔
294
                        r.Recorder.Eventf(order, aw, corev1.EventTypeNormal, "Created", "Create", "Created artifact workflow '%s' for artifact index %d", aw.Name, daw.index)
23✔
295
                        log.V(1).Info("Created artifact workflow", "artifactWorkflow", aw.Name)
23✔
296
                }
23✔
297

298
                // Update status
299
                order.Status.ArtifactWorkflows[sha] = arcv1alpha1.OrderArtifactWorkflowStatus{
23✔
300
                        ArtifactIndex: daw.index,
23✔
301
                        WorkflowStatus: arcv1alpha1.WorkflowStatus{
23✔
302
                                Phase: arcv1alpha1.WorkflowUnknown,
23✔
303
                        },
23✔
304
                }
23✔
305
        }
306

307
        // Delete obsolete artifact workflows
308
        for _, sha := range deleteAWs {
3,850✔
309
                // Does not exist anymore, let's clean up!
2✔
310
                aw := &arcv1alpha1.ArtifactWorkflow{
2✔
311
                        ObjectMeta: awObjectMeta(order, sha),
2✔
312
                }
2✔
313
                if err := r.Delete(ctx, aw); client.IgnoreNotFound(err) != nil {
2✔
314
                        r.Recorder.Eventf(order, aw, corev1.EventTypeWarning, "DeletionFailed", "Delete", "Failed to delete obsolete artifact workflow '%s': %v", sha, err)
×
315
                        return ctrlResult, errLogAndWrap(log, err, "failed to delete artifact workflow")
×
316
                }
×
317

318
                // Update status
319
                delete(order.Status.ArtifactWorkflows, sha)
2✔
320
                log.V(1).Info("Deleted obsolete artifact workflow", "artifactWorkflow", sha)
2✔
321
                r.Recorder.Eventf(order, aw, corev1.EventTypeNormal, "Deleted", "Delete", "Deleted obsolete artifact workflow '%s'", sha)
2✔
322
        }
323

324
        // Delete finished artifact workflows
325
        for _, sha := range finishedAWs {
3,941✔
326
                // Finished, let's clean up!
93✔
327
                aw := &arcv1alpha1.ArtifactWorkflow{
93✔
328
                        ObjectMeta: awObjectMeta(order, sha),
93✔
329
                }
93✔
330
                if err := r.Delete(ctx, aw); client.IgnoreNotFound(err) != nil {
93✔
331
                        r.Recorder.Eventf(order, aw, corev1.EventTypeWarning, "DeletionFailed", "Delete", "Failed to delete finished artifact workflow '%s': %v", sha, err)
×
332
                        return ctrlResult, errLogAndWrap(log, err, "failed to delete artifact workflow")
×
333
                }
×
334

335
                log.V(1).Info("Deleted finished artifact workflow", "artifactWorkflow", sha)
93✔
336
                r.Recorder.Eventf(order, aw, corev1.EventTypeNormal, "Deleted", "Delete", "Deleted finished artifact workflow '%s'", sha)
93✔
337
        }
338

339
        anyStatusChanged := false
3,848✔
340
        for sha, daw := range desiredAWs {
9,400✔
341
                if slices.Contains(createAWs, sha) {
5,580✔
342
                        // If it was just created we skip the update
28✔
343
                        continue
28✔
344
                }
345
                if daw.cron == nil && order.Status.ArtifactWorkflows[sha].Phase.Completed() {
5,619✔
346
                        // We do not need to check for updates if the workflow is completed and is NOT cron
95✔
347
                        continue
95✔
348
                }
349
                aw := arcv1alpha1.ArtifactWorkflow{}
5,429✔
350
                if err := r.Get(ctx, namespacedName(daw.objectMeta.Namespace, daw.objectMeta.Name), &aw); err != nil {
5,429✔
351
                        delete(order.Status.ArtifactWorkflows, sha)
×
352
                        log.V(1).Info("Artifact workflow not found, deleting from status.", "artifactWorkflow", sha)
×
353
                        if err := r.Status().Update(ctx, order); err != nil {
×
354
                                return ctrlResult, errLogAndWrap(log, err, "failed to update status")
×
355
                        }
×
356

357
                        return ctrlResult, errLogAndWrap(log, err, "failed to get artifact workflow")
×
358
                }
359
                orderAWStatus := order.Status.ArtifactWorkflows[sha]
5,429✔
360

5,429✔
361
                phaseChanged := orderAWStatus.Phase != aw.Status.Phase
5,429✔
362
                succeededChanged := orderAWStatus.Succeeded != aw.Status.Succeeded
5,429✔
363
                failedChanged := orderAWStatus.Failed != aw.Status.Failed
5,429✔
364
                lastScheduledChanged := !orderAWStatus.LastScheduled.Equal(aw.Status.LastScheduled)
5,429✔
365

5,429✔
366
                if phaseChanged || succeededChanged || failedChanged || lastScheduledChanged {
7,796✔
367
                        orderAWStatus.WorkflowStatus = aw.Status.WorkflowStatus
2,367✔
368
                        order.Status.ArtifactWorkflows[sha] = orderAWStatus
2,367✔
369
                        anyStatusChanged = true
2,367✔
370
                }
2,367✔
371
        }
372

373
        // Update status
374
        if len(createAWs) > 0 || len(deleteAWs) > 0 || anyStatusChanged {
6,185✔
375
                log.V(1).Info("Updating order status")
2,337✔
376
                // Make sure ArtifactIndex is up to date
2,337✔
377
                for sha, daw := range desiredAWs {
5,770✔
378
                        aws := order.Status.ArtifactWorkflows[sha]
3,433✔
379
                        aws.ArtifactIndex = daw.index
3,433✔
380
                        order.Status.ArtifactWorkflows[sha] = aws
3,433✔
381
                }
3,433✔
382
                if err := r.Status().Update(ctx, order); err != nil {
2,410✔
383
                        return ctrlResult, errLogAndWrap(log, err, "failed to update status")
73✔
384
                }
73✔
385
        }
386

387
        return ctrlResult, nil
3,775✔
388
}
389

390
func (r *OrderReconciler) hydrateArtifactWorkflow(daw *desiredAW) (*arcv1alpha1.ArtifactWorkflow, error) {
28✔
391
        params, err := dawToParameters(daw)
28✔
392
        if err != nil {
28✔
393
                return nil, err
×
394
        }
×
395

396
        // Next we create the ArtifactWorkflow instance
397
        aw := &arcv1alpha1.ArtifactWorkflow{
28✔
398
                ObjectMeta: daw.objectMeta,
28✔
399
                Spec: arcv1alpha1.ArtifactWorkflowSpec{
28✔
400
                        WorkflowTemplateRef:         daw.typeSpec.WorkflowTemplateRef,
28✔
401
                        Parameters:                  params,
28✔
402
                        SrcSecretRef:                daw.srcEndpoint.Spec.SecretRef,
28✔
403
                        DstSecretRef:                daw.dstEndpoint.Spec.SecretRef,
28✔
404
                        Cron:                        daw.cron,
28✔
405
                        ArtifactWorkflowTTLSettings: daw.typeSpec.ArtifactWorkflowTTLSettings,
28✔
406
                },
28✔
407
        }
28✔
408

28✔
409
        return aw, nil
28✔
410
}
411

412
func (r *OrderReconciler) computeDesiredAW(ctx context.Context, log logr.Logger, order *arcv1alpha1.Order, artifact *arcv1alpha1.OrderArtifact, i int) (*desiredAW, error) {
5,713✔
413
        log = log.WithValues("artifactIndex", i)
5,713✔
414

5,713✔
415
        // We need the referenced src- and dst-endpoints for the artifact
5,713✔
416
        srcRefName := artifact.SrcRef.Name
5,713✔
417
        if srcRefName == "" {
6,151✔
418
                srcRefName = order.Spec.Defaults.SrcRef.Name
438✔
419
        }
438✔
420
        dstRefName := artifact.DstRef.Name
5,713✔
421
        if dstRefName == "" {
6,291✔
422
                dstRefName = order.Spec.Defaults.DstRef.Name
578✔
423
        }
578✔
424

425
        srcEndpoint := &arcv1alpha1.Endpoint{}
5,713✔
426
        if err := r.Get(ctx, namespacedName(order.Namespace, srcRefName), srcEndpoint); err != nil {
5,726✔
427
                r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "InvalidEndpoint", "FetchEndpoint", "Failed to fetch source endpoint '%s': %v", srcRefName, err)
13✔
428
                return nil, errLogAndWrap(log, err, "failed to fetch endpoint for source")
13✔
429
        }
13✔
430
        dstEndpoint := &arcv1alpha1.Endpoint{}
5,700✔
431
        if err := r.Get(ctx, namespacedName(order.Namespace, dstRefName), dstEndpoint); err != nil {
5,714✔
432
                r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "InvalidEndpoint", "FetchEndpoint", "Failed to fetch destination endpoint '%s': %v", dstRefName, err)
14✔
433
                return nil, errLogAndWrap(log, err, "failed to fetch endpoint for destination")
14✔
434
        }
14✔
435

436
        // Validate that the endpoint usage is correct
437
        if srcEndpoint.Spec.Usage != arcv1alpha1.EndpointUsagePullOnly && srcEndpoint.Spec.Usage != arcv1alpha1.EndpointUsageAll {
5,700✔
438
                err := fmt.Errorf("endpoint '%s' usage '%s' is not compatible with source usage", srcEndpoint.Name, srcEndpoint.Spec.Usage)
14✔
439
                r.Recorder.Eventf(order, srcEndpoint, corev1.EventTypeWarning, "InvalidEndpoint", "ValidateEndpoint", "Source endpoint '%s' has incompatible usage '%s'", srcEndpoint.Name, srcEndpoint.Spec.Usage)
14✔
440

14✔
441
                return nil, errLogAndWrap(log, err, "artifact validation failed")
14✔
442
        }
14✔
443
        if dstEndpoint.Spec.Usage != arcv1alpha1.EndpointUsagePushOnly && dstEndpoint.Spec.Usage != arcv1alpha1.EndpointUsageAll {
5,686✔
444
                err := fmt.Errorf("endpoint '%s' usage '%s' is not compatible with destination usage", dstEndpoint.Name, dstEndpoint.Spec.Usage)
14✔
445
                r.Recorder.Eventf(order, dstEndpoint, corev1.EventTypeWarning, "InvalidEndpoint", "ValidateEndpoint", "Destination endpoint '%s' has incompatible usage '%s'", dstEndpoint.Name, dstEndpoint.Spec.Usage)
14✔
446

14✔
447
                return nil, errLogAndWrap(log, err, "artifact validation failed")
14✔
448
        }
14✔
449

450
        // Validate against ArtifactType rules
451
        artifactType := &arcv1alpha1.ArtifactType{}
5,658✔
452
        if err := r.Get(ctx, namespacedName(order.Namespace, artifact.Type), artifactType); client.IgnoreNotFound(err) != nil {
5,658✔
453
                r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "InvalidArtifactType", "FetchArtifactType", "Failed to fetch ArtifactType '%s': %v", artifact.Type, err)
×
454
                return nil, errLogAndWrap(log, err, "failed to fetch referenced ArtifactType")
×
455
        }
×
456
        var (
5,658✔
457
                artifactTypeGen  int64
5,658✔
458
                artifactTypeSpec *arcv1alpha1.ArtifactTypeSpec
5,658✔
459
        )
5,658✔
460
        if artifactType.Name == "" { // was not found, let's check ClusterArtifactType
11,155✔
461
                clusterArtifactType := &arcv1alpha1.ClusterArtifactType{}
5,497✔
462
                if err := r.Get(ctx, namespacedName("", artifact.Type), clusterArtifactType); err != nil {
5,586✔
463
                        return nil, errLogAndWrap(log, err, "failed to fetch ArtifactType or ClusterArtifactType")
89✔
464
                }
89✔
465
                artifactTypeSpec = &clusterArtifactType.Spec
5,408✔
466
                artifactTypeGen = clusterArtifactType.Generation
5,408✔
467
                // NOTE: ClusterArtifactTypes can only reference ClusterWorkflowTemplates, so we enforce this here:
5,408✔
468
                artifactTypeSpec.WorkflowTemplateRef.ClusterScope = true
5,408✔
469
        } else {
161✔
470
                artifactTypeSpec = &artifactType.Spec
161✔
471
                artifactTypeGen = artifactType.Generation
161✔
472
        }
161✔
473

474
        if len(artifactTypeSpec.Rules.SrcTypes) > 0 && !slices.Contains(artifactTypeSpec.Rules.SrcTypes, srcEndpoint.Spec.Type) {
5,580✔
475
                err := fmt.Errorf("source endpoint type '%s' is not allowed by ArtifactType rules", srcEndpoint.Spec.Type)
11✔
476
                r.Recorder.Eventf(order, artifactType, corev1.EventTypeWarning, "InvalidArtifactType", "ValidateArtifactType", "Source endpoint type '%s' is not allowed by ArtifactType '%s' rules", srcEndpoint.Spec.Type, artifact.Type)
11✔
477

11✔
478
                return nil, errLogAndWrap(log, err, "artifact validation failed")
11✔
479
        }
11✔
480
        if len(artifactTypeSpec.Rules.DstTypes) > 0 && !slices.Contains(artifactTypeSpec.Rules.DstTypes, dstEndpoint.Spec.Type) {
5,558✔
481
                err := fmt.Errorf("destination endpoint type '%s' is not allowed by ArtifactType rules", dstEndpoint.Spec.Type)
×
482
                r.Recorder.Eventf(order, artifactType, corev1.EventTypeWarning, "InvalidArtifactType", "ValidateArtifactType", "Destination endpoint type '%s' is not allowed by ArtifactType '%s' rules", dstEndpoint.Spec.Type, artifact.Type)
×
483

×
484
                return nil, errLogAndWrap(log, err, "artifact validation failed")
×
485
        }
×
486

487
        // Next, we need the secret contents
488
        srcSecret := &corev1.Secret{}
5,558✔
489
        if srcEndpoint.Spec.SecretRef.Name != "" {
10,962✔
490
                if err := r.Get(ctx, namespacedName(order.Namespace, srcEndpoint.Spec.SecretRef.Name), srcSecret); err != nil {
5,404✔
491
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "InvalidSecret", "FetchSecret", "Failed to fetch source secret '%s': %v", srcEndpoint.Spec.SecretRef.Name, err)
×
492
                        return nil, errLogAndWrap(log, err, "failed to fetch secret for source")
×
493
                }
×
494
        }
495

496
        dstSecret := &corev1.Secret{}
5,558✔
497
        if dstEndpoint.Spec.SecretRef.Name != "" {
10,962✔
498
                if err := r.Get(ctx, namespacedName(order.Namespace, dstEndpoint.Spec.SecretRef.Name), dstSecret); err != nil {
5,404✔
499
                        r.Recorder.Eventf(order, nil, corev1.EventTypeWarning, "InvalidSecret", "FetchSecret", "Failed to fetch destination secret '%s': %v", dstEndpoint.Spec.SecretRef.Name, err)
×
500
                        return nil, errLogAndWrap(log, err, "failed to fetch secret for destination")
×
501
                }
×
502
        }
503

504
        // Cron schedule if any
505
        cron := artifact.Cron
5,558✔
506
        if cron == nil {
11,113✔
507
                cron = order.Spec.Defaults.Cron
5,555✔
508
        }
5,555✔
509

510
        // Create a hash based on all related data for idempotency and compute the workflow name
511
        h := sha256.New()
5,558✔
512
        data := []any{
5,558✔
513
                order.Namespace,
5,558✔
514
                artifact.Type,
5,558✔
515
                artifact.Spec.Raw,
5,558✔
516
                artifactTypeGen,
5,558✔
517
                srcEndpoint.Name,
5,558✔
518
                dstEndpoint.Name,
5,558✔
519
                order.Status.LastForceAt,
5,558✔
520
                cron,
5,558✔
521
        }
5,558✔
522

5,558✔
523
        if err := json.NewEncoder(h).Encode(data); err != nil {
5,558✔
524
                return nil, errLogAndWrap(log, err, "failed to marshal artifact workflow data")
×
525
        }
×
526

527
        sha := hex.EncodeToString(h.Sum(nil))[:16]
5,558✔
528

5,558✔
529
        // We gave all the information to further process this artifact workflow.
5,558✔
530
        // Let's store it to compare it to the current status!
5,558✔
531
        return &desiredAW{
5,558✔
532
                index:       i,
5,558✔
533
                objectMeta:  awObjectMeta(order, sha),
5,558✔
534
                artifact:    artifact,
5,558✔
535
                typeSpec:    artifactTypeSpec,
5,558✔
536
                srcEndpoint: srcEndpoint,
5,558✔
537
                dstEndpoint: dstEndpoint,
5,558✔
538
                srcSecret:   srcSecret,
5,558✔
539
                dstSecret:   dstSecret,
5,558✔
540
                sha:         sha,
5,558✔
541
                cron:        cron,
5,558✔
542
        }, nil
5,558✔
543
}
544

545
// SetupWithManager sets up the controller with the Manager.
546
func (r *OrderReconciler) SetupWithManager(mgr ctrl.Manager) error {
1✔
547
        return ctrl.NewControllerManagedBy(mgr).
1✔
548
                For(&arcv1alpha1.Order{}).
1✔
549
                Owns(&arcv1alpha1.ArtifactWorkflow{}).
1✔
550
                Complete(r)
1✔
551
}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc