Debian Codegraph @

prometheus/testutil/promlint/validations/units.go

raw
1 // Copyright 2020 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package validations
15
16 import "strings"
17
18 // Units and their possible prefixes recognized by this library. More can be
19 // added over time as needed.
20 var (
21 // map a unit to the appropriate base unit.
22 units = map[string]string{
23 // Base units.
24 "amperes": "amperes",
25 "bytes": "bytes",
26 "celsius": "celsius", // Also allow Celsius because it is common in typical Prometheus use cases.
27 "grams": "grams",
28 "joules": "joules",
29 "kelvin": "kelvin", // SI base unit, used in special cases (e.g. color temperature, scientific measurements).
30 "meters": "meters", // Both American and international spelling permitted.
31 "metres": "metres",
32 "seconds": "seconds",
33 "volts": "volts",
34
35 // Non base units.
36 // Time.
37 "minutes": "seconds",
38 "hours": "seconds",
39 "days": "seconds",
40 "weeks": "seconds",
41 // Temperature.
42 "kelvins": "kelvin",
43 "fahrenheit": "celsius",
44 "rankine": "celsius",
45 // Length.
46 "inches": "meters",
47 "yards": "meters",
48 "miles": "meters",
49 // Bytes.
50 "bits": "bytes",
51 // Energy.
52 "calories": "joules",
53 // Mass.
54 "pounds": "grams",
55 "ounces": "grams",
56 }
57
58 unitPrefixes = []string{
59 "pico",
60 "nano",
61 "micro",
62 "milli",
63 "centi",
64 "deci",
65 "deca",
66 "hecto",
67 "kilo",
68 "kibi",
69 "mega",
70 "mibi",
71 "giga",
72 "gibi",
73 "tera",
74 "tebi",
75 "peta",
76 "pebi",
77 }
78
79 // Common abbreviations that we'd like to discourage.
80 unitAbbreviations = []string{
81 "s",
82 "ms",
83 "us",
84 "ns",
85 "sec",
86 "b",
87 "kb",
88 "mb",
89 "gb",
90 "tb",
91 "pb",
92 "m",
93 "h",
94 "d",
95 }
96 )
97
98 // metricUnits attempts to detect known unit types used as part of a metric name,
99 // e.g. "foo_bytes_total" or "bar_baz_milligrams".
100 func metricUnits(m string) (unit, base string, ok bool) {
101 ss := strings.Split(m, "_")
102
103 for _, s := range ss {
104 if base, found := units[s]; found {
105 return s, base, true
106 }
107
108 for _, p := range unitPrefixes {
109 if strings.HasPrefix(s, p) {
110 if base, found := units[s[len(p):]]; found {
111 return s, base, true
112 }
113 }
114 }
115 }
116
117 return "", "", false
118 }