-
Notifications
You must be signed in to change notification settings - Fork 12
/
collector.go
243 lines (204 loc) · 6.07 KB
/
collector.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
package collector
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"sync"
"time"
"github.com/xyctruth/stream"
"github.com/google/pprof/profile"
"github.com/sirupsen/logrus"
"github.com/xyctruth/profiler/pkg/storage"
)
// Collector Collect target pprof http endpoints
type Collector struct {
TargetName string
TargetConfig
exitChan chan struct{}
resetTickerChan chan time.Duration
mangerWg *sync.WaitGroup
wg *sync.WaitGroup
httpClient *http.Client
mu sync.RWMutex
log *logrus.Entry
store storage.Store
}
func newCollector(targetName string, target TargetConfig, store storage.Store, mangerWg *sync.WaitGroup) *Collector {
collector := &Collector{
TargetName: targetName,
TargetConfig: target,
exitChan: make(chan struct{}),
resetTickerChan: make(chan time.Duration, 1000),
mangerWg: mangerWg,
wg: &sync.WaitGroup{},
httpClient: &http.Client{},
log: logrus.WithField("collector", targetName),
store: store,
}
collector.ProfileConfigs = buildProfileConfigs(collector.ProfileConfigs)
return collector
}
func (collector *Collector) run() {
collector.mu.Lock()
defer collector.mu.Unlock()
collector.log.Info("collector run")
collector.mangerWg.Add(1)
go collector.scrapeLoop(collector.Interval)
}
func (collector *Collector) scrapeLoop(interval time.Duration) {
defer collector.mangerWg.Done()
collector.scrape()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-collector.exitChan:
collector.log.Info("scrape loop exit")
return
case i := <-collector.resetTickerChan:
ticker.Reset(i)
case <-ticker.C:
collector.scrape()
}
}
}
func (collector *Collector) reload(target TargetConfig) {
collector.mu.Lock()
defer collector.mu.Unlock()
target.ProfileConfigs = buildProfileConfigs(target.ProfileConfigs)
if reflect.DeepEqual(collector.TargetConfig, target) {
return
}
collector.log.Info("reload collector ")
if collector.Interval != target.Interval {
collector.resetTickerChan <- target.Interval
}
collector.TargetConfig = target
}
func (collector *Collector) exit() {
close(collector.exitChan)
}
func (collector *Collector) scrape() {
collector.mu.RLock()
defer collector.mu.RUnlock()
collector.log.Info("collector start scrape")
for profileType, profileConfig := range collector.ProfileConfigs {
if *profileConfig.Enable {
stream.NewSlice(collector.Instances).Parallel(len(collector.Instances)).ForEach(func(i int, instance string) {
collector.wg.Add(1)
collector.fetch(instance, profileType, profileConfig)
})
}
}
collector.wg.Wait()
}
func (collector *Collector) fetch(instance string, profileType string, profileConfig ProfileConfig) {
defer collector.wg.Done()
logEntry := collector.log.WithFields(logrus.Fields{"profile_type": profileType, "profile_url": profileConfig.Path})
logEntry.Info("collector start fetch")
req, err := http.NewRequest("GET", "http://"+instance+profileConfig.Path, nil)
if err != nil {
logEntry.WithError(err).Error("invoke task error")
return
}
req.Header.Set("User-Agent", "")
resp, err := collector.httpClient.Do(req)
if err != nil {
logEntry.WithError(err).Error("http request error")
return
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
logEntry.WithError(err).Error("http resp status code is ", resp.StatusCode)
return
}
profileBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
logEntry.WithError(err).Error("read resp error")
return
}
if profileType == "trace" {
err = collector.analysisTrace(instance, profileType, profileBytes)
if err != nil {
logEntry.WithError(err).Error("analysis result error")
return
}
return
}
err = collector.analysis(instance, profileType, profileBytes)
if err != nil {
logEntry.WithError(err).Error("analysis result error")
return
}
}
func (collector *Collector) analysis(instance string, profileType string, profileBytes []byte) error {
p, err := profile.ParseData(profileBytes)
if err != nil {
return err
}
if len(p.SampleType) == 0 {
return errors.New("sample type is nil")
}
// Set profile name , Display it on the Profile UI
if len(p.Mapping) > 0 {
p.Mapping[0].File = collector.TargetName
}
b := &bytes.Buffer{}
if err = p.Write(b); err != nil {
return err
}
profileID, err := collector.store.SaveProfile(fmt.Sprintf("%s-%s", collector.TargetName, profileType), b.Bytes(), collector.Expiration)
if err != nil {
return err
}
metas := make([]*storage.ProfileMeta, 0, len(p.SampleType))
for i := range p.SampleType {
meta := &storage.ProfileMeta{}
meta.Timestamp = time.Now().UnixNano() / time.Millisecond.Nanoseconds()
meta.ProfileID = profileID
meta.ProfileType = profileType
meta.TargetName = collector.TargetName
meta.Instance = instance
meta.Duration = p.DurationNanos
meta.SampleTypeUnit = p.SampleType[i].Unit
for _, s := range p.Sample {
meta.Value += s.Value[i]
}
if len(p.SampleType) > 1 {
meta.SampleType = fmt.Sprintf("%s_%s", profileType, p.SampleType[i].Type)
} else {
meta.SampleType = profileType
}
meta.Labels = collector.Labels.ToArray()
metas = append(metas, meta)
}
err = collector.store.SaveProfileMeta(metas, collector.Expiration)
if err != nil {
return err
}
return nil
}
func (collector *Collector) analysisTrace(instance string, profileType string, profileBytes []byte) error {
profileID, err := collector.store.SaveProfile(fmt.Sprintf("%s-%s", collector.TargetName, profileType), profileBytes, collector.Expiration)
if err != nil {
return err
}
metas := make([]*storage.ProfileMeta, 0, 1)
meta := &storage.ProfileMeta{}
meta.Timestamp = time.Now().UnixNano() / time.Millisecond.Nanoseconds()
meta.ProfileID = profileID
meta.ProfileType = profileType
meta.SampleType = profileType
meta.TargetName = collector.TargetName
meta.Instance = instance
meta.Labels = collector.Labels.ToArray()
metas = append(metas, meta)
err = collector.store.SaveProfileMeta(metas, collector.Expiration)
if err != nil {
return err
}
return nil
}