-
Notifications
You must be signed in to change notification settings - Fork 0
/
pod_command_executor.go
205 lines (165 loc) · 5.38 KB
/
pod_command_executor.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
/*
Copyright 2017 the Velero contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package podexec
import (
"bytes"
"net/url"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1api "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
kscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
api "github.com/adi-bhardwaj/velero-modified/pkg/apis/velero/v1"
)
const defaultTimeout = 30 * time.Second
// PodCommandExecutor is capable of executing a command in a container in a pod.
type PodCommandExecutor interface {
// ExecutePodCommand executes a command in a container in a pod. If the command takes longer than
// the specified timeout, an error is returned.
ExecutePodCommand(log logrus.FieldLogger, item map[string]interface{}, namespace, name, hookName string, hook *api.ExecHook) error
}
type poster interface {
Post() *rest.Request
}
type defaultPodCommandExecutor struct {
restClientConfig *rest.Config
restClient poster
streamExecutorFactory streamExecutorFactory
}
// NewPodCommandExecutor creates a new PodCommandExecutor.
func NewPodCommandExecutor(restClientConfig *rest.Config, restClient poster) PodCommandExecutor {
return &defaultPodCommandExecutor{
restClientConfig: restClientConfig,
restClient: restClient,
streamExecutorFactory: &defaultStreamExecutorFactory{},
}
}
// ExecutePodCommand uses the pod exec API to execute a command in a container in a pod. If the
// command takes longer than the specified timeout, an error is returned (NOTE: it is not currently
// possible to ensure the command is terminated when the timeout occurs, so it may continue to run
// in the background).
func (e *defaultPodCommandExecutor) ExecutePodCommand(log logrus.FieldLogger, item map[string]interface{}, namespace, name, hookName string, hook *api.ExecHook) error {
if item == nil {
return errors.New("item is required")
}
if namespace == "" {
return errors.New("namespace is required")
}
if name == "" {
return errors.New("name is required")
}
if hookName == "" {
return errors.New("hookName is required")
}
if hook == nil {
return errors.New("hook is required")
}
pod := new(corev1api.Pod)
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(item, pod); err != nil {
return errors.WithStack(err)
}
if hook.Container == "" {
if err := setDefaultHookContainer(pod, hook); err != nil {
return err
}
} else if err := ensureContainerExists(pod, hook.Container); err != nil {
return err
}
if len(hook.Command) == 0 {
return errors.New("command is required")
}
switch hook.OnError {
case api.HookErrorModeFail, api.HookErrorModeContinue:
// use the specified value
default:
// default to fail
hook.OnError = api.HookErrorModeFail
}
if hook.Timeout.Duration == 0 {
hook.Timeout.Duration = defaultTimeout
}
hookLog := log.WithFields(
logrus.Fields{
"hookName": hookName,
"hookContainer": hook.Container,
"hookCommand": hook.Command,
"hookOnError": hook.OnError,
"hookTimeout": hook.Timeout,
},
)
hookLog.Info("running exec hook")
req := e.restClient.Post().
Resource("pods").
Namespace(namespace).
Name(name).
SubResource("exec")
req.VersionedParams(&corev1api.PodExecOptions{
Container: hook.Container,
Command: hook.Command,
Stdout: true,
Stderr: true,
}, kscheme.ParameterCodec)
executor, err := e.streamExecutorFactory.NewSPDYExecutor(e.restClientConfig, "POST", req.URL())
if err != nil {
return err
}
var stdout, stderr bytes.Buffer
streamOptions := remotecommand.StreamOptions{
Stdout: &stdout,
Stderr: &stderr,
}
errCh := make(chan error)
go func() {
err = executor.Stream(streamOptions)
errCh <- err
}()
var timeoutCh <-chan time.Time
if hook.Timeout.Duration > 0 {
timer := time.NewTimer(hook.Timeout.Duration)
defer timer.Stop()
timeoutCh = timer.C
}
select {
case err = <-errCh:
case <-timeoutCh:
return errors.Errorf("timed out after %v", hook.Timeout.Duration)
}
hookLog.Infof("stdout: %s", stdout.String())
hookLog.Infof("stderr: %s", stderr.String())
return err
}
func ensureContainerExists(pod *corev1api.Pod, container string) error {
for _, c := range pod.Spec.Containers {
if c.Name == container {
return nil
}
}
return errors.Errorf("no such container: %q", container)
}
func setDefaultHookContainer(pod *corev1api.Pod, hook *api.ExecHook) error {
if len(pod.Spec.Containers) < 1 {
return errors.New("need at least 1 container")
}
hook.Container = pod.Spec.Containers[0].Name
return nil
}
type streamExecutorFactory interface {
NewSPDYExecutor(config *rest.Config, method string, url *url.URL) (remotecommand.Executor, error)
}
type defaultStreamExecutorFactory struct{}
func (f *defaultStreamExecutorFactory) NewSPDYExecutor(config *rest.Config, method string, url *url.URL) (remotecommand.Executor, error) {
return remotecommand.NewSPDYExecutor(config, method, url)
}