Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/local-app/cmd/workspace-ssh.go
2497 views
1
// Copyright (c) 2023 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"fmt"
10
"log/slog"
11
"time"
12
13
"github.com/bufbuild/connect-go"
14
v1 "github.com/gitpod-io/gitpod/components/public-api/go/experimental/v1"
15
"github.com/gitpod-io/local-app/pkg/helper"
16
"github.com/spf13/cobra"
17
)
18
19
var workspaceSSHOpts struct {
20
DryRun bool
21
NoImplicitStart bool
22
}
23
24
// workspaceSSHCmd connects to a given workspace
25
var workspaceSSHCmd = &cobra.Command{
26
Use: "ssh <workspace-id>",
27
Short: "Connects to a workspace via SSH",
28
Args: cobra.MinimumNArgs(1),
29
Example: ` # connect to workspace with current terminal session
30
$ gitpod workspace ssh <workspace-id>
31
32
# Execute a command through SSH
33
$ gitpod workspace ssh <workspace-id> -- ls -la
34
$ gitpod ws ssh <workspace-id> -- -t watch date
35
36
# Get all SSH features with --dry-run
37
$ $(gitpod workspace ssh <workspace-id> --dry-run) -- ls -la
38
$ $(gitpod workspace ssh <workspace-id> --dry-run) -t watch date`,
39
RunE: func(cmd *cobra.Command, args []string) error {
40
cmd.SilenceUsage = true
41
42
ctx, cancel := context.WithTimeout(cmd.Context(), 5*time.Minute)
43
defer cancel()
44
45
workspaceID := args[0]
46
47
gitpod, err := getGitpodClient(cmd.Context())
48
if err != nil {
49
return err
50
}
51
52
ws, err := gitpod.Workspaces.GetWorkspace(ctx, connect.NewRequest(&v1.GetWorkspaceRequest{WorkspaceId: workspaceID}))
53
if err != nil {
54
return err
55
}
56
57
if ws.Msg.Result.Status.Instance.Status.Phase != v1.WorkspaceInstanceStatus_PHASE_RUNNING {
58
if workspaceSSHOpts.NoImplicitStart {
59
return fmt.Errorf("workspace is not running")
60
}
61
slog.Info("workspace is not running, starting it...")
62
_, err := gitpod.Workspaces.StartWorkspace(ctx, connect.NewRequest(&v1.StartWorkspaceRequest{WorkspaceId: workspaceID}))
63
if err != nil {
64
return err
65
}
66
_, err = helper.ObserveWorkspaceUntilStarted(ctx, gitpod, workspaceID)
67
if err != nil {
68
return err
69
}
70
}
71
72
dashDashIndex := cmd.ArgsLenAtDash()
73
74
sshArgs := []string{}
75
if dashDashIndex != -1 {
76
sshArgs = args[dashDashIndex:]
77
}
78
79
return helper.SSHConnectToWorkspace(cmd.Context(), gitpod, workspaceID, workspaceSSHOpts.DryRun, sshArgs...)
80
},
81
}
82
83
func init() {
84
workspaceCmd.AddCommand(workspaceSSHCmd)
85
workspaceSSHCmd.Flags().BoolVarP(&workspaceSSHOpts.DryRun, "dry-run", "n", false, "Dry run the command")
86
workspaceSSHCmd.Flags().BoolVarP(&workspaceSSHOpts.NoImplicitStart, "no-implicit-start", "", false, "Do not start the workspace if it is not running")
87
}
88
89