-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathload_scraper.go
82 lines (67 loc) · 2.48 KB
/
load_scraper.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
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package loadscraper
import (
"context"
"time"
"github.com/shirou/gopsutil/load"
"go.uber.org/zap"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer/consumererror"
"go.opentelemetry.io/collector/consumer/pdata"
"go.opentelemetry.io/collector/receiver/hostmetricsreceiver/internal"
"go.opentelemetry.io/collector/receiver/hostmetricsreceiver/internal/metadata"
)
const metricsLen = 3
// scraper for Load Metrics
type scraper struct {
logger *zap.Logger
config *Config
// for mocking
load func() (*load.AvgStat, error)
}
// newLoadScraper creates a set of Load related metrics
func newLoadScraper(_ context.Context, logger *zap.Logger, cfg *Config) *scraper {
return &scraper{logger: logger, config: cfg, load: getSampledLoadAverages}
}
// start
func (s *scraper) start(ctx context.Context, _ component.Host) error {
return startSampling(ctx, s.logger)
}
// shutdown
func (s *scraper) shutdown(ctx context.Context) error {
return stopSampling(ctx)
}
// scrape
func (s *scraper) scrape(_ context.Context) (pdata.MetricSlice, error) {
metrics := pdata.NewMetricSlice()
now := internal.TimeToUnixNano(time.Now())
avgLoadValues, err := s.load()
if err != nil {
return metrics, consumererror.NewPartialScrapeError(err, metricsLen)
}
metrics.Resize(metricsLen)
initializeLoadMetric(metrics.At(0), metadata.Metrics.SystemCPULoadAverage1m, now, avgLoadValues.Load1)
initializeLoadMetric(metrics.At(1), metadata.Metrics.SystemCPULoadAverage5m, now, avgLoadValues.Load5)
initializeLoadMetric(metrics.At(2), metadata.Metrics.SystemCPULoadAverage15m, now, avgLoadValues.Load15)
return metrics, nil
}
func initializeLoadMetric(metric pdata.Metric, metricDescriptor metadata.Metric, now pdata.TimestampUnixNano, value float64) {
metricDescriptor.Init(metric)
idps := metric.DoubleGauge().DataPoints()
idps.Resize(1)
dp := idps.At(0)
dp.SetTimestamp(now)
dp.SetValue(value)
}