# Description
There are a number of parts of the deployment process that require
context about and configuration for the operation being executed. For
instance:
* Source evaluation -- evaluating programs in order to emit resource
registrations
* Step generation -- processing resource registrations in order to
generate steps (create this, update that, delete the other, etc.)
* Step execution -- executing steps in order to action a deployment.
Presently, these pieces all take some form of `Options` struct or pass
explicit arguments. This is problematic for a couple of reasons:
* It could be possible for different parts of the codebase to end up
operating in different contexts/with different configurations, whether
due to different values being passed explicitly or due to missed
copying/instantiation.
* Some parts need less context/configuration than others, but still
accept full `Options`, making it hard to discern what information is
actually necessary in any given part of the process.
This commit attempts to clean things up by moving deployment options
directly into the `Deployment` itself. Since step generation and
execution already refer to a `Deployment`, they get a consistent view of
the options for free. For source evaluation, we introduce an
`EvalSourceOptions` struct for configuring just the options necessary
there. At the top level, the engine configures a single set of options
to flow through the deployment steps later on.
As part of this work, a few other things have been changed:
* Preview/dry-run parameters have been incorporated into options. This
lets up lop off another argument and mitigate a bit of "boolean
blindness". We don't appear to flip this flag within a deployment
process (indeed, all options seem to be immutable) and so having it as a
separate flag doesn't seem to buy us anything.
* Several methods representing parts of the deployment process have lost
arguments in favour of state that is already being carried on (or can be
carried on) their receiver. For instance, `deployment.run` no longer
takes actions or preview configuration. While doing so means that a
`deployment` could be run multiple times with different actions/preview
arguments, we don't currently exploit this fact anywhere, so moving this
state to the point of construction both simplifies things considerably
and reduces the possibility for error (e.g. passing different values of
`preview` when instantiating a `deployment` and subsequently calling
`run`).
* Event handlers have been split out of the options object and attached
to `Deployment` separately. This means we can talk about options at a
higher level without having to `nil` out/worry about this field and
mutate it correctly later on.
* Options are no longer mutated during deployment. Presently there
appears to be only one case of this -- when handling `ContinueOnError`
in the presence of `IgnoreChanges` (e.g. when performing a refresh).
This case has been refactored so that the mutation is no longer
necessary.
# Notes
* This change is in preparation for #16146, where we'd like to add an
environment variable to control behaviour and having a single unified
`Options` struct would make it easier to pass this configuration down
with introducing (more) global state into deployments. Indeed, this
change should make it easier to factor global state into `Options` so
that it can be controlled and tested more easily/is less susceptible to
bugs, race conditions, etc.
* I've tweaked/extended some comments while I'm here and have learned
things the hard way (e.g. `Refresh` vs `isRefresh`). Feedback welcome on
this if we'd rather not conflate.
* This change does mean that if in future we wanted e.g. to be able to
run a `Deployment` in multiple different ways with multiple sets of
actions, we'd have to refactor. Pushing state to the point of object
construction reduces the flexibility of the code. However, since we are
not presently using that flexibility (nor is there an obvious [to my
mind] use case in the near future), this seems like a good trade-off to
guard against bugs/make it simpler to move that state around.
* I've left some other review comments in the code around
questions/changes that might be a bad idea; happy to receive feedback on
it all though!
<!---
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. -->
Small refactor I noticed while writing a test with engine events. We
always had to call `NewEvent` with the tag and payload value for an
event and these _had_ to match up else the engine panics. But we can
just pass the payload and type switch to work out the tag. Means one
less parameter to pass to `NewEvent` and pretty much no chance of it
going wrong. To ensure there's really no chance I've added a generic
union type so you can only pass payload types to this method now.
Cancel had to be handled separately because it doesn't have a payload
type, it's just nil.
A big change for result.Result cleanup. This removes all references to
the Result type from pkg/engine. This was mostly just search replace.
Points to note, we still map to `result.Result` in pkg/backend (that
will be the next big result change to deal with), and a little bit of
fiddlyness with multiple error values in test_plan.go `runWithContext`.
This PR implements the new policy transforms feature, which allows
policy packs to not only issue warnings and errors in response to policy
violations, but actually fix them by rewriting resource property state.
This can be used, for instance, to auto-tag resources, remove Internet
access on the fly, or apply encryption to storage, among other use
cases.
<!---
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
Fixes#14054
This PR fixes a problem that the engine cannot forward a cancellation
signal to the provider, because the plugin context is already closed. An
[earlier
commit](a9ae602867)
made the plugin context be closed too eagerly, with the intent of
cancelling plugin installation. This PR attempts to decouple the
cancellation of plugin installation from the lifecycle of the plugin
context, so that plugin installation may be cancelled during the
cancelation phase as opposed to the termination phase. Then, it closes
the plugin context in termination phase.
There's an existing test case in the engine lifecycle tests called
`TestProviderCancellation`, but it didn't catch the problem because it
uses a fake plugin host that behaves differently after being closed. The
issue was fixed in https://github.com/pulumi/pulumi/pull/14063 and the
test was temporarily disabled. This PR re-enables the test case.
A new test case `TestSourceFuncCancellation` is added to test
cancellation of the source func (where plugin installation happens, see
[update.go](https://github.com/pulumi/pulumi/pull/14057/files#diff-7d2ca3e83a05073b332435271496050e28466b4f7af8c0c91bbc77947a75a3a2R378)),
as this was the original motivation of
a9ae602867.
## 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. -->
- [x] I have added tests that prove my fix is effective or that my
feature works
<!---
User-facing changes require a CHANGELOG entry.
-->
- [x] 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. -->
Similar to how https://github.com/pulumi/pulumi/pull/13953 moves some
code from sdk/go/common to /pkg. This display code is only used in /pkg,
another simple reduction of what's in sdk/go/common.
By default Pulumi will load ambient plugins from $PATH before looking in
the plugins directory or at bundled plugins.
While this is very useful for development it often causes confusion when
people have forgotten that they have plugins left on $PATH.
This makes the use of these $PATH plugins a diagnostic warning to try
and make that failure mode a little less silent.
Normal users shouldn't ever have plugins on $PATH and so won't see this
new warning.
Re-instates https://github.com/pulumi/pulumi/pull/13607 with a fix for
symlinks included.
By default Pulumi will load ambient plugins from $PATH before looking in
the plugins directory or at bundled plugins.
While this is very useful for development it often causes confusion when
people have forgotten that they have plugins left on $PATH.
This makes the use of these $PATH plugins a diagnostic warning to try
and make that failure mode a little less silent.
Normal users shouldn't ever have plugins on $PATH and so won't see this
new warning.
These changes add support for passing source position information in
gRPC metadata and recording the source position that corresponds to a
resource registration in the statefile.
Enabling source position information in the resource model can provide
substantial benefits, including but not limited to:
- Better errors from the Pulumi CLI
- Go-to-defintion for resources in state
- Editor integration for errors, etc. from `pulumi preview`
Source positions are (file, line) or (file, line, column) tuples
represented as URIs. The line and column are stored in the fragment
portion of the URI as "line(,column)?". The scheme of the URI and the
form of its path component depends on the context in which it is
generated or used:
- During an active update, the URI's scheme is `file` and paths are
absolute filesystem paths. This allows consumers to easily access
arbitrary files that are available on the host.
- In a statefile, the URI's scheme is `project` and paths are relative
to the project root. This allows consumers to resolve source positions
relative to the project file in different contexts irrespective of the
location of the project itself (e.g. given a project-relative path and
the URL of the project's root on GitHub, one can build a GitHub URL for
the source position).
During an update, source position information may be attached to gRPC
calls as "source-position" metadata. This allows arbitrary calls to be
associated with source positions without changes to their protobuf
payloads. Modifying the protobuf payloads is also a viable approach, but
is somewhat more invasive than attaching metadata, and requires changes
to every call signature.
Source positions should reflect the position in user code that initiated
a resource model operation (e.g. the source position passed with
`RegisterResource` for `pet` in the example above should be the source
position in `index.ts`, _not_ the source position in the Pulumi SDK). In
general, the Pulumi SDK should be able to infer the source position of
the resource registration, as the relationship between a resource
registration and its corresponding user code should be static per SDK.
Source positions in state files will be stored as a new `registeredAt`
property on each resource. This property is optional.
Consolidated `Target` parameters to a single variable. The deployment
executor is not well aware of the overall update that is going on and
runs individual resource operations. The consolidation minimizes
leakage.
Moved `--target` validation for `destroy` and `refresh` into `pkg/engine`.
Fixed#6422 where `checkTargets()` would check the `prev` Snapshot for
resources after `rebuildBaseState()` was called. This would mutate prev
by removing resources from the snapshot. This caused deleted resources
on targeted updates not to be found and be reported as an error due to
having an unknown target.
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.
Incremental step towards #12132
Migrates uses of contract.{Assert, AssertNoError, Require} in pkg/engine
to `*f` variants so that we're required to provide more error context.
Refs #12132
* demo
* modifications for serialization
* Provisionally changed plugins from map to array
* warnings for duplicate
* avoid breaking change
* avoid null pointer dereference
* added test
* Delete Pulumi.yaml
* ensurePluginsAreInstalled
* lint
* reworked NewContext and added kind
* auto-detect current project for YAML
* lint
* removed debug statement
* automatically modify local paths
* typo
* First return value of GetPluginPath was never used
* Always use the path returned from getPluginInfoAndPath in GetPluginPath
Also assert that Path is the correct directory for PluginInfo.
* address comments
* added language, analyzers
* path tweaks and cosmetic changes
* changelog + tweaks
* changed NewContextWithRoot to accept plugins instead of project
* Fix TestUnmarshalProjectWithProviderList
* Fix NewContext
* Fix comment
Co-authored-by: Fraser Waters <fraser@pulumi.com>
* Moving previewDigest and exporting it, closes#9851
* Moving previewDigest and exporting it, closes#9851
* Updating changelog-pending
* Go Mod Tidy
* replacing to local
* more go.mod changes
* reseting go mod
* full move
* Fixing golint
* No go.mod changes needed
The Problem
Explicit providers that don't specify version/pluginDownloadURL are created using a potentially different plugin than the default provider.
We can have multiple versions of providers in the same go program at the same time. This means that we can also have multiple plugins loaded for providers with the same name. Due to limitations of Go, we are not able to determine which SDK version of a provider made an individual register resource request. Because requests don't specify versions, we get the above behavior trying to guess.
Pre-PR behavior
For (non-provider) resources without an explicit provider set, we use the default provider which takes its plugin from SDK provided by go.mod (or language equivalent). For explicit providers without version we take the locally installed plugin with the highest version.
Post-PR behavior
For (non-provider) resources without an explicit provider set, we use the default provider which takes its plugin from SDK provided by go.mod (or language equivalent). For explicit providers without version/pluginDownloadURL we check if there is a default provider for that package. If there is, we use that version/pluginDownloadURL. If no default exists, we still use the highest installed version.
* Respond to SIGINT
With the current state of the PR, crash on SIGINT. This is progress.
* Don't crash responding to SIGINT
* Close on cancel instead of terminate
* CL
* Fix lint
* Add ctx for node
* Be consistent for test context
* Implement resource plans in the engine
* Plumb plans through the CLI.
* Update wording
* plan renderer
* constraints
* Renames
* Update message
* fixes for rebase breaks and diffs
* WIP: outputs in plans
* fix diff
* fixup
* Liniting and test fixing
* Test and fix PropertyPath.String()
* Fix colors
* Fix cmdutil.PrintTable to handle non-simple strings
* More tests
* Readd test_plan.go
* lint
* Test expected deletes
* Test expected delete
* Test missing create
* Fix test for missing creates
* rm Paths()
* property set shrink test
* notes
* More tests
* Pop op before constraint check
* Delete plan cmd, rename arguments to preview and up
* Hide behind envvars
* typo
* Better constraint diffs
* Adds/Deletes/Updates
* Fix aliased
* Check more constraints
* fix test
* revert stack changes
* Resource sames test
* Fix same resource test
* Fix more tests
* linting
* Update pkg/cmd/pulumi/up.go
Co-authored-by: Alex Mullans <a.mullans@pulumi.com>
* Update pkg/cmd/pulumi/preview.go
Co-authored-by: Alex Mullans <a.mullans@pulumi.com>
* Auto refresh if using plans
* Fix TestGetRefreshOption
* Fix TestExplicitDeleteBeforeReplace
* lint
* More copying in tests because I do not trust myself to get mutation correct
* Small preview plan test
* Add TestPlannedUpdateChangedStack
* Revert auto-refresh changes
* Validate outputs don't change
* omitempty
* Add manifest to plan
* Add proper Plan type
* wip config work
* Config and manifest serder
* linting
* Asset NoError
* Actually check error
* Fix clone
* Test diag message
* Start on more tests
* Add String and GoString to Result
I got fed up assert errors in tests that looked like:
```
Expected nil, but got: &result.simpleResult{err:(*errors.fundamental)(0xc0002fa5d0)}
```
It was very hard to work out at a glance what had gone wrong and I kept
having to hook a debugger just to look at what the error was.
With GoString these now print something like:
```
Expected nil, but got: &simpleResult{err: Unexpected diag message: <{%reset%}>resource violates plan: properties changed: -zed, -baz, -foo<{%reset%}>
}
```
Which is much more ussful.
* Add test error text
* Fix reporting of unseen op errors
* Fix unneeded deletes
* Fix unexpected deletes
* Fix up tests
* Fix merge conflict
* lint
* Fix nil map error
* Fix serialisation typo
* Diff against old inputs
* Diff against checked goal
* Diff against empty for creates
* Fix test
* inputs not outputs
* Seperate PlanDiff type
* Add properties
* Fix input diffs
* Handle creates
* lint
* Add plan message
* Clone plan for update preview
* Save and serialise env vars in plans
* lint
* pretty print json
* input output difference test
* test alias
* fix typo in for loop
* Handle resource plans with nil goal
* go mod tidy
* typo
* Auto use plans from up previews in experimental mode
* Don't preview if we have plan
* Don't run previews with plans now
* fixing tests
* Handle diffs and goals
* Update copystructure
* tests/go.sum
* Revert mod changes
* Add copystructure to tests/go.sum
* includeUnknowns
* go mod tidy
* Make plans for imports
* Remove unused function
* Move code more locally
* Handle nil in serialize
* Handle empty output diffs
* Add test for dropping computed values
* Allow computed properties to become deletes
* if out the generation of plans unless experimental mode is opt'd into
* lint
* typo
* Revert back to plans not skipping previews, this is orthognal to --skip-preview
* Trying to work out non-determinism
* Remove notes.txt
* Hacking with check idea
* Pass checked inputs back to Check from plan file
* Include resource urn in constraint error
* Give much more informative errors when plans fail
* lint
* Update expected diag strings in tests
* Remove unused code
* Duplicate Diff and DeepEquals methods for plans
* Add comment about check ops with failures
* Fix CheckedInputs comment
* OutputDiff doesn't need to be a pointer
* Fix checks against computed
* diffStringSets
* lint
* lint pkg
* Use 4 space indent
* Don't wrap Buffer in Writer
* Mark flags hidden rather than disabled
* Remove envvars from plans
* Assert MarkHidden error
* Add to changelog
* Note plan/save-plan is experimental
Co-authored-by: Pat Gavlin <pat@pulumi.com>
Co-authored-by: Alex Mullans <a.mullans@pulumi.com>
This name better suits the semantics of the type, and aligns with the
rename of deploy.Plan to deploy.Deployment. These changes also refactor
the `update` method s.t. previews and updates are more consistent in
their behavior (e.g. duration and resource changes are now reported for
both, incl. on error paths).
* Make `async:true` the default for `invoke` calls (#3750)
* Switch away from native grpc impl. (#3728)
* Remove usage of the 'deasync' library from @pulumi/pulumi. (#3752)
* Only retry as long as we get unavailable back. Anything else continues. (#3769)
* Handle all errors for now. (#3781)
* Do not assume --yes was present when using pulumi in non-interactive mode (#3793)
* Upgrade all paths for sdk and pkg to v2
* Backport C# invoke classes and other recent gen changes (#4288)
Adjust C# generation
* Replace IDeployment with a sealed class (#4318)
Replace IDeployment with a sealed class
* .NET: default to args subtype rather than Args.Empty (#4320)
* Adding system namespace for Dotnet code gen
This is required for using Obsolute attributes for deprecations
```
Iam/InstanceProfile.cs(142,10): error CS0246: The type or namespace name 'ObsoleteAttribute' could not be found (are you missing a using directive or an assembly reference?) [/Users/stack72/code/go/src/github.com/pulumi/pulumi-aws/sdk/dotnet/Pulumi.Aws.csproj]
Iam/InstanceProfile.cs(142,10): error CS0246: The type or namespace name 'Obsolete' could not be found (are you missing a using directive or an assembly reference?) [/Users/stack72/code/go/src/github.com/pulumi/pulumi-aws/sdk/dotnet/Pulumi.Aws.csproj]
```
* Fix the nullability of config type properties in C# codegen (#4379)
This avoids unnecessary blocking inside pre/post-step callbacks if the
reader on the other side of the event channel is slow.
We do not use a buffered channel in the event pipe because it is
empirically less likely that the goroutine reading from a buffered
channel will be scheduled when new data is placed in the channel. In the
case of our event system in which events will not be delivered to the
service and display until the copying goroutine is scheduled, this can
lead to unacceptable delay between the send of the original event and
its output.
Previously, when the CLI wanted to install a plugin, it used a special
method, `DownloadPlugin` on the `httpstate` backend to actually fetch
the tarball that had the plugin. The reason for this is largely tied
to history, at one point during a closed beta, we required presenting
an API key to download plugins (as a way to enforce folks outside the
beta could not download them) and because of that it was natural to
bake that functionality into the part of the code that interfaced with
the rest of the API from the Pulumi Service.
The downside here is that it means we need to host all the plugins on
`api.pulumi.com` which prevents community folks from being able to
easily write resource providers, since they have to manually manage
the process of downloading a provider to a machine and getting it on
the `$PATH` or putting it in the plugin cache.
To make this easier, we add a `--server` argument you can pass to
`pulumi plugin install` to control the URL that it attempts to fetch
the tarball from. We still have perscriptive guidence on how the
tarball must be
named (`pulumi-[<type>]-[<provider-name>]-vX.Y.Z.tar.gz`) but the base
URL can now be configured.
Folks publishing packages can use install scripts to run `pulumi
plugin install` passing a custom `--server` argument, if needed.
There are two improvements we can make to provide a nicer end to end
story here:
- We can augment the GetRequiredPlugins method on the language
provider to also return information about an optional server to use
when downloading the provider.
- We can pass information about a server to download plugins from as
part of a resource registration or creation of a first class
provider.
These help out in cases where for one reason or another where `pulumi
plugin install` doesn't get run before an update takes place and would
allow us to either do the right thing ahead of time or provide better
error messages with the correct `--server` argument. But, for now,
this unblocks a majority of the cases we care about and provides a
path forward for folks that want to develop and host their own
resource providers.
* Install missing plugins on startup
This commit addresses the problem of missing plugins by scanning the
snapshot and language host on startup for the list of required plugins
and, if there are any plugins that are required but not installed,
installs them. The mechanism by which plugins are installed is exactly
the same as 'pulumi plugin install'.
The installation of missing plugins is best-effort and, if it fails,
will not fail the update.
This commit addresses pulumi/pulumi-azure#200, where users using Pulumi
in CI often found themselves missing plugins.
* Add CHANGELOG
* Skip downloading plugins if no client provided
* Reduce excessive test output
* Update Gopkg.lock
* Update pkg/engine/destroy.go
Co-Authored-By: swgillespie <sean@pulumi.com>
* CR: make pluginSet a newtype
* CR: Assign loop induction var to local var
This commit reverts most of #1853 and replaces it with functionally
identical logic, using the notion of status message-specific sinks.
In other words, where the original commit implemented ephemeral status
messages by adding an `isStatus` parameter to most of the logging
methdos in pulumi/pulumi, this implements ephemeral status messages as a
parallel logging sink, which emits _only_ ephemeral status messages.
The original commit message in that PR was:
> Allow log events to be marked "status" events
>
> This commit will introduce a field, IsStatus to LogRequest. A "status"
> logging event will be displayed in the Info column of the main
> display, but will not be printed out at the end, when resource
> operations complete.
>
> For example, for complex resource initialization, we'd like to display
> a series of intermediate results: [1/4] Service object created, for
> example. We'd like these to appear in the Info column, but not at the
> end, where they are not helpful to the user.
* Show a better error message when decrypting fails
It is most often the case that failing to decrypt a secret implies that
the secret was transferred from one stack to another via copying the
configuration. This commit introduces a better error message for this
case and instructs users to explicitly re-encrypt their encrypted keys
in the context of the new stack.
* Spelling
* CR: Grammar fixes
### First-Class Providers
These changes implement support for first-class providers. First-class
providers are provider plugins that are exposed as resources via the
Pulumi programming model so that they may be explicitly and multiply
instantiated. Each instance of a provider resource may be configured
differently, and configuration parameters may be source from the
outputs of other resources.
### Provider Plugin Changes
In order to accommodate the need to verify and diff provider
configuration and configure providers without complete configuration
information, these changes adjust the high-level provider plugin
interface. Two new methods for validating a provider's configuration
and diffing changes to the same have been added (`CheckConfig` and
`DiffConfig`, respectively), and the type of the configuration bag
accepted by `Configure` has been changed to a `PropertyMap`.
These changes have not yet been reflected in the provider plugin gRPC
interface. We will do this in a set of follow-up changes. Until then,
these methods are implemented by adapters:
- `CheckConfig` validates that all configuration parameters are string
or unknown properties. This is necessary because existing plugins
only accept string-typed configuration values.
- `DiffConfig` either returns "never replace" if all configuration
values are known or "must replace" if any configuration value is
unknown. The justification for this behavior is given
[here](https://github.com/pulumi/pulumi/pull/1695/files#diff-a6cd5c7f337665f5bb22e92ca5f07537R106)
- `Configure` converts the config bag to a legacy config map and
configures the provider plugin if all config values are known. If any
config value is unknown, the underlying plugin is not configured and
the provider may only perform `Check`, `Read`, and `Invoke`, all of
which return empty results. We justify this behavior becuase it is
only possible during a preview and provides the best experience we
can manage with the existing gRPC interface.
### Resource Model Changes
Providers are now exposed as resources that participate in a stack's
dependency graph. Like other resources, they are explicitly created,
may have multiple instances, and may have dependencies on other
resources. Providers are referred to using provider references, which
are a combination of the provider's URN and its ID. This design
addresses the need during a preview to refer to providers that have not
yet been physically created and therefore have no ID.
All custom resources that are not themselves providers must specify a
single provider via a provider reference. The named provider will be
used to manage that resource's CRUD operations. If a resource's
provider reference changes, the resource must be replaced. Though its
URN is not present in the resource's dependency list, the provider
should be treated as a dependency of the resource when topologically
sorting the dependency graph.
Finally, `Invoke` operations must now specify a provider to use for the
invocation via a provider reference.
### Engine Changes
First-class providers support requires a few changes to the engine:
- The engine must have some way to map from provider references to
provider plugins. It must be possible to add providers from a stack's
checkpoint to this map and to register new/updated providers during
the execution of a plan in response to CRUD operations on provider
resources.
- In order to support updating existing stacks using existing Pulumi
programs that may not explicitly instantiate providers, the engine
must be able to manage the "default" providers for each package
referenced by a checkpoint or Pulumi program. The configuration for
a "default" provider is taken from the stack's configuration data.
The former need is addressed by adding a provider registry type that is
responsible for managing all of the plugins required by a plan. In
addition to loading plugins froma checkpoint and providing the ability
to map from a provider reference to a provider plugin, this type serves
as the provider plugin for providers themselves (i.e. it is the
"provider provider").
The latter need is solved via two relatively self-contained changes to
plan setup and the eval source.
During plan setup, the old checkpoint is scanned for custom resources
that do not have a provider reference in order to compute the set of
packages that require a default provider. Once this set has been
computed, the required default provider definitions are conjured and
prepended to the checkpoint's resource list. Each resource that
requires a default provider is then updated to refer to the default
provider for its package.
While an eval source is running, each custom resource registration,
resource read, and invoke that does not name a provider is trapped
before being returned by the source iterator. If no default provider
for the appropriate package has been registered, the eval source
synthesizes an appropriate registration, waits for it to complete, and
records the registered provider's reference. This reference is injected
into the original request, which is then processed as usual. If a
default provider was already registered, the recorded reference is
used and no new registration occurs.
### SDK Changes
These changes only expose first-class providers from the Node.JS SDK.
- A new abstract class, `ProviderResource`, can be subclassed and used
to instantiate first-class providers.
- A new field in `ResourceOptions`, `provider`, can be used to supply
a particular provider instance to manage a `CustomResource`'s CRUD
operations.
- A new type, `InvokeOptions`, can be used to specify options that
control the behavior of a call to `pulumi.runtime.invoke`. This type
includes a `provider` field that is analogous to
`ResourceOptions.provider`.
In pulumi/pulumi#1356, we observed that we can fail during a destroy
because we attempt to load the language plugin, which now eagerly looks
for the @pulumi/pulumi package.
This is also blocking ingestion of the latest engine bits into the PPC.
It turns out that for destroy (and refresh), we have no need for the
language plugin. So, let's skip loading it when appropriate.
I found the flag --force to be a strange name for skipping a preview,
since that name is usually reserved for operations that might be harmful
and yet you're coercing a tool to do it anyway, knowing there's a chance
you're going to shoot yourself in the foot.
I also found that what I almost always want in the situation where
--force was being used is to actually just run a preview and have the
confirmation auto-accepted. Going straight to --force isn't the right
thing in a CI scenario, where you actually want to run a preview first,
just to ensure there aren't any issues, before doing the update.
In a sense, there are four options here:
1. Run a preview, ask for confirmation, then do an update (the default).
2. Run a preview, auto-accept, and then do an update (the CI scenario).
3. Just run a preview with neither a confirmation nor an update (dry run).
4. Just do an update, without performing a preview beforehand (rare).
This change enables all four workflows in our CLI.
Rather than have an explosion of flags, we have a single flag,
--preview, which can specify the mode that we're operating in. The
following are the values which correlate to the above four modes:
1. "": default (no --preview specified)
2. "auto": auto-accept preview confirmation
3. "only": only run a preview, don't confirm or update
4. "skip": skip the preview altogether
As part of this change, I redid a bit of how the preview modes
were specified. Rather than booleans, which had some illegal
combinations, this change introduces a new enum type. Furthermore,
because the engine is wholly ignorant of these flags -- and only the
backend understands them -- it was confusing to me that
engine.UpdateOptions stored this flag, especially given that all
interesting engine options _also_ accepted a dryRun boolean. As of
this change, the backend.PreviewBehavior controls the preview options.
* Re-introduce interface for snapshot management
Snapshot management was done through the Update interface; this commit
splits it into a separate interface
* Put the SnapshotManager instance onto the engine context
* Remove SnapshotManager from planContext and updateActions now that it can be accessed by engine Context
hese changes plumb basic support for cancellation through the engine.
Two types of cancellation are supported for all engine operations:
- Cancellation, which waits for the operation to drive itself to a safe
point before the operation returns, and
- Termination, which does not wait for the operation to drive itself
to a safe opint for the operation returns.
When updating local or managed stacks, a single ^C triggers cancellation
of any running operation; a second ^C will trigger termination.
Fixes#513, #1077.
* Lift snapshot management out of the engine
This PR is a prerequisite for parallelism by addressing a major problem
that the engine has to deal with when performing parallel resource
construction: parallel mutation of the global snapshot. This PR adds
a `SnapshotManager` type that is responsible for maintaining and
persisting the current resource snapshot. It serializes all reads and
writes to the global snapshot and persists the snapshot to persistent
storage upon every write.
As a side-effect of this, the core engine no longer needs to know about
snapshot management at all; all snapshot operations can be handled as
callbacks on deployment events. This will greatly simplify the
parallelization of the core engine.
Worth noting is that the core engine will still need to be able to read
the current snapshot, since it is interested in the dependency graphs
contained within. The full implications of that are out of scope of this
PR.
Remove dead code, Steps no longer need a reference to the plan iterator that created them
Fixing various issues that arise when bringing up pulumi-aws
Line length broke the build
Code review: remove dead field, fix yaml name error
Rebase against master, provide implementation of StackPersister for cloud backend
Code review feedback: comments on MutationStatus, style in snapshot.go
Code review feedback: move SnapshotManager to pkg/backend, change engine to use an interface SnapshotManager
Code review feedback: use a channel for synchronization
Add a comment and a new test
* Maintain two checkpoints, an immutable base and a mutable delta, and
periodically merge the two to produce snapshots
* Add a lot of tests - covers all of the non-error paths of BeginMutation and End
* Fix a test resource provider
* Add a few tests, fix a few issues
* Rebase against master, fixed merge
This change includes a bunch of refactorings I made in prep for
doing refresh (first, the command, see pulumi/pulumi#1081):
* The primary change is to change the way the engine's core update
functionality works with respect to deploy.Source. This is the
way we can plug in new sources of resource information during
planning (and, soon, diffing). The way I intend to model refresh
is by having a new kind of source, deploy.RefreshSource, which
will let us do virtually everything about an update/diff the same
way with refreshes, which avoid otherwise duplicative effort.
This includes changing the planOptions (nee deployOptions) to
take a new SourceFunc callback, which is responsible for creating
a source specific to the kind of plan being requested.
Preview, Update, and Destroy now are primarily differentiated by
the kind of deploy.Source that they return, rather than sprinkling
things like `if Destroying` throughout. This tidies up some logic
and, more importantly, gives us precisely the refresh hook we need.
* Originally, we used the deploy.NullSource for Destroy operations.
This simply returns nothing, which is how Destroy works. For some
reason, we were no longer doing this, and instead had some
`if Destroying` cases sprinkled throughout the deploy.EvalSource.
I think this is a vestige of some old way we did configuration, at
least judging by a comment, which is apparently no longer relevant.
* Move diff and diff-printing logic within the engine into its own
pkg/engine/diff.go file, to prepare for upcoming work.
* I keep noticing benign diffs anytime I regenerate protobufs. I
suspect this is because we're also on different versions. I changed
generate.sh to also dump the version into grpc_version.txt. At
least we can understand where the diffs are coming from, decide
whether to take them (i.e., a newer version), and ensure that as
a team we are monotonically increasing, and not going backwards.
* I also tidied up some tiny things I noticed while in there, like
comments, incorrect types, lint suppressions, and so on.
When a stack has secrets, we now take the secret values and construct
a regular expression which is just an alternation of all the secret
values. Then, before pushing any string data into an Event, we run the
regular expression and replace all matches with '[secret]'.
Fixes#747
The existing logic would flow colorization information into the
engine, so depending on the settings in the CLI, the engine may or may
not have emitted colorized events. This coupling is not great and we
want to start moving to a world where the presentation happens
exclusively at the CLI level.
With this change, the engine will always produce strings that have the
colorization formatting directives (i.e. the directives that
reconquest/loreley understands) and the CLI will apply
colorization (which could mean either running loreley to turn the
directives into ANSI escape codes, or drop them or retain them, for
debuging purposes).
Fixes#742