-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·96 lines (76 loc) · 2.15 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
package main
import (
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"main.go/extractor"
)
func init() {
fmt.Print("listening to server...")
}
func main() {
// createFile()
//TODO: exporting metrics to prometheus
cpuUsage := prometheus.NewGaugeFunc(prometheus.GaugeOpts{
Namespace: "",
Subsystem: "",
Name: "cpu_percent",
Help: "CPU percentage",
ConstLabels: map[string]string{},
}, func() float64 {
return extractor.Extractor()
})
prometheus.MustRegister(cpuUsage)
http.Handle("/", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
func createFile() {
usr, err := os.UserHomeDir()
if err != nil {
fmt.Print(err)
}
filePath := filepath.Join(usr, "Desktop")
// createfile, err := os.OpenFile(filepath.Join(filePath, "output.txt"), os.O_RDWR|os.O_CREATE, 0644)
absPath := filepath.Join(filePath, "output.txt")
createfile, err := os.Create(absPath)
if err != nil {
fmt.Print(err)
}
fmt.Print(createfile)
populater(usr, filePath, absPath)
}
// do we really need this?
// populates output.txt file with metrics from top utility
// this function extracts pid,cpu metrics but it can track other metrics as well, to see options available try `top --help`
func populater(usr, filePath, absPath string) {
getrawstats := exec.Command("top", "-l1", "-n10", "-stats", "pid,cpu")
output, err := getrawstats.CombinedOutput()
if err != nil {
fmt.Print(err)
}
// fmt.Print(string(output))
rawpopulate := os.WriteFile(absPath, output, 0755)
if err != nil {
fmt.Print(err)
}
fmt.Print(rawpopulate)
//you can comment below function if you want to keep the summary information generated by top command at every call
skimetrics(absPath)
}
// this function deletes the summary information generated by top command
func skimetrics(absPath string) {
skimmedstats := exec.Command("sed", "1,10d", absPath)
finaloutput, err := skimmedstats.CombinedOutput()
if err != nil {
fmt.Print(err)
}
finalpopulate := os.WriteFile(absPath, finaloutput, 0755)
if err != nil {
fmt.Print(err)
}
fmt.Print(finalpopulate)
}