diff --git a/pkg/config/common_test.go b/pkg/config/common_test.go index 19578e13..a8cec8d9 100644 --- a/pkg/config/common_test.go +++ b/pkg/config/common_test.go @@ -126,7 +126,7 @@ func TestDefaultResource(t *testing.T) { cmpopts.IgnoreFields(Sensitive{}, "fieldPaths", "AdditionalConnectionDetailsFn"), cmpopts.IgnoreFields(LateInitializer{}, "ignoredCanonicalFieldPaths"), cmpopts.IgnoreFields(ExternalName{}, "SetIdentifierArgumentFn", "GetExternalNameFn", "GetIDFn"), - cmpopts.IgnoreFields(Resource{}, "useNoForkClient"), + cmpopts.IgnoreFields(Resource{}, "useTerraformPluginSDKClient"), cmpopts.IgnoreFields(Resource{}, "useTerraformPluginFrameworkClient"), } diff --git a/pkg/config/provider.go b/pkg/config/provider.go index 6d0b71fc..cc2af625 100644 --- a/pkg/config/provider.go +++ b/pkg/config/provider.go @@ -118,14 +118,14 @@ type Provider struct { // Defaults to []string{".+"} which would include all resources. IncludeList []string - // NoForkIncludeList is a list of regex for the Terraform resources + // TerraformPluginSDKIncludeList is a list of regex for the Terraform resources // implemented with Terraform Plugin SDKv2 to be included and reconciled // in the no-fork architecture (without the Terraform CLI). // For example, to include "aws_shield_protection_group" into // the generated resources, one can add "aws_shield_protection_group$". // To include whole aws waf group, one can add "aws_waf.*" to the list. // Defaults to []string{".+"} which would include all resources. - NoForkIncludeList []string + TerraformPluginSDKIncludeList []string // TerraformPluginFrameworkIncludeList is a list of regex for the Terraform // resources implemented with Terraform Plugin Framework to be included and @@ -187,11 +187,11 @@ func WithIncludeList(l []string) ProviderOption { } } -// WithNoForkIncludeList configures the NoForkIncludeList for this Provider, +// WithTerraformPluginSDKIncludeList configures the TerraformPluginSDKIncludeList for this Provider, // with the given Terraform Plugin SDKv2-based resource name list -func WithNoForkIncludeList(l []string) ProviderOption { +func WithTerraformPluginSDKIncludeList(l []string) ProviderOption { return func(p *Provider) { - p.NoForkIncludeList = l + p.TerraformPluginSDKIncludeList = l } } @@ -311,13 +311,13 @@ func NewProvider(schema []byte, prefix string, modulePath string, metadata []byt fmt.Printf("Skipping resource %s because it has no schema\n", name) } // if in both of the include lists, the new behavior prevails - isNoFork := matches(name, p.NoForkIncludeList) + isTerraformPluginSDK := matches(name, p.TerraformPluginSDKIncludeList) isPluginFrameworkResource := matches(name, p.TerraformPluginFrameworkIncludeList) - if len(terraformResource.Schema) == 0 || matches(name, p.SkipList) || (!matches(name, p.IncludeList) && !isNoFork && !isPluginFrameworkResource) { + if len(terraformResource.Schema) == 0 || matches(name, p.SkipList) || (!matches(name, p.IncludeList) && !isTerraformPluginSDK && !isPluginFrameworkResource) { p.skippedResourceNames = append(p.skippedResourceNames, name) continue } - if isNoFork { + if isTerraformPluginSDK { if p.TerraformProvider == nil || p.TerraformProvider.ResourcesMap[name] == nil { panic(errors.Errorf("resource %q is configured to be reconciled without the Terraform CLI"+ "but either config.Provider.TerraformProvider is not configured or the Go schema does not exist for the resource", name)) @@ -345,7 +345,7 @@ func NewProvider(schema []byte, prefix string, modulePath string, metadata []byt } p.Resources[name] = DefaultResource(name, terraformResource, terraformPluginFrameworkResource, providerMetadata.Resources[name], p.DefaultResourceOptions...) - p.Resources[name].useNoForkClient = isNoFork + p.Resources[name].useTerraformPluginSDKClient = isTerraformPluginSDK p.Resources[name].useTerraformPluginFrameworkClient = isPluginFrameworkResource } for i, refInjector := range p.refInjectors { diff --git a/pkg/config/resource.go b/pkg/config/resource.go index 155210ca..ead767cc 100644 --- a/pkg/config/resource.go +++ b/pkg/config/resource.go @@ -455,9 +455,9 @@ type Resource struct { Conversions []conversion.Conversion - // useNoForkClient indicates that a no-fork external client should + // useTerraformPluginSDKClient indicates that a no-fork external client should // be generated instead of the Terraform CLI-forking client. - useNoForkClient bool + useTerraformPluginSDKClient bool // useTerraformPluginFrameworkClient indicates that a Terraform // Plugin Framework external client should be generated instead of @@ -491,11 +491,11 @@ type Resource struct { OverrideFieldNames map[string]string } -// ShouldUseNoForkClient returns whether to generate a SDKv2-based no-fork +// ShouldUseTerraformPluginSDKClient returns whether to generate a SDKv2-based no-fork // external client for this Resource, instead of the Terraform CLI-forking // external client -func (r *Resource) ShouldUseNoForkClient() bool { - return r.useNoForkClient +func (r *Resource) ShouldUseTerraformPluginSDKClient() bool { + return r.useTerraformPluginSDKClient } // ShouldUseTerraformPluginFrameworkClient returns whether to generate a diff --git a/pkg/controller/external_async_tfpluginfw.go b/pkg/controller/external_async_tfpluginfw.go index bd3fb9de..221749f8 100644 --- a/pkg/controller/external_async_tfpluginfw.go +++ b/pkg/controller/external_async_tfpluginfw.go @@ -22,12 +22,17 @@ import ( tferrors "github.com/crossplane/upjet/pkg/terraform/errors" ) +// TerraformPluginFrameworkAsyncConnector is a managed reconciler Connecter +// implementation for reconciling Terraform plugin framework based +// resources. type TerraformPluginFrameworkAsyncConnector struct { *TerraformPluginFrameworkConnector callback CallbackProvider eventHandler *handler.EventHandler } +// TerraformPluginFrameworkAsyncOption represents a configuration option for +// a TerraformPluginFrameworkAsyncConnector object. type TerraformPluginFrameworkAsyncOption func(connector *TerraformPluginFrameworkAsyncConnector) func NewTerraformPluginFrameworkAsyncConnector(kube client.Client, diff --git a/pkg/controller/external_async_tfpluginsdk.go b/pkg/controller/external_async_tfpluginsdk.go index 6829f5d1..4bf18f2b 100644 --- a/pkg/controller/external_async_tfpluginsdk.go +++ b/pkg/controller/external_async_tfpluginsdk.go @@ -25,17 +25,24 @@ import ( var defaultAsyncTimeout = 1 * time.Hour -type NoForkAsyncConnector struct { - *NoForkConnector +// TerraformPluginSDKAsyncConnector is a managed reconciler Connecter +// implementation for reconciling Terraform plugin SDK v2 based +// resources. +type TerraformPluginSDKAsyncConnector struct { + *TerraformPluginSDKConnector callback CallbackProvider eventHandler *handler.EventHandler } -type NoForkAsyncOption func(connector *NoForkAsyncConnector) +// TerraformPluginSDKAsyncOption represents a configuration option for +// a TerraformPluginSDKAsyncConnector object. +type TerraformPluginSDKAsyncOption func(connector *TerraformPluginSDKAsyncConnector) -func NewNoForkAsyncConnector(kube client.Client, ots *OperationTrackerStore, sf terraform.SetupFn, cfg *config.Resource, opts ...NoForkAsyncOption) *NoForkAsyncConnector { - nfac := &NoForkAsyncConnector{ - NoForkConnector: NewNoForkConnector(kube, sf, cfg, ots), +// NewTerraformPluginSDKAsyncConnector initializes a new +// TerraformPluginSDKAsyncConnector. +func NewTerraformPluginSDKAsyncConnector(kube client.Client, ots *OperationTrackerStore, sf terraform.SetupFn, cfg *config.Resource, opts ...TerraformPluginSDKAsyncOption) *TerraformPluginSDKAsyncConnector { + nfac := &TerraformPluginSDKAsyncConnector{ + TerraformPluginSDKConnector: NewTerraformPluginSDKConnector(kube, sf, cfg, ots), } for _, f := range opts { f(nfac) @@ -43,68 +50,70 @@ func NewNoForkAsyncConnector(kube client.Client, ots *OperationTrackerStore, sf return nfac } -func (c *NoForkAsyncConnector) Connect(ctx context.Context, mg xpresource.Managed) (managed.ExternalClient, error) { - ec, err := c.NoForkConnector.Connect(ctx, mg) +func (c *TerraformPluginSDKAsyncConnector) Connect(ctx context.Context, mg xpresource.Managed) (managed.ExternalClient, error) { + ec, err := c.TerraformPluginSDKConnector.Connect(ctx, mg) if err != nil { return nil, errors.Wrap(err, "cannot initialize the no-fork async external client") } - return &noForkAsyncExternal{ - noForkExternal: ec.(*noForkExternal), - callback: c.callback, - eventHandler: c.eventHandler, + return &terraformPluginSDKAsyncExternal{ + terraformPluginSDKExternal: ec.(*terraformPluginSDKExternal), + callback: c.callback, + eventHandler: c.eventHandler, }, nil } -// WithNoForkAsyncConnectorEventHandler configures the EventHandler so that -// the no-fork external clients can requeue reconciliation requests. -func WithNoForkAsyncConnectorEventHandler(e *handler.EventHandler) NoForkAsyncOption { - return func(c *NoForkAsyncConnector) { +// WithTerraformPluginSDKAsyncConnectorEventHandler configures the +// EventHandler so that the no-fork external clients can requeue +// reconciliation requests. +func WithTerraformPluginSDKAsyncConnectorEventHandler(e *handler.EventHandler) TerraformPluginSDKAsyncOption { + return func(c *TerraformPluginSDKAsyncConnector) { c.eventHandler = e } } -// WithNoForkAsyncCallbackProvider configures the controller to use async variant of the functions -// of the Terraform client and run given callbacks once those operations are -// completed. -func WithNoForkAsyncCallbackProvider(ac CallbackProvider) NoForkAsyncOption { - return func(c *NoForkAsyncConnector) { +// WithTerraformPluginSDKAsyncCallbackProvider configures the controller to use +// async variant of the functions of the Terraform client and run given +// callbacks once those operations are completed. +func WithTerraformPluginSDKAsyncCallbackProvider(ac CallbackProvider) TerraformPluginSDKAsyncOption { + return func(c *TerraformPluginSDKAsyncConnector) { c.callback = ac } } -// WithNoForkAsyncLogger configures a logger for the NoForkAsyncConnector. -func WithNoForkAsyncLogger(l logging.Logger) NoForkAsyncOption { - return func(c *NoForkAsyncConnector) { +// WithTerraformPluginSDKAsyncLogger configures a logger for the +// TerraformPluginSDKAsyncConnector. +func WithTerraformPluginSDKAsyncLogger(l logging.Logger) TerraformPluginSDKAsyncOption { + return func(c *TerraformPluginSDKAsyncConnector) { c.logger = l } } -// WithNoForkAsyncMetricRecorder configures a metrics.MetricRecorder for the -// NoForkAsyncConnector. -func WithNoForkAsyncMetricRecorder(r *metrics.MetricRecorder) NoForkAsyncOption { - return func(c *NoForkAsyncConnector) { +// WithTerraformPluginSDKAsyncMetricRecorder configures a +// metrics.MetricRecorder for the TerraformPluginSDKAsyncConnector. +func WithTerraformPluginSDKAsyncMetricRecorder(r *metrics.MetricRecorder) TerraformPluginSDKAsyncOption { + return func(c *TerraformPluginSDKAsyncConnector) { c.metricRecorder = r } } -// WithNoForkAsyncManagementPolicies configures whether the client should -// handle management policies. -func WithNoForkAsyncManagementPolicies(isManagementPoliciesEnabled bool) NoForkAsyncOption { - return func(c *NoForkAsyncConnector) { +// WithTerraformPluginSDKAsyncManagementPolicies configures whether the client +// should handle management policies. +func WithTerraformPluginSDKAsyncManagementPolicies(isManagementPoliciesEnabled bool) TerraformPluginSDKAsyncOption { + return func(c *TerraformPluginSDKAsyncConnector) { c.isManagementPoliciesEnabled = isManagementPoliciesEnabled } } -type noForkAsyncExternal struct { - *noForkExternal +type terraformPluginSDKAsyncExternal struct { + *terraformPluginSDKExternal callback CallbackProvider eventHandler *handler.EventHandler } type CallbackFn func(error, context.Context) error -func (n *noForkAsyncExternal) Observe(ctx context.Context, mg xpresource.Managed) (managed.ExternalObservation, error) { +func (n *terraformPluginSDKAsyncExternal) Observe(ctx context.Context, mg xpresource.Managed) (managed.ExternalObservation, error) { if n.opTracker.LastOperation.IsRunning() { n.logger.WithValues("opType", n.opTracker.LastOperation.Type).Debug("ongoing async operation") return managed.ExternalObservation{ @@ -114,7 +123,7 @@ func (n *noForkAsyncExternal) Observe(ctx context.Context, mg xpresource.Managed } n.opTracker.LastOperation.Flush() - o, err := n.noForkExternal.Observe(ctx, mg) + o, err := n.terraformPluginSDKExternal.Observe(ctx, mg) // clear any previously reported LastAsyncOperation error condition here, // because there are no pending updates on the existing resource and it's // not scheduled to be deleted. @@ -124,7 +133,7 @@ func (n *noForkAsyncExternal) Observe(ctx context.Context, mg xpresource.Managed return o, err } -func (n *noForkAsyncExternal) Create(_ context.Context, mg xpresource.Managed) (managed.ExternalCreation, error) { +func (n *terraformPluginSDKAsyncExternal) Create(_ context.Context, mg xpresource.Managed) (managed.ExternalCreation, error) { if !n.opTracker.LastOperation.MarkStart("create") { return managed.ExternalCreation{}, errors.Errorf("%s operation that started at %s is still running", n.opTracker.LastOperation.Type, n.opTracker.LastOperation.StartTime().String()) } @@ -134,7 +143,7 @@ func (n *noForkAsyncExternal) Create(_ context.Context, mg xpresource.Managed) ( defer cancel() n.opTracker.logger.Debug("Async create starting...", "tfID", n.opTracker.GetTfID()) - _, err := n.noForkExternal.Create(ctx, mg) + _, err := n.terraformPluginSDKExternal.Create(ctx, mg) err = tferrors.NewAsyncCreateFailed(err) n.opTracker.LastOperation.SetError(err) n.opTracker.logger.Debug("Async create ended.", "error", err, "tfID", n.opTracker.GetTfID()) @@ -148,7 +157,7 @@ func (n *noForkAsyncExternal) Create(_ context.Context, mg xpresource.Managed) ( return managed.ExternalCreation{}, nil } -func (n *noForkAsyncExternal) Update(_ context.Context, mg xpresource.Managed) (managed.ExternalUpdate, error) { +func (n *terraformPluginSDKAsyncExternal) Update(_ context.Context, mg xpresource.Managed) (managed.ExternalUpdate, error) { if !n.opTracker.LastOperation.MarkStart("update") { return managed.ExternalUpdate{}, errors.Errorf("%s operation that started at %s is still running", n.opTracker.LastOperation.Type, n.opTracker.LastOperation.StartTime().String()) } @@ -158,7 +167,7 @@ func (n *noForkAsyncExternal) Update(_ context.Context, mg xpresource.Managed) ( defer cancel() n.opTracker.logger.Debug("Async update starting...", "tfID", n.opTracker.GetTfID()) - _, err := n.noForkExternal.Update(ctx, mg) + _, err := n.terraformPluginSDKExternal.Update(ctx, mg) err = tferrors.NewAsyncUpdateFailed(err) n.opTracker.LastOperation.SetError(err) n.opTracker.logger.Debug("Async update ended.", "error", err, "tfID", n.opTracker.GetTfID()) @@ -172,7 +181,7 @@ func (n *noForkAsyncExternal) Update(_ context.Context, mg xpresource.Managed) ( return managed.ExternalUpdate{}, nil } -func (n *noForkAsyncExternal) Delete(_ context.Context, mg xpresource.Managed) error { +func (n *terraformPluginSDKAsyncExternal) Delete(_ context.Context, mg xpresource.Managed) error { switch { case n.opTracker.LastOperation.Type == "delete": n.opTracker.logger.Debug("The previous delete operation is still ongoing", "tfID", n.opTracker.GetTfID()) @@ -186,7 +195,7 @@ func (n *noForkAsyncExternal) Delete(_ context.Context, mg xpresource.Managed) e defer cancel() n.opTracker.logger.Debug("Async delete starting...", "tfID", n.opTracker.GetTfID()) - err := tferrors.NewAsyncDeleteFailed(n.noForkExternal.Delete(ctx, mg)) + err := tferrors.NewAsyncDeleteFailed(n.terraformPluginSDKExternal.Delete(ctx, mg)) n.opTracker.LastOperation.SetError(err) n.opTracker.logger.Debug("Async delete ended.", "error", err, "tfID", n.opTracker.GetTfID()) diff --git a/pkg/controller/external_async_tfpluginsdk_test.go b/pkg/controller/external_async_tfpluginsdk_test.go index 7acd0ae4..a8583274 100644 --- a/pkg/controller/external_async_tfpluginsdk_test.go +++ b/pkg/controller/external_async_tfpluginsdk_test.go @@ -76,14 +76,14 @@ var ( } ) -func prepareNoForkAsyncExternal(r Resource, cfg *config.Resource, fns CallbackFns) *noForkAsyncExternal { +func prepareTerraformPluginSDKAsyncExternal(r Resource, cfg *config.Resource, fns CallbackFns) *terraformPluginSDKAsyncExternal { schemaBlock := cfg.TerraformResource.CoreConfigSchema() rawConfig, err := schema.JSONMapToStateValue(map[string]any{"name": "example"}, schemaBlock) if err != nil { panic(err) } - return &noForkAsyncExternal{ - noForkExternal: &noForkExternal{ + return &terraformPluginSDKAsyncExternal{ + terraformPluginSDKExternal: &terraformPluginSDKExternal{ ts: terraform.Setup{}, resourceSchema: r, config: cfg, @@ -98,7 +98,7 @@ func prepareNoForkAsyncExternal(r Resource, cfg *config.Resource, fns CallbackFn } } -func TestAsyncNoForkConnect(t *testing.T) { +func TestAsyncTerraformPluginSDKConnect(t *testing.T) { type args struct { setupFn terraform.SetupFn cfg *config.Resource @@ -125,7 +125,7 @@ func TestAsyncNoForkConnect(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - c := NewNoForkAsyncConnector(nil, tc.args.ots, tc.args.setupFn, tc.args.cfg, WithNoForkAsyncLogger(logTest)) + c := NewTerraformPluginSDKAsyncConnector(nil, tc.args.ots, tc.args.setupFn, tc.args.cfg, WithTerraformPluginSDKAsyncLogger(logTest)) _, err := c.Connect(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) @@ -134,7 +134,7 @@ func TestAsyncNoForkConnect(t *testing.T) { } } -func TestAsyncNoForkObserve(t *testing.T) { +func TestAsyncTerraformPluginSDKObserve(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -191,8 +191,8 @@ func TestAsyncNoForkObserve(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkAsyncExternal := prepareNoForkAsyncExternal(tc.args.r, tc.args.cfg, CallbackFns{}) - observation, err := noForkAsyncExternal.Observe(context.TODO(), tc.args.obj) + terraformPluginSDKAsyncExternal := prepareTerraformPluginSDKAsyncExternal(tc.args.r, tc.args.cfg, CallbackFns{}) + observation, err := terraformPluginSDKAsyncExternal.Observe(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.obs, observation); diff != "" { t.Errorf("\n%s\nObserve(...): -want observation, +got observation:\n", diff) } @@ -203,7 +203,7 @@ func TestAsyncNoForkObserve(t *testing.T) { } } -func TestAsyncNoForkCreate(t *testing.T) { +func TestAsyncTerraformPluginSDKCreate(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -238,8 +238,8 @@ func TestAsyncNoForkCreate(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkAsyncExternal := prepareNoForkAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) - _, err := noForkAsyncExternal.Create(context.TODO(), tc.args.obj) + terraformPluginSDKAsyncExternal := prepareTerraformPluginSDKAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) + _, err := terraformPluginSDKAsyncExternal.Create(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } @@ -247,7 +247,7 @@ func TestAsyncNoForkCreate(t *testing.T) { } } -func TestAsyncNoForkUpdate(t *testing.T) { +func TestAsyncTerraformPluginSDKUpdate(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -282,8 +282,8 @@ func TestAsyncNoForkUpdate(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkAsyncExternal := prepareNoForkAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) - _, err := noForkAsyncExternal.Update(context.TODO(), tc.args.obj) + terraformPluginSDKAsyncExternal := prepareTerraformPluginSDKAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) + _, err := terraformPluginSDKAsyncExternal.Update(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } @@ -291,7 +291,7 @@ func TestAsyncNoForkUpdate(t *testing.T) { } } -func TestAsyncNoForkDelete(t *testing.T) { +func TestAsyncTerraformPluginSDKDelete(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -326,8 +326,8 @@ func TestAsyncNoForkDelete(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkAsyncExternal := prepareNoForkAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) - err := noForkAsyncExternal.Delete(context.TODO(), tc.args.obj) + terraformPluginSDKAsyncExternal := prepareTerraformPluginSDKAsyncExternal(tc.args.r, tc.args.cfg, tc.args.fns) + err := terraformPluginSDKAsyncExternal.Delete(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } diff --git a/pkg/controller/external_tfpluginsdk.go b/pkg/controller/external_tfpluginsdk.go index 82cdb373..eff84c0f 100644 --- a/pkg/controller/external_tfpluginsdk.go +++ b/pkg/controller/external_tfpluginsdk.go @@ -31,7 +31,7 @@ import ( "github.com/crossplane/upjet/pkg/terraform" ) -type NoForkConnector struct { +type TerraformPluginSDKConnector struct { getTerraformSetup terraform.SetupFn kube client.Client config *config.Resource @@ -41,34 +41,35 @@ type NoForkConnector struct { isManagementPoliciesEnabled bool } -// NoForkOption allows you to configure NoForkConnector. -type NoForkOption func(connector *NoForkConnector) +// TerraformPluginSDKOption allows you to configure TerraformPluginSDKConnector. +type TerraformPluginSDKOption func(connector *TerraformPluginSDKConnector) -// WithNoForkLogger configures a logger for the NoForkConnector. -func WithNoForkLogger(l logging.Logger) NoForkOption { - return func(c *NoForkConnector) { +// WithTerraformPluginSDKLogger configures a logger for the TerraformPluginSDKConnector. +func WithTerraformPluginSDKLogger(l logging.Logger) TerraformPluginSDKOption { + return func(c *TerraformPluginSDKConnector) { c.logger = l } } -// WithNoForkMetricRecorder configures a metrics.MetricRecorder for the -// NoForkConnector. -func WithNoForkMetricRecorder(r *metrics.MetricRecorder) NoForkOption { - return func(c *NoForkConnector) { +// WithTerraformPluginSDKMetricRecorder configures a metrics.MetricRecorder for the +// TerraformPluginSDKConnector. +func WithTerraformPluginSDKMetricRecorder(r *metrics.MetricRecorder) TerraformPluginSDKOption { + return func(c *TerraformPluginSDKConnector) { c.metricRecorder = r } } -// WithNoForkManagementPolicies configures whether the client should +// WithTerraformPluginSDKManagementPolicies configures whether the client should // handle management policies. -func WithNoForkManagementPolicies(isManagementPoliciesEnabled bool) NoForkOption { - return func(c *NoForkConnector) { +func WithTerraformPluginSDKManagementPolicies(isManagementPoliciesEnabled bool) TerraformPluginSDKOption { + return func(c *TerraformPluginSDKConnector) { c.isManagementPoliciesEnabled = isManagementPoliciesEnabled } } -func NewNoForkConnector(kube client.Client, sf terraform.SetupFn, cfg *config.Resource, ots *OperationTrackerStore, opts ...NoForkOption) *NoForkConnector { - nfc := &NoForkConnector{ +// NewTerraformPluginSDKConnector initializes a new TerraformPluginSDKConnector +func NewTerraformPluginSDKConnector(kube client.Client, sf terraform.SetupFn, cfg *config.Resource, ots *OperationTrackerStore, opts ...TerraformPluginSDKOption) *TerraformPluginSDKConnector { + nfc := &TerraformPluginSDKConnector{ kube: kube, getTerraformSetup: sf, config: cfg, @@ -108,7 +109,7 @@ type Resource interface { RefreshWithoutUpgrade(ctx context.Context, s *tf.InstanceState, meta interface{}) (*tf.InstanceState, tfdiag.Diagnostics) } -type noForkExternal struct { +type terraformPluginSDKExternal struct { ts terraform.Setup resourceSchema Resource config *config.Resource @@ -154,7 +155,7 @@ func getExtendedParameters(ctx context.Context, tr resource.Terraformed, externa return params, nil } -func (c *NoForkConnector) processParamsWithStateFunc(schemaMap map[string]*schema.Schema, params map[string]any) map[string]any { +func (c *TerraformPluginSDKConnector) processParamsWithStateFunc(schemaMap map[string]*schema.Schema, params map[string]any) map[string]any { if params == nil { return params } @@ -168,7 +169,7 @@ func (c *NoForkConnector) processParamsWithStateFunc(schemaMap map[string]*schem return params } -func (c *NoForkConnector) applyStateFuncToParam(sc *schema.Schema, param any) any { //nolint:gocyclo +func (c *TerraformPluginSDKConnector) applyStateFuncToParam(sc *schema.Schema, param any) any { //nolint:gocyclo if param == nil { return param } @@ -229,7 +230,7 @@ func (c *NoForkConnector) applyStateFuncToParam(sc *schema.Schema, param any) an return param } -func (c *NoForkConnector) Connect(ctx context.Context, mg xpresource.Managed) (managed.ExternalClient, error) { //nolint:gocyclo +func (c *TerraformPluginSDKConnector) Connect(ctx context.Context, mg xpresource.Managed) (managed.ExternalClient, error) { //nolint:gocyclo c.metricRecorder.ObserveReconcileDelay(mg.GetObjectKind().GroupVersionKind(), mg.GetName()) logger := c.logger.WithValues("uid", mg.GetUID(), "name", mg.GetName(), "gvk", mg.GetObjectKind().GroupVersionKind().String()) logger.Debug("Connecting to the service provider") @@ -295,7 +296,7 @@ func (c *NoForkConnector) Connect(ctx context.Context, mg xpresource.Managed) (m opTracker.SetTfState(s) } - return &noForkExternal{ + return &terraformPluginSDKExternal{ ts: ts, resourceSchema: c.config.TerraformResource, config: c.config, @@ -416,7 +417,7 @@ func getTimeoutParameters(config *config.Resource) map[string]any { //nolint:goc return timeouts } -func (n *noForkExternal) getResourceDataDiff(tr resource.Terraformed, ctx context.Context, s *tf.InstanceState, resourceExists bool) (*tf.InstanceDiff, error) { //nolint:gocyclo +func (n *terraformPluginSDKExternal) getResourceDataDiff(tr resource.Terraformed, ctx context.Context, s *tf.InstanceState, resourceExists bool) (*tf.InstanceDiff, error) { //nolint:gocyclo resourceConfig := tf.NewResourceConfigRaw(n.params) instanceDiff, err := schema.InternalMap(n.config.TerraformResource.Schema).Diff(ctx, s, resourceConfig, n.config.TerraformResource.CustomizeDiff, n.ts.Meta, false) if err != nil { @@ -461,7 +462,7 @@ func (n *noForkExternal) getResourceDataDiff(tr resource.Terraformed, ctx contex return instanceDiff, nil } -func (n *noForkExternal) Observe(ctx context.Context, mg xpresource.Managed) (managed.ExternalObservation, error) { //nolint:gocyclo +func (n *terraformPluginSDKExternal) Observe(ctx context.Context, mg xpresource.Managed) (managed.ExternalObservation, error) { //nolint:gocyclo n.logger.Debug("Observing the external resource") if meta.WasDeleted(mg) && n.opTracker.IsDeleted() { @@ -559,7 +560,7 @@ func (n *noForkExternal) Observe(ctx context.Context, mg xpresource.Managed) (ma // sets the external-name on the MR. Returns `true` // if the external-name of the MR has changed. -func (n *noForkExternal) setExternalName(mg xpresource.Managed, stateValueMap map[string]interface{}) (bool, error) { +func (n *terraformPluginSDKExternal) setExternalName(mg xpresource.Managed, stateValueMap map[string]interface{}) (bool, error) { id, ok := stateValueMap["id"] if !ok || id.(string) == "" { return false, nil @@ -574,7 +575,7 @@ func (n *noForkExternal) setExternalName(mg xpresource.Managed, stateValueMap ma return oldName != newName, nil } -func (n *noForkExternal) Create(ctx context.Context, mg xpresource.Managed) (managed.ExternalCreation, error) { +func (n *terraformPluginSDKExternal) Create(ctx context.Context, mg xpresource.Managed) (managed.ExternalCreation, error) { n.logger.Debug("Creating the external resource") start := time.Now() newState, diag := n.resourceSchema.Apply(ctx, n.opTracker.GetTfState(), n.instanceDiff, n.ts.Meta) @@ -636,7 +637,7 @@ func (n *noForkExternal) Create(ctx context.Context, mg xpresource.Managed) (man return managed.ExternalCreation{ConnectionDetails: conn}, nil } -func (n *noForkExternal) assertNoForceNew() error { +func (n *terraformPluginSDKExternal) assertNoForceNew() error { if n.instanceDiff == nil { return nil } @@ -656,7 +657,7 @@ func (n *noForkExternal) assertNoForceNew() error { return nil } -func (n *noForkExternal) Update(ctx context.Context, mg xpresource.Managed) (managed.ExternalUpdate, error) { +func (n *terraformPluginSDKExternal) Update(ctx context.Context, mg xpresource.Managed) (managed.ExternalUpdate, error) { n.logger.Debug("Updating the external resource") if err := n.assertNoForceNew(); err != nil { @@ -683,7 +684,7 @@ func (n *noForkExternal) Update(ctx context.Context, mg xpresource.Managed) (man return managed.ExternalUpdate{}, nil } -func (n *noForkExternal) Delete(ctx context.Context, _ xpresource.Managed) error { +func (n *terraformPluginSDKExternal) Delete(ctx context.Context, _ xpresource.Managed) error { n.logger.Debug("Deleting the external resource") if n.instanceDiff == nil { n.instanceDiff = tf.NewInstanceDiff() @@ -702,7 +703,7 @@ func (n *noForkExternal) Delete(ctx context.Context, _ xpresource.Managed) error return nil } -func (n *noForkExternal) fromInstanceStateToJSONMap(newState *tf.InstanceState) (map[string]interface{}, cty.Value, error) { +func (n *terraformPluginSDKExternal) fromInstanceStateToJSONMap(newState *tf.InstanceState) (map[string]interface{}, cty.Value, error) { impliedType := n.config.TerraformResource.CoreConfigSchema().ImpliedType() attrsAsCtyValue, err := newState.AttrsAsObjectValue(impliedType) if err != nil { diff --git a/pkg/controller/external_tfpluginsdk_test.go b/pkg/controller/external_tfpluginsdk_test.go index 3109f669..e1a11bf0 100644 --- a/pkg/controller/external_tfpluginsdk_test.go +++ b/pkg/controller/external_tfpluginsdk_test.go @@ -84,13 +84,13 @@ var ( } ) -func prepareNoForkExternal(r Resource, cfg *config.Resource) *noForkExternal { +func prepareTerraformPluginSDKExternal(r Resource, cfg *config.Resource) *terraformPluginSDKExternal { schemaBlock := cfg.TerraformResource.CoreConfigSchema() rawConfig, err := schema.JSONMapToStateValue(map[string]any{"name": "example"}, schemaBlock) if err != nil { panic(err) } - return &noForkExternal{ + return &terraformPluginSDKExternal{ ts: terraform.Setup{}, resourceSchema: r, config: cfg, @@ -116,7 +116,7 @@ func (m mockResource) RefreshWithoutUpgrade(ctx context.Context, s *tf.InstanceS return m.RefreshWithoutUpgradeFn(ctx, s, meta) } -func TestNoForkConnect(t *testing.T) { +func TestTerraformPluginSDKConnect(t *testing.T) { type args struct { setupFn terraform.SetupFn cfg *config.Resource @@ -167,7 +167,7 @@ func TestNoForkConnect(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { - c := NewNoForkConnector(nil, tc.args.setupFn, tc.args.cfg, tc.args.ots, WithNoForkLogger(logTest)) + c := NewTerraformPluginSDKConnector(nil, tc.args.setupFn, tc.args.cfg, tc.args.ots, WithTerraformPluginSDKLogger(logTest)) _, err := c.Connect(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) @@ -176,7 +176,7 @@ func TestNoForkConnect(t *testing.T) { } } -func TestNoForkObserve(t *testing.T) { +func TestTerraformPluginSDKObserve(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -270,8 +270,8 @@ func TestNoForkObserve(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkExternal := prepareNoForkExternal(tc.args.r, tc.args.cfg) - observation, err := noForkExternal.Observe(context.TODO(), tc.args.obj) + terraformPluginSDKExternal := prepareTerraformPluginSDKExternal(tc.args.r, tc.args.cfg) + observation, err := terraformPluginSDKExternal.Observe(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.obs, observation); diff != "" { t.Errorf("\n%s\nObserve(...): -want observation, +got observation:\n", diff) } @@ -282,7 +282,7 @@ func TestNoForkObserve(t *testing.T) { } } -func TestNoForkCreate(t *testing.T) { +func TestTerraformPluginSDKCreate(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -323,8 +323,8 @@ func TestNoForkCreate(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkExternal := prepareNoForkExternal(tc.args.r, tc.args.cfg) - _, err := noForkExternal.Create(context.TODO(), tc.args.obj) + terraformPluginSDKExternal := prepareTerraformPluginSDKExternal(tc.args.r, tc.args.cfg) + _, err := terraformPluginSDKExternal.Create(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } @@ -332,7 +332,7 @@ func TestNoForkCreate(t *testing.T) { } } -func TestNoForkUpdate(t *testing.T) { +func TestTerraformPluginSDKUpdate(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -359,8 +359,8 @@ func TestNoForkUpdate(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkExternal := prepareNoForkExternal(tc.args.r, tc.args.cfg) - _, err := noForkExternal.Update(context.TODO(), tc.args.obj) + terraformPluginSDKExternal := prepareTerraformPluginSDKExternal(tc.args.r, tc.args.cfg) + _, err := terraformPluginSDKExternal.Update(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } @@ -368,7 +368,7 @@ func TestNoForkUpdate(t *testing.T) { } } -func TestNoForkDelete(t *testing.T) { +func TestTerraformPluginSDKDelete(t *testing.T) { type args struct { r Resource cfg *config.Resource @@ -395,8 +395,8 @@ func TestNoForkDelete(t *testing.T) { } for name, tc := range cases { t.Run(name, func(t *testing.T) { - noForkExternal := prepareNoForkExternal(tc.args.r, tc.args.cfg) - err := noForkExternal.Delete(context.TODO(), tc.args.obj) + terraformPluginSDKExternal := prepareTerraformPluginSDKExternal(tc.args.r, tc.args.cfg) + err := terraformPluginSDKExternal.Delete(context.TODO(), tc.args.obj) if diff := cmp.Diff(tc.want.err, err, test.EquateErrors()); diff != "" { t.Errorf("\n%s\nConnect(...): -want error, +got error:\n", diff) } diff --git a/pkg/controller/finalizer_tfpluginsdk.go b/pkg/controller/finalizer_tfpluginsdk.go index 7476f454..410f9482 100644 --- a/pkg/controller/finalizer_tfpluginsdk.go +++ b/pkg/controller/finalizer_tfpluginsdk.go @@ -20,29 +20,29 @@ type TrackerCleaner interface { RemoveTracker(obj xpresource.Object) error } -// NewNoForkFinalizer returns a new NoForkFinalizer. -func NewNoForkFinalizer(tc TrackerCleaner, af xpresource.Finalizer) *NoForkFinalizer { - return &NoForkFinalizer{ +// NewTerraformPluginSDKFinalizer returns a new TerraformPluginSDKFinalizer. +func NewTerraformPluginSDKFinalizer(tc TrackerCleaner, af xpresource.Finalizer) *TerraformPluginSDKFinalizer { + return &TerraformPluginSDKFinalizer{ Finalizer: af, OperationStore: tc, } } -// NoForkFinalizer removes the operation tracker from the workspace store and only +// TerraformPluginSDKFinalizer removes the operation tracker from the workspace store and only // then calls RemoveFinalizer of the underlying Finalizer. -type NoForkFinalizer struct { +type TerraformPluginSDKFinalizer struct { xpresource.Finalizer OperationStore TrackerCleaner } // AddFinalizer to the supplied Managed resource. -func (nf *NoForkFinalizer) AddFinalizer(ctx context.Context, obj xpresource.Object) error { +func (nf *TerraformPluginSDKFinalizer) AddFinalizer(ctx context.Context, obj xpresource.Object) error { return nf.Finalizer.AddFinalizer(ctx, obj) } // RemoveFinalizer removes the workspace from workspace store before removing // the finalizer. -func (nf *NoForkFinalizer) RemoveFinalizer(ctx context.Context, obj xpresource.Object) error { +func (nf *TerraformPluginSDKFinalizer) RemoveFinalizer(ctx context.Context, obj xpresource.Object) error { if err := nf.OperationStore.RemoveTracker(obj); err != nil { return errors.Wrap(err, errRemoveTracker) } diff --git a/pkg/pipeline/controller.go b/pkg/pipeline/controller.go index cdd0339a..3400cdd5 100644 --- a/pkg/pipeline/controller.go +++ b/pkg/pipeline/controller.go @@ -50,7 +50,7 @@ func (cg *ControllerGenerator) Generate(cfg *config.Resource, typesPkgPath strin "DisableNameInitializer": cfg.ExternalName.DisableNameInitializer, "TypePackageAlias": ctrlFile.Imports.UsePackage(typesPkgPath), "UseAsync": cfg.UseAsync, - "UseNoForkClient": cfg.ShouldUseNoForkClient(), + "UseTerraformPluginSDKClient": cfg.ShouldUseTerraformPluginSDKClient(), "UseTerraformPluginFrameworkClient": cfg.ShouldUseTerraformPluginFrameworkClient(), "ResourceType": cfg.Name, "Initializers": cfg.InitializerFns, diff --git a/pkg/pipeline/templates/controller.go.tmpl b/pkg/pipeline/templates/controller.go.tmpl index dfa651e2..4d5fe20f 100644 --- a/pkg/pipeline/templates/controller.go.tmpl +++ b/pkg/pipeline/templates/controller.go.tmpl @@ -43,27 +43,27 @@ func Setup(mgr ctrl.Manager, o tjcontroller.Options) error { } eventHandler := handler.NewEventHandler(handler.WithLogger(o.Logger.WithValues("gvk", {{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind))) {{- if .UseAsync }} - ac := tjcontroller.NewAPICallbacks(mgr, xpresource.ManagedKind({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind), tjcontroller.WithEventHandler(eventHandler){{ if or .UseNoForkClient .UseTerraformPluginFrameworkClient }}, tjcontroller.WithStatusUpdates(false){{ end }}) + ac := tjcontroller.NewAPICallbacks(mgr, xpresource.ManagedKind({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind), tjcontroller.WithEventHandler(eventHandler){{ if or .UseTerraformPluginSDKClient .UseTerraformPluginFrameworkClient }}, tjcontroller.WithStatusUpdates(false){{ end }}) {{- end}} opts := []managed.ReconcilerOption{ managed.WithExternalConnecter( - {{- if .UseNoForkClient -}} + {{- if .UseTerraformPluginSDKClient -}} {{- if .UseAsync }} - tjcontroller.NewNoForkAsyncConnector(mgr.GetClient(), o.OperationTrackerStore, o.SetupFn, o.Provider.Resources["{{ .ResourceType }}"], - tjcontroller.WithNoForkAsyncLogger(o.Logger), - tjcontroller.WithNoForkAsyncConnectorEventHandler(eventHandler), - tjcontroller.WithNoForkAsyncCallbackProvider(ac), - tjcontroller.WithNoForkAsyncMetricRecorder(metrics.NewMetricRecorder({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind, mgr, o.PollInterval)), + tjcontroller.NewTerraformPluginSDKAsyncConnector(mgr.GetClient(), o.OperationTrackerStore, o.SetupFn, o.Provider.Resources["{{ .ResourceType }}"], + tjcontroller.WithTerraformPluginSDKAsyncLogger(o.Logger), + tjcontroller.WithTerraformPluginSDKAsyncConnectorEventHandler(eventHandler), + tjcontroller.WithTerraformPluginSDKAsyncCallbackProvider(ac), + tjcontroller.WithTerraformPluginSDKAsyncMetricRecorder(metrics.NewMetricRecorder({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind, mgr, o.PollInterval)), {{if .FeaturesPackageAlias -}} - tjcontroller.WithNoForkAsyncManagementPolicies(o.Features.Enabled({{ .FeaturesPackageAlias }}EnableBetaManagementPolicies)) + tjcontroller.WithTerraformPluginSDKAsyncManagementPolicies(o.Features.Enabled({{ .FeaturesPackageAlias }}EnableBetaManagementPolicies)) {{- end -}} ) {{- else -}} - tjcontroller.NewNoForkConnector(mgr.GetClient(), o.SetupFn, o.Provider.Resources["{{ .ResourceType }}"], o.OperationTrackerStore, - tjcontroller.WithNoForkLogger(o.Logger), - tjcontroller.WithNoForkMetricRecorder(metrics.NewMetricRecorder({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind, mgr, o.PollInterval)), + tjcontroller.NewTerraformPluginSDKConnector(mgr.GetClient(), o.SetupFn, o.Provider.Resources["{{ .ResourceType }}"], o.OperationTrackerStore, + tjcontroller.WithTerraformPluginSDKLogger(o.Logger), + tjcontroller.WithTerraformPluginSDKMetricRecorder(metrics.NewMetricRecorder({{ .TypePackageAlias }}{{ .CRD.Kind }}_GroupVersionKind, mgr, o.PollInterval)), {{if .FeaturesPackageAlias -}} - tjcontroller.WithNoForkManagementPolicies(o.Features.Enabled({{ .FeaturesPackageAlias }}EnableBetaManagementPolicies)) + tjcontroller.WithTerraformPluginSDKManagementPolicies(o.Features.Enabled({{ .FeaturesPackageAlias }}EnableBetaManagementPolicies)) {{- end -}} ) {{- end -}} @@ -97,9 +97,9 @@ func Setup(mgr ctrl.Manager, o tjcontroller.Options) error { ), managed.WithLogger(o.Logger.WithValues("controller", name)), managed.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))), - {{- if .UseNoForkClient }} + {{- if .UseTerraformPluginSDKClient }} {{- if .UseAsync }} - managed.WithFinalizer(tjcontroller.NewNoForkFinalizer(o.OperationTrackerStore, xpresource.NewAPIFinalizer(mgr.GetClient(), managed.FinalizerName))), + managed.WithFinalizer(tjcontroller.NewTerraformPluginSDKFinalizer(o.OperationTrackerStore, xpresource.NewAPIFinalizer(mgr.GetClient(), managed.FinalizerName))), {{- end }} {{- else }} managed.WithFinalizer(terraform.NewWorkspaceFinalizer(o.WorkspaceStore, xpresource.NewAPIFinalizer(mgr.GetClient(), managed.FinalizerName))),