-
Notifications
You must be signed in to change notification settings - Fork 375
/
grabber.go
221 lines (200 loc) · 5.41 KB
/
grabber.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
// Copyright (c) 2021 Terminus, Inc.
//
// This program is free software: you can use, redistribute, and/or modify
// it under the terms of the GNU Affero General Public License, version 3
// or later ("AGPL"), as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package grabber
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/pkg/errors"
"github.com/erda-project/erda/modules/extensions/cloud/aliyun/metrics/cloudcat/api"
gl "github.com/erda-project/erda/modules/extensions/cloud/aliyun/metrics/cloudcat/globals"
)
// var (
// ErrDifferentMetaMetrics = errors.New("metaMetrics has been changed")
// )
type Grabber struct {
Name string
Namespace string
index int // the index in Scheduler.grabbers
orgId string
done chan struct{}
pipe chan []*api.Metric
interval time.Duration // 采集时间间隔
metaMetrics []cms.Resource
}
func New(namespace string, interval time.Duration, orgId string, index int) (g *Grabber, err error) {
name, done := "", make(chan struct{})
switch namespace {
case "": // cms itself
name = "cms"
case "waf":
name = "waf"
default:
s := strings.Split(namespace, "_")
if len(s) < 2 || s[0] != "acs" {
return nil, errors.Errorf("invalid namespace %s\n", namespace)
}
name = s[1]
}
g = &Grabber{
Name: name,
Namespace: namespace,
interval: interval,
index: index,
orgId: orgId,
done: done,
}
_, err = g.loadMetaMetrics()
return
}
func (g *Grabber) String() string {
return fmt.Sprintf("%dth grabber<%s> of <%s>", g.index, g.Name, g.orgId)
}
func (g *Grabber) Subscribe(pipe chan []*api.Metric) {
g.pipe = pipe
}
func (g *Grabber) Gather() {
for {
gl.Log.Infof("grabber %s start to get data...", g)
for _, item := range g.metaMetrics {
go func(meta cms.Resource) {
data, err := api.GetDescribeMetricLast(g.orgId, meta.Namespace, meta.MetricName)
if err != nil {
switch err {
case api.ErrEmptyResults:
// ignore
default:
gl.Log.Infof("gather failed of %s. err=%s name=%s metricName=%s", g, err, g.Name, meta.MetricName)
return
}
}
if len(data) == 0 {
return
}
metric := g.toMetrics(data, meta)
if metric != nil {
g.pipe <- metric
}
}(item)
}
select {
case <-g.done:
return
case <-time.After(g.interval):
}
}
}
func (g *Grabber) toMetrics(batch []string, meta cms.Resource) []*api.Metric {
res := make([]*api.Metric, 0, len(batch))
for _, dp := range batch {
res = append(res, g.extractDataPoints(dp, meta)...)
}
return res
}
func (g *Grabber) extractDataPoints(dp string, meta cms.Resource) (res []*api.Metric) {
defer func() {
if err := recover(); err != nil {
gl.Log.Errorf("extract failed. err=%s", err)
res = nil
}
return
}()
var all []map[string]interface{}
err := json.Unmarshal([]byte(dp), &all)
if err != nil {
gl.Log.Errorf("extract datapoints %s faild. err=%s", dp, err)
return nil
}
leftTags := func(source map[string]interface{}, excludes []string) {
excludes = append(excludes, "timestamp")
for _, item := range excludes {
delete(source, item)
}
}
res = make([]*api.Metric, 0, len(all))
for i := 0; i < len(all); i++ {
data := all[i]
m := &api.Metric{
Name: "aliyun" + "_" + g.Name,
Timestamp: uint64(data["timestamp"].(float64)) * 1e6,
Tags: map[string]string{},
Fields: map[string]interface{}{},
}
switch {
case strings.Contains(meta.Statistics, "Average"):
m.Fields[meta.MetricName] = data["Average"]
case strings.Contains(meta.Statistics, "Value"):
m.Fields[meta.MetricName] = data["Value"]
case strings.Contains(meta.Statistics, "Maximum"):
m.Fields[meta.MetricName] = data["Maximum"]
case strings.Contains(meta.Statistics, "Minimum"):
m.Fields[meta.MetricName] = data["Minimum"]
default:
if len(meta.Statistics) == 0 {
continue
}
// logrus.Infof("Uncovered Statistics %s; data %+v", meta.Statistics, data)
idx := strings.Index(meta.Statistics, ",")
if idx > 0 {
m.Fields[meta.MetricName] = data[meta.Statistics[:idx]]
} else {
m.Fields[meta.MetricName] = data[meta.Statistics]
}
}
// left fields as tags
leftTags(data, strings.Split(meta.Statistics, ","))
for k, v := range data {
m.Tags[k] = fmt.Sprintf("%v", v)
}
res = append(res, m)
}
return res
}
func (g *Grabber) loadMetaMetrics() (same bool, err error) {
data, err := api.ListMetricMeta(g.orgId, g.Namespace)
if err != nil {
return false, err
}
same = reflect.DeepEqual(g.metaMetrics, data)
g.metaMetrics = data
return
}
// 1h, 2h, 4h, 8h, 16h
func (g *Grabber) Sync(notify chan int) {
growing := 1
for {
select {
case <-g.done:
return
case <-time.After(time.Duration(growing) * time.Hour):
}
same, err := g.loadMetaMetrics()
if !same {
notify <- g.index // send index to scheduler
}
if err != nil {
gl.Log.Errorf("loadMetaMetrics error. err=%s grabber=%s", err, g.Name)
continue
}
if growing < 16 {
growing = growing * 2
}
}
}
func (g *Grabber) Close() error {
close(g.done)
return nil
}