summaryrefslogtreecommitdiff
path: root/internal/control/ssh.go
blob: b7d7dd5970429f4a86f90a360a6af227d025c01e (plain)
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
package control

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

type SSHRunner struct{}

type SSHExecutor interface {
	Run(ctx context.Context, node Node, script string) (*CommandResult, error)
	Check(ctx context.Context, node Node) (*CommandResult, error)
	CopyFile(ctx context.Context, node Node, localPath, remotePath string) error
}

type CommandResult struct {
	Stdout string
	Stderr string
}

func (r SSHRunner) Run(ctx context.Context, node Node, script string) (*CommandResult, error) {
	target := sshTarget(node)
	cmd, err := sshCommand(ctx, node, target, "sh -s")
	if err != nil {
		return &CommandResult{}, err
	}
	cmd.Stdin = strings.NewReader(script)

	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		return &CommandResult{Stdout: stdout.String(), Stderr: stderr.String()}, fmt.Errorf("ssh %s: %w", target, err)
	}

	return &CommandResult{Stdout: stdout.String(), Stderr: stderr.String()}, nil
}

func (r SSHRunner) Check(ctx context.Context, node Node) (*CommandResult, error) {
	target := sshTarget(node)
	cmd, err := sshCommand(ctx, node, target, "printf ok")
	if err != nil {
		return &CommandResult{}, err
	}

	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		return &CommandResult{Stdout: stdout.String(), Stderr: stderr.String()}, fmt.Errorf("ssh %s: %w", target, err)
	}

	return &CommandResult{Stdout: stdout.String(), Stderr: stderr.String()}, nil
}

func CopyFileOverSCP(ctx context.Context, node Node, localPath, remotePath string) error {
	target := fmt.Sprintf("%s:%s", sshTarget(node), remotePath)
	cmd, err := scpCommand(ctx, node, localPath, target)
	if err != nil {
		return err
	}
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("scp %s -> %s: %w: %s", localPath, target, err, string(output))
	}
	return nil
}

func (r SSHRunner) CopyFile(ctx context.Context, node Node, localPath, remotePath string) error {
	return CopyFileOverSCP(ctx, node, localPath, remotePath)
}

func CopyDirContentsOverSCP(ctx context.Context, node Node, localDir, remoteDir string) error {
	target := fmt.Sprintf("%s:%s", sshTarget(node), remoteDir)
	cmd, err := scpCommand(ctx, node, "-r", filepath.Clean(localDir)+"/.", target)
	if err != nil {
		return err
	}
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("scp %s -> %s: %w: %s", localDir, target, err, string(output))
	}
	return nil
}

func sshBaseArgs(node Node) []string {
	args := []string{
		"-o", "StrictHostKeyChecking=accept-new",
		"-p", strconv.Itoa(defaultSSHPort(node.SSH.Port)),
	}
	if strings.TrimSpace(node.SSH.Auth) == "password" {
		args = append(args, "-o", "BatchMode=no")
	} else {
		args = append(args, "-o", "BatchMode=yes")
	}
	if strings.TrimSpace(node.SSH.IdentityFile) != "" {
		args = append(args, "-i", expandHome(node.SSH.IdentityFile))
	}
	return args
}

func scpBaseArgs(node Node) []string {
	args := []string{
		"-o", "StrictHostKeyChecking=accept-new",
		"-P", strconv.Itoa(defaultSSHPort(node.SSH.Port)),
	}
	if strings.TrimSpace(node.SSH.Auth) == "password" {
		args = append(args, "-o", "BatchMode=no")
	} else {
		args = append(args, "-o", "BatchMode=yes")
	}
	if strings.TrimSpace(node.SSH.IdentityFile) != "" {
		args = append(args, "-i", expandHome(node.SSH.IdentityFile))
	}
	return args
}

func sshTarget(node Node) string {
	return fmt.Sprintf("%s@%s", node.SSH.User, node.Host)
}

func defaultSSHPort(port int) int {
	if port == 0 {
		return 22
	}
	return port
}

func expandHome(path string) string {
	if path == "" || path[0] != '~' {
		return path
	}
	home, err := exec.Command("sh", "-lc", "printf %s \"$HOME\"").Output()
	if err != nil {
		return path
	}
	return filepath.Join(strings.TrimSpace(string(home)), strings.TrimPrefix(path, "~/"))
}

func sshCommand(ctx context.Context, node Node, extraArgs ...string) (*exec.Cmd, error) {
	args := sshBaseArgs(node)
	args = append(args, extraArgs...)
	return wrapWithPassword(ctx, node, "ssh", args...)
}

func scpCommand(ctx context.Context, node Node, extraArgs ...string) (*exec.Cmd, error) {
	args := scpBaseArgs(node)
	args = append(args, extraArgs...)
	return wrapWithPassword(ctx, node, "scp", args...)
}

func wrapWithPassword(ctx context.Context, node Node, command string, args ...string) (*exec.Cmd, error) {
	if strings.TrimSpace(node.SSH.Auth) != "password" {
		return exec.CommandContext(ctx, command, args...), nil
	}

	password := node.SSH.Password
	if password == "" {
		envName := strings.TrimSpace(node.SSH.PasswordEnv)
		if envName == "" {
			return nil, fmt.Errorf("ssh password auth for %s requires ssh.password_env", sshTarget(node))
		}
		password = os.Getenv(envName)
		if password == "" {
			return nil, fmt.Errorf("ssh password env %s is empty", envName)
		}
	}

	wrappedArgs := append([]string{"-p", password, command}, args...)
	cmd := exec.CommandContext(ctx, "sshpass", wrappedArgs...)
	return cmd, nil
}