-
Notifications
You must be signed in to change notification settings - Fork 3
/
kubernetes.js
1185 lines (1088 loc) · 47.5 KB
/
kubernetes.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
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const got = require('got')
const FormData = require('form-data')
const k8s = require('@kubernetes/client-node')
const _ = require('lodash')
const awsEFS = require('./lib/aws-efs.js')
const {
deploymentTemplate,
serviceTemplate,
ingressTemplate,
customIngressTemplate,
persistentVolumeClaimTemplate
} = require('./templates.js')
/**
* Kubernates Container driver
*
* Handles the creation and deletation of containers to back Projects
*
* This driver creates Projects backed by Kubernates
*
* @module kubernates
* @memberof forge.containers.drivers
*
*/
const createDeployment = async (project, options) => {
const stack = project.ProjectStack.properties
const localDeployment = JSON.parse(JSON.stringify(deploymentTemplate))
const localPod = localDeployment.spec.template
localDeployment.metadata.name = project.safeName
localDeployment.metadata.labels.name = project.safeName
localDeployment.metadata.labels.app = project.id
localDeployment.spec.selector.matchLabels.app = project.id
// Examples:
// 1. With this affinity definitions we can skip toarations
// affinity:
// nodeAffinity:
// requiredDuringSchedulingIgnoredDuringExecution:
// nodeSelectorTerms:
// - matchExpressions:
// - key: node-owner
// operator: In
// values:
// - streaming-services-transcribe
// 2. With this affinity
// preferredDuringSchedulingIgnoredDuringExecution:
// - weight: 100
// preference:
// matchExpressions:
// - key: purpose
// operator: In
// values:
// - skills
// ---> we need these tolerations
// tolerations:
// - key: purpose
// operator: Equal
// value: skills
// effect: NoSchedule
if (process.env.DEPLOYMENT_TOLERATIONS !== undefined) {
// TOLERATIONS
try {
localPod.spec.tolerations = JSON.parse(process.env.DEPLOYMENT_TOLERATIONS)
this._app.log.info(`DEPLOYMENT TOLERATIONS loaded: ${localPod.spec.tolerations}`)
} catch (err) {
this._app.log.error(`TOLERATIONS load error: ${err}`)
}
}
localPod.metadata.labels.app = project.id
localPod.metadata.labels.name = project.safeName
localPod.spec.serviceAccount = process.env.EDITOR_SERVICE_ACCOUNT
if (stack.container) {
localPod.spec.containers[0].image = stack.container
} else {
localPod.spec.containers[0].image = `${this._options.registry}flowforge/node-red`
}
const baseURL = new URL(this._app.config.base_url)
let projectURL
if (!project.url.startsWith('http')) {
projectURL = `${baseURL.protocol}//${project.safeName}.${this._options.domain}`
} else {
const temp = new URL(project.url)
projectURL = `${temp.protocol}//${temp.hostname}${temp.port ? ':' + temp.port : ''}`
}
const teamID = this._app.db.models.Team.encodeHashid(project.TeamId)
const authTokens = await project.refreshAuthTokens()
localPod.spec.containers[0].env.push({ name: 'FORGE_CLIENT_ID', value: authTokens.clientID })
localPod.spec.containers[0].env.push({ name: 'FORGE_CLIENT_SECRET', value: authTokens.clientSecret })
localPod.spec.containers[0].env.push({ name: 'FORGE_URL', value: this._app.config.api_url })
localPod.spec.containers[0].env.push({ name: 'BASE_URL', value: projectURL })
localPod.spec.containers[0].env.push({ name: 'FORGE_TEAM_ID', value: teamID })
localPod.spec.containers[0].env.push({ name: 'FORGE_PROJECT_ID', value: project.id })
localPod.spec.containers[0].env.push({ name: 'FORGE_PROJECT_TOKEN', value: authTokens.token })
// Inbound connections for k8s disabled by default
localPod.spec.containers[0].env.push({ name: 'FORGE_NR_NO_TCP_IN', value: 'true' }) // MVP. Future iteration could present this to YML or UI
localPod.spec.containers[0].env.push({ name: 'FORGE_NR_NO_UDP_IN', value: 'true' }) // MVP. Future iteration could present this to YML or UI
if (authTokens.broker) {
localPod.spec.containers[0].env.push({ name: 'FORGE_BROKER_URL', value: authTokens.broker.url })
localPod.spec.containers[0].env.push({ name: 'FORGE_BROKER_USERNAME', value: authTokens.broker.username })
localPod.spec.containers[0].env.push({ name: 'FORGE_BROKER_PASSWORD', value: authTokens.broker.password })
}
if (this._app.license.active()) {
localPod.spec.containers[0].env.push({ name: 'FORGE_LICENSE_TYPE', value: 'ee' })
}
if (stack.memory) {
localPod.spec.containers[0].env.push({ name: 'FORGE_MEMORY_LIMIT', value: `${stack.memory}` })
}
if (stack.cpu) {
localPod.spec.containers[0].env.push({ name: 'FORGE_CPU_LIMIT', value: `${stack.cpu}` })
}
const credentialSecret = await project.getSetting('credentialSecret')
if (credentialSecret) {
localPod.spec.containers[0].env.push({ name: 'FORGE_NR_SECRET', value: credentialSecret })
}
if (this._logPassthrough) {
localPod.spec.containers[0].env.push({ name: 'FORGE_LOG_PASSTHROUGH', value: 'true' })
}
if (this._app.config.driver.options.projectSelector) {
localPod.spec.nodeSelector = this._app.config.driver.options.projectSelector
}
if (this._app.config.driver.options.registrySecrets) {
localPod.spec.imagePullSecrets = []
this._app.config.driver.options.registrySecrets.forEach(sec => {
const entry = {
name: sec
}
localPod.spec.imagePullSecrets.push(entry)
})
}
if (this._app.config.driver.options?.privateCA) {
localPod.spec.containers[0].volumeMounts = [
{
name: 'cacert',
mountPath: '/usr/local/ssl-certs',
readOnly: true
}
]
localPod.spec.volumes = [
{
name: 'cacert',
configMap: {
name: this._app.config.driver.options.privateCA
}
}
]
localPod.spec.containers[0].env.push({ name: 'NODE_EXTRA_CA_CERTS', value: '/usr/local/ssl-certs/chain.pem' })
}
if (this._app.config.driver.options?.storage?.enabled) {
const volMount = {
name: 'persistence',
mountPath: '/data/storage'
}
const vol = {
name: 'persistence',
persistentVolumeClaim: {
claimName: `${project.id}-pvc`
}
}
if (Array.isArray(localPod.spec.containers[0].volumeMounts)) {
localPod.spec.containers[0].volumeMounts.push(volMount)
} else {
localPod.spec.containers[0].volumeMounts = [volMount]
}
if (Array.isArray(localPod.spec.volumes)) {
localPod.spec.volumes.push(vol)
} else {
localPod.spec.volumes = [vol]
}
}
if (this._app.license.active() && this._cloudProvider === 'openshift') {
localPod.spec.securityContext = {}
}
if (stack.memory && stack.cpu) {
localPod.spec.containers[0].resources.requests.memory = `${stack.memory}Mi`
// increase limit to give npm more room to run in
localPod.spec.containers[0].resources.limits.memory = `${parseInt(stack.memory) + 128}Mi`
localPod.spec.containers[0].resources.requests.cpu = `${stack.cpu * 10}m`
localPod.spec.containers[0].resources.limits.cpu = `${stack.cpu * 10}m`
}
const ha = await project.getSetting('ha')
if (ha?.replicas > 1) {
localDeployment.spec.replicas = ha.replicas
}
project.url = projectURL
await project.save()
return localDeployment
}
const createService = async (project, options) => {
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
const localService = JSON.parse(JSON.stringify(serviceTemplate))
localService.metadata.name = `${prefix}${project.safeName}`
localService.spec.selector.name = project.safeName
return localService
}
const mustache = (string, data = {}) =>
Object.entries(data).reduce((res, [key, value]) => res.replace(new RegExp(`{{\\s*${key}\\s*}}`, 'g'), value), string)
const createIngress = async (project, options) => {
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
const url = new URL(project.url)
// exposedData available for annotation replacements
const exposedData = {
serviceName: `${prefix}${project.safeName}`,
instanceURL: url.href,
instanceHost: url.host,
instanceProtocol: url.protocol
}
this._app.log.info('K8S DRIVER: start parse ingress template')
const localIngress = JSON.parse(JSON.stringify(ingressTemplate))
if (this._certManagerIssuer) {
localIngress.metadata.annotations['cert-manager.io/cluster-issuer'] = this._certManagerIssuer
localIngress.spec.tls = [
{
hosts: [
url.host
],
secretName: project.safeName
}
]
}
// process annotations with potential replacements
Object.keys(localIngress.metadata.annotations).forEach((key) => {
localIngress.metadata.annotations[key] = mustache(localIngress.metadata.annotations[key], exposedData)
})
localIngress.metadata.name = project.safeName
localIngress.spec.rules[0].host = url.host
localIngress.spec.rules[0].http.paths[0].backend.service.name = `${prefix}${project.safeName}`
return localIngress
}
const createCustomIngress = async (project, hostname, options) => {
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
const url = new URL(project.url)
url.host = hostname
// exposedData available for annotation replacements
const exposedData = {
serviceName: `${prefix}${project.safeName}`,
instanceURL: url.href,
instanceHost: url.host,
instanceProtocol: url.protocol
}
this._app.log.info('K8S DRIVER: start custom hostname ingress template')
const customIngress = JSON.parse(JSON.stringify(customIngressTemplate))
customIngress.metadata.name = `${project.safeName}-custom`
customIngress.spec.rules[0].host = hostname
customIngress.spec.rules[0].http.paths[0].backend.service.name = `${prefix}${project.safeName}`
if (this._customHostname?.certManagerIssuer) {
customIngress.metadata.annotations['cert-manager.io/cluster-issuer'] = this._customHostname.certManagerIssuer
customIngress.spec.tls = [
{
hosts: [
hostname
],
secretName: `${project.safeName}-custom`
}
]
}
// process annotations with potential replacements
Object.keys(customIngress.metadata.annotations).forEach((key) => {
customIngress.metadata.annotations[key] = mustache(customIngress.metadata.annotations[key], exposedData)
})
if (this._customHostname?.ingressClass) {
customIngress.spec.ingressClassName = `${this._customHostname.ingressClass}`
}
return customIngress
}
const createPersistentVolumeClaim = async (project, options) => {
const namespace = this._app.config.driver.options?.projectNamespace || 'flowforge'
const pvc = JSON.parse(JSON.stringify(persistentVolumeClaimTemplate))
const drvOptions = this._app.config.driver.options
if (drvOptions?.storage?.storageClass) {
pvc.spec.storageClassName = drvOptions.storage.storageClass
} else if (drvOptions?.storage?.storageClassEFSTag) {
pvc.spec.storageClassName = await awsEFS.lookupStorageClass(drvOptions?.storage?.storageClassEFSTag)
}
if (drvOptions?.storage?.size) {
pvc.spec.resources.requests.storage = drvOptions.storage.size
}
pvc.metadata.namespace = namespace
pvc.metadata.name = `${project.id}-pvc`
pvc.metadata.labels = {
'ff-project-id': project.id,
'ff-project-name': project.safeName
}
console.log(`PVC: ${JSON.stringify(pvc, null, 2)}`)
return pvc
}
const createProject = async (project, options) => {
const namespace = this._app.config.driver.options.projectNamespace || 'flowforge'
const localDeployment = await createDeployment(project, options)
const localService = await createService(project, options)
const localIngress = await createIngress(project, options)
if (this._app.config.driver.options?.storage?.enabled) {
const localPVC = await createPersistentVolumeClaim(project, options)
// console.log(JSON.stringify(localPVC, null, 2))
try {
await this._k8sApi.createNamespacedPersistentVolumeClaim(namespace, localPVC)
} catch (err) {
if (err.statusCode === 409) {
this._app.log.warn(`[k8s] PVC for instance ${project.id} already exists, proceeding...`)
} else {
if (project.state !== 'suspended') {
this._app.log.error(`[k8s] Instance ${project.id} - error creating PVC: ${err.toString()} ${err.statusCode}`)
// console.log(err)
throw err
}
}
}
}
try {
await this._k8sAppApi.createNamespacedDeployment(namespace, localDeployment)
} catch (err) {
if (err.statusCode === 409) {
// If deployment exists, perform an upgrade
this._app.log.warn(`[k8s] Deployment for instance ${project.id} already exists. Upgrading deployment`)
const result = await this._k8sAppApi.readNamespacedDeployment(project.safeName, namespace)
const existingDeployment = result.body
// Check if the metadata and spec are aligned. They won't be though (at minimal because we regenerate auth)
if (!_.isEqual(existingDeployment.metadata, localDeployment.metadata) || !_.isEqual(existingDeployment.spec, localDeployment.spec)) {
// If not aligned, replace the deployment
await this._k8sAppApi.replaceNamespacedDeployment(project.safeName, namespace, localDeployment)
}
} else {
// Log other errors and rethrow them for additional higher-level handling
this._app.log.error(`[k8s] Unexpected error creating deployment for instance ${project.id}.`)
this._app.log.error(`[k8s] deployment ${JSON.stringify(localDeployment, undefined, 2)}`)
this._app.log.error(err)
// rethrow the error so the wrapper knows this hasn't worked
throw err
}
}
await new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
await this._k8sAppApi.readNamespacedDeployment(project.safeName, this._namespace)
clearInterval(pollInterval)
resolve()
} catch (err) {
// hmm
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timeout waiting for Deployment`)
reject(new Error('Timed out to creating Deployment'))
}
}
}, this._k8sDelay)
})
try {
await this._k8sApi.createNamespacedService(namespace, localService)
} catch (err) {
if (err.statusCode === 409) {
this._app.log.warn(`[k8s] Service for instance ${project.id} already exists, proceeding...`)
} else {
if (project.state !== 'suspended') {
this._app.log.error(`[k8s] Instance ${project.id} - error creating service: ${err.toString()}`)
throw err
}
}
}
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
await new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
await this._k8sApi.readNamespacedService(prefix + project.safeName, this._namespace)
clearInterval(pollInterval)
resolve()
} catch (err) {
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timeout waiting for Service`)
reject(new Error('Timed out to creating Service'))
}
}
}, this._k8sDelay)
})
try {
await this._k8sNetApi.createNamespacedIngress(namespace, localIngress)
} catch (err) {
if (err.statusCode === 409) {
this._app.log.warn(`[k8s] Ingress for instance ${project.id} already exists, proceeding...`)
} else {
if (project.state !== 'suspended') {
this._app.log.error(`[k8s] Instance ${project.id} - error creating ingress: ${err.toString()}`)
throw err
}
}
}
if (this._customHostname?.enabled) {
const customHostname = await project.getSetting('customHostname')
if (customHostname) {
const customHostnameIngress = await createCustomIngress(project, customHostname, options)
try {
await this._k8sNetApi.createNamespacedIngress(namespace, customHostnameIngress)
} catch (err) {
if (err.statusCode === 409) {
this._app.log.warn(`[k8s] Custom Hostname Ingress for instance ${project.id} already exists, proceeding...`)
} else {
if (project.state !== 'suspended') {
this._app.log.error(`[k8s] Instance ${project.id} - error creating custom hostname ingress: ${err.toString()}`)
throw err
}
}
}
}
}
await new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
await this._k8sNetApi.readNamespacedIngress(project.safeName, this._namespace)
clearInterval(pollInterval)
resolve()
} catch (err) {
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timeout waiting for Ingress`)
reject(new Error('Timed out to creating Ingress'))
}
}
}, this._k8sDelay)
})
await project.updateSetting('k8sType', 'deployment')
this._app.log.debug(`[k8s] Container ${project.id} started`)
project.state = 'running'
await project.save()
this._projects[project.id].state = 'starting'
}
const getEndpoints = async (project) => {
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
if (await project.getSetting('ha')) {
const endpoints = await this._k8sApi.readNamespacedEndpoints(`${prefix}${project.safeName}`, this._namespace)
const addresses = endpoints.body.subsets[0].addresses.map(a => { return a.ip })
const hosts = []
for (const address in addresses) {
hosts.push(addresses[address])
}
return hosts
} else {
return [`${prefix}${project.safeName}.${this._namespace}`]
}
}
const getStaticFileUrl = async (instance, filePath) => {
const prefix = instance.safeName.match(/^[0-9]/) ? 'srv-' : ''
return `http://${prefix}${instance.safeName}.${this._namespace}:2880/flowforge/files/_/${encodeURIComponent(filePath)}`
}
module.exports = {
/**
* Initialises this driver
* @param {string} app - the Vue application
* @param {object} options - A set of configuration options for the driver
* @return {forge.containers.ProjectArguments}
*/
init: async (app, options) => {
this._app = app
this._projects = {}
this._options = options
this._namespace = this._app.config.driver.options?.projectNamespace || 'flowforge'
this._k8sDelay = this._app.config.driver.options?.k8sDelay || 1000
this._k8sRetries = this._app.config.driver.options?.k8sRetries || 10
this._certManagerIssuer = this._app.config.driver.options?.certManagerIssuer
this._logPassthrough = this._app.config.driver.options?.logPassthrough || false
this._cloudProvider = this._app.config.driver.options?.cloudProvider
if (this._app.config.driver.options?.customHostname?.enabled) {
this._app.log.info('[k8s] Enabling Custom Hostname Support')
this._customHostname = this._app.config.driver.options?.customHostname
}
const kc = new k8s.KubeConfig()
options.registry = app.config.driver.options?.registry || '' // use docker hub registry
if (options.registry !== '' && !options.registry.endsWith('/')) {
options.registry += '/'
}
kc.loadFromDefault()
this._k8sApi = kc.makeApiClient(k8s.CoreV1Api)
this._k8sAppApi = kc.makeApiClient(k8s.AppsV1Api)
this._k8sNetApi = kc.makeApiClient(k8s.NetworkingV1Api)
// Get a list of all projects - with the absolute minimum of fields returned
const projects = await app.db.models.Project.findAll({
attributes: [
'id',
'name',
'state',
'ProjectStackId',
'TeamId'
]
})
projects.forEach(async (project) => {
if (this._projects[project.id] === undefined) {
this._projects[project.id] = {
state: 'unknown'
}
}
})
this._initialCheckTimeout = setTimeout(() => {
this._app.log.debug('[k8s] Restarting projects')
const namespace = this._namespace
projects.forEach(async (project) => {
try {
if (project.state === 'suspended') {
// Do not restart suspended projects
return
}
// need to upgrade bare pods to deployments
// try {
// this._app.log.info(`[k8s] Testing ${project.id} in ${namespace} is bare pod`)
// await this._k8sApi.readNamespacedPodStatus(project.safeName, namespace)
// // should only get here is a bare pod exists
// this._app.log.info(`[k8s] upgrading ${project.id} to deployment`)
// const fullProject = await this._app.db.models.Project.byId(project.id)
// const localDeployment = await createDeployment(fullProject, options)
// this._k8sAppApi.createNamespacedDeployment(namespace, localDeployment)
// .then(() => {
// return this._k8sApi.deleteNamespacedPod(project.safeName, namespace)
// })
// .catch(err => {
// this._app.log.error(`[k8s] failed to upgrade ${project.id} to deployment`)
// })
// // it's just been created, not need to check if it still exists in the next block
// return
// } catch (err) {
// // bare pod not found can move on
// this._app.log.info(`[k8s] ${project.id} in ${namespace} is not bare pod`)
// }
// look for missing projects
const currentType = await project.getSetting('k8sType')
if (currentType === 'deployment') {
try {
this._app.log.info(`[k8s] Testing ${project.id} in ${namespace} deployment exists`)
await this._k8sAppApi.readNamespacedDeployment(project.safeName, namespace)
this._app.log.info(`[k8s] deployment ${project.id} in ${namespace} found`)
} catch (err) {
this._app.log.error(`[k8s] Error while reading namespaced deployment for project '${project.safeName}' ${project.id}. Error msg=${err.message}, stack=${err.stack}`)
this._app.log.info(`[k8s] Instance ${project.id} - recreating deployment`)
const fullProject = await this._app.db.models.Project.byId(project.id)
await createProject(fullProject, options)
}
} else {
try {
// pod already running
this._app.log.info(`[k8s] Testing ${project.id} in ${namespace} pod exists`)
await this._k8sApi.readNamespacedPodStatus(project.safeName, namespace)
this._app.log.info(`[k8s] pod ${project.id} in ${namespace} found`)
} catch (err) {
this._app.log.debug(`[k8s] Instance ${project.id} - recreating deployment`)
const fullProject = await this._app.db.models.Project.byId(project.id)
await createProject(fullProject, options)
}
}
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error resuming project: ${err.stack}`)
}
})
}, 1000)
// need to work out what we can expose for K8s
return {
stack: {
properties: {
cpu: {
label: 'CPU Cores (in 1/100th units)',
validate: '^([1-9][0-9]{0,2}|1000)$',
invalidMessage: 'Invalid value - must be a number between 1 and 1000, where 100 represents 1 CPU core',
description: 'Defines the CPU resources each Project should receive, in units of 1/100th of a CPU core. 100 equates to 1 CPU core'
},
memory: {
label: 'Memory (MB)',
validate: '^[1-9]\\d*$',
invalidMessage: 'Invalid value - must be a number',
description: 'How much memory the container for each Project will be granted, recommended value 256'
},
container: {
label: 'Container Location',
// taken from https://stackoverflow.com/a/62964157
validate: '^(([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])(:[0-9]+\\/)?(?:[0-9a-z-]+[/@])(?:([0-9a-z-]+))[/@]?(?:([0-9a-z-]+))?(?::[a-z0-9\\.-]+)?$',
invalidMessage: 'Invalid value - must be a Docker image',
description: 'Container image location, can include a tag'
}
}
}
}
},
/**
* Start a Project
* @param {Project} project - the project model instance
* @return {forge.containers.Project}
*/
start: async (project) => {
this._projects[project.id] = {
state: 'starting'
}
// Rather than await this promise, we return it. That allows the wrapper
// to respond to the create request much quicker and the create can happen
// asynchronously.
// If the create fails, the Project still exists but will be put in suspended
// state (and taken out of billing if enabled).
// Remember, this call is used for both creating a new project as well as
// restarting an existing project
// return createPod(project)
return createProject(project, this._options)
},
/**
* Stop a Project
* @param {Project} project - the project model instance
*/
stop: async (project) => {
// Stop the project
this._projects[project.id].state = 'stopping'
try {
await this._k8sNetApi.deleteNamespacedIngress(project.safeName, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting ingress: ${err.toString()}`)
}
if (this._certManagerIssuer) {
try {
await this._k8sApi.deleteNamespacedSecret(project.safeName, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting tls secret: ${err.toString()}`)
}
}
if (this._customHostname?.enabled) {
try {
await this._k8sNetApi.deleteNamespacedIngress(`${project.safeName}-custom`, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting custom ingress: ${err.toString()}`)
}
if (this._customHostname?.certManagerIssuer) {
try {
await this._k8sApi.deleteNamespacedSecret(`${project.safeName}-custom`, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting custom tls secret: ${err.toString()}`)
}
}
}
// Note that, regardless, the main objective is to delete deployment (runnable)
// Even if some k8s resources like ingress or service are still not deleted (maybe because of
// k8s service latency), the most important thing is to get to deployment.
try {
await new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
await this._k8sNetApi.readNamespacedIngress(project.safeName, this._namespace)
} catch (err) {
clearInterval(pollInterval)
resolve()
}
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timed out deleting ingress`)
reject(new Error('Timed out to deleting Ingress'))
}
}, this._k8sDelay)
})
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - Ingress was not deleted: ${err.toString()}`)
}
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
try {
await this._k8sApi.deleteNamespacedService(prefix + project.safeName, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting service: ${err.toString()}`)
}
try {
await new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
await this._k8sApi.readNamespacedService(prefix + project.safeName, this._namespace)
} catch (err) {
clearInterval(pollInterval)
resolve()
}
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timed deleting service`)
reject(new Error('Timed out to deleting Service'))
}
}, this._k8sDelay)
})
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - Service was not deleted: ${err.toString()}`)
}
const currentType = await project.getSetting('k8sType')
let pod = true
if (currentType === 'deployment') {
await this._k8sAppApi.deleteNamespacedDeployment(project.safeName, this._namespace)
pod = false
} else {
await this._k8sApi.deleteNamespacedPod(project.safeName, this._namespace)
}
// We should not delete the PVC when the instance is suspended
// if (this._app.config.driver.options?.storage?.enabled) {
// try {
// await this._k8sApi.deleteNamespacedPersistentVolumeClaim(`${project.safeName}-pvc`, this._namespace)
// } catch (err) {
// this._app.log.error(`[k8s] Instance ${project.id} - error deleting PVC: ${err.toString()} ${err.statusCode}`)
// }
// }
this._projects[project.id].state = 'suspended'
return new Promise((resolve, reject) => {
let counter = 0
const pollInterval = setInterval(async () => {
try {
if (pod) {
await this._k8sApi.readNamespacedPodStatus(project.safeName, this._namespace)
} else {
await this._k8sAppApi.readNamespacedDeployment(project.safeName, this._namespace)
}
counter++
if (counter > this._k8sRetries) {
clearInterval(pollInterval)
this._app.log.error(`[k8s] Instance ${project.id} - timed deleting ${pod ? 'Pod' : 'Deployment'}`)
reject(new Error('Timed out to deleting Deployment'))
}
} catch (err) {
clearInterval(pollInterval)
resolve()
}
}, this._k8sDelay)
})
},
/**
* Removes a Project
* @param {Project} project - the project model instance
* @return {Object}
*/
remove: async (project) => {
try {
await this._k8sNetApi.deleteNamespacedIngress(project.safeName, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting ingress: ${err.toString()}`)
}
if (this._certManagerIssuer) {
try {
await this._k8sApi.deleteNamespacedSecret(project.safeName, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting tls secret: ${err.toString()}`)
}
}
if (this._customHostname?.enabled) {
try {
await this._k8sNetApi.deleteNamespacedIngress(`${project.safeName}-custom`, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting custom ingress: ${err.toString()}`)
}
if (this._customHostname?.certManagerIssuer) {
try {
await this._k8sApi.deleteNamespacedSecret(`${project.safeName}-custom`, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting custom tls secret: ${err.toString()}`)
}
}
}
try {
if (project.safeName.match(/^[0-9]/)) {
await this._k8sApi.deleteNamespacedService('srv-' + project.safeName, this._namespace)
} else {
await this._k8sApi.deleteNamespacedService(project.safeName, this._namespace)
}
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting service: ${err.toString()}`)
}
const currentType = await project.getSetting('k8sType')
try {
// A suspended project won't have a pod to delete - but try anyway
// just in case state has got out of sync
if (currentType === 'deployment') {
await this._k8sAppApi.deleteNamespacedDeployment(project.safeName, this._namespace)
} else {
await this._k8sApi.deleteNamespacedPod(project.safeName, this._namespace)
}
} catch (err) {
if (project.state !== 'suspended') {
if (currentType === 'deployment') {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting deployment: ${err.toString()}`)
} else {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting pod: ${err.toString()}`)
}
}
}
if (this._app.config.driver.options?.storage?.enabled) {
try {
await this._k8sApi.deleteNamespacedPersistentVolumeClaim(`${project.id}-pvc`, this._namespace)
} catch (err) {
this._app.log.error(`[k8s] Instance ${project.id} - error deleting PVC: ${err.toString()} ${err.statusCode}`)
// console.log(err)
}
}
delete this._projects[project.id]
},
/**
* Retrieves details of a project's container
* @param {Project} project - the project model instance
* @return {Object}
*/
details: async (project) => {
if (this._projects[project.id] === undefined) {
return { state: 'unknown' }
}
if (this._projects[project.id].state === 'suspended') {
// We should only poll the launcher if we think it is running.
// Otherwise, return our cached state
return {
state: this._projects[project.id].state
}
}
const prefix = project.safeName.match(/^[0-9]/) ? 'srv-' : ''
// this._app.log.debug('checking actual pod, not cache')
/** @type { { response: IncomingMessage, body: k8s.V1Deployment } } */
let details
const currentType = await project.getSetting('k8sType')
try {
if (currentType === 'deployment') {
details = await this._k8sAppApi.readNamespacedDeployment(project.safeName, this._namespace)
if (details.body.status?.conditions[0].status === 'False') {
// return "starting" status until pod it running
this._projects[project.id].state = 'starting'
return {
id: project.id,
state: 'starting',
meta: {}
}
} else if (details.body.status?.conditions[0].status === 'True' &&
(details.body.status?.conditions[0].type === 'Available' ||
(details.body.status?.conditions[0].type === 'Progressing' && details.body.status?.conditions[0].reason === 'NewReplicaSetAvailable')
)) {
// not calling all endpoints for HA as they should be the same
const infoURL = `http://${prefix}${project.safeName}.${this._namespace}:2880/flowforge/info`
try {
const info = JSON.parse((await got.get(infoURL)).body)
this._projects[project.id].state = info.state
return info
} catch (err) {
this._app.log.debug(`error getting state from instance ${project.id}: ${err}`)
return {
id: project.id,
state: 'starting',
meta: {}
}
}
} else {
return {
id: project.id,
state: 'starting',
error: `Unexpected pod status '${details.body.status?.conditions[0]?.status}', type '${details.body.status?.conditions[0]?.type}'`,
meta: {}
}
}
} else {
details = await this._k8sApi.readNamespacedPodStatus(project.safeName, this._namespace)
if (details.body.status?.phase === 'Pending') {
// return "starting" status until pod it running
this._projects[project.id].state = 'starting'
return {
id: project.id,
state: 'starting',
meta: {}
}
} else if (details.body.status?.phase === 'Running') {
// not calling all endpoints for HA as they should be the same
const infoURL = `http://${prefix}${project.safeName}.${this._namespace}:2880/flowforge/info`
try {
const info = JSON.parse((await got.get(infoURL)).body)
this._projects[project.id].state = info.state
return info
} catch (err) {
this._app.log.debug(`error getting state from instance ${project.id}: ${err}`)
return {
id: project.id,
state: 'starting',
meta: {}
}
}
} else {
return {
id: project.id,
state: 'starting',
error: `Unexpected pod status '${details.body.status?.phase}'`,
meta: {}
}
}
}
} catch (err) {
this._app.log.debug(`error getting pod status for instance ${project.id}: ${err}`)
return {
id: project?.id,
error: err,
state: 'starting',
meta: details?.body?.status
}
}
},
/**
* Returns the settings for the project
* @param {Project} project - the project model instance
*/
settings: async (project) => {
const settings = {}
settings.projectID = project.id
settings.port = 1880
settings.rootDir = '/'
settings.userDir = 'data'
return settings
},
/**
* Starts the flows
* @param {Project} project - the project model instance
* @return {forge.Status}
*/