|
1 | 1 | import {Args, Command, Flags} from '@oclif/core' |
2 | | - |
| 2 | +import {NodeSSH} from 'node-ssh' |
| 3 | +import inquirerPassword from '@inquirer/password' |
| 4 | +import {SingleBar} from 'cli-progress' |
3 | 5 | import {getDisco} from '../../config.js' |
4 | 6 | import {request} from '../../auth-request.js' |
5 | | - |
6 | | -import * as fs from 'node:fs' |
7 | | -import * as os from 'node:os' |
8 | | -import * as path from 'node:path' |
9 | | -import {NodeSSH} from 'node-ssh' |
10 | | - |
11 | | -const GET_NODE_SCRIPT_URL = (version: string) => `https://downloads.letsdisco.dev/${version}/node` |
| 7 | +import { checkDockerInstalled, connectSsh, installDockerIfNeeded, runSshCommand, setupRootSshAccess, userCanSudoWitoutPassword } from '../init.js' |
12 | 8 |
|
13 | 9 | export default class NodesAdd extends Command { |
14 | | - static override args = { |
15 | | - sshString: Args.string({description: 'ssh user@IP to connect to new machine', required: true}), |
| 10 | + static args = { |
| 11 | + sshString: Args.string({required: true}), |
16 | 12 | } |
17 | 13 |
|
18 | | - static override description = 'add a new server to your deployment' |
| 14 | + static description = 'initializes a new server' |
19 | 15 |
|
20 | | - static override examples = ['<%= config.bin %> <%= command.id %> [email protected]'] |
| 16 | + static examples = [ |
| 17 | + '<%= config.bin %> <%= command.id %> [email protected]', |
| 18 | + '<%= config.bin %> <%= command.id %> [email protected] --version 0.4.0', |
| 19 | + ] |
21 | 20 |
|
22 | | - static override flags = { |
| 21 | + static flags = { |
| 22 | + verbose: Flags.boolean({default: false, description: 'show extra output'}), |
| 23 | + 'identity-file': Flags.string({ |
| 24 | + char: 'i', |
| 25 | + description: 'SSH key to use for authentication', |
| 26 | + }), |
23 | 27 | disco: Flags.string({required: false}), |
24 | | - version: Flags.string({required: false, default: 'latest'}), |
25 | 28 | } |
26 | 29 |
|
27 | 30 | public async run(): Promise<void> { |
28 | 31 | const {args, flags} = await this.parse(NodesAdd) |
29 | | - const discoConfig = getDisco(flags.disco || null) |
30 | | - // eslint-disable-next-line new-cap |
31 | | - const nodeScriptUrl = GET_NODE_SCRIPT_URL(flags.version) |
| 32 | + const {verbose, 'identity-file': identityFile, disco} = flags |
| 33 | + |
| 34 | + const discoConfig = getDisco(disco || null) |
32 | 35 |
|
33 | 36 | const url = `https://${discoConfig.host}/api/disco/swarm/join-token` |
34 | 37 | const res = await request({ |
35 | 38 | method: 'GET', |
36 | 39 | url, |
37 | 40 | discoConfig, |
38 | 41 | }) |
39 | | - const data = (await res.json()) as any |
40 | | - |
41 | | - const token = data.joinToken |
42 | | - const {ip} = data |
43 | | - const command = `curl ${nodeScriptUrl} | sudo IP=${ip} TOKEN=${token} sh` |
| 42 | + const {joinToken, ip: leaderIp, dockerVersion, registryHost} = (await res.json()) as { |
| 43 | + joinToken: string |
| 44 | + ip: string |
| 45 | + dockerVersion: string |
| 46 | + registryHost: null | string |
| 47 | + } |
44 | 48 |
|
45 | | - // TODO centralize this code which is identical to code in init.ts |
| 49 | + if (registryHost === null) { |
| 50 | + this.log("Image registry not configured") |
| 51 | + return; |
| 52 | + } |
46 | 53 |
|
47 | | - const [username, host] = args.sshString.split('@') |
| 54 | + const [argUsername, host] = args.sshString.split('@') |
48 | 55 |
|
49 | | - const sshKeyPaths = [ |
50 | | - path.join(os.homedir(), '.ssh', 'id_ed25519'), |
51 | | - path.join(os.homedir(), '.ssh', 'id_rsa'), |
52 | | - ].filter((p) => { |
53 | | - try { |
54 | | - return fs.statSync(p).isFile() |
55 | | - } catch { |
56 | | - return false |
57 | | - } |
58 | | - }) |
| 56 | + let username = argUsername |
59 | 57 |
|
60 | | - if (sshKeyPaths.length === 0) { |
61 | | - this.error('could not find an SSH key in ~/.ssh') |
| 58 | + let ssh |
| 59 | + let password |
| 60 | + try { |
| 61 | + ;({ssh, password} = await connectSsh({host, username, identityFile})) |
| 62 | + } catch { |
| 63 | + this.error('could not connect to SSH') |
62 | 64 | } |
63 | 65 |
|
64 | | - const ssh = new NodeSSH() |
| 66 | + if (username !== 'root') { |
| 67 | + const canSudoWithoutPassword = await userCanSudoWitoutPassword({ssh, verbose}) |
| 68 | + // use password if provided, or ask for one if needed |
| 69 | + const passwordToUse = |
| 70 | + password === undefined |
| 71 | + ? canSudoWithoutPassword |
| 72 | + ? undefined |
| 73 | + : await inquirerPassword({message: `${username}@${host}'s password:`}) |
| 74 | + : password |
| 75 | + if (verbose) { |
| 76 | + if (passwordToUse === undefined) { |
| 77 | + process.stdout.write('Will not use password\n') |
| 78 | + } else { |
| 79 | + process.stdout.write('Will use password\n') |
| 80 | + } |
| 81 | + } |
65 | 82 |
|
66 | | - let connected = false |
67 | | - for await (const sshKeyPath of sshKeyPaths) { |
| 83 | + await setupRootSshAccess({ssh, password: passwordToUse, verbose}) |
| 84 | + username = 'root' |
68 | 85 | try { |
69 | | - await ssh.connect({ |
70 | | - host, |
71 | | - privateKeyPath: sshKeyPath, |
72 | | - username, |
73 | | - }) |
74 | | - connected = true |
75 | | - break |
| 86 | + ;({ssh, password} = await connectSsh({host, username, identityFile})) |
76 | 87 | } catch { |
77 | | - // skip error |
| 88 | + this.error('could not connect to SSH as root') |
78 | 89 | } |
79 | 90 | } |
80 | 91 |
|
81 | | - if (!connected) { |
82 | | - this.error('could not connect to server') |
| 92 | + const dockerAlreadyInstalled = await checkDockerInstalled(ssh) |
| 93 | + let progressBar |
| 94 | + if (!verbose) { |
| 95 | + const dockerInstallOutputCount = 309 |
| 96 | + const count = dockerAlreadyInstalled ? 0 : dockerInstallOutputCount; |
| 97 | + progressBar = new SingleBar({format: '[{bar}] {percentage}%', clearOnComplete: true}) |
| 98 | + progressBar.start(count, 0) |
83 | 99 | } |
84 | 100 |
|
85 | | - this.log('connected') |
| 101 | + await installDockerIfNeeded({dockerAlreadyInstalled, verbose, ssh, dockerVersion, progressBar}) |
86 | 102 |
|
87 | | - // do something with stderr output? |
88 | | - const {code} = await ssh.execCommand(command, { |
89 | | - onStdout(chunk) { |
90 | | - const str = chunk.toString('utf8') |
91 | | - process.stdout.write(str) |
92 | | - }, |
93 | | - }) |
94 | | - if (code !== 0) { |
95 | | - this.error('failed to run ssh script') |
| 103 | + |
| 104 | + if (verbose) { |
| 105 | + this.log('Joining Swarm') |
96 | 106 | } |
97 | 107 |
|
| 108 | + await joinSwarm({ |
| 109 | + ssh, |
| 110 | + joinToken, |
| 111 | + leaderIp, |
| 112 | + verbose, |
| 113 | + progressBar, |
| 114 | + }) |
| 115 | + |
98 | 116 | ssh.dispose() |
| 117 | + if (progressBar !== undefined) { |
| 118 | + progressBar.stop() |
| 119 | + } |
| 120 | + |
| 121 | + this.log('Done') |
99 | 122 | } |
100 | 123 | } |
| 124 | + |
| 125 | + |
| 126 | +async function joinSwarm({ |
| 127 | + ssh, |
| 128 | + joinToken, |
| 129 | + leaderIp, |
| 130 | + verbose, |
| 131 | + progressBar, |
| 132 | +}: { |
| 133 | + ssh: NodeSSH |
| 134 | + joinToken: string, |
| 135 | + leaderIp: string, |
| 136 | + verbose: boolean |
| 137 | + progressBar: SingleBar | undefined |
| 138 | +}): Promise<void> { |
| 139 | + const command = `docker swarm join --token ${joinToken} ${leaderIp}:2377`; |
| 140 | + await runSshCommand({ssh, command, verbose, progressBar}) |
| 141 | +} |
| 142 | + |
0 commit comments