pulumi/pkg/backend/display/diff.go

486 lines
17 KiB
Go
Raw Permalink Normal View History

// Copyright 2016-2018, 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 display
import (
"bytes"
"fmt"
"io"
"math"
"os"
"sort"
"strings"
"time"
"github.com/dustin/go-humanize/english"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag/colors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/slice"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// ShowDiffEvents displays the engine events with the diff view.
func ShowDiffEvents(op string, events <-chan engine.Event, done chan<- bool, opts Options) {
prefix := fmt.Sprintf("%s%s...", cmdutil.EmojiOr("✨ ", "@ "), op)
stdout := opts.Stdout
if stdout == nil {
stdout = os.Stdout
}
stderr := opts.Stderr
if stderr == nil {
stderr = os.Stderr
}
var spinner cmdutil.Spinner
var ticker *time.Ticker
if stdout == os.Stdout && stderr == os.Stderr {
spinner, ticker = cmdutil.NewSpinnerAndTicker(prefix, nil, opts.Color, 8 /*timesPerSecond*/, opts.SuppressProgress)
} else {
spinner = &nopSpinner{}
ticker = time.NewTicker(math.MaxInt64)
}
defer func() {
spinner.Reset()
ticker.Stop()
close(done)
}()
seen := make(map[resource.URN]engine.StepEventMetadata)
for {
select {
case <-ticker.C:
spinner.Tick()
case event := <-events:
spinner.Reset()
out := stdout
if event.Type == engine.DiagEvent {
payload := event.Payload().(engine.DiagEventPayload)
if payload.Severity == diag.Error || payload.Severity == diag.Warning {
out = stderr
}
}
msg := RenderDiffEvent(event, seen, opts)
if msg != "" && out != nil {
fprintIgnoreError(out, msg)
}
if event.Type == engine.CancelEvent {
return
}
}
}
}
func RenderDiffEvent(event engine.Event, seen map[resource.URN]engine.StepEventMetadata, opts Options) string {
switch event.Type {
case engine.CancelEvent:
return ""
case engine.PolicyLoadEvent:
return ""
// Currently, prelude, summary, and stdout events are printed the same for both the diff and
// progress displays.
case engine.PreludeEvent:
return renderPreludeEvent(event.Payload().(engine.PreludeEventPayload), opts)
case engine.SummaryEvent:
const wroteDiagnosticHeader = false
return renderSummaryEvent(event.Payload().(engine.SummaryEventPayload), wroteDiagnosticHeader, true, opts)
case engine.StdoutColorEvent:
return renderStdoutColorEvent(event.Payload().(engine.StdoutEventPayload), opts)
// Resource operations have very specific displays for either diff or progress displays.
// These functions should not be directly used by the progress display without validating
// that the display is appropriate for both.
case engine.ResourceOperationFailed:
return renderDiffResourceOperationFailedEvent(event.Payload().(engine.ResourceOperationFailedPayload), opts)
case engine.ResourceOutputsEvent:
return renderDiffResourceOutputsEvent(event.Payload().(engine.ResourceOutputsEventPayload), seen, opts)
case engine.ResourcePreEvent:
return renderDiffResourcePreEvent(event.Payload().(engine.ResourcePreEventPayload), seen, opts)
case engine.DiagEvent:
return renderDiffDiagEvent(event.Payload().(engine.DiagEventPayload), opts)
case engine.PolicyRemediationEvent:
return renderDiffPolicyRemediationEvent(event.Payload().(engine.PolicyRemediationEventPayload), "", true, opts)
2019-06-10 22:20:44 +00:00
case engine.PolicyViolationEvent:
return renderDiffPolicyViolationEvent(event.Payload().(engine.PolicyViolationEventPayload), "", "", opts)
default:
contract.Failf("unknown event type '%s'", event.Type)
return ""
}
}
func renderDiffDiagEvent(payload engine.DiagEventPayload, opts Options) string {
if payload.Severity == diag.Debug && !opts.Debug {
return ""
}
return opts.Color.Colorize(payload.Prefix + payload.Message)
}
func renderDiffPolicyRemediationEvent(payload engine.PolicyRemediationEventPayload,
prefix string, detailed bool, opts Options,
) string {
// Diff the before/after state. If there is no diff, we show nothing.
diff := payload.Before.Diff(payload.After)
if diff == nil {
return ""
}
// Print the individual remediation's name and target resource type/name.
remediationLine := fmt.Sprintf("%s[remediate] %s%s (%s: %s)",
colors.SpecInfo, payload.PolicyName, colors.Reset, payload.ResourceURN.Type(), payload.ResourceURN.Name())
// If there is already a prefix string requested, use it, otherwise fall back to a default.
if prefix == "" {
remediationLine = fmt.Sprintf(" %s%s@v%s %s%s",
colors.SpecInfo, payload.PolicyPackName, payload.PolicyPackVersion, colors.Reset, remediationLine)
} else {
remediationLine = fmt.Sprintf("%s%s", prefix, remediationLine)
}
// Render the event's diff; if a detailed diff is requested, a full object diff is emitted, otherwise
// a short diff summary similar to what is show for an update row is emitted.
if detailed {
var b bytes.Buffer
PrintObjectDiff(&b, *diff, nil,
false /*planning*/, 2, true /*summary*/, true /*truncateOutput*/, false /*debug*/)
remediationLine = fmt.Sprintf("%s\n%s", remediationLine, b.String())
} else {
var b bytes.Buffer
writeShortDiff(&b, diff, nil)
remediationLine = fmt.Sprintf("%s [%s]", remediationLine, b.String())
}
return opts.Color.Colorize(remediationLine + "\n")
}
func renderDiffPolicyViolationEvent(payload engine.PolicyViolationEventPayload,
prefix string, linePrefix string, opts Options,
) string {
// Colorize mandatory and warning violations differently.
c := colors.SpecWarning
if payload.EnforcementLevel == apitype.Mandatory {
c = colors.SpecError
}
// Print the individual policy's name and target resource type/name.
policyLine := fmt.Sprintf("%s[%s] %s%s (%s: %s)",
c, payload.EnforcementLevel, payload.PolicyName, colors.Reset,
payload.ResourceURN.Type(), payload.ResourceURN.Name())
// If there is already a prefix string requested, use it, otherwise fall back to a default.
if prefix == "" {
policyLine = fmt.Sprintf(" %s%s@v%s %s%s",
colors.SpecInfo, payload.PolicyPackName, payload.PolicyPackVersion, colors.Reset, policyLine)
} else {
policyLine = fmt.Sprintf("%s%s", prefix, policyLine)
}
// If there is a line prefix, separate the heading and lines with a newline.
if linePrefix != "" {
policyLine += "\n"
}
// The message may span multiple lines, so we massage it so it will be indented properly.
message := strings.TrimSuffix(payload.Message, "\n")
Enable perfsprint linter (#14813) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Prompted by a comment in another review: https://github.com/pulumi/pulumi/pull/14654#discussion_r1419995945 This lints that we don't use `fmt.Errorf` when `errors.New` will suffice, it also covers a load of other cases where `Sprintf` is sub-optimal. Most of these edits were made by running `perfsprint --fix`. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [x] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-12-12 12:19:42 +00:00
message = strings.ReplaceAll(message, "\n", "\n"+linePrefix)
policyLine = fmt.Sprintf("%s%s%s", policyLine, linePrefix, message)
return opts.Color.Colorize(policyLine + "\n")
2019-06-10 22:20:44 +00:00
}
func renderStdoutColorEvent(payload engine.StdoutEventPayload, opts Options) string {
return opts.Color.Colorize(payload.Message)
}
func renderSummaryEvent(event engine.SummaryEventPayload, hasError bool, diffStyleSummary bool, opts Options) string {
changes := event.ResourceChanges
// If this is a failed preview, do not render anything. It could be surprising/misleading as it doesn't
// describe the totality of the proposed changes (for instance, could be missing resources if it errored early).
if event.IsPreview && hasError {
return ""
}
out := &bytes.Buffer{}
fprintIgnoreError(out, opts.Color.Colorize(
fmt.Sprintf("%sResources:%s\n", colors.SpecHeadline, colors.Reset)))
var planTo string
if event.IsPreview {
planTo = "to "
}
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
changeKindCount := 0
changeCount := 0
sameCount := changes[deploy.OpSame]
// Now summarize all of the changes; we print sames a little differently.
for _, op := range deploy.StepOps {
// Ignore anything that didn't change, or is related to 'reads'. 'reads' are just an
// indication of the operations we were performing, and are not indicative of any sort of
// change to the system.
if op != deploy.OpSame &&
op != deploy.OpRead &&
op != deploy.OpReadDiscard &&
op != deploy.OpReadReplacement {
if c := changes[op]; c > 0 {
opDescription := string(op)
if !event.IsPreview {
opDescription = deploy.PastTense(op)
}
// Increment the change count by the number of changes associated with this step kind
changeCount += c
// Increment the number of kinds of changes by one
changeKindCount++
// Print a summary of the changes of this kind
fprintIgnoreError(out, opts.Color.Colorize(
fmt.Sprintf(" %s%d %s%s%s\n", deploy.Prefix(op, true /*done*/), c, planTo, opDescription, colors.Reset)))
}
}
}
summaryPieces := []string{}
if changeKindCount >= 2 {
// Only if we made multiple types of changes do we need to print out the total number of
// changes. i.e. we don't need "10 changes" and "+ 10 to create". We can just say "+ 10 to create"
summaryPieces = append(summaryPieces, fmt.Sprintf("%s%d %s%s",
colors.Bold, changeCount, english.PluralWord(changeCount, "change", ""), colors.Reset))
}
if sameCount != 0 {
summaryPieces = append(summaryPieces, fmt.Sprintf("%d unchanged", sameCount))
}
if len(summaryPieces) > 0 {
fprintIgnoreError(out, " ")
for i, piece := range summaryPieces {
if i > 0 {
fprintIgnoreError(out, ". ")
}
out.WriteString(opts.Color.Colorize(piece))
}
fprintIgnoreError(out, "\n")
}
if diffStyleSummary {
// Print policy packs loaded. Data is rendered as a table of {policy-pack-name, version}.
// This is only shown during the diff view, because in the progress view we have a nicer
// summarization and grouping of all violations and remediations that have occurred. The
// diff view renders events incrementally as we go, so it cannot do this.
renderPolicyPacks(out, event.PolicyPacks, opts)
}
// For actual deploys, we print some additional summary information
if !event.IsPreview {
// Round up to the nearest second. It's not useful to spit out time with 9 digits of
// precision.
roundedSeconds := int64(math.Ceil(event.Duration.Seconds()))
roundedDuration := time.Duration(roundedSeconds) * time.Second
fprintIgnoreError(out, opts.Color.Colorize(fmt.Sprintf("\n%sDuration:%s %s\n",
colors.SpecHeadline, colors.Reset, roundedDuration)))
}
return out.String()
}
func renderPolicyPacks(out io.Writer, policyPacks map[string]string, opts Options) {
if len(policyPacks) == 0 {
return
}
fprintIgnoreError(out, opts.Color.Colorize(fmt.Sprintf("\n%sPolicy Packs run:%s\n",
colors.SpecHeadline, colors.Reset)))
// Calculate column width for the `name` column
const nameColHeader = "Name"
maxNameLen := len(nameColHeader)
for pp := range policyPacks {
if l := len(pp); l > maxNameLen {
maxNameLen = l
}
}
// Print the column headers and the policy packs.
fprintIgnoreError(out, opts.Color.Colorize(
fmt.Sprintf(" %s%s%s\n",
columnHeader(nameColHeader), messagePadding(nameColHeader, maxNameLen, 2),
columnHeader("Version"))))
for pp, ver := range policyPacks {
fprintIgnoreError(out, opts.Color.Colorize(
fmt.Sprintf(" %s%s%s\n", pp, messagePadding(pp, maxNameLen, 2), ver)))
}
}
func renderPreludeEvent(event engine.PreludeEventPayload, opts Options) string {
// Only if we have been instructed to show configuration values will we print anything during the prelude.
if !opts.ShowConfig {
return ""
}
out := &bytes.Buffer{}
fprintIgnoreError(out, opts.Color.Colorize(
fmt.Sprintf("%sConfiguration:%s\n", colors.SpecUnimportant, colors.Reset)))
keys := slice.Prealloc[string](len(event.Config))
for key := range event.Config {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fprintfIgnoreError(out, " %v: %v\n", key, event.Config[key])
}
return out.String()
}
func renderDiffResourceOperationFailedEvent(
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
payload engine.ResourceOperationFailedPayload, opts Options,
) string {
// It's not actually useful or interesting to print out any details about
// the resource state here, because we always assume that the resource state
// is unknown if an error occurs.
//
// In the future, once we get more fine-grained error messages from providers,
// we can provide useful diagnostics here.
return ""
}
func renderDiff(
out io.Writer,
metadata engine.StepEventMetadata,
Change `pulumi refresh` to report diff relative to desired state instead of relative to only output changes (#16146) Presently, the behaviour of diffing during refresh steps is incomplete, returning only an "output diff" that presents the changes in outputs. This commit changes refresh steps so that: * they compute a diff similar to the one that would be computed if a `preview` were run immediately after the refresh, which is more typically what users expect and want; and * `IgnoreChanges` resource options are respected when performing the new desired-state diffs, so that property additions or changes reported by a refresh can be ignored. In particular, `IgnoreChanges` can now be used to acknowledge that part or all of a resource may change in the provider, but the user is OK with this and doesn't want to be notified about it during a refresh. Importantly, this means that the diff won't be reported, but also that the changes won't be applied to state. The implementation covers the following: * A diff is computed using the inputs from the program and then inverting the result, since in the case of a refresh the diff is being driven by the provider side and not the program. This doesn't change what is stored back into the state, but it does produce a diff that is more aligned with the "true changes to the desired state". * `IgnoreChanges` resource options are now stored in state, so that this information can be used in refresh operations that do not have access to/run the program. * In the context of a refresh operation, `IgnoreChanges` applies to *both* input and output properties. This differs from the behaviour of a normal update operation, where `IgnoreChanges` only considers input properties. * The special `"*"` value for `IgnoreChanges` can be used to ignore all properties. It _also_ ignores the case where the resource cannot be found in the provider, and instead keeps the resource intact in state with its existing input and output properties. Because the program is not run for refresh operations, `IgnoreChanges` options must be applied separately before a refresh takes place. This can be accomplished using e.g. a `pulumi up` that applies the options prior to a refresh. We should investigate perhaps providing a `pulumi state set ...`-like CLI to make these sorts of changes directly to a state. For use cases relying on the legacy refresh diff provider, the `PULUMI_USE_LEGACY_REFRESH_DIFF` environment variable can be set, which will disable desired-state diff computation. We only need to perform checks in `RefreshStep.{ResultOp,Apply}`, since downstream code will work correctly based on the presence or absence of a `DetailedDiff` in the step. ### Notes - https://github.com/pulumi/pulumi/issues/16144 affects some of these cases - though its technically orthogonal - https://github.com/pulumi/pulumi/issues/11279 is another technically orthogonal issue that many providers (at least TFBridge ones) - do not report back changes to input properties on Read when the input property (or property path) was missing on the inputs. This is again technically orthogonal - but leads to cases that appear "wrong" in terms of what is stored back into the state still - though the same as before this change. - Azure Native doesn't seem to handle `ignoreChanges` passed to Diff, so the ability to ignore changes on refresh doesn't currently work for Azure Native. ### Fixes * Fixes #16072 * Fixes #16278 * Fixes #16334 * Not quite #12346, but likely replaces the need for that Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-12 16:17:05 +00:00
planning, debug, refresh bool,
seen map[resource.URN]engine.StepEventMetadata,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
opts Options,
) {
indent := getIndent(metadata, seen)
summary := getResourcePropertiesSummary(metadata, indent)
var details string
Never show property diffs for OpSame (#16024) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Fixes https://github.com/pulumi/pulumi/issues/15944. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. --> --------- Co-authored-by: Thomas Gummerer <t.gummerer@gmail.com>
2024-05-02 12:28:43 +00:00
// An OpSame might have a diff due to metadata changes (e.g. protect) but we should never print a property diff,
// even if the properties appear to have changed. See https://github.com/pulumi/pulumi/issues/15944 for context.
if metadata.Op != deploy.OpSame {
if metadata.DetailedDiff != nil {
var buf bytes.Buffer
Change `pulumi refresh` to report diff relative to desired state instead of relative to only output changes (#16146) Presently, the behaviour of diffing during refresh steps is incomplete, returning only an "output diff" that presents the changes in outputs. This commit changes refresh steps so that: * they compute a diff similar to the one that would be computed if a `preview` were run immediately after the refresh, which is more typically what users expect and want; and * `IgnoreChanges` resource options are respected when performing the new desired-state diffs, so that property additions or changes reported by a refresh can be ignored. In particular, `IgnoreChanges` can now be used to acknowledge that part or all of a resource may change in the provider, but the user is OK with this and doesn't want to be notified about it during a refresh. Importantly, this means that the diff won't be reported, but also that the changes won't be applied to state. The implementation covers the following: * A diff is computed using the inputs from the program and then inverting the result, since in the case of a refresh the diff is being driven by the provider side and not the program. This doesn't change what is stored back into the state, but it does produce a diff that is more aligned with the "true changes to the desired state". * `IgnoreChanges` resource options are now stored in state, so that this information can be used in refresh operations that do not have access to/run the program. * In the context of a refresh operation, `IgnoreChanges` applies to *both* input and output properties. This differs from the behaviour of a normal update operation, where `IgnoreChanges` only considers input properties. * The special `"*"` value for `IgnoreChanges` can be used to ignore all properties. It _also_ ignores the case where the resource cannot be found in the provider, and instead keeps the resource intact in state with its existing input and output properties. Because the program is not run for refresh operations, `IgnoreChanges` options must be applied separately before a refresh takes place. This can be accomplished using e.g. a `pulumi up` that applies the options prior to a refresh. We should investigate perhaps providing a `pulumi state set ...`-like CLI to make these sorts of changes directly to a state. For use cases relying on the legacy refresh diff provider, the `PULUMI_USE_LEGACY_REFRESH_DIFF` environment variable can be set, which will disable desired-state diff computation. We only need to perform checks in `RefreshStep.{ResultOp,Apply}`, since downstream code will work correctly based on the presence or absence of a `DetailedDiff` in the step. ### Notes - https://github.com/pulumi/pulumi/issues/16144 affects some of these cases - though its technically orthogonal - https://github.com/pulumi/pulumi/issues/11279 is another technically orthogonal issue that many providers (at least TFBridge ones) - do not report back changes to input properties on Read when the input property (or property path) was missing on the inputs. This is again technically orthogonal - but leads to cases that appear "wrong" in terms of what is stored back into the state still - though the same as before this change. - Azure Native doesn't seem to handle `ignoreChanges` passed to Diff, so the ability to ignore changes on refresh doesn't currently work for Azure Native. ### Fixes * Fixes #16072 * Fixes #16278 * Fixes #16334 * Not quite #12346, but likely replaces the need for that Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-12 16:17:05 +00:00
if diff := engine.TranslateDetailedDiff(&metadata, refresh); diff != nil {
Never show property diffs for OpSame (#16024) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Fixes https://github.com/pulumi/pulumi/issues/15944. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. --> --------- Co-authored-by: Thomas Gummerer <t.gummerer@gmail.com>
2024-05-02 12:28:43 +00:00
PrintObjectDiff(&buf, *diff, nil /*include*/, planning, indent+1, opts.SummaryDiff, opts.TruncateOutput, debug)
} else {
PrintObject(
&buf, metadata.Old.Inputs, planning, indent+1, deploy.OpSame, true /*prefix*/, opts.TruncateOutput, debug)
}
details = buf.String()
} else {
Never show property diffs for OpSame (#16024) <!--- Thanks so much for your contribution! If this is your first time contributing, please ensure that you have read the [CONTRIBUTING](https://github.com/pulumi/pulumi/blob/master/CONTRIBUTING.md) documentation. --> # Description <!--- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. --> Fixes https://github.com/pulumi/pulumi/issues/15944. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. --> --------- Co-authored-by: Thomas Gummerer <t.gummerer@gmail.com>
2024-05-02 12:28:43 +00:00
details = getResourcePropertiesDetails(
metadata, indent, planning, opts.SummaryDiff, opts.TruncateOutput, debug)
}
}
fprintIgnoreError(out, opts.Color.Colorize(summary))
fprintIgnoreError(out, opts.Color.Colorize(details))
fprintIgnoreError(out, opts.Color.Colorize(colors.Reset))
}
func renderDiffResourcePreEvent(
payload engine.ResourcePreEventPayload,
seen map[resource.URN]engine.StepEventMetadata,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
opts Options,
) string {
seen[payload.Metadata.URN] = payload.Metadata
if payload.Metadata.Op == deploy.OpRefresh || payload.Metadata.Op == deploy.OpImport {
return ""
}
out := &bytes.Buffer{}
if shouldShow(payload.Metadata, opts) || isRootStack(payload.Metadata) {
Change `pulumi refresh` to report diff relative to desired state instead of relative to only output changes (#16146) Presently, the behaviour of diffing during refresh steps is incomplete, returning only an "output diff" that presents the changes in outputs. This commit changes refresh steps so that: * they compute a diff similar to the one that would be computed if a `preview` were run immediately after the refresh, which is more typically what users expect and want; and * `IgnoreChanges` resource options are respected when performing the new desired-state diffs, so that property additions or changes reported by a refresh can be ignored. In particular, `IgnoreChanges` can now be used to acknowledge that part or all of a resource may change in the provider, but the user is OK with this and doesn't want to be notified about it during a refresh. Importantly, this means that the diff won't be reported, but also that the changes won't be applied to state. The implementation covers the following: * A diff is computed using the inputs from the program and then inverting the result, since in the case of a refresh the diff is being driven by the provider side and not the program. This doesn't change what is stored back into the state, but it does produce a diff that is more aligned with the "true changes to the desired state". * `IgnoreChanges` resource options are now stored in state, so that this information can be used in refresh operations that do not have access to/run the program. * In the context of a refresh operation, `IgnoreChanges` applies to *both* input and output properties. This differs from the behaviour of a normal update operation, where `IgnoreChanges` only considers input properties. * The special `"*"` value for `IgnoreChanges` can be used to ignore all properties. It _also_ ignores the case where the resource cannot be found in the provider, and instead keeps the resource intact in state with its existing input and output properties. Because the program is not run for refresh operations, `IgnoreChanges` options must be applied separately before a refresh takes place. This can be accomplished using e.g. a `pulumi up` that applies the options prior to a refresh. We should investigate perhaps providing a `pulumi state set ...`-like CLI to make these sorts of changes directly to a state. For use cases relying on the legacy refresh diff provider, the `PULUMI_USE_LEGACY_REFRESH_DIFF` environment variable can be set, which will disable desired-state diff computation. We only need to perform checks in `RefreshStep.{ResultOp,Apply}`, since downstream code will work correctly based on the presence or absence of a `DetailedDiff` in the step. ### Notes - https://github.com/pulumi/pulumi/issues/16144 affects some of these cases - though its technically orthogonal - https://github.com/pulumi/pulumi/issues/11279 is another technically orthogonal issue that many providers (at least TFBridge ones) - do not report back changes to input properties on Read when the input property (or property path) was missing on the inputs. This is again technically orthogonal - but leads to cases that appear "wrong" in terms of what is stored back into the state still - though the same as before this change. - Azure Native doesn't seem to handle `ignoreChanges` passed to Diff, so the ability to ignore changes on refresh doesn't currently work for Azure Native. ### Fixes * Fixes #16072 * Fixes #16278 * Fixes #16334 * Not quite #12346, but likely replaces the need for that Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-12 16:17:05 +00:00
renderDiff(out, payload.Metadata, payload.Planning, payload.Debug, false /* refresh */, seen, opts)
}
return out.String()
}
func renderDiffResourceOutputsEvent(
payload engine.ResourceOutputsEventPayload,
seen map[resource.URN]engine.StepEventMetadata,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
opts Options,
) string {
out := &bytes.Buffer{}
if shouldShow(payload.Metadata, opts) || isRootStack(payload.Metadata) {
Change `pulumi refresh` to report diff relative to desired state instead of relative to only output changes (#16146) Presently, the behaviour of diffing during refresh steps is incomplete, returning only an "output diff" that presents the changes in outputs. This commit changes refresh steps so that: * they compute a diff similar to the one that would be computed if a `preview` were run immediately after the refresh, which is more typically what users expect and want; and * `IgnoreChanges` resource options are respected when performing the new desired-state diffs, so that property additions or changes reported by a refresh can be ignored. In particular, `IgnoreChanges` can now be used to acknowledge that part or all of a resource may change in the provider, but the user is OK with this and doesn't want to be notified about it during a refresh. Importantly, this means that the diff won't be reported, but also that the changes won't be applied to state. The implementation covers the following: * A diff is computed using the inputs from the program and then inverting the result, since in the case of a refresh the diff is being driven by the provider side and not the program. This doesn't change what is stored back into the state, but it does produce a diff that is more aligned with the "true changes to the desired state". * `IgnoreChanges` resource options are now stored in state, so that this information can be used in refresh operations that do not have access to/run the program. * In the context of a refresh operation, `IgnoreChanges` applies to *both* input and output properties. This differs from the behaviour of a normal update operation, where `IgnoreChanges` only considers input properties. * The special `"*"` value for `IgnoreChanges` can be used to ignore all properties. It _also_ ignores the case where the resource cannot be found in the provider, and instead keeps the resource intact in state with its existing input and output properties. Because the program is not run for refresh operations, `IgnoreChanges` options must be applied separately before a refresh takes place. This can be accomplished using e.g. a `pulumi up` that applies the options prior to a refresh. We should investigate perhaps providing a `pulumi state set ...`-like CLI to make these sorts of changes directly to a state. For use cases relying on the legacy refresh diff provider, the `PULUMI_USE_LEGACY_REFRESH_DIFF` environment variable can be set, which will disable desired-state diff computation. We only need to perform checks in `RefreshStep.{ResultOp,Apply}`, since downstream code will work correctly based on the presence or absence of a `DetailedDiff` in the step. ### Notes - https://github.com/pulumi/pulumi/issues/16144 affects some of these cases - though its technically orthogonal - https://github.com/pulumi/pulumi/issues/11279 is another technically orthogonal issue that many providers (at least TFBridge ones) - do not report back changes to input properties on Read when the input property (or property path) was missing on the inputs. This is again technically orthogonal - but leads to cases that appear "wrong" in terms of what is stored back into the state still - though the same as before this change. - Azure Native doesn't seem to handle `ignoreChanges` passed to Diff, so the ability to ignore changes on refresh doesn't currently work for Azure Native. ### Fixes * Fixes #16072 * Fixes #16278 * Fixes #16334 * Not quite #12346, but likely replaces the need for that Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-12 16:17:05 +00:00
refresh := false // are these outputs from a refresh?
if m, has := seen[payload.Metadata.URN]; has && m.Op == deploy.OpRefresh {
refresh = true
}
// There are two cases where we want to display a diff at the point of a
// resource output event:
//
// * Imports, where we now have information from the provider about the
// resource being imported.
// * Refreshes, where similarly we might have updated information about the
// resource from the provider.
//
// Note that refresh step result operations will be OpUpdates (something
// changed in the provider), OpSames (nothing changed in the provider), or
// OpDeletes (the resource was deleted in the provider). We only want to
// display a diff in the OpUpdate case. In the OpSame case, there is no diff
// (otherwise the operation would have been OpUpdate), and in the OpDelete
// case, we will already be indicating a deletion and it doesn't make sense
// to display a diff that shows that we are deleting everything.
if payload.Metadata.Op == deploy.OpImport || (refresh && payload.Metadata.Op == deploy.OpUpdate) {
renderDiff(out, payload.Metadata, payload.Planning, payload.Debug, refresh, seen, opts)
return out.String()
}
indent := getIndent(payload.Metadata, seen)
Change `pulumi refresh` to report diff relative to desired state instead of relative to only output changes (#16146) Presently, the behaviour of diffing during refresh steps is incomplete, returning only an "output diff" that presents the changes in outputs. This commit changes refresh steps so that: * they compute a diff similar to the one that would be computed if a `preview` were run immediately after the refresh, which is more typically what users expect and want; and * `IgnoreChanges` resource options are respected when performing the new desired-state diffs, so that property additions or changes reported by a refresh can be ignored. In particular, `IgnoreChanges` can now be used to acknowledge that part or all of a resource may change in the provider, but the user is OK with this and doesn't want to be notified about it during a refresh. Importantly, this means that the diff won't be reported, but also that the changes won't be applied to state. The implementation covers the following: * A diff is computed using the inputs from the program and then inverting the result, since in the case of a refresh the diff is being driven by the provider side and not the program. This doesn't change what is stored back into the state, but it does produce a diff that is more aligned with the "true changes to the desired state". * `IgnoreChanges` resource options are now stored in state, so that this information can be used in refresh operations that do not have access to/run the program. * In the context of a refresh operation, `IgnoreChanges` applies to *both* input and output properties. This differs from the behaviour of a normal update operation, where `IgnoreChanges` only considers input properties. * The special `"*"` value for `IgnoreChanges` can be used to ignore all properties. It _also_ ignores the case where the resource cannot be found in the provider, and instead keeps the resource intact in state with its existing input and output properties. Because the program is not run for refresh operations, `IgnoreChanges` options must be applied separately before a refresh takes place. This can be accomplished using e.g. a `pulumi up` that applies the options prior to a refresh. We should investigate perhaps providing a `pulumi state set ...`-like CLI to make these sorts of changes directly to a state. For use cases relying on the legacy refresh diff provider, the `PULUMI_USE_LEGACY_REFRESH_DIFF` environment variable can be set, which will disable desired-state diff computation. We only need to perform checks in `RefreshStep.{ResultOp,Apply}`, since downstream code will work correctly based on the presence or absence of a `DetailedDiff` in the step. ### Notes - https://github.com/pulumi/pulumi/issues/16144 affects some of these cases - though its technically orthogonal - https://github.com/pulumi/pulumi/issues/11279 is another technically orthogonal issue that many providers (at least TFBridge ones) - do not report back changes to input properties on Read when the input property (or property path) was missing on the inputs. This is again technically orthogonal - but leads to cases that appear "wrong" in terms of what is stored back into the state still - though the same as before this change. - Azure Native doesn't seem to handle `ignoreChanges` passed to Diff, so the ability to ignore changes on refresh doesn't currently work for Azure Native. ### Fixes * Fixes #16072 * Fixes #16278 * Fixes #16334 * Not quite #12346, but likely replaces the need for that Co-authored-by: Will Jones <will@sacharissa.co.uk>
2024-06-12 16:17:05 +00:00
if refresh {
// We would not have rendered the summary yet in this case, so do it now.
summary := getResourcePropertiesSummary(payload.Metadata, indent)
fprintIgnoreError(out, opts.Color.Colorize(summary))
}
if !opts.SuppressOutputs {
// We want to hide same outputs if we're doing a read and the user didn't ask to see
// things that are the same.
text := getResourceOutputsPropertiesString(
payload.Metadata, indent+1, payload.Planning,
payload.Debug, refresh, opts.ShowSameResources)
if text != "" {
header := fmt.Sprintf("%v%v--outputs:--%v\n",
deploy.Color(payload.Metadata.Op), getIndentationString(indent+1, payload.Metadata.Op, false), colors.Reset)
fprintIgnoreError(out, opts.Color.Colorize(header))
fprintIgnoreError(out, opts.Color.Colorize(text))
}
}
}
return out.String()
}