Debian Codegraph @

instrumentation/host/host.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package host // import "go.opentelemetry.io/contrib/instrumentation/host"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "math"
11 "os"
12 "sync"
13
14 "github.com/shirou/gopsutil/v4/cpu"
15 "github.com/shirou/gopsutil/v4/mem"
16 "github.com/shirou/gopsutil/v4/net"
17 "github.com/shirou/gopsutil/v4/process"
18 "go.opentelemetry.io/otel"
19 "go.opentelemetry.io/otel/attribute"
20 "go.opentelemetry.io/otel/metric"
21 "go.opentelemetry.io/otel/semconv/v1.40.0/processconv"
22 "go.opentelemetry.io/otel/semconv/v1.40.0/systemconv"
23 )
24
25 // ScopeName is the instrumentation scope name.
26 const ScopeName = "go.opentelemetry.io/contrib/instrumentation/host"
27
28 // Host reports the work-in-progress conventional host metrics specified by OpenTelemetry.
29 type host struct {
30 config config
31 meter metric.Meter
32 }
33
34 // config contains optional settings for reporting host metrics.
35 type config struct {
36 // MeterProvider sets the metric.MeterProvider. If nil, the global
37 // Provider will be used.
38 MeterProvider metric.MeterProvider
39 }
40
41 // Option supports configuring optional settings for host metrics.
42 type Option interface {
43 apply(*config)
44 }
45
46 // WithMeterProvider sets the Metric implementation to use for
47 // reporting. If this option is not used, the global metric.MeterProvider
48 // will be used. `provider` must be non-nil.
49 func WithMeterProvider(provider metric.MeterProvider) Option {
50 return metricProviderOption{provider}
51 }
52
53 type metricProviderOption struct{ metric.MeterProvider }
54
55 func (o metricProviderOption) apply(c *config) {
56 if o.MeterProvider != nil {
57 c.MeterProvider = o.MeterProvider
58 }
59 }
60
61 // Attribute sets.
62 var (
63 // Attribute sets for CPU time measurements.
64
65 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
66 AttributeCPUTimeUser = attribute.NewSet(attribute.String("state", "user"))
67 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
68 AttributeCPUTimeSystem = attribute.NewSet(attribute.String("state", "system"))
69 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
70 AttributeCPUTimeOther = attribute.NewSet(attribute.String("state", "other"))
71 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
72 AttributeCPUTimeIdle = attribute.NewSet(attribute.String("state", "idle"))
73
74 // Attribute sets used for Memory measurements.
75
76 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
77 AttributeMemoryAvailable = attribute.NewSet(attribute.String("state", "available"))
78 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
79 AttributeMemoryUsed = attribute.NewSet(attribute.String("state", "used"))
80
81 // Attribute sets used for Network measurements.
82
83 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
84 AttributeNetworkTransmit = attribute.NewSet(attribute.String("direction", "transmit"))
85 // Deprecated: Use go.opentelemetry.io/otel/semconv instead.
86 AttributeNetworkReceive = attribute.NewSet(attribute.String("direction", "receive"))
87 )
88
89 // newConfig computes a config from a list of Options.
90 func newConfig(opts ...Option) config {
91 c := config{
92 MeterProvider: otel.GetMeterProvider(),
93 }
94 for _, opt := range opts {
95 opt.apply(&c)
96 }
97 return c
98 }
99
100 // Start initializes reporting of host metrics using the supplied config.
101 func Start(opts ...Option) error {
102 c := newConfig(opts...)
103 if c.MeterProvider == nil {
104 c.MeterProvider = otel.GetMeterProvider()
105 }
106 h := &host{
107 meter: c.MeterProvider.Meter(
108 ScopeName,
109 metric.WithInstrumentationVersion(Version),
110 ),
111 config: c,
112 }
113 return h.register()
114 }
115
116 func (h *host) register() error {
117 var (
118 err error
119
120 procCPUTime processconv.CPUTime
121 procCPUTimeModeUser = metric.WithAttributes(
122 procCPUTime.AttrCPUMode(processconv.CPUModeUser),
123 )
124 procCPUTimeModeSystem = metric.WithAttributes(
125 procCPUTime.AttrCPUMode(processconv.CPUModeSystem),
126 )
127
128 cpuTime systemconv.CPUTime
129 cpuTimeModeUser = metric.WithAttributes(
130 cpuTime.AttrCPUMode(systemconv.CPUModeUser),
131 )
132 cpuTimeModeSystem = metric.WithAttributes(
133 cpuTime.AttrCPUMode(systemconv.CPUModeSystem),
134 )
135 cpuTimeModeIdle = metric.WithAttributes(
136 cpuTime.AttrCPUMode(systemconv.CPUModeIdle),
137 )
138 cpuTimeModeOther = metric.WithAttributes(
139 cpuTime.AttrCPUMode(systemconv.CPUModeAttr("other")),
140 )
141
142 memUse systemconv.MemoryUsage
143 memUseStateFree = metric.WithAttributes(
144 memUse.AttrMemoryState(systemconv.MemoryStateFree),
145 )
146 memUseStateUsed = metric.WithAttributes(
147 memUse.AttrMemoryState(systemconv.MemoryStateUsed),
148 )
149
150 memUtil systemconv.MemoryUtilization
151 memUtilStateFree = metric.WithAttributes(
152 memUtil.AttrMemoryState(systemconv.MemoryStateFree),
153 )
154 memUtilStateUsed = metric.WithAttributes(
155 memUtil.AttrMemoryState(systemconv.MemoryStateUsed),
156 )
157
158 netIO systemconv.NetworkIO
159 netIOStateTransmit = metric.WithAttributes(
160 netIO.AttrNetworkIODirection(systemconv.NetworkIODirectionTransmit),
161 )
162 netIOStateReceive = metric.WithAttributes(
163 netIO.AttrNetworkIODirection(systemconv.NetworkIODirectionReceive),
164 )
165
166 // lock prevents a race between batch observer and instrument registration.
167 lock sync.Mutex
168 )
169
170 pid := os.Getpid()
171 if pid > math.MaxInt32 || pid < math.MinInt32 {
172 return fmt.Errorf("invalid process ID: %d", pid)
173 }
174 proc, err := process.NewProcess(int32(pid))
175 if err != nil {
176 return fmt.Errorf("could not find this process: %w", err)
177 }
178
179 lock.Lock()
180 defer lock.Unlock()
181
182 if procCPUTime, err = processconv.NewCPUTime(h.meter); err != nil {
183 return err
184 }
185 if cpuTime, err = systemconv.NewCPUTime(h.meter); err != nil {
186 return err
187 }
188 if memUse, err = systemconv.NewMemoryUsage(h.meter); err != nil {
189 return err
190 }
191 if memUtil, err = systemconv.NewMemoryUtilization(h.meter); err != nil {
192 return err
193 }
194 if netIO, err = systemconv.NewNetworkIO(h.meter); err != nil {
195 return err
196 }
197
198 _, err = h.meter.RegisterCallback(
199 func(ctx context.Context, o metric.Observer) error {
200 lock.Lock()
201 defer lock.Unlock()
202
203 // This follows the OpenTelemetry Collector's "hostmetrics"
204 // receiver/hostmetricsreceiver/internal/scraper/processscraper
205 // measures User and System IOwait time.
206 // TODO: the Collector has per-OS compilation modules to support
207 // specific metrics that are not universal.
208 processTimes, err := proc.TimesWithContext(ctx)
209 if err != nil {
210 return err
211 }
212
213 hostTimeSlice, err := cpu.TimesWithContext(ctx, false)
214 if err != nil {
215 return err
216 }
217 if len(hostTimeSlice) != 1 {
218 return errors.New("host CPU usage: incorrect summary count")
219 }
220
221 vmStats, err := mem.VirtualMemoryWithContext(ctx)
222 if err != nil {
223 return err
224 }
225
226 ioStats, err := net.IOCountersWithContext(ctx, false)
227 if err != nil {
228 return err
229 }
230 if len(ioStats) != 1 {
231 return errors.New("host network usage: incorrect summary count")
232 }
233
234 hostTime := hostTimeSlice[0]
235 o.ObserveFloat64(procCPUTime.Inst(), processTimes.User, procCPUTimeModeUser)
236 o.ObserveFloat64(procCPUTime.Inst(), processTimes.System, procCPUTimeModeSystem)
237
238 o.ObserveFloat64(cpuTime.Inst(), hostTime.User, cpuTimeModeUser)
239 o.ObserveFloat64(cpuTime.Inst(), hostTime.System, cpuTimeModeSystem)
240
241 // TODO(#244): "other" is a placeholder for actually dealing
242 // with these states. Do users actually want this
243 // (unconditionally)? How should we handle "iowait"
244 // if not all systems expose it? Should we break
245 // these down by CPU? If so, are users going to want
246 // to aggregate in-process? See:
247 // https://github.com/open-telemetry/opentelemetry-go-contrib/issues/244
248 other := hostTime.Nice +
249 hostTime.Iowait +
250 hostTime.Irq +
251 hostTime.Softirq +
252 hostTime.Steal +
253 hostTime.Guest +
254 hostTime.GuestNice
255
256 o.ObserveFloat64(cpuTime.Inst(), other, cpuTimeModeOther)
257 o.ObserveFloat64(cpuTime.Inst(), hostTime.Idle, cpuTimeModeIdle)
258
259 // Host memory usage
260 o.ObserveInt64(memUse.Inst(), clampInt64(vmStats.Used), memUseStateUsed)
261 o.ObserveInt64(memUse.Inst(), clampInt64(vmStats.Available), memUseStateFree)
262
263 // Host memory utilization
264 o.ObserveFloat64(
265 memUtil.Inst(),
266 float64(vmStats.Used)/float64(vmStats.Total), memUtilStateUsed,
267 )
268 o.ObserveFloat64(
269 memUtil.Inst(),
270 float64(vmStats.Available)/float64(vmStats.Total),
271 memUtilStateFree,
272 )
273
274 // Host network usage
275 //
276 // TODO: These can be broken down by network
277 // interface, with similar questions to those posed
278 // about per-CPU measurements above.
279 o.ObserveInt64(
280 netIO.Inst(),
281 clampInt64(ioStats[0].BytesSent),
282 netIOStateTransmit,
283 )
284 o.ObserveInt64(
285 netIO.Inst(),
286 clampInt64(ioStats[0].BytesRecv),
287 netIOStateReceive,
288 )
289
290 return nil
291 },
292 procCPUTime.Inst(),
293 cpuTime.Inst(),
294 memUse.Inst(),
295 memUtil.Inst(),
296 netIO.Inst(),
297 )
298 if err != nil {
299 return err
300 }
301
302 return nil
303 }
304
305 func clampInt64(v uint64) int64 {
306 if v > math.MaxInt64 {
307 return math.MaxInt64
308 }
309 return int64(v)
310 }