-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
import.go
371 lines (319 loc) 路 12.8 KB
/
import.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
// Copyright 2016-2020, 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"
cryptorand "crypto/rand"
"fmt"
"sort"
"github.com/blang/semver"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/result"
)
// An Import specifies a resource to import.
type Import struct {
Type tokens.Type // The type token for the resource. Required.
Name tokens.QName // The name of the resource. Required.
ID resource.ID // The ID of the resource. Required.
Parent resource.URN // The parent of the resource, if any.
Provider resource.URN // The specific provider to use for the resource, if any.
Version *semver.Version // The provider version to use for the resource, if any.
PluginDownloadURL string // The provider PluginDownloadURL to use for the resource, if any.
Protect bool // Whether to mark the resource as protected after import
Properties []string // Which properties to include (Defaults to required properties)
}
// ImportOptions controls the import process.
type ImportOptions struct {
Events Events // an optional events callback interface.
Parallel int // the degree of parallelism for resource operations (<=1 for serial).
}
// NewImportDeployment creates a new import deployment from a resource snapshot plus a set of resources to import.
//
// From the old and new states, it understands how to orchestrate an evaluation and analyze the resulting resources.
// The deployment may be used to simply inspect a series of operations, or actually perform them; these operations are
// generated based on analysis of the old and new states. If a resource exists in new, but not old, for example, it
// results in a create; if it exists in both, but is different, it results in an update; and so on and so forth.
//
// Note that a deployment uses internal concurrency and parallelism in various ways, so it must be closed if for some
// reason it isn't carried out to its final conclusion. This will result in cancellation and reclamation of resources.
func NewImportDeployment(ctx *plugin.Context, target *Target, projectName tokens.PackageName, imports []Import,
preview bool) (*Deployment, error) {
contract.Assert(ctx != nil)
contract.Assert(target != nil)
prev := target.Snapshot
source := NewErrorSource(projectName)
if err := migrateProviders(target, prev, source); err != nil {
return nil, err
}
// Produce a map of all old resources for fast access.
oldResources, olds, err := buildResourceMap(prev, preview)
if err != nil {
return nil, err
}
// Create a goal map for the deployment.
newGoals := &goalMap{}
builtins := newBuiltinProvider(nil, nil)
// Create a new provider registry.
reg, err := providers.NewRegistry(ctx.Host, oldResources, preview, builtins)
if err != nil {
return nil, err
}
// Return the prepared deployment.
return &Deployment{
ctx: ctx,
target: target,
prev: prev,
olds: olds,
goals: newGoals,
imports: imports,
isImport: true,
schemaLoader: schema.NewPluginLoader(ctx.Host),
source: NewErrorSource(projectName),
preview: preview,
providers: reg,
newPlans: newResourcePlan(target.Config),
}, nil
}
type noopEvent int
func (noopEvent) event() {}
func (noopEvent) Goal() *resource.Goal { return nil }
func (noopEvent) Done(result *RegisterResult) {}
type noopOutputsEvent resource.URN
func (noopOutputsEvent) event() {}
func (e noopOutputsEvent) URN() resource.URN { return resource.URN(e) }
func (noopOutputsEvent) Outputs() resource.PropertyMap { return resource.PropertyMap{} }
func (noopOutputsEvent) Done() {}
type importer struct {
deployment *Deployment
executor *stepExecutor
preview bool
}
func (i *importer) executeSerial(ctx context.Context, steps ...Step) bool {
return i.wait(ctx, i.executor.ExecuteSerial(steps))
}
func (i *importer) executeParallel(ctx context.Context, steps ...Step) bool {
return i.wait(ctx, i.executor.ExecuteParallel(steps))
}
func (i *importer) wait(ctx context.Context, token completionToken) bool {
token.Wait(ctx)
return ctx.Err() == nil && !i.executor.Errored()
}
func (i *importer) registerExistingResources(ctx context.Context) bool {
if i != nil && i.deployment != nil && i.deployment.prev != nil {
// Issue same steps per existing resource to make sure that they are recorded in the snapshot.
// We issue these steps serially s.t. the resources remain in the order in which they appear in the state.
for _, r := range i.deployment.prev.Resources {
if r.Delete {
continue
}
new := *r
new.ID = ""
if !i.executeSerial(ctx, NewSameStep(i.deployment, noopEvent(0), r, &new)) {
return false
}
}
}
return true
}
func (i *importer) getOrCreateStackResource(ctx context.Context) (resource.URN, bool, bool) {
// Get or create the root resource.
if i.deployment.prev != nil {
for _, res := range i.deployment.prev.Resources {
if res.Type == resource.RootStackType {
return res.URN, false, true
}
}
}
projectName, stackName := i.deployment.source.Project(), i.deployment.target.Name
typ, name := resource.RootStackType, fmt.Sprintf("%s-%s", projectName, stackName)
urn := resource.NewURN(stackName.Q(), projectName, "", typ, tokens.QName(name))
state := resource.NewState(typ, urn, false, false, "", resource.PropertyMap{}, nil, "", false, false, nil, nil, "",
nil, false, nil, nil, nil, "", false, "")
// TODO(seqnum) should stacks be created with 1? When do they ever get recreated/replaced?
if !i.executeSerial(ctx, NewCreateStep(i.deployment, noopEvent(0), state)) {
return "", false, false
}
return urn, true, true
}
func (i *importer) registerProviders(ctx context.Context) (map[resource.URN]string, result.Result, bool) {
urnToReference := map[resource.URN]string{}
// Determine which default providers are not present in the state. If all default providers are accounted for,
// we're done.
//
// NOTE: what if the configuration for an existing default provider has changed? If it has, we should diff it and
// replace it appropriately or we should not use the ambient config at all.
var defaultProviderRequests []providers.ProviderRequest
defaultProviders := map[resource.URN]struct{}{}
for _, imp := range i.deployment.imports {
if imp.Provider != "" {
// If the provider for this import exists, map its URN to its provider reference. If it does not exist,
// the import step will issue an appropriate error or errors.
ref := string(imp.Provider)
if state, ok := i.deployment.olds[imp.Provider]; ok {
r, err := providers.NewReference(imp.Provider, state.ID)
contract.AssertNoError(err)
ref = r.String()
}
urnToReference[imp.Provider] = ref
continue
}
if imp.Type.Package() == "" {
return nil, result.Error("incorrect package type specified"), false
}
req := providers.NewProviderRequest(imp.Version, imp.Type.Package(), imp.PluginDownloadURL)
typ, name := providers.MakeProviderType(req.Package()), req.Name()
urn := i.deployment.generateURN("", typ, name)
if state, ok := i.deployment.olds[urn]; ok {
ref, err := providers.NewReference(urn, state.ID)
contract.AssertNoError(err)
urnToReference[urn] = ref.String()
continue
}
if _, ok := defaultProviders[urn]; ok {
continue
}
defaultProviderRequests = append(defaultProviderRequests, req)
defaultProviders[urn] = struct{}{}
}
if len(defaultProviderRequests) == 0 {
return urnToReference, nil, true
}
steps := make([]Step, len(defaultProviderRequests))
sort.Slice(defaultProviderRequests, func(i, j int) bool {
return defaultProviderRequests[i].String() < defaultProviderRequests[j].String()
})
for idx, req := range defaultProviderRequests {
if req.Package() == "" {
return nil, result.Error("incorrect package type specified"), false
}
typ, name := providers.MakeProviderType(req.Package()), req.Name()
urn := i.deployment.generateURN("", typ, name)
// Fetch, prepare, and check the configuration for this provider.
inputs, err := i.deployment.target.GetPackageConfig(req.Package())
if err != nil {
return nil, result.Errorf("failed to fetch provider config: %v", err), false
}
// Calculate the inputs for the provider using the ambient config.
if v := req.Version(); v != nil {
providers.SetProviderVersion(inputs, v)
}
if url := req.PluginDownloadURL(); url != "" {
providers.SetProviderURL(inputs, url)
}
inputs, failures, err := i.deployment.providers.Check(urn, nil, inputs, false, nil)
if err != nil {
return nil, result.Errorf("failed to validate provider config: %v", err), false
}
state := resource.NewState(typ, urn, true, false, "", inputs, nil, "", false, false, nil, nil, "", nil, false,
nil, nil, nil, "", false, "")
// TODO(seqnum) should default providers be created with 1? When do they ever get recreated/replaced?
if issueCheckErrors(i.deployment, state, urn, failures) {
return nil, nil, false
}
steps[idx] = NewCreateStep(i.deployment, noopEvent(0), state)
}
// Issue the create steps.
if !i.executeParallel(ctx, steps...) {
return nil, nil, false
}
// Update the URN to reference map.
for _, s := range steps {
res := s.Res()
id := res.ID
if i.preview {
id = providers.UnknownID
}
ref, err := providers.NewReference(res.URN, id)
contract.AssertNoError(err)
urnToReference[res.URN] = ref.String()
}
return urnToReference, nil, true
}
func (i *importer) importResources(ctx context.Context) result.Result {
contract.Assert(len(i.deployment.imports) != 0)
if !i.registerExistingResources(ctx) {
return nil
}
stackURN, createdStack, ok := i.getOrCreateStackResource(ctx)
if !ok {
return nil
}
urnToReference, res, ok := i.registerProviders(ctx)
if !ok {
return res
}
// Create a step per resource to import and execute them in parallel. If there are duplicates, fail the import.
urns := map[resource.URN]struct{}{}
steps := make([]Step, 0, len(i.deployment.imports))
for _, imp := range i.deployment.imports {
parent := imp.Parent
if parent == "" {
parent = stackURN
}
urn := i.deployment.generateURN(parent, imp.Type, imp.Name)
// Check for duplicate imports.
if _, has := urns[urn]; has {
return result.Errorf("duplicate import '%v' of type '%v'", imp.Name, imp.Type)
}
urns[urn] = struct{}{}
// If the resource already exists and the ID matches the ID to import, skip this resource. If the ID does
// not match, the step itself will issue an error.
if old, ok := i.deployment.olds[urn]; ok {
oldID := old.ID
if old.ImportID != "" {
oldID = old.ImportID
}
if oldID == imp.ID {
continue
}
}
providerURN := imp.Provider
if providerURN == "" {
req := providers.NewProviderRequest(imp.Version, imp.Type.Package(), imp.PluginDownloadURL)
typ, name := providers.MakeProviderType(req.Package()), req.Name()
providerURN = i.deployment.generateURN("", typ, name)
}
// Fetch the provider reference for this import. All provider URNs should be mapped.
provider, ok := urnToReference[providerURN]
contract.Assert(ok)
// If we have a plan for this resource we need to feed the saved seed to Check to remove non-determinism
var randomSeed []byte
if i.deployment.plan != nil {
if resourcePlan, ok := i.deployment.plan.ResourcePlans[urn]; ok {
randomSeed = resourcePlan.Seed
}
} else {
randomSeed = make([]byte, 32)
n, err := cryptorand.Read(randomSeed)
contract.AssertNoError(err)
contract.Assert(n == len(randomSeed))
}
// Create the new desired state. Note that the resource is protected.
new := resource.NewState(urn.Type(), urn, true, false, imp.ID, resource.PropertyMap{}, nil, parent, imp.Protect,
false, nil, nil, provider, nil, false, nil, nil, nil, "", false, "")
steps = append(steps, newImportDeploymentStep(i.deployment, new, randomSeed))
}
if !i.executeParallel(ctx, steps...) {
return nil
}
if createdStack {
i.executor.ExecuteRegisterResourceOutputs(noopOutputsEvent(stackURN))
}
return nil
}