-
Notifications
You must be signed in to change notification settings - Fork 568
/
metrics.go
389 lines (368 loc) · 11 KB
/
metrics.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package metrics
import (
"context"
"fmt"
"time"
auth_client "github.com/pachyderm/pachyderm/v2/src/auth"
"github.com/pachyderm/pachyderm/v2/src/enterprise"
"github.com/pachyderm/pachyderm/v2/src/internal/config"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/log"
"github.com/pachyderm/pachyderm/v2/src/internal/pctx"
"github.com/pachyderm/pachyderm/v2/src/internal/serviceenv"
"github.com/pachyderm/pachyderm/v2/src/internal/uuid"
"github.com/pachyderm/pachyderm/v2/src/pps"
enterprisemetrics "github.com/pachyderm/pachyderm/v2/src/server/enterprise/metrics"
"github.com/pachyderm/pachyderm/v2/src/version"
"go.uber.org/zap"
"google.golang.org/grpc/metadata"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kube "k8s.io/client-go/kubernetes"
)
// Reporter is used to submit user & cluster metrics to segment
type Reporter struct {
router *router
clusterID string
env serviceenv.ServiceEnv
}
const metricsUsername = "metrics"
// NewReporter creates a new reporter and kicks off the loop to report cluster
// metrics
func NewReporter(env serviceenv.ServiceEnv) *Reporter {
var r *router
if env.Config().MetricsEndpoint != "" {
r = newRouter(env.Config().MetricsEndpoint)
} else {
r = newRouter()
}
reporter := &Reporter{
router: r,
clusterID: env.ClusterID(),
env: env,
}
go reporter.reportClusterMetrics(env.Context())
return reporter
}
// ReportUserAction pushes the action into a queue for reporting,
// and reports the start, finish, and error conditions
func ReportUserAction(ctx context.Context, r *Reporter, action string) func(time.Time, error) {
if r == nil {
// This happens when stubbing out metrics for testing, e.g. src/server/pfs/server/server_test.go
return func(time.Time, error) {}
}
// If we report nil, segment sees it, but mixpanel omits the field
r.reportUserAction(ctx, fmt.Sprintf("%vStarted", action), 1)
return func(start time.Time, err error) {
if err == nil {
r.reportUserAction(ctx, fmt.Sprintf("%vFinished", action), time.Since(start).Seconds())
} else {
r.reportUserAction(ctx, fmt.Sprintf("%vErrored", action), err.Error())
}
}
}
func getKeyFromMD(md metadata.MD, key string) (string, error) {
if md[key] != nil && len(md[key]) > 0 {
return md[key][0], nil
}
return "", errors.Errorf("error extracting userid from metadata. userid is empty")
}
func (r *Reporter) reportUserAction(ctx context.Context, action string, value interface{}) {
md, ok := metadata.FromIncomingContext(ctx)
if ok {
// metadata API downcases all the key names
userID, err := getKeyFromMD(md, "userid")
if err != nil {
// The FUSE client will never have a userID, so normal usage will produce a lot of these errors
return
}
prefix, err := getKeyFromMD(md, "prefix")
if err != nil {
// metrics errors are non fatal
return
}
r.router.reportUserMetricsToSegment(
userID,
prefix,
action,
value,
r.clusterID,
)
}
}
// Helper method called by (Start|Finish)ReportAndFlushUserAction. Like those
// functions, it is used by the pachctl binary and runs on users' machines
func reportAndFlushUserAction(action string, value interface{}) func() {
metricsDone := make(chan struct{})
go func() {
defer close(metricsDone)
cfg, _ := config.Read(false, false)
if cfg == nil || cfg.UserId == "" || !cfg.V2.Metrics {
return
}
client := newSegmentClient()
defer client.Close()
reportUserMetricsToSegment(client, cfg.UserId, "user", action, value, "")
}()
return func() {
select {
case <-metricsDone:
return
case <-time.After(time.Second * 5):
return
}
}
}
// StartReportAndFlushUserAction immediately reports the metric but does
// not block execution. It returns a wait function which waits or times
// out after 5s.
// It is used by the pachctl binary and runs on users' machines
func StartReportAndFlushUserAction(action string, value interface{}) func() {
return reportAndFlushUserAction(fmt.Sprintf("%vStarted", action), value)
}
// FinishReportAndFlushUserAction immediately reports the metric but does
// not block execution. It returns a wait function which waits or times
// out after 5s.
// It is used by the pachctl binary and runs on users' machines
func FinishReportAndFlushUserAction(action string, err error, start time.Time) func() {
var wait func()
if err != nil {
wait = reportAndFlushUserAction(fmt.Sprintf("%vErrored", action), err)
} else {
wait = reportAndFlushUserAction(fmt.Sprintf("%vFinished", action), time.Since(start).Seconds())
}
return wait
}
func (r *Reporter) reportClusterMetrics(ctx context.Context) {
ticker := time.NewTicker(reportingInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
metrics := &Metrics{}
r.internalMetrics(metrics)
externalMetrics(r.env.GetKubeClient(), metrics) //nolint:errcheck
metrics.ClusterId = r.clusterID
metrics.PodId = uuid.NewWithoutDashes()
metrics.Version = version.PrettyPrintVersion(version.Version)
r.router.reportClusterMetricsToSegment(metrics)
}
}
func externalMetrics(kubeClient kube.Interface, metrics *Metrics) error {
nodeList, err := kubeClient.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
return errors.Wrapf(err, "externalMetrics: unable to retrieve node list from k8s")
}
metrics.Nodes = int64(len(nodeList.Items))
return nil
}
func pfsInputMetrics(pfsInput *pps.PFSInput, metrics *Metrics) {
metrics.InputPfs++
if pfsInput.Commit != "" {
metrics.InputCommit++
}
if pfsInput.JoinOn != "" {
metrics.InputJoinOn++
}
if pfsInput.OuterJoin {
metrics.InputOuterJoin++
}
if pfsInput.Lazy {
metrics.InputLazy++
}
if pfsInput.EmptyFiles {
metrics.InputEmptyFiles++
}
if pfsInput.S3 {
metrics.InputS3++
}
if pfsInput.Trigger != nil {
metrics.InputTrigger++
}
}
func inputMetrics(input *pps.Input, metrics *Metrics) {
if input.Join != nil {
metrics.InputJoin++
for _, item := range input.Join {
if item.Pfs != nil {
pfsInputMetrics(item.Pfs, metrics)
} else {
inputMetrics(item, metrics)
}
}
}
if input.Group != nil {
metrics.InputGroup++
for _, item := range input.Group {
if item.Pfs != nil {
pfsInputMetrics(item.Pfs, metrics)
} else {
inputMetrics(item, metrics)
}
}
}
if input.Cross != nil {
metrics.InputCross++
for _, item := range input.Cross {
if item.Pfs != nil {
pfsInputMetrics(item.Pfs, metrics)
} else {
inputMetrics(item, metrics)
}
}
}
if input.Union != nil {
metrics.InputUnion++
for _, item := range input.Union {
if item.Pfs != nil {
pfsInputMetrics(item.Pfs, metrics)
} else {
inputMetrics(item, metrics)
}
}
}
if input.Cron != nil {
metrics.InputCron++
}
if input.Pfs != nil {
pfsInputMetrics(input.Pfs, metrics)
}
}
func (r *Reporter) internalMetrics(metrics *Metrics) {
// We should not return due to an error
// Activation code
ctx, cf := pctx.WithCancel(context.Background())
defer cf()
enterpriseState, err := r.env.EnterpriseServer().GetState(ctx, &enterprise.GetStateRequest{})
if err == nil {
metrics.ActivationCode = enterpriseState.ActivationCode
}
metrics.EnterpriseFailures = enterprisemetrics.GetEnterpriseFailures()
resp, err := r.env.AuthServer().GetRobotToken(ctx, &auth_client.GetRobotTokenRequest{
Robot: metricsUsername,
Ttl: int64(reportingInterval.Seconds() / 2),
})
if err != nil && !auth_client.IsErrNotActivated(err) {
log.Error(pctx.TODO(), "Error getting metics auth token", zap.Error(err))
return // couldn't authorize, can't continue
}
pachClient := r.env.GetPachClient(ctx)
if resp != nil {
pachClient.SetAuthToken(resp.Token)
}
// Pipeline info
infos, err := pachClient.ListPipeline(true)
if err != nil {
log.Error(ctx, "Error getting pipeline metrics", zap.Error(err))
} else {
for _, pi := range infos {
metrics.Pipelines += 1
// count total jobs
var cnt int64
// just ignore error
_ = pachClient.ListJobF(pi.Pipeline.Project.GetName(), pi.Pipeline.Name, nil, -1, false, func(ji *pps.JobInfo) error {
cnt++
return nil
})
if metrics.Jobs < cnt {
metrics.Jobs = cnt
}
if details := pi.Details; details != nil {
if details.ParallelismSpec != nil {
if metrics.MaxParallelism < details.ParallelismSpec.Constant {
metrics.MaxParallelism = details.ParallelismSpec.Constant
}
if metrics.MinParallelism > details.ParallelismSpec.Constant {
metrics.MinParallelism = details.ParallelismSpec.Constant
}
metrics.NumParallelism++
}
if details.Egress != nil {
metrics.CfgEgress++
}
if details.ResourceRequests != nil {
if details.ResourceRequests.Cpu != 0 {
metrics.ResourceCpuReq += details.ResourceRequests.Cpu
if metrics.ResourceCpuReqMax < details.ResourceRequests.Cpu {
metrics.ResourceCpuReqMax = details.ResourceRequests.Cpu
}
}
if details.ResourceRequests.Memory != "" {
metrics.ResourceMemReq += (details.ResourceRequests.Memory + " ")
}
if details.ResourceRequests.Gpu != nil {
metrics.ResourceGpuReq += details.ResourceRequests.Gpu.Number
if metrics.ResourceGpuReqMax < details.ResourceRequests.Gpu.Number {
metrics.ResourceGpuReqMax = details.ResourceRequests.Gpu.Number
}
}
if details.ResourceRequests.Disk != "" {
metrics.ResourceDiskReq += (details.ResourceRequests.Disk + " ")
}
}
if details.ResourceLimits != nil {
if details.ResourceLimits.Cpu != 0 {
metrics.ResourceCpuLimit += details.ResourceLimits.Cpu
if metrics.ResourceCpuLimitMax < details.ResourceLimits.Cpu {
metrics.ResourceCpuLimitMax = details.ResourceLimits.Cpu
}
}
if details.ResourceLimits.Memory != "" {
metrics.ResourceMemLimit += (details.ResourceLimits.Memory + " ")
}
if details.ResourceLimits.Gpu != nil {
metrics.ResourceGpuLimit += details.ResourceLimits.Gpu.Number
if metrics.ResourceGpuLimitMax < details.ResourceLimits.Gpu.Number {
metrics.ResourceGpuLimitMax = details.ResourceLimits.Gpu.Number
}
}
if details.ResourceLimits.Disk != "" {
metrics.ResourceDiskLimit += (details.ResourceLimits.Disk + " ")
}
}
if details.Input != nil {
inputMetrics(details.Input, metrics)
}
if details.Service != nil {
metrics.CfgServices++
}
if details.Spout != nil {
metrics.PpsSpout++
if details.Spout.Service != nil {
metrics.PpsSpoutService++
}
}
if details.S3Out {
metrics.CfgS3Gateway++
}
if details.Transform != nil {
if details.Transform.ErrCmd != nil {
metrics.CfgErrcmd++
}
}
if details.TfJob != nil {
metrics.CfgTfjob++
}
}
}
}
var count int64
var sz, mbranch uint64
repos, err := pachClient.ListRepo()
if err != nil {
log.Error(ctx, "Error getting repos", zap.Error(err))
} else {
for _, ri := range repos {
count += 1
sz += uint64(ri.SizeBytesUpperBound)
if mbranch < uint64(len(ri.Branches)) {
mbranch = uint64(len(ri.Branches))
}
}
metrics.Repos = int64(len(repos))
metrics.Bytes = sz
metrics.MaxBranches = mbranch
}
}