-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrun_test.go
306 lines (274 loc) · 8.13 KB
/
run_test.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
package mtest
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/cybozu-go/well"
. "github.com/onsi/gomega"
"golang.org/x/crypto/ssh"
)
const (
sshTimeout = 3 * time.Minute
defaultDialTimeout = 30 * time.Second
defaultKeepAlive = 5 * time.Second
// DefaultRunTimeout is the timeout value for Agent.Run().
DefaultRunTimeout = 10 * time.Minute
)
var (
sshClients = make(map[string]*sshAgent)
agentDialer = &net.Dialer{
Timeout: defaultDialTimeout,
KeepAlive: defaultKeepAlive,
}
)
type sshAgent struct {
client *ssh.Client
conn net.Conn
}
func sshTo(address string, sshKey ssh.Signer, userName string) (*sshAgent, error) {
conn, err := agentDialer.Dial("tcp", address+":22")
if err != nil {
fmt.Printf("failed to dial: %s\n", address)
return nil, err
}
config := &ssh.ClientConfig{
User: userName,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(sshKey),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 5 * time.Second,
}
err = conn.SetDeadline(time.Now().Add(defaultDialTimeout))
if err != nil {
conn.Close()
return nil, err
}
clientConn, channelCh, reqCh, err := ssh.NewClientConn(conn, "tcp", config)
if err != nil {
// conn was already closed in ssh.NewClientConn
return nil, err
}
err = conn.SetDeadline(time.Time{})
if err != nil {
clientConn.Close()
return nil, err
}
a := sshAgent{
client: ssh.NewClient(clientConn, channelCh, reqCh),
conn: conn,
}
return &a, nil
}
func prepareSSHClients(addresses ...string) error {
sshKey, err := parsePrivateKey(sshKeyFile)
if err != nil {
return err
}
ch := time.After(sshTimeout)
for _, a := range addresses {
RETRY:
select {
case <-ch:
return errors.New("prepareSSHClients timed out")
default:
}
agent, err := sshTo(a, sshKey, "cybozu")
if err != nil {
time.Sleep(time.Second)
goto RETRY
}
sshClients[a] = agent
}
return nil
}
func parsePrivateKey(keyPath string) (ssh.Signer, error) {
f, err := os.Open(keyPath)
if err != nil {
return nil, err
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return nil, err
}
return ssh.ParsePrivateKey(data)
}
func loadImage(path string) error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer func() {
sess.Run("rm -f " + path)
sess.Close()
}()
return sess.Run("docker load -i " + path)
})
}
env.Stop()
return env.Wait()
}
func installTools(image string) error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return sess.Run("docker run --rm -u root:root --entrypoint /usr/local/sabakan/install-tools --mount type=bind,src=/opt/bin,target=/host/usr/local/bin " + image)
})
}
env.Stop()
return env.Wait()
}
func stopEtcd() error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return sess.Run("sudo systemctl stop my-etcd.service; sudo rm -rf /home/cybozu/default.etcd")
})
}
env.Stop()
return env.Wait()
}
func runEtcd() error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return sess.Run("sudo systemd-run --unit=my-etcd.service /opt/bin/etcd --listen-client-urls=http://0.0.0.0:2379 --advertise-client-urls=http://localhost:2379 --data-dir /home/cybozu/default.etcd")
})
}
env.Stop()
return env.Wait()
}
func stopSabakan() error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return sess.Run("sudo systemctl reset-failed sabakan.service; sudo systemctl stop sabakan.service; sudo rm -rf /var/lib/sabakan")
})
}
env.Stop()
return env.Wait()
}
func runSabakan(image string) error {
env := well.NewEnvironment(context.Background())
for _, host := range []string{host1, host2, host3} {
host2 := host
env.Go(func(ctx context.Context) error {
sess, err := sshClients[host2].client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return sess.Run("sudo mkdir -p /var/lib/sabakan && sudo systemd-run --unit=sabakan.service docker run --rm --read-only --cap-drop ALL --cap-add NET_BIND_SERVICE --network host --name sabakan --mount type=bind,source=/var/lib/sabakan,target=/var/lib/sabakan --mount type=bind,source=/etc/sabakan,target=/etc/sabakan --mount type=bind,source=/etc/sabakan.yml,target=/etc/sabakan.yml " + image + " -config-file /etc/sabakan.yml")
})
}
env.Stop()
return env.Wait()
}
func execAt(host string, args ...string) (stdout, stderr []byte, e error) {
return execAtWithStream(host, nil, args...)
}
// WARNING: `input` can contain secret data. Never output `input` to console.
func execAtWithStream(host string, input io.Reader, args ...string) (stdout, stderr []byte, e error) {
agent := sshClients[host]
return doExec(agent, input, args...)
}
// WARNING: `input` can contain secret data. Never output `input` to console.
func doExec(agent *sshAgent, input io.Reader, args ...string) ([]byte, []byte, error) {
err := agent.conn.SetDeadline(time.Now().Add(DefaultRunTimeout))
if err != nil {
return nil, nil, err
}
defer agent.conn.SetDeadline(time.Time{})
sess, err := agent.client.NewSession()
if err != nil {
return nil, nil, err
}
defer sess.Close()
if input != nil {
sess.Stdin = input
}
outBuf := new(bytes.Buffer)
errBuf := new(bytes.Buffer)
sess.Stdout = outBuf
sess.Stderr = errBuf
err = sess.Run(strings.Join(args, " "))
return outBuf.Bytes(), errBuf.Bytes(), err
}
func execSafeAt(host string, args ...string) []byte {
stdout, stderr, err := execAt(host, args...)
ExpectWithOffset(1, err).To(Succeed(), "[%s] %v: %s", host, args, stderr)
return stdout
}
func remoteTempFile(body string) string {
f, err := os.CreateTemp("", "mtest")
Expect(err).NotTo(HaveOccurred())
defer f.Close()
_, err = f.WriteString(body)
Expect(err).NotTo(HaveOccurred())
_, err = f.Seek(0, io.SeekStart)
Expect(err).NotTo(HaveOccurred())
remoteFile := filepath.Join("/tmp", filepath.Base(f.Name()))
_, _, err = execAtWithStream(host1, f, "dd", "of="+f.Name())
Expect(err).NotTo(HaveOccurred())
return remoteFile
}
func sabactl(args ...string) ([]byte, []byte, error) {
args = append([]string{"/opt/bin/sabactl", "--server", "http://" + host1 + ":10080"}, args...)
return execAt(host1, args...)
}
func sabactlSafe(args ...string) []byte {
args = append([]string{"/opt/bin/sabactl", "--server", "http://" + host1 + ":10080"}, args...)
return execSafeAt(host1, args...)
}
func etcdctl(args ...string) ([]byte, []byte, error) {
args = append([]string{"/opt/bin/etcdctl", "--endpoints=http://" + host1 + ":2379"}, args...)
return execAt(host1, args...)
}
func stopHost2Sabakan() ([]byte, []byte, error) {
return execAt(host2, "sudo", "systemctl", "stop", "sabakan.service")
}
func startHost2Sabakan(image string) ([]byte, []byte, error) {
return execAt(host2, "sudo", "systemd-run", "--unit=sabakan.service",
"docker", "run", "--rm", "--read-only", "--cap-drop", "ALL", "--cap-add", "NET_BIND_SERVICE",
"--network", "host", "--name", "sabakan",
"--mount", "type=bind,source=/var/lib/sabakan,target=/var/lib/sabakan",
"--mount", "type=bind,source=/etc/sabakan.yml,target=/etc/sabakan.yml",
"--mount", "type=bind,source=/etc/sabakan,target=/etc/sabakan",
image, "-config-file=/etc/sabakan.yml")
}