-
Notifications
You must be signed in to change notification settings - Fork 7
/
cmd.go
123 lines (98 loc) · 2.48 KB
/
cmd.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
package exec
import (
"fmt"
"io"
"io/ioutil"
v1 "k8s.io/api/core/v1"
)
// Config contains all Kubernetes configuration
type Config struct {
Kubeconfig string
Namespace string
Name string
Image string
Secrets []Secret
}
// Secret represents a Kubernetes secret to pass into the pod as env variable
type Secret struct {
EnvVarName string
SecretName string
SecretKey string
}
// Cmd represents the command to execute inside the pod
type Cmd struct {
Path string
Args []string
//Env []string
Dir string
Cfg Config
pod *v1.Pod
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// Command returns the Cmd struct to execute the named program with
// the given arguments.
func Command(cfg Config, name string, arg ...string) *Cmd {
return &Cmd{
Cfg: cfg,
Path: name,
Args: arg,
}
}
// Start starts the specified command but does not wait for it to complete.
func (cmd *Cmd) Start() error {
pod, err := createPod(cmd.Cfg, []string{cmd.Path}, cmd.Args)
if err != nil {
return fmt.Errorf("cannot create pod: %v", err)
}
cmd.pod = pod
return nil
}
// Wait waits for the command to exit and waits for any copying to
// stdin or copying from stdout or stderr to complete.
//
// The command must have been started by Start.
func (cmd *Cmd) Wait() error {
if cmd.Stdin == nil {
cmd.Stdin = ioutil.NopCloser(nil)
}
if cmd.Stdout == nil {
cmd.Stdout = ioutil.Discard
}
if cmd.Stderr == nil {
cmd.Stderr = ioutil.Discard
}
// wait for pod to be running
waitPod(cmd.Cfg.Kubeconfig, cmd.pod)
attachOptions := &v1.PodAttachOptions{
Stdin: cmd.Stdin != ioutil.NopCloser(nil),
Stdout: cmd.Stdout != ioutil.Discard,
// For k8s 1.9 - see https://github.com/kubernetes/kubernetes/pull/52686
//Stderr: cmd.Stderr != ioutil.Discard,
Stderr: true,
TTY: false,
}
err := attach(cmd.Cfg.Kubeconfig, cmd.pod, attachOptions, cmd.Stdin, cmd.Stdout, cmd.Stderr)
if err != nil {
return fmt.Errorf("cannot attach: %v", err)
}
return nil
}
// Run starts the specified command and waits for it to complete.
func (cmd *Cmd) Run() error {
err := cmd.Start()
if err != nil {
return fmt.Errorf("cannot start command: %v", err)
}
return cmd.Wait()
}
// StdinPipe returns a pipe that will be connected to the command's standard input
// when the command starts.
//
// Different than os/exec.StdinPipe, returned io.WriteCloser should be closed by user.
func (cmd *Cmd) StdinPipe() (io.WriteCloser, error) {
pr, pw := io.Pipe()
cmd.Stdin = pr
return pw, nil
}