Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove spurious ConflictsWith warnings on import #1948

Merged
merged 7 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions pkg/tfbridge/deconflict.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright 2016-2024, 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 tfbridge

import (
"context"
"fmt"
"strconv"
"strings"

"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/info"
shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/walk"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/propertyvalue"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)

// Transforms inputs to enforce input bag conformance with ConflictsWith constraints.
//
// This arbitrarily drops properties until none are left in conflict.
//
// Why is this necessary: Read in Pulumi is expected to produce an input bag that is going to subsequently pass Check,
// but TF providers are not always well-behaved in this regard.
func deconflict(
ctx context.Context,
schemaMap shim.SchemaMap,
schemaInfos map[string]*info.Schema,
inputs resource.PropertyMap,
) resource.PropertyMap {
cm := newConflictsMap(schemaMap)
visitedPaths := map[string]struct{}{}
visit := func(pp resource.PropertyPath, pv resource.PropertyValue) (resource.PropertyValue, error) {
sp := PropertyPathToSchemaPath(pp, schemaMap, schemaInfos)
conflict := false
var conflictAt walk.SchemaPath
for _, cp := range cm.ConflictingPaths(sp) {
if _, ok := visitedPaths[cp.MustEncodeSchemaPath()]; ok {
conflict = true
conflictAt = cp
break
}
}
if conflict {
msg := fmt.Sprintf("Dropping property at %q to respect ConflictsWith constraint from %q",
pp.String(), conflictAt.MustEncodeSchemaPath())
GetLogger(ctx).Debug(msg)
return resource.NewNullProperty(), nil
}
visitedPaths[sp.MustEncodeSchemaPath()] = struct{}{}
return pv, nil
}

obj := resource.NewObjectProperty(inputs)
pv, err := propertyvalue.TransformPropertyValue(resource.PropertyPath{}, visit, obj)
contract.AssertNoErrorf(err, "deconflict transformation is never expected to fail")
contract.Assertf(pv.IsObject(), "deconflict transformation is not expected to change objects to something else")
return pv.ObjectValue()
}

type conflictsMap struct {
conflicts map[string][]walk.SchemaPath
}

func (cm *conflictsMap) ConflictingPaths(atPath walk.SchemaPath) []walk.SchemaPath {
return cm.conflicts[atPath.MustEncodeSchemaPath()]
}

func (cm *conflictsMap) AddConflict(atPath walk.SchemaPath, conflictingPaths []walk.SchemaPath) {
cm.conflicts[atPath.MustEncodeSchemaPath()] = conflictingPaths
}

func newConflictsMap(schemaMap shim.SchemaMap) *conflictsMap {
cm := &conflictsMap{conflicts: map[string][]walk.SchemaPath{}}
walk.VisitSchemaMap(schemaMap, func(sp walk.SchemaPath, s shim.Schema) {
if len(s.ConflictsWith()) > 0 {
conflictingPaths := []walk.SchemaPath{}
for _, p := range s.ConflictsWith() {
conflictingPaths = append(conflictingPaths, parseConflictsWith(p))
}
cm.AddConflict(sp, conflictingPaths)
}
})
return cm
}

func parseConflictsWith(s string) walk.SchemaPath {
parts := strings.Split(s, ".")
result := walk.NewSchemaPath()
for _, p := range parts {
_, strconvErr := strconv.Atoi(p)
isNum := strconvErr == nil
if isNum {
result = result.Element()
} else {
result = result.GetAttr(p)
}
}
return result
}
82 changes: 82 additions & 0 deletions pkg/tfbridge/deconflict_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2016-2024, 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 tfbridge

import (
"context"
"fmt"
"testing"

shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/schema"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/stretchr/testify/require"
)

func TestDeconflict(t *testing.T) {
ctx := context.Background()

ctx = logging.InitLogging(ctx, logging.LogOptions{})
schema := &schema.SchemaMap{
"availability_zone": (&schema.Schema{
Type: shim.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"availability_zone_id"},
}).Shim(),
"availability_zone_id": (&schema.Schema{
Type: shim.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"availability_zone"},
}).Shim(),
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test for different ConflictsWith topologies?

At the very least:

A conflicts with B (where B does not conflict with A)

A conflicts with B and C, B conflicts with A and C, C conflicts with A and B

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah good point, adding a few.


type testCase struct {
inputs resource.PropertyMap
expected resource.PropertyMap
}

testCases := []testCase{
{
inputs: resource.PropertyMap{
"availabilityZone": resource.NewStringProperty("us-east-1c"),
"availabilityZoneId": resource.NewStringProperty("use1-az1"),
},
expected: resource.PropertyMap{
"availabilityZone": resource.NewStringProperty("us-east-1c"),
"availabilityZoneId": resource.NewNullProperty(),
},
},
}

for i, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) {
actual := deconflict(ctx, schema, nil, tc.inputs)
require.Equal(t, tc.expected, actual)
})
}
}

func TestParseConflictsWith(t *testing.T) {
cw := "capacity_reservation_specification.0.capacity_reservation_target.0.capacity_reservation_id"
actual := parseConflictsWith(cw)
expect := "capacity_reservation_specification.$.capacity_reservation_target.$.capacity_reservation_id"
require.Equal(t, expect, actual.MustEncodeSchemaPath())
}
5 changes: 4 additions & 1 deletion pkg/tfbridge/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1239,7 +1239,10 @@ func (p *Provider) Read(ctx context.Context, req *pulumirpc.ReadRequest) (*pulum
if err != nil {
return nil, err
}
minputs, err := plugin.MarshalProperties(inputs, plugin.MarshalOptions{

cleanInputs := deconflict(ctx, res.TF.Schema(), res.Schema.Fields, inputs)

minputs, err := plugin.MarshalProperties(cleanInputs, plugin.MarshalOptions{
Label: label + ".inputs",
KeepSecrets: p.supportsSecrets,
})
Expand Down