generated from brevdev/seed
-
Notifications
You must be signed in to change notification settings - Fork 9
/
portforward.go
139 lines (119 loc) · 4.21 KB
/
portforward.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package portforward
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"github.com/brevdev/brev-cli/pkg/cmd/cmderrors"
"github.com/brevdev/brev-cli/pkg/cmd/completions"
"github.com/brevdev/brev-cli/pkg/cmd/refresh"
"github.com/brevdev/brev-cli/pkg/cmd/util"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"github.com/brevdev/brev-cli/pkg/terminal"
"github.com/spf13/cobra"
)
var (
sshLinkLong = "Port forward your Brev machine's port to your local port"
sshLinkExample = "brev port-forward <ws_name> -p local_port:remote_port"
)
type PortforwardStore interface {
completions.CompletionStore
refresh.RefreshStore
util.GetWorkspaceByNameOrIDErrStore
util.MakeWorkspaceWithMetaStore
}
func NewCmdPortForwardSSH(pfStore PortforwardStore, t *terminal.Terminal) *cobra.Command {
var port string
cmd := &cobra.Command{
Annotations: map[string]string{"ssh": ""},
Use: "port-forward",
DisableFlagsInUseLine: true,
Short: "Enable a local tunnel",
Long: sshLinkLong,
Example: sshLinkExample,
Args: cmderrors.TransformToValidationError(cobra.ExactArgs(1)),
ValidArgsFunction: completions.GetAllWorkspaceNameCompletionHandler(pfStore, t),
RunE: func(cmd *cobra.Command, args []string) error {
if port == "" {
port = startInput(t)
}
err := RunPortforward(pfStore, args[0], port)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
},
}
cmd.Flags().StringVarP(&port, "port", "p", "", "port forward flag describe me better")
err := cmd.RegisterFlagCompletionFunc("port", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoSpace
})
if err != nil {
breverrors.GetDefaultErrorReporter().ReportError(breverrors.WrapAndTrace(err))
fmt.Print(breverrors.WrapAndTrace(err))
}
return cmd
}
func RunPortforward(pfStore PortforwardStore, nameOrID string, portString string) error {
var portSplit []string
if strings.Contains(portString, ":") {
portSplit = strings.Split(portString, ":")
if len(portSplit) != 2 {
return breverrors.NewValidationError("port format invalid, use local_port:remote_port")
}
} else {
return breverrors.NewValidationError("port format invalid, use local_port:remote_port")
}
res := refresh.RunRefreshAsync(pfStore)
sshName, err := ConvertNametoSSHName(pfStore, nameOrID)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = res.Await()
if err != nil {
return breverrors.WrapAndTrace(err)
}
_, err = RunSSHPortForward("-L", portSplit[0], portSplit[1], sshName)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func ConvertNametoSSHName(store PortforwardStore, workspaceNameOrID string) (string, error) {
workspace, err := util.GetUserWorkspaceByNameOrIDErr(store, workspaceNameOrID)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
sshName := string(workspace.GetLocalIdentifier())
return sshName, nil
}
func RunSSHPortForward(forwardType string, localPort string, remotePort string, sshName string) (*os.Process, error) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
defer signal.Stop(signals)
portMapping := fmt.Sprintf("%s:127.0.0.1:%s", localPort, remotePort)
cmdSHH := exec.Command("ssh", "-T", forwardType, portMapping, sshName, "-N") //nolint:gosec // variables are sanitzed or user specified
cmdSHH.Stdin = os.Stdin
fmt.Println("portforwarding...")
fmt.Printf("localhost:%s -> %s:%s\n", localPort, sshName, remotePort)
out, err := cmdSHH.CombinedOutput()
if err != nil {
return nil, breverrors.WrapAndTrace(err, string(out))
}
return cmdSHH.Process, nil
}
func startInput(t *terminal.Terminal) string {
t.Vprint(t.Yellow("\nPorts flag was omitted, running interactive mode!\n"))
remoteInput := terminal.PromptGetInput(terminal.PromptContent{
Label: "What port on your Brev machine would you like to forward?",
ErrorMsg: "error",
})
localInput := terminal.PromptGetInput(terminal.PromptContent{
Label: "What port should it be on your local machine?",
ErrorMsg: "error",
})
port := localInput + ":" + remoteInput
t.Vprintf(t.Green("\n-p " + port + "\n"))
return port
}