blob: 3eff4c50ad81d562ca90705d87e2f9cf18dc17bb [file] [log] [blame]
Serge Bazanskicaa12082023-02-16 14:54:04 +01001package manager
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "net"
9 "time"
10
11 "github.com/pkg/sftp"
12 "golang.org/x/crypto/ssh"
13)
14
15// SSHClient defines a simple interface to an abstract SSH client. Usually this
16// would be PlainSSHClient, but tests can use this interface to dependency-inject
17// fake SSH connections.
18type SSHClient interface {
19 // Dial returns an SSHConnection to a given address (host:port pair) using a
20 // given username/sshkey for authentication, and with a timeout for connection.
21 Dial(ctx context.Context, address string, username string, sshkey ssh.Signer, connectTimeout time.Duration) (SSHConnection, error)
22}
23
24type SSHConnection interface {
25 // Execute a given command on a remote host synchronously, passing in stdin as
26 // input, and returning a captured stdout/stderr. The returned data might be
27 // valid even when err != nil, which might happen if the remote side returned a
28 // non-zero exit code.
29 Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error)
30 // Upload a given blob to a targetPath on the system and make executable.
31 Upload(ctx context.Context, targetPath string, data []byte) error
32 // Close this connection.
33 Close() error
34}
35
36// PlainSSHClient implements SSHClient (and SSHConnection) using
37// golang.org/x/crypto/ssh.
38type PlainSSHClient struct {
39}
40
41type plainSSHConn struct {
42 cl *ssh.Client
43}
44
45func (p *PlainSSHClient) Dial(ctx context.Context, address, username string, sshkey ssh.Signer, connectTimeout time.Duration) (SSHConnection, error) {
46 d := net.Dialer{
47 Timeout: connectTimeout,
48 }
49 conn, err := d.DialContext(ctx, "tcp", address)
50 if err != nil {
51 return nil, err
52 }
53 conf := &ssh.ClientConfig{
54 // Equinix OS installations always use root.
55 User: username,
56 Auth: []ssh.AuthMethod{
57 ssh.PublicKeys(sshkey),
58 },
59 // Ignore the host key, since it's likely the first time anything logs into
60 // this device, and also because there's no way of knowing its fingerprint.
61 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
62 // Timeout sets a bound on the time it takes to set up the connection, but
63 // not on total session time.
64 Timeout: connectTimeout,
65 }
66 conn2, chanC, reqC, err := ssh.NewClientConn(conn, address, conf)
67 if err != nil {
68 return nil, err
69 }
70 cl := ssh.NewClient(conn2, chanC, reqC)
71 return &plainSSHConn{
72 cl: cl,
73 }, nil
74}
75
76func (p *plainSSHConn) Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error) {
77 sess, err := p.cl.NewSession()
78 if err != nil {
79 return nil, nil, fmt.Errorf("while creating SSH session: %w", err)
80 }
81 stdoutBuf := bytes.NewBuffer(nil)
82 stderrBuf := bytes.NewBuffer(nil)
83 sess.Stdin = bytes.NewBuffer(stdin)
84 sess.Stdout = stdoutBuf
85 sess.Stderr = stderrBuf
86 defer sess.Close()
87
88 if err := sess.Start(command); err != nil {
89 return nil, nil, err
90 }
91 doneC := make(chan error, 1)
92 go func() {
93 doneC <- sess.Wait()
94 }()
95 select {
96 case <-ctx.Done():
97 return nil, nil, ctx.Err()
98 case err := <-doneC:
99 return stdoutBuf.Bytes(), stderrBuf.Bytes(), err
100 }
101}
102
103func (p *plainSSHConn) Upload(ctx context.Context, targetPath string, data []byte) error {
104 sc, err := sftp.NewClient(p.cl)
105 if err != nil {
106 return fmt.Errorf("while building sftp client: %w", err)
107 }
108 defer sc.Close()
109
110 acrdr := bytes.NewReader(data)
111 df, err := sc.Create(targetPath)
112 if err != nil {
113 return fmt.Errorf("while creating file on the host: %w", err)
114 }
115
116 doneC := make(chan error, 1)
117
118 go func() {
119 _, err := io.Copy(df, acrdr)
120 df.Close()
121 doneC <- err
122 }()
123
124 select {
125 case err := <-doneC:
126 if err != nil {
127 return fmt.Errorf("while copying file: %w", err)
128 }
129 case <-ctx.Done():
130 df.Close()
131 return ctx.Err()
132 }
133
134 if err := sc.Chmod(targetPath, 0755); err != nil {
135 return fmt.Errorf("while setting file permissions: %w", err)
136 }
137 return nil
138}
139
140func (p *plainSSHConn) Close() error {
141 return p.cl.Close()
142}