-
Notifications
You must be signed in to change notification settings - Fork 19
/
schema.go
1568 lines (1424 loc) · 51.1 KB
/
schema.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-2022, 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 gen
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/gedex/inflector"
"github.com/imdario/mergo"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-google-native/provider/pkg/resources"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/deepcopy"
"google.golang.org/api/discovery/v1"
)
// Note - this needs to be kept in sync with the layout in the SDK package
const goBasePath = "github.com/pulumi/pulumi-google-native/sdk/go/google"
// PulumiSchema will generate a Pulumi schema for the given Google Cloud discovery documents.
func PulumiSchema() (*schema.PackageSpec, *resources.CloudAPIMetadata, error) {
pkg := schema.PackageSpec{
Name: "google-native",
DisplayName: "Google Cloud Native",
Description: "A native Pulumi package for creating and managing Google Cloud resources.",
License: "Apache-2.0",
Keywords: []string{"pulumi", "google cloud", "category/cloud", "kind/native"},
Homepage: "https://pulumi.com",
Publisher: "Pulumi",
Repository: "https://github.com/pulumi/pulumi-google-native",
Config: schema.ConfigSpec{
Variables: map[string]schema.PropertySpec{
"project": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default project to manage resources in. If another project is specified on a resource, it will take precedence.",
},
"region": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default region to manage resources in. If another region is specified on a regional resource, it will take precedence.",
},
"zone": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default zone to manage resources in. Generally, this zone should be within the default region you specified. If another zone is specified on a zonal resource, it will take precedence.",
},
// Google Partner Name for User-Agent.
"partnerName": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "A Google Partner Name to facilitate partner resource usage attribution.",
},
"disablePartnerName": {
TypeSpec: schema.TypeSpec{Type: "boolean"},
Description: "This will disable the Pulumi Partner Name which is used if a custom `partnerName` isn't specified.",
},
"appendUserAgent": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "Additional user-agent string to append to the default one (<prod_name>/<ver>).",
},
},
},
Provider: schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "The provider type for the Google Cloud package.",
Type: "object",
Properties: map[string]schema.PropertySpec{
"project": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default project to manage resources in. If another project is specified on a resource, it will take precedence.",
},
"region": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default region to manage resources in. If another region is specified on a regional resource, it will take precedence.",
},
"zone": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The default zone to manage resources in. Generally, this zone should be within the default region you specified. If another zone is specified on a zonal resource, it will take precedence.",
},
},
},
InputProperties: map[string]schema.PropertySpec{
"project": {
TypeSpec: schema.TypeSpec{Type: "string"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_PROJECT",
"GOOGLE_CLOUD_PROJECT",
"GCLOUD_PROJECT",
"CLOUDSDK_CORE_PROJECT",
},
},
Description: "The default project to manage resources in. If another project is specified on a resource, it will take precedence.",
},
"region": {
TypeSpec: schema.TypeSpec{Type: "string"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_REGION",
"GCLOUD_REGION",
"CLOUDSDK_COMPUTE_REGION",
},
},
Description: "The default region to manage resources in. If another region is specified on a regional resource, it will take precedence.",
},
"zone": {
TypeSpec: schema.TypeSpec{Type: "string"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_ZONE",
"GCLOUD_ZONE",
"CLOUDSDK_COMPUTE_ZONE",
},
},
Description: "The default zone to manage resources in. Generally, this zone should be within the default region you specified. If another zone is specified on a zonal resource, it will take precedence.",
},
// Google Partner Name for User-Agent.
"partnerName": {
TypeSpec: schema.TypeSpec{Type: "string"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_PARTNER_NAME",
},
},
Description: "A Google Partner Name to facilitate partner resource usage attribution.",
},
"disablePartnerName": {
TypeSpec: schema.TypeSpec{Type: "boolean"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_DISABLE_PARTNER_NAME",
},
},
Description: "This will disable the Pulumi Partner Name which is used if a custom `partnerName` isn't specified.",
},
"appendUserAgent": {
TypeSpec: schema.TypeSpec{Type: "string"},
DefaultInfo: &schema.DefaultSpec{
Environment: []string{
"GOOGLE_APPEND_USER_AGENT",
},
},
Description: "Additional user-agent string to append to the default one (<prod_name>/<ver>).",
},
},
},
Types: map[string]schema.ComplexTypeSpec{},
Resources: map[string]schema.ResourceSpec{},
Functions: map[string]schema.FunctionSpec{},
Language: map[string]schema.RawMessage{},
}
metadata := resources.CloudAPIMetadata{
Types: map[string]resources.CloudAPIType{},
Resources: map[string]resources.CloudAPIResource{},
Functions: map[string]resources.CloudAPIFunction{},
}
err := genMixins(&pkg)
if err != nil {
return nil, nil, err
}
csharpNamespaces := map[string]string{
"google-native": "GoogleNative",
}
javaPackages := map[string]string{}
pythonModuleNames := map[string]string{}
golangImportAliases := map[string]string{}
var fileNames []string
root := path.Join(".", "discovery")
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
fileNames = append(fileNames, path)
}
return nil
})
if err != nil {
return nil, nil, err
}
for _, fileName := range fileNames {
document, err := readDiscoveryDocument(fileName)
if err != nil {
return nil, nil, err
}
if document.Name == "" {
continue
}
module := fmt.Sprintf("%s/%s", document.Name, document.Version)
gen := packageGenerator{
pkg: &pkg,
metadata: &metadata,
rest: document,
mod: module,
visitedTypes: codegen.NewStringSet(),
docName: fileName,
}
csharpNamespaces[document.Name] = csharpNamespace(document)
csharpNamespaces[module] = csharpVersionedNamespace(document)
javaPackages[module] = fmt.Sprintf("%s.%s", document.Name, document.Version)
pythonModuleNames[module] = module
golangImportAliases[filepath.Join(goBasePath, module)] = document.Name
res, ops, err := findResources(fileName, document.Resources, document.Schemas)
if err != nil {
return nil, nil, err
}
for _, typeName := range codegen.SortedKeys(res) {
// Generate the resource itself.
err := gen.genResource(typeName, res[typeName], ops)
if err != nil {
return nil, nil, err
}
// Generate a getXyz function for each Xyz resource.
err = gen.genFunction(typeName, res[typeName].getMethod)
if err != nil {
return nil, nil, err
}
}
for _, additionalGetMethods := range findAdditionalGetFunctions(fileName, document) {
err = gen.genFunction(additionalGetMethods.ReturnTypeName, additionalGetMethods.Method)
if err != nil {
return nil, nil, err
}
}
}
for _, version := range []string{"v1", "v1beta1"} {
pkg.Functions[fmt.Sprintf("google-native:container/%s:Cluster/getKubeconfig", version)] = schema.FunctionSpec{
Description: "Generate a kubeconfig for cluster authentication." +
"\n\nThe kubeconfig generated is automatically stringified for ease of use with the pulumi/kubernetes" +
" provider.\nThe kubeconfig uses the new `gke-gcloud-auth-plugin` authentication plugin as" +
" recommended by Google.\n\n" +
"See for more details:\n" +
`- https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke`,
Inputs: &schema.ObjectTypeSpec{
Properties: map[string]schema.PropertySpec{
"__self__": {
TypeSpec: schema.TypeSpec{
Ref: fmt.Sprintf("#/resources/google-native:container/%s:Cluster", version),
},
},
},
Required: []string{"__self__"},
},
Outputs: &schema.ObjectTypeSpec{
Properties: map[string]schema.PropertySpec{
"kubeconfig": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
Required: []string{
"kubeconfig",
},
},
}
}
pkg.Language["go"] = rawMessage(map[string]interface{}{
"importBasePath": goBasePath,
"packageImportAliases": golangImportAliases,
"liftSingleValueMethodReturns": true,
})
pkg.Language["nodejs"] = rawMessage(map[string]interface{}{
"dependencies": map[string]string{
"@pulumi/pulumi": "^3.0.0",
},
"readme": `The native Google Cloud Provider for Pulumi lets you provision Google Cloud resources in your cloud
programs. This provider uses the Google Cloud REST API directly and therefore provides full access to Google Cloud.
The provider is currently in public preview and is not recommended for production deployments yet. Breaking changes
will be introduced in minor version releases.`,
"liftSingleValueMethodReturns": true,
})
pkg.Language["python"] = rawMessage(map[string]interface{}{
"moduleNameOverrides": pythonModuleNames,
"requires": map[string]string{
"pulumi": ">=3.0.0,<4.0.0",
},
"usesIOClasses": true,
"readme": `The native Google Cloud Provider for Pulumi lets you provision Google Cloud resources in your cloud
programs. This provider uses the Google Cloud REST API directly and therefore provides full access to Google Cloud.
The provider is currently in public preview and is not recommended for production deployments yet. Breaking changes
will be introduced in minor version releases.`,
"liftSingleValueMethodReturns": true,
"pyproject": map[string]bool{
"enabled": true,
},
})
pkg.Language["csharp"] = rawMessage(map[string]interface{}{
"packageReferences": map[string]string{
"Pulumi": "3.*",
},
"namespaces": csharpNamespaces,
"liftSingleValueMethodReturns": true,
})
pkg.Language["java"] = rawMessage(map[string]interface{}{
"packages": javaPackages,
"liftSingleValueMethodReturns": true,
})
return &pkg, &metadata, nil
}
func genMixins(pkg *schema.PackageSpec) error {
// Mixin 'getClientConfig' to read current configuration values.
if _, has := pkg.Functions["google-native:authorization:getClientConfig"]; has {
return errors.New("Invoke 'google-native:authorization:getClientConfig' is already defined")
}
pkg.Functions["google-native:authorization:getClientConfig"] = schema.FunctionSpec{
Description: "Use this function to access the current configuration of the native Google provider.",
Outputs: &schema.ObjectTypeSpec{
Description: "Configuration values returned by getClientConfig.",
Properties: map[string]schema.PropertySpec{
"project": {
Description: "Project of the current user.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
"region": {
Description: "Google Cloud region",
TypeSpec: schema.TypeSpec{Type: "string"},
},
"zone": {
Description: "Google Cloud zone",
TypeSpec: schema.TypeSpec{Type: "string"},
},
},
Type: "object",
Required: []string{"project", "region"},
},
}
// Mixin 'getClientToken' to obtain an Google auth token.
if _, has := pkg.Functions["google-native:authorization:getClientToken"]; has {
return errors.New("Invoke 'google-native:authorization:getClientToken' is already defined")
}
pkg.Functions["google-native:authorization:getClientToken"] = schema.FunctionSpec{
Description: "Use this function to get an Google authentication token for the current login context.",
Outputs: &schema.ObjectTypeSpec{
Description: "Configuration values returned by getClientToken.",
Properties: map[string]schema.PropertySpec{
"accessToken": {
Description: "The OAuth2 access token used by the client to authenticate against the Google Cloud API.",
TypeSpec: schema.TypeSpec{Type: "string"},
Secret: true,
},
"expiry": {
Description: "Expiry is the optional expiration time of the access token. If zero, TokenSource implementations will reuse the same token forever and RefreshToken or equivalent mechanisms for that TokenSource will not be used.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
"refreshToken": {
Description: "RefreshToken is a token that's used by the application (as opposed to the user) to refresh the access token if it expires.",
TypeSpec: schema.TypeSpec{Type: "string"},
Secret: true,
},
"tokenType": {
Description: `The type of auth token. Possible types are "Bearer", "MAC", "Basic".`,
TypeSpec: schema.TypeSpec{Type: "string"},
},
},
Type: "object",
Required: []string{"accessToken", "tokenType"},
},
}
return nil
}
var titleReplacer = strings.NewReplacer(" ", "", "-", "")
var versionReplacer = strings.NewReplacer("alpha", "Alpha", "beta", "Beta", "v", "V")
func csharpNamespace(document *discovery.RestDescription) string {
moduleName := strings.Title(document.Name)
if v, ok := csharpNamespaceOverrides[moduleName]; ok {
return v
}
title := titleReplacer.Replace(document.Title)
idx := strings.Index(strings.ToLower(title), document.Name)
if idx >= 0 {
moduleName = title[idx : idx+len(document.Name)]
}
return moduleName
}
func csharpVersionedNamespace(document *discovery.RestDescription) string {
moduleName := csharpNamespace(document)
version := versionReplacer.Replace(document.Version)
return fmt.Sprintf("%s.%s", moduleName, version)
}
func readDiscoveryDocument(fileName string) (*discovery.RestDescription, error) {
jsonFile, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, err
}
var rest discovery.RestDescription
err = json.Unmarshal(byteValue, &rest)
if err != nil {
return nil, err
}
return &rest, nil
}
type packageGenerator struct {
pkg *schema.PackageSpec
metadata *resources.CloudAPIMetadata
rest *discovery.RestDescription
mod string
visitedTypes codegen.StringSet
docName string
}
var pathRegex = regexp.MustCompile(`{([A-Za-z0-9]*)}`)
func (g *packageGenerator) genToken(typeName string) string {
return fmt.Sprintf(`%s:%s:%s`, g.pkg.Name, g.mod, typeName)
}
func (g *packageGenerator) fullPath(method *discovery.RestMethod, preferPath bool) string {
if method == nil {
return ""
}
var pathURL string
if !preferPath && len(method.FlatPath) > 0 {
pathURL = resources.AssembleURL(g.rest.RootUrl, g.rest.BasePath, method.FlatPath)
} else {
pathURL = resources.AssembleURL(g.rest.RootUrl, g.rest.BasePath, method.Path)
}
queryParams := url.Values{}
for param, details := range method.Parameters {
if isIgnoredQueryParam(param) {
continue
}
if details.Location != "query" || !isRequired(details) {
continue
}
queryParams.Add(param, "{"+param+"}")
}
if len(queryParams) > 0 {
var err error
pathURL, err = url.QueryUnescape(pathURL + "?" + queryParams.Encode())
if err != nil {
return ""
}
}
return pathURL
}
func (g *packageGenerator) genResource(typeName string, dd discoveryDocumentResource,
ops map[string]*operation) error {
resourceTok := g.genToken(typeName)
g.pkg.Types["google-native:iam/v1:Condition"] = iamCondition
properties := map[string]schema.PropertySpec{}
requiredProperties := codegen.NewStringSet()
inputProperties := map[string]schema.PropertySpec{}
requiredInputProperties := codegen.NewStringSet()
resourcePath := func(method *discovery.RestMethod) string {
if method == nil {
return ""
}
var pathURL string
if len(method.FlatPath) > 0 {
pathURL = resources.AssembleURL(g.rest.RootUrl, g.rest.BasePath, method.FlatPath)
} else {
pathURL = resources.AssembleURL(g.rest.RootUrl, g.rest.BasePath, method.Path)
}
return pathURL
}
methodPath := func(method *discovery.RestMethod) string {
if method == nil {
return ""
}
if len(method.FlatPath) > 0 {
return method.FlatPath
}
return method.Path
}
createPath := resourcePath(dd.createMethod)
resourceMeta := resources.CloudAPIResource{
RootURL: g.rest.BaseUrl,
Create: resources.CreateAPIOperation{
CloudAPIOperation: resources.CloudAPIOperation{
Endpoint: resources.CloudAPIEndpoint{
Template: g.fullPath(dd.createMethod, false),
},
Verb: dd.createMethod.HttpMethod,
},
},
Delete: resources.CloudAPIOperation{},
Read: resources.CloudAPIOperation{
Verb: dd.getMethod.HttpMethod,
},
Update: resources.UpdateAPIOperation{
CloudAPIOperation: resources.CloudAPIOperation{},
},
}
// Populate the resource name key for `getIamPolicy` and `setIamPolicy` methods.
if strings.HasSuffix(typeName, "IamPolicy") {
switch g.mod {
case "storage/v1":
resourceMeta.IamResourceName = "bucket"
default:
resourceMeta.IamResourceName = "resource"
}
}
patternParams := codegen.NewStringSet()
for _, name := range codegen.SortedKeys(dd.createMethod.Parameters) {
param := dd.createMethod.Parameters[name]
if isIgnoredQueryParam(name) {
continue
}
if param.Location != "query" {
continue
}
p := resources.CloudAPIResourceParam{
Name: name,
Kind: "query",
}
sdkName := ToLowerCamel(name)
if sdkName != name {
p.SdkName = sdkName
}
queryType := param.Type
if queryType == "" {
queryType = "string"
}
resourceMeta.Create.Endpoint.Values = append(resourceMeta.Create.Endpoint.Values, p)
patternParams.Add(sdkName)
inputProperties[sdkName] = schema.PropertySpec{
Description: param.Description,
TypeSpec: schema.TypeSpec{Type: queryType},
ReplaceOnChanges: isRequired(param),
}
if isRequired(param) {
requiredInputProperties.Add(sdkName)
requiredProperties.Add(sdkName)
}
properties[sdkName] = inputProperties[sdkName]
}
subMatches := pathRegex.FindAllStringSubmatch(createPath, -1)
for _, names := range subMatches {
if len(names) < 2 {
return errors.Errorf("failed to match create path %q", createPath)
}
name := names[1]
sdkName := apiParamNameToSdkName(name)
inputProperties[sdkName] = schema.PropertySpec{
TypeSpec: schema.TypeSpec{Type: "string"},
ReplaceOnChanges: true, // All path parameters should trigger replace-on-changes.
}
properties[sdkName] = inputProperties[sdkName]
p := resources.CloudAPIResourceParam{
Name: name,
Kind: "path",
}
if sdkName != name {
p.SdkName = sdkName
}
resourceMeta.Create.Endpoint.Values = append(resourceMeta.Create.Endpoint.Values, p)
patternParams.Add(sdkName)
requiredInputProperties.Add(sdkName)
requiredProperties.Add(sdkName)
}
if dd.createMethod.Request != nil {
// If the request type matches the pattern when it contains a property of the type equal to the response
// type of the GET endpoint, then we want to flatten that property, so that the resource inputs are a superset
// of the resource outputs. This also helps reconcile the shape of create and update operations.
var flatten string
createRequest := g.rest.Schemas[dd.createMethod.Request.Ref]
if dd.createMethod.Request.Ref != dd.getMethod.Response.Ref {
for _, name := range codegen.SortedKeys(createRequest.Properties) {
v := createRequest.Properties[name]
if v.Ref == dd.getMethod.Response.Ref {
flatten = name
}
}
}
bodyBag, err := g.genProperties(typeName, &createRequest, flatten, false, patternParams)
if err != nil {
return err
}
isOutput := func(desc string) bool {
lowerDesc := strings.ToLower(desc)
return isReadOnly(lowerDesc) ||
!(strings.Contains(lowerDesc, "values include") ||
strings.Contains(lowerDesc, "value must be specified"))
}
for name, prop := range bodyBag.specs {
// If the create request has a status field, lets skip it from being marked as a required input.
if dd.createMethod.Request.Ref == dd.getMethod.Response.Ref && name == "status" && isOutput(prop.
Description) {
continue
}
inputProperties[name] = prop
}
for name := range bodyBag.requiredSpecs {
requiredInputProperties.Add(name)
}
resourceMeta.Create.SDKProperties = bodyBag.properties
if op, ok := ops[dd.createMethod.Response.Ref]; ok {
g.setOperationsBaseURL(&resourceMeta.Create.CloudAPIOperation, "", op)
} else {
response := g.rest.Schemas[dd.createMethod.Response.Ref]
for propName, prop := range response.Properties {
if op, ok := ops[prop.Ref]; ok {
g.setOperationsBaseURL(&resourceMeta.Create.CloudAPIOperation, propName, op)
break
}
}
}
if dd.updateMethod != nil {
resourceMeta.Update.Verb = dd.updateMethod.HttpMethod
var updateFlatten string
updateRequest := g.rest.Schemas[dd.updateMethod.Request.Ref]
if dd.updateMethod.Request.Ref != dd.getMethod.Response.Ref {
for _, name := range codegen.SortedKeys(updateRequest.Properties) {
v := updateRequest.Properties[name]
if v.Ref == dd.getMethod.Response.Ref {
updateFlatten = name
}
}
}
resourceMeta.Update.SDKProperties = map[string]resources.CloudAPIProperty{}
updateBag, err := g.genProperties(typeName, &updateRequest, updateFlatten, false, nil)
if err != nil {
return err
}
for name, param := range dd.updateMethod.Parameters {
if param.Format == "google-fieldmask" && isRequired(param) {
contract.Assert(param.Location == "query")
resourceMeta.Update.UpdateMask.QueryParamName = name
}
}
for name, value := range updateBag.properties {
if _, has := bodyBag.properties[name]; has {
resourceMeta.Update.SDKProperties[name] = value
} else {
if value.Format == "google-fieldmask" && value.Required {
resourceMeta.Update.UpdateMask.BodyPropertyName = name
} else {
fmt.Printf("unknown update property %s: %s.%s\n", resourceTok, dd.updateMethod.Request.Ref, name)
}
}
}
}
}
if dd.getMethod.Response != nil {
response := g.rest.Schemas[dd.getMethod.Response.Ref]
responseBag, err := g.genProperties(typeName, &response, "", true, nil)
if err != nil {
return err
}
if err = mergo.Merge(&properties, responseBag.specs); err != nil {
return err
}
if err = mergo.Merge(&requiredProperties, responseBag.requiredSpecs); err != nil {
return err
}
g.escapeCSharpNames(typeName, properties)
// Decide how the provider will determine the ID of a created resource.
// Option 1: it's directly returned from the API in the "self" property.
for _, p := range []string{"selfLink", "self"} {
if _, has := response.Properties[p]; has {
resourceMeta.IDProperty = p
resourceMeta.Read.Endpoint.SelfLinkProperty = p
resourceMeta.Update.Endpoint.SelfLinkProperty = p
resourceMeta.Delete.Endpoint.SelfLinkProperty = p
break
}
}
// Option 2: the provider has to manually build it from the GET method path.
if resourceMeta.IDProperty == "" {
var idVals []resources.CloudAPIResourceParam
queryValNames := codegen.NewStringSet()
idPath := methodPath(dd.getMethod)
queryParams := url.Values{}
for param, details := range dd.getMethod.Parameters {
// TODO: this may need to be changed to isRequired(details)
if details.Location != "query" || !details.Required {
continue
}
queryValNames.Add(param)
queryParams.Add(param, "{"+param+"}")
}
if len(queryParams) > 0 {
idPath, err = url.QueryUnescape(idPath + "?" + queryParams.Encode())
if err != nil {
fmt.Printf("Failed to unescape ID params for resource: %s: %v\n", resourceTok, err)
return nil
}
}
vals, err := g.buildIdParams(typeName, idPath, inputProperties, &response)
if err != nil {
fmt.Printf("Failed to build ID params for resource %s: %v\n", resourceTok, err)
return nil
}
// TODO: This logic could be extracted into something more generic. Currently, the value computation
// is always based on the GET method, so this may not be universally correct.
for _, k := range codegen.SortedKeys(vals) {
v := resources.CloudAPIResourceParam{
Name: k,
SdkName: vals[k],
Kind: "path",
}
if queryValNames.Has(k) {
v.Kind = "query"
}
idVals = append(idVals, v)
}
if p := g.fullPath(dd.getMethod, false); len(p) > 0 {
resourceMeta.Read.Endpoint.Template = p
resourceMeta.Read.Endpoint.Values = idVals
}
if p := g.fullPath(dd.updateMethod, false); len(p) > 0 {
resourceMeta.Update.Endpoint.Template = p
resourceMeta.Update.Endpoint.Values = idVals
}
if p := g.fullPath(dd.deleteMethod, false); len(p) > 0 {
resourceMeta.Delete.Endpoint.Template = p
resourceMeta.Delete.Endpoint.Values = idVals
}
resourceMeta.IDPath = idPath
resourceMeta.IDParams = vals
}
}
if dd.updateMethod != nil {
for name, value := range dd.updateMethod.Parameters {
if value.Format == "google-fieldmask" && isRequired(value) {
resourceMeta.Update.Endpoint.Values = append(resourceMeta.Update.Endpoint.Values,
resources.CloudAPIResourceParam{
Name: name,
SdkName: name,
Kind: value.Location,
})
}
}
if dd.updateMethod.Response != nil && dd.updateMethod.Response.Ref != "" {
if op, ok := ops[dd.updateMethod.Response.Ref]; ok {
g.setOperationsBaseURL(&resourceMeta.Update.CloudAPIOperation, "", op)
}
}
}
if d := dd.deleteMethod; d != nil {
if v := d.HttpMethod; len(v) > 0 {
resourceMeta.Delete.Verb = v
} else {
resourceMeta.Delete.Verb = "DELETE"
}
if dd.deleteMethod.Response != nil && dd.deleteMethod.Response.Ref != "" {
if op, ok := ops[dd.deleteMethod.Response.Ref]; ok {
g.setOperationsBaseURL(&resourceMeta.Delete, "", op)
}
}
}
// Detect resources that support media upload and mark them as such.
if dd.createMethod.MediaUpload != nil && dd.createMethod.MediaUpload.Protocols != nil &&
dd.createMethod.MediaUpload.Protocols.Simple != nil {
resourceMeta.Create.Endpoint.Template = resources.AssembleURL(
g.rest.RootUrl, dd.createMethod.MediaUpload.Protocols.Simple.Path)
resourceMeta.AssetUpload = true
inputProperties["source"] = schema.PropertySpec{
TypeSpec: schema.TypeSpec{
Ref: "pulumi.json#/Asset",
},
}
}
if strings.Contains(dd.createMethod.Description, "multipart/form-data") && dd.createMethod.Request.Ref == "GoogleApiHttpBody" {
resourceMeta.FormDataUpload = resources.FormDataUpload{
FormFields: map[string]resources.CloudAPIProperty{
"data": {},
"file": {},
},
}
inputProperties["file"] = schema.PropertySpec{
Description: "File to upload.",
TypeSpec: schema.TypeSpec{
Ref: "pulumi.json#/Asset",
},
}
}
description := dd.createMethod.Description
// Apply auto-naming.
autoNameable := !strings.HasSuffix(typeName, "IamPolicy") && !autonameExcludes.Has(resourceTok)
if autoNameable {
namePattern, err := namePropertyPattern(inputProperties)
if err == nil {
requiredInputProperties.Delete("name")
resourceMeta.Create.Autoname.FieldName = namePattern
} else if name, ok := autonameOverrides[fmt.Sprintf("google-native:%s:%s", g.mod, typeName)]; ok {
requiredInputProperties.Delete(name)
resourceMeta.Create.Autoname.FieldName = name
} else {
description += "\nAuto-naming is currently not supported for this resource."
}
}
// Apply auto-project and auto-location population.
requiredInputProperties.Delete("project")
requiredInputProperties.Delete("location")
requiredInputProperties.Delete("zone")
resourceSpec := schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: description,
Type: "object",
Properties: properties,
Required: requiredProperties.SortedValues(),
},
Methods: map[string]string{},
InputProperties: inputProperties,
RequiredInputs: requiredInputProperties.SortedValues(),
}
if md, ok := metadataOverrides[resourceTok]; ok {
if err := mergo.Merge(&resourceMeta, md, mergo.WithOverride); err != nil {
return fmt.Errorf("failed to merge metadata for resource: %q", resourceTok)
}
}
switch resourceTok {
case "google-native:container/v1:Cluster":
resourceSpec.Methods["getKubeconfig"] = "google-native:container/v1:Cluster/getKubeconfig"
case "google-native:container/v1beta1:Cluster":
resourceSpec.Methods["getKubeconfig"] = "google-native:container/v1beta1:Cluster/getKubeconfig"
}
// For resources with a `setIamPolicy` method defined, also generate Binding and Member resources to provide
// more granular alternatives to overwriting the entire policy.
if dd.hasIAMOverlays {
resourceMeta := deepcopy.Copy(resourceMeta).(resources.CloudAPIResource)
// Delete for policy is the same operation as an update.
resourceMeta.Delete.Endpoint = resourceMeta.Update.Endpoint
resourceMeta.Delete.SDKProperties = resourceMeta.Update.SDKProperties
resourceMeta.Delete.Verb = resourceMeta.Update.Verb
// Override default descriptions for overlay properties if a corresponding description is present in the schema.
// Note: the layout of these properties is inconsistent across resources, so we check multiple alternatives.
// It doesn't look like these Policy/Binding types are currently populated in the pkg.Types, so we manually
// parse the schema maps to get this information for now.
binding := deepcopy.Copy(iamBindingSpec).(schema.ResourceSpec)
binding.Description = resourceSpec.Description
member := deepcopy.Copy(iamMemberSpec).(schema.ResourceSpec)
member.Description = resourceSpec.Description
bindingMembers := binding.Properties["members"]
bindingRole := binding.Properties["role"]
memberMember := member.Properties["member"]
memberRole := member.Properties["role"]
if policy, ok := g.rest.Schemas["Policy"]; ok {
if bindings, ok := policy.Properties["bindings"]; ok {
if bindings.Items != nil && bindings.Items.Ref == "Binding" {
if bindingSchema, ok := g.rest.Schemas["Binding"]; ok {
if members, ok := bindingSchema.Properties["members"]; ok {
bindingMembers.Description = members.Description
binding.Properties["members"] = bindingMembers
memberMember.Description = members.Description
member.Properties["member"] = memberMember
}
if role, ok := bindingSchema.Properties["role"]; ok {
bindingRole.Description = role.Description
binding.Properties["role"] = bindingRole
memberRole.Description = role.Description
member.Properties["role"] = memberRole
}
}
}
if bindings.Items != nil {
if members, ok := bindings.Items.Properties["members"]; ok {
bindingMembers.Description = members.Description
binding.Properties["members"] = bindingMembers
memberMember.Description = members.Description
member.Properties["member"] = memberMember
}
if role, ok := bindings.Items.Properties["role"]; ok {
bindingRole.Description = role.Description
binding.Properties["role"] = bindingRole
memberRole.Description = role.Description
member.Properties["role"] = memberRole
}
}
}
}
// Add the IamBinding resource overlay
iamBindingToken := strings.TrimSuffix(resourceTok, "Policy") + "Binding"
g.pkg.Resources[iamBindingToken] = binding
g.metadata.Resources[iamBindingToken] = resourceMeta
// Add the IamMember resource overlay
iamMemberToken := strings.TrimSuffix(resourceTok, "Policy") + "Member"
g.pkg.Resources[iamMemberToken] = member
g.metadata.Resources[iamMemberToken] = resourceMeta
}
if resourceMeta.Delete.Undefined() {
resourceSpec.ObjectTypeSpec.Description +=
"\nNote - this resource's API doesn't support deletion. When deleted, the resource will persist\n" +
"on Google Cloud even though it will be deleted from Pulumi state."
}
g.pkg.Resources[resourceTok] = resourceSpec
g.metadata.Resources[resourceTok] = resourceMeta
return nil
}
func (g *packageGenerator) setOperationsBaseURL(cloudOp *resources.CloudAPIOperation,
embeddedOperationFieldName string,
op *operation) {
if cloudOp.Operations == nil {
cloudOp.Operations = &resources.Operations{}
}
if _, has := op.schema.Properties["selfLink"]; has {
cloudOp.Operations.SelfLinkProperty = "selfLink"
} else {
operationParamToSdkName := func(name string, param discovery.JsonSchema) string {
switch name {
case "operation":
if strings.Contains(param.Description, "(ID of the operation)") {
return "id"
}
case "managedZone":
return "name"
default:
if strings.HasSuffix(name, "Id") {
name = name[:len(name)-2]
return inflector.Singularize(name)
}
}
return name