-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgrafana.go
293 lines (254 loc) · 8.55 KB
/
grafana.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package gav3
import (
"fmt"
"github.com/blackcowmoo/grafana-google-analytics-dataSource/pkg/model"
"github.com/blackcowmoo/grafana-google-analytics-dataSource/pkg/util"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/jinzhu/copier"
reporting "google.golang.org/api/analyticsreporting/v4"
"sort"
"strconv"
"strings"
"time"
)
func transformReportToDataFrameByDimensions(columns []*model.ColumnDefinition, rows []*reporting.ReportRow, refId string, dimensions string) (*data.Frame, error) {
warnings := []string{}
meta := map[string]interface{}{}
converters := make([]data.FieldConverter, len(columns))
for i, column := range columns {
fc, ok := converterMap[column.GetType()]
if !ok {
return nil, fmt.Errorf("unknown column type: %s", column.GetType())
}
converters[i] = fc
}
inputConverter, err := data.NewFrameInputConverter(converters, len(rows))
if err != nil {
return nil, err
}
frame := inputConverter.Frame
frame.RefID = refId
frame.Name = refId // TODO: should set the name from metadata
if len(dimensions) > 0 {
frame.Name = dimensions
}
for i, column := range columns {
field := frame.Fields[i]
field.Name = column.Header
displayName := dimensions
if len(dimensions) > 0 {
displayName = displayName + "|"
}
field.Config = &data.FieldConfig{
DisplayName: displayName + column.Header,
// Unit: column.GetUnit(),
}
}
i := 0
for rowIndex, row := range rows {
if dimensions == strings.Join(row.Dimensions, "|") {
for _, metrics := range row.Metrics {
// d := row.Dimensions[dateIndex]
for valueIndex, value := range metrics.Values {
err := inputConverter.Set(valueIndex, rowIndex, value)
if err != nil {
log.DefaultLogger.Error("frame convert", "error", err.Error())
warnings = append(warnings, err.Error())
continue
}
i++
}
}
}
}
meta["warnings"] = warnings
frame.Meta = &data.FrameMeta{Custom: meta}
return frame, nil
}
// <--------- primary secondary --------->
var timeDimensions []string = []string{"ga:dateHourMinute", "ga:dateHour", "ga:date"}
func transformReportToDataFrames(report *reporting.Report, refId string, timezone string) ([]*data.Frame, error) {
timeDimension := reporting.MetricHeaderEntry{
Name: report.ColumnHeader.Dimensions[0],
Type: "TIME",
}
report.ColumnHeader.MetricHeader.MetricHeaderEntries = append([]*reporting.MetricHeaderEntry{
&timeDimension,
}, report.ColumnHeader.MetricHeader.MetricHeaderEntries...)
timeAddFunction, timeSubFunction := getTimeFunction(timeDimension.Name)
tz, err := time.LoadLocation(timezone)
if err != nil {
log.DefaultLogger.Error("Load local timezone error", "error", err.Error())
}
dimensions := map[string]struct{}{}
var parsedReportMap = make(map[string]map[int64]*reporting.ReportRow)
for _, row := range report.Data.Rows {
parsedRow, parsedTime := parseRow(row, tz)
dimension := strings.Join(parsedRow.Dimensions, "|")
if _, ok := dimensions[dimension]; !ok {
dimensions[dimension] = struct{}{}
}
if inner, ok := parsedReportMap[dimension]; !ok {
inner = make(map[int64]*reporting.ReportRow)
parsedReportMap[dimension] = inner
}
parsedReportMap[dimension][parsedTime.Unix()] = parsedRow
beforeTime := timeSubFunction(*parsedTime)
afterTime := timeAddFunction(*parsedTime)
if _, ok := parsedReportMap[dimension][beforeTime.Unix()]; !ok {
copyRow := copyRowAndInit(row)
copyRow.Metrics[0].Values[0] = beforeTime.Format(time.RFC3339)
parsedReportMap[dimension][beforeTime.Unix()] = copyRow
}
if _, ok := parsedReportMap[dimension][afterTime.Unix()]; !ok {
copyRow := copyRowAndInit(row)
copyRow.Metrics[0].Values[0] = afterTime.Format(time.RFC3339)
parsedReportMap[dimension][afterTime.Unix()] = copyRow
}
}
var dimensionKeys = make([]string, len(dimensions))
i := 0
for value := range dimensions {
dimensionKeys[i] = value
i++
}
var frames = make([]*data.Frame, 0, len(dimensionKeys))
columns := getColumnDefinitions(report.ColumnHeader)
for _, dimension := range dimensionKeys {
keys := make([]int64, len(parsedReportMap[dimension]))
i := 0
for k := range parsedReportMap[dimension] {
keys[i] = k
i++
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
var parsedRows = make([]*reporting.ReportRow, len(parsedReportMap[dimension]))
i = 0
for _, t := range keys {
parsedRows[i] = parsedReportMap[dimension][t]
i++
}
frame, err := transformReportToDataFrameByDimensions(columns, parsedRows, refId, dimension)
if err != nil {
log.DefaultLogger.Error("transformReportToDataFrameByDimensions", "error", err.Error())
return nil, err
}
frames = append(frames, frame)
}
return frames, nil
}
func transformReportsResponseToDataFrames(reportsResponse *reporting.GetReportsResponse, refId string, timezone string) (*data.Frames, error) {
var frames = make(data.Frames, 0)
for _, report := range reportsResponse.Reports {
frame, err := transformReportToDataFrames(report, refId, timezone)
if err != nil {
return nil, err
}
frames = append(frames, frame...)
}
return &frames, nil
}
// timeConverter handles sheets TIME column types.
var timeConverter = data.FieldConverter{
OutputFieldType: data.FieldTypeNullableTime,
Converter: func(i interface{}) (interface{}, error) {
strTime, ok := i.(string)
if !ok {
return nil, fmt.Errorf("expected type string, but got %T", i)
}
time, err := time.Parse(time.RFC3339, strTime)
if err != nil {
log.DefaultLogger.Error("timeConverter failed", "error", err)
return nil, err
}
return &time, nil
},
}
// stringConverter handles sheets STRING column types.
var stringConverter = data.FieldConverter{
OutputFieldType: data.FieldTypeNullableString,
Converter: func(i interface{}) (interface{}, error) {
value, ok := i.(string)
if !ok {
return nil, fmt.Errorf("expected type string, but got %T", i)
}
return &value, nil
},
}
// numberConverter handles sheets STRING column types.
var numberConverter = data.FieldConverter{
OutputFieldType: data.FieldTypeNullableFloat64,
Converter: func(i interface{}) (interface{}, error) {
value, ok := i.(string)
if !ok {
return nil, fmt.Errorf("expected type string, but got %T", i)
}
num, err := strconv.ParseFloat(value, 64)
if err != nil {
return nil, fmt.Errorf("expected type string, but got %T", value)
}
return &num, nil
},
}
// converterMap is a map sheets.ColumnType to fieldConverter and
// is used to create a data.FrameInputConverter for a returned sheet.
var converterMap = map[model.ColumnType]data.FieldConverter{
"TIME": timeConverter,
"STRING": stringConverter,
"NUMBER": numberConverter,
}
func getColumnDefinitions(header *reporting.ColumnHeader) []*model.ColumnDefinition {
columns := []*model.ColumnDefinition{}
headerRow := header.MetricHeader.MetricHeaderEntries
for columnIndex, headerCell := range headerRow {
name := strings.TrimSpace(headerCell.Name)
columns = append(columns, model.NewColumnDefinition(name, columnIndex, headerCell.Type))
}
return columns
}
func copyRow(row *reporting.ReportRow) *reporting.ReportRow {
var copyRow reporting.ReportRow
copier.CopyWithOption(©Row.Dimensions, row.Dimensions, copier.Option{DeepCopy: true})
copier.CopyWithOption(©Row.Metrics, row.Metrics, copier.Option{DeepCopy: true})
return ©Row
}
func copyRowAndInit(row *reporting.ReportRow) *reporting.ReportRow {
copyRow := copyRow(row)
copyRow.Metrics[0].Values = util.FillArray(make([]string, len(row.Metrics[0].Values)), "0")
return copyRow
}
func parseRow(row *reporting.ReportRow, timezone *time.Location) (*reporting.ReportRow, *time.Time) {
timeDimension := row.Dimensions[0]
otherDimensions := row.Dimensions[1:]
parsedTime, err := util.ParseAndTimezoneTime(timeDimension, timezone)
if err != nil {
log.DefaultLogger.Error("parsedTime err", "err", err.Error())
}
strTime := parsedTime.Format(time.RFC3339)
// row.Metrics[0].Values = append(row.Metrics[0].Values, strTime)
row.Metrics[0].Values = append([]string{strTime}, row.Metrics[0].Values...)
row.Dimensions = otherDimensions
return row, parsedTime
}
func getTimeFunction(timeDimension string) (func(time.Time) time.Time, func(time.Time) time.Time) {
var add, sub func(time.Time) time.Time
switch timeDimension {
case timeDimensions[0]:
add = util.AddOneMinute
sub = util.SubOneMinute
break
case timeDimensions[1]:
add = util.AddOneHour
sub = util.SubOneHour
break
case timeDimensions[2]:
add = util.AddOneDay
sub = util.SubOneDay
break
default:
add = util.AddOneHour
sub = util.SubOneHour
}
return add, sub
}