pulumi/pkg/resource/deploy/source_query_test.go

894 lines
24 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 deploy
import (
"context"
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
"errors"
"io"
"sync"
"testing"
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"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/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/result"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
Remove deprecated Protobufs imports (#15158) <!--- 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. --> github.com/golang/protobuf is marked deprecated and I was getting increasingly triggered by the inconsistency of importing the `Empty` type from "github.com/golang/protobuf/ptypes/empty" or "google.golang.org/protobuf/types/known/emptypb" as "pbempty" or "empty" or "emptypb". Similar for the struct type. So this replaces all the Protobufs imports with ones from "google.golang.org/protobuf", normalises the import name to always just be the module name (emptypb), and adds the depguard linter to ensure we don't use the deprecated package anymore. ## 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. -->
2024-01-17 09:35:20 +00:00
"google.golang.org/protobuf/types/known/emptypb"
)
func TestQuerySource_Trivial_Wait(t *testing.T) {
t.Parallel()
// Trivial querySource returns immediately with `Wait()`, even with multiple invocations.
// Success case.
var called1 bool
resmon1 := mockResmon{
CancelF: func() error {
called1 = true
return nil
},
}
qs1, _ := newTestQuerySource(&resmon1, func(*querySource) error {
return nil
})
qs1.forkRun()
err := qs1.Wait()
assert.NoError(t, err)
assert.False(t, called1)
// Can be called twice.
err = qs1.Wait()
assert.NoError(t, err)
// Failure case.
var called2 bool
resmon2 := mockResmon{
CancelF: func() error {
called2 = true
return nil
},
}
qs2, _ := newTestQuerySource(&resmon2, func(*querySource) error {
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
return errors.New("failed")
})
qs2.forkRun()
err = qs2.Wait()
assert.False(t, result.IsBail(err))
assert.Error(t, err)
assert.False(t, called2)
// Can be called twice.
err = qs2.Wait()
assert.False(t, result.IsBail(err))
assert.Error(t, err)
assert.False(t, called2)
}
func TestQuerySource_Async_Wait(t *testing.T) {
t.Parallel()
// `Wait()` executes asynchronously.
// Success case.
//
// test blocks until querySource signals execution has started
// -> querySource blocks until test acknowledges querySource's signal
// -> test blocks on `Wait()` until querySource completes.
var called1 bool
resmon1 := mockResmon{
CancelF: func() error {
called1 = true
return nil
},
}
qs1Start, qs1StartAck := make(chan interface{}), make(chan interface{})
qs1, _ := newTestQuerySource(&resmon1, func(*querySource) error {
qs1Start <- struct{}{}
<-qs1StartAck
return nil
})
qs1.forkRun()
// Wait until querySource starts, then acknowledge starting.
<-qs1Start
go func() {
qs1StartAck <- struct{}{}
}()
// Wait for querySource to complete.
err := qs1.Wait()
assert.NoError(t, err)
assert.False(t, called1)
err = qs1.Wait()
assert.NoError(t, err)
assert.False(t, called1)
var called2 bool
resmon2 := mockResmon{
CancelF: func() error {
called2 = true
return nil
},
}
// Cancellation case.
//
// test blocks until querySource signals execution has started
// -> querySource blocks until test acknowledges querySource's signal
// -> test blocks on `Wait()` until querySource completes.
qs2Start, qs2StartAck := make(chan interface{}), make(chan interface{})
qs2, cancelQs2 := newTestQuerySource(&resmon2, func(*querySource) error {
qs2Start <- struct{}{}
// Block forever.
<-qs2StartAck
return nil
})
qs2.forkRun()
// Wait until querySource starts, then cancel.
<-qs2Start
go func() {
cancelQs2()
}()
// Wait for querySource to complete.
err = qs2.Wait()
assert.NoError(t, err)
assert.True(t, called2)
err = qs2.Wait()
assert.NoError(t, err)
assert.True(t, called2)
}
func TestQueryResourceMonitor_UnsupportedOperations(t *testing.T) {
t.Parallel()
rm := &queryResmon{}
_, err := rm.ReadResource(context.Background(), nil)
assert.EqualError(t, err, "Query mode does not support reading resources")
_, err = rm.RegisterResource(context.Background(), nil)
assert.EqualError(t, err, "Query mode does not support creating, updating, or deleting resources")
_, err = rm.RegisterResourceOutputs(context.Background(), nil)
assert.EqualError(t, err, "Query mode does not support registering resource operations")
}
func TestQueryResourceMonitor(t *testing.T) {
t.Parallel()
t.Run("newQueryResourceMonitor", func(t *testing.T) {
t.Parallel()
t.Run("bad decrypter", func(t *testing.T) {
t.Parallel()
providerRegErrChan := make(chan error, 1)
expectedErr := errors.New("expected error")
resmon, err := newQueryResourceMonitor(
nil, nil, nil, nil, nil, providerRegErrChan, nil, &EvalRunInfo{
Proj: &workspace.Project{
Name: "expected-project",
},
Target: &Target{
Config: config.Map{
config.MustMakeKey("test", "secret"): config.NewSecureValue("secret-value"),
config.MustMakeKey("test", "regular"): config.NewValue("regular-value"),
},
Decrypter: &decrypterMock{
DecryptValueF: func(
ctx context.Context, ciphertext string,
) (string, error) {
return "", expectedErr
},
},
},
},
)
_ = resmon
assert.ErrorIs(t, err, expectedErr)
})
t.Run("ok", func(t *testing.T) {
t.Parallel()
providerRegErrChan := make(chan error, 1)
resmon, err := newQueryResourceMonitor(
nil, nil, nil, nil, nil, providerRegErrChan, nil, &EvalRunInfo{
Proj: &workspace.Project{
Name: "expected-project",
},
Target: &Target{
Name: tokens.MustParseStackName("expected-name"),
},
},
)
assert.NoError(t, err)
assert.Equal(t, "expected-project", resmon.callInfo.Project)
assert.Equal(t, "expected-name", resmon.callInfo.Stack)
})
})
t.Run("Cancel", func(t *testing.T) {
t.Parallel()
expectedErr := errors.New("expected-error")
done := make(chan error, 1)
done <- expectedErr
rm := &queryResmon{
cancel: make(chan bool),
done: done,
}
assert.ErrorIs(t, rm.Cancel(), expectedErr)
})
t.Run("Invoke", func(t *testing.T) {
t.Parallel()
t.Run("bad provider request", func(t *testing.T) {
t.Parallel()
t.Run("bad version", func(t *testing.T) {
t.Parallel()
rm := &queryResmon{}
_, err := rm.Invoke(context.Background(), &pulumirpc.ResourceInvokeRequest{
Tok: "pkgA:index:func",
Version: "bad-version",
})
assert.ErrorContains(t, err, "No Major.Minor.Patch elements found")
})
t.Run("default provider error", func(t *testing.T) {
t.Parallel()
providerRegChan := make(chan *registerResourceEvent, 1)
requests := make(chan defaultProviderRequest, 1)
rm := &queryResmon{
reg: &providers.Registry{},
defaultProviders: &defaultProviders{
requests: requests,
providerRegChan: providerRegChan,
},
}
wg := &sync.WaitGroup{}
wg.Add(1)
expectedErr := errors.New("expected error")
// Needed so defaultProviders.handleRequest() doesn't hang.
go func() {
req := <-rm.defaultProviders.requests
req.response <- defaultProviderResponse{
err: expectedErr,
}
wg.Done()
}()
_, err := rm.Invoke(context.Background(), &pulumirpc.ResourceInvokeRequest{
Tok: "pkgA:index:func",
Version: "1.0.0",
})
wg.Wait()
assert.ErrorIs(t, err, expectedErr)
})
})
})
}
//
// Test querySource constructor.
//
func newTestQuerySource(mon SourceResourceMonitor,
runLangPlugin func(*querySource) error,
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
) (*querySource, context.CancelFunc) {
cancel, cancelFunc := context.WithCancel(context.Background())
return &querySource{
mon: mon,
runLangPlugin: runLangPlugin,
langPluginFinChan: make(chan error),
cancel: cancel,
}, cancelFunc
}
//
// Mock resource monitor.
//
type mockResmon struct {
AddressF func() string
CancelF func() error
InvokeF func(ctx context.Context,
req *pulumirpc.ResourceInvokeRequest) (*pulumirpc.InvokeResponse, error)
CallF func(ctx context.Context,
Split CallRequest into ResourceCallRequest (#15404) <!--- 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. --> Similar to what we did to the `InvokeRequest` a while ago. We're currently using the same protobuf structure for `Provider.Call` and `ResourceMonitor.Call` despite different field sets being filled in for each of them. This splits the structure into `CallRequest` for providers and `ResourceCallRequest` for the resource monitor. A number of fields in each are removed and marked reserved with a comment explaining why. ## 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. --> - [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. -->
2024-02-08 13:16:23 +00:00
req *pulumirpc.ResourceCallRequest) (*pulumirpc.CallResponse, error)
ReadResourceF func(ctx context.Context,
req *pulumirpc.ReadResourceRequest) (*pulumirpc.ReadResourceResponse, error)
RegisterResourceF func(ctx context.Context,
req *pulumirpc.RegisterResourceRequest) (*pulumirpc.RegisterResourceResponse, error)
RegisterResourceOutputsF func(ctx context.Context,
Remove deprecated Protobufs imports (#15158) <!--- 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. --> github.com/golang/protobuf is marked deprecated and I was getting increasingly triggered by the inconsistency of importing the `Empty` type from "github.com/golang/protobuf/ptypes/empty" or "google.golang.org/protobuf/types/known/emptypb" as "pbempty" or "empty" or "emptypb". Similar for the struct type. So this replaces all the Protobufs imports with ones from "google.golang.org/protobuf", normalises the import name to always just be the module name (emptypb), and adds the depguard linter to ensure we don't use the deprecated package anymore. ## 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. -->
2024-01-17 09:35:20 +00:00
req *pulumirpc.RegisterResourceOutputsRequest) (*emptypb.Empty, error)
}
var _ SourceResourceMonitor = (*mockResmon)(nil)
func (rm *mockResmon) Address() string {
if rm.AddressF != nil {
return rm.AddressF()
}
panic("not implemented")
}
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
func (rm *mockResmon) Cancel() error {
if rm.CancelF != nil {
return rm.CancelF()
}
panic("not implemented")
}
func (rm *mockResmon) Invoke(ctx context.Context,
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
req *pulumirpc.ResourceInvokeRequest,
) (*pulumirpc.InvokeResponse, error) {
if rm.InvokeF != nil {
return rm.InvokeF(ctx, req)
}
panic("not implemented")
}
func (rm *mockResmon) Call(ctx context.Context,
Split CallRequest into ResourceCallRequest (#15404) <!--- 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. --> Similar to what we did to the `InvokeRequest` a while ago. We're currently using the same protobuf structure for `Provider.Call` and `ResourceMonitor.Call` despite different field sets being filled in for each of them. This splits the structure into `CallRequest` for providers and `ResourceCallRequest` for the resource monitor. A number of fields in each are removed and marked reserved with a comment explaining why. ## 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. --> - [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. -->
2024-02-08 13:16:23 +00:00
req *pulumirpc.ResourceCallRequest,
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
) (*pulumirpc.CallResponse, error) {
if rm.CallF != nil {
return rm.CallF(ctx, req)
}
panic("not implemented")
}
func (rm *mockResmon) ReadResource(ctx context.Context,
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
req *pulumirpc.ReadResourceRequest,
) (*pulumirpc.ReadResourceResponse, error) {
if rm.ReadResourceF != nil {
return rm.ReadResourceF(ctx, req)
}
panic("not implemented")
}
func (rm *mockResmon) RegisterResource(ctx context.Context,
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
req *pulumirpc.RegisterResourceRequest,
) (*pulumirpc.RegisterResourceResponse, error) {
if rm.RegisterResourceF != nil {
return rm.RegisterResourceF(ctx, req)
}
panic("not implemented")
}
func (rm *mockResmon) RegisterResourceOutputs(ctx context.Context,
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
req *pulumirpc.RegisterResourceOutputsRequest,
Remove deprecated Protobufs imports (#15158) <!--- 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. --> github.com/golang/protobuf is marked deprecated and I was getting increasingly triggered by the inconsistency of importing the `Empty` type from "github.com/golang/protobuf/ptypes/empty" or "google.golang.org/protobuf/types/known/emptypb" as "pbempty" or "empty" or "emptypb". Similar for the struct type. So this replaces all the Protobufs imports with ones from "google.golang.org/protobuf", normalises the import name to always just be the module name (emptypb), and adds the depguard linter to ensure we don't use the deprecated package anymore. ## 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. -->
2024-01-17 09:35:20 +00:00
) (*emptypb.Empty, error) {
if rm.RegisterResourceOutputsF != nil {
return rm.RegisterResourceOutputsF(ctx, req)
}
panic("not implemented")
}
func TestQuerySource(t *testing.T) {
t.Parallel()
t.Run("Wait", func(t *testing.T) {
t.Parallel()
var called bool
providerRegErrChan := make(chan error, 1)
expectedErr := errors.New("expected error")
providerRegErrChan <- expectedErr
src := &querySource{
providerRegErrChan: providerRegErrChan,
// Required to not nil ptr dereference.
cancel: context.Background(),
mon: &mockResmon{
CancelF: func() error {
called = true
return nil
},
},
}
err := src.Wait()
assert.ErrorIs(t, err, expectedErr)
assert.True(t, called)
})
}
func TestRunLangPlugin(t *testing.T) {
t.Parallel()
t.Run("failed to launch language host", func(t *testing.T) {
t.Parallel()
assert.ErrorContains(t, runLangPlugin(&querySource{
plugctx: &plugin.Context{
Host: &mockHost{
LanguageRuntimeF: func(runtime string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
return nil, errors.New("expected error")
},
},
},
runinfo: &EvalRunInfo{
ProjectRoot: "/",
Pwd: "/",
Program: ".",
Proj: &workspace.Project{
Runtime: workspace.NewProjectRuntimeInfo("stuff", map[string]interface{}{}),
},
},
}), "failed to launch language host")
})
t.Run("bad decrypter", func(t *testing.T) {
t.Parallel()
expectedErr := errors.New("expected error")
err := runLangPlugin(&querySource{
plugctx: &plugin.Context{
Host: &mockHost{
LanguageRuntimeF: func(runtime string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
return &mockLanguageRuntime{}, nil
},
},
},
runinfo: &EvalRunInfo{
ProjectRoot: "/",
Pwd: "/",
Program: ".",
Proj: &workspace.Project{
Runtime: workspace.NewProjectRuntimeInfo("stuff", map[string]interface{}{}),
},
Target: &Target{
Config: config.Map{
config.MustMakeKey("test", "secret"): config.NewSecureValue("secret-value"),
config.MustMakeKey("test", "regular"): config.NewValue("regular-value"),
},
Decrypter: &decrypterMock{
DecryptValueF: func(
ctx context.Context, ciphertext string,
) (string, error) {
return "", expectedErr
},
},
},
},
})
assert.ErrorIs(t, err, expectedErr)
})
t.Run("bail successfully", func(t *testing.T) {
t.Parallel()
err := runLangPlugin(&querySource{
plugctx: &plugin.Context{
Host: &mockHost{
LanguageRuntimeF: func(runtime string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
return &mockLanguageRuntime{
RunF: func(info plugin.RunInfo) (string, bool, error) {
return "bail should override progerr", true /* bail */, nil
},
}, nil
},
},
},
// Prevent nilptr dereference.
mon: &mockResmon{
AddressF: func() string { return "" },
},
runinfo: &EvalRunInfo{
ProjectRoot: "/",
Pwd: "/",
Program: ".",
Proj: &workspace.Project{
Runtime: workspace.NewProjectRuntimeInfo("stuff", map[string]interface{}{}),
},
},
})
assert.ErrorContains(t, err, "run bailed")
})
t.Run("progerr", func(t *testing.T) {
t.Parallel()
err := runLangPlugin(&querySource{
plugctx: &plugin.Context{
Host: &mockHost{
LanguageRuntimeF: func(runtime string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
return &mockLanguageRuntime{
RunF: func(info plugin.RunInfo) (string, bool, error) {
return "expected progerr", false /* bail */, nil
},
}, nil
},
},
},
// Prevent nilptr dereference.
mon: &mockResmon{
AddressF: func() string { return "" },
},
runinfo: &EvalRunInfo{
ProjectRoot: "/",
Pwd: "/",
Program: ".",
Proj: &workspace.Project{
Runtime: workspace.NewProjectRuntimeInfo("stuff", map[string]interface{}{}),
},
},
})
assert.ErrorContains(t, err, "expected progerr")
})
t.Run("langhost is run correctly", func(t *testing.T) {
t.Parallel()
var runCalled bool
err := runLangPlugin(&querySource{
plugctx: &plugin.Context{
Host: &mockHost{
LanguageRuntimeF: func(runtime string, p plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
return &mockLanguageRuntime{
RunF: func(info plugin.RunInfo) (string, bool, error) {
runCalled = true
assert.Equal(t, "expected-address", info.MonitorAddress)
assert.Equal(t, "expected-stack", info.Stack)
assert.Equal(t, "expected-project", info.Project)
Ensure project plugins are absolute paths (#15470) <!--- 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/15467. This tightens the restriction on paths passed to `NewProgramInfo`. Previously it allowed relative paths like "./providers/my_provider". That is now an error. This is correct behaviour. The fields of this structure are passed via protobuf and the descriptions for them in the proto spec are that they should always be absolute paths. Where we build plugin paths we ensure that if they're relative we resolve them to what they are relative to. That is generally _not_ the current working directory so `filepath.Abs` doesn't do the right thing here. ## 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. --> - [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. -->
2024-02-22 11:43:18 +00:00
assert.Equal(t, "/expected-pwd", info.Pwd)
assert.Equal(t, "/expected-pwd", info.Info.ProgramDirectory())
assert.Equal(t, "expected-program", info.Info.EntryPoint())
assert.Equal(t, []string{"expected", "args"}, info.Args)
assert.Equal(t, "secret-value", info.Config[config.MustMakeKey("test", "secret")])
assert.Equal(t, "regular-value", info.Config[config.MustMakeKey("test", "regular")])
assert.True(t, info.QueryMode)
assert.True(t, info.DryRun)
// Disregard Parallel argument.
assert.Equal(t, "expected-organization", info.Organization)
return "", false, nil
},
}, nil
},
},
},
// Prevent nilptr dereference.
mon: &mockResmon{
AddressF: func() string { return "expected-address" },
},
runinfo: &EvalRunInfo{
ProjectRoot: "/",
Proj: &workspace.Project{
Name: "expected-project",
Runtime: workspace.NewProjectRuntimeInfo("stuff", map[string]interface{}{}),
},
Ensure project plugins are absolute paths (#15470) <!--- 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/15467. This tightens the restriction on paths passed to `NewProgramInfo`. Previously it allowed relative paths like "./providers/my_provider". That is now an error. This is correct behaviour. The fields of this structure are passed via protobuf and the descriptions for them in the proto spec are that they should always be absolute paths. Where we build plugin paths we ensure that if they're relative we resolve them to what they are relative to. That is generally _not_ the current working directory so `filepath.Abs` doesn't do the right thing here. ## 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. --> - [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. -->
2024-02-22 11:43:18 +00:00
Pwd: "/expected-pwd",
Program: "expected-program",
Args: []string{"expected", "args"},
Target: &Target{
Config: config.Map{
config.MustMakeKey("test", "secret"): config.NewSecureValue("secret-value"),
config.MustMakeKey("test", "regular"): config.NewValue("regular-value"),
},
Name: tokens.MustParseStackName("expected-stack"),
Organization: "expected-organization",
Decrypter: &decrypterMock{
DecryptValueF: func(
ctx context.Context, ciphertext string,
) (string, error) {
return ciphertext, nil
},
},
},
},
})
assert.NoError(t, err)
assert.True(t, runCalled)
})
}
type mockHost struct {
ServerAddrF func() string
LogF func(sev diag.Severity, urn resource.URN, msg string, streamID int32)
LogStatusF func(sev diag.Severity, urn resource.URN, msg string, streamID int32)
AnalyzerF func(nm tokens.QName) (plugin.Analyzer, error)
PolicyAnalyzerF func(name tokens.QName, path string, opts *plugin.PolicyAnalyzerOptions) (plugin.Analyzer, error)
ListAnalyzersF func() []plugin.Analyzer
ProviderF func(pkg tokens.Package, version *semver.Version) (plugin.Provider, error)
CloseProviderF func(provider plugin.Provider) error
LanguageRuntimeF func(language string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error)
EnsurePluginsF func(plugins []workspace.PluginSpec, kinds plugin.Flags) error
ResolvePluginF func(kind apitype.PluginKind, name string, version *semver.Version) (*workspace.PluginInfo, error)
GetProjectPluginsF func() []workspace.ProjectPlugin
SignalCancellationF func() error
CloseF func() error
}
var _ plugin.Host = (*mockHost)(nil)
func (h *mockHost) ServerAddr() string {
if h.ServerAddrF != nil {
return h.ServerAddrF()
}
panic("unimplemented")
}
func (h *mockHost) Log(sev diag.Severity, urn resource.URN, msg string, streamID int32) {
if h.LogF != nil {
h.LogF(sev, urn, msg, streamID)
return
}
panic("unimplemented")
}
func (h *mockHost) LogStatus(sev diag.Severity, urn resource.URN, msg string, streamID int32) {
if h.LogStatusF != nil {
h.LogStatusF(sev, urn, msg, streamID)
return
}
panic("unimplemented")
}
func (h *mockHost) Analyzer(nm tokens.QName) (plugin.Analyzer, error) {
if h.AnalyzerF != nil {
return h.Analyzer(nm)
}
panic("unimplemented")
}
func (h *mockHost) PolicyAnalyzer(
name tokens.QName, path string, opts *plugin.PolicyAnalyzerOptions,
) (plugin.Analyzer, error) {
if h.PolicyAnalyzerF != nil {
return h.PolicyAnalyzerF(name, path, opts)
}
panic("unimplemented")
}
func (h *mockHost) ListAnalyzers() []plugin.Analyzer {
if h.ListAnalyzersF != nil {
return h.ListAnalyzersF()
}
panic("unimplemented")
}
func (h *mockHost) Provider(pkg tokens.Package, version *semver.Version) (plugin.Provider, error) {
if h.ProviderF != nil {
return h.ProviderF(pkg, version)
}
panic("unimplemented")
}
func (h *mockHost) CloseProvider(provider plugin.Provider) error {
if h.CloseProviderF != nil {
return h.CloseProviderF(provider)
}
panic("unimplemented")
}
func (h *mockHost) LanguageRuntime(runtime string, info plugin.ProgramInfo) (plugin.LanguageRuntime, error) {
if h.LanguageRuntimeF != nil {
return h.LanguageRuntimeF(runtime, info)
}
panic("unimplemented")
}
func (h *mockHost) EnsurePlugins(plugins []workspace.PluginSpec, kinds plugin.Flags) error {
if h.EnsurePluginsF != nil {
return h.EnsurePluginsF(plugins, kinds)
}
panic("unimplemented")
}
func (h *mockHost) ResolvePlugin(
kind apitype.PluginKind, name string, version *semver.Version,
) (*workspace.PluginInfo, error) {
if h.ResolvePluginF != nil {
return h.ResolvePluginF(kind, name, version)
}
panic("unimplemented")
}
func (h *mockHost) GetProjectPlugins() []workspace.ProjectPlugin {
if h.GetProjectPluginsF != nil {
return h.GetProjectPluginsF()
}
panic("unimplemented")
}
func (h *mockHost) SignalCancellation() error {
if h.SignalCancellationF != nil {
return h.SignalCancellationF()
}
panic("unimplemented")
}
// Close reclaims any resources associated with the host.
func (h *mockHost) Close() error {
if h.CloseF != nil {
return h.CloseF()
}
panic("unimplemented")
}
type mockLanguageRuntime struct {
CloseF func() error
GetRequiredPluginsF func(info plugin.ProgramInfo) ([]workspace.PluginSpec, error)
RunF func(info plugin.RunInfo) (string, bool, error)
GetPluginInfoF func() (workspace.PluginInfo, error)
InstallDependenciesF func(info plugin.ProgramInfo) error
RuntimeOptionsPromptsF func(info plugin.ProgramInfo) ([]plugin.RuntimeOptionPrompt, error)
AboutF func(info plugin.ProgramInfo) (plugin.AboutInfo, error)
GetProgramDependenciesF func(
info plugin.ProgramInfo, transitiveDependencies bool,
) ([]plugin.DependencyInfo, error)
RunPluginF func(
info plugin.RunPluginInfo,
) (io.Reader, io.Reader, context.CancelFunc, error)
GenerateProjectF func(
sourceDirectory, targetDirectory, project string,
strict bool, loaderTarget string, localDependencies map[string]string,
) (hcl.Diagnostics, error)
GeneratePackageF func(
directory string, schema string,
Use the local artifacts, not released artifacts in conformance tests (#15777) <!--- 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. --> This threads the "local_dependencies" property through to GeneratePackage, following exactly the same semantics as for "GenerateProgram". Fixes https://github.com/pulumi/pulumi/issues/15074. ## 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. --> - [x] 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. -->
2024-03-26 13:10:34 +00:00
extraFiles map[string][]byte, loaderTarget string, localDependencies map[string]string,
local bool,
) (hcl.Diagnostics, error)
GenerateProgramF func(
program map[string]string,
loaderTarget string,
) (map[string][]byte, hcl.Diagnostics, error)
PackF func(
packageDirectory string,
destinationDirectory string,
) (string, error)
}
var _ plugin.LanguageRuntime = (*mockLanguageRuntime)(nil)
func (rt *mockLanguageRuntime) Close() error {
if rt.CloseF != nil {
return rt.CloseF()
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GetRequiredPlugins(info plugin.ProgramInfo) ([]workspace.PluginSpec, error) {
if rt.GetRequiredPluginsF != nil {
return rt.GetRequiredPluginsF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) Run(info plugin.RunInfo) (string, bool, error) {
if rt.RunF != nil {
return rt.RunF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GetPluginInfo() (workspace.PluginInfo, error) {
if rt.GetPluginInfoF != nil {
return rt.GetPluginInfoF()
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) InstallDependencies(info plugin.ProgramInfo) error {
if rt.InstallDependenciesF != nil {
return rt.InstallDependenciesF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) RuntimeOptionsPrompts(info plugin.ProgramInfo) ([]plugin.RuntimeOptionPrompt, error) {
if rt.RuntimeOptionsPromptsF != nil {
return rt.RuntimeOptionsPromptsF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) About(info plugin.ProgramInfo) (plugin.AboutInfo, error) {
if rt.AboutF != nil {
return rt.AboutF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GetProgramDependencies(
info plugin.ProgramInfo, transitiveDependencies bool,
) ([]plugin.DependencyInfo, error) {
if rt.GetProgramDependenciesF != nil {
return rt.GetProgramDependenciesF(info, transitiveDependencies)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) RunPlugin(
info plugin.RunPluginInfo,
) (io.Reader, io.Reader, context.CancelFunc, error) {
if rt.RunPluginF != nil {
return rt.RunPluginF(info)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GenerateProject(
sourceDirectory, targetDirectory, project string,
strict bool, loaderTarget string, localDependencies map[string]string,
) (hcl.Diagnostics, error) {
if rt.GenerateProjectF != nil {
return rt.GenerateProjectF(
sourceDirectory, targetDirectory, project, strict, loaderTarget, localDependencies)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GeneratePackage(
Use the local artifacts, not released artifacts in conformance tests (#15777) <!--- 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. --> This threads the "local_dependencies" property through to GeneratePackage, following exactly the same semantics as for "GenerateProgram". Fixes https://github.com/pulumi/pulumi/issues/15074. ## 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. --> - [x] 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. -->
2024-03-26 13:10:34 +00:00
directory string, schema string, extraFiles map[string][]byte,
loaderTarget string, localDependencies map[string]string,
local bool,
) (hcl.Diagnostics, error) {
if rt.GeneratePackageF != nil {
return rt.GeneratePackageF(directory, schema, extraFiles, loaderTarget, localDependencies, local)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) GenerateProgram(
[cli/import] Fix undefined variable errors in code generation when imported resources use a parent or provider (#16786) Fixes #15410 Fixes #13339 ## Problem Context When using `pulumi import` we generate code snippets for the resources that were imported. Sometimes the user specifies `--parent parentName=URN` or `--provider providerName=URN` which tweak the parent or provider that the imported resources uses. When using `--parent` or `--provider` the generated code emits a resource option `parent = parentName` (in case of using `--parent`) where `parentName` is an unbound variable. Usually unbound variables would result in a _bind_ error such as `error: undefined variable parentName` when type-checking the program however in the import code generation we specify the bind option `pcl.AllowMissingVariables` which turns that unbound variable errors into warnings and code generation can continue to emit code. This is all good and works as expected. However in the issues linked above, we do get an _error_ for unbound variables in generated code even though we specified `AllowMissingVariables`. The problem as it turns out is when we are trying to generate code via dynamically loaded `LangaugeRuntime` plugins. Specifically for NodeJS and Python, we load `pulumi-language-nodejs` or `pulumi-language-python` and call `GenerateProgram` to get the generated program. That function `GenerateProgram` takes the text _SOURCE_ of the a bound program (one that was bound using option `AllowMissingVariables`) and re-binds again inside the implementation of the language plugin. The second time we bind the program, we don't pass it the option `AllowMissingVariables` and so it fails with `unboud variable` error. I've verified that the issue above don't repro when doing an import for dotnet (probably same for java/yaml) because we use the statically linked function `codegen/{lang}/gen_program.go -> GenerateProgram` ## Solution The problem can be solved by propagating the bind options from the CLI to the language hosts during import so that they know how to bind the program. I've extended the gRPC interface in `GenerateProgramRequest` with a property `Strict` which follows the same logic from `pulumi convert --strict` and made it such that the import command sends `strict=false` to the language plugins when doing `GenerateProgram`. This is consistent with `GenerateProject` that uses the same flag. When `strict=false` we use `pcl.NonStrictBindOptions()` which includes `AllowMissingVariables` . ## Repro Once can test the before and after behaviour by running `pulumi up --yes` on the following TypeScript program: ```ts import * as pulumi from "@pulumi/pulumi"; import * as random from "@pulumi/random"; export class MyComponent extends pulumi.ComponentResource { public readonly randomPetId: pulumi.Output<string>; constructor(name: string, opts?: pulumi.ComponentResourceOptions) { super("example:index:MyComponent", name, {}, opts); const randomPet = new random.RandomPet("randomPet", {}, { parent: this }); this.randomPetId = randomPet.id; this.registerOutputs({ randomPetId: randomPet.id, }); } } const example = new MyComponent("example"); export const randomPetId = example.randomPetId; ``` Then running `pulumi import -f import.json` where `import.json` contains a resource to be imported under the created component (stack=`dev`, project=`importerrors`) ```ts { "nameTable": { "parentComponent": "urn:pulumi:dev::importerrors::example:index:MyComponent::example" }, "resources": [ { "type": "random:index/randomPassword:RandomPassword", "name": "randomPassword", "id": "supersecret", "parent": "parentComponent" } ] } ``` Running this locally I get the following generated code (which previously failed to generate) ```ts import * as pulumi from "@pulumi/pulumi"; import * as random from "@pulumi/random"; const randomPassword = new random.RandomPassword("randomPassword", { length: 11, lower: true, number: true, numeric: true, special: true, upper: true, }, { parent: parentComponent, }); ```
2024-07-25 13:53:44 +00:00
program map[string]string, loaderTarget string, strict bool,
) (map[string][]byte, hcl.Diagnostics, error) {
if rt.GenerateProgramF != nil {
return rt.GenerateProgramF(program, loaderTarget)
}
panic("unimplemented")
}
func (rt *mockLanguageRuntime) Pack(
Add SupportPack to schemas to write out in the new style (#15713) <!--- 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. --> This adds a new flag to the schema metadata to tell codegen to use the new proposed style of SDKs where we fill in versions and write go.mods etc. I've reworked pack to operate on packages assuming they're in this new style. That is pack no longer has the responsibility to fill in any version information. This updates python and node codegen to write out SDKs in this new style, and fixes their core libraries to still be buildable via pack. There are two approaches to fixing those, I've chosen option 1 below but could pretty easily rework for option 2. 1) Write the version information directly to the SDKs at the same time as we edit the .version file. To simplify this I've added a new 'set-version.py' script that takes a version string an writes it to all the relevant places (.version, package.json, etc). 2) Write "pack" in the language host to search up the directory tree for the ".version" file and then fill in the version information as we we're doing before with envvar tricks and copying and editing package.json. I think 1 is simpler long term, but does force some amount of cleanup in unrelated bits of the system right now (release makefiles need a small edit). 2 is much more localised but keeps this complexity that sdk/nodejs sdk/python aren't actually valid source modules. ## 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. --> - [x] 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. -->
2024-03-22 09:25:46 +00:00
packageDirectory string, destinationDirectory string,
) (string, error) {
if rt.PackF != nil {
Add SupportPack to schemas to write out in the new style (#15713) <!--- 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. --> This adds a new flag to the schema metadata to tell codegen to use the new proposed style of SDKs where we fill in versions and write go.mods etc. I've reworked pack to operate on packages assuming they're in this new style. That is pack no longer has the responsibility to fill in any version information. This updates python and node codegen to write out SDKs in this new style, and fixes their core libraries to still be buildable via pack. There are two approaches to fixing those, I've chosen option 1 below but could pretty easily rework for option 2. 1) Write the version information directly to the SDKs at the same time as we edit the .version file. To simplify this I've added a new 'set-version.py' script that takes a version string an writes it to all the relevant places (.version, package.json, etc). 2) Write "pack" in the language host to search up the directory tree for the ".version" file and then fill in the version information as we we're doing before with envvar tricks and copying and editing package.json. I think 1 is simpler long term, but does force some amount of cleanup in unrelated bits of the system right now (release makefiles need a small edit). 2 is much more localised but keeps this complexity that sdk/nodejs sdk/python aren't actually valid source modules. ## 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. --> - [x] 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. -->
2024-03-22 09:25:46 +00:00
return rt.PackF(packageDirectory, destinationDirectory)
}
panic("unimplemented")
}