Debian Codegraph @

varnish_test.go

raw symbols SCIP
1 package main
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "runtime"
8 "testing"
9
10 "github.com/prometheus/client_golang/prometheus"
11 )
12
13 var testFileVersions = []string{"3.0.5", "4.0.5", "4.1.1", "5.2.0", "6.0.0", "6.5.1"}
14
15 func Test_VarnishVersion(t *testing.T) {
16 tests := map[string]*varnishVersion{
17 "varnishstat (varnish-6.5.1 revision 1dae23376bb5ea7a6b8e9e4b9ed95cdc9469fb64)": {
18 Major: 6, Minor: 5, Patch: 1, Revision: "1dae23376bb5ea7a6b8e9e4b9ed95cdc9469fb64",
19 },
20 "varnishstat (varnish-6.0.0 revision a068361dff0d25a0d85cf82a6e5fdaf315e06a7d)": {
21 Major: 6, Minor: 0, Patch: 0, Revision: "a068361dff0d25a0d85cf82a6e5fdaf315e06a7d",
22 },
23 "varnishstat (varnish-5.2.0 revision 4c4875cbf)": {
24 Major: 5, Minor: 2, Patch: 0, Revision: "4c4875cbf",
25 },
26 "varnishstat (varnish-4.1.10 revision 1d090c5a08f41c36562644bafcce9d3cb85d824f)": {
27 Major: 4, Minor: 1, Patch: 10, Revision: "1d090c5a08f41c36562644bafcce9d3cb85d824f",
28 },
29 "varnishstat (varnish-4.1.0 revision 3041728)": {
30 Major: 4, Minor: 1, Patch: 0, Revision: "3041728",
31 },
32 "varnishstat (varnish-4 revision)": {
33 Major: 4, Minor: -1, Patch: -1,
34 },
35 "varnishstat (varnish-3.0.5 revision 1a89b1f)": {
36 Major: 3, Minor: 0, Patch: 5, Revision: "1a89b1f",
37 },
38 "varnish 2.0": {
39 Major: 2, Minor: 0, Patch: -1,
40 },
41 "varnish 1": {
42 Major: 1, Minor: -1, Patch: -1,
43 },
44 }
45 for versionStr, test := range tests {
46 v := NewVarnishVersion()
47 if err := v.parseVersion(versionStr); err != nil {
48 t.Error(err.Error())
49 continue
50 }
51 if test.Major != v.Major ||
52 test.Minor != v.Minor ||
53 test.Patch != v.Patch ||
54 test.Revision != v.Revision {
55 t.Errorf("version mismatch on %q", versionStr)
56 continue
57 }
58 t.Logf("%q > %s\n", versionStr, v.String())
59 if !test.EqualsOrGreater(test.Major, test.Minor) {
60 t.Fatalf("%s does not satisfy itself", test)
61 }
62 if !test.EqualsOrGreater(test.Major-1, 0) {
63 t.Fatalf("%s should satisfy version %d.0", test, test.Major-1)
64 }
65 if test.EqualsOrGreater(test.Major, test.Minor+1) {
66 t.Fatalf("%s should not satisfy version %d.%d", test, test.Major, test.Minor+1)
67 }
68 }
69 }
70
71 func dummyBackendValue(backend string) (string, map[string]any) {
72 return fmt.Sprintf("VBE.%s.happy", backend), map[string]any{
73 "description": "Happy health probes",
74 "type": "VBE",
75 "ident": backend,
76 "flag": "b",
77 "format": "b",
78 "value": 0,
79 }
80 }
81
82 func matchStringSlices(s1, s2 []string) bool {
83 if len(s1) != len(s2) {
84 return false
85 }
86 for i, v1 := range s1 {
87 if s2[i] != v1 {
88 return false
89 }
90 }
91 return true
92 }
93
94 func Test_VarnishBackendNames(t *testing.T) {
95 for _, variant := range [][]string{
96 {"def0e7f7-a676-4eed-9d8b-78ef7ce21e93.us1_x.y-z:w", "us1_x.y-z:w", "def0e7f7-a676-4eed-9d8b-78ef7ce21e93"},
97 {"root:29813cbb-7329-4eb8-8969-26be2ef58c88.us2_x.y-z:w", "us2_x.y-z:w", "29813cbb-7329-4eb8-8969-26be2ef58c88"}, // ??
98 {"boot.default", "default", "unknown"},
99 {"reload_2019-08-29T100458.default", "default", "unknown"}, // varnish_reload_vcl in 4
100 {"reload_20191016_072034_54500.default", "default", "unknown"}, // varnishreload in 6+
101 {"ce19737f-72b5-4f4b-9d39-3d8c2d28240b.default", "default", "ce19737f-72b5-4f4b-9d39-3d8c2d28240b"},
102 } {
103 backend := variant[0]
104 expected_backend := variant[1]
105 expected_server := variant[2]
106
107 vName, data := dummyBackendValue(backend)
108 var (
109 vGroup = prometheusGroup(vName)
110 vDescription string
111 vIdentifier string
112 vErr error
113 )
114 if value, ok := data["description"]; ok {
115 if vDescription, ok = value.(string); !ok {
116 vErr = fmt.Errorf("%s description it not a string", vName)
117 }
118 }
119 if value, ok := data["ident"]; ok && vErr == nil {
120 if vIdentifier, ok = value.(string); !ok {
121 vErr = fmt.Errorf("%s ident it not a string", vName)
122 }
123 }
124 if vErr != nil {
125 t.Error(vErr)
126 return
127 }
128 // Varnish < 5.2
129 name_1, _, labelKeys_1, labelValues_1 := computePrometheusInfo(vName, vGroup, vIdentifier, vDescription)
130 computed_backend := findLabelValue("backend", labelKeys_1, labelValues_1)
131 computed_server := findLabelValue("server", labelKeys_1, labelValues_1)
132 t.Logf("%s > %s > %s\n", vName, backend, name_1)
133 t.Logf(" ident : %s\n", vIdentifier)
134 t.Logf(" backend : %s\n", computed_backend)
135 t.Logf(" server : %s\n", computed_server)
136
137 if expected_backend != computed_backend {
138 t.Fatalf("backend %q != %q", computed_backend, expected_backend)
139 }
140 if expected_server != computed_server {
141 t.Fatalf("server %q != %q", computed_server, expected_server)
142 }
143
144 // Varnish >= 5.2 no longer has 'ident', test that detected correctly from vName
145 name_2, _, labelKeys_2, labelValues_2 := computePrometheusInfo(vName, vGroup, "", vDescription)
146 if name_1 != name_2 {
147 t.Fatalf("name %q != %q", name_1, name_2)
148 }
149 if !matchStringSlices(labelKeys_1, labelKeys_2) {
150 t.Fatalf("labelKeys %#v != %#v", labelKeys_1, labelKeys_2)
151 }
152 if !matchStringSlices(labelValues_1, labelValues_2) {
153 t.Fatalf("labelKeys %#v != %#v", labelValues_1, labelValues_2)
154 }
155 }
156 }
157
158 func Test_VarnishMetrics(t *testing.T) {
159 dir, _ := os.Getwd()
160 if !fileExists(filepath.Join(dir, "test/scrape")) {
161 t.Skipf("Cannot find test/scrape files from workind dir %s", dir)
162 }
163 for _, version := range testFileVersions {
164 test := filepath.Join(dir, "test/scrape", version+".json")
165 VarnishVersion.parseVersion(version)
166 t.Logf("test scrape %s", VarnishVersion)
167
168 buf, err := os.ReadFile(test)
169 if err != nil {
170 t.Fatal(err.Error())
171 }
172 done := make(chan bool)
173 metrics := make(chan prometheus.Metric)
174 descs := []*prometheus.Desc{}
175 go func() {
176 for m := range metrics {
177 descs = append(descs, m.Desc())
178 }
179 done <- true
180 }()
181 _, err = ScrapeVarnishFrom(buf, metrics)
182 close(metrics)
183 <-done
184
185 if err != nil {
186 t.Fatal(err.Error())
187 }
188 t.Logf(" %d metrics", len(descs))
189 }
190 }
191
192 func Test_FindMostRecentVbeReloadPrefix(t *testing.T) {
193 type testConfig struct {
194 varnishCounters map[string]any
195 expectedMostRecentVbeReloadPrefix string
196 }
197
198 for _, testConfig := range []testConfig{
199 // Varnish <= 4.0 has no duplicated stats on reload
200 {map[string]any{
201 "VBE.default(127.0.0.1,,8080).happy": "any",
202 }, ""},
203 // Varnish 4.1 or later, not yet reloaded
204 {map[string]any{
205 "VBE.boot.default.happy": "any",
206 }, ""},
207 // Varnish 4.1, reloaded 2 times
208 {map[string]any{
209 "VBE.boot.default.happy": "any",
210 "VBE.reload_2019-08-29T100458.default.happy": "any",
211 "VBE.reload_2019-08-29T100459.default.happy": "any",
212 }, "VBE.reload_2019-08-29T100459"},
213 // Varnish 6+, reloaded 2 times
214 {map[string]any{
215 "VBE.boot.default.happy": "any",
216 "VBE.reload_20191016_072034_54500.default.happy": "any",
217 "VBE.reload_20191016_072034_54501.default.happy": "any",
218 }, "VBE.reload_20191016_072034_54501"},
219 } {
220 computedMostRecentVbeReloadPrefix := findMostRecentVbeReloadPrefix(testConfig.varnishCounters)
221 t.Logf("Varnish counters: %s\n", testConfig.varnishCounters)
222 t.Logf(" expected most recent prefix : '%s'\n", testConfig.expectedMostRecentVbeReloadPrefix)
223 t.Logf(" computed most recent prefix : '%s'\n", computedMostRecentVbeReloadPrefix)
224
225 if computedMostRecentVbeReloadPrefix != testConfig.expectedMostRecentVbeReloadPrefix {
226 t.Fatalf("mostRecentVbeReloadPrefix %q != %q", computedMostRecentVbeReloadPrefix, testConfig.expectedMostRecentVbeReloadPrefix)
227 }
228 }
229 }
230
231 func Test_IsOutdatedVbe(t *testing.T) {
232 type testConfig struct {
233 vName string
234 mostRecentVbeReloadPrefix string
235 expectedIsOutdatedVbe bool
236 }
237
238 for _, testConfig := range []testConfig{
239 {"MGT.uptime", "", false}, // not VBE
240 {"MGT.uptime", "VBE.reload_20191016_072034_54500", false}, // not VBE
241 {"VBE.boot.default.conn", "", false}, // VCL not yet reloaded
242 {"VBE.boot.default.conn", "VBE.reload_20191016_072034_54500", true}, // VCL reloaded, 'boot' is now outdated
243 {"VBE.reload_20191016_072034_54500.default.conn", "VBE.reload_20191016_072034_54500", false}, // current VCL version
244 {"VBE.reload_20191016_072034_54499.default.conn", "VBE.reload_20191016_072034_54500", true}, // previous VCL version
245 } {
246 computedIsOutdatedVbe := isOutdatedVbe(testConfig.vName, testConfig.mostRecentVbeReloadPrefix)
247 t.Logf("'%s', '%s'\n", testConfig.vName, testConfig.mostRecentVbeReloadPrefix)
248 t.Logf(" expected outdated : %t\n", testConfig.expectedIsOutdatedVbe)
249 t.Logf(" computed outdated : %t\n", computedIsOutdatedVbe)
250
251 if computedIsOutdatedVbe != testConfig.expectedIsOutdatedVbe {
252 t.Fatalf("outdatedVbe %t != %t", computedIsOutdatedVbe, testConfig.expectedIsOutdatedVbe)
253 }
254 }
255 }
256
257 type testCollector struct {
258 filepath string
259 t *testing.T
260 }
261
262 func (tc *testCollector) Describe(ch chan<- *prometheus.Desc) {
263 }
264
265 func (tc *testCollector) Collect(ch chan<- prometheus.Metric) {
266 buf, err := os.ReadFile(tc.filepath)
267 if err != nil {
268 tc.t.Fatal(err.Error())
269 }
270 _, err = ScrapeVarnishFrom(buf, ch)
271
272 if err != nil {
273 tc.t.Fatal(err.Error())
274 }
275 }
276
277 func Test_PrometheusExport(t *testing.T) {
278 dir, _ := os.Getwd()
279 if !fileExists(filepath.Join(dir, "test/scrape")) {
280 t.Skipf("Cannot find test/scrape files from workind dir %s", dir)
281 }
282 for _, version := range testFileVersions {
283 test := filepath.Join(dir, "test/scrape", version+".json")
284 VarnishVersion.parseVersion(version)
285 t.Logf("test scrape %s", VarnishVersion)
286
287 registry := prometheus.NewRegistry()
288 collector := &testCollector{filepath: test, t: t}
289 registry.MustRegister(collector)
290
291 gathering, err := registry.Gather()
292 if err != nil {
293 errors, ok := err.(prometheus.MultiError)
294 if ok {
295 for _, e := range errors {
296 t.Errorf(" Error in prometheus Gather: %#v", e)
297 }
298 } else {
299 t.Errorf(" Error in prometheus Gather: %#v", err)
300 }
301 }
302
303 metricCount := 0
304
305 includesVarnishBackendHappy := false
306 for _, mf := range gathering {
307 if *mf.Name == "varnish_backend_happy" {
308 includesVarnishBackendHappy = true
309 }
310
311 metricCount += len(mf.Metric)
312 }
313
314 // Validate presence of a single metric, which is present across all versions
315 if !includesVarnishBackendHappy {
316 t.Error("Missing metric varnish_backend_happy")
317 }
318
319 t.Logf(" %d metrics", metricCount)
320 }
321 }
322
323 // Testing against a live varnish instance is only executed in build bot(s).
324 // This is because the usual end user setup requires tests to be ran with sudo in order to work.
325 func Test_VarnishMetrics_CI(t *testing.T) {
326 if runtime.GOOS != "linux" {
327 t.Skipf("Host needs to be linux to run live metrics test: %s", runtime.GOOS)
328 return
329 } else if os.Getenv("CONTINUOUS_INTEGRATION") != "true" {
330 t.Skip("Live metrics test only ran on CI")
331 return
332 }
333
334 if err := VarnishVersion.Initialize(); err != nil {
335 t.Fatal(err)
336 }
337
338 done := make(chan bool)
339 metrics := make(chan prometheus.Metric)
340 go func() {
341 for m := range metrics {
342 t.Logf("%s", m.Desc())
343 }
344 done <- true
345 }()
346 if _, err := ScrapeVarnish(metrics); err != nil {
347 t.Fatal(err)
348 }
349 close(metrics)
350 <-done
351 }