Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to specify gcloud configuration directory in tests. #1750

Merged
merged 1 commit into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions integration_test/agents/agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -727,10 +727,10 @@ func windowsEnvironment(environment map[string]string) string {
// about PackageLocation, see the documentation for the PackageLocation struct.
func InstallOpsAgent(ctx context.Context, logger *log.Logger, vm *gce.VM, location PackageLocation) error {
if location.packagesInGCS != "" && location.repoSuffix != "" {
return fmt.Errorf("invalid PackageLocation: cannot provide both location.packagesInGCS and location.repoSuffix. location=%#v")
return fmt.Errorf("invalid PackageLocation: cannot provide both location.packagesInGCS and location.repoSuffix. location=%#v", location)
}
if location.artifactRegistryRegion != "" && location.repoSuffix == "" {
return fmt.Errorf("invalid PackageLocation: location.artifactRegistryRegion was nonempty yet location.repoSuffix was empty. location=%#v")
return fmt.Errorf("invalid PackageLocation: location.artifactRegistryRegion was nonempty yet location.repoSuffix was empty. location=%#v", location)
}

if location.packagesInGCS != "" {
Expand Down Expand Up @@ -851,6 +851,7 @@ func CommonSetupWithExtraCreateArgumentsAndMetadata(t *testing.T, imageSpec stri
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), gce.SuggestedTimeout)
t.Cleanup(cancel)
ctx = gce.WithGcloudConfigDir(ctx, t.TempDir())

logger := gce.SetupLogger(t)
logger.ToMainLog().Println("Calling SetupVM(). For details, see VM_initialization.txt.")
Expand Down
31 changes: 27 additions & 4 deletions integration_test/gce/gce_testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func init() {
log.Fatalf("init() failed to make a temporary directory for ssh keys: %v", err)
}
privateKeyFile = filepath.Join(keysDir, "gce_testing_key")
if _, err := runCommand(ctx, log.Default(), nil, []string{"ssh-keygen", "-t", "rsa", "-f", privateKeyFile, "-C", sshUserName, "-N", ""}); err != nil {
if _, err := runCommand(ctx, log.Default(), nil, []string{"ssh-keygen", "-t", "rsa", "-f", privateKeyFile, "-C", sshUserName, "-N", ""}, nil); err != nil {
log.Fatalf("init() failed to generate new public+private key pair: %v", err)
}
publicKeyFile = privateKeyFile + ".pub"
Expand Down Expand Up @@ -699,7 +699,8 @@ func (writer *ThreadSafeWriter) Write(p []byte) (int, error) {
// and stderr, and an error if the binary had a nonzero exit code.
// args is a slice containing the binary to invoke along with all its arguments,
// e.g. {"echo", "hello"}.
func runCommand(ctx context.Context, logger *log.Logger, stdin io.Reader, args []string) (CommandOutput, error) {
// env is a map containing environment variables to set for the command.
func runCommand(ctx context.Context, logger *log.Logger, stdin io.Reader, args []string, env map[string]string) (CommandOutput, error) {
var output CommandOutput
if len(args) < 1 {
return output, fmt.Errorf("runCommand() needs a nonempty argument slice, got %v", args)
Expand All @@ -715,6 +716,13 @@ func runCommand(ctx context.Context, logger *log.Logger, stdin io.Reader, args [
interleavedWriter := &ThreadSafeWriter{guarded: &interleavedBuilder}
cmd.Stdout = io.MultiWriter(&stdoutBuilder, interleavedWriter)
cmd.Stderr = io.MultiWriter(&stderrBuilder, interleavedWriter)
if len(env) > 0 {
environment := []string{}
for k, v := range env {
environment = append(environment, fmt.Sprintf("%s=%s", k, v))
}
cmd.Env = environment
}

err := cmd.Run()

Expand All @@ -731,6 +739,17 @@ func runCommand(ctx context.Context, logger *log.Logger, stdin io.Reader, args [
return output, err
}

const (
gcloudConfigDirKey = "__gcloud_config_dir__"
)

// WithGcloudConfigDir returns a context that records the desired value of the
// gcloud configuration directory. Invoking RunGcloud with that context will
// set the configuration directory for the gcloud command to that value.
func WithGcloudConfigDir(ctx context.Context, directory string) context.Context {
return context.WithValue(ctx, gcloudConfigDirKey, directory)
}

// RunGcloud invokes a gcloud binary from runfiles and waits until it finishes.
// Returns the stdout and stderr and an error if the binary had a nonzero exit
// code. args is a slice containing the arguments to pass to gcloud.
Expand All @@ -741,7 +760,11 @@ func runCommand(ctx context.Context, logger *log.Logger, stdin io.Reader, args [
// http://go/sdi-gcloud-vs-api
func RunGcloud(ctx context.Context, logger *log.Logger, stdin string, args []string) (CommandOutput, error) {
logger.Printf("Running command: gcloud %v", args)
return runCommand(ctx, logger, strings.NewReader(stdin), append([]string{gcloudPath}, args...))
env := make(map[string]string)
if configDir := ctx.Value(gcloudConfigDirKey); configDir != nil {
env["CLOUDSDK_CONFIG"] = configDir.(string)
}
return runCommand(ctx, logger, strings.NewReader(stdin), append([]string{gcloudPath}, args...), env)
}

var (
Expand Down Expand Up @@ -816,7 +839,7 @@ func RunRemotelyStdin(ctx context.Context, logger *log.Logger, vm *VM, stdin io.
args = append(args, "-oIdentityFile="+privateKeyFile)
args = append(args, sshOptions...)
args = append(args, wrappedCommand)
return runCommand(ctx, logger, stdin, args)
return runCommand(ctx, logger, stdin, args, nil)
}

// UploadContent takes an io.Reader and uploads its contents as a file to a
Expand Down
1 change: 1 addition & 0 deletions integration_test/gce/gce_testing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func SetupLoggerAndVM(t *testing.T, platform string) (context.Context, *logging.
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), gce.SuggestedTimeout)
t.Cleanup(cancel)
ctx = gce.WithGcloudConfigDir(ctx, t.TempDir())

logger := gce.SetupLogger(t)
options := gce.VMOptions{
Expand Down
1 change: 1 addition & 0 deletions integration_test/third_party_apps_test/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,7 @@ func TestThirdPartyApps(t *testing.T) {

ctx, cancel := context.WithTimeout(context.Background(), gce.SuggestedTimeout)
defer cancel()
ctx = gce.WithGcloudConfigDir(ctx, t.TempDir())

var err error
for attempt := 1; attempt <= 4; attempt++ {
Expand Down
Loading