-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
2407 lines (2004 loc) · 64.8 KB
/
main.go
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
// CBSD Project 2013-2025
// K8s-bhyve project 2020-2025
// MyBee project 2021-2025
package main
import (
"bufio"
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
// "path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
// "gopkg.in/yaml.v3"
"github.com/gorilla/mux"
"golang.org/x/crypto/ssh"
)
var lock = sync.RWMutex{}
var config Config
var runscript string
var workdir string
var server_url string
var acl_enable bool
var spool_Dir string
var onetime_Dir string
var clusterLimitMax int
const MAX_UPLOAD_SIZE = 1024 * 1024 // 1MB
type Response struct {
Message string
}
// The cluster Type. Name of elements must match with jconf params
type Vm struct {
Image string `json:image,omitempty"`
Type string `json:type,omitempty"`
Vm_os_type string `json:vm_os_type,omitempty"`
Vm_os_profile string `json:vm_os_profile,omitempty"`
Jname string `json:jname,omitempty"`
Ram string `json:ram,omitempty"`
Cpus int `"cpus,omitempty"`
Imgsize string `"imgsize,omitempty"`
Pubkey string `"pubkey,omitempty"`
PkgList string `"pkglist,omitempty"`
Extras string `"extras,omitempty"`
Recomendation string `"recomendation,omitempty"`
Host_hostname string `"host_hostname,omitempty"`
Email string `"email,omitempty"`
Callback string `"callback,omitempty"`
}
// The cluster Type. Name of elements must match with jconf params
type Cluster struct {
Image string `json:image,omitempty"`
K8s_name string `json:jname,omitempty"`
Init_masters string `json:init_masters,omitempty"`
Init_workers string `json:init_workers,omitempty"`
Master_vm_ram string `json:master_vm_ram,omitempty"`
Master_vm_cpus string `"master_vm_cpus,omitempty"`
Master_vm_imgsize string `"master_vm_imgsize,omitempty"`
Worker_vm_ram string `"worker_vm_ram,omitempty"`
Worker_vm_cpus string `"worker_vm_cpus,omitempty"`
Worker_vm_imgsize string `"worker_vm_imgsize,omitempty"`
Pv_enable string `"pv_enable,omitempty"`
Pv_size string `"pv_size,omitempty"`
Kubelet_master string `"kubelet_master,omitempty"`
Email string `"email,omitempty"`
Callback string `"callback,omitempty"`
Pubkey string `"pubkey,omitempty"`
Recomendation string `"recomendation,omitempty"`
}
// Todo: validate mod?
// e.g for simple check:
// bhyve_name string `json:"name" validate:"required,min=2,max=100"`
var (
body = flag.String("body", "", "Body of message")
cbsdEnv = flag.String("cbsdenv", "/usr/jails", "CBSD workdir environment")
configFile = flag.String("config", "/usr/local/etc/cbsd-mq-api.json", "Path to config.json")
listen *string = flag.String("listen", "0.0.0.0:65531", "Listen host:port")
runScriptJail = flag.String("runscript_jail", "jail-api", "CBSD target run script")
runScriptBhyve = flag.String("runscript_bhyve", "bhyve-api", "CBSD target run script")
runScriptK8s = flag.String("runscript_k8s", "k8world", "CBSD target run Kubernetes script")
destroyScript = flag.String("destroy_script", "control-api", "CBSD target run script")
destroyK8sScript = flag.String("destroy_k8s_script", "k8world", "CBSD target to destroy K8S")
startScript = flag.String("start_script", "control-api", "CBSD target run script")
stopScript = flag.String("stop_script", "control-api", "CBSD target run script")
serverUrl = flag.String("server_url", "http://127.0.0.1:65532", "Server URL for external requests")
dbDir = flag.String("dbdir", "/var/db/cbsd-api", "db root dir")
k8sDbDir = flag.String("k8sdbdir", "/var/db/cbsd-k8s", "db root dir")
allowListFile = flag.String("allowlist", "", "Path to PubKey whitelist, e.g: -allowlist /usr/local/etc/cbsd-mq-api.allow")
clusterLimit = flag.Int("cluster_limit", 3, "Max number of clusters")
spoolDir = flag.String("spooldir", "/var/spool/cbsd-mq-api", "spool root dir")
oneTimeConfDir = flag.String("onetimeconfdir", "", "one-time config dir")
)
type AllowList struct {
keyType string
key string
comment string
cid string
next *AllowList // link to the next records
}
// linked struct
type Feed struct {
length int
start *AllowList
}
type MyFeeds struct {
f *Feed
}
// Progress is used to track the progress of a file upload.
// It implements the io.Writer interface so it can be passed
// to an io.TeeReader()
type Progress struct {
TotalSize int64
BytesRead int64
}
// Write is used to satisfy the io.Writer interface.
// Instead of writing somewhere, it simply aggregates
// the total bytes on each read
func (pr *Progress) Write(p []byte) (n int, err error) {
n, err = len(p), nil
pr.BytesRead += int64(n)
pr.Print()
return
}
// Print displays the current progress of the file upload
func (pr *Progress) Print() {
if pr.BytesRead == pr.TotalSize {
fmt.Println("DONE!")
return
}
fmt.Printf("File upload in progress: %d\n", pr.BytesRead)
}
func (f *Feed) Append(newAllow *AllowList) {
if f.length == 0 {
f.start = newAllow
} else {
currentPost := f.start
for currentPost.next != nil {
currentPost = currentPost.next
}
currentPost.next = newAllow
}
f.length++
}
func newAllow(keyType string, key string, comment string) *AllowList {
KeyInList := fmt.Sprintf("%s %s %s", keyType, key, comment)
uid := []byte(KeyInList)
cid := md5.Sum(uid)
cidString := fmt.Sprintf("%x", cid)
np := AllowList{keyType: keyType, key: key, comment: comment, cid: cidString}
// np.Response = ""
// np.Time = 0
return &np
}
// we need overwrite Content-Type here
// https://stackoverflow.com/questions/59763852/can-you-return-json-in-golang-http-error
func JSONError(w http.ResponseWriter, message string, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
// write header is mandatory to overwrite header
w.WriteHeader(code)
if len(message) > 0 {
response := Response{message}
js, err := json.Marshal(response)
if err != nil {
fmt.Fprintln(w, "{\"Message\":\"Marshal error\"}", http.StatusMethodNotAllowed)
return
}
http.Error(w, string(js), code)
} else {
http.Error(w, "{}", http.StatusOK)
}
return
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("file does not exist", filename)
return false
} else {
// error
return false
}
} else {
// file exist
return true
}
}
// main function to boot up everything
func main() {
flag.Parse()
var err error
config, err = LoadConfiguration(*configFile)
workdir = config.CbsdEnv
server_url = config.ServerUrl
spool_Dir = *spoolDir
onetime_Dir = *oneTimeConfDir
if !fileExists(spool_Dir) {
os.MkdirAll(spool_Dir, 0770)
}
clusterLimitMax = *clusterLimit
if err != nil {
fmt.Println("config load error")
os.Exit(1)
}
if !fileExists(config.Recomendation) {
fmt.Printf("no such Recomendation script, please check config/path: %s\n", config.Recomendation)
os.Exit(1)
}
if !fileExists(config.Freejname) {
fmt.Printf("no such Freejname script, please check config/path: %s\n", config.Freejname)
os.Exit(1)
}
if !fileExists(*dbDir) {
fmt.Printf("* db dir created: %s\n", *dbDir)
os.MkdirAll(*dbDir, 0770)
}
if !fileExists(*k8sDbDir) {
fmt.Printf("* db dir created: %s\n", *k8sDbDir)
os.MkdirAll(*k8sDbDir, 0770)
}
f := &Feed{}
fmt.Printf("* Cluster limit: %d\n", clusterLimitMax)
// WhiteList
if (*allowListFile == "") || (!fileExists(*allowListFile)) {
fmt.Println("* no such allowList file ( -allowlist <path> )")
fmt.Println("* ACL disabled: fully open system, all queries are permit!")
acl_enable = false
} else {
fmt.Printf("* ACL enabled: %s\n", *allowListFile)
acl_enable = true
// loadconfig
fd, err := os.Open(*allowListFile)
if err != nil {
panic(err)
}
defer fd.Close()
scanner := bufio.NewScanner(fd)
var keyType string
var key string
var comment string
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
fd.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
// todo: input validation
// todo: auto-reload, signal
_, err := fmt.Sscanf(eachline, "%s %s %s", &keyType, &key, &comment)
if err != nil {
log.Fatal(err)
break
}
fmt.Printf("* ACL loaded: [%s %s %s]\n", keyType, key, comment)
p := newAllow(keyType, key, comment)
f.Append(p)
}
fmt.Printf("* AllowList Length: %v\n", f.length)
}
// setup: we need to pass Feed into handler function
feeds := &MyFeeds{f: f}
router := mux.NewRouter()
router.HandleFunc("/api/v1/create/{InstanceId}", feeds.HandleClusterCreate).Methods("POST")
router.HandleFunc("/api/v1/status/{InstanceId}", feeds.HandleClusterStatus).Methods("GET")
router.HandleFunc("/api/v1/kubeconfig/{InstanceId}", feeds.HandleClusterKubeConfig).Methods("GET")
router.HandleFunc("/api/v1/start/{InstanceId}", feeds.HandleClusterStart).Methods("GET")
router.HandleFunc("/api/v1/stop/{InstanceId}", feeds.HandleClusterStop).Methods("GET")
router.HandleFunc("/api/v1/destroy/{InstanceId}", feeds.HandleClusterDestroy).Methods("GET")
router.HandleFunc("/api/v1/cluster", feeds.HandleClusterCluster).Methods("GET")
router.HandleFunc("/api/v1/k8scluster", feeds.HandleK8sClusterCluster).Methods("GET")
// for test only
// router.HandleFunc("/api/v1/iac/{InstanceId}", feeds.HandleIac).Methods("POST")
// router.HandleFunc("/api/v1/iac/{InstanceId}", feeds.HandleIacRequestStatus).Methods("GET")
router.HandleFunc("/images", HandleClusterImages).Methods("GET")
router.HandleFunc("/flavors", HandleClusterFlavors).Methods("GET")
if len(onetime_Dir) > 1 {
if !fileExists(onetime_Dir) {
fmt.Printf("One-time directory not exist: %s\n", onetime_Dir)
os.Exit(1)
} else {
fmt.Printf("* One-time dir enabled: %s\n", onetime_Dir)
router.HandleFunc("/api/v1/otc/{CfgFile}", feeds.HandleOneTimeConf).Methods("GET")
}
} else {
fmt.Println("* One-time dir disabled")
}
fmt.Println("* Listen", *listen)
fmt.Println("* Server URL", server_url)
log.Fatal(http.ListenAndServe(*listen, router))
}
func validateCid(Cid string) bool {
var regexpCid = regexp.MustCompile("^[a-f0-9]{32}$")
if regexpCid.MatchString(Cid) {
return true
} else {
return false
}
}
func validateInstanceId(InstanceId string) bool {
var regexpInstanceId = regexp.MustCompile("^[a-z_]([a-z0-9_])*$")
if len(InstanceId) < 1 || len(InstanceId) > 40 {
return false
}
if regexpInstanceId.MatchString(InstanceId) {
return true
} else {
return false
}
}
func validateCfgFile(CfgFile string) bool {
var regexpCfgFile = regexp.MustCompile("^[aA0-zZ9_]([aA0-zZ9_])*$")
if len(CfgFile) < 1 || len(CfgFile) > 10 {
return false
}
if regexpCfgFile.MatchString(CfgFile) {
return true
} else {
return false
}
}
func isPubKeyAllowed(feeds *MyFeeds, PubKey string) bool {
//ALLOWED?
var p *AllowList
currentAllow := feeds.f.start
if !acl_enable {
return true
}
for i := 0; i < feeds.f.length; i++ {
p = currentAllow
currentAllow = currentAllow.next
ResultKeyType := (string(p.keyType))
ResultKey := (string(p.key))
ResultKeyComment := (string(p.comment))
//fmt.Println("ResultType: ", ResultKeyType)
KeyInList := fmt.Sprintf("%s %s %s", ResultKeyType, ResultKey, ResultKeyComment)
fmt.Printf("[%s][%s]\n", PubKey, KeyInList)
if len(PubKey) == len(KeyInList) {
if strings.Compare(PubKey, KeyInList) == 0 {
fmt.Printf("pubkey matched\n")
return true
}
}
}
return false
}
func isCidAllowed(feeds *MyFeeds, Cid string) bool {
//ALLOWED?
var p *AllowList
currentAllow := feeds.f.start
if !acl_enable {
return true
}
for i := 0; i < feeds.f.length; i++ {
p = currentAllow
currentAllow = currentAllow.next
CidInList := (string(p.cid))
if strings.Compare(Cid, CidInList) == 0 {
fmt.Printf("Cid ACL matched: %s\n", Cid)
return true
}
}
return false
}
func (feeds *MyFeeds) HandleClusterStatus(w http.ResponseWriter, r *http.Request) {
var InstanceId string
// enum { 0 - vm, 1 - k8s }
var vmType int
params := mux.Vars(r)
InstanceId = params["InstanceId"]
if !validateInstanceId(InstanceId) {
JSONError(w, "The InstanceId should be valid form: ^[a-z_]([a-z0-9_])*$ (maxlen: 40)", http.StatusMethodNotAllowed)
return
}
Cid := r.Header.Get("cid")
if !validateCid(Cid) {
JSONError(w, "The cid should be valid form: ^[a-f0-9]{32}$", http.StatusMethodNotAllowed)
return
}
if !isCidAllowed(feeds, Cid) {
fmt.Printf("CID not in ACL: %s\n", Cid)
JSONError(w, "not allowed", http.StatusMethodNotAllowed)
return
}
var mapfile string
checkMapfile := fmt.Sprintf("%s/var/db/api/map/%s-%s", workdir, Cid, InstanceId)
if _, err := os.Stat(checkMapfile); os.IsNotExist(err) {
fmt.Printf("status: no such %s/%s/vms - check K8S...\n", *dbDir, Cid)
// check K8S dir
checkMapfile = fmt.Sprintf("%s/var/db/k8s/map/%s-%s", workdir, Cid, InstanceId)
if _, err := os.Stat(checkMapfile); os.IsNotExist(err) {
JSONError(w, "not found", http.StatusOK)
return
} else {
fmt.Printf("%s found - its K8S\n", checkMapfile)
// K8S instance
vmType = 1
mapfile = checkMapfile
}
} else {
//VM/jail instance
fmt.Printf("%s/%s/vms found - its not K8S\n", *dbDir, Cid)
vmType = 0
mapfile = checkMapfile
}
b, err := ioutil.ReadFile(mapfile) // just pass the file name
if err != nil {
fmt.Printf("unable to read jname from: [%s]/var/db/api/map/%s-%s\n", mapfile)
JSONError(w, "not found", http.StatusOK)
return
}
var SqliteDBPath string
if ( vmType == 1 ) {
SqliteDBPath = fmt.Sprintf("%s/%s/%s-bhyve.ssh", *k8sDbDir, Cid, string(b))
} else {
SqliteDBPath = fmt.Sprintf("%s/%s/%s-bhyve.ssh", *dbDir, Cid, string(b))
}
if fileExists(SqliteDBPath) {
b, err := ioutil.ReadFile(SqliteDBPath) // just pass the file name
if err != nil {
JSONError(w, "", 400)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
}
}
func (feeds *MyFeeds) HandleK8sClusterStatus(w http.ResponseWriter, r *http.Request) {
var InstanceId string
params := mux.Vars(r)
InstanceId = params["InstanceId"]
if !validateInstanceId(InstanceId) {
JSONError(w, "The InstanceId should be valid form: ^[a-z_]([a-z0-9_])*$ (maxlen: 40)", http.StatusMethodNotAllowed)
return
}
Cid := r.Header.Get("cid")
if !validateCid(Cid) {
JSONError(w, "The cid should be valid form: ^[a-f0-9]{32}$", http.StatusMethodNotAllowed)
return
}
if !isCidAllowed(feeds, Cid) {
fmt.Printf("CID not in ACL: %s\n", Cid)
JSONError(w, "not allowed", http.StatusMethodNotAllowed)
return
}
HomePath := fmt.Sprintf("%s/%s/vms", *k8sDbDir, Cid)
if _, err := os.Stat(HomePath); os.IsNotExist(err) {
JSONError(w, "not found", http.StatusOK)
return
}
mapfile := fmt.Sprintf("%s/var/db/k8s/map/%s-%s", workdir, Cid, InstanceId)
if !fileExists(config.Recomendation) {
fmt.Printf("no such map file %s/var/db/k8s/map/%s-%s\n", workdir, Cid, InstanceId)
JSONError(w, "not found", http.StatusOK)
return
}
b, err := ioutil.ReadFile(mapfile) // just pass the file name
if err != nil {
fmt.Printf("unable to read jname from %s/var/db/k8s/map/%s-%s\n", workdir, Cid, InstanceId)
JSONError(w, "not found", http.StatusOK)
return
}
SqliteDBPath := fmt.Sprintf("%s/%s/%s-bhyve.ssh", *k8sDbDir, Cid, string(b))
if fileExists(SqliteDBPath) {
b, err := ioutil.ReadFile(SqliteDBPath) // just pass the file name
if err != nil {
JSONError(w, "", 400)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
}
}
func (feeds *MyFeeds) HandleClusterKubeConfig(w http.ResponseWriter, r *http.Request) {
var InstanceId string
params := mux.Vars(r)
InstanceId = params["InstanceId"]
if !validateInstanceId(InstanceId) {
JSONError(w, "The InstanceId should be valid form: ^[a-z_]([a-z0-9_])*$ (maxlen: 40)", http.StatusMethodNotAllowed)
return
}
Cid := r.Header.Get("cid")
if !validateCid(Cid) {
JSONError(w, "The cid should be valid form: ^[a-f0-9]{32}$", http.StatusMethodNotAllowed)
return
}
if !isCidAllowed(feeds, Cid) {
fmt.Printf("CID not in ACL: %s\n", Cid)
JSONError(w, "not allowed", http.StatusMethodNotAllowed)
return
}
VmPath := fmt.Sprintf("%s/%s/cluster-%s", *k8sDbDir, Cid, InstanceId)
if !fileExists(VmPath) {
fmt.Printf("ClusterKubeConfig: Error read vmpath file [%s]\n", VmPath)
JSONError(w, "", 400)
return
}
b, err := ioutil.ReadFile(VmPath) // just pass the file name
if err != nil {
fmt.Printf("Error read vmpath file [%s]\n", VmPath)
JSONError(w, "", 400)
return
} else {
kubeFile := fmt.Sprintf("%s/var/db/k8s/%s.kubeconfig", workdir, string(b))
if fileExists(kubeFile) {
b, err := ioutil.ReadFile(kubeFile) // just pass the file name
if err != nil {
fmt.Printf("unable to read content %s\n", kubeFile)
JSONError(w, "", http.StatusOK)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
} else {
fmt.Printf("Error read kubeconfig [%s]\n", kubeFile)
JSONError(w, "", 400)
return
}
}
}
func (feeds *MyFeeds) HandleClusterCluster(w http.ResponseWriter, r *http.Request) {
Cid := r.Header.Get("cid")
if !validateCid(Cid) {
JSONError(w, "The cid should be valid form: ^[a-f0-9]{32}$", http.StatusMethodNotAllowed)
return
}
if !isCidAllowed(feeds, Cid) {
fmt.Printf("CID not in ACL: %s\n", Cid)
JSONError(w, "not allowed", http.StatusMethodNotAllowed)
return
}
HomePath := fmt.Sprintf("%s/%s/vms", *dbDir, Cid)
//fmt.Println("CID IS: [ %s ]", cid)
if _, err := os.Stat(HomePath); os.IsNotExist(err) {
JSONError(w, "", http.StatusOK)
return
}
SqliteDBPath := fmt.Sprintf("%s/%s/vm.list", *dbDir, Cid)
if fileExists(SqliteDBPath) {
b, err := ioutil.ReadFile(SqliteDBPath) // just pass the file name
if err != nil {
JSONError(w, "", http.StatusOK)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
return
}
}
// read /var/db/cbsd-k8s/<cid>/vms/vm.list
func (feeds *MyFeeds) HandleK8sClusterCluster(w http.ResponseWriter, r *http.Request) {
Cid := r.Header.Get("cid")
if !validateCid(Cid) {
JSONError(w, "The cid should be valid form: ^[a-f0-9]{32}$", http.StatusMethodNotAllowed)
return
}
if !isCidAllowed(feeds, Cid) {
fmt.Printf("CID not in ACL: %s\n", Cid)
JSONError(w, "not allowed", http.StatusMethodNotAllowed)
return
}
HomePath := fmt.Sprintf("%s/%s/vms", *k8sDbDir, Cid)
//fmt.Println("CID IS: [ %s ]", cid)
if _, err := os.Stat(HomePath); os.IsNotExist(err) {
JSONError(w, "", http.StatusOK)
return
}
SqliteDBPath := fmt.Sprintf("%s/%s/vm.list", *k8sDbDir, Cid)
if fileExists(SqliteDBPath) {
b, err := ioutil.ReadFile(SqliteDBPath) // just pass the file name
if err != nil {
JSONError(w, "", http.StatusOK)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
return
}
}
func HandleClusterImages(w http.ResponseWriter, r *http.Request) {
if fileExists(config.Cloud_images_list) {
b, err := ioutil.ReadFile(config.Cloud_images_list) // just pass the file name
if err != nil {
JSONError(w, "", http.StatusOK)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
return
}
}
func HandleClusterFlavors(w http.ResponseWriter, r *http.Request) {
if fileExists(config.Flavors_list) {
b, err := ioutil.ReadFile(config.Flavors_list) // just pass the file name
if err != nil {
JSONError(w, "", http.StatusOK)
return
} else {
// already in json - send as-is
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(200)
http.Error(w, string(b), 200)
return
}
} else {
JSONError(w, "", http.StatusOK)
return
}
}
func realInstanceCreate(body string) {
a := &body
stdout, err := beanstalkSend(config.BeanstalkConfig, *a)
fmt.Printf("%s\n", stdout)
if err != nil {
return
}
}
func getStructTag(f reflect.StructField) string {
return string(f.Tag)
}
func getNodeRecomendation(body string, offer string) {
// offer - recomendation host from user, we can check them in external helper
// for valid/resource
var result string
if len(offer) > 1 {
result = offer
fmt.Printf("FORCED Host Recomendation: [%s]\n", result)
} else {
cmdStr := fmt.Sprintf("%s %s", config.Recomendation, body)
cmdArgs := strings.Fields(cmdStr)
cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("get recomendation script failed")
return
}
result = (string(out))
}
fmt.Printf("Host Recomendation: [%s]\n", result)
result = strings.Replace(result, ".", "_", -1)
result = strings.Replace(result, "-", "_", -1)
tube := fmt.Sprintf("cbsd_%s", result)
reply := fmt.Sprintf("cbsd_%s_result_id", result)
fmt.Printf("Tube selected: [%s]\n", tube)
fmt.Printf("ReplyTube selected: [%s]\n", reply)
config.BeanstalkConfig.Tube = tube
config.BeanstalkConfig.ReplyTubePrefix = reply
}
func applyIac(env string, yaml string) {
// offer - recomendation host from user, we can check them in external helper
// for valid/resource
var result string
cmdStr := fmt.Sprintf("/usr/local/bin/cbsd-mq-api-apply %s /var/spool/cbsd-mq-api/upload/%s", env, yaml)
cmdArgs := strings.Fields(cmdStr)
cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("cbsd-mq-api-apply failed", cmdStr)
return
}
result = (string(out))
fmt.Printf("IaC Apply: [%s]\n", result)
}
func getJname() string {
cmdStr := fmt.Sprintf("%s", config.Freejname)
cmdArgs := strings.Fields(cmdStr)
cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("get freejname script failed")
return ""
}
result := (string(out))
fmt.Printf("Freejname Recomendation: [%s]\n", result)
return result
}
func getId(cid string) string {
cmdStr := fmt.Sprintf("%s", config.Freeid)
cmdArgs := strings.Fields(cmdStr)
// cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
cmd := exec.Command(cmdArgs[0], cid)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("get freeid script failed")
return ""
}
result := (string(out))
fmt.Printf("Freeid Recomendation: [%s]\n", result)
return result
}
//func (feeds *MyFeeds) HandleClusterCluster(w http.ResponseWriter, r *http.Request) {
//func HandleClusterCreate(w http.ResponseWriter, r *http.Request) {
//func (feeds *MyFeeds)
//func HandleCreateVm(w http.ResponseWriter, r *http.Request ) {
func HandleCreateVm(w http.ResponseWriter, vm Vm) {
var regexpPkgList = regexp.MustCompile(`^[aA-zZ_]([aA-zZ0-9_\-/ ])*$`)
var regexpExtras = regexp.MustCompile("^[a-zA-Z0-9:,]*$")
var regexpSize = regexp.MustCompile(`^[1-9](([0-9]+)?)([m|g|t])$`)
var regexpParamName = regexp.MustCompile(`^[a-z_]+$`)
var regexpParamVal = regexp.MustCompile(`^[aA-zZ0-9_\-. ]+$`)
var regexpHostName = regexp.MustCompile(`^[aA-zZ0-9_\-\.]+$`)
var suggest string
var InstanceId string
InstanceId = vm.Jname
uid := []byte(vm.Pubkey)
//existance?
// check for existance
cid := md5.Sum(uid)
VmPathDir := fmt.Sprintf("%s/%x", *dbDir, cid)
if !fileExists(VmPathDir) {
os.Mkdir(VmPathDir, 0775)
}
VmPath := fmt.Sprintf("%s/%x/vm-%s", *dbDir, cid, InstanceId)
if fileExists(VmPath) {
fmt.Printf("Error: vm already exist: [%s]\n", VmPath)
JSONError(w, "vm already exist", http.StatusMethodNotAllowed)
return
}
fmt.Printf("vm file not exist, create empty: [%s]\n", VmPath)
// create empty file
f, err := os.Create(VmPath)
if err != nil {
log.Fatal(err)
}
if len(vm.PkgList) > 1 {
if !regexpPkgList.MatchString(vm.PkgList) {
fmt.Printf("Error: wrong pkglist: [%s]\n", vm.PkgList)
JSONError(w, "pkglist should be valid form. valid form", http.StatusMethodNotAllowed)
return
}
}
if len(vm.Host_hostname) > 1 {
if !regexpHostName.MatchString(vm.Host_hostname) {
fmt.Printf("Error: wrong hostname: [%s]\n", vm.Host_hostname)
JSONError(w, "host_hostname should be valid form. valid form", http.StatusMethodNotAllowed)
return
} else {
fmt.Printf("Found host_hostname: [%s]\n", vm.Host_hostname)
}
}
if len(vm.Extras) > 1 {
if !regexpExtras.MatchString(vm.Extras) {
fmt.Printf("Error: wrong extras: [%s]\n", vm.Extras)
JSONError(w, "extras should be valid form. valid form", http.StatusMethodNotAllowed)
return
} else {
fmt.Printf("Found extras: [%s]\n", vm.Extras)
}
}
if len(vm.Recomendation) > 1 {
if !regexpHostName.MatchString(vm.Recomendation) {
fmt.Printf("Error: wrong hostname recomendation: [%s]\n", vm.Recomendation)
JSONError(w, "recomendation should be valid form. valid form", http.StatusMethodNotAllowed)
return
} else {
fmt.Printf("Found vm recomendation: [%s]\n", vm.Recomendation)
suggest = vm.Recomendation
}
} else {
suggest = ""
}
if vm.Cpus <= 0 || vm.Cpus > 16 {
JSONError(w, "cpus valid range: 1-16", http.StatusMethodNotAllowed)
return
}
if len(vm.Ram) > 0 {
if !regexpSize.MatchString(vm.Ram) {
JSONError(w, "The ram should be valid form, 512m, 1g", http.StatusMethodNotAllowed)
return
}
} else {
// unlimited for jail
vm.Ram = "0"
}
switch vm.Image {
case "jail":
//Imgsize optional for jail type
if len(vm.Imgsize) > 0 {
if !regexpSize.MatchString(vm.Imgsize) {
fmt.Printf("wrong imgsize: [%s] [%d]\n", vm.Imgsize, vm.Imgsize)
JSONError(w, "The imgsize should be valid form: 2g, 30g", http.StatusMethodNotAllowed)
return
}
}
default:
if !regexpSize.MatchString(vm.Imgsize) {
fmt.Printf("wrong imgsize: [%s] [%d]\n", vm.Imgsize, vm.Imgsize)
JSONError(w, "The imgsize should be valid form: 2g, 30g", http.StatusMethodNotAllowed)
return
}
}
Jname := getJname()
if len(Jname) < 1 {
log.Fatal("unable to get jname")
return
}
fmt.Printf("GET NEXT FREE JNAME: [%s]\n", Jname)
_, err2 := f.WriteString(Jname)
if err2 != nil {
log.Fatal(err2)
}