/
context.go
1902 lines (1677 loc) 路 60.1 KB
/
context.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 2016-2021, 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.
//go:generate go run generate/main.go
package pulumi
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"sort"
"strings"
"sync"
multierror "github.com/hashicorp/go-multierror"
"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/slice"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"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/rpcutil"
"github.com/pulumi/pulumi/sdk/v3/go/internal"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/structpb"
)
var disableResourceReferences = cmdutil.IsTruthy(os.Getenv("PULUMI_DISABLE_RESOURCE_REFERENCES"))
type workGroup = internal.WorkGroup
type contextState struct {
info RunInfo
stack Resource
exports map[string]Input
monitor pulumirpc.ResourceMonitorClient
monitorConn *grpc.ClientConn
engine pulumirpc.EngineClient
engineConn *grpc.ClientConn
keepResources bool // true if resources should be marshaled as strongly-typed references.
keepOutputValues bool // true if outputs should be marshaled as strongly-type output values.
supportsDeletedWith bool // true if deletedWith supported by pulumi
supportsAliasSpecs bool // true if full alias specification is supported by pulumi
rpcs int // the number of outstanding RPC requests.
rpcsDone *sync.Cond // an event signaling completion of RPCs.
rpcsLock sync.Mutex // a lock protecting the RPC count and event.
rpcError error // the first error (if any) encountered during an RPC.
join workGroup // the waitgroup for non-RPC async work associated with this context
}
// Context handles registration of resources and exposes metadata about the current deployment context.
type Context struct {
state *contextState
ctx context.Context
Log Log // the logging interface for the Pulumi log stream.
}
// NewContext creates a fresh run context out of the given metadata.
func NewContext(ctx context.Context, info RunInfo) (*Context, error) {
// Connect to the gRPC endpoints if we have addresses for them.
var monitorConn *grpc.ClientConn
var monitor pulumirpc.ResourceMonitorClient
if addr := info.MonitorAddr; addr != "" {
conn, err := grpc.Dial(
info.MonitorAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
rpcutil.GrpcChannelOptions(),
)
if err != nil {
return nil, fmt.Errorf("connecting to resource monitor over RPC: %w", err)
}
monitorConn = conn
monitor = pulumirpc.NewResourceMonitorClient(monitorConn)
}
var engineConn *grpc.ClientConn
var engine pulumirpc.EngineClient
if info.engineConn != nil {
engineConn = info.engineConn
engine = pulumirpc.NewEngineClient(engineConn)
} else if addr := info.EngineAddr; addr != "" {
conn, err := grpc.Dial(
info.EngineAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
rpcutil.GrpcChannelOptions(),
)
if err != nil {
return nil, fmt.Errorf("connecting to engine over RPC: %w", err)
}
engineConn = conn
engine = pulumirpc.NewEngineClient(engineConn)
}
if info.Mocks != nil {
monitor = &mockMonitor{project: info.Project, stack: info.Stack, mocks: info.Mocks}
engine = &mockEngine{}
}
if wrap := info.wrapResourceMonitorClient; wrap != nil {
monitor = wrap(monitor)
}
supportsFeature := func(id string) (bool, error) {
if monitor != nil {
resp, err := monitor.SupportsFeature(ctx, &pulumirpc.SupportsFeatureRequest{Id: id})
if err != nil {
return false, fmt.Errorf("checking monitor features: %w", err)
}
return resp.GetHasSupport(), nil
}
return false, nil
}
keepResources, err := supportsFeature("resourceReferences")
if err != nil {
return nil, err
}
keepOutputValues, err := supportsFeature("outputValues")
if err != nil {
return nil, err
}
supportsDeletedWith, err := supportsFeature("deletedWith")
if err != nil {
return nil, err
}
supportsAliasSpecs, err := supportsFeature("aliasSpecs")
if err != nil {
return nil, err
}
contextState := &contextState{
info: info,
exports: make(map[string]Input),
monitorConn: monitorConn,
monitor: monitor,
engineConn: engineConn,
engine: engine,
keepResources: keepResources,
keepOutputValues: keepOutputValues,
supportsDeletedWith: supportsDeletedWith,
supportsAliasSpecs: supportsAliasSpecs,
}
contextState.rpcsDone = sync.NewCond(&contextState.rpcsLock)
context := &Context{
state: contextState,
ctx: ctx,
}
context.Log = &logState{
engine: engine,
ctx: ctx,
join: &contextState.join,
}
return context, nil
}
// Context returns the base context used to instantiate the current context.
func (ctx *Context) Context() context.Context {
return ctx.ctx
}
// WithValue returns a copy of base context in which the value associated with key is val.
func (ctx *Context) WithValue(key, val any) *Context {
newCtx := &Context{
ctx: ctx.ctx,
state: ctx.state,
Log: ctx.Log,
}
newCtx.ctx = context.WithValue(newCtx.ctx, key, val)
return newCtx
}
// Value returns the value associated with key from base context
func (ctx *Context) Value(key any) any {
return ctx.ctx.Value(key)
}
// Close implements io.Closer and relinquishes any outstanding resources held by the context.
func (ctx *Context) Close() error {
if ctx.state.engineConn != nil {
if err := ctx.state.engineConn.Close(); err != nil {
return err
}
}
if ctx.state.monitorConn != nil {
if err := ctx.state.monitorConn.Close(); err != nil {
return err
}
}
return nil
}
// wait waits for all asynchronous work associated with this context to drain. RPCs may not be queued once wait
// returns.
func (ctx *Context) wait() error {
// Wait for async work to flush.
ctx.state.join.Wait()
// Ensure all outstanding RPCs have completed before proceeding. Also, prevent any new RPCs from happening.
ctx.state.rpcsLock.Lock()
defer ctx.state.rpcsLock.Unlock()
// Wait until the RPC count hits zero.
for ctx.state.rpcs > 0 {
ctx.state.rpcsDone.Wait()
}
// Mark the RPCs flag so that no more RPCs are permitted.
ctx.state.rpcs = noMoreRPCs
if ctx.state.rpcError != nil {
return fmt.Errorf("waiting for RPCs: %w", ctx.state.rpcError)
}
return nil
}
// Organization returns the current organization name.
func (ctx *Context) Organization() string {
org := ctx.state.info.Organization
if org == "" {
org = "organization"
}
return org
}
// Project returns the current project name.
func (ctx *Context) Project() string { return ctx.state.info.Project }
// Stack returns the current stack name being deployed into.
func (ctx *Context) Stack() string { return ctx.state.info.Stack }
// Parallel returns the degree of parallelism currently being used by the engine (1 being entirely serial).
func (ctx *Context) Parallel() int { return ctx.state.info.Parallel }
// DryRun is true when evaluating a program for purposes of planning, instead of performing a true deployment.
func (ctx *Context) DryRun() bool { return ctx.state.info.DryRun }
// RunningWithMocks is true if the program is running using a Mock monitor instead of a real Pulumi engine.
func (ctx *Context) RunningWithMocks() bool {
_, isMockMonitor := ctx.state.monitor.(*mockMonitor)
return isMockMonitor
}
// GetConfig returns the config value, as a string, and a bool indicating whether it exists or not.
func (ctx *Context) GetConfig(key string) (string, bool) {
v, ok := ctx.state.info.Config[key]
return v, ok
}
// IsConfigSecret returns true if the config value is a secret.
func (ctx *Context) IsConfigSecret(key string) bool {
for _, secretKey := range ctx.state.info.ConfigSecretKeys {
if key == secretKey {
return true
}
}
return false
}
// Invoke will invoke a provider's function, identified by its token tok. This function call is synchronous.
//
// args and result must be pointers to struct values fields and appropriately tagged and typed for use with Pulumi.
func (ctx *Context) Invoke(tok string, args interface{}, result interface{}, opts ...InvokeOption) (err error) {
if tok == "" {
return errors.New("invoke token must not be empty")
}
resultV := reflect.ValueOf(result)
if !(resultV.Kind() == reflect.Ptr &&
(resultV.Elem().Kind() == reflect.Struct ||
(resultV.Elem().Kind() == reflect.Map && resultV.Elem().Type().Key().Kind() == reflect.String))) {
return errors.New("result must be a pointer to a struct or map value")
}
options, err := NewInvokeOptions(opts...)
if err != nil {
return err
}
// Note that we're about to make an outstanding RPC request, so that we can rendezvous during shutdown.
if err = ctx.beginRPC(); err != nil {
return err
}
defer ctx.endRPC(err)
var providerRef string
providers, err := ctx.mergeProviders(tok, options.Parent, options.Provider, nil)
if err != nil {
return err
}
if provider := providers[getPackage(tok)]; provider != nil {
pr, err := ctx.resolveProviderReference(provider)
if err != nil {
return err
}
providerRef = pr
}
// Serialize arguments. Outputs will not be awaited: instead, an error will be returned if any Outputs are present.
if args == nil {
args = struct{}{}
}
resolvedArgs, _, err := marshalInput(args, anyType, false)
if err != nil {
return fmt.Errorf("marshaling arguments: %w", err)
}
resolvedArgsMap := resource.PropertyMap{}
if resolvedArgs.IsObject() {
resolvedArgsMap = resolvedArgs.ObjectValue()
}
rpcArgs, err := plugin.MarshalProperties(
resolvedArgsMap,
ctx.withKeepOrRejectUnknowns(plugin.MarshalOptions{
KeepSecrets: true,
KeepResources: ctx.state.keepResources,
}),
)
if err != nil {
return fmt.Errorf("marshaling arguments: %w", err)
}
// Now, invoke the RPC to the provider synchronously.
logging.V(9).Infof("Invoke(%s, #args=%d): RPC call being made synchronously", tok, len(resolvedArgsMap))
resp, err := ctx.state.monitor.Invoke(ctx.ctx, &pulumirpc.ResourceInvokeRequest{
Tok: tok,
Args: rpcArgs,
Provider: providerRef,
Version: options.Version,
PluginDownloadURL: options.PluginDownloadURL,
AcceptResources: !disableResourceReferences,
})
if err != nil {
logging.V(9).Infof("Invoke(%s, ...): error: %v", tok, err)
return err
}
// If there were any failures from the provider, return them.
if len(resp.Failures) > 0 {
logging.V(9).Infof("Invoke(%s, ...): success: w/ %d failures", tok, len(resp.Failures))
var ferr error
for _, failure := range resp.Failures {
ferr = multierror.Append(ferr,
fmt.Errorf("%s invoke failed: %s (%s)", tok, failure.Reason, failure.Property))
}
return ferr
}
// Otherwise, simply unmarshal the output properties and return the result.
outProps, err := plugin.UnmarshalProperties(
resp.Return,
ctx.withKeepOrRejectUnknowns(plugin.MarshalOptions{
KeepSecrets: true,
KeepResources: true,
}),
)
if err != nil {
return err
}
// fail if there are secrets returned from the invoke
hasSecret, err := unmarshalOutput(ctx, resource.NewObjectProperty(outProps), resultV.Elem())
if err != nil {
return err
}
if hasSecret {
return errors.New("unexpected secret result returned to invoke call")
}
logging.V(9).Infof("Invoke(%s, ...): success: w/ %d outs (err=%v)", tok, len(outProps), err)
return nil
}
// Call will invoke a provider call function, identified by its token tok.
//
// output is used to determine the output type to return; self is optional for methods.
func (ctx *Context) Call(tok string, args Input, output Output, self Resource, opts ...InvokeOption) (Output, error) {
if tok == "" {
return nil, errors.New("call token must not be empty")
}
output = ctx.newOutput(reflect.TypeOf(output))
options, err := NewInvokeOptions(opts...)
if err != nil {
return nil, err
}
// Note that we're about to make an outstanding RPC request, so that we can rendezvous during shutdown.
if err := ctx.beginRPC(); err != nil {
return nil, err
}
prepareCallRequest := func() (*pulumirpc.CallRequest, error) {
// Determine the provider, version and url to use.
var provider ProviderResource
var version string
var pluginURL string
if self != nil {
provider = self.getProvider()
version = self.getVersion()
pluginURL = self.getPluginDownloadURL()
} else {
providers, err := ctx.mergeProviders(tok, options.Parent, options.Provider, nil)
if err != nil {
return nil, err
}
provider = providers[getPackage(tok)]
version = options.Version
pluginURL = options.PluginDownloadURL
}
var providerRef string
if provider != nil {
pr, err := ctx.resolveProviderReference(provider)
if err != nil {
return nil, err
}
providerRef = pr
}
// Serialize all args, first by awaiting them, and then marshaling them to the requisite gRPC values.
resolvedArgs, argDeps, _, err := marshalInputs(args)
if err != nil {
return nil, fmt.Errorf("marshaling args: %w", err)
}
// If we have a value for self, add it to the arguments.
if self != nil {
var deps []URN
resolvedSelf, selfDeps, err := marshalInput(self, reflect.TypeOf(self), true)
if err != nil {
return nil, fmt.Errorf("marshaling __self__: %w", err)
}
for _, dep := range selfDeps {
depURN, _, _, err := dep.URN().awaitURN(context.TODO())
if err != nil {
return nil, err
}
deps = append(deps, depURN)
}
resolvedArgs["__self__"] = resolvedSelf
argDeps["__self__"] = deps
}
// Marshal all properties for the RPC call.
rpcArgs, err := plugin.MarshalProperties(
resolvedArgs,
ctx.withKeepOrRejectUnknowns(plugin.MarshalOptions{
KeepSecrets: true,
KeepResources: ctx.state.keepResources,
KeepOutputValues: ctx.state.keepOutputValues,
}))
if err != nil {
return nil, fmt.Errorf("marshaling args: %w", err)
}
// Convert the arg dependencies map for RPC and remove duplicates.
rpcArgDeps := make(map[string]*pulumirpc.CallRequest_ArgumentDependencies)
for k, deps := range argDeps {
sort.Slice(deps, func(i, j int) bool { return deps[i] < deps[j] })
urns := slice.Prealloc[string](len(deps))
for i, d := range deps {
if i > 0 && urns[i-1] == string(d) {
continue
}
urns = append(urns, string(d))
}
rpcArgDeps[k] = &pulumirpc.CallRequest_ArgumentDependencies{
Urns: urns,
}
}
return &pulumirpc.CallRequest{
Tok: tok,
Args: rpcArgs,
ArgDependencies: rpcArgDeps,
Provider: providerRef,
Version: version,
PluginDownloadURL: pluginURL,
}, nil
}
// Kick off the call.
go func() {
var ret *structpb.Struct
var deps []Resource
var err error
defer func() {
defer ctx.endRPC(err)
var outprops resource.PropertyMap
if err == nil {
outprops, err = plugin.UnmarshalProperties(ret, ctx.withKeepOrRejectUnknowns(plugin.MarshalOptions{
KeepSecrets: true,
KeepResources: true,
}))
}
if err != nil {
logging.V(9).Infof("Call(%s, ...): success: w/ unmarshal error: %v", tok, err)
internal.RejectOutput(output, err)
return
}
// Allocate storage for the unmarshalled output.
var secret bool
dest := reflect.New(output.ElementType()).Elem()
known := !outprops.ContainsUnknowns()
secret, err = unmarshalOutput(ctx, resource.NewObjectProperty(outprops), dest)
if err != nil {
internal.RejectOutput(output, err)
} else {
internal.ResolveOutput(output, dest.Interface(), known, secret, resourcesToInternal(deps))
}
logging.V(9).Infof("Call(%s, ...): success: w/ %d outs (err=%v)", tok, len(outprops), err)
}()
// Prepare the RPC request.
var req *pulumirpc.CallRequest
req, err = prepareCallRequest()
if err != nil {
return
}
// Now, call the RPC.
var resp *pulumirpc.CallResponse
logging.V(9).Infof("Call(%s): Goroutine spawned, RPC call being made", tok)
resp, err = ctx.state.monitor.Call(ctx.ctx, req)
if err != nil {
logging.V(9).Infof("Call(%s, ...): error: %v", tok, err)
} else if len(resp.Failures) > 0 {
logging.V(9).Infof("Call(%s, ...): success: w/ %d failures", tok, len(resp.Failures))
for _, failure := range resp.Failures {
err = multierror.Append(err,
fmt.Errorf("%s call failed: %s (%s)", tok, failure.Reason, failure.Property))
}
}
if resp != nil {
ret = resp.Return
// Combine the individual dependencies into a single set of dependency resources.
urns := make(map[string]struct{})
for _, returnDependencies := range resp.GetReturnDependencies() {
for _, urn := range returnDependencies.GetUrns() {
urns[urn] = struct{}{}
}
}
for urn := range urns {
deps = append(deps, ctx.newDependencyResource(URN(urn)))
}
}
}()
return output, nil
}
// ReadResource reads an existing custom resource's state from the resource monitor. t is the fully qualified type
// token and name is the "name" part to use in creating a stable and globally unique URN for the object. id is the ID
// of the resource to read, and props contains any state necessary to perform the read (typically props will be nil).
// opts contains optional settings that govern the way the resource is managed.
//
// The value passed to resource must be a pointer to a struct. The fields of this struct that correspond to output
// properties of the resource must have types that are assignable from Output, and must have a `pulumi` tag that
// records the name of the corresponding output property. The struct must embed the CustomResourceState type.
//
// For example, given a custom resource with an int-typed output "foo" and a string-typed output "bar", one would
// define the following CustomResource type:
//
// type MyResource struct {
// pulumi.CustomResourceState
//
// Foo pulumi.IntOutput `pulumi:"foo"`
// Bar pulumi.StringOutput `pulumi:"bar"`
// }
//
// And invoke ReadResource like so:
//
// var resource MyResource
// err := ctx.ReadResource(tok, name, id, nil, &resource, opts...)
func (ctx *Context) ReadResource(
t, name string, id IDInput, props Input, resource CustomResource, opts ...ResourceOption,
) error {
if t == "" {
return errors.New("resource type argument cannot be empty")
} else if name == "" {
return errors.New("resource name argument (for URN creation) cannot be empty")
} else if id == nil {
return errors.New("resource ID is required for lookup and cannot be empty")
}
if props != nil {
propsType := reflect.TypeOf(props)
if propsType.Kind() == reflect.Ptr {
propsType = propsType.Elem()
}
if !(propsType.Kind() == reflect.Struct ||
(propsType.Kind() == reflect.Map && propsType.Key().Kind() == reflect.String)) {
return errors.New("props must be a struct or map or a pointer to a struct or map")
}
}
options := merge(opts...)
parent := options.Parent
if options.Parent == nil {
options.Parent = ctx.state.stack
}
// Before anything else, if there are transformations registered, give them a chance to run to modify the
// user-provided properties and options assigned to this resource.
props, options, transformations, err := applyTransformations(t, name, props, resource, opts, options)
if err != nil {
return err
}
// Collapse aliases to URNs.
var aliasURNs []URNOutput
if options.Aliases != nil {
aliasURNs = make([]URNOutput, len(options.Aliases))
project, stack := ctx.Project(), ctx.Stack()
for i, alias := range options.Aliases {
aliasURN, err := alias.collapseToURN(name, t, parent, project, stack)
if err != nil {
return fmt.Errorf("failed to collapse alias to URN: %w", err)
}
aliasURNs[i] = aliasURN
}
}
if options.DeletedWith != nil && !ctx.state.supportsDeletedWith {
return errors.New("the Pulumi CLI does not support the DeletedWith option. Please update the Pulumi CLI")
}
// Note that we're about to make an outstanding RPC request, so that we can rendezvous during shutdown.
if err := ctx.beginRPC(); err != nil {
return err
}
// Merge providers.
providers, err := ctx.mergeProviders(t, options.Parent, options.Provider, options.Providers)
if err != nil {
return err
}
// Get the provider for the resource.
provider := getProvider(t, options.Provider, providers)
// Create resolvers for the resource's outputs.
res := ctx.makeResourceState(t, name, resource, providers, provider,
options.Version, options.PluginDownloadURL, aliasURNs, transformations)
// Get the source position for the resource registration. Note that this assumes that there is an intermediate
// between the this function and user code.
sourcePosition := ctx.getSourcePosition(2)
// Kick off the resource read operation. This will happen asynchronously and resolve the above properties.
go func() {
// No matter the outcome, make sure all promises are resolved and that we've signaled completion of this RPC.
var urn, resID string
var inputs *resourceInputs
var state *structpb.Struct
var err error
defer func() {
res.resolve(ctx, err, inputs, urn, resID, state, nil)
ctx.endRPC(err)
}()
idToRead, known, _, err := id.ToIDOutput().awaitID(context.TODO())
if !known || err != nil {
return
}
// Prepare the inputs for an impending operation.
inputs, err = ctx.prepareResourceInputs(resource, props, t, options, res, false /* remote */, true /* custom */)
if err != nil {
return
}
logging.V(9).Infof("ReadResource(%s, %s): Goroutine spawned, RPC call being made", t, name)
resp, err := ctx.state.monitor.ReadResource(ctx.ctx, &pulumirpc.ReadResourceRequest{
Type: t,
Name: name,
Parent: inputs.parent,
Properties: inputs.rpcProps,
Provider: inputs.provider,
Id: string(idToRead),
AcceptSecrets: true,
AcceptResources: !disableResourceReferences,
AdditionalSecretOutputs: inputs.additionalSecretOutputs,
SourcePosition: sourcePosition,
})
if err != nil {
logging.V(9).Infof("ReadResource(%s, %s): error: %v", t, name, err)
} else {
logging.V(9).Infof("ReadResource(%s, %s): success: %s %s ...", t, name, resp.Urn, id)
}
if resp != nil {
urn, resID = resp.Urn, string(idToRead)
state = resp.Properties
}
}()
return nil
}
// RegisterResource creates and registers a new resource object. t is the fully qualified type token and name is
// the "name" part to use in creating a stable and globally unique URN for the object. props contains the goal state
// for the resource object and opts contains optional settings that govern the way the resource is created.
//
// The value passed to resource must be a pointer to a struct. The fields of this struct that correspond to output
// properties of the resource must have types that are assignable from Output, and must have a `pulumi` tag that
// records the name of the corresponding output property. The struct must embed either the ResourceState or the
// CustomResourceState type.
//
// For example, given a custom resource with an int-typed output "foo" and a string-typed output "bar", one would
// define the following CustomResource type:
//
// type MyResource struct {
// pulumi.CustomResourceState
//
// Foo pulumi.IntOutput `pulumi:"foo"`
// Bar pulumi.StringOutput `pulumi:"bar"`
// }
//
// And invoke RegisterResource like so:
//
// var resource MyResource
// err := ctx.RegisterResource(tok, name, props, &resource, opts...)
func (ctx *Context) RegisterResource(
t, name string, props Input, resource Resource, opts ...ResourceOption,
) error {
return ctx.registerResource(t, name, props, resource, false /*remote*/, opts...)
}
func (ctx *Context) getResource(urn string) (*pulumirpc.RegisterResourceResponse, error) {
// This is a resource that already exists. Read its state from the engine.
resolvedArgsMap := resource.NewPropertyMapFromMap(map[string]interface{}{
"urn": urn,
})
rpcArgs, err := plugin.MarshalProperties(
resolvedArgsMap,
ctx.withKeepOrRejectUnknowns(plugin.MarshalOptions{
KeepSecrets: true,
KeepResources: ctx.state.keepResources,
}),
)
if err != nil {
return nil, fmt.Errorf("marshaling arguments: %w", err)
}
tok := "pulumi:pulumi:getResource"
logging.V(9).Infof("Invoke(%s, #args=%d): RPC call being made synchronously", tok, len(resolvedArgsMap))
resp, err := ctx.state.monitor.Invoke(ctx.ctx, &pulumirpc.ResourceInvokeRequest{
Tok: "pulumi:pulumi:getResource",
Args: rpcArgs,
AcceptResources: !disableResourceReferences,
})
if err != nil {
return nil, fmt.Errorf("invoke(%s, ...): error: %w", tok, err)
}
// If there were any failures from the provider, return them.
if len(resp.Failures) > 0 {
logging.V(9).Infof("Invoke(%s, ...): success: w/ %d failures", tok, len(resp.Failures))
var ferr error
for _, failure := range resp.Failures {
ferr = multierror.Append(ferr,
fmt.Errorf("%s invoke failed: %s (%s)", tok, failure.Reason, failure.Property))
}
return nil, ferr
}
return &pulumirpc.RegisterResourceResponse{
Urn: resp.Return.Fields["urn"].GetStringValue(),
Id: resp.Return.Fields["id"].GetStringValue(),
Object: resp.Return.Fields["state"].GetStructValue(),
}, nil
}
func (ctx *Context) registerResource(
t, name string, props Input, resource Resource, remote bool, opts ...ResourceOption,
) error {
if t == "" {
return errors.New("resource type argument cannot be empty")
} else if name == "" {
return errors.New("resource name argument (for URN creation) cannot be empty")
}
if _, isProvider := resource.(ProviderResource); isProvider && !strings.HasPrefix(t, "pulumi:providers:") {
return errors.New("provider resource type must begin with \"pulumi:providers:\"")
}
if props != nil {
propsType := reflect.TypeOf(props)
if propsType.Kind() == reflect.Ptr {
propsType = propsType.Elem()
}
if !(propsType.Kind() == reflect.Struct ||
(propsType.Kind() == reflect.Map && propsType.Key().Kind() == reflect.String)) {
return errors.New("props must be a struct or map or a pointer to a struct or map")
}
}
options := merge(opts...)
if parent := options.Parent; parent != nil && internal.GetOutputState(parent.URN()) == nil {
// Guard against uninitialized parent resources to prevent
// panics from invalid state further down the line.
// Uninitialized parent resources won't have a URN.
resourceType := "resource"
registerMethod := "RegisterResource"
if _, parentIsCustom := parent.(CustomResource); !parentIsCustom {
resourceType = "component resource"
registerMethod = "RegisterComponentResource"
}
err := ctx.Log.Warn(fmt.Sprintf(
"Ignoring %v %T (parent of %v :: %v) because it was not registered with %v",
resourceType, parent, name, t, registerMethod), nil /* args */)
contract.IgnoreError(err)
options.Parent = nil
}
_, custom := resource.(CustomResource)
isRemoteComponentOrRehydratedComponent := !custom && (remote || options.URN != "")
if isRemoteComponentOrRehydratedComponent {
resource.setKeepDependency()
}
parent := options.Parent
if options.Parent == nil {
options.Parent = ctx.state.stack
}
// Before anything else, if there are transformations registered, give them a chance to run to modify the
// user-provided properties and options assigned to this resource.
props, options, transformations, err := applyTransformations(t, name, props, resource, opts, options)
if err != nil {
return err
}
// Collapse aliases to URNs.
var aliasURNs []URNOutput
if options.Aliases != nil {
aliasURNs = make([]URNOutput, len(options.Aliases))
project, stack := ctx.Project(), ctx.Stack()
for i, alias := range options.Aliases {
aliasURN, err := alias.collapseToURN(name, t, parent, project, stack)
if err != nil {
return fmt.Errorf("failed to collapse alias to URN: %w", err)
}
aliasURNs[i] = aliasURN
}
}
// Note that we're about to make an outstanding RPC request, so that we can rendezvous during shutdown.
if err := ctx.beginRPC(); err != nil {
return err
}
// Merge providers.
providers, err := ctx.mergeProviders(t, options.Parent, options.Provider, options.Providers)
if err != nil {
return err
}
// Get the provider for the resource.
provider := getProvider(t, options.Provider, providers)
// Create resolvers for the resource's outputs.
resState := ctx.makeResourceState(t, name, resource, providers, provider,
options.Version, options.PluginDownloadURL, aliasURNs, transformations)
// Get the source position for the resource registration. Note that this assumes that there are two intermediate
// frames between this function and user code.
sourcePosition := ctx.getSourcePosition(3)
// Kick off the resource registration. If we are actually performing a deployment, the resulting properties
// will be resolved asynchronously as the RPC operation completes. If we're just planning, values won't resolve.
go func() {
// No matter the outcome, make sure all promises are resolved and that we've signaled completion of this RPC.
var urn, resID string
var inputs *resourceInputs
var state *structpb.Struct
deps := make(map[string][]Resource)
var err error
defer func() {
resState.resolve(ctx, err, inputs, urn, resID, state, deps)
ctx.endRPC(err)
}()
// Prepare the inputs for an impending operation.
inputs, err = ctx.prepareResourceInputs(resource, props, t, options, resState, remote, custom)
if err != nil {
return
}
// initialize both aliases and aliasURNs slices as nil
// depending on supportsAliasSpecs flag, one of them will be populated
// and sent off to the engine for registring the resource
var (
aliasURNs []string
aliases []*pulumirpc.Alias
)
if !ctx.state.supportsAliasSpecs {
aliasURNs = make([]string, len(inputs.aliases))
for i, alias := range inputs.aliases {
aliasURNs[i] = alias.GetUrn()
}
} else {
aliases = inputs.aliases
}
var resp *pulumirpc.RegisterResourceResponse
if options.URN != "" {
resp, err = ctx.getResource(options.URN)
if err != nil {
logging.V(9).Infof("getResource(%s, %s): error: %v", t, name, err)
} else {
logging.V(9).Infof("getResource(%s, %s): success: %s %s ...", t, name, resp.Urn, resp.Id)
}
} else {
logging.V(9).Infof("RegisterResource(%s, %s): Goroutine spawned, RPC call being made", t, name)
resp, err = ctx.state.monitor.RegisterResource(ctx.ctx, &pulumirpc.RegisterResourceRequest{
Type: t,
Name: name,
Parent: inputs.parent,
Object: inputs.rpcProps,
Custom: custom,
Protect: inputs.protect,
Dependencies: inputs.deps,
Provider: inputs.provider,
Providers: inputs.providers,
PropertyDependencies: inputs.rpcPropertyDeps,
DeleteBeforeReplace: inputs.deleteBeforeReplace,
ImportId: inputs.importID,
CustomTimeouts: inputs.customTimeouts,
IgnoreChanges: inputs.ignoreChanges,
AliasURNs: aliasURNs,
Aliases: aliases,
AcceptSecrets: true,
AcceptResources: !disableResourceReferences,
AdditionalSecretOutputs: inputs.additionalSecretOutputs,
Version: inputs.version,
PluginDownloadURL: inputs.pluginDownloadURL,
Remote: remote,
ReplaceOnChanges: inputs.replaceOnChanges,
RetainOnDelete: inputs.retainOnDelete,
DeletedWith: inputs.deletedWith,
SourcePosition: sourcePosition,
})
if err != nil {
logging.V(9).Infof("RegisterResource(%s, %s): error: %v", t, name, err)
} else {
logging.V(9).Infof("RegisterResource(%s, %s): success: %s %s ...", t, name, resp.Urn, resp.Id)
}
}
if resp != nil {
urn, resID = resp.Urn, resp.Id
state = resp.Object
for key, propertyDependencies := range resp.GetPropertyDependencies() {
var resources []Resource
for _, urn := range propertyDependencies.GetUrns() {
resources = append(resources, &ResourceState{urn: URNInput(URN(urn)).ToURNOutput()})
}
deps[key] = resources
}
}
}()