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
|
// 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/fatih/color"
"github.com/joomcode/errorx"
"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"
"golang.org/x/crypto/ssh"
)
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 (
// 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 = &NativeSSHExecutor{}
func loadPrivateKey(keyPath, passphrase string) (ssh.Signer, error) {
key, err := os.ReadFile(keyPath)
if err != nil {
return nil, fmt.Errorf("failed to read private key file %s: %w", keyPath, err)
}
var signer ssh.Signer
if passphrase != "" {
signer, err = ssh.ParsePrivateKeyWithPassphrase(key, []byte(passphrase))
} else {
signer, err = ssh.ParsePrivateKey(key)
}
if err != nil {
return nil, fmt.Errorf("failed to parse private key %s: %w", keyPath, err)
}
return signer, nil
}
// ConnectSSH establishes an SSH connection using the configuration.
func ConnectSSH(config *SSHConfig) (*ssh.Client, error) {
authMethods := make([]ssh.AuthMethod, 0)
if config.Password != "" {
authMethods = append(authMethods, ssh.Password(config.Password))
}
if config.KeyFile != "" {
signer, err := loadPrivateKey(config.KeyFile, config.Passphrase)
if err != nil {
return nil, err
}
authMethods = append(authMethods, ssh.PublicKeys(signer))
}
if len(authMethods) == 0 {
return nil, fmt.Errorf("no authentication method provided for SSH connection to %s:%d", config.Host, config.Port)
}
sshConfig := &ssh.ClientConfig{
User: config.User,
Auth: authMethods,
// InsecureIgnoreHostKey is used here to mimic the behavior of NativeSSHExecutor which uses StrictHostKeyChecking=no.
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: config.Timeout,
}
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
if config.Proxy != nil {
proxyClient, err := ConnectSSH(config.Proxy)
if err != nil {
return nil, fmt.Errorf("failed to connect to SSH proxy %s:%d: %w", config.Proxy.Host, config.Proxy.Port, err)
}
defer proxyClient.Close()
conn, err := proxyClient.Dial("tcp", addr)
if err != nil {
return nil, fmt.Errorf("failed to dial target %s via proxy: %w", addr, err)
}
ncc, chans, reqs, err := ssh.NewClientConn(conn, addr, sshConfig)
if err != nil {
return nil, fmt.Errorf("failed to create client connection via proxy: %w", err)
}
return ssh.NewClient(ncc, chans, reqs), nil
}
client, err := ssh.Dial("tcp", addr, sshConfig)
if err != nil {
return nil, fmt.Errorf("failed to dial SSH server %s: %w", addr, err)
}
return client, nil
}
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
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.MkdirAll(targetPath, 0755); 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
}
|