Repository navigation
feat(container): show SSH connection information #1581
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
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
452e1b2
feat(container): show connection and current checkout information
atty303 5757a34
fix(container): use the shared table formatter for info
atty303 25e7bc3
fix(container): recognize no-checkout diagnostics after Git trace output
atty303 600bd19
refactor(container): limit info to SSH connection details
atty303 f30f5b6
ci: run container info in the existing integration job
atty303 ac873bb
refactor(container): simplify command constructor name
atty303 48b8876
test(container): focus assertions on SSH connection output
atty303 4e34436
refactor(container): expose info through the public command
atty303 5f731c8
refactor(container): move public commands into their own package
atty303 84a102a
test(container): align coverage with the existing test layout
atty303 ef184ff
test(container): verify info in the workspace-up test
atty303 d3e6770
test(container): use the fixture user as the expected value
atty303 c66f170
test(container): group root integration coverage by command
atty303 a5da8f7
fix(container): chain the root pre-run hook for container commands
skevetter c3ea588
fix(compose): inject workspace identity env into compose services
skevetter 2da222b
docs(container): clarify SSH alias, remote VM and compose recreate ca…
skevetter 3a42b58
test(compose): use constants for repeated workspace identity literals
skevetter 67579d1
test(container): reset EnvHome in info failure test
skevetter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package container | ||
|
|
||
| import ( | ||
| "github.com/devsy-org/devsy/cmd/flags" | ||
| "github.com/devsy-org/devsy/pkg/envfile" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| // NewContainerCmd returns the container command. Cobra runs only the nearest | ||
| // persistent pre-run hook, so the root hook is chained explicitly to keep | ||
| // log-level validation and context-deletion recovery in effect. | ||
| func NewContainerCmd( | ||
| globalFlags *flags.GlobalFlags, | ||
| rootPreRunE func(*cobra.Command, []string) error, | ||
| ) *cobra.Command { | ||
| cmd := &cobra.Command{ | ||
| Use: "container", | ||
| Short: "Inspect the current container", | ||
| PersistentPreRunE: func(command *cobra.Command, args []string) error { | ||
| envfile.Apply() | ||
| if rootPreRunE != nil { | ||
| return rootPreRunE(command, args) | ||
| } | ||
| return nil | ||
| }, | ||
| } | ||
| cmd.AddCommand(newInfoCmd(globalFlags)) | ||
| return cmd | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| package container | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "strings" | ||
|
|
||
| "al.essio.dev/pkg/shellescape" | ||
| "github.com/devsy-org/devsy/cmd/flags" | ||
| "github.com/devsy-org/devsy/pkg/clierr" | ||
| "github.com/devsy-org/devsy/pkg/config" | ||
| devconfig "github.com/devsy-org/devsy/pkg/devcontainer/config" | ||
| "github.com/devsy-org/devsy/pkg/output" | ||
| "github.com/devsy-org/devsy/pkg/table" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| type containerInfo struct { | ||
| SSHCommand string `json:"sshCommand"` | ||
| SSHHost string `json:"sshHost"` | ||
| RemoteUser string `json:"remoteUser"` | ||
| } | ||
|
|
||
| func newInfoCmd(globalFlags *flags.GlobalFlags) *cobra.Command { | ||
| return &cobra.Command{ | ||
| Use: "info", | ||
| Short: "Show this container's SSH connection information", | ||
| Args: cobra.NoArgs, | ||
| RunE: func(cmd *cobra.Command, _ []string) error { | ||
| mode, err := output.ResolveMode(globalFlags.ResultFormat) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| info, err := readContainerInfo(cmd.Context()) | ||
| if err != nil { | ||
| classified := clierr.Classify(err) | ||
| if classified.Code == clierr.CodeUnknown { | ||
| classified.Code = "container_info_failed" | ||
| } | ||
| return classified | ||
| } | ||
| return writeContainerInfo(cmd.OutOrStdout(), mode, info) | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func readContainerInfo(ctx context.Context) (*containerInfo, error) { | ||
| workspaceID := os.Getenv(config.EnvWorkspaceID) | ||
| if workspaceID == "" { | ||
| return nil, fmt.Errorf( | ||
| "%s is missing; Devsy workspace identity is unavailable here. "+ | ||
| "recreate Docker Compose containers created before it was injected", | ||
| config.EnvWorkspaceID, | ||
| ) | ||
| } | ||
| result, err := readInfoSetupResult(ctx) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| info := &containerInfo{ | ||
| SSHHost: workspaceID + config.SSHHostSuffix, | ||
| RemoteUser: devconfig.GetRemoteUser(result), | ||
| } | ||
| info.SSHCommand = "ssh " + shellescape.Quote(info.RemoteUser+"@"+info.SSHHost) | ||
| return info, nil | ||
| } | ||
|
|
||
| func readInfoSetupResult(ctx context.Context) (*devconfig.Result, error) { | ||
| command := exec.CommandContext(ctx, "sh") | ||
| command.Args = append(command.Args, "-c", config.ReadDevContainerResultCommand()) | ||
| raw, err := command.Output() | ||
| if err != nil { | ||
| if exit, ok := errors.AsType[*exec.ExitError](err); ok { | ||
| return nil, fmt.Errorf( | ||
| "read selected container setup result: %w: %s", | ||
| err, | ||
| strings.TrimSpace(string(exit.Stderr)), | ||
| ) | ||
| } | ||
| return nil, fmt.Errorf("read selected container setup result: %w", err) | ||
| } | ||
| result := &devconfig.Result{} | ||
| if err := json.Unmarshal(raw, result); err != nil { | ||
| return nil, fmt.Errorf("parse container setup result: %w", err) | ||
| } | ||
| if result.MergedConfig == nil || result.ContainerDetails == nil || result.Error != "" { | ||
| return nil, fmt.Errorf("container setup result is incomplete or failed") | ||
| } | ||
| return result, nil | ||
| } | ||
|
|
||
| func writeContainerInfo(w io.Writer, mode string, info *containerInfo) error { | ||
| if mode == output.ModeJSON { | ||
| return json.NewEncoder(w).Encode(info) | ||
| } | ||
| rows := [][]string{ | ||
| {"SSH command", info.SSHCommand}, | ||
| {"SSH host", info.SSHHost}, | ||
| {"Remote user", info.RemoteUser}, | ||
| } | ||
| _, err := fmt.Fprintln(w, table.Render([]string{"Field", "Value"}, rows)) | ||
| return err | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package container | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "os" | ||
| "path/filepath" | ||
| "runtime" | ||
| "testing" | ||
|
|
||
| "al.essio.dev/pkg/shellescape" | ||
| "github.com/devsy-org/devsy/cmd/flags" | ||
| "github.com/devsy-org/devsy/pkg/clierr" | ||
| "github.com/devsy-org/devsy/pkg/config" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const ( | ||
| infoWorkspaceID = "test-workspace" | ||
| infoIncompleteResult = "incomplete or failed" | ||
| infoSetupFixture = `{ | ||
| "MergedConfig":{"remoteUser":"configured-user","containerUser":"other-user","remoteEnv":{"TOKEN":"do-not-output"}}, | ||
| "ContainerDetails":{"Config":{"User":"image-user"}} | ||
| }` | ||
| ) | ||
|
|
||
| func containerInfoFixture(t *testing.T, result string) string { | ||
| t.Helper() | ||
| if runtime.GOOS == "windows" { | ||
| t.Skip("container commands require sh") | ||
| } | ||
| dir := t.TempDir() | ||
| fixture := filepath.Join(dir, "setup-result.json") | ||
| require.NoError(t, os.WriteFile(fixture, []byte(result), 0o600)) | ||
| script := "#!/bin/sh\nexec /bin/cat " + shellescape.Quote(fixture) + "\n" | ||
| file, err := os.CreateTemp(dir, "sh-*") | ||
| require.NoError(t, err) | ||
| _, err = file.WriteString(script) | ||
| require.NoError(t, err) | ||
| require.NoError(t, file.Chmod(0o700)) | ||
| require.NoError(t, file.Close()) | ||
| require.NoError(t, os.Symlink(file.Name(), filepath.Join(dir, "sh"))) | ||
| t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) | ||
| t.Setenv(config.EnvWorkspaceID, infoWorkspaceID) | ||
| t.Setenv("DEVSY_UI", "") | ||
| t.Setenv("LC_ALL", "C") | ||
| t.Setenv("USER", "wrong-os-user") | ||
| t.Setenv("LOGNAME", "wrong-os-user") | ||
| return fixture | ||
| } | ||
|
|
||
| func executeContainerInfo(t *testing.T, format string) (string, error) { | ||
| t.Helper() | ||
| command := newInfoCmd(&flags.GlobalFlags{ResultFormat: format}) | ||
| command.SetContext(t.Context()) | ||
| var out bytes.Buffer | ||
| command.SetOut(&out) | ||
| command.SetErr(&out) | ||
| err := command.RunE(command, nil) | ||
| return out.String(), err | ||
| } | ||
|
|
||
| func TestContainerInfo(t *testing.T) { | ||
| containerInfoFixture(t, infoSetupFixture) | ||
| raw, err := executeContainerInfo(t, "json") | ||
| require.NoError(t, err) | ||
| var got map[string]any | ||
| require.NoError(t, json.Unmarshal([]byte(raw), &got)) | ||
| require.Equal(t, map[string]any{ | ||
| "sshCommand": "ssh configured-user@test-workspace.devsy", | ||
| "sshHost": "test-workspace.devsy", "remoteUser": "configured-user", | ||
| }, got) | ||
| text, err := executeContainerInfo(t, "plain") | ||
| require.NoError(t, err) | ||
| for _, value := range []string{ | ||
| "Field", "Value", "SSH command", "SSH host", "Remote user", | ||
| "ssh configured-user@test-workspace.devsy", | ||
| } { | ||
| require.Contains(t, text, value) | ||
| } | ||
| for _, omitted := range []string{"do-not-output", "wrong-os-user"} { | ||
| require.NotContains(t, text, omitted) | ||
| } | ||
| } | ||
|
|
||
| func TestContainerInfoSetupFailures(t *testing.T) { | ||
| for _, tt := range []struct{ name, result, workspaceID, want string }{ | ||
| {"missing workspace", infoSetupFixture, "", config.EnvWorkspaceID}, | ||
| {"invalid JSON", "{", infoWorkspaceID, "parse container setup result"}, | ||
| {"null result", "null", infoWorkspaceID, infoIncompleteResult}, | ||
| {"missing config", `{"ContainerDetails":{}}`, infoWorkspaceID, infoIncompleteResult}, | ||
| {"missing container", `{"MergedConfig":{}}`, infoWorkspaceID, infoIncompleteResult}, | ||
| { | ||
| "failed setup", `{"MergedConfig":{},"ContainerDetails":{},"Error":"private-error"}`, | ||
| infoWorkspaceID, infoIncompleteResult, | ||
| }, | ||
| } { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| containerInfoFixture(t, tt.result) | ||
| t.Setenv(config.EnvWorkspaceID, tt.workspaceID) | ||
| raw, err := executeContainerInfo(t, "json") | ||
| require.ErrorContains(t, err, tt.want) | ||
| require.Empty(t, raw) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestContainerInfoReadFailure(t *testing.T) { | ||
| fixture := containerInfoFixture(t, infoSetupFixture) | ||
| require.NoError(t, os.Remove(fixture)) | ||
| raw, err := executeContainerInfo(t, "json") | ||
| require.ErrorContains(t, err, "read selected container setup result") | ||
| require.ErrorContains(t, err, "No such file or directory") | ||
| require.Equal(t, clierr.Code("container_info_failed"), clierr.Classify(err).Code) | ||
| require.Empty(t, raw) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "os" | ||
| "testing" | ||
|
|
||
| "github.com/devsy-org/devsy/pkg/config" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const ( | ||
| containerCommandName = "container" | ||
| infoCommandName = "info" | ||
| ) | ||
|
|
||
| func TestContainerInfoFailureRendering(t *testing.T) { | ||
| t.Setenv(config.EnvWorkspaceID, "") | ||
| // --home sets process-wide EnvHome; register a restore before it leaks. | ||
| t.Setenv(config.EnvHome, "") | ||
| root, _ := BuildRoot() | ||
| var out bytes.Buffer | ||
| root.SetOut(&out) | ||
| root.SetArgs([]string{ | ||
| containerCommandName, infoCommandName, "--home", t.TempDir(), | ||
| "--context", "not-configured", "--provider", "not-configured", "--result-format", "json", | ||
| }) | ||
| err := root.Execute() | ||
| require.ErrorContains(t, err, config.EnvWorkspaceID) | ||
| require.Empty(t, out.String()) | ||
| for _, machine := range []bool{false, true} { | ||
| reader, writer, pipeErr := os.Pipe() | ||
| require.NoError(t, pipeErr) | ||
| original := os.Stderr | ||
| os.Stderr = writer | ||
| code := exitCodeForError(err, machine) | ||
| os.Stderr = original | ||
| require.NoError(t, writer.Close()) | ||
| raw, readErr := io.ReadAll(reader) | ||
| require.NoError(t, readErr) | ||
| require.NoError(t, reader.Close()) | ||
| require.Equal(t, 1, code) | ||
| require.Contains(t, string(raw), config.EnvWorkspaceID) | ||
| require.Contains(t, string(raw), "container_info_failed") | ||
| } | ||
| } | ||
|
|
||
| func TestContainerInfoRunsRootValidation(t *testing.T) { | ||
| t.Setenv(config.EnvWorkspaceID, "") | ||
| root, _ := BuildRoot() | ||
| root.SetArgs([]string{ | ||
| containerCommandName, infoCommandName, "--log-level", "definitely-invalid", | ||
| }) | ||
| err := root.Execute() | ||
| require.ErrorContains(t, err, "invalid log level") | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.