1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Package ssh_executor provides an implementation of pool.Executor
6 // using a long-lived multiplexed SSH session.
17 "git.curoverse.com/arvados.git/lib/cloud"
18 "golang.org/x/crypto/ssh"
21 // New returns a new Executor, using the given target.
22 func New(t cloud.ExecutorTarget) *Executor {
23 return &Executor{target: t}
26 // An Executor uses a multiplexed SSH connection to execute shell
27 // commands on a remote target. It reconnects automatically after
30 // When setting up a connection, the Executor accepts whatever host
31 // key is provided by the remote server, then passes the received key
32 // and the SSH connection to the target's VerifyHostKey method before
33 // executing commands on the connection.
35 // A zero Executor must not be used before calling SetTarget.
37 // An Executor must not be copied.
38 type Executor struct {
39 target cloud.ExecutorTarget
43 mtx sync.RWMutex // controls access to instance after creation
47 clientOnce sync.Once // initialized private state
48 clientSetup chan bool // len>0 while client setup is in progress
49 hostKey ssh.PublicKey // most recent host key that passed verification, if any
52 // SetSigners updates the set of private keys that will be offered to
53 // the target next time the Executor sets up a new connection.
54 func (exr *Executor) SetSigners(signers ...ssh.Signer) {
56 defer exr.mtx.Unlock()
60 // SetTarget sets the current target. The new target will be used next
61 // time a new connection is set up; until then, the Executor will
62 // continue to use the existing target.
64 // The new target is assumed to represent the same host as the
65 // previous target, although its address and host key might differ.
66 func (exr *Executor) SetTarget(t cloud.ExecutorTarget) {
68 defer exr.mtx.Unlock()
72 // SetTargetPort sets the default port (name or number) to connect
73 // to. This is used only when the address returned by the target's
74 // Address() method does not specify a port. If the given port is
75 // empty (or SetTargetPort is not called at all), the default port is
77 func (exr *Executor) SetTargetPort(port string) {
79 defer exr.mtx.Unlock()
83 // Target returns the current target.
84 func (exr *Executor) Target() cloud.ExecutorTarget {
86 defer exr.mtx.RUnlock()
90 // Execute runs cmd on the target. If an existing connection is not
91 // usable, it sets up a new connection to the current target.
92 func (exr *Executor) Execute(env map[string]string, cmd string, stdin io.Reader) ([]byte, []byte, error) {
93 session, err := exr.newSession()
98 for k, v := range env {
99 err = session.Setenv(k, v)
104 var stdout, stderr bytes.Buffer
105 session.Stdin = stdin
106 session.Stdout = &stdout
107 session.Stderr = &stderr
108 err = session.Run(cmd)
109 return stdout.Bytes(), stderr.Bytes(), err
112 // Close shuts down any active connections.
113 func (exr *Executor) Close() {
114 // Ensure exr is initialized
117 exr.clientSetup <- true
118 if exr.client != nil {
119 defer exr.client.Close()
121 exr.client, exr.clientErr = nil, errors.New("closed")
125 // Create a new SSH session. If session setup fails or the SSH client
126 // hasn't been setup yet, setup a new SSH client and try again.
127 func (exr *Executor) newSession() (*ssh.Session, error) {
128 try := func(create bool) (*ssh.Session, error) {
129 client, err := exr.sshClient(create)
133 return client.NewSession()
135 session, err := try(false)
137 session, err = try(true)
142 // Get the latest SSH client. If another goroutine is in the process
143 // of setting one up, wait for it to finish and return its result (or
144 // the last successfully setup client, if it fails).
145 func (exr *Executor) sshClient(create bool) (*ssh.Client, error) {
146 exr.clientOnce.Do(func() {
147 exr.clientSetup = make(chan bool, 1)
148 exr.clientErr = errors.New("client not yet created")
150 defer func() { <-exr.clientSetup }()
152 case exr.clientSetup <- true:
154 client, err := exr.setupSSHClient()
155 if err == nil || exr.client == nil {
156 if exr.client != nil {
157 // Hang up the previous
158 // (non-working) client
159 go exr.client.Close()
161 exr.client, exr.clientErr = client, err
168 // Another goroutine is doing the above case. Wait
169 // for it to finish and return whatever it leaves in
171 exr.clientSetup <- true
173 return exr.client, exr.clientErr
176 // Create a new SSH client.
177 func (exr *Executor) setupSSHClient() (*ssh.Client, error) {
178 target := exr.Target()
179 addr := target.Address()
181 return nil, errors.New("instance has no address")
183 if h, p, err := net.SplitHostPort(addr); err != nil || p == "" {
184 // Target address does not specify a port. Use
185 // targetPort, or "ssh".
189 if p = exr.targetPort; p == "" {
192 addr = net.JoinHostPort(h, p)
194 var receivedKey ssh.PublicKey
195 client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{
196 User: target.RemoteUser(),
197 Auth: []ssh.AuthMethod{
198 ssh.PublicKeys(exr.signers...),
200 HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
204 Timeout: time.Minute,
208 } else if receivedKey == nil {
209 return nil, errors.New("BUG: key was never provided to HostKeyCallback")
212 if exr.hostKey == nil || !bytes.Equal(exr.hostKey.Marshal(), receivedKey.Marshal()) {
213 err = target.VerifyHostKey(receivedKey, client)
217 exr.hostKey = receivedKey