-
Notifications
You must be signed in to change notification settings - Fork 115
/
main.go
523 lines (458 loc) · 17.8 KB
/
main.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
// 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.
// nolint:gosec
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-kubernetes/provider/v3/pkg/gen"
providerVersion "github.com/pulumi/pulumi-kubernetes/provider/v3/pkg/version"
"github.com/pulumi/pulumi/pkg/v3/codegen"
dotnetgen "github.com/pulumi/pulumi/pkg/v3/codegen/dotnet"
gogen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
nodejsgen "github.com/pulumi/pulumi/pkg/v3/codegen/nodejs"
pythongen "github.com/pulumi/pulumi/pkg/v3/codegen/python"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// TemplateDir is the path to the base directory for code generator templates.
var TemplateDir string
// BaseDir is the path to the base pulumi-kubernetes directory.
var BaseDir string
// Language is the SDK language.
type Language string
const (
DotNet Language = "dotnet"
Go Language = "go"
NodeJS Language = "nodejs"
Kinds Language = "kinds"
Python Language = "python"
Schema Language = "schema"
)
func main() {
flag.Usage = func() {
const usageFormat = "Usage: %s <language> <swagger-or-schema-file> <root-pulumi-kubernetes-dir>"
_, err := fmt.Fprintf(flag.CommandLine.Output(), usageFormat, os.Args[0])
contract.IgnoreError(err)
flag.PrintDefaults()
}
var version string
flag.StringVar(&version, "version", providerVersion.Version, "the provider version to record in the generated code")
flag.Parse()
args := flag.Args()
if len(args) < 3 {
flag.Usage()
return
}
language, inputFile := Language(args[0]), args[1]
BaseDir = args[2]
TemplateDir = filepath.Join(BaseDir, "provider", "pkg", "gen")
outdir := filepath.Join(BaseDir, "sdk", string(language))
switch language {
case NodeJS:
templateDir := filepath.Join(TemplateDir, "nodejs-templates")
writeNodeJSClient(readSchema(inputFile, version), outdir, templateDir)
case Python:
templateDir := filepath.Join(TemplateDir, "python-templates")
writePythonClient(readSchema(inputFile, version), outdir, templateDir)
case DotNet:
templateDir := filepath.Join(TemplateDir, "dotnet-templates")
writeDotnetClient(readSchema(inputFile, version), outdir, templateDir)
case Go:
templateDir := filepath.Join(TemplateDir, "_go-templates")
writeGoClient(readSchema(inputFile, version), outdir, templateDir)
case Kinds:
pkg := readSchema(inputFile, version)
genK8sResourceTypes(pkg)
case Schema:
pkgSpec := generateSchema(inputFile)
mustWritePulumiSchema(pkgSpec, version)
default:
panic(fmt.Sprintf("Unrecognized language '%s'", language))
}
}
func readSchema(schemaPath string, version string) *schema.Package {
// Read in, decode, and import the schema.
schemaBytes, err := ioutil.ReadFile(schemaPath)
if err != nil {
panic(err)
}
var pkgSpec schema.PackageSpec
if err = json.Unmarshal(schemaBytes, &pkgSpec); err != nil {
panic(err)
}
pkgSpec.Version = version
pkg, err := schema.ImportSpec(pkgSpec, nil)
if err != nil {
panic(err)
}
return pkg
}
func generateSchema(swaggerPath string) schema.PackageSpec {
swagger, err := ioutil.ReadFile(swaggerPath)
if err != nil {
panic(err)
}
swaggerDir := filepath.Dir(swaggerPath)
// The following APIs have been deprecated and removed in the more recent versions of k8s:
// - extensions/v1beta1/*
// - apps/v1beta1/*
// - apps/v1beta2/*
// - networking/v1beta1/IngressClass
// Since these resources will continue to be important to users for the foreseeable future, we will merge in
// newer specs on top of this spec so that these resources continue to be available in our SDKs.
urlFmt := "https://raw.githubusercontent.com/kubernetes/kubernetes/v1.%s.0/api/openapi-spec/swagger.json"
filenameFmt := "swagger-v1.%s.0.json"
for _, v := range []string{"17", "18", "19", "20"} {
legacySwaggerPath := filepath.Join(swaggerDir, fmt.Sprintf(filenameFmt, v))
err = DownloadFile(legacySwaggerPath, fmt.Sprintf(urlFmt, v))
if err != nil {
panic(err)
}
legacySwagger, err := ioutil.ReadFile(legacySwaggerPath)
if err != nil {
panic(err)
}
swagger = mergeSwaggerSpecs(legacySwagger, swagger)
}
var schemaMap map[string]interface{}
err = json.Unmarshal(swagger, &schemaMap)
if err != nil {
panic(err)
}
// Generate schema
return gen.PulumiSchema(schemaMap)
}
// This is to mostly filter resources from the spec.
var resourcesToFilterFromTemplate = codegen.NewStringSet("kubernetes:helm.sh/v3:Release")
func writeNodeJSClient(pkg *schema.Package, outdir, templateDir string) {
resources, err := nodejsgen.LanguageResources(pkg)
if err != nil {
panic(err)
}
templateResources := gen.TemplateResources{}
packages := codegen.StringSet{}
for tok, resource := range resources {
if resourcesToFilterFromTemplate.Has(tok) {
continue
}
if resource.Package == "" {
continue
}
if strings.HasSuffix(resource.Name, "Patch") {
continue
}
tr := gen.TemplateResource{
Name: resource.Name,
Package: resource.Package,
Token: resource.Token,
}
for _, property := range resource.Properties {
// hack(levi): manually remove `| undefined` from the ConstValue and Package until https://github.com/pulumi/pulumi-kubernetes/issues/1650 is resolved.
cv := strings.TrimSuffix(property.ConstValue, " | undefined")
pkg := strings.TrimSuffix(property.Package, " | undefined")
tp := gen.TemplateProperty{
ConstValue: cv,
Name: property.Name,
Package: pkg,
}
tr.Properties = append(tr.Properties, tp)
}
templateResources.Resources = append(templateResources.Resources, tr)
groupPackage := strings.Split(resource.Package, ".")[0]
packages.Add(groupPackage)
}
sort.Slice(templateResources.Resources, func(i, j int) bool {
return templateResources.Resources[i].Token < templateResources.Resources[j].Token
})
templateResources.Packages = packages.SortedValues()
overlays := map[string][]byte{
"apiextensions/customResource.ts": mustLoadFile(filepath.Join(templateDir, "apiextensions", "customResource.ts")),
"apiextensions/customResourcePatch.ts": mustLoadFile(filepath.Join(templateDir, "apiextensions", "customResourcePatch.ts")),
"helm/v2/helm.ts": mustLoadFile(filepath.Join(templateDir, "helm", "v2", "helm.ts")),
"helm/v3/helm.ts": mustLoadFile(filepath.Join(templateDir, "helm", "v3", "helm.ts")),
"kustomize/kustomize.ts": mustLoadFile(filepath.Join(templateDir, "kustomize", "kustomize.ts")),
"yaml/yaml.ts": mustRenderTemplate(filepath.Join(templateDir, "yaml", "yaml.tmpl"), templateResources),
}
files, err := nodejsgen.GeneratePackage("pulumigen", pkg, overlays)
if err != nil {
panic(err)
}
// Internal files that don't need to be exported
files["path.ts"] = mustLoadFile(filepath.Join(templateDir, "path.ts"))
files["tests/path.ts"] = mustLoadFile(filepath.Join(templateDir, "tests", "path.ts"))
mustWriteFiles(outdir, files)
}
func writePythonClient(pkg *schema.Package, outdir string, templateDir string) {
resources, err := pythongen.LanguageResources("pulumigen", pkg)
if err != nil {
panic(err)
}
templateResources := gen.TemplateResources{}
for tok, resource := range resources {
if resourcesToFilterFromTemplate.Has(tok) {
continue
}
if strings.HasSuffix(resource.Name, "Patch") {
continue
}
r := gen.TemplateResource{
Name: resource.Name,
Package: resource.Package,
Token: resource.Token,
}
templateResources.Resources = append(templateResources.Resources, r)
}
sort.Slice(templateResources.Resources, func(i, j int) bool {
return templateResources.Resources[i].Token < templateResources.Resources[j].Token
})
overlays := map[string][]byte{
"apiextensions/CustomResource.py": mustLoadFile(filepath.Join(templateDir, "apiextensions", "CustomResource.py")),
"apiextensions/CustomResourcePatch.py": mustLoadFile(filepath.Join(templateDir, "apiextensions", "CustomResourcePatch.py")),
"helm/v2/helm.py": mustLoadFile(filepath.Join(templateDir, "helm", "v2", "helm.py")),
"helm/v3/helm.py": mustLoadFile(filepath.Join(templateDir, "helm", "v3", "helm.py")),
"kustomize/kustomize.py": mustLoadFile(filepath.Join(templateDir, "kustomize", "kustomize.py")),
"yaml/yaml.py": mustRenderTemplate(filepath.Join(templateDir, "yaml", "yaml.tmpl"), templateResources),
}
files, err := pythongen.GeneratePackage("pulumigen", pkg, overlays)
if err != nil {
panic(err)
}
mustWriteFiles(outdir, files)
}
func writeDotnetClient(pkg *schema.Package, outdir, templateDir string) {
resources, err := dotnetgen.LanguageResources("pulumigen", pkg)
if err != nil {
panic(err)
}
templateResources := gen.TemplateResources{}
for tok, resource := range resources {
if resourcesToFilterFromTemplate.Has(tok) {
continue
}
if strings.HasSuffix(resource.Name, "Patch") {
continue
}
r := gen.TemplateResource{
Name: resource.Name,
Package: resource.Package,
Token: resource.Token,
}
templateResources.Resources = append(templateResources.Resources, r)
}
sort.Slice(templateResources.Resources, func(i, j int) bool {
return templateResources.Resources[i].Token < templateResources.Resources[j].Token
})
overlays := map[string][]byte{
"ApiExtensions/CustomResource.cs": mustLoadFile(filepath.Join(templateDir, "apiextensions", "CustomResource.cs")),
"ApiExtensions/CustomResourcePatch.cs": mustLoadFile(filepath.Join(templateDir, "apiextensions", "CustomResourcePatch.cs")),
"Helm/ChartBase.cs": mustLoadFile(filepath.Join(templateDir, "helm", "ChartBase.cs")),
"Helm/Unwraps.cs": mustLoadFile(filepath.Join(templateDir, "helm", "Unwraps.cs")),
"Helm/V2/Chart.cs": mustLoadFile(filepath.Join(templateDir, "helm", "v2", "Chart.cs")),
"Helm/V3/Chart.cs": mustLoadFile(filepath.Join(templateDir, "helm", "v3", "Chart.cs")),
"Helm/V3/Invokes.cs": mustLoadFile(filepath.Join(templateDir, "helm", "v3", "Invokes.cs")),
"Kustomize/Directory.cs": mustLoadFile(filepath.Join(templateDir, "kustomize", "Directory.cs")),
"Kustomize/Invokes.cs": mustLoadFile(filepath.Join(templateDir, "kustomize", "Invokes.cs")),
"Yaml/ConfigFile.cs": mustLoadFile(filepath.Join(templateDir, "yaml", "ConfigFile.cs")),
"Yaml/ConfigGroup.cs": mustLoadFile(filepath.Join(templateDir, "yaml", "ConfigGroup.cs")),
"Yaml/Invokes.cs": mustLoadFile(filepath.Join(templateDir, "yaml", "Invokes.cs")),
"Yaml/TransformationAction.cs": mustLoadFile(filepath.Join(templateDir, "yaml", "TransformationAction.cs")),
"Yaml/Yaml.cs": mustRenderTemplate(filepath.Join(templateDir, "yaml", "yaml.tmpl"), templateResources),
}
files, err := dotnetgen.GeneratePackage("pulumigen", pkg, overlays)
if err != nil {
panic(err)
}
for filename, contents := range files {
path := filepath.Join(outdir, filename)
if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {
panic(err)
}
err := ioutil.WriteFile(path, contents, 0644)
if err != nil {
panic(err)
}
}
}
func writeGoClient(pkg *schema.Package, outdir string, templateDir string) {
files, err := gogen.GeneratePackage("pulumigen", pkg)
if err != nil {
panic(err)
}
renamePackage := func(fileNames []string, sourcePackage, renameTo string) {
re := regexp.MustCompile(fmt.Sprintf(`(%s)`, sourcePackage))
for _, f := range fileNames {
content, ok := files[f]
if !ok {
contract.Failf("Expected file: %q but not found.", f)
}
files[f] = re.ReplaceAll(content, []byte(renameTo))
}
}
// Go codegen maps package to "v3" for Helm Release. Manually rename to
// helm to avoid conflict with existing templates.
renamePackage([]string{
"kubernetes/helm/v3/pulumiTypes.go",
"kubernetes/helm/v3/init.go",
"kubernetes/helm/v3/release.go",
},
"package v3",
"package helm")
resources, err := gogen.LanguageResources("pulumigen", pkg)
if err != nil {
panic(err)
}
templateResources := gen.GoTemplateResources{}
for tok, resource := range resources {
if resourcesToFilterFromTemplate.Has(tok) {
continue
}
if strings.HasSuffix(resource.Name, "Patch") {
continue
}
r := gen.TemplateResource{
Alias: resource.Alias,
Name: resource.Name,
Package: resource.Package,
Token: resource.Token,
}
templateResources.Resources = append(templateResources.Resources, r)
}
sort.Slice(templateResources.Resources, func(i, j int) bool {
return templateResources.Resources[i].Token < templateResources.Resources[j].Token
})
files["kubernetes/customPulumiTypes.go"] = mustLoadGoFile(filepath.Join(templateDir, "customPulumiTypes.go"))
files["kubernetes/apiextensions/customResource.go"] = mustLoadGoFile(filepath.Join(templateDir, "apiextensions", "customResource.go"))
files["kubernetes/apiextensions/customResourcePatch.go"] = mustLoadGoFile(filepath.Join(templateDir, "apiextensions", "customResourcePatch.go"))
files["kubernetes/helm/v2/chart.go"] = mustLoadGoFile(filepath.Join(templateDir, "helm", "v2", "chart.go"))
files["kubernetes/helm/v2/pulumiTypes.go"] = mustLoadGoFile(filepath.Join(templateDir, "helm", "v2", "pulumiTypes.go"))
files["kubernetes/helm/v3/chart.go"] = mustLoadGoFile(filepath.Join(templateDir, "helm", "v3", "chart.go"))
// Rename pulumiTypes.go to avoid conflict with schema generated Helm Release types.
files["kubernetes/helm/v3/chartPulumiTypes.go"] = mustLoadGoFile(filepath.Join(templateDir, "helm", "v3", "pulumiTypes.go"))
files["kubernetes/kustomize/directory.go"] = mustLoadGoFile(filepath.Join(templateDir, "kustomize", "directory.go"))
files["kubernetes/kustomize/pulumiTypes.go"] = mustLoadGoFile(filepath.Join(templateDir, "kustomize", "pulumiTypes.go"))
files["kubernetes/yaml/configFile.go"] = mustLoadGoFile(filepath.Join(templateDir, "yaml", "configFile.go"))
files["kubernetes/yaml/configGroup.go"] = mustLoadGoFile(filepath.Join(templateDir, "yaml", "configGroup.go"))
files["kubernetes/yaml/transformation.go"] = mustLoadGoFile(filepath.Join(templateDir, "yaml", "transformation.go"))
files["kubernetes/yaml/yaml.go"] = mustRenderGoTemplate(filepath.Join(templateDir, "yaml", "yaml.tmpl"), templateResources)
mustWriteFiles(outdir, files)
}
func mustLoadFile(path string) []byte {
b, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
return b
}
func mustLoadGoFile(path string) []byte {
b := mustLoadFile(path)
formattedSource, err := format.Source(b)
if err != nil {
panic(err)
}
return formattedSource
}
func mustRenderTemplate(path string, resources interface{}) []byte {
b := mustLoadFile(path)
t := template.Must(template.New("resources").Parse(string(b)))
var buf bytes.Buffer
err := t.Execute(&buf, resources)
if err != nil {
panic(err)
}
return buf.Bytes()
}
func mustRenderGoTemplate(path string, resources interface{}) []byte {
bytes := mustRenderTemplate(path, resources)
formattedSource, err := format.Source(bytes)
contract.AssertNoErrorf(err, "err: %+v path: %q source:\n%s", err, path, string(bytes))
return formattedSource
}
func genK8sResourceTypes(pkg *schema.Package) {
groupVersions, kinds := codegen.NewStringSet(), codegen.NewStringSet()
for _, resource := range pkg.Resources {
if resourcesToFilterFromTemplate.Has(resource.Token) {
continue
}
parts := strings.Split(resource.Token, ":")
contract.Assert(len(parts) == 3)
groupVersion, kind := parts[1], parts[2]
if resource.IsOverlay {
continue
}
if strings.HasSuffix(kind, "Patch") {
continue
}
groupVersions.Add(groupVersion)
kinds.Add(kind)
}
gvk := gen.GVK{Kinds: kinds.SortedValues()}
gvStrings := groupVersions.SortedValues()
for _, gvString := range gvStrings {
gvk.GroupVersions = append(gvk.GroupVersions, gen.GroupVersion(gvString))
}
files := map[string][]byte{}
files["provider/pkg/kinds/kinds.go"] = mustRenderGoTemplate(filepath.Join(TemplateDir, "kinds", "kinds.tmpl"), gvk)
mustWriteFiles(BaseDir, files)
}
func mustWriteFiles(rootDir string, files map[string][]byte) {
for filename, contents := range files {
mustWriteFile(rootDir, filename, contents)
}
}
func mustWriteFile(rootDir, filename string, contents []byte) {
outPath := filepath.Join(rootDir, filename)
if err := os.MkdirAll(filepath.Dir(outPath), 0755); err != nil {
panic(err)
}
err := ioutil.WriteFile(outPath, contents, 0644)
if err != nil {
panic(err)
}
}
func makeJSONString(v interface{}) ([]byte, error) {
var out bytes.Buffer
encoder := json.NewEncoder(&out)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(v); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func mustWritePulumiSchema(pkgSpec schema.PackageSpec, version string) {
schemaJSON, err := makeJSONString(pkgSpec)
if err != nil {
panic(errors.Wrap(err, "marshaling Pulumi schema"))
}
mustWriteFile(BaseDir, filepath.Join("provider", "cmd", "pulumi-resource-kubernetes", "schema.json"), schemaJSON)
versionedPkgSpec := pkgSpec
versionedPkgSpec.Version = version
versionedSchemaJSON, err := makeJSONString(versionedPkgSpec)
if err != nil {
panic(errors.Wrap(err, "marshaling Pulumi schema"))
}
mustWriteFile(BaseDir, filepath.Join("sdk", "schema", "schema.json"), versionedSchemaJSON)
}