-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
247 lines (229 loc) · 7.39 KB
/
connection.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
package googlecloud
import (
"context"
"fmt"
"strings"
"time"
"github.com/F1997/categraf/inputs/googlecloud/internal"
"github.com/F1997/categraf/types"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
"github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/api/iterator"
)
// func (ins *Instance) DescribeMetric(w io.Writer, metricType string) error {
// req := &monitoringpb.GetMetricDescriptorRequest{
// Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", ins.ProjectID, metricType),
// }
// ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
// defer cancel()
//
// resp, err := ins.v3client.GetMetricDescriptor(ctx, req)
// if err != nil {
// return fmt.Errorf("could not get custom metric: %w", err)
// }
//
// fmt.Fprintf(w, "Name: %v\n", resp.GetName())
// fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
// fmt.Fprintf(w, "Type: %v\n", resp.GetType())
// fmt.Fprintf(w, "Metric Kind: %v\n", resp.GetMetricKind())
// fmt.Fprintf(w, "Value Type: %v\n", resp.GetValueType())
// fmt.Fprintf(w, "Unit: %v\n", resp.GetUnit())
// fmt.Fprintf(w, "Labels:\n")
// for _, l := range resp.GetLabels() {
// fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
// }
// return nil
// }
//
// func (ins *Instance) getMonitoredResource(w io.Writer, resource string) error {
// ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
// defer cancel()
//
// req := &monitoringpb.GetMonitoredResourceDescriptorRequest{
// Name: fmt.Sprintf(resource),
// }
// resp, err := ins.v3client.GetMonitoredResourceDescriptor(ctx, req)
// if err != nil {
// return fmt.Errorf("could not get custom metric: %w", err)
// }
//
// fmt.Fprintf(w, "Name: %v\n", resp.GetName())
// fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
// fmt.Fprintf(w, "Type: %v\n", resp.GetType())
// fmt.Fprintf(w, "Labels:\n")
// for _, l := range resp.GetLabels() {
// fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
// }
// return nil
// }
//
// func (ins *Instance) readTimeSeriesFields(w io.Writer, filter string) error {
// ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
// defer cancel()
//
// startTime := time.Now().UTC().Add(-time.Duration(ins.Period) - time.Duration(ins.Delay))
// endTime := time.Now().UTC().Add(-time.Duration(ins.Delay))
// req := &monitoringpb.ListTimeSeriesRequest{
// Name: "projects/" + ins.ProjectID,
// Filter: filter,
// Interval: &monitoringpb.TimeInterval{
// StartTime: ×tamp.Timestamp{
// Seconds: startTime.Unix(),
// },
// EndTime: ×tamp.Timestamp{
// Seconds: endTime.Unix(),
// },
// },
// View: monitoringpb.ListTimeSeriesRequest_HEADERS,
// }
// fmt.Fprintln(w, "Found data points for the following instances:")
// it := ins.v3client.ListTimeSeries(ctx, req)
// for {
// resp, err := it.Next()
// if err == iterator.Done {
// break
// }
// if err != nil {
// return fmt.Errorf("could not read time series value: %w", err)
// }
// fmt.Fprintf(w, "\t%v\n", resp.GetMetric().GetLabels()["instance_name"])
// }
// fmt.Fprintln(w, "Done")
// return nil
// }
// func (ins *Instance) listMonitoredResources(w io.Writer) error {
// ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
// defer cancel()
//
// req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{
// Name: "projects/" + ins.ProjectID,
// }
// iter := ins.v3client.ListMonitoredResourceDescriptors(ctx, req)
//
// for {
// resp, err := iter.Next()
// if err == iterator.Done {
// break
// }
// if err != nil {
// return fmt.Errorf("Could not list time series: %w", err)
// }
// fmt.Fprintf(w, "%v\n", resp)
// }
// fmt.Fprintln(w, "Done")
// return nil
// }
var distributionQuantileBuckets = []string{
"p50",
"p75",
"p90",
"p95",
"p99",
"p999",
"mean",
}
func (ins *Instance) readTimeSeriesValue(slist *types.SampleList, filter string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
defer cancel()
startTime := time.Now().UTC().Add(-time.Duration(ins.Delay) - time.Duration(ins.Period)).Unix()
endTime := time.Now().UTC().Add(time.Duration(ins.Delay)).Unix()
req := &monitoringpb.ListTimeSeriesRequest{
Name: "projects/" + ins.ProjectID,
Filter: filter,
Interval: &monitoringpb.TimeInterval{
StartTime: ×tamp.Timestamp{Seconds: startTime},
EndTime: ×tamp.Timestamp{Seconds: endTime},
},
}
iter := ins.v3client.ListTimeSeries(ctx, req)
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return fmt.Errorf("could not read time series value, %w ", err)
}
labels := make(map[string]string)
for k, v := range resp.GetMetric().GetLabels() {
labels[k] = v
}
for k, v := range resp.GetResource().GetLabels() {
labels[k] = v
}
if !ins.UnmaskProjectID {
delete(labels, "project_id")
}
labels["metric_type"] = resp.GetMetric().GetType()
labels["resource_type"] = resp.GetResource().GetType()
if labels["resource_type"] == "gce_instance" {
labels[ins.GceHostTag] = labels["instance_name"]
}
metric := strings.ReplaceAll(labels["metric_type"], "/", "_")
// metric = strings.ReplaceAll(labels["metric_type"], ".googleapis.com/", "")
samples := make([]*types.Sample, 0, len(resp.GetPoints()))
var val interface{}
for _, point := range resp.GetPoints() {
val = 0
pointTS := time.Unix(point.GetInterval().GetEndTime().GetSeconds(), 0)
switch point.GetValue().GetValue().(type) {
case *monitoringpb.TypedValue_DoubleValue:
val = point.GetValue().GetDoubleValue()
case *monitoringpb.TypedValue_Int64Value:
val = point.GetValue().GetInt64Value()
case *monitoringpb.TypedValue_DistributionValue:
// Calculate quantile sum
val = point.GetValue().GetDistributionValue().GetCount()
samples = append(
samples,
types.NewSample("gcp", metric+"_sum", val, labels).SetTime(pointTS),
)
// try to calculate quantile value
if quantile, err := internal.GenerateHistogramBuckets(point.GetValue().GetDistributionValue()); err != nil {
samples = append(
samples,
types.NewSample("gcp", metric, val, labels).SetTime(pointTS),
)
} else {
// append mean quantile to slice
for i, qt := range append(
quantile.GetQuantiles(),
point.GetValue().GetDistributionValue().GetMean(),
) {
// add new quantile label to identify quantile
lbs := labels
lbs["quantile"] = distributionQuantileBuckets[i]
samples = append(samples, types.NewSample("gcp", metric, qt, lbs).SetTime(pointTS))
}
}
continue
}
samples = append(
samples,
types.NewSample("gcp", metric, val, labels).SetTime(pointTS),
)
}
slist.PushFrontN(samples)
}
return nil
}
func (ins *Instance) ListMetrics() ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(ins.Timeout))
defer cancel()
req := &monitoringpb.ListMetricDescriptorsRequest{
Name: "projects/" + ins.ProjectID,
}
iter := ins.v3client.ListMetricDescriptors(ctx, req)
result := make([]string, 0, 100)
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("Could not list metrics: %w", err)
}
result = append(result, resp.GetType())
}
return result, nil
}