forked from jpillora/csv-to-influxdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
264 lines (239 loc) · 6.88 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/influxdata/influxdb/client/v2"
"github.com/jpillora/backoff"
"github.com/jpillora/opts"
)
var VERSION = "0.0.0-src"
type config struct {
CSVFile string `type:"arg" help:"<csv-file> must be a path a to valid CSV file with an initial header row"`
Server string `help:"Server address"`
Database string `help:"Database name"`
Username string `help:"User name"`
Password string `help:"Password"`
Measurement string `help:"Measurement name"`
BatchSize int `help:"Batch insert size"`
TagColumns string `help:"Comma-separated list of columns to use as tags instead of fields"`
TimestampColumn string `short:"ts" help:"Header name of the column to use as the timestamp"`
TimestampFormat string `short:"tf" help:"Timestamp format used to parse all timestamp records"`
NoAutoCreate bool `help:"Disable automatic creation of database"`
ForceFloat bool `help:"Force all numeric values to insert as float"`
ForceString bool `help:"Force all numeric values to insert as string"`
Attempts int `help:"Maximum number of attempts to send data to influxdb before failing"`
HttpTimeout int `help:"Timeout (in seconds) for http writes used by underlying influxdb client"`
}
func main() {
//configuration defaults
conf := config{
Server: "http://localhost:8086",
Database: "test",
Username: "",
Password: "",
Measurement: "data",
BatchSize: 5000,
ForceFloat: false,
ForceString: false,
TimestampColumn: "timestamp",
TimestampFormat: "2006-01-02 15:04:05",
HttpTimeout: 10,
}
//parse config
opts.New(&conf).
Name("csv-to-influxdb").
Repo("github.com/jpillora/csv-to-influxdb").
Version(VERSION).
Parse()
//set tag names
tagNames := map[string]bool{}
for _, name := range strings.Split(conf.TagColumns, ",") {
name = strings.TrimSpace(name)
if name != "" {
tagNames[name] = true
}
}
//regular expressions
numbersRe := regexp.MustCompile(`\d`)
integerRe := regexp.MustCompile(`^\d+$`)
floatRe := regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$`)
trueRe := regexp.MustCompile(`^(true|T|True|TRUE)$`)
falseRe := regexp.MustCompile(`^(false|F|False|FALSE)$`)
timestampRe, err := regexp.Compile("^" + numbersRe.ReplaceAllString(conf.TimestampFormat, `\d`) + "$")
if err != nil {
log.Fatalf("time stamp regexp creation failed")
}
//influxdb client
//u, err := url.Parse(conf.Server)
//if err != nil {
// log.Fatalf("Invalid server address: %s", err)
//}
c, err := client.NewHTTPClient(client.HTTPConfig{Addr: conf.Server, Username: conf.Username, Password: conf.Password, Timeout: time.Duration(conf.HttpTimeout) * time.Second})
defer c.Close()
dbsResp, err := c.Query(client.Query{Command: "SHOW DATABASES"})
if err != nil {
log.Fatalf("Invalid server address: %s", err)
}
dbExists := false
if len(dbsResp.Results) == 0 {
log.Fatalf("No databases found, probably an authentication issue, please provide username and password.")
}
for _, v := range dbsResp.Results[0].Series[0].Values {
dbName := v[0].(string)
if conf.Database == dbName {
dbExists = true
break
}
}
if !dbExists {
if conf.NoAutoCreate {
log.Fatalf("Database '%s' does not exist", conf.Database)
}
_, err := c.Query(client.Query{Command: "CREATE DATABASE \"" + conf.Database + "\""})
if err != nil {
log.Fatalf("Failed to create database: %s", err)
}
}
//open csv file
f, err := os.Open(conf.CSVFile)
if err != nil {
log.Fatalf("Failed to open %s", conf.CSVFile)
}
//headers and init fn
var firstField string
var headers []string
setHeaders := func(hdrs []string) {
//check timestamp and tag columns
hasTs := false
n := len(tagNames)
for _, h := range hdrs {
if h == conf.TimestampColumn {
hasTs = true
} else if tagNames[h] {
log.Println(h)
n--
} else if firstField == "" {
firstField = h
}
}
if firstField == "" {
log.Fatalf("You must have at least one field (non-tag)")
}
if !hasTs {
log.Fatalf("Timestamp column (%s) does not match any header (%s)", conf.TimestampColumn, strings.Join(headers, ","))
}
if n > 0 {
log.Fatalf("Tag names (%s) to do not all have matching headers (%s)", conf.TagColumns, strings.Join(headers, ","))
}
headers = hdrs
}
var bpConfig = client.BatchPointsConfig{Database: conf.Database}
bp, _ := client.NewBatchPoints(bpConfig) //current batch
bpSize := 0
totalSize := 0
// lastCount := ""
//write the current batch
write := func() {
if bpSize == 0 {
return
}
b := backoff.Backoff{}
for {
if err := c.Write(bp); err != nil {
d := b.Duration()
log.Printf("Write failed: %s (retrying in %s)", err, d)
if int(b.Attempt()) == conf.Attempts {
log.Fatalf("Failed to write to db after %d attempts", int(b.Attempt()))
}
time.Sleep(d)
continue
}
break
}
//TODO(jpillora): wait until the new points become readable
// count := ""
// for count == lastCount {
// resp, err := c.Query(client.Query{Command: "SELECT count(" + firstField + ") FROM " + conf.Measurement, Database: conf.Database})
// if err != nil {
// log.Fatal("failed to count rows")
// }
// count = resp.Results[0].Series[0].Values[0][1].(string)
// }
//reset
bp, _ = client.NewBatchPoints(bpConfig)
bpSize = 0
}
//read csv, line by line
r := csv.NewReader(f)
for i := 0; ; i++ {
records, err := r.Read()
if err != nil {
if err == io.EOF {
break
}
log.Fatalf("CSV error: %s", err)
}
if i == 0 {
setHeaders(records)
continue
}
// Create a point and add to batch
tags := map[string]string{}
fields := map[string]interface{}{}
var ts time.Time
//move all into tags and fields
for hi, h := range headers {
r := records[hi]
if len(r) == 0 {
continue
}
//tags are just strings
if tagNames[h] {
tags[h] = r
continue
}
//fields require string parsing
if timestampRe.MatchString(r) {
t, err := time.Parse(conf.TimestampFormat, r)
if err != nil {
fmt.Printf("#%d: %s: Invalid time: %s\n", i, h, err)
continue
}
if conf.TimestampColumn == h {
ts = t //the timestamp column!
continue
}
fields[h] = t
} else if !conf.ForceFloat && !conf.ForceString && integerRe.MatchString(r) {
i, _ := strconv.Atoi(r)
fields[h] = i
} else if !conf.ForceString && floatRe.MatchString(r) {
f, _ := strconv.ParseFloat(r, 64)
fields[h] = f
} else if trueRe.MatchString(r) {
fields[h] = true
} else if falseRe.MatchString(r) {
fields[h] = false
} else {
fields[h] = r
}
}
p, err := client.NewPoint(conf.Measurement, tags, fields, ts)
bp.AddPoint(p)
bpSize++
totalSize++
if bpSize == conf.BatchSize {
write()
}
}
//send remainder
write()
log.Printf("Done (wrote %d points)", totalSize)
}