-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2247 lines (2034 loc) · 79.9 KB
/
main.go
File metadata and controls
2247 lines (2034 loc) · 79.9 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
//go:generate goversioninfo -icon=icon.ico -64=true -manifest=goversioninfo.exe.manifest
//sets the binary properties and icon
// from go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"math"
"math/rand"
net1 "net"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"time"
//deal with windows services
"github.com/kardianos/service"
//sqllite
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
//stats
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
// "go/types"
"log"
"net/http"
"os/exec"
// "strconv"
//ntfs perms, registry
"github.com/hectane/go-acl"
_ "github.com/hectane/go-acl"
"golang.org/x/sys/windows"
_ "golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
"golang.org/x/sys/windows/svc"
)
//Version = version number
const Version = "1.0.0.1"
//DiskStats structure for diskstats return
type DiskStats struct {
//gorm.Model
ID uint `json:"ID"`
CreatedAt time.Time `json:"CreatedAt"`
Path string `json:"path"`
Fstype string `json:"fstype"`
Total uint64 `json:"total"`
Free uint64 `json:"free"`
Used uint64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
InodesTotal uint64 `json:"inodesTotal"`
InodesUsed uint64 `json:"inodesUsed"`
InodesFree uint64 `json:"inodesFree"`
InodesUsedPercent float64 `json:"inodesUsedPercent"`
}
// MemStats is for memory stats returns
type MemStats struct {
Total int64 `json:"total"`
Available int64 `json:"available"`
Used int64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
Free int64 `json:"free"`
Active int64 `json:"active"`
Inactive int64 `json:"inactive"`
Wired int64 `json:"wired"`
Laundry int `json:"laundry"`
Buffers int `json:"buffers"`
Cached int `json:"cached"`
Writeback int `json:"writeback"`
Dirty int `json:"dirty"`
Writebacktmp int `json:"writebacktmp"`
Shared int `json:"shared"`
Slab int `json:"slab"`
Sreclaimable int `json:"sreclaimable"`
Sunreclaim int `json:"sunreclaim"`
Pagetables int `json:"pagetables"`
Swapcached int `json:"swapcached"`
Commitlimit int `json:"commitlimit"`
Committedas int `json:"committedas"`
Hightotal int `json:"hightotal"`
Highfree int `json:"highfree"`
Lowtotal int `json:"lowtotal"`
Lowfree int `json:"lowfree"`
Swaptotal int `json:"swaptotal"`
Swapfree int `json:"swapfree"`
Mapped int `json:"mapped"`
Vmalloctotal int `json:"vmalloctotal"`
Vmallocused int `json:"vmallocused"`
Vmallocchunk int `json:"vmallocchunk"`
Hugepagestotal int `json:"hugepagestotal"`
Hugepagesfree int `json:"hugepagesfree"`
Hugepagesize int `json:"hugepagesize"`
}
// MemStats1 is for memory stats returns
type MemStats1 struct {
ID uint `json:"ID"`
CreatedAt time.Time `json:"CreatedAt"`
Total uint64 `json:"total"`
Available uint64 `json:"available"`
Used uint64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
Free uint64 `json:"free"`
Active uint64 `json:"active"`
Inactive uint64 `json:"inactive"`
}
//Diskio structure for Diskio return
type Diskio struct {
// gorm.Model
ID uint `json:"ID"`
CreatedAt time.Time `json:"CreatedAt"`
ReadCount uint64 `json:"readCount"`
MergedReadCount uint64 `json:"mergedReadCount"`
WriteCount uint64 `json:"writeCount"`
MergedWriteCount uint64 `json:"mergedWriteCount"`
ReadBytes uint64 `json:"readBytes"`
WriteBytes uint64 `json:"writeBytes"`
ReadTime uint64 `json:"readTime"`
WriteTime uint64 `json:"writeTime"`
IopsInProgress uint64 `json:"iopsInProgress"`
IoTime uint64 `json:"ioTime"`
WeightedIO uint64 `json:"weightedIO"`
Name string `json:"name"`
SerialNumber string `json:"serialNumber"`
Label string `json:"label"`
}
//CPUStats struct only has 1 field
type CPUStats struct {
ID uint `json:"ID"`
CreatedAt time.Time `json:"CreatedAt"`
Average int `json:"avg"`
}
//ServerStats puts some of it together
type ServerStats struct {
UsedPercentMem float64 `json:"usedPercentMem"`
UsedPercentDisk float64 `json:"usedPercentDisk"`
AverageCPU int `json:"avgCpu"`
IP string `json:"ip"`
ServerName string `json:"serverName"`
}
//ExportsJSON shows the current list of nfs exported disks, empty json object if none {}
type ExportsJSON struct {
Anonymousaccess bool `json:"anonymousaccess"`
Anonymousgid int64 `json:"anonymousgid"`
Anonymousuid int64 `json:"anonymousuid"`
Isonline bool `json:"isonline"`
Name string `json:"name"`
Path string `json:"path"`
}
//NetworkIoStats holds structure for networkiostats
type NetworkIoStats struct {
ID uint `json:"ID"`
CreatedAt time.Time `json:"CreatedAt"`
BytesRecv uint64 `json:"bytesRecv"`
BytesSent uint64 `json:"bytesSent"`
Dropin uint64 `json:"dropin"`
Dropout uint64 `json:"dropout"`
Errin uint64 `json:"errin"`
Errout uint64 `json:"errout"`
Fifoin uint64 `json:"fifoin"`
Fifoout uint64 `json:"fifoout"`
Name string `json:"name"`
PacketsRecv uint64 `json:"packetsRecv"`
PacketsSent uint64 `json:"packetsSent"`
}
//func Updatediskio_db() {
//
//}
//func Creatediskio_db() int {
// Migrate the schema
//db.AutoMigrate(&Diskio{})
//
//}
//from https://dev.to/moficodes/build-your-first-rest-api-with-go-2gcj
//collectStatsCPU 1 second cpu time sample
func collectStatsCPU(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//w.WriteHeader(http.StatusOK)
percent, err := cpu.Percent(1*time.Second, false)
if err != nil {
fmt.Printf("error getting cpu stats: error: %v", err)
}
var u CPUStats
u.Average = int(math.Round(percent[0]))
json.NewEncoder(w).Encode(u)
}
//collectStatsMEM returns memory usage
func collectStatsMEM(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
v, err := mem.VirtualMemory()
if err != nil {
fmt.Printf("error getting mem stats: error: %v", err)
}
json.NewEncoder(w).Encode(v)
}
//collectStatsDISK used when the url is /disk/X: note, it will only take capitolized disk letters
func collectStatsDISK(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
pathParams := mux.Vars(r)
driveltr := "null"
val := pathParams["driveletter"]
//fmt.Printf(" the drive letter passed to me was %v", val)
checkedvar, err := regexp.MatchString("^[a-zA-Z]:$", val)
if err != nil {
fmt.Printf("incorrect args passed as drive letter: %v", err)
}
if checkedvar == true {
driveltr = pathParams["driveletter"]
v, err := disk.Usage(driveltr)
if err != nil {
fmt.Printf("error getting disk stats, error: %v", err)
}
json.NewEncoder(w).Encode(v)
return
}
}
//Iocounts will return input/output for all drives. counters are bases on since disk showed up after boot, or mounting.(they could zeroize)
func Iocounts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
v, err := disk.IOCounters(":")
if err != nil {
//fmt.Printf("error is %v \n enabling disk stats interface with diskperf -y \n", err)
var cmdargs1 = "diskperf -y"
_, err := exec.Command("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", cmdargs1).Output()
if err != nil {
fmt.Printf("failed to enable diskstats, error is : %v \n", err)
}
}
json.NewEncoder(w).Encode(v)
}
//nCounters shows network traffic counters, since boot.
func nCounters(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
v, err := net.IOCounters(true)
if err != nil {
fmt.Printf("error with network stats collection is %v \n ", err)
}
json.NewEncoder(w).Encode(v)
}
//pshell test function, can be removed
func pshell() []byte {
// var cmdargs1 = "Get-WmiObject win32_volume | Select-Object SystemName, BlockSize, Capacity, FreeSpace, DriveLetter , @{Name=\"CapacityGB\";Expression={[math]::round($_.Capacity/1GB,2)}}, @{Name=\"FreeSpaceGB\";Expression={[math]::round($_.FreeSpace/1GB,2)}} , @{Name=\"FreeSpacePercent\";Expression={[math]::round(($_.FreeSpace/($_.Capacity*1.00))*100.00,2)}} , @{Name=\"Date\";Expression={$(Get-Date -f s)}}| Sort-Object Name | Convertto-JSON"
var cmdargs1 = "Get-WmiObject win32_volume | Select-Object Label, FileSystem, SystemVolume, BootVolume, SystemName, BlockSize, Capacity, FreeSpace, DriveLetter , @{Name=\"CapacityGB\";Expression={[math]::round($_.Capacity/1GB,2)}}, @{Name=\"FreeSpaceGB\";Expression={[math]::round($_.FreeSpace/1GB,2)}} , @{Name=\"FreeSpacePercent\";Expression={[math]::round(($_.FreeSpace/($_.Capacity*1.00))*100.00,2)}} , @{Name=\"Date\";Expression={$(Get-Date -f s)}}| Sort-Object Name | where-object \"DriveLetter\" -notlike \"\" | where-object DriveLetter -notlike \"C:\" | where-object BlockSize -notlike \"\" | where-object FileSystem -like \"NTFS\" | where-object Label -notlike \"System\" | Convertto-JSON"
out, err := exec.Command("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", cmdargs1).Output()
if err != nil {
// log.Print("error: %v \n" ,&err)
log.Writer()
}
//if no length, an error happened or, there were no drives discovered. handle it with blank object handed back to api.
sz := len(out)
if 0 == sz {
//a := []byte("{}")
//fmt.Println("NO drives found")
//return a
errmsg := fmt.Sprintln(`{"message": "No Drives Found"}`)
fmt.Printf("%v", errmsg)
return []byte(errmsg)
}
//else return the json output from the powershell
return out
}
//collectStatsHome prints a templated stats page in html, may not be used. just a test
func collectStatsHome(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>EDOS Status</title>
</head>
<body style="background-color: #212121;">
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
<div class="row fluid-img">
<br><br>
</div>
<!-- Optional JavaScript -->
<script>document.addEventListener('DOMContentLoaded', function () {
var myChart = Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});</script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
`)
}
//getexportsps is the powershell command to get the current nfs exports listing
func getexportsps() []byte {
// uses struct ExportsJson or ExportsJsonArray 2+ result is
exportarrayresulttestdata := []byte(`
[ {
"name": "powershell nfs missing",
"anonymousaccess": true,
"anonymousuid": 65534,
"anonymousgid": 65534,
"isonline": true,
"path": "D:\\"
},
{
"name": "Please install nfs",
"anonymousaccess": false,
"anonymousuid": -2,
"anonymousgid": -2,
"isonline": true,
"path": "H:\\"
}
]`)
// 1 export result is
exportnoarraytestdata := []byte(` {
"name": "test",
"anonymousaccess": true,
"anonymousuid": 65534,
"anonymousgid": 65534,
"isonline": true,
"path": "D:\\"
}`)
// no export result is literally null.
exportnoexportstestdata := []byte(``)
//here we run powershell to get the current nfs shares, this is mostly nice due to the ability to have it already json content.
var cmdargs1 = "Get-NfsShare |select name, anonymousaccess, anonymousuid, anonymousgid, isonline, path | Convertto-JSON"
//var cmdargs1 = "Get-WmiObject win32_volume| Convertto-JSON"
out, err := exec.Command("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", cmdargs1).Output()
if err != nil {
//maybe powershell fails, or nfs modules not installed. use this for test case static definitions here.
out1 := exportarrayresulttestdata
out2 := exportnoarraytestdata
out3 := exportnoexportstestdata
//which test case
out = out1
_ = out2
_ = out3
}
//check if the result contains an array bracket, if so we know its an array result, else not an array.
if bytes.Contains(out, []byte("[")) {
// fmt.Printf(" json array detected, using array struct\n")
var res []ExportsJSON
// fmt.Println("just a test +\n", "1")
json.Unmarshal(out, &res)
// fmt.Printf(" no loop match %+v", res)
for _, re := range res {
fmt.Printf("multiple exports found, name is %s \n", re.Name)
}
} else {
var res ExportsJSON
json.Unmarshal(out, &res)
fmt.Printf("single export found, name is %s\n", res.Name)
}
//if no length, an error happened or, there were no exports discovered. handle it with blank object handed back to api.
sz := len(out)
if 0 == sz {
a := []byte("{}")
fmt.Println("NO exports found")
return a
}
return out
}
func printSlice(s []byte) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
func importdrivepacksps() []byte {
var cmdargs1 = "/c1 /fall import j"
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
// log.Print("error: %v \n" ,&err)
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
log.Printf("error import foreign array. error: %v \n", errfixed)
errmsg := fmt.Sprintf(`{"message": "Error importing foreign array. error: %v \n"}`, errfixed)
fmt.Printf("%v", errmsg)
return []byte(errmsg)
}
return out
}
//MakeDrivesUnconfiguredGoodps is the powershell script to tell the raid controller to change the state to good. will error if already good, so returns are trivial and need inspection
func MakeDrivesUnconfiguredGoodps() []byte {
var cmdargs1 = "/c1 /e245 /sall set good j"
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
// log.Print("error: %v \n" ,&err)
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
fmt.Printf("error making drives unconfigured good. error: %v \n", errfixed)
errmsg := fmt.Sprintf(`{"message": "error making drives unconfigured good. error: %v \n"}`, errfixed)
return []byte(errmsg)
}
return out
}
//getraiddrivestatusps is the powershell script to get the status of all drives on the raid card.
func getraiddrivestatusps() []byte {
//just get the output of the drives, dont go into a logic rabbit hole to try to fix, let the user take actions off the data.
var cmdargs1 = "/c1 show j"
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
fmt.Printf("Error showing drive status, error: %v \n", errfixed)
errmsg := fmt.Sprintf(`{"message": "Error showing drive status, error: %v \n"}`, errfixed)
return []byte(errmsg)
}
return out
}
//GetUnitInfops is the powershell script to get all unit status (degraded, optimal etc)
func GetUnitInfops() []byte {
//gets unit info, only shows if the unit was imported
var cmdargs1 = "/c1 /vall show j"
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
fmt.Printf(`{"message": "error showing unit info, error: %v \n"}`, errfixed)
errmsg := fmt.Sprintf(`{"message": "error showing unit info, error: %v \n"}`, errfixed)
return []byte(errmsg)
}
log.Printf("GetUnitInfo returned: \n %s", out)
return out
}
//
func createraidAPI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
pathParams := mux.Vars(r)
ports := pathParams["ports"]
name := pathParams["name"]
fmt.Printf("ports is %v\n name is %v\n", ports, name)
m, err := regexp.MatchString("[0]\\-[3]|[4]\\-[7]|[8]\\-[1][1]", ports)
fmt.Printf("m is %v", m)
if err != nil || m != true {
errmsg := `{"message": "Drive numbers not recognized.only 0 - 3,4 - 7,8 - 11 are accepted."}`
fmt.Printf("%v", errmsg)
w.Write([]byte(errmsg))
return
}
var cmdargs1 = fmt.Sprintf("/c1 add vd type=r5 name=%v drives=245:%v SED direct j", name, ports)
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
log.Printf("error creating raid, error: %v \n", err)
//errstring := err.Error()
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
errmsg := string(fmt.Sprintf(`{"message": "Error creating raid, error: %v"}`, errfixed))
fmt.Printf("%v", errmsg)
w.Write([]byte(errmsg))
return
}
fmt.Printf(`{"message": "Createraid command output: %v"}`, string(out))
//json.NewEncoder(w).Encode(out) //not needed, output is already json
w.Write(out)
return
}
//rescandiskps is the powershell to rescan all disks on the raid controller.
func rescandisksps() []byte {
//rescans the disks
var cmdargs1 = "/c1 restart j"
out, err := exec.Command("C:\\Program Files (x86)\\MegaRAID Storage Manager\\storcli64.exe", cmdargs1).Output()
if err != nil {
// log.Print("error: %v \n" ,&err)
//log.Writer()
//log.Printf("error rescanning disks on /c1, error: %v \n", err)
errfixed := strings.ReplaceAll(err.Error(), `"`, `\"`)
errmsg := string(fmt.Sprintf(`{"message": "error rescanning disks on /c1, error: %v \n"}`, errfixed))
fmt.Printf("%v", errmsg)
return []byte(errmsg)
}
log.Printf("controller restart returned: \n %s", out)
return out
}
func get(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "get called"}`))
}
func status(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(pshell())
}
func getexports(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(getexportsps())
}
func importdrivepacks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(importdrivepacksps())
}
func getraiddrivestatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(getraiddrivestatusps())
}
//MakeDrivesUnconfiguredGood will try to change status to good on all drives attached. (in hopes of changing unconfigured bad to unconfigured good)
func MakeDrivesUnconfiguredGood(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(MakeDrivesUnconfiguredGoodps())
}
//GetUnitInfo will get the status of the current raids
func GetUnitInfo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(GetUnitInfops())
}
func rescandisks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(rescandisksps())
}
//func params(w http.ResponseWriter, r *http.Request) {
// pathParams := mux.Vars(r)
// w.Header().Set("Content-Type", "application/json")
//
// userID := -1
// var err error
// if val, ok := pathParams["userID"]; ok {
// userID, err = strconv.Atoi(val)
// if err != nil {
// w.WriteHeader(http.StatusInternalServerError)
// w.Write([]byte(`{"message": "need a number"}`))
// return
// }
// }
// commentID := -1
// if val, ok := pathParams["commentID"]; ok {
// commentID, err = strconv.Atoi(val)
// if err != nil {
// w.WriteHeader(http.StatusInternalServerError)
// w.Write([]byte(`{"message": "need a number"}`))
// return
// }
// }
// query := r.URL.Query()
// location := query.Get("location")
// w.Write([]byte(fmt.Sprintf(`{"userID": %d, "commentID": %d, "location": "%s" }`, userID, commentID, location)))
//}
//CollectDiskIoStatsInBackground will gather disk io stats per 10 seconds (or value called)
//store in the db, for around 500 iterations
func CollectDiskIoStatsInBackground(driveltr string) {
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
diskiodata, err := disk.IOCounters(driveltr)
if err != nil {
//fmt.Printf("error is %v \n enabling disk stats interface with diskperf -y \n", err)
var cmdargs1 = "diskperf -y"
_, err := exec.Command("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", cmdargs1).Output()
if err != nil {
fmt.Printf("failed to enable diskstats, error is : %v \n", err)
}
}
if diskiodata[driveltr].Name != "" {
//fmt.Printf("\nprinting io for drive %v: %v\n", driveltr, diskiodata[driveltr])
//fmt.Printf("readCount = \nPath: %v, \nmergedReadCount: %v, \nwriteCount: %v, \nmergedwriteCount: %v, \nreadBytes: %v, \nreadTime: %v, \nwriteTime: %v, \niopsInProgress: %v, \nioTime: %v, \nweightedIO: %v, \nname: %v, \nserialNumber: %v, \nlabel: %v\n", diskiodata.readCount, diskiodata.mergedReadCount, diskiodata.writeCount, diskiodata.mergedWriteCount, diskiodata.readBytes, diskiodata.writeBytes, diskiodata.readTime, diskiodata.writeTime, diskiodata.iopsInProgress, diskiodata.IoTime, diskiodata.weightedIO, diskiodata.name, diskiodata.serialNumber, diskiodata.label)
db.AutoMigrate(&Diskio{})
db.Create(&Diskio{ReadCount: diskiodata[driveltr].ReadCount,
MergedReadCount: diskiodata[driveltr].WriteCount,
WriteCount: diskiodata[driveltr].WriteCount,
MergedWriteCount: diskiodata[driveltr].MergedWriteCount,
ReadBytes: diskiodata[driveltr].ReadBytes,
WriteBytes: diskiodata[driveltr].WriteBytes,
ReadTime: diskiodata[driveltr].ReadTime,
WriteTime: diskiodata[driveltr].WriteTime,
IopsInProgress: diskiodata[driveltr].IopsInProgress,
IoTime: diskiodata[driveltr].IoTime,
WeightedIO: diskiodata[driveltr].WeightedIO,
Name: diskiodata[driveltr].Name,
SerialNumber: diskiodata[driveltr].SerialNumber,
Label: diskiodata[driveltr].Label})
}
}
//CollectNetworkIoStatsInBackground will store network stats in the sqllite db, every 5-10 seconds for 2 hours
func CollectNetworkIoStatsInBackground() {
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
db.AutoMigrate(&NetworkIoStats{})
nstats, err := net.IOCounters(true)
if err != nil {
fmt.Printf("error getting network stats, error: %v", err)
}
for _, v := range nstats {
if v.BytesRecv != 0 {
//fmt.Printf("name: %v\n", v.Name)
db.Create(&NetworkIoStats{
BytesRecv: v.BytesRecv,
BytesSent: v.BytesSent,
Dropin: v.Dropin,
Dropout: v.Dropout,
Errin: v.Errin,
Errout: v.Errout,
Fifoin: v.Fifoin,
Fifoout: v.Fifoout,
Name: v.Name,
PacketsRecv: v.PacketsRecv,
PacketsSent: v.PacketsSent})
}
//fmt.Printf("zero value on name: %v\n", v.Name)
}
}
//CollectcpustatsInBackground will store cpu stats in the sqllite db, every 5-10 seconds for 2 hours
func CollectcpustatsInBackground() {
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
db.AutoMigrate(&CPUStats{})
percent, err := cpu.Percent(1*time.Second, false)
if err != nil {
fmt.Printf("error getting cpu stats, error: %v", err)
}
var u CPUStats
u.Average = int(math.Round(percent[0]))
fmt.Printf("cpu is %d\n", u.Average)
db.Create(&CPUStats{
Average: u.Average})
//for _, v := range percent {
// db.Create(&CPUStats1{
// Average: v. })
// fmt.Printf("value on name: %v\n", v.Average)
//}
}
//CollectmemstatsInBackground will store cpu stats in the sqllite db, every 5-10 seconds for 2 hours
func CollectmemstatsInBackground() {
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
db.AutoMigrate(&MemStats1{})
//percent, err := cpu.Percent(1*time.Second, false)
if err != nil {
fmt.Printf("error getting Memory stats, error: %v", err)
}
//var u MemStats1
//u.Average = int(math.Round(percent[0]))
u, err := mem.VirtualMemory()
//u.UsedPercent = int(math.Round(u.UsedPercent))
fmt.Printf("Mem is %d\n", int(math.Round(u.UsedPercent)))
db.Create(&MemStats1{
Available: u.Available,
Used: u.Used,
UsedPercent: u.UsedPercent,
Free: u.Free,
Active: u.Active,
Inactive: u.Inactive})
//for _, v := range percent {
// db.Create(&CPUStats1{
// Average: v. })
// fmt.Printf("value on name: %v\n", v.Average)
//}
}
//getnetworkstatsfromdb will present json data to make a graph with
func getnetworkstatsfromdb(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
type Results struct {
Total string
}
var sqldata []NetworkIoStats
db.Table("network_io_stats").Select("*").Scan(&sqldata)
//db.Table("network_io_stats").Find(&sqldata)
emp := &sqldata
e, err := json.Marshal(emp)
w.Write([]byte(e))
}
//getdiskstatsfromdb will present json data to make a graph with
func getdiskstatsfromdb(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
type Results struct {
Total string
}
var sqldata []DiskStats
db.Table("disk_stats").Select("*").Scan(&sqldata)
//db.Table("network_io_stats").Find(&sqldata)
emp := &sqldata
e, err := json.Marshal(emp)
w.Write([]byte(e))
}
//getmemstatsfromdb will present json data to make a graph with
func getmemstatsfromdb(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
var sqldata []MemStats1
db.Table("mem_stats1").Select("*").Scan(&sqldata)
//db.Table("mem_stats").Find(&sqldata)
emp := &sqldata
e, err := json.Marshal(emp)
w.Write([]byte(e))
}
//getcpustatsfromdb will present json data to make a graph with
func getcpustatsfromdb(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
var sqldata []CPUStats
db.Table("cpu_stats").Select("*").Scan(&sqldata)
//db.Table("network_io_stats").Find(&sqldata)
emp := &sqldata
e, err := json.Marshal(emp)
w.Write([]byte(e))
}
//getdiskiostatsfromdb will present json data to make a graph with
func getdiskiotatsfromdb(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
type Results struct {
Total string
}
var sqldata []Diskio
db.Table("network_io_stats").Select("*").Scan(&sqldata)
//db.Table("network_io_stats").Find(&sqldata)
emp := &sqldata
e, err := json.Marshal(emp)
w.Write([]byte(e))
}
//CollectDiskstatsInBackground will collect the driveltr passed disk (partition) stats, and store in sqllite db under drive_stats table.
//intended to be called by a threaded function for each disk.
func CollectDiskstatsInBackground(driveltr string) uint {
//fmt.Print(driveltr)
//fmt.Print(keepduration)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
diskdata, err := disk.Usage(driveltr)
if err != nil {
fmt.Printf("error getting disk stats, error: %v", err)
}
db.AutoMigrate(&DiskStats{})
// Create
//fmt.Printf("Disk Stats = \nPath: %v, \nFstype: %v, \nTotal: %v, \nFree: %v, \nUsed: %v, \nUsedPercent: %v, \nInodesTotal: %v, \nInodesUsed: %v, \nInodesFree: %v, \nInodesUsedPercent: %v", diskdata.Path, diskdata.Fstype, diskdata.Total, diskdata.Free, diskdata.Used, diskdata.UsedPercent, diskdata.InodesTotal, diskdata.InodesUsed, diskdata.InodesFree, diskdata.InodesUsedPercent)
db.Create(&DiskStats{Path: diskdata.Path,
Fstype: diskdata.Fstype,
Total: diskdata.Total, Free: diskdata.Free,
Used: diskdata.Used,
UsedPercent: diskdata.UsedPercent,
InodesTotal: diskdata.InodesTotal,
InodesUsed: diskdata.InodesUsed,
InodesFree: diskdata.InodesFree,
InodesUsedPercent: diskdata.InodesUsedPercent})
//fmt.Printf("Path: %v, Fstype: %v, Total: %v, Free: %v, Used: %v, UsedPercent: %v, InodesTotal: %v, InodesUsed: %v, InodesFree: %v, InodesUsedPercent: %v", diskstats.Path, diskdata.Fstype, diskdata.Total, diskdata.Free, diskdata.Used, diskdata.UsedPercent, diskdata.InodesTotal, diskdata.InodesUsed, diskdata.InodesFree, diskdata.InodesUsedPercent)
var firstrecord DiskStats
var lastrecord DiskStats
type Results struct {
Total uint
}
var rowtotal Results
//db.LogMode(true)
db.First(&firstrecord, "Path = ?", driveltr).Where("Path = ?", driveltr)
db.Last(&lastrecord, "Path = ?", driveltr).Where("Path = ?", driveltr)
//get total rows for this disk in the db
db.Table("disk_stats").Select("count(id) as total").Where("Path = ?", driveltr).Scan(&rowtotal)
fmt.Printf("\ntotal row count for drive %v is %v\n", driveltr, rowtotal.Total)
//now take that, and delete all records with that path, older then the keepduration. limiting the storage used.
if rowtotal.Total > 100 {
dl := db.Unscoped().Delete(&DiskStats{}, "Path = ? AND created_at < datetime('now', '-30 days')", driveltr)
fmt.Printf("deleted old disk_stats rows = %v\n", dl.RowsAffected)
}
return firstrecord.ID
}
//PurgeDbRecordsDiskios will delete data from the sqllite db
func PurgeDbRecordsDiskios(duration string) {
//fmt.Printf("table: %v, duration: %v, direction: %v\n", table, duration, direction)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
//just use raw sql, the library hates me
//db.LogMode(true)
result := db.Exec("DELETE from diskios where created_at < datetime('now', ?);", duration)
fmt.Printf("deleted old diskios rows = %v\n", result.RowsAffected)
}
//PurgeDbRecordsCPU will delete data from the sqllite db
func PurgeDbRecordsCPU(duration string) {
//fmt.Printf("table: %v, duration: %v, direction: %v\n", table, duration, direction)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
//just use raw sql, the library hates me
//db.LogMode(true)
result := db.Exec("DELETE from cpu_stats where created_at < datetime('now', ?);", duration)
fmt.Printf("deleted old CPU stats rows = %v\n", result.RowsAffected)
}
//PurgeDbRecordsMEM will delete data from the sqllite db
func PurgeDbRecordsMEM(duration string) {
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
result := db.Exec("DELETE from mem_stats1 where created_at < datetime('now', ?);", duration)
fmt.Printf("deleted old mem_stats rows = %v\n", result.RowsAffected)
}
//PurgeDbRecordsNetworkIoStats will delete data from the sqllite db
func PurgeDbRecordsNetworkIoStats(duration string) {
//fmt.Printf("table: %v, duration: %v, direction: %v\n", table, duration, direction)
db, err := gorm.Open("sqlite3", `C:\ProgramData\edosAPI\edosapi.db`)
if err != nil {
// panic("failed to connect database")
fmt.Printf("failed to attach to database %v \n", `C:\ProgramData\edosAPI\edosapi.db`)
}
defer db.Close()
//just use raw sql, the library hates me
//db.LogMode(true)
result := db.Exec("DELETE from network_io_stats where created_at < datetime('now', ?);", duration)
fmt.Printf("deleted old network stats rows = %v\n", result.RowsAffected)
}
func getalldrives() []string {
var drives []string
partitions, _ := disk.Partitions(false)
for _, partition := range partitions {
// fmt.Println(partition.Mountpoint)
drives = append(drives, partition.Mountpoint)
}
return drives
}
//initializedisk will try to put a partition table on a disk, returning exit code on, 0 for success, 1 for fail
func initializedisk(w http.ResponseWriter, r *http.Request) {