2024-02-08 03:48:59 -06:00
// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
2023-05-02 10:33:06 -05:00
// SPDX-License-Identifier: MPL-2.0
2023-09-20 07:16:53 -05:00
package tofu
2018-11-30 12:56:50 -06:00
import (
2020-08-06 20:45:57 -05:00
"encoding/json"
2018-11-30 12:56:50 -06:00
"fmt"
"log"
2023-09-20 06:35:35 -05:00
"github.com/opentofu/opentofu/internal/addrs"
"github.com/opentofu/opentofu/internal/configs/configschema"
"github.com/opentofu/opentofu/internal/providers"
"github.com/opentofu/opentofu/internal/states"
"github.com/opentofu/opentofu/internal/tfdiags"
2020-08-06 20:45:57 -05:00
"github.com/zclconf/go-cty/cty"
2018-11-30 12:56:50 -06:00
)
2020-12-10 08:55:50 -06:00
// upgradeResourceState will, if necessary, run the provider-defined upgrade
2018-11-30 12:56:50 -06:00
// logic against the given state object to make it compliant with the
// current schema version. This is a no-op if the given state object is
// already at the latest version.
//
// If any errors occur during upgrade, error diagnostics are returned. In that
// case it is not safe to proceed with using the original state object.
2020-12-10 08:55:50 -06:00
func upgradeResourceState ( addr addrs . AbsResourceInstance , provider providers . Interface , src * states . ResourceInstanceObjectSrc , currentSchema * configschema . Block , currentVersion uint64 ) ( * states . ResourceInstanceObjectSrc , tfdiags . Diagnostics ) {
2022-04-11 10:55:53 -05:00
if addr . Resource . Resource . Mode != addrs . ManagedResourceMode {
// We only do state upgrading for managed resources.
// This was a part of the normal workflow in older versions and
// returned early, so we are only going to log the error for now.
log . Printf ( "[ERROR] data resource %s should not require state upgrade" , addr )
return src , nil
}
2020-08-06 20:45:57 -05:00
// Remove any attributes from state that are not present in the schema.
// This was previously taken care of by the provider, but data sources do
// not go through the UpgradeResourceState process.
//
// Legacy flatmap state is already taken care of during conversion.
// If the schema version is be changed, then allow the provider to handle
// removed attributes.
if len ( src . AttrsJSON ) > 0 && src . SchemaVersion == currentVersion {
src . AttrsJSON = stripRemovedStateAttributes ( src . AttrsJSON , currentSchema . ImpliedType ( ) )
}
2019-05-10 11:25:02 -05:00
stateIsFlatmap := len ( src . AttrsJSON ) == 0
Initial steps towards AbsProviderConfig/LocalProviderConfig separation (#23978)
* Introduce "Local" terminology for non-absolute provider config addresses
In a future change AbsProviderConfig and LocalProviderConfig are going to
become two entirely distinct types, rather than Abs embedding Local as
written here. This naming change is in preparation for that subsequent
work, which will also include introducing a new "ProviderConfig" type
that is an interface that AbsProviderConfig and LocalProviderConfig both
implement.
This is intended to be largely just a naming change to get started, so
we can deal with all of the messy renaming. However, this did also require
a slight change in modeling where the Resource.DefaultProviderConfig
method has become Resource.DefaultProvider returning a Provider address
directly, because this method doesn't have enough information to construct
a true and accurate LocalProviderConfig -- it would need to refer to the
configuration to know what this module is calling the provider it has
selected.
In order to leave a trail to follow for subsequent work, all of the
changes here are intended to ensure that remaining work will become
obvious via compile-time errors when all of the following changes happen:
- The concept of "legacy" provider addresses is removed from the addrs
package, including removing addrs.NewLegacyProvider and
addrs.Provider.LegacyString.
- addrs.AbsProviderConfig stops having addrs.LocalProviderConfig embedded
in it and has an addrs.Provider and a string alias directly instead.
- The provider-schema-handling parts of Terraform core are updated to
work with addrs.Provider to identify providers, rather than legacy
strings.
In particular, there are still several codepaths here making legacy
provider address assumptions (in order to limit the scope of this change)
but I've made sure each one is doing something that relies on at least
one of the above changes not having been made yet.
* addrs: ProviderConfig interface
In a (very) few special situations in the main "terraform" package we need
to make runtime decisions about whether a provider config is absolute
or local.
We currently do that by exploiting the fact that AbsProviderConfig has
LocalProviderConfig nested inside of it and so in the local case we can
just ignore the wrapping AbsProviderConfig and use the embedded value.
In a future change we'll be moving away from that embedding and making
these two types distinct in order to represent that mapping between them
requires consulting a lookup table in the configuration, and so here we
introduce a new interface type ProviderConfig that can represent either
AbsProviderConfig or LocalProviderConfig decided dynamically at runtime.
This also includes the Config.ResolveAbsProviderAddr method that will
eventually be responsible for that local-to-absolute translation, so
that callers with access to the configuration can normalize to an
addrs.AbsProviderConfig given a non-nil addrs.ProviderConfig. That's
currently unused because existing callers are still relying on the
simplistic structural transform, but we'll switch them over in a later
commit.
* rename LocalType to LocalName
Co-authored-by: Kristin Laemmert <mildwonkey@users.noreply.github.com>
2020-01-31 07:23:07 -06:00
// TODO: This should eventually use a proper FQN.
2020-03-18 07:58:20 -05:00
providerType := addr . Resource . Resource . ImpliedProvider ( )
2018-11-30 12:56:50 -06:00
if src . SchemaVersion > currentVersion {
2020-12-10 08:55:50 -06:00
log . Printf ( "[TRACE] upgradeResourceState: can't downgrade state for %s from version %d to %d" , addr , src . SchemaVersion , currentVersion )
2018-11-30 12:56:50 -06:00
var diags tfdiags . Diagnostics
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Resource instance managed by newer provider version" ,
// This is not a very good error message, but we don't retain enough
// information in state to give good feedback on what provider
// version might be required here. :(
fmt . Sprintf ( "The current state of %s was created by a newer provider version than is currently selected. Upgrade the %s provider to work with this state." , addr , providerType ) ,
) )
return nil , diags
}
// If we get down here then we need to upgrade the state, with the
// provider's help.
2023-09-26 12:09:27 -05:00
// If this state was originally created by a version of OpenTofu prior to
2018-11-30 12:56:50 -06:00
// v0.12, this also includes translating from legacy flatmap to new-style
// representation, since only the provider has enough information to
// understand a flatmap built against an older schema.
2019-05-10 11:25:02 -05:00
if src . SchemaVersion != currentVersion {
2020-12-10 08:55:50 -06:00
log . Printf ( "[TRACE] upgradeResourceState: upgrading state for %s from version %d to %d using provider %q" , addr , src . SchemaVersion , currentVersion , providerType )
2019-05-10 11:25:02 -05:00
} else {
2020-12-10 08:55:50 -06:00
log . Printf ( "[TRACE] upgradeResourceState: schema version of %s is still %d; calling provider %q for any other minor fixups" , addr , currentVersion , providerType )
2019-05-10 11:25:02 -05:00
}
2018-11-30 12:56:50 -06:00
req := providers . UpgradeResourceStateRequest {
TypeName : addr . Resource . Resource . Type ,
// TODO: The internal schema version representations are all using
// uint64 instead of int64, but unsigned integers aren't friendly
// to all protobuf target languages so in practice we use int64
// on the wire. In future we will change all of our internal
// representations to int64 too.
Version : int64 ( src . SchemaVersion ) ,
}
2019-03-21 14:03:12 -05:00
if stateIsFlatmap {
2018-11-30 12:56:50 -06:00
req . RawStateFlatmap = src . AttrsFlat
2019-03-21 14:03:12 -05:00
} else {
req . RawStateJSON = src . AttrsJSON
2018-11-30 12:56:50 -06:00
}
resp := provider . UpgradeResourceState ( req )
diags := resp . Diagnostics
if diags . HasErrors ( ) {
return nil , diags
}
// After upgrading, the new value must conform to the current schema. When
// going over RPC this is actually already ensured by the
// marshaling/unmarshaling of the new value, but we'll check it here
// anyway for robustness, e.g. for in-process providers.
newValue := resp . UpgradedState
if errs := newValue . Type ( ) . TestConformance ( currentSchema . ImpliedType ( ) ) ; len ( errs ) > 0 {
for _ , err := range errs {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid resource state upgrade" ,
fmt . Sprintf ( "The %s provider upgraded the state for %s from a previous version, but produced an invalid result: %s." , providerType , addr , tfdiags . FormatError ( err ) ) ,
) )
}
return nil , diags
}
new , err := src . CompleteUpgrade ( newValue , currentSchema . ImpliedType ( ) , uint64 ( currentVersion ) )
if err != nil {
// We already checked for type conformance above, so getting into this
// codepath should be rare and is probably a bug somewhere under CompleteUpgrade.
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to encode result of resource state upgrade" ,
fmt . Sprintf ( "Failed to encode state for %s after resource schema upgrade: %s." , addr , tfdiags . FormatError ( err ) ) ,
) )
}
return new , diags
}
2020-08-06 20:45:57 -05:00
// stripRemovedStateAttributes deletes any attributes no longer present in the
// schema, so that the json can be correctly decoded.
func stripRemovedStateAttributes ( state [ ] byte , ty cty . Type ) [ ] byte {
jsonMap := map [ string ] interface { } { }
err := json . Unmarshal ( state , & jsonMap )
if err != nil {
// we just log any errors here, and let the normal decode process catch
// invalid JSON.
2022-04-11 08:41:22 -05:00
log . Printf ( "[ERROR] UpgradeResourceState: stripRemovedStateAttributes: %s" , err )
2020-08-06 20:45:57 -05:00
return state
}
// if no changes were made, we return the original state to ensure nothing
// was altered in the marshaling process.
if ! removeRemovedAttrs ( jsonMap , ty ) {
return state
}
js , err := json . Marshal ( jsonMap )
if err != nil {
2024-09-09 06:51:39 -05:00
// if the json map was somehow mangled enough to not marshal, something
2020-08-06 20:45:57 -05:00
// went horribly wrong
panic ( err )
}
return js
}
// strip out the actual missing attributes, and return a bool indicating if any
// changes were made.
func removeRemovedAttrs ( v interface { } , ty cty . Type ) bool {
modified := false
// we're only concerned with finding maps that correspond to object
// attributes
switch v := v . ( type ) {
case [ ] interface { } :
switch {
// If these aren't blocks the next call will be a noop
case ty . IsListType ( ) || ty . IsSetType ( ) :
eTy := ty . ElementType ( )
for _ , eV := range v {
modified = removeRemovedAttrs ( eV , eTy ) || modified
}
}
return modified
case map [ string ] interface { } :
switch {
case ty . IsMapType ( ) :
// map blocks aren't yet supported, but handle this just in case
eTy := ty . ElementType ( )
for _ , eV := range v {
modified = removeRemovedAttrs ( eV , eTy ) || modified
}
return modified
case ty == cty . DynamicPseudoType :
log . Printf ( "[DEBUG] UpgradeResourceState: ignoring dynamic block: %#v\n" , v )
return false
case ty . IsObjectType ( ) :
attrTypes := ty . AttributeTypes ( )
for attr , attrV := range v {
attrTy , ok := attrTypes [ attr ]
if ! ok {
log . Printf ( "[DEBUG] UpgradeResourceState: attribute %q no longer present in schema" , attr )
delete ( v , attr )
modified = true
continue
}
modified = removeRemovedAttrs ( attrV , attrTy ) || modified
}
return modified
default :
// This shouldn't happen, and will fail to decode further on, so
// there's no need to handle it here.
log . Printf ( "[WARN] UpgradeResourceState: unexpected type %#v for map in json state" , ty )
return false
}
}
return modified
}