-
Notifications
You must be signed in to change notification settings - Fork 866
/
Copy pathCaptainManager.ts
848 lines (751 loc) · 28.2 KB
/
CaptainManager.ts
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
import { v4 as uuid } from 'uuid'
import ApiStatusCodes from '../../api/ApiStatusCodes'
import DataStore from '../../datastore/DataStore'
import DataStoreProvider from '../../datastore/DataStoreProvider'
import DockerApi from '../../docker/DockerApi'
import { IRegistryInfo, IRegistryTypes } from '../../models/IRegistryInfo'
import CaptainConstants from '../../utils/CaptainConstants'
import Logger from '../../utils/Logger'
import MigrateCaptainDuckDuck from '../../utils/MigrateCaptainDuckDuck'
import Utils from '../../utils/Utils'
import Authenticator from '../Authenticator'
import ServiceManager from '../ServiceManager'
import BackupManager from './BackupManager'
import CertbotManager from './CertbotManager'
import DomainResolveChecker from './DomainResolveChecker'
import LoadBalancerManager from './LoadBalancerManager'
import SelfHostedDockerRegistry from './SelfHostedDockerRegistry'
import request = require('request')
import fs = require('fs-extra')
const DEBUG_SALT = 'THIS IS NOT A REAL CERTIFICATE'
const MAX_FAIL_ALLOWED = 4
const HEALTH_CHECK_INTERVAL = 20000 // ms
const TIMEOUT_HEALTH_CHECK = 15000 // ms
interface ISuccessCallback {
(success: boolean): void
}
class CaptainManager {
private hasForceSsl: boolean
private dataStore: DataStore
private dockerApi: DockerApi
private certbotManager: CertbotManager
private loadBalancerManager: LoadBalancerManager
private domainResolveChecker: DomainResolveChecker
private dockerRegistry: SelfHostedDockerRegistry
private backupManager: BackupManager
private myNodeId: string | undefined
private inited: boolean
private waitUntilRestarted: boolean
private captainSalt: string
private consecutiveHealthCheckFailCount: number
private healthCheckUuid: string
constructor() {
const dockerApi = DockerApi.get()
this.hasForceSsl = false
this.dataStore = DataStoreProvider.getDataStore(
CaptainConstants.rootNameSpace
)
this.dockerApi = dockerApi
this.certbotManager = new CertbotManager(dockerApi)
this.loadBalancerManager = new LoadBalancerManager(
dockerApi,
this.certbotManager,
this.dataStore
)
this.domainResolveChecker = new DomainResolveChecker(
this.loadBalancerManager,
this.certbotManager
)
this.myNodeId = undefined
this.inited = false
this.waitUntilRestarted = false
this.captainSalt = ''
this.consecutiveHealthCheckFailCount = 0
this.healthCheckUuid = uuid()
this.backupManager = new BackupManager()
}
initialize() {
// If a linked file / directory is deleted on the host, it loses the connection to
// the container and needs an update to be picked up again.
const self = this
const dataStore = this.dataStore
const dockerApi = this.dockerApi
const loadBalancerManager = this.loadBalancerManager
let myNodeId: string
self.refreshForceSslState()
.then(function () {
return dockerApi.getNodeIdByServiceName(
CaptainConstants.captainServiceName,
0
)
})
.then(function (nodeId) {
myNodeId = nodeId
self.myNodeId = myNodeId
self.dockerRegistry = new SelfHostedDockerRegistry(
self.dockerApi,
self.dataStore,
self.certbotManager,
self.loadBalancerManager,
self.myNodeId
)
return dockerApi.isNodeManager(myNodeId)
})
.then(function (isManager) {
if (!isManager) {
throw new Error('Captain should only run on a manager node')
}
})
.then(function () {
Logger.d('Emptying generated and temp folders.')
return fs.emptyDir(CaptainConstants.captainRootDirectoryTemp)
})
.then(function () {
return fs.emptyDir(
CaptainConstants.captainRootDirectoryGenerated
)
})
.then(function () {
Logger.d('Ensuring directories are available on host. Started.')
return fs.ensureDir(CaptainConstants.letsEncryptEtcPath)
})
.then(function () {
return fs.ensureDir(CaptainConstants.letsEncryptLibPath)
})
.then(function () {
return fs.ensureDir(CaptainConstants.captainStaticFilesDir)
})
.then(function () {
return fs.ensureDir(CaptainConstants.perAppNginxConfigPathBase)
})
.then(function () {
return fs.ensureFile(CaptainConstants.baseNginxConfigPath)
})
.then(function () {
return fs.ensureDir(CaptainConstants.registryPathOnHost)
})
.then(function () {
return dockerApi.ensureOverlayNetwork(
CaptainConstants.captainNetworkName
)
})
.then(function () {
Logger.d(
'Ensuring directories are available on host. Finished.'
)
return dockerApi.ensureServiceConnectedToNetwork(
CaptainConstants.captainServiceName,
CaptainConstants.captainNetworkName
)
})
.then(function () {
const valueIfNotExist = CaptainConstants.isDebug
? DEBUG_SALT
: uuid()
return dockerApi.ensureSecret(
CaptainConstants.captainSaltSecretKey,
valueIfNotExist
)
})
.then(function () {
return dockerApi.ensureSecretOnService(
CaptainConstants.captainServiceName,
CaptainConstants.captainSaltSecretKey
)
})
.then(function (secretHadExistedBefore) {
if (!secretHadExistedBefore) {
return new Promise<void>(function () {
Logger.d(
'I am halting here. I expect to get restarted in a few seconds due to a secret (captain salt) being updated.'
)
})
}
})
.then(function () {
const secretFileName = `/run/secrets/${CaptainConstants.captainSaltSecretKey}`
if (!fs.pathExistsSync(secretFileName)) {
throw new Error(
`Secret is attached according to Docker. But file cannot be found. ${secretFileName}`
)
}
const secretContent = fs.readFileSync(secretFileName).toString()
if (!secretContent) {
throw new Error('Salt secret content is empty!')
}
self.captainSalt = secretContent
return true
})
.then(function () {
return Authenticator.setMainSalt(self.getCaptainSalt())
})
.then(function () {
return dataStore.setEncryptionSalt(self.getCaptainSalt())
})
.then(function () {
return new MigrateCaptainDuckDuck(
dataStore,
Authenticator.getAuthenticator(dataStore.getNameSpace())
)
.migrateIfNeeded()
.then(function (migrationPerformed) {
if (migrationPerformed) {
return self.resetSelf()
}
})
})
.then(function () {
return loadBalancerManager.init(myNodeId, dataStore)
})
.then(function () {
return dataStore.getRegistriesDataStore().getAllRegistries()
})
.then(function (registries) {
let localRegistry: IRegistryInfo | undefined = undefined
for (let idx = 0; idx < registries.length; idx++) {
const element = registries[idx]
if (element.registryType === IRegistryTypes.LOCAL_REG) {
localRegistry = element
}
}
if (localRegistry) {
Logger.d('Ensuring Docker Registry is running...')
return self.dockerRegistry.ensureDockerRegistryRunningOnThisNode(
localRegistry.registryPassword
)
}
return Promise.resolve(true)
})
.then(function () {
return self.backupManager.startRestorationIfNeededPhase2(
self.getCaptainSalt(),
() => {
return self.ensureAllAppsInited()
}
)
})
.then(function () {
self.inited = true
self.performHealthCheck()
Logger.d(
'**** Captain is initialized and ready to serve you! ****'
)
})
.catch(function (error) {
Logger.e(error)
setTimeout(function () {
process.exit(0)
}, 5000)
})
}
getDomainResolveChecker() {
return this.domainResolveChecker
}
performHealthCheck() {
const self = this
const captainPublicDomain = `${
CaptainConstants.configs.captainSubDomain
}.${self.dataStore.getRootDomain()}`
function scheduleNextHealthCheck() {
self.healthCheckUuid = uuid()
setTimeout(function () {
self.performHealthCheck()
}, HEALTH_CHECK_INTERVAL)
}
// For debug build, we'll turn off health check
if (CaptainConstants.isDebug || !self.dataStore.hasCustomDomain()) {
scheduleNextHealthCheck()
return
}
function checkCaptainHealth(callback: ISuccessCallback) {
let callbackCalled = false
setTimeout(function () {
if (callbackCalled) {
return
}
callbackCalled = true
callback(false)
}, TIMEOUT_HEALTH_CHECK)
if (CaptainConstants.configs.skipVerifyingDomains) {
setTimeout(function () {
if (callbackCalled) {
return
}
callbackCalled = true
callback(true)
}, 10)
return
}
const url = `http://${captainPublicDomain}${CaptainConstants.healthCheckEndPoint}`
request(
url,
function (error, response, body) {
if (callbackCalled) {
return
}
callbackCalled = true
if (error || !body || body !== self.getHealthCheckUuid()) {
callback(false)
} else {
callback(true)
}
}
)
}
function checkNginxHealth(callback: ISuccessCallback) {
let callbackCalled = false
setTimeout(function () {
if (callbackCalled) {
return
}
callbackCalled = true
callback(false)
}, TIMEOUT_HEALTH_CHECK)
self.domainResolveChecker
.verifyCaptainOwnsDomainOrThrow(
captainPublicDomain,
'-healthcheck'
)
.then(function () {
if (callbackCalled) {
return
}
callbackCalled = true
callback(true)
})
.catch(function () {
if (callbackCalled) {
return
}
callbackCalled = true
callback(false)
})
}
interface IChecks {
captainHealth: { value: boolean }
nginxHealth: { value: boolean }
}
const checksPerformed = {} as IChecks
function scheduleIfNecessary() {
if (
!checksPerformed.captainHealth ||
!checksPerformed.nginxHealth
) {
return
}
let hasFailedCheck = false
if (!checksPerformed.captainHealth.value) {
Logger.w(
`Captain health check failed: #${self.consecutiveHealthCheckFailCount} at ${captainPublicDomain}`
)
hasFailedCheck = true
}
if (!checksPerformed.nginxHealth.value) {
Logger.w(
`NGINX health check failed: #${self.consecutiveHealthCheckFailCount}`
)
hasFailedCheck = true
}
if (hasFailedCheck) {
self.consecutiveHealthCheckFailCount =
self.consecutiveHealthCheckFailCount + 1
} else {
self.consecutiveHealthCheckFailCount = 0
}
scheduleNextHealthCheck()
if (self.consecutiveHealthCheckFailCount > MAX_FAIL_ALLOWED) {
process.exit(1)
}
}
checkCaptainHealth(function (success) {
checksPerformed.captainHealth = {
value: success,
}
scheduleIfNecessary()
})
checkNginxHealth(function (success) {
checksPerformed.nginxHealth = {
value: success,
}
scheduleIfNecessary()
})
}
getHealthCheckUuid() {
return this.healthCheckUuid
}
getBackupManager() {
return this.backupManager
}
getCertbotManager() {
return this.certbotManager
}
isInitialized() {
return (
this.inited &&
!this.waitUntilRestarted &&
!this.backupManager.isRunning()
)
}
ensureAllAppsInited() {
const self = this
return Promise.resolve() //
.then(function () {
return self.dataStore.getAppsDataStore().getAppDefinitions()
})
.then(function (apps) {
const promises: (() => Promise<void>)[] = []
const serviceManager = ServiceManager.get(
self.dataStore.getNameSpace(),
Authenticator.getAuthenticator(
self.dataStore.getNameSpace()
),
self.dataStore,
self.dockerApi,
CaptainManager.get().getLoadBalanceManager(),
CaptainManager.get().getDomainResolveChecker()
)
Object.keys(apps).forEach((appName) => {
promises.push(function () {
return Promise.resolve() //
.then(function () {
return serviceManager.ensureServiceInitedAndUpdated(
appName
)
})
.then(function () {
Logger.d(
`Waiting 5 second for the service to settle... ${appName}`
)
return Utils.getDelayedPromise(5000)
})
})
})
return Utils.runPromises(promises)
})
}
getMyNodeId() {
if (!this.myNodeId) {
const msg = 'myNodeId is not set yet!!'
Logger.e(msg)
throw new Error(msg)
}
return this.myNodeId
}
getCaptainSalt() {
if (!this.captainSalt) {
const msg = 'Captain Salt is not set yet!!'
Logger.e(msg)
throw new Error(msg)
}
return this.captainSalt
}
updateNetDataInfo(netDataInfo: NetDataInfo) {
const self = this
const dockerApi = this.dockerApi
return Promise.resolve()
.then(function () {
return dockerApi.ensureContainerStoppedAndRemoved(
CaptainConstants.netDataContainerName,
CaptainConstants.captainNetworkName
)
})
.then(function () {
if (netDataInfo.isEnabled) {
const vols = [
{
hostPath: '/proc',
containerPath: '/host/proc',
mode: 'ro',
},
{
hostPath: '/sys',
containerPath: '/host/sys',
mode: 'ro',
},
{
hostPath: '/var/run/docker.sock',
containerPath: '/var/run/docker.sock',
},
]
const envVars = []
if (netDataInfo.data.smtp) {
envVars.push({
key: 'SSMTP_TO',
value: netDataInfo.data.smtp.to,
})
envVars.push({
key: 'SSMTP_HOSTNAME',
value: netDataInfo.data.smtp.hostname,
})
envVars.push({
key: 'SSMTP_SERVER',
value: netDataInfo.data.smtp.server,
})
envVars.push({
key: 'SSMTP_PORT',
value: netDataInfo.data.smtp.port,
})
envVars.push({
key: 'SSMTP_TLS',
value: netDataInfo.data.smtp.allowNonTls
? 'NO'
: 'YES',
})
envVars.push({
key: 'SSMTP_USER',
value: netDataInfo.data.smtp.username,
})
envVars.push({
key: 'SSMTP_PASS',
value: netDataInfo.data.smtp.password,
})
}
if (netDataInfo.data.slack) {
envVars.push({
key: 'SLACK_WEBHOOK_URL',
value: netDataInfo.data.slack.hook,
})
envVars.push({
key: 'SLACK_CHANNEL',
value: netDataInfo.data.slack.channel,
})
}
if (netDataInfo.data.telegram) {
envVars.push({
key: 'TELEGRAM_BOT_TOKEN',
value: netDataInfo.data.telegram.botToken,
})
envVars.push({
key: 'TELEGRAM_CHAT_ID',
value: netDataInfo.data.telegram.chatId,
})
}
if (netDataInfo.data.pushBullet) {
envVars.push({
key: 'PUSHBULLET_ACCESS_TOKEN',
value: netDataInfo.data.pushBullet.apiToken,
})
envVars.push({
key: 'PUSHBULLET_DEFAULT_EMAIL',
value: netDataInfo.data.pushBullet.fallbackEmail,
})
}
return dockerApi.createStickyContainer(
CaptainConstants.netDataContainerName,
CaptainConstants.configs.netDataImageName,
vols,
CaptainConstants.captainNetworkName,
envVars,
['SYS_PTRACE'],
['apparmor:unconfined'],
undefined
)
}
// Just removing the old container. No need to create a new one.
return true
})
.then(function () {
return self.dataStore.setNetDataInfo(netDataInfo)
})
}
getNodesInfo() {
const dockerApi = this.dockerApi
return Promise.resolve()
.then(function () {
return dockerApi.getNodesInfo()
})
.then(function (data) {
if (!data || !data.length) {
throw ApiStatusCodes.createError(
ApiStatusCodes.STATUS_ERROR_GENERIC,
'No cluster node was found!'
)
}
return data
})
}
getLoadBalanceManager() {
return this.loadBalancerManager
}
getDockerRegistry() {
return this.dockerRegistry
}
enableSsl(emailAddress: string) {
const self = this
return Promise.resolve()
.then(function () {
return self.certbotManager.ensureRegistered(emailAddress)
})
.then(function () {
return self.certbotManager.enableSsl(
`${
CaptainConstants.configs.captainSubDomain
}.${self.dataStore.getRootDomain()}`
)
})
.then(function () {
return self.dataStore.setUserEmailAddress(emailAddress)
})
.then(function () {
return self.dataStore.setHasRootSsl(true)
})
.then(function () {
Logger.d('Updating Load Balancer - CaptainManager.enableSsl')
return self.loadBalancerManager.rePopulateNginxConfigFile(
self.dataStore
)
})
}
forceSsl(isEnabled: boolean) {
const self = this
return Promise.resolve()
.then(function () {
return self.dataStore.getHasRootSsl()
})
.then(function (hasRootSsl) {
if (!hasRootSsl && isEnabled) {
throw ApiStatusCodes.createError(
ApiStatusCodes.STATUS_ERROR_GENERIC,
'You first need to enable SSL on the root domain before forcing it.'
)
}
return self.dataStore.setForceSsl(isEnabled)
})
.then(function () {
return self.refreshForceSslState()
})
}
refreshForceSslState() {
const self = this
return Promise.resolve()
.then(function () {
return self.dataStore.getForceSsl()
})
.then(function (hasForceSsl) {
self.hasForceSsl = hasForceSsl
})
}
getForceSslValue() {
return !!this.hasForceSsl
}
getNginxConfig() {
const self = this
return Promise.resolve().then(function () {
return self.dataStore.getNginxConfig()
})
}
setNginxConfig(baseConfig: string, captainConfig: string) {
const self = this
return Promise.resolve()
.then(function () {
return self.dataStore.setNginxConfig(baseConfig, captainConfig)
})
.then(function () {
self.resetSelf()
})
}
changeCaptainRootDomain(requestedCustomDomain: string, force: boolean) {
const self = this
// Some DNS servers do not allow wild cards. Therefore this line may fail.
// We still allow users to specify the domains in their DNS settings individually
// SubDomains that need to be added are "captain." "registry." "app-name."
const url = `${uuid()}.${requestedCustomDomain}:${
CaptainConstants.nginxPortNumber
}`
return self.domainResolveChecker
.verifyDomainResolvesToDefaultServerOnHost(url)
.then(function () {
return self.dataStore.getHasRootSsl()
})
.then(function (hasRootSsl) {
if (
!force &&
hasRootSsl &&
self.dataStore.getRootDomain() !== requestedCustomDomain
) {
throw ApiStatusCodes.createError(
ApiStatusCodes.STATUS_ERROR_GENERIC,
'SSL is enabled for root. You can still force change the root domain, but read docs for consequences!'
)
}
if (force) {
return self
.forceSsl(false)
.then(function () {
return self.dataStore.setHasRootSsl(false)
})
.then(function () {
return self.dataStore
.getAppsDataStore()
.ensureAllAppsSubDomainSslDisabled()
})
}
})
.then(function () {
return self.dataStore
.getRegistriesDataStore()
.getAllRegistries()
})
.then(function (registries) {
let localRegistry: IRegistryInfo | undefined = undefined
for (let idx = 0; idx < registries.length; idx++) {
const element = registries[idx]
if (element.registryType === IRegistryTypes.LOCAL_REG) {
localRegistry = element
}
}
if (localRegistry) {
throw ApiStatusCodes.createError(
ApiStatusCodes.ILLEGAL_OPERATION,
'Delete your self-hosted Docker registry before changing the domain.'
)
}
return Promise.resolve(true)
})
.then(function () {
return self.dataStore.setCustomDomain(requestedCustomDomain)
})
.then(function () {
Logger.d(
'Updating Load Balancer - CaptainManager.changeCaptainRootDomain'
)
return self.loadBalancerManager.rePopulateNginxConfigFile(
self.dataStore
)
})
}
resetSelf() {
const self = this
Logger.d('Captain is resetting itself!')
self.waitUntilRestarted = true
return new Promise<void>(function (resolve, reject) {
setTimeout(function () {
return self.dockerApi.updateService(
CaptainConstants.captainServiceName,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined
)
}, 2000)
})
}
private static captainManagerInstance: CaptainManager | undefined
static get(): CaptainManager {
if (!CaptainManager.captainManagerInstance) {
CaptainManager.captainManagerInstance = new CaptainManager()
}
return CaptainManager.captainManagerInstance
}
}
export default CaptainManager