-
Notifications
You must be signed in to change notification settings - Fork 312
/
ssh.go
427 lines (370 loc) · 13.5 KB
/
ssh.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2020 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package executor
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/appleboy/easyssh-proxy"
"github.com/fatih/color"
"github.com/joomcode/errorx"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/pkg/cluster/ctxt"
"github.com/pingcap/tiup/pkg/localdata"
"github.com/pingcap/tiup/pkg/tui"
"github.com/pingcap/tiup/pkg/utils"
"go.uber.org/zap"
)
var (
errNSSSH = errNS.NewSubNamespace("ssh")
// ErrPropSSHCommand is ErrPropSSHCommand
ErrPropSSHCommand = errorx.RegisterPrintableProperty("ssh_command")
// ErrPropSSHStdout is ErrPropSSHStdout
ErrPropSSHStdout = errorx.RegisterPrintableProperty("ssh_stdout")
// ErrPropSSHStderr is ErrPropSSHStderr
ErrPropSSHStderr = errorx.RegisterPrintableProperty("ssh_stderr")
// ErrSSHExecuteFailed is ErrSSHExecuteFailed
ErrSSHExecuteFailed = errNSSSH.NewType("execute_failed")
// ErrSSHExecuteTimedout is ErrSSHExecuteTimedout
ErrSSHExecuteTimedout = errNSSSH.NewType("execute_timedout")
)
func init() {
v := os.Getenv("TIUP_CLUSTER_EXECUTE_DEFAULT_TIMEOUT")
if v != "" {
d, err := time.ParseDuration(v)
if err != nil {
fmt.Println("ignore invalid TIUP_CLUSTER_EXECUTE_DEFAULT_TIMEOUT: ", v)
return
}
executeDefaultTimeout = d
}
}
type (
// EasySSHExecutor implements Executor with EasySSH as transportation layer.
EasySSHExecutor struct {
Config *easyssh.MakeConfig
Locale string // the locale used when executing the command
Sudo bool // all commands run with this executor will be using sudo
}
// NativeSSHExecutor implements Excutor with native SSH transportation layer.
NativeSSHExecutor struct {
Config *SSHConfig
Locale string // the locale used when executing the command
Sudo bool // all commands run with this executor will be using sudo
ConnectionTestResult error // test if the connection can be established in initialization phase
}
// SSHConfig is the configuration needed to establish SSH connection.
SSHConfig struct {
Host string // hostname of the SSH server
Port int // port of the SSH server
User string // username to login to the SSH server
Password string // password of the user
KeyFile string // path to the private key file
Passphrase string // passphrase of the private key file
Timeout time.Duration // Timeout is the maximum amount of time for the TCP connection to establish.
ExeTimeout time.Duration // ExeTimeout is the maximum amount of time for the command to finish
Proxy *SSHConfig // ssh proxy config
}
)
var _ ctxt.Executor = &EasySSHExecutor{}
var _ ctxt.Executor = &NativeSSHExecutor{}
// initialize builds and initializes a EasySSHExecutor
func (e *EasySSHExecutor) initialize(config SSHConfig) {
// build easyssh config
e.Config = &easyssh.MakeConfig{
Server: config.Host,
Port: strconv.Itoa(config.Port),
User: config.User,
Timeout: config.Timeout, // timeout when connecting to remote
}
if config.ExeTimeout > 0 {
executeDefaultTimeout = config.ExeTimeout
}
// prefer private key authentication
if len(config.KeyFile) > 0 {
e.Config.KeyPath = config.KeyFile
e.Config.Passphrase = config.Passphrase
} else if len(config.Password) > 0 {
e.Config.Password = config.Password
}
if proxy := config.Proxy; proxy != nil {
e.Config.Proxy = easyssh.DefaultConfig{
Server: proxy.Host,
Port: strconv.Itoa(proxy.Port),
User: proxy.User,
Timeout: proxy.Timeout, // timeout when connecting to remote
}
if len(proxy.KeyFile) > 0 {
e.Config.Proxy.KeyPath = proxy.KeyFile
e.Config.Proxy.Passphrase = proxy.Passphrase
} else if len(proxy.Password) > 0 {
e.Config.Proxy.Password = proxy.Password
}
}
}
// Execute run the command via SSH, it's not invoking any specific shell by default.
func (e *EasySSHExecutor) Execute(ctx context.Context, cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {
// try to acquire root permission
if e.Sudo || sudo {
cmd = fmt.Sprintf("/usr/bin/sudo -H bash -c \"%s\"", cmd)
}
// set a basic PATH in case it's empty on login
cmd = fmt.Sprintf("PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin %s", cmd)
if e.Locale != "" {
cmd = fmt.Sprintf("export LANG=%s; %s", e.Locale, cmd)
}
// run command on remote host
// default timeout is 60s in easyssh-proxy
if len(timeout) == 0 {
timeout = append(timeout, executeDefaultTimeout)
}
stdout, stderr, done, err := e.Config.Run(cmd, timeout...)
logfn := zap.L().Info
if err != nil {
logfn = zap.L().Error
}
logfn("SSHCommand",
zap.String("host", e.Config.Server),
zap.String("port", e.Config.Port),
zap.String("cmd", cmd),
zap.Error(err),
zap.String("stdout", stdout),
zap.String("stderr", stderr))
if err != nil {
baseErr := ErrSSHExecuteFailed.
Wrap(err, "Failed to execute command over SSH for '%s@%s:%s'", e.Config.User, e.Config.Server, e.Config.Port).
WithProperty(ErrPropSSHCommand, cmd).
WithProperty(ErrPropSSHStdout, stdout).
WithProperty(ErrPropSSHStderr, stderr)
if len(stdout) > 0 || len(stderr) > 0 {
output := strings.TrimSpace(strings.Join([]string{stdout, stderr}, "\n"))
baseErr = baseErr.
WithProperty(tui.SuggestionFromFormat("Command output on remote host %s:\n%s\n",
e.Config.Server,
color.YellowString(output)))
}
return []byte(stdout), []byte(stderr), baseErr
}
if !done { // timeout case,
return []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.
Wrap(err, "Execute command over SSH timedout for '%s@%s:%s'", e.Config.User, e.Config.Server, e.Config.Port).
WithProperty(ErrPropSSHCommand, cmd).
WithProperty(ErrPropSSHStdout, stdout).
WithProperty(ErrPropSSHStderr, stderr)
}
return []byte(stdout), []byte(stderr), nil
}
// Transfer copies files via SCP
// This function depends on `scp` (a tool from OpenSSH or other SSH implementation)
// This function is based on easyssh.MakeConfig.Scp() but with support of copying
// file from remote to local.
func (e *EasySSHExecutor) Transfer(ctx context.Context, src, dst string, download bool, limit int, compress bool) error {
if !download {
err := e.Config.Scp(src, dst)
if err != nil {
return errors.Annotatef(err, "failed to scp %s to %s@%s:%s", src, e.Config.User, e.Config.Server, dst)
}
return nil
}
// download file from remote
session, client, err := e.Config.Connect()
if err != nil {
return err
}
defer client.Close()
defer session.Close()
return ScpDownload(session, client, src, dst, limit, compress)
}
func (e *NativeSSHExecutor) prompt(def string) string {
if prom := os.Getenv(localdata.EnvNameSSHPassPrompt); prom != "" {
return prom
}
return def
}
func (e *NativeSSHExecutor) configArgs(args []string, isScp bool) []string {
if e.Config.Port != 0 && e.Config.Port != 22 {
if isScp {
args = append(args, "-P", strconv.Itoa(e.Config.Port))
} else {
args = append(args, "-p", strconv.Itoa(e.Config.Port))
}
}
if e.Config.Timeout != 0 {
args = append(args, "-o", fmt.Sprintf("ConnectTimeout=%d", int64(e.Config.Timeout.Seconds())))
}
if e.Config.Password != "" {
args = append([]string{"sshpass", "-p", e.Config.Password, "-P", e.prompt("password")}, args...)
} else if e.Config.KeyFile != "" {
args = append(args, "-i", e.Config.KeyFile)
if e.Config.Passphrase != "" {
args = append([]string{"sshpass", "-p", e.Config.Passphrase, "-P", e.prompt("passphrase")}, args...)
}
}
proxy := e.Config.Proxy
if proxy != nil {
proxyArgs := []string{"ssh"}
if proxy.Timeout != 0 {
proxyArgs = append(proxyArgs, "-o", fmt.Sprintf("ConnectTimeout=%d", int64(proxy.Timeout.Seconds())))
}
if proxy.Password != "" {
proxyArgs = append([]string{"sshpass", "-p", proxy.Password, "-P", e.prompt("password")}, proxyArgs...)
} else if proxy.KeyFile != "" {
proxyArgs = append(proxyArgs, "-i", proxy.KeyFile)
if proxy.Passphrase != "" {
proxyArgs = append([]string{"sshpass", "-p", proxy.Passphrase, "-P", e.prompt("passphrase")}, proxyArgs...)
}
}
// Don't need to extra quote it, exec.Command will handle it right
// ref https://stackoverflow.com/a/26473771/2298986
args = append(args, []string{"-o", fmt.Sprintf(`ProxyCommand=%s %s@%s -p %d -W %%h:%%p`, strings.Join(proxyArgs, " "), proxy.User, proxy.Host, proxy.Port)}...)
}
return args
}
// Execute run the command via SSH, it's not invoking any specific shell by default.
func (e *NativeSSHExecutor) Execute(ctx context.Context, cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {
if e.ConnectionTestResult != nil {
return nil, nil, e.ConnectionTestResult
}
// try to acquire root permission
if e.Sudo || sudo {
cmd = fmt.Sprintf("/usr/bin/sudo -H bash -c \"%s\"", cmd)
}
// set a basic PATH in case it's empty on login
cmd = fmt.Sprintf("PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin %s", cmd)
if e.Locale != "" {
cmd = fmt.Sprintf("export LANG=%s; %s", e.Locale, cmd)
}
// run command on remote host
// default timeout is 60s in easyssh-proxy
if len(timeout) == 0 {
timeout = append(timeout, executeDefaultTimeout)
}
if len(timeout) > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout[0])
defer cancel()
}
ssh := "ssh"
if val := os.Getenv(localdata.EnvNameSSHPath); val != "" {
if isExec := utils.IsExecBinary(val); !isExec {
return nil, nil, fmt.Errorf("specified SSH in the environment variable `%s` does not exist or is not executable", localdata.EnvNameSSHPath)
}
ssh = val
}
args := []string{ssh, "-o", "StrictHostKeyChecking=no"}
args = e.configArgs(args, false) // prefix and postfix args
args = append(args, fmt.Sprintf("%s@%s", e.Config.User, e.Config.Host), cmd)
command := exec.CommandContext(ctx, args[0], args[1:]...)
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
command.Stdout = stdout
command.Stderr = stderr
err := command.Run()
logfn := zap.L().Info
if err != nil {
logfn = zap.L().Error
}
logfn("SSHCommand",
zap.String("host", e.Config.Host),
zap.Int("port", e.Config.Port),
zap.String("cmd", cmd),
zap.Error(err),
zap.String("stdout", stdout.String()),
zap.String("stderr", stderr.String()))
if err != nil {
baseErr := ErrSSHExecuteFailed.
Wrap(err, "Failed to execute command over SSH for '%s@%s:%d'", e.Config.User, e.Config.Host, e.Config.Port).
WithProperty(ErrPropSSHCommand, cmd).
WithProperty(ErrPropSSHStdout, stdout).
WithProperty(ErrPropSSHStderr, stderr)
if len(stdout.Bytes()) > 0 || len(stderr.Bytes()) > 0 {
output := strings.TrimSpace(strings.Join([]string{stdout.String(), stderr.String()}, "\n"))
baseErr = baseErr.
WithProperty(tui.SuggestionFromFormat("Command output on remote host %s:\n%s\n",
e.Config.Host,
color.YellowString(output)))
}
return stdout.Bytes(), stderr.Bytes(), baseErr
}
return stdout.Bytes(), stderr.Bytes(), err
}
// Transfer copies files via SCP
// This function depends on `scp` (a tool from OpenSSH or other SSH implementation)
func (e *NativeSSHExecutor) Transfer(ctx context.Context, src, dst string, download bool, limit int, compress bool) error {
if e.ConnectionTestResult != nil {
return e.ConnectionTestResult
}
scp := "scp"
if val := os.Getenv(localdata.EnvNameSCPPath); val != "" {
if isExec := utils.IsExecBinary(val); !isExec {
return fmt.Errorf("specified SCP in the environment variable `%s` does not exist or is not executable", localdata.EnvNameSCPPath)
}
scp = val
}
args := []string{scp, "-r", "-o", "StrictHostKeyChecking=no"}
if limit > 0 {
args = append(args, "-l", fmt.Sprint(limit))
}
if compress {
args = append(args, "-C")
}
args = e.configArgs(args, true) // prefix and postfix args
if download {
targetPath := filepath.Dir(dst)
if err := utils.CreateDir(targetPath); err != nil {
return err
}
args = append(args, fmt.Sprintf("%s@%s:%s", e.Config.User, e.Config.Host, src), dst)
} else {
args = append(args, src, fmt.Sprintf("%s@%s:%s", e.Config.User, e.Config.Host, dst))
}
command := exec.Command(args[0], args[1:]...)
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
command.Stdout = stdout
command.Stderr = stderr
err := command.Run()
logfn := zap.L().Info
if err != nil {
logfn = zap.L().Error
}
logfn("SCPCommand",
zap.String("host", e.Config.Host),
zap.Int("port", e.Config.Port),
zap.String("cmd", strings.Join(args, " ")),
zap.Error(err),
zap.String("stdout", stdout.String()),
zap.String("stderr", stderr.String()))
if err != nil {
baseErr := ErrSSHExecuteFailed.
Wrap(err, "Failed to transfer file over SCP for '%s@%s:%d'", e.Config.User, e.Config.Host, e.Config.Port).
WithProperty(ErrPropSSHCommand, strings.Join(args, " ")).
WithProperty(ErrPropSSHStdout, stdout).
WithProperty(ErrPropSSHStderr, stderr)
if len(stdout.Bytes()) > 0 || len(stderr.Bytes()) > 0 {
output := strings.TrimSpace(strings.Join([]string{stdout.String(), stderr.String()}, "\n"))
baseErr = baseErr.
WithProperty(tui.SuggestionFromFormat("Command output on remote host %s:\n%s\n",
e.Config.Host,
color.YellowString(output)))
}
return baseErr
}
return err
}