forked from akuity/kargo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstage.go
More file actions
318 lines (291 loc) · 9.37 KB
/
stage.go
File metadata and controls
318 lines (291 loc) · 9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
kargoapi "github.com/akuity/kargo/api/v1alpha1"
"github.com/akuity/kargo/pkg/server/user"
)
// GetStage returns a pointer to the Stage resource specified by the
// namespacedName argument. If no such resource is found, nil is returned
// instead.
func GetStage(
ctx context.Context,
c client.Client,
namespacedName types.NamespacedName,
) (*kargoapi.Stage, error) {
stage := kargoapi.Stage{}
if err := c.Get(ctx, namespacedName, &stage); err != nil {
if err = client.IgnoreNotFound(err); err == nil {
return nil, nil
}
return nil, fmt.Errorf(
"error getting Stage %q in namespace %q: %w",
namespacedName.Name,
namespacedName.Namespace,
err,
)
}
return &stage, nil
}
// ListStagesOptions defines the options for listing Stages.
type ListStagesOptions struct {
// Warehouses is an optional list of Warehouse names to filter the Stages by.
Warehouses []string
}
// ListStagesByWarehouses lists Stages in the given Project, optionally
// filtered by the provided options.
func ListStagesByWarehouses(
ctx context.Context,
c client.Client,
project string,
opts *ListStagesOptions,
) ([]kargoapi.Stage, error) {
if opts == nil {
opts = &ListStagesOptions{}
}
var list kargoapi.StageList
if err := c.List(ctx, &list, client.InNamespace(project)); err != nil {
return nil, err
}
if len(opts.Warehouses) == 0 {
return list.Items, nil
}
var stages []kargoapi.Stage
for _, stage := range list.Items {
if StageMatchesAnyWarehouse(&stage, opts.Warehouses) {
stages = append(stages, stage)
}
}
return stages, nil
}
// StageMatchesAnyWarehouse returns true if the Stage requests Freight that
// originated from at least one of the specified warehouses, either directly
// or through upstream stages.
func StageMatchesAnyWarehouse(stage *kargoapi.Stage, warehouses []string) bool {
for _, req := range stage.Spec.RequestedFreight {
if req.Origin.Kind == kargoapi.FreightOriginKindWarehouse &&
slices.Contains(warehouses, req.Origin.Name) {
return true
}
}
return false
}
// ListFreightAvailableToStage lists all Freight available to the Stage for any
// reason. This includes:
//
// 1. Any Freight from a Warehouse that the Stage subscribes to directly
// 2. Any Freight that is verified in upstream Stages matching configured
// AvailabilityStrategy (with any applicable soak time elapsed)
// 3. Any Freight that is approved for the Stage
func ListFreightAvailableToStage(
ctx context.Context,
c client.Client,
s *kargoapi.Stage,
) ([]kargoapi.Freight, error) {
var availableFreight []kargoapi.Freight
for _, req := range s.Spec.RequestedFreight {
// Get the Warehouse of origin
warehouse, err := GetWarehouse(
ctx,
c,
types.NamespacedName{
Namespace: s.Namespace,
Name: req.Origin.Name,
},
)
if err != nil {
return nil, err
}
if warehouse == nil {
// nolint:staticcheck
return nil, fmt.Errorf(
"Warehouse %q not found in namespace %q",
req.Origin.Name,
s.Namespace,
)
}
// Get applicable Freight from the Warehouse
var listOpts *ListWarehouseFreightOptions
if !req.Sources.Direct {
listOpts = &ListWarehouseFreightOptions{
ApprovedFor: s.Name,
VerifiedIn: req.Sources.Stages,
AvailabilityStrategy: req.Sources.AvailabilityStrategy,
RequiredSoakTime: req.Sources.RequiredSoakTime,
}
if req.Sources.AutoPromotionOptions != nil &&
req.Sources.AutoPromotionOptions.SelectionPolicy == kargoapi.AutoPromotionSelectionPolicyMatchUpstream {
// Validation should have ensured there is exactly one upstream Stage
// if this selection policy is set.
listOpts.CurrentlyIn = req.Sources.Stages[0]
}
}
freightFromWarehouse, err := ListFreightFromWarehouse(
ctx, c, warehouse, listOpts,
)
if err != nil {
return nil, err
}
availableFreight = append(availableFreight, freightFromWarehouse...)
}
// Sort and de-dupe the available Freight
slices.SortFunc(availableFreight, func(lhs, rhs kargoapi.Freight) int {
return strings.Compare(lhs.Name, rhs.Name)
})
availableFreight = slices.CompactFunc(availableFreight, func(lhs, rhs kargoapi.Freight) bool {
return lhs.Name == rhs.Name
})
return availableFreight, nil
}
// RefreshStage forces reconciliation of a Stage by setting an annotation
// on the Stage, causing the controller to reconcile it. Currently, the
// annotation value is the timestamp of the request, but might in the
// future include additional metadata/context necessary for the request.
func RefreshStage(
ctx context.Context,
c client.Client,
namespacedName types.NamespacedName,
) (*kargoapi.Stage, error) {
stage := &kargoapi.Stage{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespacedName.Namespace,
Name: namespacedName.Name,
},
}
if err := patchAnnotation(ctx, c, stage, kargoapi.AnnotationKeyRefresh, time.Now().Format(time.RFC3339)); err != nil {
return nil, fmt.Errorf("refresh: %w", err)
}
return stage, nil
}
// AnnotateStageWithArgoCDContext annotates a Stage with the ArgoCD context
// necessary for the frontend to display ArgoCD information for the Stage.
//
// The annotation value is a JSON-encoded list of ArgoCD apps that are
// associated with the Stage, constructed from the HealthCheckSteps from
// the latest Promotion.
//
// If no ArgoCD apps are found, the annotation is removed.
func AnnotateStageWithArgoCDContext(
ctx context.Context,
c client.Client,
healthChecks []kargoapi.HealthCheckStep,
stage *kargoapi.Stage,
) error {
var argoCDApps []map[string]any
for _, healthCheck := range healthChecks {
healthCheckConfig := healthCheck.GetConfig()
appsList, ok := healthCheckConfig["apps"].([]any)
if !ok {
continue
}
for _, rawApp := range appsList {
appConfig, ok := rawApp.(map[string]any)
if !ok {
continue
}
argoCDApps = append(argoCDApps, map[string]any{
"name": appConfig["name"],
"namespace": appConfig["namespace"],
})
}
}
// If we did not find any ArgoCD apps, we should remove the annotation.
if len(argoCDApps) == 0 {
return deleteAnnotation(ctx, c, stage, kargoapi.AnnotationKeyArgoCDContext)
}
// Marshal the ArgoCD context to JSON and set the annotation on the Stage.
argoCDAppsJSON, err := json.Marshal(argoCDApps)
if err != nil {
return fmt.Errorf("failed to marshal ArgoCD context: %w", err)
}
return patchAnnotation(ctx, c, stage, kargoapi.AnnotationKeyArgoCDContext, string(argoCDAppsJSON))
}
// ReverifyStageFreight forces reconfirmation of the verification of the
// Freight associated with a Stage by setting an AnnotationKeyReverify
// annotation on the Stage, causing the controller to rerun the verification.
// The annotation value is the identifier of the existing VerificationInfo for
// the Stage.
func ReverifyStageFreight(
ctx context.Context,
c client.Client,
namespacedName types.NamespacedName,
) error {
stage, err := GetStage(ctx, c, namespacedName)
if err != nil || stage == nil {
if stage == nil {
// nolint:staticcheck
err = fmt.Errorf("Stage %q in namespace %q not found", namespacedName.Name, namespacedName.Namespace)
}
return err
}
currentFC := stage.Status.FreightHistory.Current()
if currentFC == nil || len(currentFC.Freight) == 0 {
return errors.New("stage has no current freight")
}
currentVI := currentFC.VerificationHistory.Current()
if currentVI == nil {
return errors.New("stage has no current verification info")
}
if currentVI.ID == "" {
return fmt.Errorf("current stage verification info has no ID")
}
rr := kargoapi.VerificationRequest{
ID: currentVI.ID,
}
// Put actor information to track on the controller side
if u, ok := user.InfoFromContext(ctx); ok {
rr.Actor = FormatEventUserActor(u)
}
return patchAnnotation(ctx, c, stage, kargoapi.AnnotationKeyReverify, rr.String())
}
// AbortStageFreightVerification forces aborting the verification of the
// Freight associated with a Stage by setting an AnnotationKeyAbort
// annotation on the Stage, causing the controller to abort the verification.
// The annotation value is the identifier of the existing VerificationInfo for
// the Stage.
func AbortStageFreightVerification(
ctx context.Context,
c client.Client,
namespacedName types.NamespacedName,
) error {
stage, err := GetStage(ctx, c, namespacedName)
if err != nil || stage == nil {
if stage == nil {
// nolint:staticcheck
err = fmt.Errorf("Stage %q in namespace %q not found", namespacedName.Name, namespacedName.Namespace)
}
return err
}
currentFC := stage.Status.FreightHistory.Current()
if currentFC == nil || len(currentFC.Freight) == 0 {
return errors.New("stage has no current freight")
}
currentVI := currentFC.VerificationHistory.Current()
if currentVI == nil {
return errors.New("stage has no current verification info")
}
if currentVI.Phase.IsTerminal() {
// The verification is already in a terminal phase, so we can skip the
// abort request.
return nil
}
if currentVI.ID == "" {
return fmt.Errorf("current stage verification info has no ID")
}
ar := kargoapi.VerificationRequest{
ID: currentVI.ID,
}
// Put actor information to track on the controller side
if u, ok := user.InfoFromContext(ctx); ok {
ar.Actor = FormatEventUserActor(u)
}
return patchAnnotation(ctx, c, stage, kargoapi.AnnotationKeyAbort, ar.String())
}