-
Notifications
You must be signed in to change notification settings - Fork 117
/
registry.go
333 lines (300 loc) · 12 KB
/
registry.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
// SPDX-FileCopyrightText: 2024 The Crossplane Authors <https://crossplane.io>
//
// SPDX-License-Identifier: CC0-1.0
package config
import (
"context"
_ "embed"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/crossplane/upjet/pkg/config"
"github.com/crossplane/upjet/pkg/config/conversion"
"github.com/crossplane/upjet/pkg/registry/reference"
"github.com/crossplane/upjet/pkg/schema/traverser"
conversiontfjson "github.com/crossplane/upjet/pkg/types/conversion/tfjson"
tfjson "github.com/hashicorp/terraform-json"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/xpprovider"
"github.com/pkg/errors"
"github.com/upbound/provider-aws/hack"
)
var (
//go:embed schema.json
providerSchema string
//go:embed provider-metadata.yaml
providerMetadata []byte
//go:embed field-rename.yaml
fieldRename []byte
// oldSingletonListAPIs is a newline-delimited list of Terraform resource
// names with converted singleton list APIs with at least CRD API version
// containing the old singleton list API. This is to prevent the API
// conversion for the newly added resources whose CRD APIs will already
// use embedded objects instead of the singleton lists and thus, will
// not possess a CRD API version with the singleton list. Thus, for
// the newly added resources (resources added after the singleton lists
// have been converted), we do not need the CRD API conversion
// functions that convert between singleton lists and embedded objects,
// but we need only the Terraform conversion functions.
// This list is immutable and represents the set of resources with the
// already generated CRD API versions with now converted singleton lists.
// Because new resources should never have singleton lists in their
// generated APIs, there should be no need to add them to this list.
// However, bugs might result in exceptions in the future.
// Please see:
// https://github.com/crossplane-contrib/provider-upjet-aws/pull/1332
// for more context on singleton list to embedded object conversions.
//go:embed old-singleton-list-apis.txt
oldSingletonListAPIs string
)
var skipList = []string{
"aws_waf_rule_group$", // Too big CRD schema
"aws_wafregional_rule_group$", // Too big CRD schema
"aws_mwaa_environment$", // See https://github.com/crossplane-contrib/terrajet/issues/100
"aws_ecs_tag$", // tags are already managed by ecs resources.
"aws_alb$", // identical with aws_lb
"aws_alb_target_group_attachment$", // identical with aws_lb_target_group_attachment
"aws_iam_policy_attachment$", // identical with aws_iam_*_policy_attachment resources.
"aws_iam_group_policy$", // identical with aws_iam_*_policy_attachment resources.
"aws_iam_user_policy$", // identical with aws_iam_*_policy_attachment resources.
"aws_alb$", // identical with aws_lb.
"aws_alb_listener$", // identical with aws_lb_listener.
"aws_alb_target_group$", // identical with aws_lb_target_group.
"aws_alb_target_group_attachment$", // identical with aws_lb_target_group_attachment.
"aws_iot_authorizer$", // failure with unknown reason.
"aws_location_map$", // failure with unknown reason.
"aws_appflow_connector_profile$", // failure with unknown reason.
"aws_rds_reserved_instance", // Expense of testing
}
var (
reAPIVersion = regexp.MustCompile(`^v(\d+)((alpha|beta)(\d+))?$`)
)
const (
errFmtCannotBumpSingletonList = "cannot bump the API version for the resource %q containing a singleton list in its API"
errFmtCannotFindPrev = "cannot compute the previous API versions for the resource %q containing a singleton list in its API"
errFmtInvalidAPIVersion = "cannot parse %q as a Kubernetes API version string"
)
// workaround for the TF AWS v4.67.0-based no-fork release: We would like to
// keep the types in the generated CRDs intact
// (prevent number->int type replacements).
func getProviderSchema(s string) (*schema.Provider, error) {
ps := tfjson.ProviderSchemas{}
if err := ps.UnmarshalJSON([]byte(s)); err != nil {
panic(err)
}
if len(ps.Schemas) != 1 {
return nil, errors.Errorf("there should exactly be 1 provider schema but there are %d", len(ps.Schemas))
}
var rs map[string]*tfjson.Schema
for _, v := range ps.Schemas {
rs = v.ResourceSchemas
break
}
return &schema.Provider{
ResourcesMap: conversiontfjson.GetV2ResourceMap(rs),
}, nil
}
// GetProvider returns the provider configuration.
// The `generationProvider` argument specifies whether the provider
// configuration is being read for the code generation pipelines.
// In that case, we will only use the JSON schema for generating
// the CRDs.
func GetProvider(ctx context.Context, generationProvider bool) (*config.Provider, error) {
fwProvider, sdkProvider, err := xpprovider.GetProvider(ctx)
if err != nil {
return nil, errors.Wrap(err, "cannot get the Terraform framework and SDK providers")
}
if generationProvider {
p, err := getProviderSchema(providerSchema)
if err != nil {
return nil, errors.Wrap(err, "cannot read the Terraform SDK provider from the JSON schema for code generation")
}
if err := traverser.TFResourceSchema(sdkProvider.ResourcesMap).Traverse(traverser.NewMaxItemsSync(p.ResourcesMap)); err != nil {
return nil, errors.Wrap(err, "cannot sync the MaxItems constraints between the Go schema and the JSON schema")
}
// use the JSON schema to temporarily prevent float64->int64
// conversions in the CRD APIs.
// We would like to convert to int64s with the next major release of
// the provider.
sdkProvider = p
}
modulePath := "github.com/upbound/provider-aws"
pc := config.NewProvider([]byte(providerSchema), "aws",
modulePath, providerMetadata,
config.WithShortName("aws"),
config.WithRootGroup("aws.upbound.io"),
config.WithIncludeList(CLIReconciledResourceList()),
config.WithTerraformPluginSDKIncludeList(TerraformPluginSDKResourceList()),
config.WithTerraformPluginFrameworkIncludeList(TerraformPluginFrameworkResourceList()),
config.WithReferenceInjectors([]config.ReferenceInjector{reference.NewInjector(modulePath)}),
config.WithSkipList(skipList),
config.WithFeaturesPackage("internal/features"),
config.WithMainTemplate(hack.MainTemplate),
config.WithTerraformProvider(sdkProvider),
config.WithTerraformPluginFrameworkProvider(fwProvider),
config.WithSchemaTraversers(&config.SingletonListEmbedder{}),
config.WithDefaultResourceOptions(
GroupKindOverrides(),
KindOverrides(),
RegionAddition(),
TagsAllRemoval(),
IdentifierAssignedByAWS(),
KnownReferencers(),
AddExternalTagsField(),
ResourceConfigurator(),
NamePrefixRemoval(),
DocumentationForTags(),
injectFieldRenamingConversionFunctions(),
),
)
pc.BasePackages.ControllerMap["internal/controller/eks/clusterauth"] = "eks"
for _, configure := range ProviderConfiguration {
configure(pc)
}
pc.ConfigureResources()
return pc, bumpVersionsWithEmbeddedLists(pc)
}
func bumpVersionsWithEmbeddedLists(pc *config.Provider) error {
l := strings.Split(strings.TrimSpace(oldSingletonListAPIs), "\n")
oldSLAPIs := make(map[string]struct{}, len(l))
for _, n := range l {
oldSLAPIs[n] = struct{}{}
}
for name, r := range pc.Resources {
r := r
// nothing to do if no singleton list has been converted to
// an embedded object
if len(r.CRDListConversionPaths()) == 0 {
continue
}
if _, ok := oldSLAPIs[name]; ok {
if err := configureSingletonListAPIConverters(r); err != nil {
return errors.Wrap(err, "failed to configure singleton list API converters")
}
} else {
// the controller will be reconciling on the CRD API version
// with the converted API (with embedded objects in place of
// singleton lists), so we need the appropriate Terraform
// converter in this case.
r.TerraformConversions = []config.TerraformConversion{
config.NewTFSingletonConversion(),
}
}
pc.Resources[name] = r
}
return nil
}
func configureSingletonListAPIConverters(r *config.Resource) error {
bumped, err := bumpAPIVersion(r.Version)
if err != nil {
return errors.Wrapf(err, errFmtCannotBumpSingletonList, r.Name)
}
if r.PreviousVersions == nil {
prev, err := getPreviousVersions(bumped)
if err != nil {
return errors.Wrapf(err, errFmtCannotFindPrev, r.Name)
}
r.PreviousVersions = prev
}
currentVer := r.Version
r.Version = bumped
// we would like to set the storage version to v1beta1 to facilitate
// downgrades.
r.SetCRDStorageVersion(currentVer)
// because the controller reconciles on the API version with the singleton list API,
// no need for a Terraform conversion.
r.ControllerReconcileVersion = currentVer
r.Conversions = []conversion.Conversion{
conversion.NewIdentityConversionExpandPaths(conversion.AllVersions, conversion.AllVersions, conversion.DefaultPathPrefixes(), r.CRDListConversionPaths()...),
conversion.NewSingletonListConversion(conversion.AllVersions, bumped, conversion.DefaultPathPrefixes(), r.CRDListConversionPaths(), conversion.ToEmbeddedObject),
conversion.NewSingletonListConversion(bumped, conversion.AllVersions, conversion.DefaultPathPrefixes(), r.CRDListConversionPaths(), conversion.ToSingletonList)}
return nil
}
// returns a new API version by bumping the last number if the
// API version string is a Kubernetes API version string such
// as v1alpha1, v1beta1 or v1. Otherwise, returns an error.
// If the specified version is v1beta1, then the bumped version is v1beta2.
// If the specified version is v1, then the bumped version is v2.
func bumpAPIVersion(v string) (string, error) {
m := reAPIVersion.FindStringSubmatch(v)
switch {
// e.g., v1
case len(m) == 2:
n, err := strconv.ParseUint(m[1], 10, 0)
if err != nil {
return "", errors.Wrapf(err, errFmtInvalidAPIVersion, v)
}
return fmt.Sprintf("v%d", n+1), nil
// e.g., v1beta1
case len(m) == 5:
n, err := strconv.ParseUint(m[4], 10, 0)
if err != nil {
return "", errors.Wrapf(err, errFmtInvalidAPIVersion, v)
}
return fmt.Sprintf("v%s%s%d", m[1], m[3], n+1), nil
default:
// then cannot bump this version string
return "", errors.Errorf(errFmtInvalidAPIVersion, v)
}
}
func getPreviousVersions(v string) ([]string, error) {
p := "v1beta1"
var result []string
var err error
for p != v {
result = append(result, p)
p, err = bumpAPIVersion(p)
if err != nil {
return nil, err
}
}
return result, nil
}
// CLIReconciledResourceList returns the list of resources that have external
// name configured in ExternalNameConfigs table and to be reconciled under
// the TF CLI based architecture.
func CLIReconciledResourceList() []string {
l := make([]string, len(CLIReconciledExternalNameConfigs))
i := 0
for name := range CLIReconciledExternalNameConfigs {
// Expected format is regex, and we'd like to have exact matches.
l[i] = name + "$"
i++
}
return l
}
// TerraformPluginSDKResourceList returns the list of resources that have external
// name configured in ExternalNameConfigs table and to be reconciled under
// the no-fork architecture.
func TerraformPluginSDKResourceList() []string {
l := make([]string, len(TerraformPluginSDKExternalNameConfigs))
i := 0
for name := range TerraformPluginSDKExternalNameConfigs {
// Expected format is regex, and we'd like to have exact matches.
l[i] = name + "$"
i++
}
return l
}
func TerraformPluginFrameworkResourceList() []string {
l := make([]string, len(TerraformPluginFrameworkExternalNameConfigs))
i := 0
for name := range TerraformPluginFrameworkExternalNameConfigs {
// Expected format is regex, and we'd like to have exact matches.
l[i] = name + "$"
i++
}
return l
}
// Configure configures the specified Provider.
type Configure func(provider *config.Provider)
// Configurator is a registry for provider Configs.
type Configurator []Configure
// AddConfig adds a Config to the Configurator registry.
func (c *Configurator) AddConfig(conf Configure) {
*c = append(*c, conf)
}
// ProviderConfiguration is a global registry to be used by
// the resource providers to register their Config functions.
var ProviderConfiguration = Configurator{}