-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathapi_app.go
More file actions
2470 lines (2237 loc) · 88.4 KB
/
api_app.go
File metadata and controls
2470 lines (2237 loc) · 88.4 KB
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
// replication-manager - Replication Manager Monitoring and CLI for MariaDB and MySQL
// Copyright 2017-2021 SIGNAL18 CLOUD SAS
// Author: Stephane Varoqui <svaroqui@gmail.com>
// License: GNU General Public License, version 3. Redistribution/Reuse of this code is permitted under the GNU v3 license, as an additional term ALL code must carry the original Author(s) credit in comment form.
// See LICENSE in this directory for the integral text.
package server
import (
"encoding/json"
"fmt"
"io"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/signal18/replication-manager/cluster"
"github.com/signal18/replication-manager/config"
"github.com/signal18/replication-manager/utils/githelper"
"github.com/tidwall/sjson"
)
func (repman *ReplicationManager) apiAppProtectedHandler(router *mux.Router) {
//PROTECTED ENDPOINTS FOR APPS
router.Handle("/api/clusters/{clusterName}/apps/{appName}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxApp)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/service-opensvc", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxGetAppServiceConfig)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/substitution", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppSubstitutionVariables)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/resolve-template", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppResolveTemplate)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/deployment", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppDeployments)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/deployment/{field}/index/{index}/{key}/modify", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxModifyDeploymentField)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/deployment/{field}/add", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAddDeploymentFieldRow)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/deployment/{field}/index/{index}/drop", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxDropDeploymentFieldRow)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/unprovision", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppUnprovision)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/provision", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppProvision)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/stop", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppStop)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/stop/{node}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppStop)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/start", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppStart)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/start/{node}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppStart)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/restart", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppRestart)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/restart/{node}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppRestart)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/need-restart", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppNeedRestart)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/actions/need-reprov", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppNeedReprov)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appId}/settings/actions/set/{setting}/{value:.*}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppSetSetting)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appId}/settings/actions/switch/{setting}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppSwitchSetting)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appId}/settings/actions/clear/{setting}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppClearSetting)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/settings/actions/reset-from-template", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppResetFromTemplate)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/settings/actions/save-as-template", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppSaveAsTemplate)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/settings/actions/save-as-template/{templateName}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppSaveAsTemplate)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/storages/{field}/index/{index}/{key}/modify", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxModifyStorageField)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/storages/{field}/add", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAddStorage)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appName}/storages/{field}/index/{index}/drop", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxDropStorageFieldRow)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appId}/git/{gitName}/actions/get-repo-tree", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxGitRepoTree)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appId}/git/{gitName}/actions/get-repo-tree/{force}", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxGitRepoTree)),
))
router.Handle("/api/clusters/{clusterName}/apps/{appHost}/{appPort}/actions/drop", negroni.New(
negroni.HandlerFunc(repman.validateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(repman.handlerMuxAppDropByName)),
))
}
// @Summary Shows the apps for that specific named cluster
// @Description Shows the apps for that specific named cluster
// @Tags Apps
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Success 200 {object} cluster.App "Server details retrieved successfully"
// @Failure 500 {string} string "Internal Server Error"
// @Router /api/clusters/{clusterName}/apps/{appName} [get]
func (repman *ReplicationManager) handlerMuxApp(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
//marshal unmarchal for ofuscation deep copy of struc
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
uname := repman.GetUserFromRequest(r)
if _, ok := mycluster.APIUsers[uname]; !ok {
http.Error(w, "No Valid ACL", http.StatusInternalServerError)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil {
data, _ := json.Marshal(node)
var app cluster.App
err := json.Unmarshal(data, &app)
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error encoding JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
e := json.NewEncoder(w)
e.SetIndent("", "\t")
err = e.Encode(app)
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error encoding JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
}
// @Summary Start App Service
// @Description Start the app service for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Param node path string false "Node Name (optional, if not provided, will start default node). Can use ALL or * to start on all nodes."
// @Success 200 {string} string "App Service Started"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Cluster Not Found" "Server Not Found"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/start [post]
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/start/{node} [post]
func (repman *ReplicationManager) handlerMuxAppStart(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
if mycluster.GetOrchestrator() != "opensvc" {
http.Error(w, "Orchestrator not supported", http.StatusInternalServerError)
return
}
app := mycluster.GetAppFromName(vars["appName"])
if app != nil {
mycluster.OpenSVCStartAppService(app, vars["node"])
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Cluster Not Found", http.StatusInternalServerError)
return
}
}
// @Summary Stop App Service
// @Description Stop the app service for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Param node path string false "Node Name (optional, if not provided, will stop default node). Can use ALL or * to stop on all nodes."
// @Success 200 {string} string "App Service Stopped"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Cluster Not Found" "Server Not Found"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/stop [post]
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/stop/{node} [post]
func (repman *ReplicationManager) handlerMuxAppStop(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
if mycluster.GetOrchestrator() != "opensvc" {
http.Error(w, "Orchestrator not supported", http.StatusInternalServerError)
return
}
app := mycluster.GetAppFromName(vars["appName"])
if app != nil {
mycluster.OpenSVCStopAppService(app, vars["node"])
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Cluster Not Found", http.StatusInternalServerError)
return
}
}
// @Summary Restart App Service
// @Description Restart the app service for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Param node path string false "Node Name (optional, if not provided, will restart default node). Can use ALL or * to restart on all nodes."
// @Success 200 {string} string "App Service Restarted"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Cluster Not Found" "Server Not Found"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/restart [post]
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/restart/{node} [post]
func (repman *ReplicationManager) handlerMuxAppRestart(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
if mycluster.GetOrchestrator() != "opensvc" {
http.Error(w, "Orchestrator not supported", http.StatusInternalServerError)
return
}
app := mycluster.GetAppFromName(vars["appName"])
if app != nil {
rid := r.URL.Query().Get("rid")
mycluster.OpenSVCRestartAppService(app, vars["node"], rid)
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Cluster Not Found", http.StatusInternalServerError)
return
}
}
// @Summary Provision App Service
// @Description Provision the app service for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Success 200 {string} string "App Service Provisioned"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Cluster Not Found" "Server Not Found"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/provision [post]
func (repman *ReplicationManager) handlerMuxAppProvision(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
if mycluster.GetOrchestrator() != "opensvc" {
http.Error(w, "Orchestrator not supported", http.StatusInternalServerError)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil {
err := mycluster.InitAppService(node)
if err != nil {
http.Error(w, "Failed to provision app service: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Cluster Not Found", http.StatusInternalServerError)
return
}
}
// @Summary Unprovision App Service
// @Description Unprovision the app service for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Success 200 {string} string "App Service Unprovisioned"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Cluster Not Found" "Server Not Found"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/unprovision [post]
func (repman *ReplicationManager) handlerMuxAppUnprovision(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
if mycluster.GetOrchestrator() != "opensvc" {
http.Error(w, "Orchestrator not supported", http.StatusInternalServerError)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil {
mycluster.OpenSVCUnprovisionAppService(node)
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Cluster Not Found", http.StatusInternalServerError)
return
}
}
// @Summary Check if App Needs Restart
// @Description Check if the app service for a given cluster and app needs a restart
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Success 200 {string} string "Need restart!"
// @Failure 403 {string} string "No valid ACL"
// @Failure 503 {string} string "No restart needed!" "Not a Valid Server!"
// @Failure 500 {string} string "No cluster"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/need-restart [get]
func (repman *ReplicationManager) handlerMuxAppNeedRestart(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil && !node.IsDown() {
if node.HasRestartCookie() {
w.Write([]byte("200 -Need restart!"))
return
}
w.Write([]byte("503 -No restart needed!"))
http.Error(w, "Encoding error", http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("503 -Not a Valid Server!"))
}
} else {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
}
// @Summary Check if App Needs Reprovision
// @Description Check if the app service for a given cluster and app needs reprovisioning
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Success 200 {string} string "Need reprov!"
// @Failure 403 {string} string "No valid ACL"
// @Failure 503 {string} string "No reprov needed!" "Not a Valid Server!"
// @Failure 500 {string} string "No cluster"
// @Router /api/clusters/{clusterName}/apps/{appName}/actions/need-reprov [get]
func (repman *ReplicationManager) handlerMuxAppNeedReprov(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil && !node.IsDown() {
if node.HasReprovCookie() {
w.Write([]byte("200 -Need reprov!"))
return
}
w.Write([]byte("503 -No reprov needed!"))
http.Error(w, "Encoding error", http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("503 -Not a Valid Server!"))
}
} else {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
}
// @Summary Shows the deployments for that specific named app
// @Description Shows the deployments for that specific named app
// @Tags Apps
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Success 200 {array} config.Deployment "Server details retrieved successfully"
// @Failure 500 {string} string "Internal Server Error"
// @Router /api/clusters/{clusterName}/apps/{appName}/deployment [get]
func (repman *ReplicationManager) handlerMuxAppDeployments(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
//marshal unmarchal for ofuscation deep copy of struc
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
uname := repman.GetUserFromRequest(r)
if _, ok := mycluster.APIUsers[uname]; !ok {
http.Error(w, "No Valid ACL", http.StatusInternalServerError)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil {
dep, err := json.MarshalIndent(node.AppConfig.Deployment, "", "\t")
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error encoding JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
for vidx, v := range node.AppConfig.Deployment.Variables {
if v.Type == "secret" {
dep, err = sjson.SetBytes(dep, fmt.Sprintf("variables.%d.value", vidx), "*****")
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error maskin secrets JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
}
}
for gidx := range node.AppConfig.Deployment.Storages.GitClones {
dep, err = sjson.SetBytes(dep, fmt.Sprintf("storages.gitClones.%d.pass", gidx), "*****")
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error maskin secrets JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
}
for midx := range node.AppConfig.Deployment.Storages.S3Mounts {
dep, err = sjson.SetBytes(dep, fmt.Sprintf("storages.s3Mounts.%d.secretkey", midx), "*****")
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error maskin secrets JSON: ", err)
http.Error(w, "Encoding error", http.StatusInternalServerError)
return
}
}
w.Write(dep)
return
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
}
// @Summary Modify Deployment Field
// @Description Modify a specific field in a deployment for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Param field path string true "Field to modify"
// @Param index path string true "Index of the field to modify"
// @Param key path string true "Key of the field to modify"
// @Param value body object{value=any} true "New value for the field"
// @Success 200 {string} string "Deployment field modified"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Error decoding JSON" "Server Not Found" "Deployment not found" "No cluster"
// @Router /api/clusters/{clusterName}/apps/{appName}/deployment/{field}/index/{index}/{key}/modify [post]
func (repman *ReplicationManager) handlerMuxModifyDeploymentField(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster != nil {
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node != nil {
var newValue string
var condValue config.AVSlice
if vars["field"] == "variables" && vars["key"] == "conditional" {
type ConditionalValue struct {
Value config.AVSlice `json:"value"`
}
var body ConditionalValue
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
http.Error(w, "Error decoding JSON: "+err.Error(), http.StatusInternalServerError)
return
}
condValue = body.Value
sort.Sort(condValue)
} else {
type FieldValue struct {
Value string `json:"value"`
}
var body FieldValue
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
http.Error(w, "Error decoding JSON: "+err.Error(), http.StatusInternalServerError)
return
}
newValue = body.Value
}
if vars["index"] == "" || vars["index"] == "undefined" {
http.Error(w, "Index not provided", http.StatusInternalServerError)
return
}
index, err := strconv.Atoi(vars["index"])
if err != nil {
http.Error(w, "Error parsing index: "+err.Error(), http.StatusInternalServerError)
return
}
if index < 0 {
http.Error(w, "Index cannot be negative", http.StatusInternalServerError)
return
}
if vars["key"] == "" || vars["key"] == "undefined" {
// For gitClones, variables, and path, key is required
http.Error(w, "Key not provided", http.StatusInternalServerError)
return
}
switch vars["field"] {
// fields which are arrays of objects
case "routes":
if index >= len(node.AppConfig.Deployment.Routes) {
http.Error(w, "Index out of range for routes", http.StatusInternalServerError)
return
}
// Modify field based on key
switch vars["key"] {
case "cname":
if node.AppConfig.Deployment.Routes[index].CName == newValue {
http.Error(w, "CNAME unchanged", http.StatusInternalServerError)
return
}
for _, existing := range node.AppConfig.Deployment.Routes {
if existing.CName == newValue {
http.Error(w, "Cannot duplicate route with same CName", http.StatusInternalServerError)
return
}
}
node.AppConfig.Deployment.Routes[index].CName = newValue
case "port":
if node.AppConfig.Deployment.Routes[index].Port == newValue {
http.Error(w, "Port unchanged", http.StatusInternalServerError)
return
}
node.AppConfig.Deployment.Routes[index].Port = newValue
case "protocol":
if node.AppConfig.Deployment.Routes[index].Protocol == newValue {
http.Error(w, "Protocol unchanged", http.StatusInternalServerError)
return
}
if newValue != "tcp" && newValue != "https" {
http.Error(w, "Invalid protocol. Must be 'tcp' or 'https'", http.StatusInternalServerError)
return
}
node.AppConfig.Deployment.Routes[index].Protocol = newValue
default:
http.Error(w, "Invalid key for routes", http.StatusInternalServerError)
return
}
case "variables":
if index >= len(node.AppConfig.Deployment.Variables) {
http.Error(w, "Index out of range for variables", http.StatusInternalServerError)
return
}
row := node.AppConfig.Deployment.Variables[index]
if row.Locked {
http.Error(w, "Unable to change name of locked variable. Please change the source of the variable instead.", http.StatusInternalServerError)
return
}
// Modify field based on key
switch vars["key"] {
case "name":
if row.Name == newValue {
http.Error(w, "Variable name unchanged", http.StatusInternalServerError)
return
}
row.Name = newValue
case "value":
if row.Value == newValue {
http.Error(w, "Variable value unchanged", http.StatusInternalServerError)
return
}
row.Value = newValue
case "type":
if row.Type == newValue {
http.Error(w, "Variable type unchanged", http.StatusInternalServerError)
return
}
row.Type = newValue
case "conditional":
old := row.Conditional
// addFunc := func(new config.AgentVariable) config.AgentVariable {
// // new.Value, _ = node.ClusterGroup.ParseAppTemplate(new.Value, node.AppClusterSubstitute)
// return new
// }
// updateFunc := func(old, new config.AgentVariable) config.AgentVariable {
// // new.Value, _ = node.ClusterGroup.ParseAppTemplate(new.Value, node.AppClusterSubstitute)
// return new
// }
if row.Type == config.VariableTypeSecret {
for i, v := range condValue {
// Decrypt the value if it's a secret
condValue[i].Value = mycluster.Conf.GetEncryptedString(mycluster.Conf.GetDecryptedPassword(row.Name+"@"+v.Agent, v.Value))
}
}
row.Conditional = old.Merge(condValue, nil, nil)
default:
http.Error(w, "Invalid key for variables", http.StatusInternalServerError)
return
}
if row.Type == config.VariableTypeSecret {
row.Value = mycluster.Conf.GetEncryptedString(mycluster.Conf.GetDecryptedPassword(row.Name, row.Value))
}
node.AppConfig.Deployment.Variables[index] = row
case "paths":
if index >= len(node.AppConfig.Deployment.Paths) {
http.Error(w, "Index out of range for paths", http.StatusInternalServerError)
return
}
deployment := node.AppConfig.Deployment
if index >= len(deployment.Paths) {
http.Error(w, "Index out of range for paths", http.StatusInternalServerError)
return
}
pm := deployment.Paths[index]
// Modify field based on key
switch vars["key"] {
case "name":
http.Error(w, "Cannot change name of path. Please drop the path and recreate it with the new name.", http.StatusInternalServerError)
return
case "parent":
if pm.ParentName == newValue {
http.Error(w, "Parent unchanged", http.StatusInternalServerError)
return
}
if newValue == "" {
pm.ParentName = ""
pm.Parent = nil
} else {
parent, err := deployment.GetPathMapping(newValue)
if err != nil {
http.Error(w, "Parent path not found: "+err.Error(), http.StatusInternalServerError)
return
}
pm.ParentName = newValue
pm.Parent = parent
}
case "dockerpath":
if pm.DockerPath == newValue {
http.Error(w, "Docker path unchanged", http.StatusInternalServerError)
return
}
pm.DockerPath = newValue
case "srctype":
newSourceType := config.SourceType(newValue)
if pm.SourceType == newSourceType {
http.Error(w, "Source type unchanged", http.StatusInternalServerError)
return
}
if newValue == "" {
http.Error(w, "Source type cannot be empty", http.StatusInternalServerError)
return
}
switch newValue {
case string(config.SourceGit), string(config.SourceS3), string(config.SourceVolume):
// Reset source name and path if type changes
pm.SourceType = newSourceType
pm.SourceName = "" // Reset source name if type changes
if node.HasProvisionCookie() {
node.SetReprovCookie()
}
default:
http.Error(w, "Invalid source type. Must be 'git', 's3', or 'volume'", http.StatusInternalServerError)
return
}
case "srcname":
if pm.SourceName == newValue {
http.Error(w, "Source name unchanged", http.StatusInternalServerError)
return
}
if newValue == "" && pm.SourceType != "" {
http.Error(w, "Source name cannot be empty when source type is set", http.StatusInternalServerError)
return
}
switch pm.SourceType {
case config.SourceGit:
source, err := deployment.GetGitClone(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
case config.SourceS3:
source, err := deployment.GetS3Mount(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
case config.SourceVolume:
source, err := deployment.GetVolumeByName(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
default:
http.Error(w, "Invalid source type. Must be 'git', 's3', or 'volume'", http.StatusInternalServerError)
return
}
pm.SourceName = newValue
case "srcpath":
if pm.SourcePath == newValue {
http.Error(w, "Source path unchanged", http.StatusInternalServerError)
return
}
if newValue != "" && newValue != "/" {
pm.SourcePath = newValue
} else if pm.SourceName != "" {
switch pm.SourceType {
case config.SourceGit:
source, err := deployment.GetGitClone(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
case config.SourceS3:
source, err := deployment.GetS3Mount(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
case config.SourceVolume:
source, err := deployment.GetVolumeByName(newValue)
if err == nil {
pm.SourcePath = source.GetSourcePath()
}
default:
http.Error(w, "Invalid source type. Must be 'git', 's3', or 'volume'", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "Source path cannot be empty", http.StatusInternalServerError)
return
}
default:
http.Error(w, "Invalid key for path", http.StatusInternalServerError)
return
}
err := deployment.ResolvePath(pm)
if err != nil {
mycluster.LogModulePrintf(mycluster.Conf.Verbose, config.ConstLogModGeneral, config.LvlErr, "API Error resolving path after modification: ", err)
}
default:
http.Error(w, "Invalid field", http.StatusInternalServerError)
return
}
mycluster.EnqueueRefreshAppTemplateMD5(node)
mycluster.ConfigManager.SaveConfig(mycluster, false)
w.Write([]byte("Deployment field modified"))
} else {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
} else {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
}
// @Summary Add Deployment Field Row
// @Description Add a new row to a specific field in a deployment for a given cluster and app
// @Tags Apps
// @Accept json
// @Produce json
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)
// @Param clusterName path string true "Cluster Name"
// @Param appName path string true "App Name"
// @Param field path string true "Field to add a row to (routes, gitClones, variables, path)"
// @Param body body any true "Array of objects depending on field: - routes: []config.Route - gitClones: []config.GitClone - variables: []config.VariableMapping - path: []config.PathMapping"
// @Success 200 {string} string "Deployment field row added"
// @Failure 403 {string} string "No valid ACL"
// @Failure 500 {string} string "Error decoding JSON" "Server Not Found" "Deployment not found" "No cluster"
// @Router /api/clusters/{clusterName}/apps/{appName}/deployment/{field}/add [post]
func (repman *ReplicationManager) handlerMuxAddDeploymentFieldRow(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
mycluster := repman.getClusterByName(vars["clusterName"])
if mycluster == nil {
http.Error(w, "No cluster", http.StatusInternalServerError)
return
}
if valid, _ := repman.IsValidClusterACL(r, mycluster); !valid {
http.Error(w, "No valid ACL", http.StatusForbidden)
return
}
node := mycluster.GetAppFromName(vars["appName"])
if node == nil {
http.Error(w, "Server Not Found", http.StatusInternalServerError)
return
}
field := vars["field"]
var affected bool
switch field {
case "routes":
var body []config.Route
body, err := decodeSlice[config.Route](r, w, "route")
if err != nil {
http.Error(w, "Error decoding JSON: "+err.Error(), http.StatusInternalServerError)
return
}
for _, row := range body {
if !isValidPortFormat(row.Port) {
http.Error(w, "Invalid port format. Expected hostPort with valid port numbers", http.StatusInternalServerError)
return
}
if row.CName == "" {
http.Error(w, "CName must be provided for route", http.StatusInternalServerError)
return
}
if row.Protocol != "tcp" && row.Protocol != "https" {
http.Error(w, "Invalid protocol. Must be 'tcp' or 'https'", http.StatusInternalServerError)
return
}
// Check for duplicate route
for _, existing := range node.AppConfig.Deployment.Routes {
if existing.CName == row.CName {
http.Error(w, "Cannot duplicate route with same CName", http.StatusInternalServerError)
return
}
}
node.AppConfig.Deployment.Routes = append(node.AppConfig.Deployment.Routes, row)
affected = true
}
case "variables":
var body []config.VariableMapping
body, err := decodeSlice[config.VariableMapping](r, w, "variable")
if err != nil {
http.Error(w, "Error decoding JSON: "+err.Error(), http.StatusInternalServerError)
return
}
for _, row := range body {
old := node.AppConfig.GetDeploymentVariables(row.Name)
if old != nil {
http.Error(w, "Cannot duplicate variable with same name", http.StatusBadRequest)
return
}
// row.Value, _ = mycluster.ParseAppTemplate(row.Value, node.AppClusterSubstitute)
mycluster.SetAppVariableValue(node, row)