Debian Codegraph @

fs/metrics/layer/metrics.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package layermetrics
18
19 import (
20 "sync"
21
22 "github.com/containerd/stargz-snapshotter/fs/layer"
23 metrics "github.com/docker/go-metrics"
24 "github.com/prometheus/client_golang/prometheus"
25 )
26
27 func NewLayerMetrics(ns *metrics.Namespace) *Controller {
28 if ns == nil {
29 return &Controller{}
30 }
31 c := &Controller{
32 ns: ns,
33 layer: make(map[string]layer.Layer),
34 }
35 c.metrics = append(c.metrics, layerMetrics...)
36 ns.Add(c)
37 return c
38 }
39
40 type Controller struct {
41 ns *metrics.Namespace
42 metrics []*metric
43
44 layer map[string]layer.Layer
45 layerMu sync.RWMutex
46 }
47
48 func (c *Controller) Describe(ch chan<- *prometheus.Desc) {
49 for _, e := range c.metrics {
50 ch <- e.desc(c.ns)
51 }
52 }
53
54 func (c *Controller) Collect(ch chan<- prometheus.Metric) {
55 c.layerMu.RLock()
56 wg := &sync.WaitGroup{}
57 for mp, l := range c.layer {
58 mp, l := mp, l
59 wg.Add(1)
60 go func() {
61 defer wg.Done()
62 for _, e := range c.metrics {
63 e.collect(mp, l, c.ns, ch)
64 }
65 }()
66 }
67 c.layerMu.RUnlock()
68 wg.Wait()
69 }
70
71 func (c *Controller) Add(key string, l layer.Layer) {
72 if c.ns == nil {
73 return
74 }
75 c.layerMu.Lock()
76 c.layer[key] = l
77 c.layerMu.Unlock()
78 }
79
80 func (c *Controller) Remove(key string) {
81 if c.ns == nil {
82 return
83 }
84 c.layerMu.Lock()
85 delete(c.layer, key)
86 c.layerMu.Unlock()
87 }
88
89 type value struct {
90 v float64
91 l []string
92 }
93
94 type metric struct {
95 name string
96 help string
97 unit metrics.Unit
98 vt prometheus.ValueType
99 labels []string
100 // getValues returns the value and labels for the data
101 getValues func(l layer.Layer) []value
102 }
103
104 func (m *metric) desc(ns *metrics.Namespace) *prometheus.Desc {
105 return ns.NewDesc(m.name, m.help, m.unit, append([]string{"digest", "mountpoint"}, m.labels...)...)
106 }
107
108 func (m *metric) collect(mountpoint string, l layer.Layer, ns *metrics.Namespace, ch chan<- prometheus.Metric) {
109 values := m.getValues(l)
110 for _, v := range values {
111 ch <- prometheus.MustNewConstMetric(m.desc(ns), m.vt, v.v, append([]string{l.Info().Digest.String(), mountpoint}, v.l...)...)
112 }
113 }