pulumi/pkg/engine/query.go

175 lines
5.6 KiB
Go
Raw Normal View History

// Copyright 2016-2023, 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 engine
import (
"context"
"fmt"
"github.com/opentracing/opentracing-go"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/fsutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/result"
)
type QueryOptions struct {
Events eventEmitter // the channel to write events from the engine to.
Diag diag.Sink // the sink to use for diag'ing.
StatusDiag diag.Sink // the sink to use for diag'ing status messages.
host plugin.Host // the plugin host to use for this query.
pwd, main string
plugctx *plugin.Context
tracingSpan opentracing.Span
}
func Query(ctx *Context, q QueryInfo, opts UpdateOptions) error {
contract.Requiref(q != nil, "update", "cannot be nil")
contract.Requiref(ctx != nil, "ctx", "cannot be nil")
defer func() { ctx.Events <- NewCancelEvent() }()
tracingSpan := func(opName string, parentSpan opentracing.SpanContext) opentracing.Span {
// Create a root span for the operation
opts := []opentracing.StartSpanOption{}
if opName != "" {
opts = append(opts, opentracing.Tag{Key: "operation", Value: opName})
}
if parentSpan != nil {
opts = append(opts, opentracing.ChildOf(parentSpan))
}
return opentracing.StartSpan("pulumi-query", opts...)
}("query", ctx.ParentSpan)
defer tracingSpan.Finish()
emitter, err := makeQueryEventEmitter(ctx.Events)
if err != nil {
return err
}
defer emitter.Close()
// First, load the package metadata and the deployment target in preparation for executing the package's program
// and creating resources. This includes fetching its pwd and main overrides.
diag := newEventSink(emitter, false)
statusDiag := newEventSink(emitter, true)
proj := q.GetProject()
contract.Assertf(proj != nil, "query project cannot be nil")
pwd, main, plugctx, err := ProjectInfoContext(&Projinfo{Proj: proj, Root: q.GetRoot()},
opts.Host, diag, statusDiag, false, tracingSpan, nil)
if err != nil {
return err
}
defer plugctx.Close()
return query(ctx, q, QueryOptions{
Events: emitter,
Diag: diag,
StatusDiag: statusDiag,
host: opts.Host,
pwd: pwd,
main: main,
plugctx: plugctx,
tracingSpan: tracingSpan,
})
}
func newQuerySource(cancel context.Context, client deploy.BackendClient, q QueryInfo,
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 QueryOptions,
) (deploy.QuerySource, error) {
ctrl-c should cause Pulumi to call Cancel operation on providers (#14057) <!--- 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](https://github.com/pulumi/pulumi/pull/9793/commits/a9ae602867834efc9821abd866ef388c1b051114) 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 https://github.com/pulumi/pulumi/pull/9793/commits/a9ae602867834efc9821abd866ef388c1b051114. ## 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. -->
2023-09-29 22:12:35 +00:00
allPlugins, defaultProviderVersions, err := installPlugins(cancel, q.GetProject(), opts.pwd, opts.main,
nil, opts.plugctx, false /*returnInstallErrors*/)
if err != nil {
return nil, err
}
// Once we've installed all of the plugins we need, make sure that all analyzers and language plugins are
// loaded up and ready to go. Provider plugins are loaded lazily by the provider registry and thus don't
// need to be loaded here.
const kinds = plugin.LanguagePlugins
if err := ensurePluginsAreLoaded(opts.plugctx, allPlugins, kinds); err != nil {
return nil, err
}
if opts.tracingSpan != nil {
cancel = opentracing.ContextWithSpan(cancel, opts.tracingSpan)
}
// If that succeeded, create a new source that will perform interpretation of the compiled program.
// TODO[pulumi/pulumi#88]: we are passing `nil` as the arguments map; we need to allow a way to pass these.
return deploy.NewQuerySource(cancel, opts.plugctx, client, &deploy.EvalRunInfo{
ProjectRoot: q.GetRoot(),
Proj: q.GetProject(),
Pwd: opts.pwd,
Program: opts.main,
}, defaultProviderVersions, nil)
}
func query(ctx *Context, q QueryInfo, opts QueryOptions) error {
// Make the current working directory the same as the program's, and restore it upon exit.
done, err := fsutil.Chdir(opts.plugctx.Pwd)
if err != nil {
return err
}
defer done()
if err := runQuery(ctx, q, opts); err != nil {
if result.IsBail(err) {
return err
}
return fmt.Errorf("an error occurred while running the query: %w", err)
}
return nil
}
func runQuery(cancelCtx *Context, q QueryInfo, opts QueryOptions) error {
ctx, cancelFunc := context.WithCancel(context.Background())
// Set up a goroutine that will signal cancellation to the plan's plugins if the caller context
// is cancelled.
go func() {
2019-04-30 22:21:26 +00:00
<-cancelCtx.Cancel.Canceled()
logging.V(4).Infof("engine.runQuery(...): signalling cancellation to providers...")
cancelFunc()
cancelErr := opts.plugctx.Host.SignalCancellation()
if cancelErr != nil {
logging.V(4).Infof("engine.runQuery(...): failed to signal cancellation to providers: %v", cancelErr)
}
}()
ctrl-c should cause Pulumi to call Cancel operation on providers (#14057) <!--- 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](https://github.com/pulumi/pulumi/pull/9793/commits/a9ae602867834efc9821abd866ef388c1b051114) 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 https://github.com/pulumi/pulumi/pull/9793/commits/a9ae602867834efc9821abd866ef388c1b051114. ## 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. -->
2023-09-29 22:12:35 +00:00
src, err := newQuerySource(ctx, cancelCtx.BackendClient, q, opts)
if err != nil {
return err
}
done := make(chan error)
go func() {
done <- src.Wait()
}()
// Block until query completes.
select {
case <-cancelCtx.Cancel.Terminated():
return cancelCtx.Cancel.TerminateErr()
case err := <-done:
return err
}
}