-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1285 lines (1161 loc) · 56 KB
/
index.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 util = require('node:util');
const fs = require('fs');
const exec = util.promisify(require('node:child_process').exec);
const accountStore = require('./accounts.json');
const clustersPerAccount = 90;
const clusterPrefix = "argotesting";
const re = new RegExp("^"+clusterPrefix+"([0-9]{1,4})$");
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function setContext(contextArr, vClusterContext) {
if(vClusterContext) {
await runCommand('kubectl config use-context '+vClusterContext);
//await runCommand('kubie ctx '+vClusterContext);
} else {
await runCommand('kubectl config use-context '+contextArr[0]);
//await runCommand('kubie ctx '+vClusterContext);
}
}
function getParameters(paramName) {
const index = process.argv.indexOf("--"+paramName);
let value;
if(index > -1) {
value = process.argv[index+1];
return value;
} else {
return false;
}
}
function getAcctFromClusterNum(clusterNum) {
let acctNum = Math.ceil(clusterNum / clustersPerAccount) - 1;
if(acctNum < 0) {
acctNum = 0;
}
return accountStore[acctNum];
}
async function getKubeContexts() {
let returnArr = [];
let contextOutput = await runCommand('kubectl config get-contexts --output=name',"","",true);
let contextArr = contextOutput.stdout.split("\n").filter((obj)=>obj.match(re));
for(let i in contextArr) {
let regmatch = contextArr[i].match(re);
returnArr[regmatch[1]] = contextArr[i];
}
return returnArr;
}
async function loginArgoCD() {
let getURL = JSON.parse((await runCommand('kubectl -n argocd get svc argocd-server -o json','"loadBalancer": {}',"",true)).stdout);
let argoHostname = getURL.status.loadBalancer.ingress[0].hostname;
if(!argoHostname) {
argoHostname = getURL.status.loadBalancer.ingress[0].ip;
}
let getSecret = JSON.parse((await runCommand('kubectl get secrets -n argocd argocd-initial-admin-secret -o json', "NotFound", "", true)).stdout);
let secretBuf = Buffer.from(getSecret.data["password"], 'base64');
await runCommand('argocd login '+argoHostname+' --insecure --config ~/argoconfigs/'+argoHostname+' --username admin --password '+secretBuf.toString("ascii"),"", "", false);
return argoHostname;
}
async function getDashboards() {
try {
let getSecret = JSON.parse((await runCommand('kubectl get secrets -n argocd argocd-initial-admin-secret -o json', "", "NotFound", true)).stdout);
let secretBuf = Buffer.from(getSecret.data["password"], 'base64');
let getURL = JSON.parse((await runCommand('kubectl -n argocd get svc argocd-server -o json',"", "",true)).stdout);
let argoHostname = getURL.status.loadBalancer.ingress[0].hostname;
if(!argoHostname) {
argoHostname = getURL.status.loadBalancer.ingress[0].ip;
}
console.log("ArgoCD URL: https://" + argoHostname);
console.log("Username: admin");
console.log("Password: "+secretBuf.toString("ascii"));
} catch (e) {}
let getGrafanaURL = JSON.parse((await runCommand('kubectl get svc prometheus-operator-grafana -n prometheus -o json',"", "",true)).stdout);
let grafanaHostname = getGrafanaURL.status.loadBalancer.ingress[0].hostname;
if(!grafanaHostname) {
grafanaHostname = getGrafanaURL.status.loadBalancer.ingress[0].ip;
}
console.log("Grafana URL: http://"+ grafanaHostname);
console.log("Username: admin");
let grafanaAdminPassword = JSON.parse((await runCommand('kubectl get secret prometheus-operator-grafana -n prometheus -o json',"", "",true)).stdout);
let grafanaSecretBuf = Buffer.from(grafanaAdminPassword.data["admin-password"], 'base64');
console.log("Password: "+grafanaSecretBuf.toString("ascii"));
try {
let getArgoWorkflowURL = JSON.parse((await runCommand('kubectl get svc argoworkflows-argo-workflows-server -n argocd -o json',"", "NotFound",true)).stdout);
console.log("ArgoWorkflows URL: http://" + getArgoWorkflowURL.status.loadBalancer.ingress[0].hostname+":2746");
let argoWorkflowSecret = JSON.parse((await runCommand('kubectl get secret argo-workflow.service-account-token -n argocd -o json',"","",true)).stdout);
let argoWorkflowSecretBuf = Buffer.from(argoWorkflowSecret.data.token, 'base64');
console.log("Bearer Token: Bearer "+argoWorkflowSecretBuf.toString("ascii"));
} catch(e) {}
try {
let getGiteaURL = JSON.parse((await runCommand('kubectl get svc gitea-http -n gitea -o json',"", "NotFound",true)).stdout);
console.log("Gitea URL: http://" + getGiteaURL.status.loadBalancer.ingress[0].hostname+":3000");
} catch(e) {
}
}
async function getClusterURLs() {
let getClusterURL = (JSON.parse((await runCommand('kubectl get secret -n argocd -o json',"", "",true)).stdout)).items;
let clusterArr = ["https://kubernetes.default.svc"];
for(let i in getClusterURL) {
if(getClusterURL[i].metadata.labels?.["argocd.argoproj.io/secret-type"] === "cluster") {
let bufServer = Buffer.from(getClusterURL[i].data.server, 'base64');
let bufName = Buffer.from(getClusterURL[i].data.name, 'base64');
let regmatch = bufName.toString("ascii").match(re);
clusterArr[regmatch[1]] = bufServer.toString("ascii");
}
}
return clusterArr;
}
async function getArgoApps(appName, argoHostname) {
let returnArr = [];
let argoApps = (JSON.parse((await runCommand('argocd app list --config ~/argoconfigs/'+argoHostname+' -o json',"", "",true)).stdout));
for(let i in argoApps) {
let regex = new RegExp('cluster-([0-9]{1,4})-'+appName+'-([0-9]{1,4})');
let regmatch = argoApps[i].metadata.name.match(regex);
if(regmatch) {
if(!returnArr[regmatch[1]]) {
returnArr[regmatch[1]] = [];
}
returnArr[regmatch[1]][regmatch[2]] = argoApps[i].metadata.name;
}
}
return returnArr;
}
async function scaleNodes(numReplicas,cluster,account) {
let nodeGroup = JSON.parse((await runCommand('eksctl get nodegroup --cluster '+cluster+' -o json',"","",true,account)).stdout)[0].Name;
await runCommand('aws eks update-nodegroup-config --cluster-name '+cluster+' --scaling-config minSize='+numReplicas+',maxSize='+numReplicas+',desiredSize='+numReplicas+' --nodegroup-name '+nodeGroup,"ExpiredTokenException","",false,account);
}
async function scaleArgoController(numReplicas) {
await runCommand('kubectl patch statefulset argocd-application-controller -n argocd -p "{\\"spec\\":{\\"template\\":{\\"spec\\":{\\"containers\\":[{\\"name\\": \\"application-controller\\", \\"env\\":[{\\"name\\":\\"ARGOCD_CONTROLLER_REPLICAS\\",\\"value\\":\\"'+numReplicas+'\\"}]}]}}}}"');
let appServerStatefulSet = (JSON.parse((await runCommand('kubectl get statefulset -n argocd -l app.kubernetes.io/name=argocd-application-controller -o json',"","",true)).stdout)).items;
if(appServerStatefulSet[0]) {
if(appServerStatefulSet[0].spec.replicas !== parseInt(numReplicas)) {
await runCommand('kubectl scale statefulsets '+appServerStatefulSet[0].spec.serviceName+' --replicas='+numReplicas+' -n argocd');
}
} else {
console.log("No stateful set for argocd application set found.")
process.exit(1);
}
}
async function setArgoControllerShardAlgorithm(shardAlgorithm) {
//await runCommand('kubectl patch statefulset argocd-application-controller -n argocd -p "{\\"spec\\":{\\"template\\":{\\"spec\\":{\\"containers\\":[{\\"name\\": \\"application-controller\\", \\"env\\":[{\\"name\\":\\"ARGOCD_CONTROLLER_SHARDING_ALGORITHM\\",\\"value\\":\\"'+shardAlgorithm+'\\"}]}]}}}}"');
//await runCommand('kubectl rollout restart statefulset argocd-application-controller -n argocd');
await runCommand('kubectl get configmap argocd-cmd-params-cm -n argocd -o json > argocd-cmd-params-cm.json',"","",true);
let file = fs.readFileSync("argocd-cmd-params-cm.json");
let json = JSON.parse(file.toString());
try {
if(json.data['controller.sharding.algorithm'] != shardAlgorithm) {
console.log("Setting controller.sharding.algorithm to "+shardAlgorithm);
json.data['controller.sharding.algorithm'] = shardAlgorithm.toString();
}
} catch(e){
console.log(e);
process.exit(1);
}
fs.writeFileSync("argocd-cmd-params-cm.json",JSON.stringify(json));
await runCommand('kubectl apply -f argocd-cmd-params-cm.json -n argocd',"","",false);
await runCommand('kubectl rollout restart statefulset argocd-application-controller -n argocd');
}
async function scaleArgoRepoServer(numReplicas) {
let repoServerDeployment = (JSON.parse((await runCommand('kubectl get deployments -n argocd argocd-repo-server -o json',"","",true)).stdout));
if(repoServerDeployment) {
if(repoServerDeployment.spec.replicas !== parseInt(numReplicas)) {
await runCommand('kubectl scale deployment argocd-repo-server --replicas='+numReplicas+' -n argocd');
}
} else {
console.log("No deployment for argocd repo deployment found.")
process.exit(1);
}
}
async function scaleArgoApiServer(numReplicas) {
let apiServerDeployment = (JSON.parse((await runCommand('kubectl get deployments -n argocd argocd-server -o json',"","",true)).stdout));
if(apiServerDeployment) {
if(apiServerDeployment.spec.replicas !== parseInt(numReplicas)) {
await runCommand('kubectl scale deployment argocd-server --replicas='+numReplicas+' -n argocd');
}
} else {
console.log("No deployment for argocd deployment found.")
process.exit(1);
}
}
async function runCommand(command,failString,successString,quiet,account) {
if(!quiet) {
console.log("Running command: "+ command);
}
let retry = 0;
let output = {};
let success = false;
if(!account) {
account = accountStore[0];
}
let execOptions = {
maxBuffer: 1024 * 1024 * 1024,
env: {
...process.env,
'AWS_ACCESS_KEY_ID': account['credentials']['accessKeyId'],
'AWS_SECRET_ACCESS_KEY': account['credentials']['secretAccessKey'],
'AWS_DEFAULT_REGION': account['region']
}
};
while(retry<6) {
try {
output = await exec(command,execOptions);
if(!failString) {
retry = 6;
success = true;
} else if(output.stdout.includes(failString)) {
retry++;
await sleep(retry*10000);
} else {
retry = 6;
success = true;
}
} catch(e) {
if(!quiet) {
console.log(e);
}
if(successString) {
if(e.stderr.includes(successString)) {
retry = 6;
success = true;
output = e;
}
}
if(e.stderr.includes("Unauthorized")) {
console.log("Unauthorized.");
process.exit(1);
}
if(!success) {
retry++;
await sleep(retry*10000);
}
}
}
if(output.stdout && !quiet) {
console.log(output.stdout);
}
if(output.stderr && !quiet) {
console.log(output.stderr);
}
return output;
}
async function main() {
let action = getParameters("action");
let numClusters = parseInt(getParameters("numClusters"));
let numApps = parseInt(getParameters("numApps"));
let numWorkflows = parseInt(getParameters("numWorkflows"));
let numAppsPerCluster = parseInt(getParameters("numAppsPerCluster"));
let numNodes = parseInt(getParameters("numNodes"));
let numReplicas = parseInt(getParameters("numReplicas"));
let clusterStart = parseInt(getParameters("clusterStart"));
let appName = getParameters("appName");
let appRepo = getParameters("appRepo");
let opProc = getParameters("opProc");
let statProc = getParameters("statProc");
let recTimeout = getParameters("recTimeout");
let instanceType = getParameters("instanceType");
let burstQPS = getParameters("burstQPS");
let QPS = getParameters("QPS");
let logLevel = getParameters("logLevel");
let manifestUrl = getParameters("manifestUrl");
let roleArn = getParameters("roleArn");
let shardAlgorithm = getParameters("shardAlgorithm");
let numWorkers = getParameters("numWorkers");
let targetCluster = getParameters("targetCluster");
let vClusterContext = getParameters("vClusterContext");
let ackService = getParameters("ackService");
let giteaToken = getParameters("giteaToken");
let appPrefix = getParameters("appPrefix");
if(!instanceType) {
instanceType = "m5.large";
}
if(!action) {
console.log("Missing required parameter.");
process.exit(1);
}
if(action.match(/^(create|delete|createPostSteps|createNodeGroups|createClusters|deleteClusters|fixKubeContexts|deleteKubeContexts)$/)) {
if(!numClusters) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
let currentNumClusters = contextArr.length;
if(clusterStart || clusterStart === 0) {
currentNumClusters = clusterStart;
}
if(action.match(/^(delete|deleteClusters|deleteKubeContexts|fixKubeContexts)$/)) {
currentNumClusters = 0;
} else {
if(currentNumClusters > numClusters) {
console.log("numClusters must be greater than current number of clusters with create action.");
process.exit(1);
}
}
console.time();
let promiseArr = [];
let errorFound = "";
for(let i = currentNumClusters;i<numClusters;i++) {
let account = getAcctFromClusterNum(i);
let execOptions = {
env: {
...process.env,
'AWS_ACCESS_KEY_ID': account['credentials']['accessKeyId'],
'AWS_SECRET_ACCESS_KEY': account['credentials']['secretAccessKey'],
'AWS_DEFAULT_REGION': account['region']
}
}
if(action.match(/^(create|createClusters)$/)) {
let checkCluster = await runCommand('aws cloudformation describe-stacks --stack-name eksctl-'+clusterPrefix+''+i+'-cluster',"","ValidationError",true,getAcctFromClusterNum(i));
let stackError = false;
if(checkCluster.stdout) {
if((JSON.parse(checkCluster.stdout)).Stacks[0].StackStatus !== "CREATE_COMPLETE") {
console.log("Cluster "+clusterPrefix+""+i+" is not healthy. Deleting the stack.");
stackError = true;
await runCommand('aws cloudformation delete-stack --stack-name eksctl-'+clusterPrefix+''+i+'-cluster',"","",true,getAcctFromClusterNum(i));
let stackDeleted = false;
while(!stackDeleted) {
let checkStackDeleted = await runCommand('aws cloudformation describe-stacks --stack-name eksctl-'+clusterPrefix+''+i+'-cluster',"","ValidationError",true,getAcctFromClusterNum(i));
if(checkStackDeleted.stderr.match(/ValidationError/)) {
stackDeleted = true;
}
await sleep(5000);
}
}
}
if(checkCluster.stderr.match(/ValidationError/) || stackError) {
console.log('Creating cluster '+clusterPrefix+''+i);
let promise = exec('eksctl create cluster --name '+clusterPrefix+''+i+' --region '+account['region']+' --version 1.27 --vpc-private-subnets '+account['subnets'].join(',')+' --without-nodegroup',execOptions).catch((error)=> {
console.log(clusterPrefix+""+i+":"+error);
errorFound = "create";
});
promiseArr.push(promise);
if(promiseArr.length > 50) {
await Promise.all(promiseArr);
promiseArr = [];
}
}
} else if(action.match(/^(delete|deleteClusters)$/)) {
console.log('Deleting cluster '+clusterPrefix+''+i);
let promise = exec('eksctl delete --region='+account['region']+' cluster --name '+clusterPrefix+''+i,execOptions).catch((error)=> {
console.log(clusterPrefix+""+i+":"+error);
errorFound = "delete";
});
promiseArr.push(promise);
if(promiseArr.length > 50) {
await Promise.all(promiseArr);
promiseArr = [];
}
}
}
await Promise.all(promiseArr);
console.timeEnd();
if(errorFound) {
if(errorFound === "create") {
console.log("Errors found on creation. Try running the command again with the following parameters: --action create --numClusters "+numClusters+" --clusterStart "+currentNumClusters);
} else if(errorFound === "delete") {
console.log("Errors found on deletion. Try running the command again.");
}
process.exit(1);
}
if(action.match(/^(create|fixKubeContexts|delete|deleteClusters|deleteKubeContexts)$/)) {
let contextArr = await getKubeContexts();
let account = getAcctFromClusterNum(0);
for(let i=currentNumClusters;i<numClusters;i++) {
if(contextArr[i]) {
console.log(i);
await runCommand('kubectl config delete-context '+contextArr[i]);
}
if(action.match(/^(create|fixKubeContexts)$/)) {
await runCommand('aws eks update-kubeconfig --region="'+account['region']+'" --name="'+clusterPrefix+''+i+'" --alias="'+clusterPrefix+''+i+'"',"","",false,getAcctFromClusterNum(i));
}
}
}
console.time();
promiseArr = [];
contextArr = await getKubeContexts();
for(let i = currentNumClusters;i<numClusters;i++) {
let account = getAcctFromClusterNum(i);
let execOptions = {
env: {
...process.env,
'AWS_ACCESS_KEY_ID': account['credentials']['accessKeyId'],
'AWS_SECRET_ACCESS_KEY': account['credentials']['secretAccessKey'],
'AWS_DEFAULT_REGION': account['region']
}
}
if(action.match(/^(create|createNodeGroups)$/)) {
await runCommand('kubectl config use-context '+contextArr[i],"","",false,getAcctFromClusterNum(i));
await runCommand('kubectl set env daemonset aws-node -n kube-system ENABLE_PREFIX_DELEGATION=true',"","",false,getAcctFromClusterNum(i));
await runCommand('kubectl set env ds aws-node -n kube-system WARM_PREFIX_TARGET=1',"","",false,getAcctFromClusterNum(i));
console.log('Creating nodegroups for '+clusterPrefix+''+i);
if(!numNodes) {
numNodes = 1;
}
if(i !== 0) {
instanceType = "m5.large";
} else {
instanceType = "m5.4xlarge"
}
let promise = exec('eksctl create nodegroup --cluster '+clusterPrefix+''+i+' --name node-group-'+instanceType.replaceAll(".","")+' --node-type '+instanceType+' --node-ami-family AmazonLinux2 --nodes '+numNodes+' --subnet-ids '+account['subnets'].join(',')+' --node-private-networking --max-pods-per-node 110', execOptions).catch((error)=> {
console.log(clusterPrefix+''+i+":"+error);
});
promiseArr.push(promise);
}
}
await Promise.all(promiseArr);
console.timeEnd();
if(action.match(/^(create|createPostSteps)$/)) {
if(currentNumClusters === 0) {
console.log("Setting up Argo Cluster.");
let contextArr = await getKubeContexts();
let account = getAcctFromClusterNum(0);
await runCommand('kubectl config use-context '+contextArr[0]);
await runCommand('aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicy --policy-document file://iam_policy.json',"","EntityAlreadyExists",true);
await runCommand('eksctl utils associate-iam-oidc-provider --region='+account['region']+' --cluster='+clusterPrefix+'0 --approve');
await runCommand('eksctl create iamserviceaccount --cluster='+clusterPrefix+'0 --namespace=kube-system --name=aws-load-balancer-controller --role-name=AmazonEKSLoadBalancerControllerRole --attach-policy-arn=arn:aws:iam::'+account['awsAccountNum']+':policy/AWSLoadBalancerControllerIAMPolicy --approve');
await runCommand('eksctl create iamserviceaccount --cluster='+clusterPrefix+'0 --namespace=kube-system --name=ebs-csi-controller-sa --role-name=AmazonEKS_EBS_CSI_DriverRole --attach-policy-arn=arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy --approve --role-only');
await runCommand('eksctl create addon --name aws-ebs-csi-driver --cluster '+clusterPrefix+'0 --service-account-role-arn arn:aws:iam::'+account['awsAccountNum']+':role/AmazonEKS_EBS_CSI_DriverRole --force');
await runCommand('helm repo add eks https://aws.github.io/eks-charts');
await runCommand('helm repo add prometheus-community https://prometheus-community.github.io/helm-charts');
await runCommand('helm repo update');
await runCommand('helm install aws-load-balancer-controller eks/aws-load-balancer-controller -n kube-system --set clusterName='+clusterPrefix+'0 --set serviceAccount.create=false --set serviceAccount.name=aws-load-balancer-controller');
await runCommand('kubectl create namespace prometheus');
await runCommand('helm install prometheus-operator prometheus-community/kube-prometheus-stack -n prometheus');
await runCommand('kubectl patch svc prometheus-operator-grafana -n prometheus -p "{\\"spec\\": {\\"type\\": \\"LoadBalancer\\"}}"');
} else {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let argoHostname = await loginArgoCD();
for(let i = currentNumClusters;i<numClusters;i++) {
console.log("Registering cluster "+clusterPrefix+""+i+" to argocd.");
await runCommand('argocd cluster add --config ~/argoconfigs/'+argoHostname+' '+contextArr[i],"","",false,getAcctFromClusterNum(i));
}
}
}
}
if(action.match(/^(postVClusterCreate)$/)) {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let checkNamespace = await runCommand('kubectl get namespace');
if(!checkNamespace.stdout.match(/prometheus/g)) {
console.log("Namespace not found, creating namespace and deploying prometheus.");
await runCommand('kubectl create namespace prometheus');
}
await runCommand('helm upgrade --install prometheus-operator prometheus-community/kube-prometheus-stack -n prometheus');
await runCommand('kubectl patch svc prometheus-operator-grafana -n prometheus -p "{\\"spec\\": {\\"type\\": \\"LoadBalancer\\"}}"');
}
if(action.match(/^(installArgo)$/)) {
console.log("Installing argo on Argo Cluster.");
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let checkNamespace = await runCommand('kubectl get namespace');
if(!checkNamespace.stdout.match(/argocd/g)) {
console.log("Namespace not found, creating namespace and deploying argocd.");
await runCommand('kubectl create namespace argocd');
}
await runCommand('helm repo add argo https://argoproj.github.io/argo-helm');
await runCommand('helm -f argocd_values.yaml upgrade --install argocd argo/argo-cd -n argocd');
await runCommand('kubectl wait pod -n argocd -l app.kubernetes.io/name=argocd-server --for=condition=ready --timeout=90s');
await runCommand('kubectl apply -f argocd-dashboard.yaml -n prometheus');
}
if(action.match(/^(installArgo|postInstallArgo)$/)) {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let argoHostname = await loginArgoCD();
for(let i = 1;i<contextArr.length;i++) {
console.log("Registering cluster "+clusterPrefix+""+i+" to argocd.");
await runCommand('argocd --config ~/argoconfigs/'+argoHostname+' cluster add '+contextArr[i],"","",false,getAcctFromClusterNum(i));
}
await runCommand('kubectl apply -f argocd-metrics.yaml -n argocd');
await getDashboards();
}
if(action.match(/^(installGitea)$/)) {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
await runCommand('helm upgrade --install gitea gitea --repo https://dl.gitea.com/charts/ --set redis-cluster.enabled=false --set postgresql.enabled=false --set postgresql-ha.enabled=false --set persistence.enabled=false --set gitea.config.database.DB_TYPE=sqlite3 --set gitea.config.session.PROVIDER=memory --set gitea.config.cache.ADAPTER=memory --set gitea.config.queue.TYPE=level --set gitea.admin.username=adminuser --set gitea.admin.password=password --set service.http.type=LoadBalancer --set-json service.http.annotations=\'{"service.beta.kubernetes.io/aws-load-balancer-scheme": "internet-facing"}\' --namespace gitea --create-namespace --wait',"","Error: services \"gitea-http\" not found", false);
await getDashboards();
}
if(action.match(/^(scaleAWKApps)$/)) {
if(!giteaToken || !numAppsPerCluster || !appName) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let getGiteaURL = JSON.parse((await runCommand('kubectl get svc gitea-http -n gitea -o json',"", "NotFound",true,getAcctFromClusterNum(0))).stdout);
let gitHostname = getGiteaURL.status.loadBalancer.ingress[0].hostname;
let gitURL = 'http://' + gitHostname +':3000';
await runCommand('tea login add --url gitURL --user adminuser --password password --token '+giteaToken, "","Error: token already been used",true)
let clusterArr = await getClusterURLs();
if(!numClusters) {
numClusters = clusterArr.length;
} else {
numClusters = parseInt(numClusters);
if(numClusters >= clusterArr.length) {
numClusters = clusterArr.length;
} else {
numClusters += 1;
}
}
let argoHostname = await loginArgoCD();
let argoApps = await getArgoApps(appName, argoHostname);
console.time();
let promiseArr = [];
let errors = 0;
for(let i=1;i<numClusters;i++) {
if(!argoApps[i]) {
argoApps[i] = [];
}
for(let y=0;y<numAppsPerCluster;y++) {
if(!argoApps[i][y]) {
let appNameFull = 'cluster-'+i+'-'+appName+'-'+y
await runCommand('tea repo create --name '+appNameFull, "","Error: The repository with the same name already exists",true);
await runCommand('git clone '+gitURL+'/adminuser/'+appNameFull+' temp/'+appNameFull, "", "already exists and is not an empty directory.", true);
await runCommand('cd temp/'+appNameFull+'; git remote set-url origin http://adminuser:password@'+gitHostname+':3000/adminuser/'+appNameFull, "", "", true);
let testUser = `
apiVersion: iam.services.k8s.aws/v1alpha1
kind: User
metadata:
name: `+appNameFull+`
spec:
name: `+appNameFull+`
tags:
- key: tag1
value: val1
`;
await runCommand('mkdir temp/'+appNameFull+'/app; echo "'+testUser+'" > temp/'+appNameFull+'/app/testuser.yaml', "", "", true);
await runCommand('cd temp/'+appNameFull+'; git add .; git commit -m "Test"; git push origin main', "", "", true);
let promise = exec('argocd app create '+appNameFull+' --config ~/argoconfigs/'+argoHostname+' --repo '+gitURL+'/adminuser/'+appNameFull+' --path app --dest-namespace ack-system --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto').catch((error)=>{
errors++;
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
}
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
if(action.match(/^(installArgoWorkflows)$/)) {
console.log("Installing argo workflows on Argo Cluster.");
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let checkNamespace = await runCommand('kubectl get namespace');
if(!checkNamespace.stdout.match(/argocd/g)) {
console.log("Namespace not found, creating namespace and deploying argocd.");
await runCommand('kubectl create namespace argocd');
}
await runCommand('helm repo add argo https://argoproj.github.io/argo-helm');
await runCommand('helm -f argoworkflows_values.yaml install argoworkflows argo/argo-workflows -n argocd');
}
if(action.match(/^(installArgoWorkflows|postInstallArgoWorkflows)$/)) {
let contextArr = await getKubeContexts();
await runCommand('kubectl config use-context '+contextArr[0]);
await runCommand('kubectl apply -f argoworkflows-secret.yaml -n argocd');
await runCommand('kubectl create clusterrolebinding argo-workflow-admin --clusterrole=admin --serviceaccount=argocd:argo-workflow');
await runCommand('kubectl apply -f argoworkflows-metrics.yaml -n argocd');
await getDashboards();
}
if(action.match(/^(installArgoWorkflowsNamespace)$/)) {
if(!numWorkflows) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
for(let i=1;i<=numWorkflows;i++) {
let namespace = "argoworkflows"+i;
await runCommand('kubectl create namespace '+namespace, "", "AlreadyExists", true);
await runCommand('kubectl apply -n '+namespace+' -f namespace-install.yaml');
await runCommand('kubectl apply -f argoworkflows-metrics.yaml -n '+namespace)
}
}
if(action.match(/^setWorkflowsQPS$/)) {
if(!burstQPS && !QPS && !numWorkflows) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
for(let i=1;i<=numWorkflows;i++) {
let namespace = "argoworkflows"+i;
await runCommand('kubectl get deployment workflow-controller -n '+namespace+' -o json > argoworkflows-argo-workflows-workflow-controller-'+namespace+'.json',"","",true);
let file = fs.readFileSync("argoworkflows-argo-workflows-workflow-controller-"+namespace+".json");
let json = JSON.parse(file.toString());
let qpsIndex = json.spec.template.spec.containers[0].args.indexOf('--qps');
if(qpsIndex !== -1) {
json.spec.template.spec.containers[0].args[qpsIndex+1] = ""+QPS+"";
} else {
json.spec.template.spec.containers[0].args.push('--qps');
json.spec.template.spec.containers[0].args.push(""+QPS+"");
}
let burstQPSIndex = json.spec.template.spec.containers[0].args.indexOf("--burst");
if (burstQPSIndex !== -1) {
json.spec.template.spec.containers[0].args[burstQPSIndex+1] = ""+burstQPS+"";
} else {
json.spec.template.spec.containers[0].args.push('--burst');
json.spec.template.spec.containers[0].args.push(""+burstQPS+"");
}
fs.writeFileSync("argoworkflows-argo-workflows-workflow-controller-"+namespace+".json",JSON.stringify(json));
await runCommand('kubectl apply -f argoworkflows-argo-workflows-workflow-controller-'+namespace+'.json -n '+namespace,"","",false);
await runCommand('kubectl rollout restart deployment workflow-controller -n '+namespace);
}
}
if(action.match(/^setWorkflowsWorkers$/)) {
if(!numWorkers && !numWorkflows) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
for(let i=1;i<=numWorkflows;i++) {
let namespace = "argoworkflows"+i;
await runCommand('kubectl get deployment workflow-controller -n '+namespace+' -o json > argoworkflows-argo-workflows-workflow-controller-'+namespace+'.json',"","",true);
let file = fs.readFileSync("argoworkflows-argo-workflows-workflow-controller-"+namespace+".json");
let json = JSON.parse(file.toString());
let workersIndex = json.spec.template.spec.containers[0].args.indexOf('--workflow-workers');
if (workersIndex !== -1) {
json.spec.template.spec.containers[0].args[workersIndex+1] = ""+numWorkers+"";
} else {
json.spec.template.spec.containers[0].args.push('--workflow-workers');
json.spec.template.spec.containers[0].args.push(""+numWorkers+"");
}
fs.writeFileSync("argoworkflows-argo-workflows-workflow-controller-"+namespace+".json",JSON.stringify(json));
await runCommand('kubectl apply -f argoworkflows-argo-workflows-workflow-controller-'+namespace+'.json -n '+namespace,"","",false);
await runCommand('kubectl rollout restart deployment workflow-controller -n '+namespace);
}
}
if(action.match(/^(installACK)$/)) {
if(!clusterStart && !numClusters && !ackService) {
console.log("Missing required parameter.");
process.exit(1);
}
console.log("Installing ACK on remote Clusters.");
let contextArr = await getKubeContexts();
for(let i=clusterStart;i<numClusters;i++) {
console.log(contextArr[i]);
await runCommand('kubectl config use-context '+contextArr[i]);
let account = getAcctFromClusterNum(i);
await runCommand('eksctl utils associate-iam-oidc-provider --cluster '+contextArr[i]+' --region '+account['region']+' --approve',"","",false,account);
let oidcProvider = (await runCommand('aws eks describe-cluster --name '+contextArr[i]+' --region '+account['region']+' --query "cluster.identity.oidc.issuer" --output text | sed -e "s/^https:\\/\\///"',"","",true,account)).stdout;
oidcProvider = oidcProvider.replaceAll("\n","");
let trustPolicy = `
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::${account['awsAccountNum']}:oidc-provider/${oidcProvider}"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"${oidcProvider}:sub": "system:serviceaccount:ack-system:ack-${ackService}-controller"
}
}
}
]
}
`;
await runCommand('aws iam create-role --role-name "'+contextArr[i]+'-ack-'+ackService+'-controller" --assume-role-policy-document \''+JSON.stringify(JSON.parse(trustPolicy))+'\' --description "IRSA role for all ACK Controllers"',"","EntityAlreadyExists",true,account);
await runCommand('aws iam attach-role-policy --role-name "'+contextArr[i]+'-ack-'+ackService+'-controller" --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess"',"","",false,account);
await runCommand('aws ecr-public get-login-password --region '+account['region']+' | helm registry login --username AWS --password-stdin public.ecr.aws',"","",false,account);
let releaseVersion = (JSON.parse((await runCommand("curl -sL https://api.github.com/repos/aws-controllers-k8s/"+ackService+"-controller/releases/latest","","",true,account)).stdout)['tag_name']).replaceAll("v","");
await runCommand('helm upgrade --install --create-namespace -n ack-system ack-'+ackService+'-controller oci://public.ecr.aws/aws-controllers-k8s/'+ackService+'-chart --version='+releaseVersion+' --set=aws.region='+account['region']+' --set-json \'serviceAccount.name="ack-'+ackService+'-controller"\' --set-json \'serviceAccount.annotations={"eks.amazonaws.com/role-arn":"arn:aws:iam::'+account['awsAccountNum']+':role/'+contextArr[i]+'-ack-'+ackService+'-controller"}\'',"","INSTALLATION FAILED: cannot re-use a name that is still in use",false,account);
await runCommand('kubectl set env deployment/ack-'+ackService+'-controller-'+ackService+'-chart -n ack-system RECONCILE_DEFAULT_RESYNC_SECONDS=10',"","",false,account);
}
}
if(action.match(/^(getDashboards)$/)) {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
await loginArgoCD();
await getDashboards();
}
if(action.match(/^(scaleAppsRandom)$/)) {
if(!numApps || !appName) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await runCommand('kubectl config use-context '+contextArr[0]);
let clusterArr = await getClusterURLs();
if(!numClusters) {
numClusters = clusterArr.length;
} else {
numClusters = parseInt(numClusters);
if(numClusters >= clusterArr.length) {
numClusters = clusterArr.length;
} else {
numClusters += 1;
}
}
let argoHostname = await loginArgoCD();
console.time();
let promiseArr = [];
let errors = 0;
for(let i=1;i<numClusters;i++) {
let numAppsToCreate = Math.floor(Math.random() * (400 - 1) + 1);
if((i+1) === numClusters) {
numAppsToCreate = numApps;
}
if(numAppsToCreate < numApps) {
numApps = numApps - numAppsToCreate;
} else {
numAppsToCreate = numApps;
numApps = 0;
}
console.log(i+":"+numAppsToCreate);
for(let y=0;y<numAppsToCreate;y++) {
let promise = exec('argocd app create cluster-'+i+'-'+appName+'-'+y+' --config ~/argoconfigs/'+argoHostname+' --repo '+appRepo+' --path '+appName+' --dest-namespace cluster-'+i+'-'+appName+'-'+y+' --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto --sync-option CreateNamespace=true').catch((error)=>{
errors++;
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
}
await Promise.allSettled(promiseArr);
promiseArr = [];
console.timeEnd();
console.log("Errors: "+errors);
}
if(action.match(/^(fixApps)$/)) {
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let clusterArr = await getClusterURLs();
if(!numClusters) {
numClusters = clusterArr.length;
} else {
numClusters = parseInt(numClusters);
if(numClusters >= clusterArr.length) {
numClusters = clusterArr.length;
} else {
numClusters += 1;
}
}
let argoHostname = await loginArgoCD();
let argoApps = await getArgoApps(appName, argoHostname);
let promiseArr = [];
let errors = 0;
for(let i=1;i<numClusters;i++) {
if(i >= 46) {
console.log(i+"\n");
for(let y=0;y<1;y++) {
let appGenName = 'cluster-'+i+'-'+appName+'-'+y;
if(appPrefix) {
appGenName = appPrefix + "-" + appGenName;
}
let promise = exec('argocd app create '+appGenName+' --config ~/argoconfigs/'+argoHostname+' --repo '+appRepo+' --path '+appName+' --dest-namespace '+appGenName+' --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto --sync-option CreateNamespace=true').catch((error)=>{
console.log(error);
errors++;
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
}
}
await Promise.allSettled(promiseArr);
}
if(action.match(/^(scaleApps)$/)) {
if(!numAppsPerCluster || !appName) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let clusterArr = await getClusterURLs();
if(!numClusters) {
numClusters = clusterArr.length;
} else {
numClusters = parseInt(numClusters);
if(numClusters >= clusterArr.length) {
numClusters = clusterArr.length;
} else {
numClusters += 1;
}
}
let argoHostname = await loginArgoCD();
let argoApps = await getArgoApps(appName, argoHostname);
console.time();
let promiseArr = [];
let errors = 0;
for(let i=1;i<numClusters;i++) {
if(!argoApps[i]) {
argoApps[i] = [];
}
if(appRepo) {
for(let y=0;y<numAppsPerCluster;y++) {
let appGenName = 'cluster-'+i+'-'+appName+'-'+y;
if(appPrefix) {
appGenName = appPrefix + "-" + appGenName;
}
if(!argoApps[i][y]) {
let promise = exec('argocd app create '+appGenName+' --config ~/argoconfigs/'+argoHostname+' --repo '+appRepo+' --path '+appName+' --dest-namespace '+appGenName+' --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto --sync-option CreateNamespace=true').catch((error)=>{
console.log(error);
errors++;
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
}
await Promise.allSettled(promiseArr);
promiseArr = [];
}
if(numAppsPerCluster > argoApps[i].length) {
if(!appRepo) {
console.log("Missing required parameters: appRepo for scale up.");
process.exit(1);
}
for(let y=argoApps[i].length;y<numAppsPerCluster;y++) {
let appGenName = 'cluster-'+i+'-'+appName+'-'+y;
if(appPrefix) {
appGenName = appPrefix + "-" + appGenName;
}
let promise = exec('argocd app create '+appGenName+' --config ~/argoconfigs/'+argoHostname+' --repo '+appRepo+' --path '+appName+' --dest-namespace '+appGenName+' --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto --sync-option CreateNamespace=true').catch((error)=>{
console.log('Tried to run command: argocd app create '+appGenName+' --config ~/argoconfigs/'+argoHostname+' --repo '+appRepo+' --path '+appName+' --dest-namespace '+appGenName+' --dest-server '+clusterArr[i]+' --directory-recurse --sync-policy auto --sync-option CreateNamespace=true');
console.log(error.stderr);
errors++;
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
} else if(numAppsPerCluster < argoApps[i].length) {
for(let y=argoApps[i].length-1;y>numAppsPerCluster-1;y--) {
let appGenName = 'cluster-'+i+'-'+appName+'-'+y;
if(appPrefix) {
appGenName = appPrefix + "-" + appGenName;
}
let promise = exec('argocd app delete '+appGenName+' --config ~/argoconfigs/'+argoHostname+' --yes').catch((error)=> {
console.log(error.stderr);
});
promiseArr.push(promise);
await sleep(300);
if(promiseArr.length > 50) {
await Promise.allSettled(promiseArr);
promiseArr = [];
}
}
}
}
await Promise.allSettled(promiseArr);
console.timeEnd();
console.log("Errors: "+errors);
}
if(action.match(/^(deleteAllApps)$/)) {
if(!appName) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await setContext(contextArr, vClusterContext);
let clusterArr = await getClusterURLs();
let argoHostname = await loginArgoCD();
let argoApps = await getArgoApps(appName, argoHostname);
console.time();
let promiseArr = [];
for(let i in clusterArr) {
if(!argoApps[i]) {
argoApps[i] = [];
}
for(let y in argoApps[i]) {
let promise = exec('argocd app delete '+argoApps[i][y]+' --config ~/argoconfigs/'+argoHostname+' --yes').catch((error)=> {
console.log(error.stderr);
});
promiseArr.push(promise);
await sleep(200);
if(promiseArr.length > 50) {
await Promise.all(promiseArr);
promiseArr = [];
}
}
}
await Promise.all(promiseArr);
console.timeEnd();
}
if(action.match(/^(scaleArgoCluster)$/)) {
if(!numNodes) {
console.log("Missing required parameter.");
process.exit(1);
}
let contextArr = await getKubeContexts();
await runCommand('kubectl config use-context '+contextArr[0]);
if(instanceType) {
let oldNodeGroup = JSON.parse((await runCommand('eksctl get nodegroup --cluster '+clusterPrefix+'0 -o json',"","",true)).stdout)[0].Name;
if(oldNodeGroup.split("-")[2] != instanceType) {