-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
metrics_requester.go
252 lines (206 loc) · 7.75 KB
/
metrics_requester.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package metrics
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/golang/protobuf/ptypes/duration"
monitoring "cloud.google.com/go/monitoring/apiv3/v2"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
"github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/api/iterator"
"github.com/elastic/beats/v7/x-pack/metricbeat/module/gcp"
"github.com/elastic/elastic-agent-libs/logp"
)
type metricsRequester struct {
config config
client *monitoring.MetricClient
logger *logp.Logger
}
type timeSeriesWithAligner struct {
timeSeries []*monitoringpb.TimeSeries
aligner string
}
func (r *metricsRequester) Metric(ctx context.Context, serviceName, metricType string, timeInterval *monitoringpb.TimeInterval, aligner string) timeSeriesWithAligner {
timeSeries := make([]*monitoringpb.TimeSeries, 0)
req := &monitoringpb.ListTimeSeriesRequest{
Name: "projects/" + r.config.ProjectID,
Interval: timeInterval,
View: monitoringpb.ListTimeSeriesRequest_FULL,
Filter: r.getFilterForMetric(serviceName, metricType),
Aggregation: &monitoringpb.Aggregation{
PerSeriesAligner: gcp.AlignersMapToGCP[aligner],
AlignmentPeriod: r.config.period,
},
}
it := r.client.ListTimeSeries(ctx, req)
for {
resp, err := it.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
r.logger.Errorf("Could not read time series value: %s: %v", metricType, err)
break
}
timeSeries = append(timeSeries, resp)
}
out := timeSeriesWithAligner{
aligner: aligner,
timeSeries: timeSeries,
}
return out
}
func (r *metricsRequester) Metrics(ctx context.Context, serviceName string, aligner string, metricsToCollect map[string]metricMeta) ([]timeSeriesWithAligner, error) {
var lock sync.Mutex
var wg sync.WaitGroup
results := make([]timeSeriesWithAligner, 0)
for mt, meta := range metricsToCollect {
wg.Add(1)
metricMeta := meta
go func(mt string) {
defer wg.Done()
r.logger.Debugf("For metricType %s, metricMeta = %d, aligner = %s", mt, metricMeta, aligner)
interval, aligner := getTimeIntervalAligner(metricMeta.ingestDelay, metricMeta.samplePeriod, r.config.period, aligner)
ts := r.Metric(ctx, serviceName, mt, interval, aligner)
lock.Lock()
defer lock.Unlock()
results = append(results, ts)
}(mt)
}
wg.Wait()
return results, nil
}
func (r *metricsRequester) buildRegionsFilter(regions []string, label string) string {
if len(regions) == 0 {
return ""
}
var filter strings.Builder
// No. of regions added to the filter string.
var regionsCount uint
for _, region := range regions {
// If 1 region has been added and the iteration continues, add the OR operator.
if regionsCount > 0 {
filter.WriteString("OR")
filter.WriteString(" ")
}
filter.WriteString(fmt.Sprintf("%s = starts_with(\"%s\")", label, trimWildcard(region)))
filter.WriteString(" ")
regionsCount++
}
switch {
// If the filter string has more than 1 region, parentheses are added for better filter readability.
case regionsCount > 1:
return fmt.Sprintf("(%s)", strings.TrimSpace(filter.String()))
default:
return strings.TrimSpace(filter.String())
}
}
// getServiceLabelFor return the appropriate label to use for filtering metrics of a given service.
func getServiceLabelFor(serviceName string) string {
switch serviceName {
case gcp.ServiceCompute:
return gcp.ComputeResourceLabel
case gcp.ServiceGKE:
return gcp.GKEResourceLabel
case gcp.ServiceDataproc:
return gcp.DataprocResourceLabel
case gcp.ServiceStorage:
return gcp.StorageResourceLabel
case gcp.ServiceCloudSQL:
return gcp.CloudSQLResourceLabel
case gcp.ServiceRedis:
return gcp.RedisResourceLabel
default:
return gcp.DefaultResourceLabel
}
}
func (r *metricsRequester) buildLocationFilter(serviceLabel, filter string) string {
if r.config.Region != "" && r.config.Zone != "" {
r.logger.Warnf("when region %s and zone %s config parameter "+
"both are provided, only use region", r.config.Regions, r.config.Zone)
}
if r.config.Region != "" && len(r.config.Regions) != 0 {
r.logger.Warnf("when region %s and regions config parameters are both provided, use region", r.config.Region)
}
switch {
case r.config.Region != "":
filter = fmt.Sprintf("%s AND %s = starts_with(\"%s\")", filter, serviceLabel, trimWildcard(r.config.Region))
case r.config.Zone != "":
filter = fmt.Sprintf("%s AND %s = starts_with(\"%s\")", filter, serviceLabel, trimWildcard(r.config.Zone))
case len(r.config.Regions) != 0:
regionsFilter := r.buildRegionsFilter(r.config.Regions, serviceLabel)
filter = fmt.Sprintf("%s AND %s", filter, regionsFilter)
}
return filter
}
// trimWildcard remove wildcard value `*` from the end of the string.
func trimWildcard(value string) string {
return strings.TrimSuffix(value, "*")
}
// isAGlobalService return true if the given service is considered global from GCP and does not
// uses the regional or zonal metrics filtering.
func isAGlobalService(serviceName string) bool {
switch serviceName {
case gcp.ServicePubsub, gcp.ServiceLoadBalancing, gcp.ServiceCloudFunctions, gcp.ServiceFirestore:
return true
default:
return false
}
}
// getFilterForMetric returns the filter associated with the corresponding filter. Some services like Pub/Sub fails
// if they have a region specified.
func (r *metricsRequester) getFilterForMetric(serviceName, m string) string {
f := fmt.Sprintf(`metric.type="%s"`, m)
locationsConfigsAvailable := r.config.Region != "" || r.config.Zone != "" || len(r.config.Regions) > 0
// NOTE: some GCP services are global, not regional or zonal. To these services we don't need
// to apply any additional filters.
if locationsConfigsAvailable && !isAGlobalService(serviceName) {
serviceLabel := getServiceLabelFor(serviceName)
f = r.buildLocationFilter(serviceLabel, f)
}
// NOTE: make sure to log the applied filter, as it helpful when debugging
r.logger.Debugf("ListTimeSeries API filter = %s", f)
return f
}
// Returns a GCP TimeInterval based on the ingestDelay and samplePeriod from ListMetricDescriptor
func getTimeIntervalAligner(ingestDelay time.Duration, samplePeriod time.Duration, collectionPeriod *duration.Duration, inputAligner string) (*monitoringpb.TimeInterval, string) {
var startTime, endTime, currentTime time.Time
var needsAggregation bool
currentTime = time.Now().UTC()
// When samplePeriod < collectionPeriod, aggregation will be done in ListTimeSeriesRequest.
// For example, samplePeriod = 60s, collectionPeriod = 300s, if perSeriesAligner is not given,
// ALIGN_MEAN will be used by default.
if int64(samplePeriod.Seconds()) < collectionPeriod.Seconds {
endTime = currentTime.Add(-ingestDelay)
startTime = endTime.Add(-time.Duration(collectionPeriod.Seconds) * time.Second)
needsAggregation = true
}
// When samplePeriod == collectionPeriod, aggregation is not needed
// When samplePeriod > collectionPeriod, aggregation is not needed, use sample period
// to determine startTime and endTime to make sure there will be data point in this time range.
if int64(samplePeriod.Seconds()) >= collectionPeriod.Seconds {
endTime = currentTime.Add(-ingestDelay)
startTime = endTime.Add(-samplePeriod)
needsAggregation = false
}
interval := &monitoringpb.TimeInterval{
StartTime: ×tamp.Timestamp{
Seconds: startTime.Unix(),
},
EndTime: ×tamp.Timestamp{
Seconds: endTime.Unix(),
},
}
// Default aligner for aggregation is ALIGN_NONE if it's not given
updatedAligner := gcp.DefaultAligner
if needsAggregation && inputAligner != "" {
updatedAligner = inputAligner
}
return interval, updatedAligner
}