-
Notifications
You must be signed in to change notification settings - Fork 62
/
kube.ts
1299 lines (1185 loc) · 45.1 KB
/
kube.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
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
/*********************************************************************
* Copyright (c) 2019 Red Hat, Inc.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
**********************************************************************/
import { ApiextensionsV1beta1Api, ApisApi, AppsV1Api, CoreV1Api, CustomObjectsApi, ExtensionsV1beta1Api, KubeConfig, RbacAuthorizationV1Api, V1beta1CustomResourceDefinition, V1beta1IngressList, V1ClusterRole, V1ClusterRoleBinding, V1ConfigMap, V1ConfigMapEnvSource, V1Container, V1DeleteOptions, V1Deployment, V1DeploymentList, V1DeploymentSpec, V1EnvFromSource, V1LabelSelector, V1ObjectMeta, V1PersistentVolumeClaimList, V1Pod, V1PodSpec, V1PodTemplateSpec, V1Role, V1RoleBinding, V1RoleRef, V1Secret, V1ServiceAccount, V1ServiceList, V1Subject } from '@kubernetes/client-node'
import axios from 'axios'
import { cli } from 'cli-ux'
import { readFileSync } from 'fs'
import https = require('https')
import * as yaml from 'js-yaml'
import { DEFAULT_CHE_IMAGE } from '../constants'
export class KubeHelper {
kc = new KubeConfig()
podWaitTimeout: number
podReadyTimeout: number
constructor(flags?: any, context?: string) {
if (!context) {
this.kc.loadFromDefault()
} else {
this.kc.loadFromString(context)
}
if (flags && flags.k8spodwaittimeout) {
this.podWaitTimeout = parseInt(flags.k8spodwaittimeout, 10)
} else {
this.podWaitTimeout = 300000
}
if (flags && flags.k8spodreadytimeout) {
this.podReadyTimeout = parseInt(flags.k8spodreadytimeout, 10)
} else {
this.podReadyTimeout = 130000
}
}
async deleteAllServices(namespace = '') {
const k8sApi = this.kc.makeApiClient(CoreV1Api)
try {
const res = await k8sApi.listNamespacedService(namespace, true)
if (res && res.response && res.response.statusCode === 200) {
const serviceList = res.body
const options = new V1DeleteOptions()
await serviceList.items.forEach(async service => {
await k8sApi.deleteNamespacedService(service.metadata!.name!, namespace, undefined, options)
})
}
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async getServicesBySelector(labelSelector = '', namespace = ''): Promise<V1ServiceList> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
const res = await k8sCoreApi.listNamespacedService(namespace, true, 'true', undefined, undefined, labelSelector)
if (res && res.body) {
return res.body
}
} catch (e) {
throw this.wrapK8sClientError(e)
}
throw new Error('ERR_LIST_SERVICES')
}
async waitForService(selector: string, namespace = '', intervalMs = 500, timeoutMs = 30000) {
const iterations = timeoutMs / intervalMs
for (let index = 0; index < iterations; index++) {
let currentServices = await this.getServicesBySelector(selector, namespace)
if (currentServices && currentServices.items.length > 0) {
return
}
await cli.wait(intervalMs)
}
throw new Error(`ERR_TIMEOUT: Timeout set to waiting for service ${timeoutMs}`)
}
async serviceAccountExist(name = '', namespace = ''): Promise<boolean> {
const k8sApi = this.kc.makeApiClient(CoreV1Api)
try {
const { body } = await k8sApi.readNamespacedServiceAccount(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async createServiceAccount(name = '', namespace = '') {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
let sa = new V1ServiceAccount()
sa.metadata = new V1ObjectMeta()
sa.metadata.name = name
sa.metadata.namespace = namespace
try {
return await k8sCoreApi.createNamespacedServiceAccount(namespace, sa)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteServiceAccount(name = '', namespace = '') {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
const options = new V1DeleteOptions()
await k8sCoreApi.deleteNamespacedServiceAccount(name, namespace, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createServiceAccountFromFile(filePath: string, namespace = '') {
const yamlServiceAccount = this.safeLoadFromYamlFile(filePath) as V1ServiceAccount
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
return await k8sCoreApi.createNamespacedServiceAccount(namespace, yamlServiceAccount)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async replaceServiceAccountFromFile(filePath: string, namespace = '') {
const yamlServiceAccount = this.safeLoadFromYamlFile(filePath) as V1ServiceAccount
if (!yamlServiceAccount || !yamlServiceAccount.metadata || !yamlServiceAccount.metadata.name) {
throw new Error(`Service account read from ${filePath} must have name specified.`)
}
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
return await k8sCoreApi.replaceNamespacedServiceAccount(yamlServiceAccount.metadata.name, namespace, yamlServiceAccount)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async roleExist(name = '', namespace = ''): Promise<boolean> {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const { body } = await k8sRbacAuthApi.readNamespacedRole(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async clusterRoleExist(name = ''): Promise<boolean> {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const { body } = await k8sRbacAuthApi.readClusterRole(name)
return this.compare(body, name)
} catch {
return false
}
}
async createRoleFromFile(filePath: string, namespace = '') {
const yamlRole = this.safeLoadFromYamlFile(filePath) as V1Role
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const res = await k8sRbacAuthApi.createNamespacedRole(namespace, yamlRole)
return res.response.statusCode
} catch (e) {
if (e.response && e.response.statusCode && e.response.statusCode === 403) {
return e.response.statusCode
} else {
throw this.wrapK8sClientError(e)
}
}
}
async replaceRoleFromFile(filePath: string, namespace = '') {
const yamlRole = this.safeLoadFromYamlFile(filePath) as V1Role
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
if (!yamlRole.metadata || !yamlRole.metadata.name) {
throw new Error(`Role read from ${filePath} must have name specified`)
}
try {
const res = await k8sRbacAuthApi.replaceNamespacedRole(yamlRole.metadata.name, namespace, yamlRole)
return res.response.statusCode
} catch (e) {
if (e.response && e.response.statusCode && e.response.statusCode === 403) {
return e.response.statusCode
} else {
throw this.wrapK8sClientError(e)
}
}
}
async createClusterRoleFromFile(filePath: string) {
const yamlRole = this.safeLoadFromYamlFile(filePath) as V1ClusterRole
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const res = await k8sRbacAuthApi.createClusterRole(yamlRole)
return res.response.statusCode
} catch (e) {
if (e.response && e.response.statusCode && e.response.statusCode === 403) {
return e.response.statusCode
} else {
throw this.wrapK8sClientError(e)
}
}
}
async replaceClusterRoleFromFile(filePath: string) {
const yamlRole = this.safeLoadFromYamlFile(filePath) as V1ClusterRole
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
if (!yamlRole.metadata || !yamlRole.metadata.name) {
throw new Error(`Cluster Role read from ${filePath} must have name specified`)
}
try {
const res = await k8sRbacAuthApi.replaceClusterRole(yamlRole.metadata.name, yamlRole)
return res.response.statusCode
} catch (e) {
if (e.response && e.response.statusCode && e.response.statusCode === 403) {
return e.response.statusCode
} else {
throw this.wrapK8sClientError(e)
}
}
}
async deleteRole(name = '', namespace = '') {
const k8sCoreApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const options = new V1DeleteOptions()
await k8sCoreApi.deleteNamespacedRole(name, namespace, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteClusterRole(name = '') {
const k8sCoreApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const options = new V1DeleteOptions()
await k8sCoreApi.deleteClusterRole(name, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async roleBindingExist(name = '', namespace = ''): Promise<boolean> {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const { body } = await k8sRbacAuthApi.readNamespacedRoleBinding(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async clusterRoleBindingExist(name = ''): Promise<boolean | ''> {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const { body } = await k8sRbacAuthApi.readClusterRoleBinding(name)
return this.compare(body, name)
} catch {
return false
}
}
async createAdminRoleBinding(name = '', serviceAccount = '', namespace = '') {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
let rb = new V1RoleBinding()
rb.metadata = new V1ObjectMeta()
rb.metadata.name = name
rb.metadata.namespace = namespace
rb.roleRef = new V1RoleRef()
rb.roleRef.kind = 'ClusterRole'
rb.roleRef.name = 'admin'
let subject = new V1Subject()
subject.kind = 'ServiceAccount'
subject.name = serviceAccount
subject.namespace = namespace
rb.subjects = [subject]
try {
return await k8sRbacAuthApi.createNamespacedRoleBinding(namespace, rb)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createRoleBindingFromFile(filePath: string, namespace = '') {
const yamlRoleBinding = this.safeLoadFromYamlFile(filePath) as V1RoleBinding
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
return await k8sRbacAuthApi.createNamespacedRoleBinding(namespace, yamlRoleBinding)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async replaceRoleBindingFromFile(filePath: string, namespace = '') {
const yamlRoleBinding = this.safeLoadFromYamlFile(filePath) as V1RoleBinding
if (!yamlRoleBinding.metadata || !yamlRoleBinding.metadata.name) {
throw new Error(`Role binding read from ${filePath} must have name specified`)
}
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
return await k8sRbacAuthApi.replaceNamespacedRoleBinding(yamlRoleBinding.metadata.name, namespace, yamlRoleBinding)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createClusterRoleBinding(name: string, saName: string, saNamespace = '', roleName = '') {
const clusterRoleBinding = {
apiVersion: 'rbac.authorization.k8s.io/v1',
metadata: {
name: `${name}`
},
subjects: [
{
kind: 'ServiceAccount',
name: `${saName}`,
namespace: `${saNamespace}`
}
],
roleRef: {
kind: 'ClusterRole',
name: `${roleName}`,
apiGroup: 'rbac.authorization.k8s.io'
}
} as V1ClusterRoleBinding
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
return await k8sRbacAuthApi.createClusterRoleBinding(clusterRoleBinding)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async replaceClusterRoleBinding(name: string, saName: string, saNamespace = '', roleName = '') {
const clusterRoleBinding = {
apiVersion: 'rbac.authorization.k8s.io/v1',
metadata: {
name: `${name}`
},
subjects: [
{
kind: 'ServiceAccount',
name: `${saName}`,
namespace: `${saNamespace}`
}
],
roleRef: {
kind: 'ClusterRole',
name: `${roleName}`,
apiGroup: 'rbac.authorization.k8s.io'
}
} as V1ClusterRoleBinding
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
return await k8sRbacAuthApi.replaceClusterRoleBinding(name, clusterRoleBinding)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteRoleBinding(name = '', namespace = '') {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const options = new V1DeleteOptions()
return await k8sRbacAuthApi.deleteNamespacedRoleBinding(name, namespace, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteClusterRoleBinding(name = '') {
const k8sRbacAuthApi = this.kc.makeApiClient(RbacAuthorizationV1Api)
try {
const options = new V1DeleteOptions()
return await k8sRbacAuthApi.deleteClusterRoleBinding(name, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async configMapExist(name = '', namespace = ''): Promise<boolean> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
const { body } = await k8sCoreApi.readNamespacedConfigMap(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async createConfigMapFromFile(filePath: string, namespace = '') {
const yamlConfigMap = this.safeLoadFromYamlFile(filePath) as V1ConfigMap
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
return await k8sCoreApi.createNamespacedConfigMap(namespace, yamlConfigMap)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async patchConfigMap(name: string, patch: any, namespace = '') {
const k8sCoreApi = this.kc.makeApiClient(PatchedK8sApi)
try {
return await k8sCoreApi.patchNamespacedConfigMap(name, namespace, patch)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteConfigMap(name: string, namespace = '') {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
const options = new V1DeleteOptions()
await k8sCoreApi.deleteNamespacedConfigMap(name, namespace, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async podExist(name = '', namespace = ''): Promise<boolean> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
try {
const { body } = await k8sCoreApi.readNamespacedPod(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async podsExistBySelector(selector: string, namespace = ''): Promise<boolean> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
let res
try {
res = await k8sCoreApi.listNamespacedPod(namespace, true, undefined, undefined, undefined, selector)
} catch (e) {
throw this.wrapK8sClientError(e)
}
if (!res || !res.body || !res.body.items) {
throw new Error(`Get pods by selector "${selector}" returned an invalid response`)
}
return (res.body.items.length > 0)
}
async getPodPhase(selector: string, namespace = ''): Promise<string> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
let res
try {
res = await k8sCoreApi.listNamespacedPod(namespace, true, undefined, undefined, undefined, selector)
} catch (e) {
throw this.wrapK8sClientError(e)
}
if (!res || !res.body || !res.body.items) {
throw new Error(`Get pods by selector "${selector}" returned an invalid response`)
}
if (res.body.items.length !== 1) {
throw new Error(`Get pods by selector "${selector}" returned ${res.body.items.length} pods (1 was expected)`)
}
if (!res.body.items[0].status || !res.body.items[0].status.phase) {
throw new Error(`Get pods by selector "${selector}" returned a pod with an invalid state`)
}
return res.body.items[0].status.phase
}
async getPodReadyConditionStatus(selector: string, namespace = ''): Promise<string> {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
let res
try {
res = await k8sCoreApi.listNamespacedPod(namespace, true, undefined, undefined, undefined, selector)
} catch (e) {
throw this.wrapK8sClientError(e)
}
if (!res || !res.body || !res.body.items) {
throw new Error(`Get pods by selector "${selector}" returned an invalid response`)
}
if (res.body.items.length < 1) {
// No pods found by the specified selector. So, it's not ready.
return 'False'
}
if (res.body.items.length > 1) {
throw new Error(`Get pods by selector "${selector}" returned ${res.body.items.length} pods (1 was expected)`)
}
if (!res.body.items[0].status) {
throw new Error(`Get pods by selector "${selector}" returned a pod with an invalid state`)
}
if (!res.body.items[0].status.conditions || !(res.body.items[0].status.conditions.length > 0)) {
throw new Error(`Get pods by selector "${selector}" returned a pod with an invalid status.conditions`)
}
const conditions = res.body.items[0].status.conditions
for (let condition of conditions) {
if (condition.type === 'Ready') {
return condition.status
}
}
throw new Error(`Get pods by selector "${selector}" returned a pod without a status.condition of type "Ready"`)
}
async waitForPodPhase(selector: string, targetPhase: string, namespace = '', intervalMs = 500, timeoutMs = this.podWaitTimeout) {
const iterations = timeoutMs / intervalMs
for (let index = 0; index < iterations; index++) {
let currentPhase = await this.getPodPhase(selector, namespace)
if (targetPhase === currentPhase) {
return
}
await cli.wait(intervalMs)
}
throw new Error(`ERR_TIMEOUT: Timeout set to pod wait timeout ${this.podWaitTimeout}`)
}
async waitForPodPending(selector: string, namespace = '', intervalMs = 500, timeoutMs = this.podWaitTimeout) {
const iterations = timeoutMs / intervalMs
let podExist
let currentPhase
for (let index = 0; index < iterations; index++) {
podExist = await this.podsExistBySelector(selector, namespace)
if (podExist) {
currentPhase = await this.getPodPhase(selector, namespace)
if (currentPhase === 'Pending' || currentPhase === 'Running') {
return
} else {
throw new Error(`ERR_UNEXPECTED_PHASE: ${currentPhase} (Pending expected) `)
}
}
await cli.wait(intervalMs)
}
throw new Error(`ERR_TIMEOUT: Timeout set to pod wait timeout ${this.podWaitTimeout}. podExist: ${podExist}, currentPhase: ${currentPhase}`)
}
async waitForPodReady(selector: string, namespace = '', intervalMs = 500, timeoutMs = this.podReadyTimeout) {
const iterations = timeoutMs / intervalMs
for (let index = 0; index < iterations; index++) {
let readyStatus = await this.getPodReadyConditionStatus(selector, namespace)
if (readyStatus === 'True') {
return
}
if (readyStatus !== 'False') {
throw new Error(`ERR_BAD_READY_STATUS: ${readyStatus} (True or False expected) `)
}
await cli.wait(intervalMs)
}
throw new Error(`ERR_TIMEOUT: Timeout set to pod ready timeout ${this.podReadyTimeout}`)
}
async waitUntilPodIsDeleted(selector: string, namespace = '', intervalMs = 500, timeoutMs = this.podReadyTimeout) {
const iterations = timeoutMs / intervalMs
for (let index = 0; index < iterations; index++) {
let readyStatus = await this.getPodReadyConditionStatus(selector, namespace)
if (readyStatus === 'False') {
return
}
if (readyStatus !== 'True') {
throw new Error(`ERR_BAD_READY_STATUS: ${readyStatus} (True or False expected) `)
}
await cli.wait(intervalMs)
}
throw new Error(`ERR_TIMEOUT: Timeout set to pod ready timeout ${this.podReadyTimeout}`)
}
async deletePod(name: string, namespace = '') {
this.kc.loadFromDefault()
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
const options = new V1DeleteOptions()
try {
return await k8sCoreApi.deleteNamespacedPod(name, namespace, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
// make sure that flag is specified for command that it's invoked
async waitLatestReplica(deploymentName: string, namespace = '', intervalMs = 500, timeoutMs = this.podWaitTimeout) {
const iterations = timeoutMs / intervalMs
for (let index = 0; index < iterations; index++) {
const deployment = await this.getDeployment(deploymentName, namespace)
if (!deployment) {
throw new Error(`Deployment ${namespace}/${deploymentName} is not found.`)
}
const deploymentStatus = deployment.status
if (!deploymentStatus) {
throw new Error(`Deployment ${namespace}/${deploymentName} does not have any status`)
}
if (deploymentStatus.unavailableReplicas && deploymentStatus.unavailableReplicas > 0) {
await cli.wait(intervalMs)
} else {
return
}
}
throw new Error(`ERR_TIMEOUT: Timeout set to pod wait timeout ${this.podWaitTimeout}`)
}
async deploymentExist(name = '', namespace = ''): Promise<boolean> {
const k8sApi = this.kc.makeApiClient(AppsV1Api)
try {
const { body } = await k8sApi.readNamespacedDeployment(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async deploymentReady(name = '', namespace = ''): Promise<boolean> {
const k8sApi = this.kc.makeApiClient(AppsV1Api)
try {
const res = await k8sApi.readNamespacedDeployment(name, namespace)
return ((res && res.body &&
res.body.status && res.body.status.readyReplicas
&& res.body.status.readyReplicas > 0) as boolean)
} catch {
return false
}
}
async deploymentStopped(name = '', namespace = ''): Promise<boolean> {
const k8sApi = this.kc.makeApiClient(AppsV1Api)
try {
const res = await k8sApi.readNamespacedDeployment(name, namespace)
if (res && res.body && res.body.spec && res.body.spec.replicas) {
throw new Error(`Deployment '${name}' without replicas in spec is fetched`)
}
return res.body!.spec!.replicas === 0
} catch {
return false
}
}
async isDeploymentPaused(name = '', namespace = ''): Promise<boolean> {
const k8sApi = this.kc.makeApiClient(AppsV1Api)
try {
const res = await k8sApi.readNamespacedDeployment(name, namespace)
if (!res || !res.body || !res.body.spec) {
throw new Error('E_BAD_DEPLOY_RESPONSE')
}
return res.body.spec.paused || false
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async pauseDeployment(name = '', namespace = '') {
const k8sApi = this.kc.makeApiClient(PatchedK8sAppsApi)
try {
const patch = {
spec: {
paused: true
}
}
await k8sApi.patchNamespacedDeployment(name, namespace, patch)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async resumeDeployment(name = '', namespace = '') {
const k8sApi = this.kc.makeApiClient(PatchedK8sAppsApi)
try {
const patch = {
spec: {
paused: false
}
}
await k8sApi.patchNamespacedDeployment(name, namespace, patch)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async scaleDeployment(name = '', namespace = '', replicas: number) {
const k8sAppsApi = this.kc.makeApiClient(PatchedK8sAppsApi)
const patch = {
spec: {
replicas
}
}
let res
try {
res = await k8sAppsApi.patchNamespacedDeploymentScale(name, namespace, patch)
} catch (e) {
throw this.wrapK8sClientError(e)
}
if (!res || !res.body) {
throw new Error('Patch deployment scale returned an invalid response')
}
}
async createDeployment(name: string,
image: string,
serviceAccount: string,
pullPolicy: string,
configMapEnvSource: string,
namespace: string) {
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
let deployment = new V1Deployment()
deployment.metadata = new V1ObjectMeta()
deployment.metadata.name = name
deployment.metadata.namespace = namespace
deployment.spec = new V1DeploymentSpec()
deployment.spec.selector = new V1LabelSelector()
deployment.spec.selector.matchLabels = { app: name }
deployment.spec.template = new V1PodTemplateSpec()
deployment.spec.template.metadata = new V1ObjectMeta()
deployment.spec.template.metadata.name = name
deployment.spec.template.metadata.labels = { app: name }
deployment.spec.template.spec = new V1PodSpec()
deployment.spec.template.spec.serviceAccountName = serviceAccount
let opContainer = new V1Container()
opContainer.name = name
opContainer.image = image
opContainer.imagePullPolicy = pullPolicy
let envFromSource = new V1EnvFromSource()
envFromSource.configMapRef = new V1ConfigMapEnvSource()
envFromSource.configMapRef.name = configMapEnvSource
opContainer.envFrom = [envFromSource]
deployment.spec.template.spec.containers = [opContainer]
try {
return await k8sAppsApi.createNamespacedDeployment(namespace, deployment)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createDeploymentFromFile(filePath: string, namespace = '', containerImage = '', containerIndex = 0) {
const yamlDeployment = this.safeLoadFromYamlFile(filePath) as V1Deployment
if (containerImage) {
yamlDeployment.spec!.template.spec!.containers[containerIndex].image = containerImage
}
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
try {
return await k8sAppsApi.createNamespacedDeployment(namespace, yamlDeployment)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async replaceDeploymentFromFile(filePath: string, namespace = '', containerImage = '', containerIndex = 0) {
const yamlDeployment = this.safeLoadFromYamlFile(filePath) as V1Deployment
if (containerImage) {
yamlDeployment.spec!.template.spec!.containers[containerIndex].image = containerImage
}
if (!yamlDeployment.metadata || !yamlDeployment.metadata.name) {
throw new Error(`Deployment read from ${filePath} must have name specified`)
}
// updating restartedAt to make sure that rollout will be restarted
let annotations = yamlDeployment.spec!.template!.metadata!.annotations
if (!annotations) {
annotations = {}
yamlDeployment.spec!.template!.metadata!.annotations = annotations
}
annotations['kubectl.kubernetes.io/restartedAt'] = new Date().toISOString()
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
try {
return await k8sAppsApi.replaceNamespacedDeployment(yamlDeployment.metadata.name, namespace, yamlDeployment)
} catch (e) {
if (e.response && e.response.body && e.response.body.message && e.response.body.message.toString().endsWith('field is immutable')) {
try {
await k8sAppsApi.deleteNamespacedDeployment(yamlDeployment.metadata.name, namespace)
return await k8sAppsApi.createNamespacedDeployment(namespace, yamlDeployment)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
throw this.wrapK8sClientError(e)
}
}
async deleteAllDeployments(namespace = '') {
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
try {
await k8sAppsApi.deleteCollectionNamespacedDeployment(namespace)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async getDeploymentsBySelector(labelSelector = '', namespace = ''): Promise<V1DeploymentList> {
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
try {
const res = await k8sAppsApi.listNamespacedDeployment(namespace, true, 'true', undefined, undefined, labelSelector)
if (res && res.body) {
return res.body
}
} catch (e) {
throw this.wrapK8sClientError(e)
}
throw new Error('ERR_LIST_NAMESPACES')
}
async getDeployment(name: string, namespace: string): Promise<V1Deployment | undefined> {
const k8sAppsApi = this.kc.makeApiClient(AppsV1Api)
try {
const res = await k8sAppsApi.readNamespacedDeployment(name, namespace)
if (res && res.body) {
return res.body!
}
} catch (error) {
if (error.response && error.response.statusCode === 404) {
return
}
throw this.wrapK8sClientError(error)
}
throw new Error('ERR_GET_DEPLOYMENT')
}
async createPod(name: string,
image: string,
serviceAccount: string,
restartPolicy: string,
pullPolicy: string,
configMapEnvSource: string,
namespace: string) {
const k8sCoreApi = this.kc.makeApiClient(CoreV1Api)
let pod = new V1Pod()
pod.metadata = new V1ObjectMeta()
pod.metadata.name = name
pod.metadata.labels = { app: name }
pod.metadata.namespace = namespace
pod.spec = new V1PodSpec()
pod.spec.containers
pod.spec.restartPolicy = restartPolicy
pod.spec.serviceAccountName = serviceAccount
let opContainer = new V1Container()
opContainer.name = name
opContainer.image = image
opContainer.imagePullPolicy = pullPolicy
let envFromSource = new V1EnvFromSource()
envFromSource.configMapRef = new V1ConfigMapEnvSource()
envFromSource.configMapRef.name = configMapEnvSource
opContainer.envFrom = [envFromSource]
pod.spec.containers = [opContainer]
try {
return await k8sCoreApi.createNamespacedPod(namespace, pod)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async compare(body: any, name: string): Promise<boolean> {
if (body && body.metadata && body.metadata.name && body.metadata.name === name) {
return true
} else {
return false
}
}
async ingressExist(name = '', namespace = ''): Promise<boolean> {
const k8sExtensionsApi = this.kc.makeApiClient(ExtensionsV1beta1Api)
try {
const { body } = await k8sExtensionsApi.readNamespacedIngress(name, namespace)
return this.compare(body, name)
} catch {
return false
}
}
async deleteAllIngresses(namespace = '') {
const k8sExtensionsApi = this.kc.makeApiClient(ExtensionsV1beta1Api)
try {
await k8sExtensionsApi.deleteCollectionNamespacedIngress(namespace)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createCrdFromFile(filePath: string) {
const yamlCrd = this.safeLoadFromYamlFile(filePath) as V1beta1CustomResourceDefinition
const k8sApiextensionsApi = this.kc.makeApiClient(ApiextensionsV1beta1Api)
try {
return await k8sApiextensionsApi.createCustomResourceDefinition(yamlCrd)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async replaceCrdFromFile(filePath: string, resourceVersion: string) {
const yamlCrd = this.safeLoadFromYamlFile(filePath) as V1beta1CustomResourceDefinition
if (!yamlCrd.metadata || !yamlCrd.metadata.name) {
throw new Error(`CRD read from ${filePath} must have name specified`)
}
yamlCrd.metadata.resourceVersion = resourceVersion
const k8sApiextensionsApi = this.kc.makeApiClient(ApiextensionsV1beta1Api)
try {
return await k8sApiextensionsApi.replaceCustomResourceDefinition(yamlCrd.metadata.name, yamlCrd)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async crdExist(name = ''): Promise<boolean | ''> {
const k8sApiextensionsApi = this.kc.makeApiClient(ApiextensionsV1beta1Api)
try {
const { body } = await k8sApiextensionsApi.readCustomResourceDefinition(name)
return this.compare(body, name)
} catch {
return false
}
}
async getCrd(name = ''): Promise<V1beta1CustomResourceDefinition> {
const k8sApiextensionsApi = this.kc.makeApiClient(ApiextensionsV1beta1Api)
try {
const { body } = await k8sApiextensionsApi.readCustomResourceDefinition(name)
return body
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async deleteCrd(name = '') {
const k8sApiextensionsApi = this.kc.makeApiClient(ApiextensionsV1beta1Api)
try {
const options = new V1DeleteOptions()
await k8sApiextensionsApi.deleteCustomResourceDefinition(name, undefined, options)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}
async createCheClusterFromFile(filePath: string, flags: any, useDefaultCR: boolean) {
let yamlCr = this.safeLoadFromYamlFile(filePath)
const cheNamespace = flags.chenamespace
if (useDefaultCR) {
// If we don't use an explicitely provided CheCluster CR,
// then let's modify the default example CR with values
// derived from the other parameters
const cheImage = flags.cheimage
const imageAndTag = cheImage.split(':', 2)
yamlCr.spec.server.cheImage = imageAndTag[0]
yamlCr.spec.server.cheImageTag = imageAndTag.length === 2 ? imageAndTag[1] : 'latest'
yamlCr.spec.auth.openShiftoAuth = flags['os-oauth']
yamlCr.spec.server.tlsSupport = flags.tls
if (flags.tls) {
yamlCr.spec.k8s.tlsSecretName = 'che-tls'
}
yamlCr.spec.server.selfSignedCert = flags['self-signed-cert']
yamlCr.spec.k8s.ingressDomain = flags.domain
let pluginRegistryUrl = flags['plugin-registry-url']
if (pluginRegistryUrl) {
yamlCr.spec.server.pluginRegistryUrl = pluginRegistryUrl
yamlCr.spec.server.externalPluginRegistry = true
}
let devfileRegistryUrl = flags['devfile-registry-url']
if (devfileRegistryUrl) {
yamlCr.spec.server.devfileRegistryUrl = devfileRegistryUrl
yamlCr.spec.server.externalDevfileRegistry = true
}
if (flags.cheimage === DEFAULT_CHE_IMAGE &&
yamlCr.spec.server.cheImageTag !== 'nightly' &&
yamlCr.spec.server.cheImageTag !== 'latest') {
// We obviously are using a release version of chectl with the default `cheimage`
// => We should use the operator defaults for docker images
yamlCr.spec.server.cheImage = ''
yamlCr.spec.server.cheImageTag = ''
yamlCr.spec.server.pluginRegistryImage = ''
yamlCr.spec.server.devfileRegistryImage = ''
yamlCr.spec.auth.identityProviderImage = ''
} else {
// We obviously are using a non-released version of chectl
// or are providing a non-default `cheimage`, with a specific tag, to run with
// => We should override the image tags for all the associated docker images
const tagExp = /:[^:]*$/
const newTag = `:${yamlCr.spec.server.cheImageTag}`
yamlCr.spec.auth.identityProviderImage = yamlCr.spec.auth.identityProviderImage.replace(tagExp, newTag)
yamlCr.spec.server.pluginRegistryImage = yamlCr.spec.server.pluginRegistryImage.replace(tagExp, newTag)
yamlCr.spec.server.devfileRegistryImage = yamlCr.spec.server.devfileRegistryImage.replace(tagExp, newTag)
}
}
const customObjectsApi = this.kc.makeApiClient(CustomObjectsApi)
try {
return await customObjectsApi.createNamespacedCustomObject('org.eclipse.che', 'v1', cheNamespace, 'checlusters', yamlCr)
} catch (e) {
throw this.wrapK8sClientError(e)
}
}