-
Notifications
You must be signed in to change notification settings - Fork 787
/
rsh.go
254 lines (227 loc) · 6.42 KB
/
rsh.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package cmd
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/jenkins-x/jx/pkg/log"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
corev1 "k8s.io/api/core/v1"
)
const (
DefaultShell = "/bin/sh"
ShellsFile = "/etc/shells"
defaultRshCommand = "bash"
)
type RshOptions struct {
*CommonOptions
Container string
Namespace string
Pod string
Executable string
ExecCmd string
DevPod bool
Username string
Environment string
stopCh chan struct{}
}
var (
rsh_long = templates.LongDesc(`
Opens a terminal or runs a command in a pods container
`)
rsh_example = templates.Examples(`
# Open a terminal in the first container of the foo deployment's latest pod
jx rsh foo
# Opens a terminal in the cheese container in the latest pod in the foo deployment
jx rsh -c cheese foo
# To connect to one of your DevPods use:
jx rsh -d
# To execute something in the remote shell (like classic rsh or ssh commands)
jx rsh -e 'do something'
`)
)
func NewCmdRsh(commonOpts *CommonOptions) *cobra.Command {
options := &RshOptions{
CommonOptions: commonOpts,
}
cmd := &cobra.Command{
Use: "rsh [deploymentOrPodName]",
Short: "Opens a terminal in a pod or runs a command in the pod",
Long: rsh_long,
Example: rsh_example,
Aliases: []string{"log"},
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Container, "container", "c", "", "The name of the container to log")
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "the namespace to look for the Deployment. Defaults to the current namespace")
cmd.Flags().StringVarP(&options.Namespace, "pod", "p", "", "the pod name to use")
cmd.Flags().StringVarP(&options.Executable, "shell", "s", "", "Path to the shell command")
cmd.Flags().BoolVarP(&options.DevPod, "devpod", "d", false, "Connect to a DevPod")
cmd.Flags().StringVarP(&options.ExecCmd, "execute", "e", defaultRshCommand, "Execute this command on the remote container")
cmd.Flags().StringVarP(&options.Username, "username", "", "", "The username to create the DevPod. If not specified defaults to the current operating system user or $USER'")
cmd.Flags().StringVarP(&options.Environment, "environment", "", "", "The environment in which to look for the Deployment. Defaults to the current environment")
return cmd
}
func (o *RshOptions) Run() error {
args := o.Args
client, curNs, err := o.KubeClientAndNamespace()
if err != nil {
return err
}
ns := o.Namespace
if ns == "" {
ns = curNs
}
if o.Environment != "" {
ns, err = o.findEnvironmentNamespace(o.Environment)
if err != nil {
return err
}
}
if o.ExecCmd == "" {
o.ExecCmd = defaultRshCommand
}
filter := ""
names := []string{}
podsName := "Pods"
pods := map[string]*corev1.Pod{}
if o.DevPod {
podsName = "DevPods"
userName, err := o.getUsername(o.Username)
if err != nil {
return err
}
names, pods, err = kube.GetDevPodNames(client, ns, userName)
if err != nil {
return err
}
} else {
names, err = kube.GetPodNames(client, ns, "")
if err != nil {
return err
}
}
if len(names) == 0 {
if filter == "" {
return fmt.Errorf("There are no %s", podsName)
} else {
return fmt.Errorf("There are no %s matching filter: %s", podsName, filter)
}
}
name := o.Pod
if len(args) == 0 {
if util.StringArrayIndex(names, name) < 0 {
n, err := util.PickName(names, "Pick Pod:", "", o.In, o.Out, o.Err)
if err != nil {
return err
}
name = n
}
} else {
name = args[0]
if util.StringArrayIndex(names, name) < 0 {
// lets try use the name as a filter
filteredNames := []string{}
for _, n := range names {
if strings.Contains(n, name) {
filteredNames = append(filteredNames, n)
}
}
n, err := util.PickName(filteredNames, "Pick Pod:", "", o.In, o.Out, o.Err)
if err != nil {
return err
}
name = n
}
}
if name == "" {
return fmt.Errorf("No pod found for namespace %s with name %s", ns, name)
}
commandArguments := []string{}
if o.Executable == "" {
if o.DevPod {
workingDir := ""
pod := pods[name]
if pod != nil && pod.Annotations != nil {
workingDir = pod.Annotations[kube.AnnotationWorkingDir]
}
if workingDir != "" {
commandArguments = []string{"--", "/bin/sh", "-c", "mkdir -p " + workingDir + "\ncd " + workingDir + "\n" + o.ExecCmd}
} else {
commandArguments = []string{"--", "/bin/sh", "-c", o.ExecCmd}
}
} else {
bash, err := o.detectBash(ns, name, o.Container)
if err != nil {
if o.ExecCmd != "" {
if o.ExecCmd == "bash" {
commandArguments = []string{DefaultShell}
} else {
commandArguments = []string{DefaultShell, "-c", o.ExecCmd}
}
} else {
commandArguments = []string{DefaultShell}
}
} else {
if o.ExecCmd != "" {
if o.ExecCmd == "bash" {
commandArguments = []string{bash}
} else {
commandArguments = []string{"--", bash, "-c", o.ExecCmd}
}
} else {
commandArguments = []string{bash}
}
}
}
}
if len(commandArguments) == 0 {
commandArguments = []string{o.Executable}
}
a := []string{"exec", "-it", "-n", ns}
if o.Container != "" {
a = append(a, "-c", o.Container)
}
a = append(a, name)
if len(args) > 1 {
a = append(a, args[1:]...)
} else if len(commandArguments) > 0 {
a = append(a, commandArguments...)
}
if o.Verbose {
log.Infof("Running command: kubectl %s\n", strings.Join(a, " "))
}
return o.runCommandInteractive(true, "kubectl", a...)
}
func (o *RshOptions) detectBash(ns string, podName string, container string) (string, error) {
fileName := "/tmp/pod_" + podName + "_shells"
args := []string{"cp", ns + "/" + podName + ":" + ShellsFile, fileName}
if container != "" {
args = append(args, "-c", container)
}
err := o.runCommandQuietly("kubectl", args...)
if err != nil {
return "", errors.Wrapf(err, "failed to copy the shell file form POD '%s'", podName)
}
defer os.Remove(fileName)
content, err := ioutil.ReadFile(fileName)
if err != nil {
return "", errors.Wrap(err, "failed to read the copied shell")
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.HasSuffix(line, "bash") {
return line, nil
}
}
return "", fmt.Errorf("no bash found in POD '%s'", podName)
}