pulumi/sdk/go/pulumi-language-go/main_test.go

470 lines
12 KiB
Go
Raw Permalink Normal View History

// Copyright 2016-2021, 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 main
import (
"context"
"flag"
"os"
feat(go/host): Support vendored dependencies The Go language host cannot resolve dependencies or plugins if a Pulumi program vendors its dependencies. BACKGROUND The GetRequiredPlugins and GetProgramDependencies methods of the Go language host rely on the following two commands: go list -m -mod=mod all go list -m -mod=mod ... # '...' means current module and its descendants GetRequiredPlugins additionally searches the source directories for each returned module for pulumi-plugin.json files at a pre-determined paths. $module/pulumi-plugin.json $module/go/pulumi-plugin.json $module/go/*/pulumi-plugin.json This works for most Pulumi programs, except those that vendor private dependencies with 'go mod vendor'. For those programs, the above commands fail because -mod=mod forces them to run in module mode, and their private dependencies are not accessible in module mode (because they are not exposed publicly). We use the -mod=mod flag to force 'go list' to run in module mode because otherwise, it will automatically use vendor mode if a vendor directory is present. However, in vendor mode, the two 'go list' commands above are not supported. The following links add more context on why, but in short: vendor does not have enough information for the general 'go list'. - https://stackoverflow.com/a/60660593, - https://github.com/golang/go/issues/35589#issuecomment-554488544 In short, - list all with -mod=mod fails because the dependency is private - list without -mod=mod will use vendor mode - vendor mode doesn't support the listing all SOLUTION Drop the -mod=mod flag so that 'go list' can decide whether to run in module mode or vendor mode. However, instead of running it with 'all' or '...', pass in a list of dependencies extracted from the go.mod. go list -m import/path1 import/path2 # ... This operation is completely offline in vendor mode so it can list information about private dependencies too. This alone isn't enough though because in vendor mode, the JSON output does not include the module root directory. E.g. % go list -mod=vendor -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "GoVersion": "1.18" } # Versus % go list -mod=mod -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "Time": "2023-02-14T11:04:22Z", "Dir": "[...]/go/pkg/mod/github.com/pulumi/pulumi/sdk/v3@v3.55.0", "GoMod": "[...]/go/pkg/mod/cache/download/github.com/pulumi/pulumi/sdk/v3/@v/v3.55.0.mod", "GoVersion": "1.18" } Therefore, we have to manually calculate the path for each module root. That's easy enough: vendor/$importPath. Lastly, since GetProgramDependencies only needs a dependency list, it now extracts information from the go.mod without calling 'go list'. TESTING Adds a variant of the test added in #12715 that verifies the functionality with vendoring. It removes the sources for the dependencies to simulate private dependencies. The new test fails without the accompanying change. The fix was further manually verified against the reproduction included in #12526. % cd go-output % pulumi plugin rm -a -y % pulumi preview Previewing update (abhinav): Downloading plugin: 15.19 MiB / 15.19 MiB [=========================] 100.00% 0s [resource plugin random-4.8.2] installing Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create % pulumi plugin ls NAME KIND VERSION SIZE INSTALLED LAST USED random resource 4.8.2 33 MB 26 seconds ago 26 seconds ago TOTAL plugin cache size: 33 MB Note that the version of random (4.8.2) is what's specified in the go.mod, not the latest release (v4.12.1). % grep pulumi-random go.mod github.com/pulumi/pulumi-random/sdk/v4 v4.8.2 With the plugin downloaded, I ran this again without an internet connection. % pulumi preview Previewing update (abhinav): Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create This means that if the dependencies are vendored, and the plugin is already available, we won't make additional network requests, which also addresses #7089. Resolves #12526 Resolves #7089
2023-04-20 23:27:39 +00:00
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/testing/iotest"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/fsutil"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseRunParams(t *testing.T) {
t.Parallel()
tests := []struct {
desc string
give []string
want runParams
wantErr string // non-empty if we expect an error
}{
{
desc: "no arguments",
wantErr: "missing required engine RPC address argument",
},
{
desc: "no options",
give: []string{"localhost:1234"},
want: runParams{
engineAddress: "localhost:1234",
},
},
{
desc: "tracing",
give: []string{"-tracing", "foo.trace", "localhost:1234"},
want: runParams{
tracing: "foo.trace",
engineAddress: "localhost:1234",
},
},
{
desc: "binary",
give: []string{"-binary", "foo", "localhost:1234"},
want: runParams{
engineAddress: "localhost:1234",
},
},
{
desc: "buildTarget",
give: []string{"-buildTarget", "foo", "localhost:1234"},
want: runParams{
engineAddress: "localhost:1234",
},
},
{
desc: "root",
give: []string{"-root", "path/to/root", "localhost:1234"},
want: runParams{
engineAddress: "localhost:1234",
},
},
{
desc: "unknown option",
give: []string{"-unknown-option", "bar", "localhost:1234"},
wantErr: "flag provided but not defined: -unknown-option",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.desc, func(t *testing.T) {
t.Parallel()
// Use a FlagSet with ContinueOnError for each case
// instead of using the global flag set.
//
// The global flag set uses flag.ExitOnError,
// so it cannot validate error cases during tests.
fset := flag.NewFlagSet(t.Name(), flag.ContinueOnError)
fset.SetOutput(iotest.LogWriter(t))
got, err := parseRunParams(fset, tt.give)
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
assert.Equal(t, &tt.want, got)
}
})
}
}
func TestGetPlugin(t *testing.T) {
t.Parallel()
cases := []struct {
Name string
Mod *modInfo
Expected *pulumirpc.PluginDependency
ExpectedError string
JSON *plugin.PulumiPluginJSON
JSONPath string
}{
{
Name: "valid-pulumi-mod",
Mod: &modInfo{
Path: "github.com/pulumi/pulumi-aws/sdk",
Version: "v1.29.0",
},
Expected: &pulumirpc.PluginDependency{
Name: "aws",
Version: "v1.29.0",
},
},
{
Name: "pulumi-pseduo-version-plugin",
Mod: &modInfo{
Path: "github.com/pulumi/pulumi-aws/sdk",
Version: "v1.29.1-0.20200403140640-efb5e2a48a86",
},
Expected: &pulumirpc.PluginDependency{
Name: "aws",
Version: "v1.29.0",
},
},
{
Name: "non-pulumi-mod",
Mod: &modInfo{
Path: "github.com/moolumi/pulumi-aws/sdk",
Version: "v1.29.0",
},
ExpectedError: "module is not a pulumi provider",
},
{
Name: "invalid-version-module",
Mod: &modInfo{
Path: "github.com/pulumi/pulumi-aws/sdk",
Version: "42-42-42",
},
ExpectedError: "module does not have semver compatible version",
},
{
Name: "pulumi-pulumi-mod",
Mod: &modInfo{
Path: "github.com/pulumi/pulumi/sdk",
Version: "v1.14.0",
},
ExpectedError: "module is not a pulumi provider",
},
{
Name: "beta-pulumi-module",
Mod: &modInfo{
Path: "github.com/pulumi/pulumi-aws/sdk",
Version: "v2.0.0-beta.1",
},
Expected: &pulumirpc.PluginDependency{
Name: "aws",
Version: "v2.0.0-beta.1",
},
},
{
Name: "non-zero-patch-module", Mod: &modInfo{
Path: "github.com/pulumi/pulumi-kubernetes/sdk",
Version: "v1.5.8",
},
Expected: &pulumirpc.PluginDependency{
Name: "kubernetes",
Version: "v1.5.8",
},
},
{
Name: "pulumiplugin",
Mod: &modInfo{
Path: "github.com/me/myself/i",
Version: "invalid-Version",
},
Expected: &pulumirpc.PluginDependency{
Name: "thing1",
Version: "v1.2.3",
Server: "myserver.com",
},
JSON: &plugin.PulumiPluginJSON{
Resource: true,
Name: "thing1",
Version: "v1.2.3",
Server: "myserver.com",
},
},
{
Name: "non-resource",
Mod: &modInfo{},
ExpectedError: "module is not a pulumi provider",
JSON: &plugin.PulumiPluginJSON{
Resource: false,
},
},
{
Name: "missing-pulumiplugin",
Mod: &modInfo{
Dir: "/not/real",
},
ExpectedError: "module is not a pulumi provider",
JSON: &plugin.PulumiPluginJSON{
Name: "thing2",
Version: "v1.2.3",
},
},
{
Name: "pulumiplugin-go-lookup",
Mod: &modInfo{
Path: "github.com/me/myself",
Version: "v1.2.3",
},
JSON: &plugin.PulumiPluginJSON{
Name: "name",
Resource: true,
},
JSONPath: "go",
Expected: &pulumirpc.PluginDependency{
Name: "name",
Version: "v1.2.3",
},
},
{
Name: "pulumiplugin-go-name-lookup",
Mod: &modInfo{
Path: "github.com/me/myself",
Version: "v1.2.3",
},
JSON: &plugin.PulumiPluginJSON{
Name: "name",
Resource: true,
},
JSONPath: filepath.Join("go", "name"),
Expected: &pulumirpc.PluginDependency{
Name: "name",
Version: "v1.2.3",
},
},
{
Name: "pulumiplugin-nested-too-deep",
Mod: &modInfo{
Path: "path.com/here",
Version: "v0.0",
},
JSONPath: filepath.Join("go", "valid", "invalid"),
JSON: &plugin.PulumiPluginJSON{
Name: "name",
Resource: true,
},
ExpectedError: "module is not a pulumi provider",
},
{
Name: "nested-wrong-folder",
Mod: &modInfo{
Path: "path.com/here",
Version: "v0.0",
},
JSONPath: filepath.Join("invalid", "valid"),
JSON: &plugin.PulumiPluginJSON{
Name: "name",
Resource: true,
},
ExpectedError: "module is not a pulumi provider",
},
}
for _, c := range cases {
c := c
t.Run(c.Name, func(t *testing.T) {
t.Parallel()
cwd := t.TempDir()
fix(host/go): Download external plugins even if they're not imported We previously changed how the Go language host retrieves information about a Go module: before: go list -m -json -mod=mod all after: go list -m -json $importPath1 $importPath1 This change made it possible for us to supprot running in vendored mode which allowed for use of private plugins that are not go-get-able. This uncovered a corner case in the `go` command's behavior when running in module mode: If a package is listed in the go.mod but it's not imported by the current module, `go list -m -json $importPath` will not list its Dir in the output even if it's present in the module cache. For example, given a go.mod file that declares a dependency but code that doesn't import it, as of Go 1.20.5, export GOMODCACHE=$(mktemp -d) go mod download -json go list -m -json $importPath The output of `go mod download` will include information about the dependency and the `Dir` where it was downloaded, but `go list -m` will not. Unfortunately, we can't just use `go mod download` because that breaks vendoring: vendored dependencies cannot always be redownloaded. To resolve this issue, we switch to a two-pass variant to gather this information: - Run `go list -m` to get whatever information we can locally. This will be sufficient for the majority of use cases. - For the handful of cases where the dependency isn't imported, we'll use `go mod download -json` to download them on-demand and get their location from that instead. The `go mod download` step will take place only if we're in module mode. In vendor mode, we'll work with what we have. Resolves #13301
2023-07-11 22:00:40 +00:00
if c.Mod.Dir == "" {
c.Mod.Dir = cwd
}
if c.JSON != nil {
path := filepath.Join(cwd, c.JSONPath)
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
err := os.MkdirAll(path, 0o700)
assert.NoErrorf(t, err, "Failed to setup test folder %s", path)
bytes, err := c.JSON.JSON()
assert.NoError(t, err, "Failed to setup test pulumi-plugin.json")
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
err = os.WriteFile(filepath.Join(path, "pulumi-plugin.json"), bytes, 0o600)
assert.NoError(t, err, "Failed to write pulumi-plugin.json")
}
feat(go/host): Support vendored dependencies The Go language host cannot resolve dependencies or plugins if a Pulumi program vendors its dependencies. BACKGROUND The GetRequiredPlugins and GetProgramDependencies methods of the Go language host rely on the following two commands: go list -m -mod=mod all go list -m -mod=mod ... # '...' means current module and its descendants GetRequiredPlugins additionally searches the source directories for each returned module for pulumi-plugin.json files at a pre-determined paths. $module/pulumi-plugin.json $module/go/pulumi-plugin.json $module/go/*/pulumi-plugin.json This works for most Pulumi programs, except those that vendor private dependencies with 'go mod vendor'. For those programs, the above commands fail because -mod=mod forces them to run in module mode, and their private dependencies are not accessible in module mode (because they are not exposed publicly). We use the -mod=mod flag to force 'go list' to run in module mode because otherwise, it will automatically use vendor mode if a vendor directory is present. However, in vendor mode, the two 'go list' commands above are not supported. The following links add more context on why, but in short: vendor does not have enough information for the general 'go list'. - https://stackoverflow.com/a/60660593, - https://github.com/golang/go/issues/35589#issuecomment-554488544 In short, - list all with -mod=mod fails because the dependency is private - list without -mod=mod will use vendor mode - vendor mode doesn't support the listing all SOLUTION Drop the -mod=mod flag so that 'go list' can decide whether to run in module mode or vendor mode. However, instead of running it with 'all' or '...', pass in a list of dependencies extracted from the go.mod. go list -m import/path1 import/path2 # ... This operation is completely offline in vendor mode so it can list information about private dependencies too. This alone isn't enough though because in vendor mode, the JSON output does not include the module root directory. E.g. % go list -mod=vendor -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "GoVersion": "1.18" } # Versus % go list -mod=mod -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "Time": "2023-02-14T11:04:22Z", "Dir": "[...]/go/pkg/mod/github.com/pulumi/pulumi/sdk/v3@v3.55.0", "GoMod": "[...]/go/pkg/mod/cache/download/github.com/pulumi/pulumi/sdk/v3/@v/v3.55.0.mod", "GoVersion": "1.18" } Therefore, we have to manually calculate the path for each module root. That's easy enough: vendor/$importPath. Lastly, since GetProgramDependencies only needs a dependency list, it now extracts information from the go.mod without calling 'go list'. TESTING Adds a variant of the test added in #12715 that verifies the functionality with vendoring. It removes the sources for the dependencies to simulate private dependencies. The new test fails without the accompanying change. The fix was further manually verified against the reproduction included in #12526. % cd go-output % pulumi plugin rm -a -y % pulumi preview Previewing update (abhinav): Downloading plugin: 15.19 MiB / 15.19 MiB [=========================] 100.00% 0s [resource plugin random-4.8.2] installing Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create % pulumi plugin ls NAME KIND VERSION SIZE INSTALLED LAST USED random resource 4.8.2 33 MB 26 seconds ago 26 seconds ago TOTAL plugin cache size: 33 MB Note that the version of random (4.8.2) is what's specified in the go.mod, not the latest release (v4.12.1). % grep pulumi-random go.mod github.com/pulumi/pulumi-random/sdk/v4 v4.8.2 With the plugin downloaded, I ran this again without an internet connection. % pulumi preview Previewing update (abhinav): Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create This means that if the dependencies are vendored, and the plugin is already available, we won't make additional network requests, which also addresses #7089. Resolves #12526 Resolves #7089
2023-04-20 23:27:39 +00:00
actual, err := c.Mod.getPlugin(t.TempDir())
if c.ExpectedError != "" {
assert.EqualError(t, err, c.ExpectedError)
} else {
// Kind must be resource. We can thus exclude it from the test.
if c.Expected.Kind == "" {
c.Expected.Kind = "resource"
}
assert.NoError(t, err)
assert.Equal(t, c.Expected, actual)
}
})
}
}
func TestPluginsAndDependencies_moduleMode(t *testing.T) {
t.Parallel()
root := t.TempDir()
require.NoError(t,
fsutil.CopyFile(root, filepath.Join("testdata", "sample"), nil),
"copy test data")
testPluginsAndDependencies(t, filepath.Join(root, "prog"))
}
feat(go/host): Support vendored dependencies The Go language host cannot resolve dependencies or plugins if a Pulumi program vendors its dependencies. BACKGROUND The GetRequiredPlugins and GetProgramDependencies methods of the Go language host rely on the following two commands: go list -m -mod=mod all go list -m -mod=mod ... # '...' means current module and its descendants GetRequiredPlugins additionally searches the source directories for each returned module for pulumi-plugin.json files at a pre-determined paths. $module/pulumi-plugin.json $module/go/pulumi-plugin.json $module/go/*/pulumi-plugin.json This works for most Pulumi programs, except those that vendor private dependencies with 'go mod vendor'. For those programs, the above commands fail because -mod=mod forces them to run in module mode, and their private dependencies are not accessible in module mode (because they are not exposed publicly). We use the -mod=mod flag to force 'go list' to run in module mode because otherwise, it will automatically use vendor mode if a vendor directory is present. However, in vendor mode, the two 'go list' commands above are not supported. The following links add more context on why, but in short: vendor does not have enough information for the general 'go list'. - https://stackoverflow.com/a/60660593, - https://github.com/golang/go/issues/35589#issuecomment-554488544 In short, - list all with -mod=mod fails because the dependency is private - list without -mod=mod will use vendor mode - vendor mode doesn't support the listing all SOLUTION Drop the -mod=mod flag so that 'go list' can decide whether to run in module mode or vendor mode. However, instead of running it with 'all' or '...', pass in a list of dependencies extracted from the go.mod. go list -m import/path1 import/path2 # ... This operation is completely offline in vendor mode so it can list information about private dependencies too. This alone isn't enough though because in vendor mode, the JSON output does not include the module root directory. E.g. % go list -mod=vendor -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "GoVersion": "1.18" } # Versus % go list -mod=mod -json -m github.com/pulumi/pulumi/sdk/v3 { "Path": "github.com/pulumi/pulumi/sdk/v3", "Version": "v3.55.0", "Time": "2023-02-14T11:04:22Z", "Dir": "[...]/go/pkg/mod/github.com/pulumi/pulumi/sdk/v3@v3.55.0", "GoMod": "[...]/go/pkg/mod/cache/download/github.com/pulumi/pulumi/sdk/v3/@v/v3.55.0.mod", "GoVersion": "1.18" } Therefore, we have to manually calculate the path for each module root. That's easy enough: vendor/$importPath. Lastly, since GetProgramDependencies only needs a dependency list, it now extracts information from the go.mod without calling 'go list'. TESTING Adds a variant of the test added in #12715 that verifies the functionality with vendoring. It removes the sources for the dependencies to simulate private dependencies. The new test fails without the accompanying change. The fix was further manually verified against the reproduction included in #12526. % cd go-output % pulumi plugin rm -a -y % pulumi preview Previewing update (abhinav): Downloading plugin: 15.19 MiB / 15.19 MiB [=========================] 100.00% 0s [resource plugin random-4.8.2] installing Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create % pulumi plugin ls NAME KIND VERSION SIZE INSTALLED LAST USED random resource 4.8.2 33 MB 26 seconds ago 26 seconds ago TOTAL plugin cache size: 33 MB Note that the version of random (4.8.2) is what's specified in the go.mod, not the latest release (v4.12.1). % grep pulumi-random go.mod github.com/pulumi/pulumi-random/sdk/v4 v4.8.2 With the plugin downloaded, I ran this again without an internet connection. % pulumi preview Previewing update (abhinav): Type Name Plan + pulumi:pulumi:Stack go-output-abhinav create + └─ random:index:RandomId rrr create Resources: + 2 to create This means that if the dependencies are vendored, and the plugin is already available, we won't make additional network requests, which also addresses #7089. Resolves #12526 Resolves #7089
2023-04-20 23:27:39 +00:00
// Test for https://github.com/pulumi/pulumi/issues/12526.
// Validates that if a Pulumi program has vendored its dependencies,
// the language host can still find the plugin and run the program.
func TestPluginsAndDependencies_vendored(t *testing.T) {
t.Parallel()
root := t.TempDir()
require.NoError(t,
fsutil.CopyFile(root, filepath.Join("testdata", "sample"), nil),
"copy test data")
progDir := filepath.Join(root, "prog")
// Vendor the dependencies and nuke the sources
// to ensure that the language host can only use the vendored version.
cmd := exec.Command("go", "mod", "vendor")
cmd.Dir = progDir
cmd.Stdout = iotest.LogWriter(t)
cmd.Stderr = iotest.LogWriter(t)
require.NoError(t, cmd.Run(), "vendor dependencies")
require.NoError(t, os.RemoveAll(filepath.Join(root, "plugin")))
require.NoError(t, os.RemoveAll(filepath.Join(root, "dep")))
require.NoError(t, os.RemoveAll(filepath.Join(root, "indirect-dep")))
testPluginsAndDependencies(t, progDir)
}
// Regression test for https://github.com/pulumi/pulumi/issues/12963.
// Verifies that the language host can find plugins and dependencies
// when the Pulumi program is in a subdirectory of the project root.
func TestPluginsAndDependencies_subdir(t *testing.T) {
t.Parallel()
t.Run("moduleMode", func(t *testing.T) {
t.Parallel()
root := t.TempDir()
require.NoError(t,
fsutil.CopyFile(root, filepath.Join("testdata", "sample"), nil),
"copy test data")
testPluginsAndDependencies(t, filepath.Join(root, "prog-subdir", "infra"))
})
t.Run("vendored", func(t *testing.T) {
t.Parallel()
root := t.TempDir()
require.NoError(t,
fsutil.CopyFile(root, filepath.Join("testdata", "sample"), nil),
"copy test data")
progDir := filepath.Join(root, "prog-subdir", "infra")
// Vendor the dependencies and nuke the sources
// to ensure that the language host can only use the vendored version.
cmd := exec.Command("go", "mod", "vendor")
cmd.Dir = progDir
cmd.Stdout = iotest.LogWriter(t)
cmd.Stderr = iotest.LogWriter(t)
require.NoError(t, cmd.Run(), "vendor dependencies")
require.NoError(t, os.RemoveAll(filepath.Join(root, "plugin")))
require.NoError(t, os.RemoveAll(filepath.Join(root, "dep")))
require.NoError(t, os.RemoveAll(filepath.Join(root, "indirect-dep")))
testPluginsAndDependencies(t, progDir)
})
Fix lookup module deps with go.work files (#15743) <!--- 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/15741. `go list -m` returns all modules in a workspace if inside a Go workspace. We only need the one module found in the Pulumi program directory (or above it). So we set `GOWORK=off` before calling `go list -m`. ## 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-03-21 09:48:04 +00:00
t.Run("gowork", func(t *testing.T) {
t.Parallel()
root := t.TempDir()
require.NoError(t,
fsutil.CopyFile(root, filepath.Join("testdata", "sample"), nil),
"copy test data")
testPluginsAndDependencies(t, filepath.Join(root, "prog-gowork", "prog"))
})
}
func testPluginsAndDependencies(t *testing.T, progDir string) {
Pass root and main info to language host methods (#14654) <!--- 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 is two changes rolled together in a way. Firstly passing some of the data that we pass on language runtime startup to also pass it to Run/GetRequiredPlugins/etc. This is needed for matrix testing, as we only get to start the language runtime up once for that but want to execute multiple programs with it. I feel it's also a little more consistent as we use the language runtimes in other contexts (codegen) where there isn't really a root directory, and aren't any options (and if we did do options the options for codegen are not going to be the same as for execution). It also means we can reuse a language host for shimless and substack programs, as before they heavily relied on their current working directory to calculate paths, and obviosly could only take one set of options at startup. Imagine a shimless python package + a python root program, that would have needed two startups of the python language host to deal with, this unblocks it so we can make the engine smarter and only use one. Secondly renaming some of the fields we pass to Run/GetRequiredPlugins/etc today. `Pwd` and `Program` were not very descriptive and had pretty non-obvious documentation: ``` string pwd = 3; // the program's working directory. string program = 4; // the path to the program to execute. ``` `pwd` will remain, although probably rename it to `working_directory` at some point, because while today we always start programs up with the working directory equal to the program directory that definitely is going to change in the future (at least for MLCs and substack programs). But the name `pwd` doesn't make it clear that this was intended to be the working directory _and_ the directory which contains the program. `program` was in fact nearly always ".", and if it wasn't that it was just a filename. The engine never sent a path for `program` (although we did have some unit tests to check how that worked for the nodejs and python hosts). These are now replaced by a new structure with (I think) more clearly named and documented fields (see ProgramInfo in langauge.proto). The engine still sends the old data for now, we need to update dotnet/yaml/java before we break the old interface and give Virtus Labs a chance to update [besom](https://github.com/VirtusLab/besom). ## 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. --> - [ ] 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-10 17:30:51 +00:00
host := newLanguageHost("0.0.0.0:0", progDir, "")
ctx := context.Background()
t.Run("GetRequiredPlugins", func(t *testing.T) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
res, err := host.GetRequiredPlugins(ctx, &pulumirpc.GetRequiredPluginsRequest{
Clean up project usage (#15154) <!--- 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. --> The project field on `GetProgramDependenciesRequest` and `GetRequiredPluginsRequest` was marked deprecated at the start of December. None of the language runtimes are using this, so this cleans up the engine side code so we don't need to thread a `*workspace.Project` down to the plugin layer to fill in these fields anymore. I haven't fully removed them from the Protobuf structs yet, we probably could but just to give a little more time for people to get a clear usage error if still using it. ## 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-16 17:06:14 +00:00
Project: "deprecated",
Pwd: progDir,
Pass root and main info to language host methods (#14654) <!--- 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 is two changes rolled together in a way. Firstly passing some of the data that we pass on language runtime startup to also pass it to Run/GetRequiredPlugins/etc. This is needed for matrix testing, as we only get to start the language runtime up once for that but want to execute multiple programs with it. I feel it's also a little more consistent as we use the language runtimes in other contexts (codegen) where there isn't really a root directory, and aren't any options (and if we did do options the options for codegen are not going to be the same as for execution). It also means we can reuse a language host for shimless and substack programs, as before they heavily relied on their current working directory to calculate paths, and obviosly could only take one set of options at startup. Imagine a shimless python package + a python root program, that would have needed two startups of the python language host to deal with, this unblocks it so we can make the engine smarter and only use one. Secondly renaming some of the fields we pass to Run/GetRequiredPlugins/etc today. `Pwd` and `Program` were not very descriptive and had pretty non-obvious documentation: ``` string pwd = 3; // the program's working directory. string program = 4; // the path to the program to execute. ``` `pwd` will remain, although probably rename it to `working_directory` at some point, because while today we always start programs up with the working directory equal to the program directory that definitely is going to change in the future (at least for MLCs and substack programs). But the name `pwd` doesn't make it clear that this was intended to be the working directory _and_ the directory which contains the program. `program` was in fact nearly always ".", and if it wasn't that it was just a filename. The engine never sent a path for `program` (although we did have some unit tests to check how that worked for the nodejs and python hosts). These are now replaced by a new structure with (I think) more clearly named and documented fields (see ProgramInfo in langauge.proto). The engine still sends the old data for now, we need to update dotnet/yaml/java before we break the old interface and give Virtus Labs a chance to update [besom](https://github.com/VirtusLab/besom). ## 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. --> - [ ] 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-10 17:30:51 +00:00
Info: &pulumirpc.ProgramInfo{
RootDirectory: progDir,
ProgramDirectory: progDir,
EntryPoint: ".",
},
})
require.NoError(t, err)
require.Len(t, res.Plugins, 1)
plug := res.Plugins[0]
assert.Equal(t, "example", plug.Name, "plugin name")
assert.Equal(t, "v1.2.3", plug.Version, "plugin version")
assert.Equal(t, "resource", plug.Kind, "plugin kind")
assert.Equal(t, "example.com/download", plug.Server, "plugin server")
})
t.Run("GetProgramDependencies", func(t *testing.T) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
res, err := host.GetProgramDependencies(ctx, &pulumirpc.GetProgramDependenciesRequest{
Clean up project usage (#15154) <!--- 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. --> The project field on `GetProgramDependenciesRequest` and `GetRequiredPluginsRequest` was marked deprecated at the start of December. None of the language runtimes are using this, so this cleans up the engine side code so we don't need to thread a `*workspace.Project` down to the plugin layer to fill in these fields anymore. I haven't fully removed them from the Protobuf structs yet, we probably could but just to give a little more time for people to get a clear usage error if still using it. ## 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-16 17:06:14 +00:00
Project: "deprecated",
Pwd: progDir,
TransitiveDependencies: true,
Pass root and main info to language host methods (#14654) <!--- 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 is two changes rolled together in a way. Firstly passing some of the data that we pass on language runtime startup to also pass it to Run/GetRequiredPlugins/etc. This is needed for matrix testing, as we only get to start the language runtime up once for that but want to execute multiple programs with it. I feel it's also a little more consistent as we use the language runtimes in other contexts (codegen) where there isn't really a root directory, and aren't any options (and if we did do options the options for codegen are not going to be the same as for execution). It also means we can reuse a language host for shimless and substack programs, as before they heavily relied on their current working directory to calculate paths, and obviosly could only take one set of options at startup. Imagine a shimless python package + a python root program, that would have needed two startups of the python language host to deal with, this unblocks it so we can make the engine smarter and only use one. Secondly renaming some of the fields we pass to Run/GetRequiredPlugins/etc today. `Pwd` and `Program` were not very descriptive and had pretty non-obvious documentation: ``` string pwd = 3; // the program's working directory. string program = 4; // the path to the program to execute. ``` `pwd` will remain, although probably rename it to `working_directory` at some point, because while today we always start programs up with the working directory equal to the program directory that definitely is going to change in the future (at least for MLCs and substack programs). But the name `pwd` doesn't make it clear that this was intended to be the working directory _and_ the directory which contains the program. `program` was in fact nearly always ".", and if it wasn't that it was just a filename. The engine never sent a path for `program` (although we did have some unit tests to check how that worked for the nodejs and python hosts). These are now replaced by a new structure with (I think) more clearly named and documented fields (see ProgramInfo in langauge.proto). The engine still sends the old data for now, we need to update dotnet/yaml/java before we break the old interface and give Virtus Labs a chance to update [besom](https://github.com/VirtusLab/besom). ## 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. --> - [ ] 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-10 17:30:51 +00:00
Info: &pulumirpc.ProgramInfo{
RootDirectory: progDir,
ProgramDirectory: progDir,
EntryPoint: ".",
},
})
require.NoError(t, err)
gotDeps := make(map[string]string) // name => version
for _, dep := range res.Dependencies {
gotDeps[dep.Name] = dep.Version
}
assert.Equal(t, map[string]string{
"github.com/pulumi/go-dependency-testdata/plugin": "v1.2.3",
"github.com/pulumi/go-dependency-testdata/dep": "v1.6.0",
"github.com/pulumi/go-dependency-testdata/indirect-dep/v2": "v2.1.0",
}, gotDeps)
})
}