-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
deployment_executor.go
682 lines (599 loc) 路 25.3 KB
/
deployment_executor.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
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package deploy
import (
"context"
"errors"
"fmt"
"strings"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/pkg/v3/resource/graph"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/display"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/result"
)
// deploymentExecutor is responsible for taking a deployment and driving it to completion.
// Its primary responsibility is to own a `stepGenerator` and `stepExecutor`, serving
// as the glue that links the two subsystems together.
type deploymentExecutor struct {
deployment *Deployment // The deployment that we are executing
stepGen *stepGenerator // step generator owned by this deployment
stepExec *stepExecutor // step executor owned by this deployment
}
// A set is returned of all the target URNs to facilitate later callers. The set can be 'nil'
// indicating no targets, or will be non-nil and non-empty if there are targets. Only URNs in the
// original array are in the set. i.e. it's only checked for containment. The value of the map is
// unused.
func createTargetMap(targets []resource.URN) map[resource.URN]bool {
if len(targets) == 0 {
return nil
}
targetMap := make(map[resource.URN]bool)
for _, target := range targets {
targetMap[target] = true
}
return targetMap
}
// checkTargets validates that all the targets passed in refer to existing resources. Diagnostics
// are generated for any target that cannot be found. The target must either have existed in the stack
// prior to running the operation, or it must be the urn for a resource that was created.
func (ex *deploymentExecutor) checkTargets(targets []resource.URN, op display.StepOp) result.Result {
if len(targets) == 0 {
return nil
}
olds := ex.deployment.olds
var news map[resource.URN]bool
if ex.stepGen != nil {
news = ex.stepGen.urns
}
hasUnknownTarget := false
for _, target := range targets {
hasOld := false
if _, has := olds[target]; has {
hasOld = true
}
hasNew := news != nil && news[target]
if !hasOld && !hasNew {
hasUnknownTarget = true
logging.V(7).Infof("Resource to %v (%v) could not be found in the stack.", op, target)
if strings.Contains(string(target), "$") {
ex.deployment.Diag().Errorf(diag.GetTargetCouldNotBeFoundError(), target)
} else {
ex.deployment.Diag().Errorf(diag.GetTargetCouldNotBeFoundDidYouForgetError(), target)
}
}
}
if hasUnknownTarget {
return result.Bail()
}
return nil
}
func (ex *deploymentExecutor) printPendingOperationsWarning() {
pendingOperations := ""
for _, op := range ex.deployment.prev.PendingOperations {
pendingOperations = pendingOperations + fmt.Sprintf(" * %s, interrupted while %s\n", op.Resource.URN, op.Type)
}
resolutionMessage := "" +
"These resources are in an unknown state because the Pulumi CLI was interrupted while " +
"waiting for changes to these resources to complete. You should confirm whether or not the " +
"operations listed completed successfully by checking the state of the appropriate provider. " +
"For example, if you are using AWS, you can confirm using the AWS Console.\n" +
"\n" +
"Once you have confirmed the status of the interrupted operations, you can repair your stack " +
"using `pulumi refresh` which will refresh the state from the provider you are using and " +
"clear the pending operations if there are any.\n" +
"\n" +
"Note that `pulumi refresh` will need to be run interactively to clear pending CREATE operations."
warning := "Attempting to deploy or update resources " +
fmt.Sprintf("with %d pending operations from previous deployment.\n", len(ex.deployment.prev.PendingOperations)) +
pendingOperations +
resolutionMessage
ex.deployment.Diag().Warningf(diag.RawMessage("" /*urn*/, warning))
}
// reportExecResult issues an appropriate diagnostic depending on went wrong.
func (ex *deploymentExecutor) reportExecResult(message string, preview bool) {
kind := "update"
if preview {
kind = "preview"
}
ex.reportError("", errors.New(kind+" "+message))
}
// reportError reports a single error to the executor's diag stream with the indicated URN for context.
func (ex *deploymentExecutor) reportError(urn resource.URN, err error) {
ex.deployment.Diag().Errorf(diag.RawMessage(urn, err.Error()))
}
// Execute executes a deployment to completion, using the given cancellation context and running a preview
// or update.
func (ex *deploymentExecutor) Execute(callerCtx context.Context, opts Options, preview bool) (*Plan, result.Result) {
// Set up a goroutine that will signal cancellation to the deployment's plugins if the caller context is cancelled.
// We do not hang this off of the context we create below because we do not want the failure of a single step to
// cause other steps to fail.
done := make(chan bool)
defer close(done)
go func() {
select {
case <-callerCtx.Done():
logging.V(4).Infof("deploymentExecutor.Execute(...): signalling cancellation to providers...")
cancelErr := ex.deployment.ctx.Host.SignalCancellation()
if cancelErr != nil {
logging.V(4).Infof("deploymentExecutor.Execute(...): failed to signal cancellation to providers: %v", cancelErr)
}
case <-done:
logging.V(4).Infof("deploymentExecutor.Execute(...): exiting provider canceller")
}
}()
// If this deployment is an import, run the imports and exit.
if ex.deployment.isImport {
return ex.importResources(callerCtx, opts, preview)
}
// Before doing anything else, optionally refresh each resource in the base checkpoint.
if opts.Refresh {
if res := ex.refresh(callerCtx, opts, preview); res != nil {
return nil, res
}
if opts.RefreshOnly {
return nil, nil
}
} else if ex.deployment.prev != nil && len(ex.deployment.prev.PendingOperations) > 0 && !preview {
// Print a warning for users that there are pending operations.
// Explain that these operations can be cleared using pulumi refresh (except for CREATE operations)
// since these require user intevention:
ex.printPendingOperationsWarning()
}
// The set of -t targets provided on the command line. 'nil' means 'update everything'.
// Non-nil means 'update only in this set'. We don't error if the user specifies a target
// during `update` that we don't know about because it might be the urn for a resource they
// want to create.
updateTargetsOpt := createTargetMap(opts.UpdateTargets)
replaceTargetsOpt := createTargetMap(opts.ReplaceTargets)
destroyTargetsOpt := createTargetMap(opts.DestroyTargets)
if res := ex.checkTargets(opts.ReplaceTargets, OpReplace); res != nil {
return nil, res
}
if res := ex.checkTargets(opts.DestroyTargets, OpDelete); res != nil {
return nil, res
}
if (updateTargetsOpt != nil || replaceTargetsOpt != nil) && destroyTargetsOpt != nil {
contract.Failf("Should not be possible to have both .DestroyTargets and .UpdateTargets or .ReplaceTargets")
}
// Begin iterating the source.
src, res := ex.deployment.source.Iterate(callerCtx, opts, ex.deployment)
if res != nil {
return nil, res
}
// Set up a step generator for this deployment.
ex.stepGen = newStepGenerator(ex.deployment, opts, updateTargetsOpt, replaceTargetsOpt)
// Derive a cancellable context for this deployment. We will only cancel this context if some piece of the
// deployment's execution fails.
ctx, cancel := context.WithCancel(callerCtx)
// Set up a step generator and executor for this deployment.
ex.stepExec = newStepExecutor(ctx, cancel, ex.deployment, opts, preview, false)
// We iterate the source in its own goroutine because iteration is blocking and we want the main loop to be able to
// respond to cancellation requests promptly.
type nextEvent struct {
Event SourceEvent
Result result.Result
}
incomingEvents := make(chan nextEvent)
go func() {
for {
event, sourceErr := src.Next()
select {
case incomingEvents <- nextEvent{event, sourceErr}:
if event == nil {
return
}
case <-done:
logging.V(4).Infof("deploymentExecutor.Execute(...): incoming events goroutine exiting")
return
}
}
}()
// The main loop. We'll continuously select for incoming events and the cancellation signal. There are
// a three ways we can exit this loop:
// 1. The SourceIterator sends us a `nil` event. This means that we're done processing source events and
// we should begin processing deletes.
// 2. The SourceIterator sends us an error. This means some error occurred in the source program and we
// should bail.
// 3. The stepExecCancel cancel context gets canceled. This means some error occurred in the step executor
// and we need to bail. This can also happen if the user hits Ctrl-C.
canceled, res := func() (bool, result.Result) {
logging.V(4).Infof("deploymentExecutor.Execute(...): waiting for incoming events")
for {
select {
case event := <-incomingEvents:
logging.V(4).Infof("deploymentExecutor.Execute(...): incoming event (nil? %v, %v)", event.Event == nil,
event.Result)
if event.Result != nil {
if !event.Result.IsBail() {
ex.reportError("", event.Result.Error())
}
cancel()
// We reported any errors above. So we can just bail now.
return false, result.Bail()
}
if event.Event == nil {
res := ex.performDeletes(ctx, updateTargetsOpt, destroyTargetsOpt)
if res != nil {
if resErr := res.Error(); resErr != nil {
logging.V(4).Infof("deploymentExecutor.Execute(...): error performing deletes: %v", resErr)
ex.reportError("", resErr)
return false, result.Bail()
}
}
return false, res
}
if res := ex.handleSingleEvent(event.Event); res != nil {
if resErr := res.Error(); resErr != nil {
logging.V(4).Infof("deploymentExecutor.Execute(...): error handling event: %v", resErr)
ex.reportError(ex.deployment.generateEventURN(event.Event), resErr)
}
cancel()
return false, result.Bail()
}
case <-ctx.Done():
logging.V(4).Infof("deploymentExecutor.Execute(...): context finished: %v", ctx.Err())
// NOTE: we use the presence of an error in the caller context in order to distinguish caller-initiated
// cancellation from internally-initiated cancellation.
return callerCtx.Err() != nil, nil
}
}
}()
ex.stepExec.WaitForCompletion()
logging.V(4).Infof("deploymentExecutor.Execute(...): step executor has completed")
// Now that we've performed all steps in the deployment, ensure that the list of targets to update was
// valid. We have to do this *after* performing the steps as the target list may have referred
// to a resource that was created in one of hte steps.
if res == nil {
res = ex.checkTargets(opts.UpdateTargets, OpUpdate)
}
// Check that we did operations for everything expected in the plan. We mutate ResourcePlan.Ops as we run
// so by the time we get here everything in the map should have an empty ops list (except for unneeded
// deletes). We skip this check if we already have an error, chances are if the deployment failed lots of
// operations wouldn't have got a chance to run so we'll spam errors about all of those failed operations
// making it less clear to the user what the root cause error was.
if res == nil && ex.deployment.plan != nil {
for urn, resourcePlan := range ex.deployment.plan.ResourcePlans {
if len(resourcePlan.Ops) != 0 {
if len(resourcePlan.Ops) == 1 && resourcePlan.Ops[0] == OpDelete {
// We haven't done a delete for this resource check if it was in the snapshot,
// if it's already gone this wasn't done because it wasn't needed
found := false
for i := range ex.deployment.prev.Resources {
if ex.deployment.prev.Resources[i].URN == urn {
found = true
break
}
}
// Didn't find the resource in the old snapshot so this was just an unneeded delete
if !found {
continue
}
}
err := fmt.Errorf("expected resource operations for %v but none were seen", urn)
logging.V(4).Infof("deploymentExecutor.Execute(...): error handling event: %v", err)
ex.reportError(urn, err)
res = result.Bail()
}
}
}
if res != nil && res.IsBail() {
return nil, res
}
// If the step generator and step executor were both successful, then we send all the resources
// observed to be analyzed. Otherwise, this step is skipped.
if res == nil && !ex.stepExec.Errored() {
res := ex.stepGen.AnalyzeResources()
if res != nil {
if resErr := res.Error(); resErr != nil {
logging.V(4).Infof("deploymentExecutor.Execute(...): error analyzing resources: %v", resErr)
ex.reportError("", resErr)
}
return nil, result.Bail()
}
}
// Figure out if execution failed and why. Step generation and execution errors trump cancellation.
if res != nil || ex.stepExec.Errored() || ex.stepGen.Errored() {
// TODO(cyrusn): We seem to be losing any information about the original 'res's errors. Should
// we be doing a merge here?
ex.reportExecResult("failed", preview)
return nil, result.Bail()
} else if canceled {
ex.reportExecResult("canceled", preview)
return nil, result.Bail()
}
return ex.deployment.newPlans.plan(), res
}
func (ex *deploymentExecutor) performDeletes(
ctx context.Context, updateTargetsOpt, destroyTargetsOpt map[resource.URN]bool) result.Result {
defer func() {
// We're done here - signal completion so that the step executor knows to terminate.
ex.stepExec.SignalCompletion()
}()
prev := ex.deployment.prev
if prev == nil || len(prev.Resources) == 0 {
return nil
}
logging.V(7).Infof("performDeletes(...): beginning")
// At this point we have generated the set of resources above that we would normally want to
// delete. However, if the user provided -target's we will only actually delete the specific
// resources that are in the set explicitly asked for.
var targetsOpt map[resource.URN]bool
if updateTargetsOpt != nil {
targetsOpt = updateTargetsOpt
} else if destroyTargetsOpt != nil {
targetsOpt = destroyTargetsOpt
}
deleteSteps, res := ex.stepGen.GenerateDeletes(targetsOpt)
if res != nil {
logging.V(7).Infof("performDeletes(...): generating deletes produced error result")
return res
}
deletes := ex.stepGen.ScheduleDeletes(deleteSteps)
// ScheduleDeletes gives us a list of lists of steps. Each list of steps can safely be executed
// in parallel, but each list must execute completes before the next list can safely begin
// executing.
//
// This is not "true" delete parallelism, since there may be resources that could safely begin
// deleting but we won't until the previous set of deletes fully completes. This approximation
// is conservative, but correct.
for _, antichain := range deletes {
logging.V(4).Infof("deploymentExecutor.Execute(...): beginning delete antichain")
tok := ex.stepExec.ExecuteParallel(antichain)
tok.Wait(ctx)
logging.V(4).Infof("deploymentExecutor.Execute(...): antichain complete")
}
// After executing targeted deletes, we may now have resources that depend on the resource that
// were deleted. Go through and clean things up accordingly for them.
if targetsOpt != nil {
resourceToStep := make(map[*resource.State]Step)
for _, step := range deleteSteps {
resourceToStep[ex.deployment.olds[step.URN()]] = step
}
ex.rebuildBaseState(resourceToStep, false /*refresh*/)
}
return nil
}
// handleSingleEvent handles a single source event. For all incoming events, it produces a chain that needs
// to be executed and schedules the chain for execution.
func (ex *deploymentExecutor) handleSingleEvent(event SourceEvent) result.Result {
contract.Require(event != nil, "event != nil")
var steps []Step
var res result.Result
switch e := event.(type) {
case RegisterResourceEvent:
logging.V(4).Infof("deploymentExecutor.handleSingleEvent(...): received RegisterResourceEvent")
steps, res = ex.stepGen.GenerateSteps(e)
case ReadResourceEvent:
logging.V(4).Infof("deploymentExecutor.handleSingleEvent(...): received ReadResourceEvent")
steps, res = ex.stepGen.GenerateReadSteps(e)
case RegisterResourceOutputsEvent:
logging.V(4).Infof("deploymentExecutor.handleSingleEvent(...): received register resource outputs")
return ex.stepExec.ExecuteRegisterResourceOutputs(e)
}
if res != nil {
return res
}
ex.stepExec.ExecuteSerial(steps)
return nil
}
// import imports a list of resources into a stack.
func (ex *deploymentExecutor) importResources(
callerCtx context.Context,
opts Options,
preview bool) (*Plan, result.Result) {
if len(ex.deployment.imports) == 0 {
return nil, nil
}
// Create an executor for this import.
ctx, cancel := context.WithCancel(callerCtx)
stepExec := newStepExecutor(ctx, cancel, ex.deployment, opts, preview, true)
importer := &importer{
deployment: ex.deployment,
executor: stepExec,
preview: preview,
}
res := importer.importResources(ctx)
stepExec.SignalCompletion()
stepExec.WaitForCompletion()
// NOTE: we use the presence of an error in the caller context in order to distinguish caller-initiated
// cancellation from internally-initiated cancellation.
canceled := callerCtx.Err() != nil
if res != nil || stepExec.Errored() {
if res != nil && res.Error() != nil {
ex.reportExecResult(fmt.Sprintf("failed: %s", res.Error()), preview)
} else {
ex.reportExecResult("failed", preview)
}
return nil, result.Bail()
} else if canceled {
ex.reportExecResult("canceled", preview)
return nil, result.Bail()
}
return ex.deployment.newPlans.plan(), nil
}
// refresh refreshes the state of the base checkpoint file for the current deployment in memory.
func (ex *deploymentExecutor) refresh(callerCtx context.Context, opts Options, preview bool) result.Result {
prev := ex.deployment.prev
if prev == nil || len(prev.Resources) == 0 {
return nil
}
// Make sure if there were any targets specified, that they all refer to existing resources.
if res := ex.checkTargets(opts.RefreshTargets, OpRefresh); res != nil {
return res
}
// If the user did not provide any --target's, create a refresh step for each resource in the
// old snapshot. If they did provider --target's then only create refresh steps for those
// specific targets.
steps := []Step{}
resourceToStep := map[*resource.State]Step{}
targetMapOpt := createTargetMap(opts.RefreshTargets)
for _, res := range prev.Resources {
if targetMapOpt == nil || targetMapOpt[res.URN] {
step := NewRefreshStep(ex.deployment, res, nil)
steps = append(steps, step)
resourceToStep[res] = step
}
}
// Fire up a worker pool and issue each refresh in turn.
ctx, cancel := context.WithCancel(callerCtx)
stepExec := newStepExecutor(ctx, cancel, ex.deployment, opts, preview, true)
stepExec.ExecuteParallel(steps)
stepExec.SignalCompletion()
stepExec.WaitForCompletion()
ex.rebuildBaseState(resourceToStep, true /*refresh*/)
// NOTE: we use the presence of an error in the caller context in order to distinguish caller-initiated
// cancellation from internally-initiated cancellation.
canceled := callerCtx.Err() != nil
if stepExec.Errored() {
ex.reportExecResult("failed", preview)
return result.Bail()
} else if canceled {
ex.reportExecResult("canceled", preview)
return result.Bail()
}
return nil
}
func (ex *deploymentExecutor) rebuildBaseState(resourceToStep map[*resource.State]Step, refresh bool) {
// Rebuild this deployment's map of old resources and dependency graph, stripping out any deleted
// resources and repairing dependency lists as necessary. Note that this updates the base
// snapshot _in memory_, so it is critical that any components that use the snapshot refer to
// the same instance and avoid reading it concurrently with this rebuild.
//
// The process of repairing dependency lists is a bit subtle. Because multiple physical
// resources may share a URN, the ability of a particular URN to be referenced in a dependency
// list can change based on the dependent resource's position in the resource list. For example,
// consider the following list of resources, where each resource is a (URN, ID, Dependencies)
// tuple:
//
// [ (A, 0, []), (B, 0, [A]), (A, 1, []), (A, 2, []), (C, 0, [A]) ]
//
// Let `(A, 0, [])` and `(A, 2, [])` be deleted by the refresh. This produces the following
// intermediate list before dependency lists are repaired:
//
// [ (B, 0, [A]), (A, 1, []), (C, 0, [A]) ]
//
// In order to repair the dependency lists, we iterate over the intermediate resource list,
// keeping track of which URNs refer to at least one physical resource at each point in the
// list, and remove any dependencies that refer to URNs that do not refer to any physical
// resources. This process produces the following final list:
//
// [ (B, 0, []), (A, 1, []), (C, 0, [A]) ]
//
// Note that the correctness of this process depends on the fact that the list of resources is a
// topological sort of its corresponding dependency graph, so a resource always appears in the
// list after any resources on which it may depend.
resources := []*resource.State{}
referenceable := make(map[resource.URN]bool)
olds := make(map[resource.URN]*resource.State)
for _, s := range ex.deployment.prev.Resources {
var old, new *resource.State
if step, has := resourceToStep[s]; has {
// We produced a refresh step for this specific resource. Use the new information about
// its dependencies during the update.
old = step.Old()
new = step.New()
} else {
// We didn't do anything with this resource. However, we still may want to update its
// dependencies. So use this resource itself as the 'new' one to update.
old = s
new = s
}
if new == nil {
if refresh {
contract.Assertf(old.Custom, "Expected custom resource")
contract.Assert(!providers.IsProviderType(old.Type))
}
continue
}
// Remove any deleted resources from this resource's dependency list.
if len(new.Dependencies) != 0 {
deps := make([]resource.URN, 0, len(new.Dependencies))
for _, d := range new.Dependencies {
if referenceable[d] {
deps = append(deps, d)
}
}
new.Dependencies = deps
}
// Add this resource to the resource list and mark it as referenceable.
resources = append(resources, new)
referenceable[new.URN] = true
// Do not record resources that are pending deletion in the "olds" lookup table.
if !new.Delete {
olds[new.URN] = new
}
}
undangleParentResources(olds, resources)
ex.deployment.prev.Resources = resources
ex.deployment.olds, ex.deployment.depGraph = olds, graph.NewDependencyGraph(resources)
}
func undangleParentResources(undeleted map[resource.URN]*resource.State, resources []*resource.State) {
// Since a refresh may delete arbitrary resources, we need to handle the case where
// the parent of a still existing resource is deleted.
//
// Invalid parents need to be fixed since otherwise they leave the state invalid, and
// the user sees an error:
// ```
// snapshot integrity failure; refusing to use it: child resource ${validURN} refers to missing parent ${deletedURN}
// ```
// To solve the problem we traverse the topologically sorted list of resources in
// order, setting newly invalidated parent URNS to the URN of the parent's parent.
//
// This can be illustrated by an example. Consider the graph of resource parents:
//
// A xBx
// / \ |
// xCx D xEx
// | / \ |
// F G xHx I
//
// When a capital letter is marked for deletion, it is bracketed by `x`s.
// We can obtain a topological sort by reading left to right, top to bottom.
//
// A..D -> valid parents, so we do nothing
// E -> The parent of E is marked for deletion, so set E.Parent to E.Parent.Parent.
// Since B (E's parent) has no parent, we set E.Parent to "".
// F -> The parent of F is marked for deletion, so set F.Parent to F.Parent.Parent.
// We set F.Parent to "A"
// G, H -> valid parents, do nothing
// I -> The parent of I is marked for deletion, so set I.Parent to I.Parent.Parent.
// The parent of I has parent "", (since we addressed the parent of E
// previously), so we set I.Parent = "".
//
// The new graph looks like this:
//
// A xBx xEx I
// / | \
// xCx F D
// / \
// G xHx
// We observe that it is perfectly valid for deleted nodes to be leaf nodes, but they
// cannot be intermediary nodes.
_, hasEmptyValue := undeleted[""]
contract.Assertf(!hasEmptyValue, "the zero value for an URN is not a valid URN")
availableParents := map[resource.URN]resource.URN{}
for _, r := range resources {
if _, ok := undeleted[r.Parent]; !ok {
// Since existing must obey a topological sort, we have already addressed
// p.Parent. Since we know that it doesn't dangle, and that r.Parent no longer
// exists, we set r.Parent as r.Parent.Parent.
r.Parent = availableParents[r.Parent]
}
availableParents[r.URN] = r.Parent
}
}