forked from shirou/mqforward
/
influxdb.go
182 lines (155 loc) · 3.34 KB
/
influxdb.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package main
import (
"fmt"
"strings"
"time"
log "github.com/Sirupsen/logrus"
client "github.com/influxdata/influxdb/client/v2"
"github.com/oleiade/lane"
)
const (
DefaultTick = 1
)
type InfluxDBConf struct {
Hostname string
Port int
Db string
UserName string
Password string
Tick int
UDP bool
Debug string
}
type InfluxDBClient struct {
Client client.Client
Config InfluxDBConf
Status string
Tick int
Buffer *lane.Deque
ifChan chan Message
commandChan chan string
}
func NewInfluxDBClient(conf InfluxDBConf, ifChan chan Message, commandChan chan string) (*InfluxDBClient, error) {
host := fmt.Sprintf("http://%s:%d", conf.Hostname, conf.Port)
log.Infof("influxdb host: %s", host)
ifConf := client.HTTPConfig{
Addr: host,
Username: conf.UserName,
Password: conf.Password,
}
con, err := client.NewHTTPClient(ifConf)
if err != nil {
return nil, err
}
log.Infof("influxdb connected.")
tick := conf.Tick
if tick == 0 {
tick = DefaultTick
}
ifc := InfluxDBClient{
Client: con,
Tick: tick,
Status: StatusStopped,
Config: conf,
// prepare 2times by MaxBufferSize for Buffer itself
Buffer: lane.NewCappedDeque(MaxBufferSize * 2),
ifChan: ifChan,
commandChan: commandChan,
}
return &ifc, nil
}
func (ifc *InfluxDBClient) Send() error {
if ifc.Buffer.Size() == 0 {
return nil
}
log.Debugf("send to influxdb: size=%d", ifc.Buffer.Size())
var err error
buf := make([]Message, MaxBufferSize)
for i := 0; i < MaxBufferSize; i++ {
msg := ifc.Buffer.Shift()
if msg == nil {
break
}
m, ok := msg.(Message)
if !ok {
log.Warn("could not cast to message")
break
}
if m.Topic == "" && len(m.Payload) == 0 {
break
}
buf[i] = m
}
bp := Msg2Series(buf, ifc.Config.Db)
err = ifc.Client.Write(bp)
if err != nil {
return err
}
return nil
}
// Stop stops sending data, after all data sent.
func (ifc *InfluxDBClient) Stop() {
ifc.Status = StatusStopped
}
// Start start sending
func (ifc *InfluxDBClient) Start() error {
ifc.Status = StatusStarted
duration := time.Duration(ifc.Tick)
ticker := time.NewTicker(duration * time.Second)
for {
select {
case <-ticker.C:
if ifc.Status == StatusStopped {
log.Info("stopped by Status")
return fmt.Errorf("stopped by Status")
}
err := ifc.Send()
if err != nil {
log.Errorf("influxdb write err: %s", err)
}
case msg := <-ifc.ifChan:
log.Debugf("add: %s", msg.Topic)
ifc.Buffer.Append(msg)
case msg := <-ifc.commandChan:
switch msg {
case "stop":
ticker.Stop()
ifc.Status = StatusStopped
}
}
}
return nil
}
func Msg2Series(msgs []Message, database string) client.BatchPoints {
// Create a new point batch
bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
Database: database,
Precision: "s",
})
for _, msg := range msgs {
if msg.Topic == "" && len(msg.Payload) == 0 {
break
}
tokens := strings.Split(msg.Topic, "/")
if len(tokens) < 2 {
break
}
j, err := MsgParse(msg.Payload)
if err != nil {
log.Warn(err)
continue
}
//name := strings.Replace(msg.Topic, "/", ".", -1)
name := strings.Join(tokens[1:], "_")
tags := map[string]string{
"device": tokens[0],
}
pt, err := client.NewPoint(name, tags, j, time.Now())
if err != nil {
break
}
bp.AddPoint(pt)
fmt.Printf("%+v\n", pt)
}
return bp
}