-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathplanner.go
More file actions
714 lines (625 loc) · 25.4 KB
/
planner.go
File metadata and controls
714 lines (625 loc) · 25.4 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2024 Datadog, Inc.
package planner
import (
"errors"
"fmt"
"time"
"github.com/go-logr/logr"
temporaliov1alpha1 "github.com/temporalio/temporal-worker-controller/api/v1alpha1"
"github.com/temporalio/temporal-worker-controller/internal/k8s"
"github.com/temporalio/temporal-worker-controller/internal/temporal"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Plan holds the actions to execute during reconciliation
type Plan struct {
// Which actions to take
DeleteDeployments []*appsv1.Deployment
ScaleDeployments map[*corev1.ObjectReference]uint32
UpdateDeployments []*appsv1.Deployment
ShouldCreateDeployment bool
VersionConfig *VersionConfig
TestWorkflows []WorkflowConfig
}
// VersionConfig defines version configuration for Temporal
type VersionConfig struct {
// Token to use for conflict detection
ConflictToken []byte
// Build ID for the version
BuildID string
// One of RampPercentage OR SetCurrent must be set to a non-zero value.
// Set this as the build ID for all new executions
SetCurrent bool
// Acceptable values [0,100]
RampPercentage int32
// ManagerIdentity is the current manager identity of the worker deployment in Temporal.
// An empty string indicates the controller should claim the identity before applying
// any routing config changes.
ManagerIdentity string
}
// WorkflowConfig defines a workflow to be started
type WorkflowConfig struct {
WorkflowType string
WorkflowID string
BuildID string
TaskQueue string
GateInput string
// IsInputSecret indicates whether the GateInput came from a Secret reference
// and should be treated as sensitive (not logged)
IsInputSecret bool
}
// Config holds the configuration for planning
type Config struct {
// RolloutStrategy to use
RolloutStrategy temporaliov1alpha1.RolloutStrategy
}
// GeneratePlan creates a plan for updating the worker deployment
func GeneratePlan(
l logr.Logger,
k8sState *k8s.DeploymentState,
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
temporalState *temporal.TemporalWorkerState,
connection temporaliov1alpha1.TemporalConnectionSpec,
config *Config,
workerDeploymentName string,
maxVersionsIneligibleForDeletion int32,
gateInput []byte,
isGateInputSecret bool,
) (*Plan, error) {
plan := &Plan{
ScaleDeployments: make(map[*corev1.ObjectReference]uint32),
}
// If Deployment was not found in temporal, which always happens on the first worker deployment version
// and sometimes happens transiently thereafter, the versions list will be empty. If the deployment
// exists and was found, there will always be at least one version in the list.
foundDeploymentInTemporal := temporalState != nil && len(temporalState.Versions) > 0
// Add delete/scale operations based on version status
plan.DeleteDeployments = getDeleteDeployments(k8sState, status, spec, foundDeploymentInTemporal)
plan.ScaleDeployments = getScaleDeployments(k8sState, status, spec)
plan.ShouldCreateDeployment = shouldCreateDeployment(status, maxVersionsIneligibleForDeletion)
plan.UpdateDeployments = getUpdateDeployments(k8sState, status, spec, connection)
// Determine if we need to start any test workflows
plan.TestWorkflows = getTestWorkflows(status, config, workerDeploymentName, gateInput, isGateInputSecret)
// Determine version config changes
plan.VersionConfig = getVersionConfigDiff(l, status, temporalState, config, workerDeploymentName)
// TODO(jlegrone): generate warnings/events on the TemporalWorkerDeployment resource when buildIDs are reachable
// but have no corresponding Deployment.
return plan, nil
}
// checkAndUpdateDeploymentConnectionSpec determines whether the Deployment for the given buildID is
// out-of-date with respect to the provided TemporalConnectionSpec. If an update is required, it mutates
// the existing Deployment in-place and returns a pointer to that Deployment. If no update is needed or
// the Deployment does not exist, it returns nil.
func checkAndUpdateDeploymentConnectionSpec(
buildID string,
k8sState *k8s.DeploymentState,
connection temporaliov1alpha1.TemporalConnectionSpec,
) *appsv1.Deployment {
existingDeployment, exists := k8sState.Deployments[buildID]
if !exists {
return nil
}
// If the connection spec hash has changed, update the deployment
currentHash := k8s.ComputeConnectionSpecHash(connection)
if currentHash != existingDeployment.Spec.Template.Annotations[k8s.ConnectionSpecHashAnnotation] {
// Update the deployment in-place with new connection info
updateDeploymentWithConnection(existingDeployment, connection)
return existingDeployment // Return the modified deployment
}
return nil
}
// updateDeploymentWithConnection updates an existing deployment with new TemporalConnectionSpec
func updateDeploymentWithConnection(deployment *appsv1.Deployment, connection temporaliov1alpha1.TemporalConnectionSpec) {
// Update the connection spec hash annotation
deployment.Spec.Template.Annotations[k8s.ConnectionSpecHashAnnotation] = k8s.ComputeConnectionSpecHash(connection)
// Update secret volume if mTLS is enabled
if connection.MutualTLSSecretRef != nil {
for i, volume := range deployment.Spec.Template.Spec.Volumes {
if volume.Name == "temporal-tls" && volume.Secret != nil {
deployment.Spec.Template.Spec.Volumes[i].Secret.SecretName = connection.MutualTLSSecretRef.Name
break
}
}
}
// Update any environment variables that reference the connection
for i, container := range deployment.Spec.Template.Spec.Containers {
for j, env := range container.Env {
if env.Name == "TEMPORAL_ADDRESS" {
deployment.Spec.Template.Spec.Containers[i].Env[j].Value = connection.HostPort
}
}
}
}
// checkAndUpdateDeploymentPodTemplateSpec determines whether the Deployment for the given buildID is
// out-of-date with respect to the user-provided pod template spec. This enables rolling updates when
// the build ID is stable (e.g., using spec.workerOptions.buildID) but the pod spec has changed.
// If an update is required, it rebuilds the deployment spec and returns a pointer to that Deployment.
// If no update is needed or the Deployment does not exist, it returns nil.
func checkAndUpdateDeploymentPodTemplateSpec(
buildID string,
k8sState *k8s.DeploymentState,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
connection temporaliov1alpha1.TemporalConnectionSpec,
) *appsv1.Deployment {
existingDeployment, exists := k8sState.Deployments[buildID]
if !exists {
return nil
}
// Only check for drift when UnsafeCustomBuildID is explicitly set by the user.
// If buildID is auto-generated, any spec change would generate a new buildID anyway.
if spec.WorkerOptions.UnsafeCustomBuildID == "" {
return nil
}
// Get the stored hash from the existing deployment's pod template annotations
storedHash := ""
if existingDeployment.Spec.Template.Annotations != nil {
storedHash = existingDeployment.Spec.Template.Annotations[k8s.PodTemplateSpecHashAnnotation]
}
// Backwards compatibility: if no hash annotation exists (legacy deployment),
// don't trigger an update - the hash will be added on the next spec change
if storedHash == "" {
return nil
}
// Compute the hash of the current user-provided pod template spec
currentHash := k8s.ComputePodTemplateSpecHash(spec.Template)
// If hashes match, no drift detected
if storedHash == currentHash {
return nil
}
// Pod template has changed - rebuild the pod spec from the TWD spec
// This applies all controller modifications (env vars, TLS mounts, etc.)
updateDeploymentWithPodTemplateSpec(existingDeployment, spec, connection)
return existingDeployment
}
// updateDeploymentWithPodTemplateSpec updates an existing deployment with a new pod template spec
// from the TWD spec. This applies all the controller modifications that NewDeploymentWithOwnerRef does.
func updateDeploymentWithPodTemplateSpec(
deployment *appsv1.Deployment,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
connection temporaliov1alpha1.TemporalConnectionSpec,
) {
// Deep copy the user-provided pod spec to avoid mutating the original
podSpec := spec.Template.Spec.DeepCopy()
// Extract the build ID from the deployment's labels (with nil safety)
var buildID string
if deployment.Labels != nil {
buildID = deployment.Labels[k8s.BuildIDLabel]
}
// Extract the worker deployment name from existing env vars
var workerDeploymentName string
for _, container := range deployment.Spec.Template.Spec.Containers {
for _, env := range container.Env {
if env.Name == "TEMPORAL_DEPLOYMENT_NAME" {
workerDeploymentName = env.Value
break
}
}
if workerDeploymentName != "" {
break
}
}
// Apply controller-managed environment variables and volume mounts
// Uses the same shared helper as NewDeploymentWithOwnerRef
k8s.ApplyControllerPodSpecModifications(podSpec, connection, spec.WorkerOptions.TemporalNamespace, workerDeploymentName, buildID)
// Build new pod annotations
podAnnotations := make(map[string]string)
for k, v := range spec.Template.Annotations {
podAnnotations[k] = v
}
podAnnotations[k8s.ConnectionSpecHashAnnotation] = k8s.ComputeConnectionSpecHash(connection)
// Store the new pod template spec hash
podAnnotations[k8s.PodTemplateSpecHashAnnotation] = k8s.ComputePodTemplateSpecHash(spec.Template)
// Preserve existing pod labels and add/update required labels
podLabels := make(map[string]string)
for k, v := range spec.Template.Labels {
podLabels[k] = v
}
// Copy selector labels from existing deployment
for k, v := range deployment.Spec.Selector.MatchLabels {
podLabels[k] = v
}
// Update the deployment's pod template
deployment.Spec.Template.ObjectMeta.Labels = podLabels
deployment.Spec.Template.ObjectMeta.Annotations = podAnnotations
deployment.Spec.Template.Spec = *podSpec
// Update replicas if changed
deployment.Spec.Replicas = spec.Replicas
deployment.Spec.MinReadySeconds = spec.MinReadySeconds
}
func getUpdateDeployments(
k8sState *k8s.DeploymentState,
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
connection temporaliov1alpha1.TemporalConnectionSpec,
) []*appsv1.Deployment {
var updateDeployments []*appsv1.Deployment
// Track which deployments we've already added to avoid duplicates
updatedBuildIDs := make(map[string]bool)
// Check target version deployment for pod template spec drift
// This enables rolling updates when the build ID is stable but spec changed
if status.TargetVersion.BuildID != "" {
if deployment := checkAndUpdateDeploymentPodTemplateSpec(status.TargetVersion.BuildID, k8sState, spec, connection); deployment != nil {
updateDeployments = append(updateDeployments, deployment)
updatedBuildIDs[status.TargetVersion.BuildID] = true
}
}
// Check target version deployment if it has an expired connection spec hash
// (only if not already updated by pod template check)
if status.TargetVersion.BuildID != "" && !updatedBuildIDs[status.TargetVersion.BuildID] {
if deployment := checkAndUpdateDeploymentConnectionSpec(status.TargetVersion.BuildID, k8sState, connection); deployment != nil {
updateDeployments = append(updateDeployments, deployment)
updatedBuildIDs[status.TargetVersion.BuildID] = true
}
}
// Check current version deployment if it has an expired connection spec hash
if status.CurrentVersion != nil && status.CurrentVersion.BuildID != "" && !updatedBuildIDs[status.CurrentVersion.BuildID] {
if deployment := checkAndUpdateDeploymentConnectionSpec(status.CurrentVersion.BuildID, k8sState, connection); deployment != nil {
updateDeployments = append(updateDeployments, deployment)
updatedBuildIDs[status.CurrentVersion.BuildID] = true
}
}
// Check deprecated versions for expired connection spec hashes
for _, version := range status.DeprecatedVersions {
if !updatedBuildIDs[version.BuildID] {
if deployment := checkAndUpdateDeploymentConnectionSpec(version.BuildID, k8sState, connection); deployment != nil {
updateDeployments = append(updateDeployments, deployment)
updatedBuildIDs[version.BuildID] = true
}
}
}
return updateDeployments
}
// getDeleteDeployments determines which deployments should be deleted
func getDeleteDeployments(
k8sState *k8s.DeploymentState,
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
foundDeploymentInTemporal bool,
) []*appsv1.Deployment {
var deleteDeployments []*appsv1.Deployment
for _, version := range status.DeprecatedVersions {
if version.Deployment == nil {
continue
}
// Look up the deployment using buildID
d, exists := k8sState.Deployments[version.BuildID]
if !exists {
continue
}
switch version.Status {
case temporaliov1alpha1.VersionStatusDrained:
// Deleting a deployment is only possible when:
// 1. The deployment has been drained for deleteDelay + scaledownDelay.
// 2. The deployment is scaled to 0 replicas.
if version.DrainedSince != nil &&
(time.Since(version.DrainedSince.Time) > spec.SunsetStrategy.DeleteDelay.Duration+spec.SunsetStrategy.ScaledownDelay.Duration) &&
d.Spec.Replicas != nil && *d.Spec.Replicas == 0 {
deleteDeployments = append(deleteDeployments, d)
}
case temporaliov1alpha1.VersionStatusNotRegistered:
// Only delete Deployments of NotRegistered versions if temporalState was not empty
if foundDeploymentInTemporal &&
// NotRegistered versions are versions that the server doesn't know about.
// Only delete if it's not the target version.
status.TargetVersion.BuildID != version.BuildID {
deleteDeployments = append(deleteDeployments, d)
}
}
}
return deleteDeployments
}
// getScaleDeployments determines which deployments should be scaled and to what size
func getScaleDeployments(
k8sState *k8s.DeploymentState,
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
spec *temporaliov1alpha1.TemporalWorkerDeploymentSpec,
) map[*corev1.ObjectReference]uint32 {
scaleDeployments := make(map[*corev1.ObjectReference]uint32)
replicas := *spec.Replicas
// Scale the current version if needed
if status.CurrentVersion != nil && status.CurrentVersion.Deployment != nil {
ref := status.CurrentVersion.Deployment
if d, exists := k8sState.Deployments[status.CurrentVersion.BuildID]; exists {
if d.Spec.Replicas != nil && *d.Spec.Replicas != replicas {
scaleDeployments[ref] = uint32(replicas)
}
}
}
// Scale the target version if it exists, and isn't current
if (status.CurrentVersion == nil || status.CurrentVersion.BuildID != status.TargetVersion.BuildID) &&
status.TargetVersion.Deployment != nil {
if d, exists := k8sState.Deployments[status.TargetVersion.BuildID]; exists {
if d.Spec.Replicas == nil || *d.Spec.Replicas != replicas {
scaleDeployments[status.TargetVersion.Deployment] = uint32(replicas)
}
}
}
// Scale other versions based on status
for _, version := range status.DeprecatedVersions {
if version.Deployment == nil {
continue
}
d, exists := k8sState.Deployments[version.BuildID]
if !exists {
continue
}
switch version.Status {
case temporaliov1alpha1.VersionStatusInactive:
// Scale down inactive versions that are not the target
if status.TargetVersion.BuildID == version.BuildID {
if d.Spec.Replicas != nil && *d.Spec.Replicas != replicas {
scaleDeployments[version.Deployment] = uint32(replicas)
}
} else if d.Spec.Replicas != nil && *d.Spec.Replicas != 0 {
scaleDeployments[version.Deployment] = 0
}
case temporaliov1alpha1.VersionStatusRamping, temporaliov1alpha1.VersionStatusCurrent:
// Scale up these deployments
if d.Spec.Replicas != nil && *d.Spec.Replicas != replicas {
scaleDeployments[version.Deployment] = uint32(replicas)
}
case temporaliov1alpha1.VersionStatusDrained:
if version.DrainedSince != nil && time.Since(version.DrainedSince.Time) > spec.SunsetStrategy.ScaledownDelay.Duration {
// TODO(jlegrone): Compute scale based on load? Or percentage of replicas?
// Scale down drained deployments after delay
if d.Spec.Replicas != nil && *d.Spec.Replicas != 0 {
scaleDeployments[version.Deployment] = 0
}
}
}
}
return scaleDeployments
}
// shouldCreateDeployment determines if a new deployment needs to be created
func shouldCreateDeployment(
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
maxVersionsIneligibleForDeletion int32,
) bool {
// Check if target version already has a deployment
if status.TargetVersion.Deployment != nil {
return false
}
versionCountIneligibleForDeletion := int32(0)
for _, v := range status.DeprecatedVersions {
if !v.EligibleForDeletion {
versionCountIneligibleForDeletion++
}
}
if versionCountIneligibleForDeletion >= maxVersionsIneligibleForDeletion {
return false
}
return true
}
// getTestWorkflows determines which test workflows should be started
func getTestWorkflows(
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
config *Config,
workerDeploymentName string,
gateInput []byte,
isGateInputSecret bool,
) []WorkflowConfig {
var testWorkflows []WorkflowConfig
// Skip if there's no gate workflow defined, if the target version is already the current, or if the target
// version is not yet registered in temporal
if config.RolloutStrategy.Gate == nil ||
(status.CurrentVersion != nil && status.CurrentVersion.BuildID == status.TargetVersion.BuildID) ||
status.TargetVersion.Status == temporaliov1alpha1.VersionStatusNotRegistered {
return nil
}
targetVersion := status.TargetVersion
// Create a map of task queues that already have running test workflows
taskQueuesWithWorkflows := make(map[string]struct{})
for _, wf := range targetVersion.TestWorkflows {
taskQueuesWithWorkflows[wf.TaskQueue] = struct{}{}
}
// For each task queue without a running test workflow, create a config
for _, tq := range targetVersion.TaskQueues {
if _, ok := taskQueuesWithWorkflows[tq.Name]; !ok {
testWorkflows = append(testWorkflows, WorkflowConfig{
WorkflowType: config.RolloutStrategy.Gate.WorkflowType,
WorkflowID: temporal.GetTestWorkflowID(workerDeploymentName, targetVersion.BuildID, tq.Name),
BuildID: targetVersion.BuildID,
TaskQueue: tq.Name,
GateInput: string(gateInput),
IsInputSecret: isGateInputSecret,
})
}
}
return testWorkflows
}
// getVersionConfigDiff determines the version configuration based on the rollout strategy
func getVersionConfigDiff(
l logr.Logger,
status *temporaliov1alpha1.TemporalWorkerDeploymentStatus,
temporalState *temporal.TemporalWorkerState,
config *Config,
workerDeploymentName string,
) *VersionConfig {
strategy := config.RolloutStrategy
conflictToken := status.VersionConflictToken
if strategy.Strategy == temporaliov1alpha1.UpdateManual {
return nil
}
// Do nothing if target version's deployment is not healthy yet, or if the version is not yet registered in temporal
if status.TargetVersion.HealthySince == nil ||
status.TargetVersion.Status == temporaliov1alpha1.VersionStatusNotRegistered {
return nil
}
// Do nothing if the test workflows have not completed successfully
if strategy.Gate != nil {
if len(status.TargetVersion.TaskQueues) == 0 {
return nil
}
if len(status.TargetVersion.TestWorkflows) < len(status.TargetVersion.TaskQueues) {
return nil
}
for _, wf := range status.TargetVersion.TestWorkflows {
if wf.Status != temporaliov1alpha1.WorkflowExecutionStatusCompleted {
return nil
}
}
}
managerIdentity := ""
if temporalState != nil {
managerIdentity = temporalState.ManagerIdentity
}
vcfg := &VersionConfig{
ConflictToken: conflictToken,
BuildID: status.TargetVersion.BuildID,
ManagerIdentity: managerIdentity,
}
// If there is no current version and presence of unversioned pollers is not confirmed for all
// target version task queues, set the target version as the current version right away.
if status.CurrentVersion == nil &&
status.TargetVersion.Status == temporaliov1alpha1.VersionStatusInactive &&
!temporalState.Versions[status.TargetVersion.BuildID].AllTaskQueuesHaveUnversionedPoller {
vcfg.SetCurrent = true
return vcfg
}
// If the current version is the target version
if status.CurrentVersion != nil && status.CurrentVersion.BuildID == status.TargetVersion.BuildID {
// Reset ramp if needed, this would happen if a ramp has been rolled back before completing
if temporalState.RampingBuildID != "" {
vcfg.BuildID = ""
vcfg.RampPercentage = 0
return vcfg
}
// Otherwise, do nothing
return nil
}
switch strategy.Strategy {
case temporaliov1alpha1.UpdateManual:
return nil
case temporaliov1alpha1.UpdateAllAtOnce:
// Set new current version immediately
vcfg.SetCurrent = true
return vcfg
case temporaliov1alpha1.UpdateProgressive:
return handleProgressiveRollout(strategy.Steps, time.Now(), status.TargetVersion.RampLastModifiedAt, status.TargetVersion.RampPercentage, vcfg)
}
return nil
}
// handleProgressiveRollout handles the progressive rollout strategy logic
func handleProgressiveRollout(
steps []temporaliov1alpha1.RolloutStep,
currentTime time.Time, // avoid calling time.Now() inside function to make it easier to test
rampLastModifiedAt *metav1.Time,
targetRampPercentage *float32,
vcfg *VersionConfig,
) *VersionConfig {
// Protect against modifying the current version right away if there are no steps.
//
// The validating admission webhook _should_ prevent creating rollouts with 0 steps,
// but just in case validation is skipped we should go with the more conservative
// behavior of not updating the current version from the controller.
if len(steps) == 0 {
return nil
}
// Get the currently active step
i := getCurrentStepIndex(steps, targetRampPercentage)
currentStep := steps[i]
// If this is the first step and there is no ramp percentage set, set the ramp percentage
// to the step's ramp percentage.
if targetRampPercentage == nil {
vcfg.RampPercentage = int32(currentStep.RampPercentage)
return vcfg
}
// If the target ramp percentage doesn't match the current step's defined ramp, the ramp
// is reset immediately. This might be considered overly conservative, but it guarantees that
// rollouts resume from the earliest possible step, and that at least the last step is always
// respected (both % and duration).
if *targetRampPercentage != float32(currentStep.RampPercentage) {
vcfg.RampPercentage = int32(currentStep.RampPercentage)
return vcfg
}
// Move to the next step if it has been long enough since the last update
if rampLastModifiedAt != nil {
if rampLastModifiedAt.Add(currentStep.PauseDuration.Duration).Before(currentTime) {
if i < len(steps)-1 {
vcfg.RampPercentage = int32(steps[i+1].RampPercentage)
return vcfg
} else {
vcfg.SetCurrent = true
return vcfg
}
}
}
// In all other cases, do nothing
return nil
}
func getCurrentStepIndex(steps []temporaliov1alpha1.RolloutStep, targetRampPercentage *float32) int {
if targetRampPercentage == nil {
return 0
}
var result int
for i, s := range steps {
// Break if ramp percentage is greater than current (use last index)
if float32(s.RampPercentage) > *targetRampPercentage {
break
}
result = i
}
return result
}
// validateGateInputConfig validates that gate input is configured correctly
func validateGateInputConfig(gate *temporaliov1alpha1.GateWorkflowConfig) error {
if gate == nil {
return nil
}
// If both are set, return error (webhook should prevent this, but double-check)
if gate.Input != nil && gate.InputFrom != nil {
return errors.New("both spec.rollout.gate.input and spec.rollout.gate.inputFrom are set")
}
if gate.InputFrom == nil {
return nil
}
// Exactly one of ConfigMapKeyRef or SecretKeyRef should be set
cmSet := gate.InputFrom.ConfigMapKeyRef != nil
secSet := gate.InputFrom.SecretKeyRef != nil
if (cmSet && secSet) || (!cmSet && !secSet) {
return errors.New("spec.rollout.gate.inputFrom must set exactly one of configMapKeyRef or secretKeyRef")
}
return nil
}
// ResolveGateInput resolves the gate input from inline JSON or from a referenced ConfigMap/Secret
// Returns the input bytes and a boolean indicating whether the input came from a Secret
func ResolveGateInput(gate *temporaliov1alpha1.GateWorkflowConfig, namespace string, configMapData map[string]string, configMapBinaryData map[string][]byte, secretData map[string][]byte) ([]byte, bool, error) {
if gate == nil {
return nil, false, nil
}
if err := validateGateInputConfig(gate); err != nil {
return nil, false, err
}
if gate.Input != nil {
return gate.Input.Raw, false, nil
}
if gate.InputFrom == nil {
return nil, false, nil
}
if cmRef := gate.InputFrom.ConfigMapKeyRef; cmRef != nil {
if configMapData != nil {
if val, ok := configMapData[cmRef.Key]; ok {
return []byte(val), false, nil
}
}
if configMapBinaryData != nil {
if bval, ok := configMapBinaryData[cmRef.Key]; ok {
return bval, false, nil
}
}
return nil, false, fmt.Errorf("key %q not found in ConfigMap %s/%s", cmRef.Key, namespace, cmRef.Name)
}
if secRef := gate.InputFrom.SecretKeyRef; secRef != nil {
if secretData != nil {
if bval, ok := secretData[secRef.Key]; ok {
return bval, true, nil // true indicates this came from a Secret
}
}
return nil, false, fmt.Errorf("key %q not found in Secret %s/%s", secRef.Key, namespace, secRef.Name)
}
return nil, false, nil
}