This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
/
remote_shell.go
131 lines (108 loc) · 2.55 KB
/
remote_shell.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
package executors
import (
"bytes"
"context"
"fmt"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
type RemoteShell struct {
envStore
tempWorkDir string
wd string
user, host, keyFilePath string
}
var _ Executor = &RemoteShell{}
func NewRemoteShell(user, host, keyFilePath string) *RemoteShell {
return &RemoteShell{
envStore: envStore{},
user: user,
host: host,
keyFilePath: keyFilePath,
}
}
func (s *RemoteShell) SetupTempWorkDir(ctx context.Context) error {
out, err := s.Run(ctx, "mktemp", "-d")
if err != nil {
return err
}
s.tempWorkDir = strings.TrimSpace(out)
if s.tempWorkDir == "" {
return fmt.Errorf("empty temp dir")
}
s.wd = s.tempWorkDir
return nil
}
func quoteArgs(args []string) []string {
var ret []string
for _, arg := range args {
ret = append(ret, strconv.Quote(arg))
}
return ret
}
func sprintArgs(args []string) string {
return strings.Join(quoteArgs(args), " ")
}
func (s RemoteShell) Run(ctx context.Context, name string, srcArgs ...string) (string, error) {
shellArg := fmt.Sprintf("cd %s; %s %s %s",
s.wd,
strings.Join(s.env, " "),
name, strings.Join(srcArgs, " "))
args := []string{
"-i",
s.keyFilePath,
fmt.Sprintf("%s@%s", s.user, s.host),
shellArg,
}
cmd := exec.CommandContext(ctx, "ssh", args...)
var stderrBuf bytes.Buffer
cmd.Stderr = &stderrBuf
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("can't execute command ssh %s: %s, %s, %s",
sprintArgs(args), err, string(out), stderrBuf.String())
}
return string(out), nil
}
func (s RemoteShell) CopyFile(ctx context.Context, dst, src string) error {
if !filepath.IsAbs(dst) {
dst = filepath.Join(s.WorkDir(), dst)
}
out, err := exec.CommandContext(ctx, "scp",
"-i", s.keyFilePath,
src,
fmt.Sprintf("%s@%s:%s", s.user, s.host, dst),
).CombinedOutput()
if err != nil {
return fmt.Errorf("can't copy file %s to %s: %s, %s", src, dst, err, out)
}
return nil
}
func (s RemoteShell) Clean() {
if s.tempWorkDir == "" {
panic("empty temp work dir")
}
out, err := s.Run(context.TODO(), "rm", "-r", s.tempWorkDir)
if err != nil {
logrus.Warnf("Can't remove temp work dir in remote shell: %s, %s", err, out)
}
}
func (s RemoteShell) WithEnv(k, v string) Executor {
eCopy := s
eCopy.SetEnv(k, v)
return &eCopy
}
func (s RemoteShell) WorkDir() string {
return s.wd
}
func (s *RemoteShell) SetWorkDir(wd string) {
s.wd = wd
}
func (s RemoteShell) WithWorkDir(wd string) Executor {
eCopy := s
eCopy.wd = wd
return &eCopy
}