/
stack_controller.go
1964 lines (1763 loc) · 76.1 KB
/
stack_controller.go
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021, Pulumi Corporation. All rights reserved.
package stack
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
git "github.com/go-git/go-git/v5"
"github.com/operator-framework/operator-lib/handler"
"github.com/pulumi/pulumi-kubernetes-operator/pkg/apis/pulumi/shared"
pulumiv1 "github.com/pulumi/pulumi-kubernetes-operator/pkg/apis/pulumi/v1"
"github.com/pulumi/pulumi-kubernetes-operator/pkg/logging"
"github.com/pulumi/pulumi-kubernetes-operator/version"
"github.com/pulumi/pulumi/sdk/v3/go/auto"
"github.com/pulumi/pulumi/sdk/v3/go/auto/optdestroy"
"github.com/pulumi/pulumi/sdk/v3/go/auto/optrefresh"
"github.com/pulumi/pulumi/sdk/v3/go/auto/optup"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
giturls "github.com/whilp/git-urls"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
ctrlhandler "sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
yaml "sigs.k8s.io/yaml"
)
var (
log = logf.Log.WithName("controller_stack")
execAgent = fmt.Sprintf("pulumi-kubernetes-operator/%s", version.Version)
errRequirementNotRun = fmt.Errorf("prerequisite has not run to completion")
errRequirementFailed = fmt.Errorf("prerequisite failed")
errRequirementOutOfDate = fmt.Errorf("prerequisite succeeded but not recently enough")
)
const (
pulumiFinalizer = "finalizer.stack.pulumi.com"
defaultMaxConcurrentReconciles = 10
programRefIndexFieldName = ".spec.programRef.name" // this is an arbitrary string, named for the field it indexes
fluxSourceIndexFieldName = ".spec.fluxSource.sourceRef" // an arbitrary name, named for the field it indexes
)
const (
// envInsecureNoNamespaceIsolation is the name of the environment entry which, when set to a
// truthy value (1|true), shall allow multiple namespaces to be watched, and cross-namespace
// references to be accepted.
EnvInsecureNoNamespaceIsolation = "INSECURE_NO_NAMESPACE_ISOLATION"
)
// A directory (under /tmp) under which to put all working directories, for convenience in cleaning
// up.
const buildDirectoryPrefix = "pulumi-working"
func IsNamespaceIsolationWaived() bool {
switch os.Getenv(EnvInsecureNoNamespaceIsolation) {
case "1", "true":
return true
default:
return false
}
}
func getSourceGVK(src shared.FluxSourceReference) (schema.GroupVersionKind, error) {
gv, err := schema.ParseGroupVersion(src.APIVersion)
return gv.WithKind(src.Kind), err
}
func fluxSourceKey(gvk schema.GroupVersionKind, name string) string {
return fmt.Sprintf("%s:%s", gvk, name)
}
// Add creates a new Stack Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager) error {
// Use the ServiceAccount CA cert and token to setup $HOME/.kube/config.
// This is used to deploy Pulumi Stacks of k8s resources
// in-cluster that use the default, ambient kubeconfig.
if err := setupInClusterKubeconfig(); err != nil {
log.Error(err, "skipping in-cluster kubeconfig setup due to non-existent ServiceAccount")
}
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) *ReconcileStack {
return &ReconcileStack{
client: mgr.GetClient(),
scheme: mgr.GetScheme(),
recorder: mgr.GetEventRecorderFor("stack-controller"),
}
}
// prerequisiteIndexFieldName is the name used for indexing the prerequisites field.
const prerequisiteIndexFieldName = "spec.prerequisites.name"
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r *ReconcileStack) error {
var err error
maxConcurrentReconciles := defaultMaxConcurrentReconciles
maxConcurrentReconcilesStr, set := os.LookupEnv("MAX_CONCURRENT_RECONCILES")
if set {
maxConcurrentReconciles, err = strconv.Atoi(maxConcurrentReconcilesStr)
if err != nil {
return err
}
}
// Create a new controller
c, err := controller.New("stack-controller", mgr, controller.Options{
Reconciler: r,
MaxConcurrentReconciles: maxConcurrentReconciles,
})
if err != nil {
return err
}
// Filter for update events where an object's metadata.generation is changed (no spec change!),
// or the "force reconcile" annotation is used (and not marked as handled).
predicates := []predicate.Predicate{
predicate.Or(predicate.GenerationChangedPredicate{}, ReconcileRequestedPredicate{}),
}
stackInformer, err := mgr.GetCache().GetInformer(context.Background(), &pulumiv1.Stack{})
if err != nil {
return err
}
stackInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: newStackCallback,
UpdateFunc: updateStackCallback,
DeleteFunc: deleteStackCallback,
})
// Maintain an index of stacks->dependents; so that when a stack succeeds, we can requeue any
// stacks that might be waiting for it.
indexer := mgr.GetFieldIndexer()
if err = indexer.IndexField(context.Background(), &pulumiv1.Stack{}, prerequisiteIndexFieldName, func(o client.Object) []string {
stack := o.(*pulumiv1.Stack)
names := make([]string, len(stack.Spec.Prerequisites), len(stack.Spec.Prerequisites))
for i := range stack.Spec.Prerequisites {
names[i] = stack.Spec.Prerequisites[i].Name
}
return names
}); err != nil {
return err
}
enqueueDependents := func(stack client.Object) []reconcile.Request {
var dependentStacks pulumiv1.StackList
err := mgr.GetClient().List(context.TODO(), &dependentStacks,
client.InNamespace(stack.GetNamespace()),
client.MatchingFields{prerequisiteIndexFieldName: stack.GetName()})
if err == nil {
reqs := make([]reconcile.Request, len(dependentStacks.Items), len(dependentStacks.Items))
for i := range dependentStacks.Items {
reqs[i].NamespacedName = client.ObjectKeyFromObject(&dependentStacks.Items[i])
}
return reqs
}
// we don't get to return an error; only to fail quietly
mgr.GetLogger().Error(err, "failed to fetch dependents for object", "name", stack.GetName(), "namespace", stack.GetNamespace())
return nil
}
// Watch for changes to primary resource Stack
if err = c.Watch(&source.Kind{Type: &pulumiv1.Stack{}}, &handler.InstrumentedEnqueueRequestForObject{}, predicates...); err != nil {
return err
}
// Watch stacks so that dependent stacks can be requeued when they change
if err = c.Watch(&source.Kind{Type: &pulumiv1.Stack{}}, ctrlhandler.EnqueueRequestsFromMapFunc(enqueueDependents)); err != nil {
return err
}
// Watch Programs, and look up which (if any) Stack refers to them when they change
// Index stacks against the names of programs they reference
if err = indexer.IndexField(context.Background(), &pulumiv1.Stack{}, programRefIndexFieldName, func(o client.Object) []string {
stack := o.(*pulumiv1.Stack)
if stack.Spec.ProgramRef != nil {
return []string{stack.Spec.ProgramRef.Name}
}
return nil
}); err != nil {
return err
}
// this encodes the "use an index to look up the stacks used by a source" pattern which both
// ProgramRef and FluxSource need.
enqueueStacksForSourceFunc := func(indexName string, getFieldKey func(client.Object) string) func(client.Object) []reconcile.Request {
return func(src client.Object) []reconcile.Request {
var stacks pulumiv1.StackList
err := mgr.GetClient().List(context.TODO(), &stacks,
client.InNamespace(src.GetNamespace()),
client.MatchingFields{indexName: getFieldKey(src)})
if err == nil {
reqs := make([]reconcile.Request, len(stacks.Items), len(stacks.Items))
for i := range stacks.Items {
reqs[i].NamespacedName = client.ObjectKeyFromObject(&stacks.Items[i])
}
return reqs
}
// we don't get to return an error; only to fail quietly
mgr.GetLogger().Error(err, "failed to fetch stack referring to source",
"gvk", src.GetObjectKind().GroupVersionKind(),
"name", src.GetName(),
"namespace", src.GetNamespace())
return nil
}
}
err = c.Watch(&source.Kind{Type: &pulumiv1.Program{}}, ctrlhandler.EnqueueRequestsFromMapFunc(
enqueueStacksForSourceFunc(programRefIndexFieldName,
func(obj client.Object) string {
return obj.GetName()
})))
if err != nil {
return err
}
// Watch Flux sources we get told about, and look up the Stack(s) using them when they change
// Index the stacks against the type and name of sources they reference.
if err = indexer.IndexField(context.Background(), &pulumiv1.Stack{}, fluxSourceIndexFieldName, func(o client.Object) []string {
stack := o.(*pulumiv1.Stack)
if source := stack.Spec.FluxSource; source != nil {
gvk, err := getSourceGVK(source.SourceRef)
if err != nil {
mgr.GetLogger().Error(err, "unable to parse .sourceRef.apiVersion in Flux source")
return nil
}
// the keys include the type, because the references are not of a fixed type of object
return []string{fluxSourceKey(gvk, source.SourceRef.Name)}
}
return nil
}); err != nil {
return err
}
// We can't watch a specific type (i.e., using source.Kind) here; what we have to do is wait
// until we see stacks that refer to particular kinds, then watch those. Technically this can
// "leak" watches -- we may end up watching kinds that are no longer mentioned in stacks. My
// assumption is that the number of distinct types that might be mentioned (including typos) is
// low enough that this remains acceptably cheap.
// Keep track of types we've already watched, so we don't install more than one handler for a
// type.
watched := make(map[schema.GroupVersionKind]struct{})
watchedMu := sync.Mutex{}
// Calling this will attempt to install a watch for the kind given in the source reference. It
// will return an error if there's something wrong with the source reference or if the watch
// could not be attempted otherwise. If the kind cannot be found then this will keep trying in
// the background until the context given to controller.Start is cancelled, rather than return
// an error.
r.maybeWatchFluxSourceKind = func(src shared.FluxSourceReference) error {
gvk, err := getSourceGVK(src)
if err != nil {
return err
}
watchedMu.Lock()
_, ok := watched[gvk]
if !ok {
watched[gvk] = struct{}{}
}
watchedMu.Unlock()
if !ok {
// Using PartialObjectMetadata means we don't need the actual types registered in the
// schema.
var sourceKind metav1.PartialObjectMetadata
sourceKind.SetGroupVersionKind(gvk)
mgr.GetLogger().Info("installing watcher for newly seen source kind", "GroupVersionKind", gvk)
if err := c.Watch(&source.Kind{Type: &sourceKind},
ctrlhandler.EnqueueRequestsFromMapFunc(
enqueueStacksForSourceFunc(fluxSourceIndexFieldName, func(obj client.Object) string {
gvk := obj.GetObjectKind().GroupVersionKind()
return fluxSourceKey(gvk, obj.GetName())
}))); err != nil {
watchedMu.Lock()
delete(watched, gvk)
watchedMu.Unlock()
mgr.GetLogger().Error(err, "failed to watch source kind", "GroupVersionKind", gvk)
return err
}
}
return nil
}
return nil
}
// isRequirementSatisfied checks the given readiness requirement against the given stack, and
// returns nil if the requirement is satisfied, and an error otherwise. The requirement can be nil
// itself, in which case the prerequisite is only that the stack succeeded on its last run.
func isRequirementSatisfied(req *shared.RequirementSpec, stack pulumiv1.Stack) error {
if stack.Status.LastUpdate == nil {
return errRequirementNotRun
}
if stack.Status.LastUpdate.State != shared.SucceededStackStateMessage {
return errRequirementFailed
}
if req != nil && req.SucceededWithinDuration != nil {
lastRun := stack.Status.LastUpdate.LastResyncTime
if lastRun.IsZero() || time.Since(lastRun.Time) > req.SucceededWithinDuration.Duration {
return errRequirementOutOfDate
}
}
return nil
}
// ReconcileRequestedPredicate filters (returns true) for resources that are updated with a new or
// amended annotation value at `ReconcileRequestAnnotation`.
//
// Reconciliation request protocol:
//
// This gives a means of prompting the controller to reconsider a resource that otherwise might not
// be queued, e.g., because it has already reached a success state. This is useful for command-line
// tooling (e.g., you can trigger updates with `kubectl annotate`), and is the mechanism used to
// requeue prerequisites that are not up to date.
//
// The protocol works like this:
// - when you want the object to be considered for reconciliation, annotate it with the key
// `shared.ReconcileRequestAnnotation` and any likely-to-be-unique value. This causes the object
// to be queued for consideration by the controller;
// - the controller shall save the value of the annotation to `.status.observedReconcileRequest`
// whenever it processes a resource without returning an error. This is so you can check the
// status to see whether the annotation has been seen (similar to `.status.observedGeneration`).
//
// This protocol is the same mechanism used by many Flux controllers, as explained at
// https://pkg.go.dev/github.com/fluxcd/pkg/runtime/predicates#ReconcileRequestedPredicate and
// related documentation.
type ReconcileRequestedPredicate struct {
predicate.Funcs
}
func getReconcileRequestAnnotation(obj client.Object) (string, bool) {
r, ok := obj.GetAnnotations()[shared.ReconcileRequestAnnotation]
return r, ok
}
// Update filters update events based on whether the request reconciliation annotation has been
// added or amended.
func (p ReconcileRequestedPredicate) Update(e event.UpdateEvent) bool {
if e.ObjectOld == nil || e.ObjectNew == nil {
return false
}
if vNew, ok := getReconcileRequestAnnotation(e.ObjectNew); ok {
if vOld, ok := getReconcileRequestAnnotation(e.ObjectOld); ok {
return vNew != vOld
}
return true // new object has it, old one doesn't
}
return false // either removed, or present in neither object
}
// blank assignment to verify that ReconcileStack implements reconcile.Reconciler
var _ reconcile.Reconciler = &ReconcileStack{}
// ReconcileStack reconciles a Stack object
type ReconcileStack struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
recorder record.EventRecorder
// this is initialised by add(), to be available to Reconcile
maybeWatchFluxSourceKind func(shared.FluxSourceReference) error
}
// StallError represents a problem that makes a Stack spec unprocessable, while otherwise being
// valid. For example: the spec refers to a secret in another namespace. This is used to signal
// "stall" failures within helpers -- that is, when the operator cannot process the object as it is
// specified.
type StallError struct {
error
}
func newStallErrorf(format string, args ...interface{}) error {
return StallError{fmt.Errorf(format, args...)}
}
func isStalledError(e error) bool {
var s StallError
return errors.As(e, &s)
}
var errNamespaceIsolation = newStallErrorf(`refs are constrained to the object's namespace unless %s is set`, EnvInsecureNoNamespaceIsolation)
var errOtherThanOneSourceSpecified = newStallErrorf(`exactly one source (.spec.fluxSource, .spec.projectRepo, or .spec.programRef) for the stack must be given`)
var errProgramNotFound = fmt.Errorf("unable to retrieve program for stack")
// Reconcile reads that state of the cluster for a Stack object and makes changes based on the state read
// and what is in the Stack.Spec
func (r *ReconcileStack) Reconcile(ctx context.Context, request reconcile.Request) (retres reconcile.Result, reterr error) {
reqLogger := logging.WithValues(log, "Request.Namespace", request.Namespace, "Request.Name", request.Name)
reqLogger.Info("Reconciling Stack")
// Fetch the Stack instance
instance := &pulumiv1.Stack{}
err := r.client.Get(ctx, request.NamespacedName, instance)
if err != nil {
if k8serrors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
reqLogger.Info("Stack resource not found. Ignoring since object must be deleted.")
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
// Deletion/finalization protocol: Usually
// (https://book.kubebuilder.io/reference/using-finalizers.html) you would add a finalizer when
// you first see an object; and, when an object is being deleted, do clean up and exit instead
// of continuing on to process it. For this controller, clean-up may need some preparation
// (e.g., fetching the git repo), and there is a risk that finalization cannot be completed if
// that preparation fails (e.g., the git repo doesn't exist). To mitigate this, an object isn't
// given a finalizer until preparation has succeeded once (see under Step 2).
// Check if the Stack instance is marked to be deleted, which is indicated by the deletion
// timestamp being set.
isStackMarkedToBeDeleted := instance.GetDeletionTimestamp() != nil
// If there's no finalizer, it's either been cleaned up, never been seen, or never gotten far
// enough to need cleaning up.
if isStackMarkedToBeDeleted && !contains(instance.GetFinalizers(), pulumiFinalizer) {
return reconcile.Result{}, nil
}
// This helper helps with updates, from here onwards.
stack := instance.Spec
sess := newReconcileStackSession(reqLogger, stack, r.client, request.Namespace)
// Create a long-term working directory containing the home and workspace directories.
// The working directory is deleted during stack finalization.
// Any problem here is unexpected, and treated as a controller error.
_, err = sess.MakeRootDir(instance.GetNamespace(), instance.GetName())
if err != nil {
return reconcile.Result{}, fmt.Errorf("unable to create root directory for stack: %w", err)
}
// We can exit early if there is no clean-up to do.
if isStackMarkedToBeDeleted && !stack.DestroyOnFinalize {
// We know `!(isStackMarkedToBeDeleted && !contains(finalizer))` from above, and now
// `isStackMarkedToBeDeleted`, implying `contains(finalizer)`; but this would be correct
// even if it's a no-op.
return reconcile.Result{}, sess.finalize(ctx, instance)
}
// This makes sure the status reflects the outcome of reconciliation. Any non-error return means
// the object definition was observed, whether the object ended up in a ready state or not. An
// error return (now we have successfully fetched the object) means it is "in progress" and not
// ready.
saveStatus := func() {
if reterr == nil {
instance.Status.ObservedGeneration = instance.GetGeneration()
if req, ok := getReconcileRequestAnnotation(instance); ok {
instance.Status.ObservedReconcileRequest = req
}
} else {
// controller-runtime will requeue the object, so reflect that in the conditions by
// saying it is still in progress.
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, reterr.Error())
}
if err := sess.patchStatus(ctx, instance); err != nil {
log.Error(err, "unable to save object status")
}
}
// there's no reason to save the status if it's being deleted, and it'll fail anyway.
if !isStackMarkedToBeDeleted {
defer saveStatus()
}
// Check prerequisites, to make sure they are adequately up to date. Any prerequisite failing to
// be met will cause this run to be abandoned and the stack under consideration to be requeued;
// however, we go through all of the prerequisites anyway, so we can annotate all failing stacks
// to be requeued themselves.
var failedPrereqNames []string // in the case there's more than one, we report the names
var failedPrereqErr error // in caase there's just one, we report the specific error
for _, prereq := range instance.Spec.Prerequisites {
var prereqStack pulumiv1.Stack
key := types.NamespacedName{Name: prereq.Name, Namespace: instance.Namespace}
err := r.client.Get(ctx, key, &prereqStack)
if err != nil {
prereqErr := fmt.Errorf("unable to fetch prerequisite %q: %w", prereq.Name, err)
if k8serrors.IsNotFound(err) {
failedPrereqNames = append(failedPrereqNames, prereq.Name)
failedPrereqErr = prereqErr
continue
}
// otherwise, report as crash
r.markStackFailed(sess, instance, prereqErr, "", "")
return reconcile.Result{}, err
}
// does the prerequisite stack satisfy the requirements given?
requireErr := isRequirementSatisfied(prereq.Requirement, prereqStack)
if requireErr != nil {
failedPrereqNames = append(failedPrereqNames, prereq.Name)
failedPrereqErr = fmt.Errorf("prerequisite not satisfied for %q: %w", prereq.Name, requireErr)
// annotate the out of date stack so that it'll be queued. The value is arbitrary; this
// value gives a bit of context which might be helpful when troubleshooting.
v := fmt.Sprintf("update prerequisite of %s at %s", instance.Name, time.Now().Format(time.RFC3339))
prereqStack1 := prereqStack.DeepCopy()
a := prereqStack1.GetAnnotations()
if a == nil {
a = map[string]string{}
}
a[shared.ReconcileRequestAnnotation] = v
prereqStack1.SetAnnotations(a)
reqLogger.Info("requesting requeue of prerequisite", "name", prereqStack1.Name, "cause", requireErr.Error())
if err := r.client.Patch(ctx, prereqStack1, client.MergeFrom(&prereqStack)); err != nil {
// A conflict here may mean the prerequisite has been changed, or it's just been
// run. In any case, requeueing this object means we'll see the new state of the
// world next time around.
return reconcile.Result{}, fmt.Errorf("annotating prerequisite to force requeue: %w", err)
}
}
}
if len(failedPrereqNames) > 1 {
failedPrereqErr = fmt.Errorf("multiple prerequisites were not satisfied %s", strings.Join(failedPrereqNames, ", "))
}
if failedPrereqErr != nil {
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingPrerequisiteNotSatisfiedReason, failedPrereqErr.Error())
// Rely on the watcher watching prerequisites to requeue this, rather than requeuing
// explicitly.
return reconcile.Result{}, nil
}
// We're ready to do some actual work. Until we have a definitive outcome, mark the stack as
// reconciling.
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingProcessingReason, pulumiv1.ReconcilingProcessingMessage)
if err = sess.patchStatus(ctx, instance); err != nil {
return reconcile.Result{}, err
}
// This value is reported in .status, and is set from some property of the source -- whether
// it's the actual commit, or some analogue.
var currentCommit string
// Step 1. Set up the workdir, select the right stack and populate config if supplied.
exactlyOneOf := func(these ...bool) bool {
var found bool
for _, b := range these {
if found && b {
return false
}
found = found || b
}
return found
}
// Create the workspace directory. Any problem here is unexpected, and treated as a
// controller error.
_, err = sess.MakeWorkspaceDir()
if err != nil {
return reconcile.Result{}, fmt.Errorf("unable to create tmp directory for workspace: %w", err)
}
// Delete the workspace directory after the reconciliation is completed (regardless of success or failure).
defer sess.CleanupWorkspaceDir()
// Check which kind of source we have.
switch {
case !exactlyOneOf(stack.GitSource != nil, stack.FluxSource != nil, stack.ProgramRef != nil):
err := errOtherThanOneSourceSpecified
r.markStackFailed(sess, instance, err, "", "")
instance.Status.MarkStalledCondition(pulumiv1.StalledSpecInvalidReason, err.Error())
return reconcile.Result{}, nil
case stack.GitSource != nil:
gitSource := stack.GitSource
// Validate that there is enough specified to be able to clone the git repo.
if gitSource.ProjectRepo == "" || (gitSource.Commit == "" && gitSource.Branch == "") {
msg := "Stack git source needs to specify 'projectRepo' and either 'branch' or 'commit'"
r.emitEvent(instance, pulumiv1.StackConfigInvalidEvent(), msg)
reqLogger.Info(msg)
r.markStackFailed(sess, instance, errors.New(msg), "", "")
instance.Status.MarkStalledCondition(pulumiv1.StalledSpecInvalidReason, msg)
// this object won't be processable until the spec is changed, so no reason to requeue
// explicitly
return reconcile.Result{}, nil
}
gitAuth, err := sess.SetupGitAuth(ctx) // TODO be more explicit about what's being fed in here
if err != nil {
r.emitEvent(instance, pulumiv1.StackGitAuthFailureEvent(), "Failed to setup git authentication: %v", err.Error())
reqLogger.Error(err, "Failed to setup git authentication", "Stack.Name", stack.Stack)
r.markStackFailed(sess, instance, err, "", "")
instance.Status.MarkStalledCondition(pulumiv1.StalledSourceUnavailableReason, err.Error())
return reconcile.Result{}, nil
}
if gitAuth.SSHPrivateKey != "" {
// Add the project repo's public SSH keys to the SSH known hosts
// to perform the necessary key checking during SSH git cloning.
sess.addSSHKeysToKnownHosts(sess.stack.ProjectRepo)
}
if currentCommit, err = sess.SetupWorkdirFromGitSource(ctx, gitAuth, gitSource); err != nil {
r.emitEvent(instance, pulumiv1.StackInitializationFailureEvent(), "Failed to initialize stack: %v", err.Error())
reqLogger.Error(err, "Failed to setup Pulumi workspace", "Stack.Name", stack.Stack)
r.markStackFailed(sess, instance, err, "", "")
if isStalledError(err) {
instance.Status.MarkStalledCondition(pulumiv1.StalledCrossNamespaceRefForbiddenReason, err.Error())
return reconcile.Result{}, nil
}
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
// this can fail for reasons which might go away without intervention; so, retry explicitly
return reconcile.Result{Requeue: true}, nil
}
case stack.FluxSource != nil:
fluxSource := stack.FluxSource
var sourceObject unstructured.Unstructured
sourceObject.SetAPIVersion(fluxSource.SourceRef.APIVersion)
sourceObject.SetKind(fluxSource.SourceRef.Kind)
if err := r.client.Get(ctx, client.ObjectKey{
Name: fluxSource.SourceRef.Name,
Namespace: request.Namespace,
}, &sourceObject); err != nil {
reterr := fmt.Errorf("could not resolve sourceRef: %w", err)
r.markStackFailed(sess, instance, reterr, "", "")
if client.IgnoreNotFound(err) != nil {
return reconcile.Result{}, err
}
// this is marked as stalled and not requeued; the watch mechanism will requeue it if
// the source it points to appears.
instance.Status.MarkStalledCondition(pulumiv1.StalledSourceUnavailableReason, reterr.Error())
return reconcile.Result{}, nil
}
// Watch this kind of source, if we haven't already.
if err := r.maybeWatchFluxSourceKind(fluxSource.SourceRef); err != nil {
reterr := fmt.Errorf("cannot process source reference: %w", err)
r.markStackFailed(sess, instance, reterr, "", "")
instance.Status.MarkStalledCondition(pulumiv1.StalledSpecInvalidReason, reterr.Error())
return reconcile.Result{}, nil
}
if err := checkFluxSourceReady(sourceObject); err != nil {
r.markStackFailed(sess, instance, err, "", "")
// This is marked as retrying, but we're really waiting until the source is ready, at
// which time the watch mechanism will requeue it.
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
return reconcile.Result{}, nil
}
currentCommit, err = sess.SetupWorkdirFromFluxSource(ctx, sourceObject, fluxSource)
if err != nil {
r.emitEvent(instance, pulumiv1.StackInitializationFailureEvent(), "Failed to initialize stack: %v", err.Error())
reqLogger.Error(err, "Failed to setup Pulumi workspace", "Stack.Name", stack.Stack)
r.markStackFailed(sess, instance, err, "", "")
if isStalledError(err) {
instance.Status.MarkStalledCondition(pulumiv1.StalledCrossNamespaceRefForbiddenReason, err.Error())
return reconcile.Result{}, nil
}
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
// this can fail for reasons which might go away without intervention; so, retry explicitly
return reconcile.Result{Requeue: true}, nil
}
case stack.ProgramRef != nil:
programRef := stack.ProgramRef
if currentCommit, err = sess.SetupWorkdirFromYAML(ctx, *programRef); err != nil {
r.emitEvent(instance, pulumiv1.StackInitializationFailureEvent(), "Failed to initialize stack: %v", err.Error())
reqLogger.Error(err, "Failed to setup Pulumi workspace", "Stack.Name", stack.Stack)
r.markStackFailed(sess, instance, err, "", "")
if errors.Is(err, errProgramNotFound) {
instance.Status.MarkStalledCondition(pulumiv1.StalledSourceUnavailableReason, err.Error())
return reconcile.Result{}, nil
}
if isStalledError(err) {
instance.Status.MarkStalledCondition(pulumiv1.StalledSpecInvalidReason, err.Error())
return reconcile.Result{}, nil
}
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
// this can fail for reasons which might go away without intervention; so, retry explicitly
return reconcile.Result{Requeue: true}, nil
}
}
// Step 2. If there are extra environment variables, read them in now and use them for subsequent commands.
if err = sess.SetEnvs(ctx, stack.Envs, request.Namespace); err != nil {
err := fmt.Errorf("could not find ConfigMap for Envs: %w", err)
r.markStackFailed(sess, instance, err, currentCommit, "")
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
return reconcile.Result{Requeue: true}, nil
}
if err = sess.SetSecretEnvs(ctx, stack.SecretEnvs, request.Namespace); err != nil {
err := fmt.Errorf("could not find Secret for SecretEnvs: %w", err)
r.markStackFailed(sess, instance, err, currentCommit, "")
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
return reconcile.Result{Requeue: true}, nil
}
// This is enough preparation to be able to destroy the stack, if it's being deleted, or to
// consider it destroyable, if not.
if isStackMarkedToBeDeleted {
if contains(instance.GetFinalizers(), pulumiFinalizer) {
err := sess.finalize(ctx, instance)
// Manage extra status here
return reconcile.Result{}, err
}
} else {
if !contains(instance.GetFinalizers(), pulumiFinalizer) {
// Add finalizer to Stack if not being deleted
err := sess.addFinalizerAndUpdate(ctx, instance)
if err != nil {
return reconcile.Result{}, err
}
time.Sleep(2 * time.Second) // arbitrary sleep after finalizer add to avoid stale obj for permalink
// Add default permalink for the stack in the Pulumi Service.
if err := sess.addDefaultPermalink(ctx, instance); err != nil {
return reconcile.Result{}, err
}
}
}
// Proceed/Requeue logic: this depends on the kind of source, but broadly:
// - if the fetched revision is the same as the last one, proceed only if
// `ContinueResyncOnCommitMatch`
// - if not proceeding, requeue in ResyncFrequencySeconds (sic)
// requeueForSourcePoll keeps track of whether this object will need to be requeued for the
// purpose of polling its source.
requeueForSourcePoll := true
resyncFreqSeconds := sess.stack.ResyncFrequencySeconds
if sess.stack.ResyncFrequencySeconds != 0 && sess.stack.ResyncFrequencySeconds < 60 {
resyncFreqSeconds = 60
}
if stack.GitSource != nil {
trackBranch := len(stack.GitSource.Branch) > 0
// this object won't need to be requeued later if it's not tracking a branch
requeueForSourcePoll = trackBranch
// when tracking a branch, rather than an exact commit, always requeue
if trackBranch || sess.stack.ContinueResyncOnCommitMatch {
if resyncFreqSeconds == 0 {
resyncFreqSeconds = 60
}
}
if trackBranch && instance.Status.LastUpdate != nil {
reqLogger.Info("Checking current HEAD commit hash", "Current commit", currentCommit)
if instance.Status.LastUpdate.LastSuccessfulCommit == currentCommit && !sess.stack.ContinueResyncOnCommitMatch {
reqLogger.Info("Commit hash unchanged. Will poll again.", "pollFrequencySeconds", resyncFreqSeconds)
// Reconcile every resyncFreqSeconds to check for new commits to the branch.
instance.Status.MarkReadyCondition() // FIXME: should this reflect the previous update state?
// Ensure lastUpdate state is updated if previous sync failure occurred
if instance.Status.LastUpdate.State != shared.SucceededStackStateMessage {
instance.Status.LastUpdate.State = shared.SucceededStackStateMessage
instance.Status.LastUpdate.LastResyncTime = metav1.Now()
}
return reconcile.Result{RequeueAfter: time.Duration(resyncFreqSeconds) * time.Second}, nil
}
if instance.Status.LastUpdate.LastSuccessfulCommit != currentCommit {
r.emitEvent(instance, pulumiv1.StackUpdateDetectedEvent(), "New commit detected: %q.", currentCommit)
reqLogger.Info("New commit hash found", "Current commit", currentCommit,
"Last commit", instance.Status.LastUpdate.LastSuccessfulCommit)
}
}
} else if stack.FluxSource != nil {
if instance.Status.LastUpdate != nil {
if instance.Status.LastUpdate.LastSuccessfulCommit == currentCommit && !stack.ContinueResyncOnCommitMatch {
reqLogger.Info("Commit hash unchanged. Will poll again.", "pollFrequencySeconds", resyncFreqSeconds)
// Reconcile every resyncFreqSeconds to check for new commits to the branch.
instance.Status.MarkReadyCondition() // FIXME: should this reflect the previous update state?
// Ensure lastUpdate state is updated if previous sync failure occurred
if instance.Status.LastUpdate.State != shared.SucceededStackStateMessage {
instance.Status.LastUpdate.State = shared.SucceededStackStateMessage
instance.Status.LastUpdate.LastResyncTime = metav1.Now()
}
return reconcile.Result{RequeueAfter: time.Duration(resyncFreqSeconds) * time.Second}, nil
}
if instance.Status.LastUpdate.LastSuccessfulCommit != currentCommit {
r.emitEvent(instance, pulumiv1.StackUpdateDetectedEvent(), "New commit detected: %q.", currentCommit)
reqLogger.Info("New commit hash found", "Current commit", currentCommit,
"Last commit", instance.Status.LastUpdate.LastSuccessfulCommit)
}
}
} else if stack.ProgramRef != nil {
if instance.Status.LastUpdate != nil {
if instance.Status.LastUpdate.LastSuccessfulCommit == currentCommit && !stack.ContinueResyncOnCommitMatch {
reqLogger.Info("Commit hash unchanged. Will poll again.", "pollFrequencySeconds", resyncFreqSeconds)
// Reconcile every resyncFreqSeconds to check for new commits to the branch.
instance.Status.MarkReadyCondition() // FIXME: should this reflect the previous update state?
// Ensure lastUpdate state is updated if previous sync failure occurred
if instance.Status.LastUpdate.State != shared.SucceededStackStateMessage {
instance.Status.LastUpdate.State = shared.SucceededStackStateMessage
instance.Status.LastUpdate.LastResyncTime = metav1.Now()
}
return reconcile.Result{RequeueAfter: time.Duration(resyncFreqSeconds) * time.Second}, nil
}
if instance.Status.LastUpdate.LastSuccessfulCommit != currentCommit {
r.emitEvent(instance, pulumiv1.StackUpdateDetectedEvent(), "New commit detected: %q.", currentCommit)
reqLogger.Info("New commit hash found", "Current commit", currentCommit,
"Last commit", instance.Status.LastUpdate.LastSuccessfulCommit)
}
}
}
// targets are used for both refresh and up, if present
targets := stack.Targets
// Step 3. If a stack refresh is requested, run it now.
if sess.stack.Refresh {
permalink, err := sess.RefreshStack(ctx, sess.stack.ExpectNoRefreshChanges, targets)
if err != nil {
r.markStackFailed(sess, instance, fmt.Errorf("refreshing stack: %w", err), currentCommit, permalink)
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
return reconcile.Result{Requeue: true}, nil
}
if instance.Status.LastUpdate == nil {
instance.Status.LastUpdate = &shared.StackUpdateState{}
}
instance.Status.LastUpdate.Permalink = permalink
err = sess.patchStatus(ctx, instance)
if err != nil {
reqLogger.Error(err, "Failed to update Stack status for refresh", "Stack.Name", stack.Stack)
return reconcile.Result{}, err
}
reqLogger.Info("Successfully refreshed Stack", "Stack.Name", stack.Stack)
}
// Step 4. Run a `pulumi up --skip-preview`.
// TODO: is it possible to support a --dry-run with a preview?
status, permalink, result, err := sess.UpdateStack(ctx, targets)
switch status {
case shared.StackUpdateConflict:
r.emitEvent(instance,
pulumiv1.StackUpdateConflictDetectedEvent(),
"Conflict with another concurrent update. "+
"If Stack CR specifies 'retryOnUpdateConflict' a retry will trigger automatically.")
if sess.stack.RetryOnUpdateConflict {
reqLogger.Error(err, "Conflict with another concurrent update -- will retry shortly", "Stack.Name", stack.Stack)
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, "conflict with concurrent update, retryOnUpdateConflict set")
return reconcile.Result{RequeueAfter: time.Second * 5}, nil
}
reqLogger.Error(err, "Conflict with another concurrent update -- NOT retrying", "Stack.Name", stack.Stack)
instance.Status.MarkStalledCondition(pulumiv1.StalledConflictReason, "conflict with concurrent update, retryOnUpdateConflict not set")
return reconcile.Result{}, nil
case shared.StackNotFound:
r.emitEvent(instance, pulumiv1.StackNotFoundEvent(), "Stack not found. Will retry.")
reqLogger.Error(err, "Stack not found -- will retry shortly", "Stack.Name", stack.Stack, "Err:")
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, "stack not found in backend; retrying")
return reconcile.Result{RequeueAfter: time.Second * 5}, nil
default:
if err != nil {
r.markStackFailed(sess, instance, err, currentCommit, permalink)
instance.Status.MarkReconcilingCondition(pulumiv1.ReconcilingRetryReason, err.Error())
return reconcile.Result{Requeue: true}, nil
}
}
// At this point, the stack has been processed successfully. Mark it as ready, and rely on the
// post-return hook `saveStatus` to account for any last minute exceptions.
instance.Status.MarkReadyCondition()
// Step 5. Capture outputs onto the resulting status object.
outs, err := sess.GetStackOutputs(result.Outputs)
if err != nil {
r.emitEvent(instance, pulumiv1.StackOutputRetrievalFailureEvent(), "Failed to get Stack outputs: %v.", err.Error())
reqLogger.Error(err, "Failed to get Stack outputs", "Stack.Name", stack.Stack)
return reconcile.Result{}, err
}
if outs == nil {
reqLogger.Info("Stack outputs are empty. Skipping status update", "Stack.Name", stack.Stack)
return reconcile.Result{}, nil
}
instance.Status.Outputs = outs
instance.Status.LastUpdate = &shared.StackUpdateState{
State: shared.SucceededStackStateMessage,
LastAttemptedCommit: currentCommit,
LastSuccessfulCommit: currentCommit,
Permalink: permalink,
LastResyncTime: metav1.Now(),
}
r.emitEvent(instance, pulumiv1.StackUpdateSuccessfulEvent(), "Successfully updated stack.")
if requeueForSourcePoll || sess.stack.ContinueResyncOnCommitMatch {
// Reconcile every 60 seconds to check for new commits to the branch.
reqLogger.Debug("Will requeue in", "seconds", resyncFreqSeconds)
return reconcile.Result{RequeueAfter: time.Duration(resyncFreqSeconds) * time.Second}, nil
}
return reconcile.Result{}, nil
}
func (r *ReconcileStack) emitEvent(instance *pulumiv1.Stack, event pulumiv1.StackEvent, messageFmt string, args ...interface{}) {
r.recorder.Eventf(instance, event.EventType(), event.Reason(), messageFmt, args...)
}
// markStackFailed updates the status of the Stack object `instance` locally, to reflect a failure to process the stack.
func (r *ReconcileStack) markStackFailed(sess *reconcileStackSession, instance *pulumiv1.Stack, err error, currentCommit string, permalink shared.Permalink) {
r.emitEvent(instance, pulumiv1.StackUpdateFailureEvent(), "Failed to update Stack: %v.", err.Error())
sess.logger.Error(err, "Failed to update Stack", "Stack.Name", sess.stack.Stack)
// Update Stack status with failed state
if instance.Status.LastUpdate == nil {
instance.Status.LastUpdate = &shared.StackUpdateState{}
}
instance.Status.LastUpdate.LastAttemptedCommit = currentCommit
instance.Status.LastUpdate.State = shared.FailedStackStateMessage
instance.Status.LastUpdate.Permalink = permalink
instance.Status.LastUpdate.LastResyncTime = metav1.Now()
}
func (sess *reconcileStackSession) finalize(ctx context.Context, stack *pulumiv1.Stack) error {
sess.logger.Info("Finalizing the stack")
// Run finalization logic for pulumiFinalizer. If the
// finalization logic fails, don't remove the finalizer so
// that we can retry during the next reconciliation.
if err := sess.finalizeStack(ctx); err != nil {
sess.logger.Error(err, "Failed to run Pulumi finalizer", "Stack.Name", stack.Spec.Stack)
return err
}
if err := sess.removeFinalizerAndUpdate(ctx, stack); err != nil {
sess.logger.Error(err, "Failed to delete Pulumi finalizer", "Stack.Name", stack.Spec.Stack)
return err
}
return nil
}
// removeFinalizerAndUpdate makes sure this controller's finalizer is not present in the instance
// given, and updates the object with the Kubernetes API client. It will retry if there is a
// conflict, which is a possibility since other processes may be removing finalizers at the same
// time.
func (sess *reconcileStackSession) removeFinalizerAndUpdate(ctx context.Context, instance *pulumiv1.Stack) error {
key := client.ObjectKeyFromObject(instance)
return retry.RetryOnConflict(retry.DefaultBackoff, func() error {
var stack pulumiv1.Stack
if err := sess.kubeClient.Get(ctx, key, &stack); err != nil {
return err
}
// TODO: in more recent controller-runtime, the following returns a bool, and we could avoid
// the update if not necessary.
controllerutil.RemoveFinalizer(&stack, pulumiFinalizer)
return sess.kubeClient.Update(ctx, &stack)
})
}
func (sess *reconcileStackSession) finalizeStack(ctx context.Context) error {
// Destroy the stack resources and stack.
if sess.stack.DestroyOnFinalize {
if err := sess.DestroyStack(ctx); err != nil {
return err
}
}
// Delete the root directory for this stack.
sess.cleanupRootDir()
sess.logger.Info("Successfully finalized stack")
return nil
}
// addFinalizerAndUpdate adds this controller's finalizer to the given object, and updates it with