-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
94 lines (76 loc) · 2.24 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
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
var (
collectdURL string
fileLocation string
pollInterval int
removeTimestamp bool
)
flag.StringVar(&collectdURL, "collectd-url", "", "collectd URL *required")
flag.StringVar(&fileLocation, "file-location", "", "location of file to write in *required")
flag.IntVar(&pollInterval, "poll-interval", 15, "poll interval")
flag.BoolVar(&removeTimestamp, "remove-timestamp", true, "remove last column with timestamp")
flag.Parse()
if collectdURL == "" {
log.Fatalln("collectd-url is required param")
}
if fileLocation == "" {
log.Fatalln("file-location is required param")
}
for {
data, err := getPrometheusData(collectdURL)
if err != nil {
log.Println("could not get data from collectd: ", err.Error())
}
if len(data) > 0 {
if removeTimestamp {
data = removeTimestampFromData(data)
}
err = writeToFile(fileLocation, data)
if err != nil {
log.Println("could not write data to file: ", err.Error())
}
}
time.Sleep(time.Duration(pollInterval) * time.Second)
}
}
//getPrometheusData retrieves prometheus data from server
func getPrometheusData(collectdURL string) ([]byte, error) {
r, err := http.Get(collectdURL)
if err != nil {
return nil, err
}
defer r.Body.Close()
return ioutil.ReadAll(r.Body)
}
//removeTimestampFromData deletes timestamp from each line
func removeTimestampFromData(data []byte) []byte {
lines := strings.Split(string(data), "\n")
updatedLines := make([]string, len(lines))
for i, line := range lines {
//if line is empty or starts with # skip it
if line == "" || string(line[0]) == "#" {
updatedLines[i] = line
continue
}
updatedLines[i] = strings.TrimSuffix(line, line[strings.LastIndex(line, " "):])
}
return []byte(strings.Join(updatedLines, "\n"))
}
//writeToFile checks if file path exists and writes data to file
func writeToFile(fileLocation string, prometheusData []byte) error {
pathToFile := strings.TrimSuffix(fileLocation, fileLocation[strings.LastIndex(fileLocation, "/"):])
if _, err := os.Stat(pathToFile); os.IsNotExist(err) {
log.Fatalln("file location is not accessible")
}
return ioutil.WriteFile(fileLocation, prometheusData, 0644)
}