/
pod_executor.go
72 lines (62 loc) · 1.97 KB
/
pod_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
package kubernetes
import (
"bytes"
"fmt"
"github.com/gazebo-web/cloudsim/pkg/orchestrator/components/pods"
"github.com/gazebo-web/cloudsim/pkg/orchestrator/components/spdy"
"github.com/gazebo-web/cloudsim/pkg/orchestrator/resource"
"github.com/gazebo-web/gz-go/v7"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/remotecommand"
)
// executor is a pods.Executor implementation.
type executor struct {
API kubernetes.Interface
pod resource.Resource
spdyInit spdy.Initializer
logger gz.Logger
}
// Cmd is used to run a command in a container inside a resource.
func (e *executor) Cmd(container string, command []string) error {
e.logger.Debug(fmt.Sprintf("Running command [%s] on pod [%s]", command, e.pod.Name()))
// Prepare buffers
var stdout, stderr bytes.Buffer
// Prepare options for SPDY
options := remotecommand.StreamOptions{
Stdin: nil,
Stdout: &stdout,
Stderr: &stderr,
Tty: false,
}
// Run command
err := runExec(runExecInput{
kubernetes: e.API,
namespace: e.pod.Namespace(),
name: e.pod.Name(),
container: container,
command: command,
options: options,
spdy: e.spdyInit,
})
if err == nil {
e.logger.Debug(fmt.Sprintf("Command [%s] on pod [%s] sucessfully run.", command, e.pod.Name()))
return nil
}
err = parseExecError(err, &stdout, &stderr)
e.logger.Debug(fmt.Sprintf("Running ommand [%s] on pod [%s] failed. Error: %s", command, e.pod.Name(), err.Error()))
return err
}
// Script is used to run a bash script inside a container.
func (e *executor) Script(container, script string) error {
e.logger.Debug(fmt.Sprintf("Running script [%s] on pod [%s]", script, e.pod.Name()))
return e.Cmd(container, []string{"sh", "-c", script})
}
// newExecutor initializes a new executor.
func newExecutor(api kubernetes.Interface, pod resource.Resource, spdyInit spdy.Initializer, logger gz.Logger) pods.Executor {
return &executor{
API: api,
pod: pod,
spdyInit: spdyInit,
logger: logger,
}
}