-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathcsv.go
More file actions
244 lines (213 loc) · 5.92 KB
/
csv.go
File metadata and controls
244 lines (213 loc) · 5.92 KB
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
package csv
import (
"bytes"
"encoding/csv"
"fmt"
"runtime"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/serializers"
)
type Serializer struct {
TimestampFormat string `toml:"csv_timestamp_format"`
Separator string `toml:"csv_separator"`
Header bool `toml:"csv_header"`
Prefix bool `toml:"csv_column_prefix"`
Columns []string `toml:"csv_columns"`
buffer bytes.Buffer
writer *csv.Writer
}
func (s *Serializer) Init() error {
// Setting defaults
if s.Separator == "" {
s.Separator = ","
}
// Check inputs
if len(s.Separator) > 1 {
return fmt.Errorf("invalid separator %q", s.Separator)
}
switch s.TimestampFormat {
case "":
s.TimestampFormat = "unix"
case "unix", "unix_ms", "unix_us", "unix_ns":
default:
if time.Now().Format(s.TimestampFormat) == s.TimestampFormat {
return fmt.Errorf("invalid timestamp format %q", s.TimestampFormat)
}
}
// Check columns if any
for _, name := range s.Columns {
switch {
case name == "timestamp", name == "name",
strings.HasPrefix(name, "tag."),
strings.HasPrefix(name, "field."):
default:
return fmt.Errorf("invalid column reference %q", name)
}
}
// Initialize the writer
s.writer = csv.NewWriter(&s.buffer)
s.writer.Comma, _ = utf8.DecodeRuneInString(s.Separator)
s.writer.UseCRLF = runtime.GOOS == "windows"
return nil
}
func (s *Serializer) Serialize(metric telegraf.Metric) ([]byte, error) {
return s.SerializeBatch([]telegraf.Metric{metric})
}
func (s *Serializer) SerializeBatch(metrics []telegraf.Metric) ([]byte, error) {
if len(metrics) < 1 {
return nil, nil
}
// Clear the buffer
s.buffer.Truncate(0)
// Write the header if the user wants us to
if s.Header {
if len(s.Columns) > 0 {
if err := s.writeHeaderOrdered(); err != nil {
return nil, fmt.Errorf("writing header failed: %w", err)
}
} else {
if err := s.writeHeader(metrics[0]); err != nil {
return nil, fmt.Errorf("writing header failed: %w", err)
}
}
s.Header = false
}
for _, m := range metrics {
if len(s.Columns) > 0 {
if err := s.writeDataOrdered(m); err != nil {
return nil, fmt.Errorf("writing data failed: %w", err)
}
} else {
if err := s.writeData(m); err != nil {
return nil, fmt.Errorf("writing data failed: %w", err)
}
}
}
// Finish up
s.writer.Flush()
return s.buffer.Bytes(), nil
}
func (s *Serializer) writeHeader(metric telegraf.Metric) error {
columns := []string{
"timestamp",
"measurement",
}
for _, tag := range metric.TagList() {
if s.Prefix {
columns = append(columns, "tag_"+tag.Key)
} else {
columns = append(columns, tag.Key)
}
}
// Sort the fields by name
sort.Slice(metric.FieldList(), func(i, j int) bool {
return metric.FieldList()[i].Key < metric.FieldList()[j].Key
})
for _, field := range metric.FieldList() {
if s.Prefix {
columns = append(columns, "field_"+field.Key)
} else {
columns = append(columns, field.Key)
}
}
return s.writer.Write(columns)
}
func (s *Serializer) writeHeaderOrdered() error {
columns := make([]string, 0, len(s.Columns))
for _, name := range s.Columns {
if s.Prefix {
name = strings.ReplaceAll(name, ".", "_")
} else {
name = strings.TrimPrefix(name, "tag.")
name = strings.TrimPrefix(name, "field.")
}
columns = append(columns, name)
}
return s.writer.Write(columns)
}
func (s *Serializer) writeData(metric telegraf.Metric) error {
var timestamp string
// Format the time
switch s.TimestampFormat {
case "unix":
timestamp = strconv.FormatInt(metric.Time().Unix(), 10)
case "unix_ms":
timestamp = strconv.FormatInt(metric.Time().UnixNano()/1_000_000, 10)
case "unix_us":
timestamp = strconv.FormatInt(metric.Time().UnixNano()/1_000, 10)
case "unix_ns":
timestamp = strconv.FormatInt(metric.Time().UnixNano(), 10)
default:
timestamp = metric.Time().UTC().Format(s.TimestampFormat)
}
columns := make([]string, 0, len(metric.TagList())+len(metric.FieldList())+2)
columns = append(columns, timestamp, metric.Name())
for _, tag := range metric.TagList() {
columns = append(columns, tag.Value)
}
// Sort the fields by name
sort.Slice(metric.FieldList(), func(i, j int) bool {
return metric.FieldList()[i].Key < metric.FieldList()[j].Key
})
for _, field := range metric.FieldList() {
v, err := internal.ToString(field.Value)
if err != nil {
return fmt.Errorf("converting field %q to string failed: %w", field.Key, err)
}
columns = append(columns, v)
}
return s.writer.Write(columns)
}
func (s *Serializer) writeDataOrdered(metric telegraf.Metric) error {
var timestamp string
// Format the time
switch s.TimestampFormat {
case "unix":
timestamp = strconv.FormatInt(metric.Time().Unix(), 10)
case "unix_ms":
timestamp = strconv.FormatInt(metric.Time().UnixNano()/1_000_000, 10)
case "unix_us":
timestamp = strconv.FormatInt(metric.Time().UnixNano()/1_000, 10)
case "unix_ns":
timestamp = strconv.FormatInt(metric.Time().UnixNano(), 10)
default:
timestamp = metric.Time().UTC().Format(s.TimestampFormat)
}
columns := make([]string, 0, len(s.Columns))
for _, name := range s.Columns {
switch {
case name == "timestamp":
columns = append(columns, timestamp)
case name == "name":
columns = append(columns, metric.Name())
case strings.HasPrefix(name, "tag."):
v, _ := metric.GetTag(strings.TrimPrefix(name, "tag."))
columns = append(columns, v)
case strings.HasPrefix(name, "field."):
var v string
field := strings.TrimPrefix(name, "field.")
if raw, ok := metric.GetField(field); ok {
var err error
v, err = internal.ToString(raw)
if err != nil {
return fmt.Errorf("converting field %q to string failed: %w", field, err)
}
}
columns = append(columns, v)
}
}
return s.writer.Write(columns)
}
func init() {
serializers.Add("csv",
func() telegraf.Serializer {
return &Serializer{}
},
)
}