pulumi/sdk/go/pulumi-language-go/main.go

1184 lines
35 KiB
Go
Raw Permalink Normal View History

// Copyright 2016-2023, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
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
"strconv"
"strings"
"syscall"
"time"
"github.com/blang/semver"
"github.com/opentracing/opentracing-go"
"golang.org/x/mod/modfile"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
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"
"github.com/pulumi/pulumi/sdk/go/pulumi-language-go/v3/buildutil"
"github.com/pulumi/pulumi/sdk/go/pulumi-language-go/v3/goversion"
"github.com/pulumi/pulumi/sdk/v3/go/common/constant"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/slice"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
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
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/executable"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/rpcutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/version"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
codegen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
hclsyntax "github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/pcl"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
// This function takes a file target to specify where to compile to.
// If `outfile` is "", the binary is compiled to a new temporary file.
// This function returns the path of the file that was produced.
func compileProgram(programDirectory string, outfile string) (string, error) {
goFileSearchPattern := filepath.Join(programDirectory, "*.go")
if matches, err := filepath.Glob(goFileSearchPattern); err != nil || len(matches) == 0 {
return "", fmt.Errorf("Failed to find go files for 'go build' matching %s", goFileSearchPattern)
}
2022-09-14 21:48:09 +00:00
if outfile == "" {
2022-09-14 22:18:30 +00:00
// If no outfile is supplied, write the Go binary to a temporary file.
f, err := os.CreateTemp("", "pulumi-go.*")
2022-09-14 21:48:09 +00:00
if err != nil {
return "", fmt.Errorf("unable to create go program temp file: %w", err)
2022-09-14 21:48:09 +00:00
}
2022-09-14 21:48:09 +00:00
if err := f.Close(); err != nil {
return "", fmt.Errorf("unable to close go program temp file: %w", err)
2022-09-14 21:48:09 +00:00
}
outfile = f.Name()
}
gobin, err := executable.FindExecutable("go")
if err != nil {
return "", fmt.Errorf("unable to find 'go' executable: %w", err)
}
logging.V(5).Infof("Attempting to build go program in %s with: %s build -o %s", programDirectory, gobin, outfile)
buildCmd := exec.Command(gobin, "build", "-o", outfile)
buildCmd.Dir = programDirectory
buildCmd.Stdout, buildCmd.Stderr = os.Stdout, os.Stderr
if err := buildCmd.Run(); err != nil {
return "", fmt.Errorf("unable to run `go build`: %w", err)
}
return outfile, nil
}
// runParams defines the command line arguments accepted by this program.
type runParams struct {
tracing string
engineAddress string
}
// parseRunParams parses the given arguments into a runParams structure,
// using the provided FlagSet.
func parseRunParams(flag *flag.FlagSet, args []string) (*runParams, error) {
var p runParams
flag.StringVar(&p.tracing, "tracing", "", "Emit tracing to a Zipkin-compatible tracing endpoint")
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
flag.String("binary", "", "[obsolete] Look on path for a binary executable with this name")
flag.String("buildTarget", "", "[obsolete] Path to use to output the compiled Pulumi Go program")
flag.String("root", "", "[obsolete] Project root path to use")
if err := flag.Parse(args); err != nil {
return nil, err
}
// Pluck out the engine so we can do logging, etc.
args = flag.Args()
if len(args) == 0 {
return nil, errors.New("missing required engine RPC address argument")
}
p.engineAddress = args[0]
return &p, nil
}
// Launches the language host, which in turn fires up an RPC server implementing the LanguageRuntimeServer endpoint.
func main() {
p, err := parseRunParams(flag.CommandLine, os.Args[1:])
if err != nil {
cmdutil.Exit(err)
}
logging.InitLogging(false, 0, false)
cmdutil.InitTracing("pulumi-language-go", "pulumi-language-go", p.tracing)
var cmd mainCmd
if err := cmd.Run(p); err != nil {
cmdutil.Exit(err)
}
}
type mainCmd struct {
Stdout io.Writer // == os.Stdout
Getwd func() (string, error) // == os.Getwd
}
func (cmd *mainCmd) init() {
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Getwd == nil {
cmd.Getwd = os.Getwd
}
}
func (cmd *mainCmd) Run(p *runParams) error {
cmd.init()
cwd, err := cmd.Getwd()
if err != nil {
return err
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
// map the context Done channel to the rpcutil boolean cancel channel
cancelChannel := make(chan bool)
go func() {
<-ctx.Done()
cancel() // deregister handler so we don't catch another interrupt
close(cancelChannel)
}()
err = rpcutil.Healthcheck(ctx, p.engineAddress, 5*time.Minute, cancel)
if err != nil {
return fmt.Errorf("could not start health check host RPC server: %w", err)
2022-09-14 21:48:09 +00:00
}
// Fire up a gRPC server, letting the kernel choose a free port.
2022-11-01 15:15:09 +00:00
handle, err := rpcutil.ServeWithOptions(rpcutil.ServeOptions{
Cancel: cancelChannel,
Init: func(srv *grpc.Server) error {
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(p.engineAddress, cwd, p.tracing)
pulumirpc.RegisterLanguageRuntimeServer(srv, host)
return nil
},
2022-11-01 15:15:09 +00:00
Options: rpcutil.OpenTracingServerInterceptorOptions(nil),
})
if err != nil {
return fmt.Errorf("could not start language host RPC server: %w", err)
}
// Otherwise, print out the port so that the spawner knows how to reach us.
fmt.Fprintf(cmd.Stdout, "%d\n", handle.Port)
// And finally wait for the server to stop serving.
2022-11-01 15:15:09 +00:00
if err := <-handle.Done; err != nil {
return fmt.Errorf("language host RPC stopped serving: %w", err)
}
return nil
}
// goLanguageHost implements the LanguageRuntimeServer interface for use as an API endpoint.
type goLanguageHost struct {
pulumirpc.UnsafeLanguageRuntimeServer // opt out of forward compat
cwd string
engineAddress string
tracing 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
type goOptions struct {
// Look on path for a binary executable with this name.
binary string
// Path to use to output the compiled Pulumi Go program.
buildTarget string
}
func parseOptions(root string, options map[string]interface{}) (goOptions, error) {
var goOptions goOptions
if binary, ok := options["binary"]; ok {
if binary, ok := binary.(string); ok {
goOptions.binary = binary
} else {
return goOptions, errors.New("binary option must be a string")
}
}
if buildTarget, ok := options["buildTarget"]; ok {
if args, ok := buildTarget.(string); ok {
goOptions.buildTarget = args
} else {
return goOptions, errors.New("buildTarget option must be a string")
}
}
if goOptions.binary != "" && goOptions.buildTarget != "" {
return goOptions, errors.New("binary and buildTarget cannot both be specified")
}
return goOptions, nil
}
func newLanguageHost(engineAddress, cwd, tracing string) pulumirpc.LanguageRuntimeServer {
return &goLanguageHost{
engineAddress: engineAddress,
cwd: cwd,
tracing: tracing,
}
}
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
// modInfo is the useful portion of the output from
// 'go list -m -json' and 'go mod download -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
// with respect to plugin acquisition.
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
// The listed fields are present in both command outputs.
//
// If we add fields that are only present in one or the other,
// we'll need to add a new struct type instead of re-using this.
type modInfo struct {
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
// Path is the module import path.
Path string
// Version of the module.
Version string
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
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
// Dir is the directory holding the source code of the module, if any.
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
Dir string
}
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
// findModuleSources finds the source code roots for the given modules.
//
// gobin is the path to the go binary to use.
// rootModuleDir is the path to the root directory of the program that may import the modules.
// It must contain the go.mod file for the program.
// modulePaths is a list of import paths for the modules to find.
//
// If $rootModuleDir/vendor exists, findModuleSources operates in vendor mode.
// In vendor mode, returned paths are inside the vendor directory exclusively.
func findModuleSources(ctx context.Context, gobin, rootModuleDir string, modulePaths []string) ([]modInfo, error) {
contract.Requiref(gobin != "", "gobin", "must not be empty")
contract.Requiref(rootModuleDir != "", "rootModuleDir", "must not be empty")
if len(modulePaths) == 0 {
return nil, nil
}
// To find the source code for a module, we would typically use
// 'go list -m -json'.
// Its output includes, among other things:
//
// type Module struct {
// ...
// Dir string // directory holding local copy of files, if any
// ...
// }
//
// However, whether Dir is set or not depends on a few different factors.
//
// - If the module is not in the local module cache,
// then Dir is always empty.
// - If the module is imported by the current module, then Dir is set.
// - If the module is not imported,
// then Dir is set if we run with -mod=mod.
// - If the module is not imported and we run without -mod=mod,
// then:
// - If there's a vendor/ directory, then Dir is not set
// because we're running in vendor mode.
// - If there's no vendor/ directory, then Dir is set
// if we add the module to the module cache
// with `go mod download $path`.
//
// These are all corner cases that aren't fully specified,
// and may change between versions of Go.
//
// Therefore, the flow we use is:
//
// - Run 'go list -m -json $path1 $path2 ...'
// to make a first pass at getting module information.
// - If there's a vendor/ directory,
// use the module information from the vendor directory,
// skipping anything that's missing.
// We can't make requests to download modules in vendor mode.
// - Otherwise, for modules with missing Dir fields,
// run `go mod download -json $path` to download them to the module cache
// and get their locations.
modules, err := goListModules(ctx, gobin, rootModuleDir, modulePaths)
if err != nil {
return nil, fmt.Errorf("go list: %w", err)
}
// If there's a vendor directory, then we're in vendor mode.
// In vendor mode, Dir won't be set for any modules.
// Find these modules in the vendor directory.
vendorDir := filepath.Join(rootModuleDir, "vendor")
if _, err := os.Stat(vendorDir); err == nil {
newModules := modules[:0] // in-place filter
for _, module := range modules {
if module.Dir == "" {
vendoredModule := filepath.Join(vendorDir, module.Path)
if _, err := os.Stat(vendoredModule); err == nil {
module.Dir = vendoredModule
}
}
// We can't download modules in vendor mode,
// so we'll skip any modules that aren't already in the vendor directory.
if module.Dir != "" {
newModules = append(newModules, module)
}
}
return newModules, nil
}
// We're not in vendor mode, so we can download modules and fill in missing directories.
var (
// Import paths of modules with no Dir field.
missingDirs []string
// Map from module path to index in modules.
moduleIndex = make(map[string]int, len(modules))
)
for i, module := range modules {
moduleIndex[module.Path] = i
if module.Dir == "" {
missingDirs = append(missingDirs, module.Path)
}
}
// Fill in missing module directories with `go mod download`.
if len(missingDirs) > 0 {
missingMods, err := goModDownload(ctx, gobin, rootModuleDir, missingDirs)
if err != nil {
return nil, fmt.Errorf("go mod download: %w", err)
}
for _, m := range missingMods {
if m.Dir == "" {
continue
}
// If this was a module we were missing,
// then we can fill in the directory now.
if idx, ok := moduleIndex[m.Path]; ok && modules[idx].Dir == "" {
modules[idx].Dir = m.Dir
}
}
}
// Any other modules with no Dir field can be discarded;
// we tried our best to find their source.
newModules := modules[:0] // in-place filter
for _, module := range modules {
if module.Dir != "" {
newModules = append(newModules, module)
}
}
return newModules, nil
}
// Runs 'go list -m' on the given list of modules
// and reports information about them.
func goListModules(ctx context.Context, gobin, dir string, modulePaths []string) ([]modInfo, error) {
args := slice.Prealloc[string](len(modulePaths) + 3)
args = append(args, "list", "-m", "-json")
args = append(args, modulePaths...)
span, ctx := opentracing.StartSpanFromContext(ctx,
gobin+" list -m json",
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
opentracing.Tag{Key: "component", Value: "exec.Command"},
opentracing.Tag{Key: "command", Value: gobin},
opentracing.Tag{Key: "args", Value: args})
defer span.Finish()
cmd := exec.CommandContext(ctx, gobin, args...)
cmd.Dir = dir
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("create stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start command: %w", err)
}
var modules []modInfo
dec := json.NewDecoder(stdout)
for dec.More() {
var info modInfo
if err := dec.Decode(&info); err != nil {
return nil, fmt.Errorf("decode module info: %w", err)
}
modules = append(modules, info)
}
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("wait for command: %w", err)
}
return modules, nil
}
// goModDownload downloads the given modules to the module cache,
// reporting information about them in the returned modInfo.
func goModDownload(ctx context.Context, gobin, dir string, modulePaths []string) ([]modInfo, error) {
args := slice.Prealloc[string](len(modulePaths) + 3)
args = append(args, "mod", "download", "-json")
args = append(args, modulePaths...)
span, ctx := opentracing.StartSpanFromContext(ctx,
gobin+" mod download -json",
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
opentracing.Tag{Key: "component", Value: "exec.Command"},
opentracing.Tag{Key: "command", Value: gobin},
opentracing.Tag{Key: "args", Value: args})
defer span.Finish()
cmd := exec.CommandContext(ctx, gobin, args...)
cmd.Dir = dir
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("create stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start command: %w", err)
}
var modules []modInfo
dec := json.NewDecoder(stdout)
for dec.More() {
var info modInfo
if err := dec.Decode(&info); err != nil {
return nil, fmt.Errorf("decode module info: %w", err)
}
modules = append(modules, info)
}
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("wait for command: %w", err)
}
return modules, nil
}
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
// Returns the pulumi-plugin.json if found.
// If not found, then returns nil, nil.
//
// The lookup path for pulumi-plugin.json is:
//
// - m.Dir
// - m.Dir/go
// - m.Dir/go/*
//
// moduleRoot is the root directory of the module that imports this plugin.
// It is used to resolve the vendor directory.
// moduleRoot may be empty if unknown.
func (m *modInfo) readPulumiPluginJSON(moduleRoot string) (*plugin.PulumiPluginJSON, error) {
dir := m.Dir
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
contract.Assertf(dir != "", "module directory must be known")
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
paths := []string{
filepath.Join(dir, "pulumi-plugin.json"),
filepath.Join(dir, "go", "pulumi-plugin.json"),
}
if path, err := filepath.Glob(filepath.Join(dir, "go", "*", "pulumi-plugin.json")); err == nil {
paths = append(paths, path...)
}
for _, path := range paths {
plugin, err := plugin.LoadPulumiPluginJSON(path)
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
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
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
return plugin, nil
}
return nil, nil
}
func normalizeVersion(version string) (string, error) {
v, err := semver.ParseTolerant(version)
if err != nil {
return "", errors.New("module does not have semver compatible version")
}
// psuedoversions are commits that don't have a corresponding tag at the specified git hash
// https://golang.org/cmd/go/#hdr-Pseudo_versions
// pulumi-aws v1.29.1-0.20200403140640-efb5e2a48a86 (first commit after 1.29.0 release)
if buildutil.IsPseudoVersion(version) {
// no prior tag means there was never a release build
if v.Major == 0 && v.Minor == 0 && v.Patch == 0 {
return "", errors.New("invalid pseduoversion with no prior tag")
}
// patch is typically bumped from the previous tag when using pseudo version
// downgrade the patch by 1 to make sure we match a release that exists
patch := v.Patch
if patch > 0 {
patch--
}
version = fmt.Sprintf("v%v.%v.%v", v.Major, v.Minor, patch)
}
return version, nil
}
// getPlugin loads information about this plugin.
//
// moduleRoot is the root directory of the Go module that imports this plugin.
// It must hold the go.mod file and the vendor directory (if any).
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
func (m *modInfo) getPlugin(moduleRoot string) (*pulumirpc.PluginDependency, error) {
pulumiPlugin, err := m.readPulumiPluginJSON(moduleRoot)
if err != nil {
return nil, fmt.Errorf("failed to load pulumi-plugin.json: %w", err)
}
if (!strings.HasPrefix(m.Path, "github.com/pulumi/pulumi-") && pulumiPlugin == nil) ||
(pulumiPlugin != nil && !pulumiPlugin.Resource) {
return nil, errors.New("module is not a pulumi provider")
}
var name string
if pulumiPlugin != nil && pulumiPlugin.Name != "" {
name = pulumiPlugin.Name
} else {
// github.com/pulumi/pulumi-aws/sdk/... => aws
pluginPart := strings.Split(m.Path, "/")[2]
name = strings.SplitN(pluginPart, "-", 2)[1]
}
version := m.Version
if pulumiPlugin != nil && pulumiPlugin.Version != "" {
version = pulumiPlugin.Version
}
version, err = normalizeVersion(version)
if err != nil {
return nil, err
}
var server string
if pulumiPlugin != nil {
// There is no way to specify server without using `pulumi-plugin.json`.
server = pulumiPlugin.Server
}
plugin := &pulumirpc.PluginDependency{
Name: name,
Version: version,
Kind: "resource",
Server: server,
}
return plugin, nil
}
// Reads and parses the go.mod file for the program at the given path.
// Returns the parsed go.mod file and the path to the module directory.
// Relies on the 'go' command to find the go.mod file for this program.
func (host *goLanguageHost) loadGomod(gobin, programDir string) (modDir string, modFile *modfile.File, err error) {
// Get the path to the go.mod file.
// This may be different from the programDir if the Pulumi program
// is in a subdirectory of the Go module.
//
// The '-f {{.GoMod}}' specifies that the command should print
// just the path to the go.mod file.
//
// type Module struct {
// Path string // module path
// ...
// GoMod string // path to go.mod file
// }
//
// See 'go help list' for the full definition.
cmd := exec.Command(gobin, "list", "-m", "-f", "{{.GoMod}}")
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
// Disable GOWORK, we only want the one module found in this (or a parent) directory. Workspaces being
// enabled will cause "list -m" to list every module in the workspace.
cmd.Env = append(os.Environ(), "GOWORK=off")
cmd.Dir = programDir
cmd.Stderr = os.Stderr
out, err := cmd.Output()
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
if err != nil {
return "", nil, fmt.Errorf("go list -m: %w", err)
}
out = bytes.TrimSpace(out)
if len(out) == 0 {
// The 'go list' command above will exit successfully
// and return no output if the program is not in a Go module.
return "", nil, fmt.Errorf("no go.mod file found: %v", programDir)
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
}
modPath := string(out)
body, err := os.ReadFile(modPath)
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
if err != nil {
return "", nil, err
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
}
f, err := modfile.ParseLax(modPath, body, nil)
if err != nil {
return "", nil, fmt.Errorf("parse: %w", err)
}
return filepath.Dir(modPath), f, nil
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
}
// GetRequiredPlugins computes the complete set of anticipated plugins required by a program.
// We're lenient here as this relies on the `go list` command and the use of modules.
// If the consumer insists on using some other form of dependency management tool like
// dep or glide, the list command fails with "go list -m: not using modules".
// However, we do enforce that go 1.14.0 or higher is installed.
func (host *goLanguageHost) GetRequiredPlugins(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.GetRequiredPluginsRequest,
) (*pulumirpc.GetRequiredPluginsResponse, error) {
logging.V(5).Infof("GetRequiredPlugins: Determining pulumi packages")
gobin, err := executable.FindExecutable("go")
if err != nil {
return nil, fmt.Errorf("couldn't find go binary: %w", err)
}
if err = goversion.CheckMinimumGoVersion(gobin); err != nil {
return nil, err
}
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
moduleDir, gomod, err := host.loadGomod(gobin, req.Info.ProgramDirectory)
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
if err != nil {
// Don't fail if not using Go modules.
logging.V(5).Infof("GetRequiredPlugins: Error reading go.mod: %v", err)
return &pulumirpc.GetRequiredPluginsResponse{}, nil
}
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
modulePaths := slice.Prealloc[string](len(gomod.Require))
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
for _, req := range gomod.Require {
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
modulePaths = append(modulePaths, req.Mod.Path)
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
}
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
modInfos, err := findModuleSources(ctx, gobin, moduleDir, modulePaths)
if err != nil {
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
logging.V(5).Infof("GetRequiredPlugins: Error finding module sources: %v", err)
return &pulumirpc.GetRequiredPluginsResponse{}, nil
}
plugins := []*pulumirpc.PluginDependency{}
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
for _, m := range modInfos {
plugin, err := m.getPlugin(moduleDir)
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
if err != nil {
logging.V(5).Infof(
"GetRequiredPlugins: Ignoring dependency: %s, version: %s, error: %s",
m.Path,
m.Version,
err,
)
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
continue
}
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
logging.V(5).Infof("GetRequiredPlugins: Found plugin name: %s, version: %s", plugin.Name, plugin.Version)
plugins = append(plugins, plugin)
}
return &pulumirpc.GetRequiredPluginsResponse{
Plugins: plugins,
}, nil
}
func runCmdStatus(cmd *exec.Cmd, env []string) (int, error) {
cmd.Env = env
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err := cmd.Run()
// The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and
// exits with a zero exit status.
if err == nil {
return 0, nil
}
// error handling
exiterr, ok := err.(*exec.ExitError)
if !ok {
return 0, fmt.Errorf("command errored unexpectedly: %w", err)
}
// retrieve the status code
status, ok := exiterr.Sys().(syscall.WaitStatus)
if !ok {
return 0, fmt.Errorf("program exited unexpectedly: %w", err)
}
return status.ExitStatus(), nil
}
func runProgram(pwd, bin string, env []string) *pulumirpc.RunResponse {
cmd := exec.Command(bin)
cmd.Dir = pwd
status, err := runCmdStatus(cmd, env)
if err != nil {
return &pulumirpc.RunResponse{
Error: err.Error(),
}
}
if status == 0 {
return &pulumirpc.RunResponse{}
}
// If the program ran, but returned an error,
// the error message should look as nice as possible.
if status == constant.ExitStatusLoggedError {
// program failed but sent an error to the engine
return &pulumirpc.RunResponse{
Bail: true,
}
}
// If the program ran, but exited with a non-zero and non-reserved error code.
// indicate to the user which exit code the program returned.
return &pulumirpc.RunResponse{
Error: fmt.Sprintf("program exited with non-zero exit code: %d", status),
}
}
// Run is RPC endpoint for LanguageRuntimeServer::Run
func (host *goLanguageHost) Run(ctx context.Context, req *pulumirpc.RunRequest) (*pulumirpc.RunResponse, error) {
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
opts, err := parseOptions(req.Info.RootDirectory, req.Info.Options.AsMap())
if err != nil {
return nil, err
}
// Create the environment we'll use to run the process. This is how we pass the RunInfo to the actual
// Go program runtime, to avoid needing any sort of program interface other than just a main entrypoint.
env, err := host.constructEnv(req)
if err != nil {
return nil, fmt.Errorf("failed to prepare environment: %w", err)
}
// the user can explicitly opt in to using a binary executable by specifying
// runtime.options.binary in the Pulumi.yaml
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
if opts.binary != "" {
bin, err := executable.FindExecutable(opts.binary)
if err != nil {
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
return nil, fmt.Errorf("unable to find '%s' executable: %w", opts.binary, err)
}
return runProgram(req.Pwd, bin, env), nil
}
// feature flag to enable deprecated old behavior and use `go run`
if os.Getenv("PULUMI_GO_USE_RUN") != "" {
gobin, err := executable.FindExecutable("go")
if err != nil {
return nil, fmt.Errorf("unable to find 'go' executable: %w", err)
}
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
cmd := exec.Command(gobin, "run", req.Info.ProgramDirectory)
cmd.Dir = host.cwd
status, err := runCmdStatus(cmd, env)
if err != nil {
return &pulumirpc.RunResponse{
Error: err.Error(),
}, nil
}
// `go run` does not return the actual exit status of a program
// it only returns 2 non-zero exit statuses {1, 2}
// and it emits the exit status to stderr
if status != 0 {
return &pulumirpc.RunResponse{
Bail: true,
}, nil
}
return &pulumirpc.RunResponse{}, nil
}
// user did not specify a binary and we will compile and run the binary on-demand
logging.V(5).Infof("No prebuilt executable specified, attempting invocation via compilation")
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
program, err := compileProgram(req.Info.ProgramDirectory, opts.buildTarget)
if err != nil {
return nil, fmt.Errorf("error in compiling Go: %w", err)
}
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
if opts.buildTarget == "" {
2022-09-14 22:18:30 +00:00
// If there is no specified buildTarget, delete the temporary program after running it.
2022-09-14 21:48:09 +00:00
defer os.Remove(program)
}
return runProgram(req.Pwd, program, env), nil
}
// constructEnv constructs an environment for a Go progam by enumerating all of the optional and non-optional
// arguments present in a RunRequest.
func (host *goLanguageHost) constructEnv(req *pulumirpc.RunRequest) ([]string, error) {
config, err := host.constructConfig(req)
if err != nil {
return nil, err
}
configSecretKeys, err := host.constructConfigSecretKeys(req)
if err != nil {
return nil, err
}
env := os.Environ()
maybeAppendEnv := func(k, v string) {
if v != "" {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
}
2022-09-20 08:50:04 +00:00
maybeAppendEnv(pulumi.EnvOrganization, req.GetOrganization())
maybeAppendEnv(pulumi.EnvProject, req.GetProject())
maybeAppendEnv(pulumi.EnvStack, req.GetStack())
maybeAppendEnv(pulumi.EnvConfig, config)
maybeAppendEnv(pulumi.EnvConfigSecretKeys, configSecretKeys)
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
maybeAppendEnv(pulumi.EnvDryRun, strconv.FormatBool(req.GetDryRun()))
maybeAppendEnv(pulumi.EnvParallel, strconv.Itoa(int(req.GetParallel())))
maybeAppendEnv(pulumi.EnvMonitor, req.GetMonitorAddress())
maybeAppendEnv(pulumi.EnvEngine, host.engineAddress)
return env, nil
}
// constructConfig JSON-serializes the configuration data given as part of a RunRequest.
func (host *goLanguageHost) constructConfig(req *pulumirpc.RunRequest) (string, error) {
configMap := req.GetConfig()
if configMap == nil {
return "", nil
}
configJSON, err := json.Marshal(configMap)
if err != nil {
return "", err
}
return string(configJSON), nil
}
// constructConfigSecretKeys JSON-serializes the list of keys that contain secret values given as part of
// a RunRequest.
func (host *goLanguageHost) constructConfigSecretKeys(req *pulumirpc.RunRequest) (string, error) {
configSecretKeys := req.GetConfigSecretKeys()
if configSecretKeys == nil {
return "[]", nil
}
configSecretKeysJSON, err := json.Marshal(configSecretKeys)
if err != nil {
return "", err
}
return string(configSecretKeysJSON), nil
}
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
func (host *goLanguageHost) GetPluginInfo(ctx context.Context, req *emptypb.Empty) (*pulumirpc.PluginInfo, error) {
return &pulumirpc.PluginInfo{
Version: version.Version,
}, nil
}
Move InstallDependencies to the language plugin (#9294) * Move InstallDependencies to the language plugin This changes `pulumi new` and `pulumi up <template>` to invoke the language plugin to install dependencies, rather than having the code to install dependencies hardcoded into the cli itself. This does not change the way policypacks or plugin dependencies are installed. In theory we can make pretty much the same change to just invoke the language plugin, but baby steps we don't need to make that change at the same time as this. We used to feed the result of these install commands (dotnet build, npm install, etc) directly through to the CLI stdout/stderr. To mostly maintain that behaviour the InstallDependencies gRCP method streams back bytes to be written to stdout/stderr, those bytes are either read from pipes or a pty that we run the install commands with. The use of a pty is controlled by the global colorisation option in the cli. An alternative designs was to use the Engine interface to Log the results of install commands. This renders very differently to just writing directly to the standard outputs and I don't think would support control codes so well. The design as is means that `npm install` for example is still able to display a progress bar and colors even though we're running it in a separate process and streaming its output back via gRPC. The only "oddity" I feel that's fallen out of this work is that InstallDependencies for python used to overwrite the virtualenv runtime option. It looks like this was because our templates don't bother setting that. Because InstallDependencies doesn't have the project file, and at any rate will be used for policy pack projects in the future, I've moved that logic into `pulumi new` when it mutates the other project file settings. I think we should at some point cleanup so the templates correctly indicate to use a venv, or maybe change python to assume a virtual env of "venv" if none is given? * Just warn if pty fails to open * Add tests and return real tty files * Add to CHANGELOG * lint * format * Test strings * Log pty opening for trace debugging * s/Hack/Workaround * Use termios * Tweak terminal test * lint * Fix windows build
2022-04-03 14:54:59 +00:00
func (host *goLanguageHost) InstallDependencies(
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.InstallDependenciesRequest, server pulumirpc.LanguageRuntime_InstallDependenciesServer,
) error {
closer, stdout, stderr, err := rpcutil.MakeInstallDependenciesStreams(server, req.IsTerminal)
Move InstallDependencies to the language plugin (#9294) * Move InstallDependencies to the language plugin This changes `pulumi new` and `pulumi up <template>` to invoke the language plugin to install dependencies, rather than having the code to install dependencies hardcoded into the cli itself. This does not change the way policypacks or plugin dependencies are installed. In theory we can make pretty much the same change to just invoke the language plugin, but baby steps we don't need to make that change at the same time as this. We used to feed the result of these install commands (dotnet build, npm install, etc) directly through to the CLI stdout/stderr. To mostly maintain that behaviour the InstallDependencies gRCP method streams back bytes to be written to stdout/stderr, those bytes are either read from pipes or a pty that we run the install commands with. The use of a pty is controlled by the global colorisation option in the cli. An alternative designs was to use the Engine interface to Log the results of install commands. This renders very differently to just writing directly to the standard outputs and I don't think would support control codes so well. The design as is means that `npm install` for example is still able to display a progress bar and colors even though we're running it in a separate process and streaming its output back via gRPC. The only "oddity" I feel that's fallen out of this work is that InstallDependencies for python used to overwrite the virtualenv runtime option. It looks like this was because our templates don't bother setting that. Because InstallDependencies doesn't have the project file, and at any rate will be used for policy pack projects in the future, I've moved that logic into `pulumi new` when it mutates the other project file settings. I think we should at some point cleanup so the templates correctly indicate to use a venv, or maybe change python to assume a virtual env of "venv" if none is given? * Just warn if pty fails to open * Add tests and return real tty files * Add to CHANGELOG * lint * format * Test strings * Log pty opening for trace debugging * s/Hack/Workaround * Use termios * Tweak terminal test * lint * Fix windows build
2022-04-03 14:54:59 +00:00
if err != nil {
return err
}
// best effort close, but we try an explicit close and error check at the end as well
defer closer.Close()
stdout.Write([]byte("Installing dependencies...\n\n"))
gobin, err := executable.FindExecutable("go")
if err != nil {
return err
}
if err = goversion.CheckMinimumGoVersion(gobin); err != nil {
return err
}
cmd := exec.Command(gobin, "mod", "tidy", "-compat=1.18")
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
cmd.Dir = req.Info.ProgramDirectory
Move InstallDependencies to the language plugin (#9294) * Move InstallDependencies to the language plugin This changes `pulumi new` and `pulumi up <template>` to invoke the language plugin to install dependencies, rather than having the code to install dependencies hardcoded into the cli itself. This does not change the way policypacks or plugin dependencies are installed. In theory we can make pretty much the same change to just invoke the language plugin, but baby steps we don't need to make that change at the same time as this. We used to feed the result of these install commands (dotnet build, npm install, etc) directly through to the CLI stdout/stderr. To mostly maintain that behaviour the InstallDependencies gRCP method streams back bytes to be written to stdout/stderr, those bytes are either read from pipes or a pty that we run the install commands with. The use of a pty is controlled by the global colorisation option in the cli. An alternative designs was to use the Engine interface to Log the results of install commands. This renders very differently to just writing directly to the standard outputs and I don't think would support control codes so well. The design as is means that `npm install` for example is still able to display a progress bar and colors even though we're running it in a separate process and streaming its output back via gRPC. The only "oddity" I feel that's fallen out of this work is that InstallDependencies for python used to overwrite the virtualenv runtime option. It looks like this was because our templates don't bother setting that. Because InstallDependencies doesn't have the project file, and at any rate will be used for policy pack projects in the future, I've moved that logic into `pulumi new` when it mutates the other project file settings. I think we should at some point cleanup so the templates correctly indicate to use a venv, or maybe change python to assume a virtual env of "venv" if none is given? * Just warn if pty fails to open * Add tests and return real tty files * Add to CHANGELOG * lint * format * Test strings * Log pty opening for trace debugging * s/Hack/Workaround * Use termios * Tweak terminal test * lint * Fix windows build
2022-04-03 14:54:59 +00:00
cmd.Env = os.Environ()
cmd.Stdout, cmd.Stderr = stdout, stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("`go mod tidy` failed to install dependencies: %w", err)
}
stdout.Write([]byte("Finished installing dependencies\n\n"))
all: Fix revive issues Fixes the following issues found by revive included in the latest release of golangci-lint. Full list of issues: **pkg** ``` backend/display/object_diff.go:47:10: superfluous-else: if block ends with a break statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) backend/display/object_diff.go:716:12: redefines-builtin-id: redefinition of the built-in function delete (revive) backend/display/object_diff.go:742:14: redefines-builtin-id: redefinition of the built-in function delete (revive) backend/display/object_diff.go:983:10: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (revive) backend/httpstate/backend.go:1814:4: redefines-builtin-id: redefinition of the built-in function cap (revive) backend/httpstate/backend.go:1824:5: redefines-builtin-id: redefinition of the built-in function cap (revive) backend/httpstate/client/client.go:444:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) backend/httpstate/client/client.go:455:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) cmd/pulumi/org.go:113:4: if-return: redundant if ...; err != nil check, just return error instead. (revive) cmd/pulumi/util.go:216:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) codegen/docs/gen.go:428:2: redefines-builtin-id: redefinition of the built-in function copy (revive) codegen/hcl2/model/expression.go:2151:5: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:151:2: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:329:3: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:381:5: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/nodejs/gen.go:1367:5: redefines-builtin-id: redefinition of the built-in function copy (revive) codegen/python/gen_program_expressions.go:136:2: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/python/gen_program_expressions.go:142:3: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/report/report.go:126:6: redefines-builtin-id: redefinition of the built-in function panic (revive) codegen/schema/docs_test.go:210:10: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) codegen/schema/schema.go:790:2: redefines-builtin-id: redefinition of the built-in type any (revive) codegen/schema/schema.go:793:4: redefines-builtin-id: redefinition of the built-in type any (revive) resource/deploy/plan.go:506:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) resource/deploy/snapshot_test.go:59:3: redefines-builtin-id: redefinition of the built-in function copy (revive) resource/deploy/state_builder.go:108:2: redefines-builtin-id: redefinition of the built-in function copy (revive) ``` **sdk** ``` go/common/resource/plugin/context.go:142:2: redefines-builtin-id: redefinition of the built-in function copy (revive) go/common/resource/plugin/plugin.go:142:12: superfluous-else: if block ends with a break statement, so drop this else and outdent its block (revive) go/common/resource/properties_diff.go:114:2: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:117:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:122:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:127:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:132:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/util/deepcopy/copy.go:30:1: redefines-builtin-id: redefinition of the built-in function copy (revive) go/common/workspace/creds.go:242:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi-language-go/main.go:569:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi-language-go/main.go:706:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi/run_test.go:925:2: redefines-builtin-id: redefinition of the built-in type any (revive) go/pulumi/run_test.go:933:3: redefines-builtin-id: redefinition of the built-in type any (revive) nodejs/cmd/pulumi-language-nodejs/main.go:778:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/cmd/pulumi-language-python/main.go:1011:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/cmd/pulumi-language-python/main.go:863:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/python.go:230:2: redefines-builtin-id: redefinition of the built-in function print (revive) ``` **tests** ``` integration/integration_util_test.go:282:11: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) ```
2023-03-20 23:48:02 +00:00
return closer.Close()
Move InstallDependencies to the language plugin (#9294) * Move InstallDependencies to the language plugin This changes `pulumi new` and `pulumi up <template>` to invoke the language plugin to install dependencies, rather than having the code to install dependencies hardcoded into the cli itself. This does not change the way policypacks or plugin dependencies are installed. In theory we can make pretty much the same change to just invoke the language plugin, but baby steps we don't need to make that change at the same time as this. We used to feed the result of these install commands (dotnet build, npm install, etc) directly through to the CLI stdout/stderr. To mostly maintain that behaviour the InstallDependencies gRCP method streams back bytes to be written to stdout/stderr, those bytes are either read from pipes or a pty that we run the install commands with. The use of a pty is controlled by the global colorisation option in the cli. An alternative designs was to use the Engine interface to Log the results of install commands. This renders very differently to just writing directly to the standard outputs and I don't think would support control codes so well. The design as is means that `npm install` for example is still able to display a progress bar and colors even though we're running it in a separate process and streaming its output back via gRPC. The only "oddity" I feel that's fallen out of this work is that InstallDependencies for python used to overwrite the virtualenv runtime option. It looks like this was because our templates don't bother setting that. Because InstallDependencies doesn't have the project file, and at any rate will be used for policy pack projects in the future, I've moved that logic into `pulumi new` when it mutates the other project file settings. I think we should at some point cleanup so the templates correctly indicate to use a venv, or maybe change python to assume a virtual env of "venv" if none is given? * Just warn if pty fails to open * Add tests and return real tty files * Add to CHANGELOG * lint * format * Test strings * Log pty opening for trace debugging * s/Hack/Workaround * Use termios * Tweak terminal test * lint * Fix windows build
2022-04-03 14:54:59 +00:00
}
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
func (host *goLanguageHost) About(ctx context.Context, req *emptypb.Empty) (*pulumirpc.AboutResponse, error) {
getResponse := func(execString string, args ...string) (string, string, error) {
ex, err := executable.FindExecutable(execString)
if err != nil {
return "", "", fmt.Errorf("could not find executable '%s': %w", execString, err)
}
cmd := exec.Command(ex, args...)
cmd.Dir = host.cwd
var out []byte
if out, err = cmd.Output(); err != nil {
cmd := ex
if len(args) != 0 {
cmd += " " + strings.Join(args, " ")
}
return "", "", fmt.Errorf("failed to execute '%s'", cmd)
}
return ex, strings.TrimSpace(string(out)), nil
}
goexe, version, err := getResponse("go", "version")
if err != nil {
return nil, err
}
return &pulumirpc.AboutResponse{
Executable: goexe,
Version: version,
}, nil
}
func (host *goLanguageHost) GetProgramDependencies(
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
ctx context.Context, req *pulumirpc.GetProgramDependenciesRequest,
) (*pulumirpc.GetProgramDependenciesResponse, error) {
gobin, err := executable.FindExecutable("go")
if err != nil {
return nil, fmt.Errorf("couldn't find go binary: %w", err)
}
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
_, gomod, err := host.loadGomod(gobin, req.Info.ProgramDirectory)
if err != nil {
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
return nil, fmt.Errorf("load go.mod: %w", err)
}
result := slice.Prealloc[*pulumirpc.DependencyInfo](len(gomod.Require))
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
for _, d := range gomod.Require {
if !d.Indirect || req.TransitiveDependencies {
datum := pulumirpc.DependencyInfo{
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
Name: d.Mod.Path,
Version: d.Mod.Version,
}
result = append(result, &datum)
}
}
return &pulumirpc.GetProgramDependenciesResponse{
Dependencies: result,
}, nil
}
func (host *goLanguageHost) RunPlugin(
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.RunPluginRequest, server pulumirpc.LanguageRuntime_RunPluginServer,
) error {
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
logging.V(5).Infof("Attempting to run go plugin in %s", req.Info.ProgramDirectory)
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
program, err := compileProgram(req.Info.ProgramDirectory, "")
if err != nil {
return fmt.Errorf("error in compiling Go: %w", err)
}
defer os.Remove(program)
closer, stdout, stderr, err := rpcutil.MakeRunPluginStreams(server, false)
if err != nil {
return err
}
// best effort close, but we try an explicit close and error check at the end as well
defer closer.Close()
cmd := exec.Command(program, req.Args...)
cmd.Dir = req.Pwd
cmd.Env = req.Env
cmd.Stdout, cmd.Stderr = stdout, stderr
if err = cmd.Run(); err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
err = server.Send(&pulumirpc.RunPluginResponse{
Output: &pulumirpc.RunPluginResponse_Exitcode{Exitcode: int32(status.ExitStatus())},
})
} else {
err = fmt.Errorf("program exited unexpectedly: %w", exiterr)
}
} else {
return fmt.Errorf("problem executing plugin program (could not run language executor): %w", err)
}
}
if err != nil {
return err
}
all: Fix revive issues Fixes the following issues found by revive included in the latest release of golangci-lint. Full list of issues: **pkg** ``` backend/display/object_diff.go:47:10: superfluous-else: if block ends with a break statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) backend/display/object_diff.go:716:12: redefines-builtin-id: redefinition of the built-in function delete (revive) backend/display/object_diff.go:742:14: redefines-builtin-id: redefinition of the built-in function delete (revive) backend/display/object_diff.go:983:10: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (revive) backend/httpstate/backend.go:1814:4: redefines-builtin-id: redefinition of the built-in function cap (revive) backend/httpstate/backend.go:1824:5: redefines-builtin-id: redefinition of the built-in function cap (revive) backend/httpstate/client/client.go:444:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) backend/httpstate/client/client.go:455:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) cmd/pulumi/org.go:113:4: if-return: redundant if ...; err != nil check, just return error instead. (revive) cmd/pulumi/util.go:216:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) codegen/docs/gen.go:428:2: redefines-builtin-id: redefinition of the built-in function copy (revive) codegen/hcl2/model/expression.go:2151:5: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:151:2: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:329:3: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/hcl2/syntax/comments.go:381:5: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/nodejs/gen.go:1367:5: redefines-builtin-id: redefinition of the built-in function copy (revive) codegen/python/gen_program_expressions.go:136:2: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/python/gen_program_expressions.go:142:3: redefines-builtin-id: redefinition of the built-in function close (revive) codegen/report/report.go:126:6: redefines-builtin-id: redefinition of the built-in function panic (revive) codegen/schema/docs_test.go:210:10: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) codegen/schema/schema.go:790:2: redefines-builtin-id: redefinition of the built-in type any (revive) codegen/schema/schema.go:793:4: redefines-builtin-id: redefinition of the built-in type any (revive) resource/deploy/plan.go:506:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) resource/deploy/snapshot_test.go:59:3: redefines-builtin-id: redefinition of the built-in function copy (revive) resource/deploy/state_builder.go:108:2: redefines-builtin-id: redefinition of the built-in function copy (revive) ``` **sdk** ``` go/common/resource/plugin/context.go:142:2: redefines-builtin-id: redefinition of the built-in function copy (revive) go/common/resource/plugin/plugin.go:142:12: superfluous-else: if block ends with a break statement, so drop this else and outdent its block (revive) go/common/resource/properties_diff.go:114:2: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:117:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:122:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:127:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/resource/properties_diff.go:132:4: redefines-builtin-id: redefinition of the built-in function len (revive) go/common/util/deepcopy/copy.go:30:1: redefines-builtin-id: redefinition of the built-in function copy (revive) go/common/workspace/creds.go:242:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi-language-go/main.go:569:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi-language-go/main.go:706:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) go/pulumi/run_test.go:925:2: redefines-builtin-id: redefinition of the built-in type any (revive) go/pulumi/run_test.go:933:3: redefines-builtin-id: redefinition of the built-in type any (revive) nodejs/cmd/pulumi-language-nodejs/main.go:778:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/cmd/pulumi-language-python/main.go:1011:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/cmd/pulumi-language-python/main.go:863:2: if-return: redundant if ...; err != nil check, just return error instead. (revive) python/python.go:230:2: redefines-builtin-id: redefinition of the built-in function print (revive) ``` **tests** ``` integration/integration_util_test.go:282:11: superfluous-else: if block ends with a continue statement, so drop this else and outdent its block (move short variable declaration to its own line if necessary) (revive) ```
2023-03-20 23:48:02 +00:00
return closer.Close()
}
func (host *goLanguageHost) GenerateProject(
ctx context.Context, req *pulumirpc.GenerateProjectRequest,
) (*pulumirpc.GenerateProjectResponse, error) {
loader, err := schema.NewLoaderClient(req.LoaderTarget)
if err != nil {
return nil, err
}
var extraOptions []pcl.BindOption
if !req.Strict {
extraOptions = append(extraOptions, pcl.NonStrictBindOptions()...)
}
program, diags, err := pcl.BindDirectory(req.SourceDirectory, loader, extraOptions...)
if err != nil {
return nil, err
}
2023-05-26 10:32:19 +00:00
rpcDiagnostics := plugin.HclDiagnosticsToRPCDiagnostics(diags)
if diags.HasErrors() {
2023-05-26 10:32:19 +00:00
return &pulumirpc.GenerateProjectResponse{
Diagnostics: rpcDiagnostics,
}, nil
}
if program == nil {
return nil, errors.New("internal error: program was nil")
}
var project workspace.Project
if err := json.Unmarshal([]byte(req.Project), &project); err != nil {
return nil, err
}
err = codegen.GenerateProject(req.TargetDirectory, project, program, req.LocalDependencies)
if err != nil {
return nil, err
}
2023-05-26 10:32:19 +00:00
return &pulumirpc.GenerateProjectResponse{
Diagnostics: rpcDiagnostics,
}, nil
}
func (host *goLanguageHost) GenerateProgram(
ctx context.Context, req *pulumirpc.GenerateProgramRequest,
) (*pulumirpc.GenerateProgramResponse, error) {
loader, err := schema.NewLoaderClient(req.LoaderTarget)
if err != nil {
return nil, err
}
parser := hclsyntax.NewParser()
// Load all .pp files in the directory
for path, contents := range req.Source {
err = parser.ParseFile(strings.NewReader(contents), path)
if err != nil {
return nil, err
}
diags := parser.Diagnostics
if diags.HasErrors() {
return nil, diags
}
}
program, diags, err := pcl.BindProgram(parser.Files, pcl.Loader(loader))
if err != nil {
return nil, err
}
rpcDiagnostics := plugin.HclDiagnosticsToRPCDiagnostics(diags)
if diags.HasErrors() {
return &pulumirpc.GenerateProgramResponse{
Diagnostics: rpcDiagnostics,
}, nil
}
if program == nil {
return nil, errors.New("internal error: program was nil")
}
files, diags, err := codegen.GenerateProgram(program)
if err != nil {
return nil, err
}
rpcDiagnostics = append(rpcDiagnostics, plugin.HclDiagnosticsToRPCDiagnostics(diags)...)
return &pulumirpc.GenerateProgramResponse{
Source: files,
Diagnostics: rpcDiagnostics,
}, nil
}
func (host *goLanguageHost) GeneratePackage(
ctx context.Context, req *pulumirpc.GeneratePackageRequest,
) (*pulumirpc.GeneratePackageResponse, error) {
if len(req.ExtraFiles) > 0 {
return nil, errors.New("overlays are not supported for Go")
}
loader, err := schema.NewLoaderClient(req.LoaderTarget)
if err != nil {
return nil, err
}
var spec schema.PackageSpec
err = json.Unmarshal([]byte(req.Schema), &spec)
if err != nil {
return nil, err
}
pkg, diags, err := schema.BindSpec(spec, loader)
if err != nil {
return nil, err
}
Return diagnostics from GeneratePackage (#14661) <!--- 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/14660. Fairly simple change to bring the GeneratePackage RPC method into alignment with the other codegen methods and use returned diagnostics rather than just error values. `gen-sdk` is updated to print those diagnostics, and the python/node/go runtimes updated to return the diagnostics from schema binding as diagnostics rather than just an error value. Might be worth at some point seeing if the rest of package generation could use diagnostics rather than error values, but that's a larger lift. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-12-05 17:47:52 +00:00
rpcDiagnostics := plugin.HclDiagnosticsToRPCDiagnostics(diags)
if diags.HasErrors() {
Return diagnostics from GeneratePackage (#14661) <!--- 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/14660. Fairly simple change to bring the GeneratePackage RPC method into alignment with the other codegen methods and use returned diagnostics rather than just error values. `gen-sdk` is updated to print those diagnostics, and the python/node/go runtimes updated to return the diagnostics from schema binding as diagnostics rather than just an error value. Might be worth at some point seeing if the rest of package generation could use diagnostics rather than error values, but that's a larger lift. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-12-05 17:47:52 +00:00
return &pulumirpc.GeneratePackageResponse{
Diagnostics: rpcDiagnostics,
}, nil
}
files, err := codegen.GeneratePackage("pulumi-language-go", pkg)
if err != nil {
return nil, err
}
for filename, data := range files {
outPath := filepath.Join(req.Directory, filename)
err := os.MkdirAll(filepath.Dir(outPath), 0o700)
if err != nil {
return nil, fmt.Errorf("could not create output directory %s: %w", filepath.Dir(filename), err)
}
err = os.WriteFile(outPath, data, 0o600)
if err != nil {
return nil, fmt.Errorf("could not write output file %s: %w", filename, err)
}
}
Return diagnostics from GeneratePackage (#14661) <!--- 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/14660. Fairly simple change to bring the GeneratePackage RPC method into alignment with the other codegen methods and use returned diagnostics rather than just error values. `gen-sdk` is updated to print those diagnostics, and the python/node/go runtimes updated to return the diagnostics from schema binding as diagnostics rather than just an error value. Might be worth at some point seeing if the rest of package generation could use diagnostics rather than error values, but that's a larger lift. ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [ ] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [x] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2023-12-05 17:47:52 +00:00
return &pulumirpc.GeneratePackageResponse{
Diagnostics: rpcDiagnostics,
}, nil
}
func (host *goLanguageHost) Pack(ctx context.Context, req *pulumirpc.PackRequest) (*pulumirpc.PackResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Pack not implemented")
}