-
Notifications
You must be signed in to change notification settings - Fork 17
/
discovery.go
210 lines (195 loc) · 5.96 KB
/
discovery.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
package elasticsearch
import (
"context"
"encoding/json"
"fmt"
"text/template"
"github.com/elastic/elasticsearch-adapter/pkg/config"
esv7 "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/itchyny/gojq"
"github.com/kubernetes-sigs/custom-metrics-apiserver/pkg/provider"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/klog/v2"
)
var allowedTypes = map[string]struct{}{
"byte": {},
"double": {},
"float": {},
"half_float": {},
"integer": {},
"long": {},
"scaled_float": {},
"short": {},
"unsigned_long": {},
}
func isTypeAllowed(t string) bool {
_, ok := allowedTypes[t]
return ok
}
type MetricMetadata struct {
Fields config.Fields
Search *config.Search
Indices []string
MetricsProvider provider.MetricsProvider
}
// discoverMetrics attempts to create a list of the available metrics and maintains an internal state.
func (mc *MetricsClient) discoverMetrics() error {
namer, err := config.NewNamer(mc.GetConfiguration().Rename)
if err != nil {
klog.Fatalf("%s: failed to create namer: %v", mc.GetConfiguration().Name, err)
}
metricRecorder := newRecorder(namer)
// We first record static fields, they do not require to read the mapping
for _, metricSet := range mc.metricServerCfg.MetricSets {
for _, field := range metricSet.Fields {
if len(field.Name) > 0 {
search := field.Search
search.Template = template.Must(template.New("").Parse(search.Body))
metricResultQuery, err := gojq.Parse(search.MetricPath)
if err != nil {
klog.Fatalf("Error while parsing metricResultQuery for field %s: error: %v", field.Name, err)
}
search.MetricResultQuery = metricResultQuery
timestampResultQuery, err := gojq.Parse(search.TimestampPath)
if err != nil {
klog.Fatalf("Error while parsing timestampResultQuery for field %s: error: %v", field.Name, err)
}
search.TimestampResultQuery = timestampResultQuery
// This is a static field, save the request body and the metric path
metricRecorder.indexedMetrics[field.Name] = MetricMetadata{
Search: &search,
Indices: metricSet.Indices,
}
metricRecorder.metrics[field.Name] = provider.CustomMetricInfo{
GroupResource: schema.GroupResource{ // TODO: infer resource from configuration
Group: "",
Resource: "pods",
},
Namespaced: true,
Metric: field.Name,
}
}
}
}
for _, metricSet := range mc.metricServerCfg.MetricSets {
if err := getMappingFor(metricSet, mc.Client, metricRecorder); err != nil {
return err
}
}
mc.lock.Lock()
defer mc.lock.Unlock()
mc.metrics = metricRecorder.metrics
mc.indexedMetrics = metricRecorder.indexedMetrics
mc.namer = namer
return nil
}
func getMappingFor(metricSet config.MetricSet, esClient *esv7.Client, recorder *recorder) error {
req := esapi.IndicesGetMappingRequest{Index: metricSet.Indices}
res, err := req.Do(context.Background(), esClient)
if err != nil {
return fmt.Errorf("discovery error, got response: %s", err)
}
defer res.Body.Close()
if res.IsError() {
return fmt.Errorf("[%s] Error getting index mapping %v", res.Status(), metricSet.Indices)
} else {
// Deserialize the response into a map.
var r map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
return fmt.Errorf("error parsing the response body: %s", err)
} else {
if len(r) == 0 {
klog.Infof("Mapping is empty for index pattern %s", metricSet.Indices)
return nil
}
// Process mapping
for _, indexMapping := range r {
m := indexMapping.(map[string]interface{})
mapping, hasMapping := m["mappings"]
if !hasMapping {
return fmt.Errorf("discovery error: no 'mapping' field in %s", metricSet.Indices)
}
recorder.processMappingDocument(mapping, metricSet.Fields, metricSet.Indices)
}
}
}
return nil
}
func (r *recorder) processMappingDocument(mapping interface{}, fields config.FieldsSet, indices []string) {
tm, ok := mapping.(map[string]interface{})
if !ok {
return
}
rp := tm["properties"]
rpm, ok := rp.(map[string]interface{})
if !ok {
return
}
r._processMappingDocument("", rpm, fields, indices)
}
func newRecorder(namer config.Namer) *recorder {
return &recorder{
metrics: make(map[string]provider.CustomMetricInfo),
indexedMetrics: make(map[string]MetricMetadata),
namer: namer,
}
}
type recorder struct {
metrics map[string]provider.CustomMetricInfo
indexedMetrics map[string]MetricMetadata
namer config.Namer
}
func (r *recorder) _processMappingDocument(root string, d map[string]interface{}, fieldsSet config.FieldsSet, indices []string) {
for k, t := range d {
if k == "*" {
return
}
if k == "properties" {
tm, ok := t.(map[string]interface{})
if !ok {
continue
}
r._processMappingDocument(root, tm, fieldsSet, indices)
} else {
// Is there a properties child ?
child, ok := t.(map[string]interface{})
if !ok {
continue
}
if _, hasProperties := child["properties"]; hasProperties {
var newRoot string
if root == "" {
newRoot = k
} else {
newRoot = fmt.Sprintf("%s.%s", root, k)
}
r._processMappingDocument(newRoot, child, fieldsSet, indices)
} else {
// Ensure that we have a type
if t, hasType := child["type"]; !(hasType && isTypeAllowed(t.(string))) {
continue
}
// New metric
metricName := fmt.Sprintf("%s.%s", root, k)
fields := fieldsSet.FindMetadata(metricName)
if fields == nil {
// field does not match a pattern, do not register it as available
continue
}
r.metrics[metricName] = provider.CustomMetricInfo{
GroupResource: schema.GroupResource{ // TODO: infer resource from configuration
Group: "",
Resource: "pods",
},
Namespaced: true,
Metric: r.namer.Register(metricName),
}
r.indexedMetrics[metricName] = MetricMetadata{
Fields: *fields,
Indices: indices,
}
}
}
}
}