-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphite.go
112 lines (94 loc) · 2.21 KB
/
graphite.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
package graphite
import (
"bytes"
"fmt"
"net"
"time"
)
// Mertic defines a graphite metric of name, value and timestamp
type Metric struct {
Name string
Value string
Timestamp int64
}
// Client defines a graphite client
type Client struct {
Host string
Port int
Protocol string
Timeout time.Duration
Connection net.Conn
}
const defaultTimeout = 5
// Connect is used to connect to graphite server
func (client *Client) Connect() error {
if client.Connection != nil {
client.Connection.Close()
}
var err error
address := fmt.Sprintf("%s:%d", client.Host, client.Port)
if client.Timeout == 0 {
client.Timeout = defaultTimeout * time.Second
}
if client.Protocol == "udp" {
udpAddr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return err
}
client.Connection, err = net.DialUDP(client.Protocol, nil, udpAddr)
} else {
client.Connection, err = net.DialTimeout(client.Protocol, address, client.Timeout)
}
if err != nil {
return err
}
return nil
}
// Disconnect is used to disconnect to graphite server
func (client *Client) Disconnect() error {
err := client.Connection.Close()
client.Connection = nil
return err
}
func (client *Client) sendMetrics(metrics []Metric) error {
empty_metric := Metric{}
buf := bytes.NewBufferString("")
for _, metric := range metrics {
if metric == empty_metric {
continue
}
if metric.Timestamp == 0 {
metric.Timestamp = time.Now().Unix()
}
if client.Protocol == "udp" {
fmt.Fprintf(client.Connection, "%s %s %d\n", metric.Name, metric.Value, metric.Timestamp)
continue
}
buf.WriteString(fmt.Sprintf("%s %s %d\n", metric.Name, metric.Value, metric.Timestamp))
}
if client.Protocol == "tcp" {
_, err := client.Connection.Write(buf.Bytes())
if err != nil {
return err
}
}
return nil
}
func (client *Client) SendMetric(metric Metric) error {
metrics := make([]Metric, 1)
metrics[0] = metric
return client.sendMetrics(metrics)
}
func (client *Client) Send(stat string, value string) error {
metrics := make([]Metric, 1)
metrics[0] = Metric{
Name: stat,
Value: value,
Timestamp: time.Now().Unix(),
}
err := client.sendMetrics(metrics)
if err != nil {
return err
}
return nil
}