/
baremetal.js
701 lines (614 loc) · 17.6 KB
/
baremetal.js
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import fs from 'fs'
import path from 'path'
import toml from '@iarna/toml'
import boxen from 'boxen'
import { Listr } from 'listr2'
import terminalLink from 'terminal-link'
import { titleCase } from 'title-case'
import { getPaths } from '../../lib'
import c from '../../lib/colors'
const CONFIG_FILENAME = 'deploy.toml'
const SYMLINK_FLAGS = '-nsf'
const CURRENT_RELEASE_SYMLINK_NAME = 'current'
const LIFECYCLE_HOOKS = ['before', 'after']
export const DEFAULT_SERVER_CONFIG = {
port: 22,
branch: 'main',
packageManagerCommand: 'yarn',
monitorCommand: 'pm2',
sides: ['api', 'web'],
keepReleases: 5,
}
export const command = 'baremetal [environment]'
export const description = 'Deploy to baremetal server(s)'
// force all paths to have forward slashes so that you can deploy to *nix
// systems from a Windows system
const pathJoin = path.posix.join
export const execaOptions = {
cwd: pathJoin(getPaths().base),
stdio: 'inherit',
shell: true,
cleanup: true,
}
export const builder = (yargs) => {
yargs.positional('environment', {
describe: 'The environment to deploy to',
type: 'string',
})
yargs.option('first-run', {
describe:
'Set this flag the first time you deploy: starts server processes from scratch',
default: false,
type: 'boolean',
})
yargs.option('update', {
describe: 'Update code to latest revision',
default: true,
type: 'boolean',
})
yargs.option('install', {
describe: 'Run `yarn install`',
default: true,
type: 'boolean',
})
yargs.option('migrate', {
describe: 'Run database migration tasks',
default: true,
type: 'boolean',
})
yargs.option('build', {
describe: 'Run build process for the deployed `sides`',
default: true,
type: 'boolean',
})
yargs.option('restart', {
describe: 'Restart server processes',
default: true,
type: 'boolean',
})
yargs.option('cleanup', {
describe: 'Remove old deploy directories',
default: true,
type: 'boolean',
})
yargs.option('releaseDir', {
describe:
'Directory to create for the latest release, defaults to timestamp',
default: new Date()
.toISOString()
.replace(/[:\-TZ]/g, '')
.replace(/\.\d+$/, ''),
type: 'string',
})
yargs.option('branch', {
describe: 'The branch to deploy',
type: 'string',
})
yargs.option('maintenance', {
describe: 'Add/remove the maintenance page',
choices: ['up', 'down'],
help: 'Put up a maintenance page by replacing the content of web/dist/index.html with the content of web/src/maintenance.html',
})
yargs.option('rollback', {
describe: 'Add/remove the maintenance page',
help: 'Rollback [count] number of releases',
})
// TODO: Allow option to pass --sides and only deploy select sides instead of all, always
yargs.epilogue(
`Also see the ${terminalLink(
'Redwood Baremetal Deploy Reference',
'https://redwoodjs.com/docs/cli-commands#deploy'
)}\n`
)
}
// Executes a single command via SSH connection. Displays an error and will
// exit() with the same code returned from the SSH command.
const sshExec = async (ssh, path, command, args) => {
let sshCommand = command
if (args) {
sshCommand += ` ${args.join(' ')}`
}
const result = await ssh.execCommand(sshCommand, {
cwd: path,
})
if (result.code !== 0) {
console.error(c.error(`\nDeploy failed!`))
console.error(
c.error(`Error while running command \`${command} ${args.join(' ')}\`:`)
)
console.error(
boxen(result.stderr, {
padding: { top: 0, bottom: 0, right: 1, left: 1 },
margin: 0,
borderColor: 'red',
})
)
process.exit(result.code)
}
return result
}
export const throwMissingConfig = (name) => {
throw new Error(
`"${name}" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml`
)
}
export const verifyConfig = (config, yargs) => {
if (!yargs.environment) {
throw new Error(
'Must specify an environment to deploy to, ex: `yarn rw deploy baremetal production`'
)
}
if (!config[yargs.environment]) {
throw new Error(`No servers found for environment "${yargs.environment}"`)
}
return true
}
export const verifyServerConfig = (config) => {
if (!config.host) {
throwMissingConfig('host')
}
if (!config.path) {
throwMissingConfig('path')
}
if (!config.repo) {
throwMissingConfig('repo')
}
return true
}
const symlinkCurrentCommand = async (dir, ssh, path) => {
return await sshExec(ssh, path, 'ln', [
SYMLINK_FLAGS,
dir,
CURRENT_RELEASE_SYMLINK_NAME,
])
}
const restartProcessCommand = async (processName, ssh, serverConfig, path) => {
return await sshExec(ssh, path, serverConfig.monitorCommand, [
'restart',
processName,
])
}
export const serverConfigWithDefaults = (serverConfig, yargs) => {
return {
...DEFAULT_SERVER_CONFIG,
...serverConfig,
branch: yargs.branch || serverConfig.branch || DEFAULT_SERVER_CONFIG.branch,
}
}
export const maintenanceTasks = (status, ssh, serverConfig) => {
const deployPath = pathJoin(serverConfig.path, CURRENT_RELEASE_SYMLINK_NAME)
const tasks = []
if (status === 'up') {
tasks.push({
title: `Enabling maintenance page...`,
task: async () => {
await sshExec(ssh, deployPath, 'cp', [
pathJoin('web', 'dist', '200.html'),
pathJoin('web', 'dist', '200.html.orig'),
])
await sshExec(ssh, deployPath, 'ln', [
SYMLINK_FLAGS,
pathJoin('..', 'src', 'maintenance.html'),
pathJoin('web', 'dist', '200.html'),
])
},
})
if (serverConfig.processNames) {
tasks.push({
title: `Stopping ${serverConfig.processNames.join(', ')} processes...`,
task: async () => {
await sshExec(ssh, serverConfig.path, serverConfig.monitorCommand, [
'stop',
serverConfig.processNames.join(' '),
])
},
})
}
} else if (status === 'down') {
tasks.push({
title: `Starting ${serverConfig.processNames.join(', ')} processes...`,
task: async () => {
await sshExec(ssh, serverConfig.path, serverConfig.monitorCommand, [
'start',
serverConfig.processNames.join(' '),
])
},
})
if (serverConfig.processNames) {
tasks.push({
title: `Disabling maintenance page...`,
task: async () => {
await sshExec(ssh, deployPath, 'rm', [
pathJoin('web', 'dist', '200.html'),
])
await sshExec(ssh, deployPath, 'cp', [
pathJoin('web', 'dist', '200.html.orig'),
pathJoin('web', 'dist', '200.html'),
])
},
})
}
}
return tasks
}
export const rollbackTasks = (count, ssh, serverConfig) => {
let rollbackCount = 1
if (parseInt(count) === count) {
rollbackCount = count
}
const tasks = [
{
title: `Rolling back ${rollbackCount} release(s)...`,
task: async () => {
const currentLink = (
await sshExec(ssh, serverConfig.path, 'readlink', ['-f', 'current'])
).stdout
.split('/')
.pop()
const dirs = (
await sshExec(ssh, serverConfig.path, 'ls', ['-t'])
).stdout
.split('\n')
.filter((dirs) => !dirs.match(/current/))
const deployedIndex = dirs.indexOf(currentLink)
const rollbackIndex = deployedIndex + rollbackCount
if (dirs[rollbackIndex]) {
console.info('Setting symlink')
await symlinkCurrentCommand(
dirs[rollbackIndex],
ssh,
serverConfig.path
)
} else {
throw new Error(
`Cannot rollback ${rollbackCount} release(s): ${
dirs.length - dirs.indexOf(currentLink) - 1
} previous release(s) available`
)
}
},
},
]
if (serverConfig.processNames) {
for (const processName of serverConfig.processNames) {
tasks.push({
title: `Restarting ${processName} process...`,
task: async () => {
await restartProcessCommand(
processName,
ssh,
serverConfig,
serverConfig.path
)
},
})
}
}
return tasks
}
export const lifecycleTask = (
lifecycle,
task,
skip,
{ serverLifecycle, ssh, cmdPath }
) => {
if (serverLifecycle[lifecycle]?.[task]) {
const tasks = []
for (const command of serverLifecycle[lifecycle][task]) {
tasks.push({
title: `${titleCase(lifecycle)} ${task}: \`${command}\``,
task: async () => {
await sshExec(ssh, cmdPath, command)
},
skip: () => skip,
})
}
return tasks
}
}
// wraps a given command with any defined before/after lifecycle commands
export const commandWithLifecycleEvents = ({ name, config, skip, command }) => {
const tasks = []
tasks.push(lifecycleTask('before', name, skip, config))
tasks.push({ ...command, skip: () => skip })
tasks.push(lifecycleTask('after', name, skip, config))
return tasks.flat().filter((t) => t)
}
export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => {
const cmdPath = pathJoin(serverConfig.path, yargs.releaseDir)
const config = { yargs, ssh, serverConfig, serverLifecycle, cmdPath }
const tasks = []
tasks.push(
commandWithLifecycleEvents({
name: 'update',
config: { ...config, cmdPath: serverConfig.path },
skip: !yargs.update,
command: {
title: `Cloning \`${serverConfig.branch}\` branch...`,
task: async () => {
await sshExec(ssh, serverConfig.path, 'git', [
'clone',
`--branch=${serverConfig.branch}`,
`--depth=1`,
serverConfig.repo,
yargs.releaseDir,
])
},
},
})
)
tasks.push(
commandWithLifecycleEvents({
name: 'symlinkEnv',
config,
skip: !yargs.update,
command: {
title: `Symlink .env...`,
task: async () => {
await sshExec(ssh, cmdPath, 'ln', [SYMLINK_FLAGS, '../.env', '.env'])
},
},
})
)
tasks.push(
commandWithLifecycleEvents({
name: 'install',
config,
skip: !yargs.install,
command: {
title: `Installing dependencies...`,
task: async () => {
await sshExec(ssh, cmdPath, serverConfig.packageManagerCommand, [
'install',
])
},
},
})
)
tasks.push(
commandWithLifecycleEvents({
name: 'migrate',
config,
skip: !yargs.migrate || serverConfig?.migrate === false,
command: {
title: `DB Migrations...`,
task: async () => {
await sshExec(ssh, cmdPath, serverConfig.packageManagerCommand, [
'rw',
'prisma',
'migrate',
'deploy',
])
await sshExec(ssh, cmdPath, serverConfig.packageManagerCommand, [
'rw',
'prisma',
'generate',
])
await sshExec(ssh, cmdPath, serverConfig.packageManagerCommand, [
'rw',
'dataMigrate',
'up',
])
},
},
})
)
for (const side of serverConfig.sides) {
tasks.push(
commandWithLifecycleEvents({
name: 'build',
config,
skip: !yargs.build,
command: {
title: `Building ${side}...`,
task: async () => {
await sshExec(ssh, cmdPath, serverConfig.packageManagerCommand, [
'rw',
'build',
side,
])
},
},
})
)
}
tasks.push(
commandWithLifecycleEvents({
name: 'symlinkCurrent',
config,
skip: !yargs.update,
command: {
title: `Symlinking current release...`,
task: async () => {
await symlinkCurrentCommand(yargs.releaseDir, ssh, serverConfig.path)
},
skip: () => !yargs.update,
},
})
)
if (serverConfig.processNames) {
for (const processName of serverConfig.processNames) {
if (yargs.firstRun) {
tasks.push(
commandWithLifecycleEvents({
name: 'restart',
config,
skip: !yargs.restart,
command: {
title: `Starting ${processName} process for the first time...`,
task: async () => {
await sshExec(
ssh,
serverConfig.path,
serverConfig.monitorCommand,
[
'start',
pathJoin(
CURRENT_RELEASE_SYMLINK_NAME,
'ecosystem.config.js'
),
'--only',
processName,
]
)
},
},
})
)
tasks.push({
title: `Saving ${processName} state for future startup...`,
task: async () => {
await sshExec(ssh, serverConfig.path, serverConfig.monitorCommand, [
'save',
])
},
skip: () => !yargs.restart,
})
} else {
tasks.push(
commandWithLifecycleEvents({
name: 'restart',
config,
skip: !yargs.restart,
command: {
title: `Restarting ${processName} process...`,
task: async () => {
await restartProcessCommand(
processName,
ssh,
serverConfig,
serverConfig.path
)
},
},
})
)
}
}
}
tasks.push(
commandWithLifecycleEvents({
name: 'cleanup',
config: { ...config, cmdPath: serverConfig.path },
skip: !yargs.cleanup,
command: {
title: `Cleaning up old deploys...`,
task: async () => {
// add 2 to skip `current` and start on the keepReleases + 1th release
const fileStartIndex = serverConfig.keepReleases + 2
await sshExec(
ssh,
serverConfig.path,
`ls -t | tail -n +${fileStartIndex} | xargs rm -rf`
)
},
},
})
)
return tasks.flat().filter((e) => e)
}
// merges additional lifecycle events into an existing object
const mergeLifecycleEvents = (lifecycle, other) => {
let lifecycleCopy = JSON.parse(JSON.stringify(lifecycle))
for (const hook of LIFECYCLE_HOOKS) {
for (const key in other[hook]) {
lifecycleCopy[hook][key] = (lifecycleCopy[hook][key] || []).concat(
other[hook][key]
)
}
}
return lifecycleCopy
}
export const parseConfig = (yargs, configToml) => {
const config = toml.parse(configToml)
let envConfig
const emptyLifecycle = {}
verifyConfig(config, yargs)
// start with an emtpy set of hooks, { before: {}, after: {} }
for (const hook of LIFECYCLE_HOOKS) {
emptyLifecycle[hook] = {}
}
// global lifecycle config
let envLifecycle = mergeLifecycleEvents(emptyLifecycle, config)
// get config for given environment
envConfig = config[yargs.environment]
envLifecycle = mergeLifecycleEvents(envLifecycle, envConfig)
return { envConfig, envLifecycle }
}
export const commands = (yargs, ssh) => {
const deployConfig = fs
.readFileSync(pathJoin(getPaths().base, CONFIG_FILENAME))
.toString()
let { envConfig, envLifecycle } = parseConfig(yargs, deployConfig)
let servers = []
let tasks = []
// loop through each server in deploy.toml
for (const config of envConfig.servers) {
// merge in defaults
const serverConfig = serverConfigWithDefaults(config, yargs)
verifyServerConfig(serverConfig)
// server-specific lifecycle
const serverLifecycle = mergeLifecycleEvents(envLifecycle, serverConfig)
tasks.push({
title: 'Connecting...',
task: () =>
ssh.connect({
host: serverConfig.host,
port: serverConfig.port,
username: serverConfig.username,
password: serverConfig.password,
privateKey: serverConfig.privateKey,
privateKeyPath: serverConfig.privateKeyPath,
passphrase: serverConfig.passphrase,
agent: serverConfig.agentForward && process.env.SSH_AUTH_SOCK,
agentForward: serverConfig.agentForward,
}),
})
if (yargs.maintenance) {
tasks = tasks.concat(
maintenanceTasks(yargs.maintenance, ssh, serverConfig)
)
} else if (yargs.rollback) {
tasks = tasks.concat(rollbackTasks(yargs.rollback, ssh, serverConfig))
} else {
tasks = tasks.concat(
deployTasks(yargs, ssh, serverConfig, serverLifecycle)
)
}
tasks.push({
title: 'Disconnecting...',
task: () => ssh.dispose(),
})
// Sets each server as a "parent" task so that the actual deploy tasks
// run as children. Each server deploy can run concurrently
servers.push({
title: serverConfig.host,
task: () => {
return new Listr(tasks)
},
})
}
return servers
}
export const handler = async (yargs) => {
const { NodeSSH } = require('node-ssh')
const ssh = new NodeSSH()
try {
const tasks = new Listr(commands(yargs, ssh), {
concurrent: true,
exitOnError: true,
renderer: yargs.verbose && 'verbose',
})
await tasks.run()
} catch (e) {
console.error(c.error('\nDeploy failed:'))
console.error(
boxen(e.stderr || e.message, {
padding: { top: 0, bottom: 0, right: 1, left: 1 },
margin: 0,
borderColor: 'red',
})
)
process.exit(e?.exitCode || 1)
}
}