/
main.go
126 lines (106 loc) · 2.61 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
/*
Copyright 2015 Patrick Moroney
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/csv"
"flag"
"io/ioutil"
"log"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/quipo/statsd"
)
func getStats() {
file, err := ioutil.TempFile("", "sar")
if err != nil {
log.Print(err)
return
}
defer func() {
err = os.Remove(file.Name())
if err != nil {
log.Print(err)
}
}()
err = exec.Command("sar", "1", "1", "-A", "-o", file.Name()).Run()
if err != nil {
log.Print(err)
return
}
cmd := exec.Command("sadf", "1", "1", "--", "-A", file.Name())
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Print(err)
return
}
if err := cmd.Start(); err != nil {
log.Print(err)
return
}
csv := csv.NewReader(stdout)
csv.Comma = ' '
records, err := csv.ReadAll()
if err != nil {
log.Print(err)
return
}
if err := cmd.Wait(); err != nil {
log.Print(err)
return
}
for _, record := range records {
_ = sendRecord(record)
}
}
func sendRecord(record []string) error {
value, err := strconv.ParseFloat(record[5], 64)
if err != nil {
// We aren't interested in non-numeric values
return err
}
metric := record[4]
if metric[:2] == "kb" {
// if metric is in kilobits, convert it into bits
metric = metric[2:]
value = value * 1024
} else if len(metric) > 3 && metric[2:4] == "kB" {
// if metric is in kilobytes, convert it into bits
metric = metric[:2] + "bit" + metric[4:]
value = value * 1024 * 8
}
if record[3] != "-" && record[3] != "all" {
// add device name to metric
metric = record[3] + "." + metric
}
metric = strings.Replace(metric, "%", "pct_", -1)
sd.FGauge(metric, value)
return nil
}
var statsdServer = flag.String("d", ":8125", "Destination statsd server address")
var statsdPrefix = flag.String("p", "sar", "Statsd prefix for metrics")
var interval = flag.Duration("i", 10*time.Second, "Interval to send metrics")
var sd = statsd.NewStatsdClient(*statsdServer, *statsdPrefix+".")
func main() {
flag.Parse()
err := sd.CreateSocket()
if err != nil {
log.Fatal(err)
}
c := time.Tick(*interval)
for _ = range c {
go getStats()
}
}