/
main.go
164 lines (147 loc) · 3.5 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/jpillora/backoff"
"github.com/jpillora/opts"
"github.com/miekg/dns"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
)
var VERSION = "0"
const MAX_QUEUED = 10e3
type config struct {
URL string `help:"InfluxDB URL"`
Database string `help:"InfluxDB database"`
Interval time.Duration `help:"Time between reports"`
Tags string `help:"InfluxDB tags in the form \"<tag>=<value>,<tag>=<value>\""`
DNS string `help:"DNS server (used to lookup URL)"`
}
func main() {
c := config{
URL: "http://localhost:8086",
Database: "test",
Interval: 5 * time.Minute,
}
opts.New(&c).Name("sysflux").Version(VERSION).Parse()
//validate config
u, err := url.Parse(c.URL)
if err != nil {
log.Fatal("Invalid URL")
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
log.Fatal("Invalid host and port")
}
if u.Path == "" {
u.Path = "/write"
}
v := url.Values{}
v.Set("db", c.Database)
u.RawQuery = v.Encode()
tags := ""
if c.Tags != "" {
tags = "," + c.Tags
}
//good to go
log.Printf("Using InfluxDB endpoint: %s", u)
success := false
lock := sync.Mutex{}
entries := []string{}
send := func() error {
body := strings.NewReader(strings.Join(entries, "\n"))
if c.DNS != "" {
//lookup host every POST
ips, err := lookup(host, c.DNS)
if err != nil {
return fmt.Errorf("Lookup failed: %s", err)
}
u.Host = ips[0] + ":" + port
}
resp, err := http.Post(u.String(), "application/x-www-form-urlencoded", body)
if err != nil {
return fmt.Errorf("HTTP POST failed: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
msg, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Response download failed: %s", err)
}
return fmt.Errorf("Response: %d => %s", resp.StatusCode, msg)
}
//show first success
if !success {
log.Printf("Success")
success = true
}
//clear once recieved!
entries = nil
return nil
}
report := func() {
t := time.Now().UnixNano()
if l, err := load.LoadAvg(); err == nil {
entries = append(entries, fmt.Sprintf("cpu_load_short%s value=%f %d", tags, l.Load1*100, t))
entries = append(entries, fmt.Sprintf("cpu_load_medium%s value=%f %d", tags, l.Load5*100, t))
entries = append(entries, fmt.Sprintf("cpu_load_long%s value=%f %d", tags, l.Load15*100, t))
}
if v, err := mem.VirtualMemory(); err == nil {
entries = append(entries, fmt.Sprintf("mem_usage%s value=%f %d", tags, v.UsedPercent, t))
}
if len(entries) > MAX_QUEUED {
entries = entries[len(entries)-MAX_QUEUED:]
}
}
//send loop
go func() {
b := backoff.Backoff{}
for {
wait := time.Second
lock.Lock()
if len(entries) > 0 {
if err := send(); err == nil {
b.Reset()
} else {
log.Println(err)
wait = b.Duration()
}
}
lock.Unlock()
time.Sleep(wait)
}
}()
//report loop
for {
lock.Lock()
report()
lock.Unlock()
time.Sleep(c.Interval)
}
}
var dnsClient = dns.Client{}
func lookup(domain, server string) ([]string, error) {
msg := dns.Msg{}
msg.SetQuestion(domain+".", dns.TypeA)
r, _, err := dnsClient.Exchange(&msg, server+":53")
if err != nil {
return nil, err
}
l := len(r.Answer)
if l == 0 {
return nil, fmt.Errorf("No answers")
}
ips := make([]string, l)
for i, answer := range r.Answer {
ans := answer.(*dns.A)
ips[i] = ans.A.String()
}
return ips, nil
}