(connection: PiSshConnection)
| 28 | |
| 29 | /** Opens one SSH connection plus an SFTP channel for the run. */ |
| 30 | export async function openSshSession(connection: PiSshConnection): Promise<PiSshSession> { |
| 31 | const client = await createSSHConnection({ |
| 32 | host: connection.host, |
| 33 | port: connection.port, |
| 34 | username: connection.username, |
| 35 | password: connection.password ?? null, |
| 36 | privateKey: connection.privateKey ?? null, |
| 37 | passphrase: connection.passphrase ?? null, |
| 38 | }) |
| 39 | |
| 40 | const close = () => { |
| 41 | try { |
| 42 | client.end() |
| 43 | } catch (error) { |
| 44 | logger.warn('Failed to close SSH session', { error: getErrorMessage(error) }) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // The TCP/SSH connection is already open here, so close it if opening the SFTP |
| 49 | // channel fails (e.g. the server has the SFTP subsystem disabled) — otherwise |
| 50 | // the connection is orphaned when this function throws. |
| 51 | try { |
| 52 | const sftp = await new Promise<SFTPWrapper>((resolve, reject) => { |
| 53 | client.sftp((err, channel) => (err ? reject(err) : resolve(channel))) |
| 54 | }) |
| 55 | return { client, sftp, close } |
| 56 | } catch (error) { |
| 57 | close() |
| 58 | throw error |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | function readRemoteFile(sftp: SFTPWrapper, path: string): Promise<string> { |
| 63 | return new Promise((resolve, reject) => { |
no test coverage detected