Repository navigation
Expand file tree
/
Copy pathengine_requests_test.go
More file actions
1485 lines (1399 loc) · 60.8 KB
/
Copy pathengine_requests_test.go
File metadata and controls
1485 lines (1399 loc) · 60.8 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2026 Netdata Inc. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
package gosnmp
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"io"
"maps"
"net"
"net/netip"
"os"
"os/exec"
"runtime"
"slices"
"sync/atomic"
"syscall"
"testing"
"testing/synctest"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/netdata/gosnmp/internal/ber"
)
var engineGolden = goldenFiles{dir: "testdata/engine", title: "Engine"}
const engineOID = ".1.3.6.1.2.1.1.1.0"
// engineScenario is one v1/v2c request run against a scripted agent.
type engineScenario struct {
v1 bool // SNMPv1 instead of SNMPv2c
// config, when set, changes the client's configuration before NewClient.
config func(c *Config)
setup func(x *Client, c *fakeTransport)
// context, when set, gives the request's context, background unless
// set; its cancel runs when the scenario ends.
context func() (context.Context, context.CancelFunc)
agent engineAgent
run func(ctx context.Context, x *Client) (*Message, error) // a Get of engineOID unless set
}
// answer is an agent that answers every request at once with vbs.
func answer(vbs ...VarBind) engineAgent {
return answerWith(nil, vbs...)
}
// answerWith is an agent that answers every request at once with a reply
// changed by edit.
func answerWith(edit func(*Message), vbs ...VarBind) engineAgent {
return func(_ int, req []byte) []agentReply {
return []agentReply{{data: replyTo(req, edit, vbs...)}}
}
}
// errEngineCause is the cause a scenario cancels its context with.
var errEngineCause = errors.New("engine test cause")
// bareV3Report encodes an SNMPv3 noAuthNoPriv Report answering req whose
// msgData is the Report PDU itself, without the scoped PDU around it, so that
// a v1/v2c client reads it as the PDU after the SNMPv3 header.
func bareV3Report(req []byte, counter string) []byte {
return bareV3Answer(req, 7, Report, VarBind{Name: counter, Value: Counter32Value(1)})
}
// bareV3Answer is bareV3Report with msgID for a PDU of type pduType with vbs.
func bareV3Answer(req []byte, msgID uint32, pduType PDUType, vbs ...VarBind) []byte {
in, err := decodeMessage(req)
if err != nil {
panic(fmt.Sprintf("agent cannot decode the request: %v", err))
}
out := &Message{
Version: Version3, SecurityLevel: NoAuthNoPriv,
SecurityParameters: SecurityParameters{UserName: "public"},
PDUType: pduType, RequestID: in.RequestID, MsgID: msgID,
VarBinds: vbs,
}
b, err := out.Encode(nil)
if err != nil {
panic(fmt.Sprintf("agent cannot encode the reply: %v", err))
}
m, err := parseV3Message(b)
if err != nil {
panic(fmt.Sprintf("agent cannot read its reply: %v", err))
}
r := ber.NewReader(m.scoped)
for range 2 { // context engine ID and context name
if _, _, err = r.Next(); err != nil {
panic(err)
}
}
if m.scopedTag, m.scoped, err = r.Next(); err != nil {
panic(err)
}
return m.bytes()
}
// answerFromSecond is an agent that answers the requests from the second on
// with vbs.
func answerFromSecond(vbs ...VarBind) engineAgent {
return answerFrom(2, vbs...)
}
// answerFrom is an agent that answers the requests from the first-th on with
// vbs.
func answerFrom(first int, vbs ...VarBind) engineAgent {
return func(n int, req []byte) []agentReply {
if n < first {
return nil
}
return []agentReply{{data: replyTo(req, nil, vbs...)}}
}
}
// errCallerFailure is what the caller's code panics with in the panic
// scenarios.
var errCallerFailure = errors.New("the caller's code failed")
// panicWithError panics with errCallerFailure.
func panicWithError() { panic(errCallerFailure) }
// panicOnNilMap panics with a runtime error: an assignment to a nil map.
func panicOnNilMap() {
var m map[string]int
m["key"]++ //nolint:staticcheck // the runtime error is the point
}
// panicsOnce returns a transport function that panics through fail the first
// time it runs, which the transcript names as what with its number n.
func panicsOnce(c *fakeTransport, what string, fail func()) func(n int) error {
armed := true
return func(n int) error {
if armed {
armed = false
c.tr.addf("%s #%d panics", what, n)
fail()
}
return nil
}
}
// asAction drops the error of a transport function that never fails.
func asAction(f func(n int) error) func(n int) {
return func(n int) { _ = f(n) }
}
// atDeadline makes the fake connection run act as it sets deadline k in the
// future (counted from 1), the deadline of the k-th attempt it sees, before
// setting it.
func atDeadline(c *fakeTransport, k int, act func()) {
n := 0
c.beforeDeadline = func() {
if n++; n == k {
act()
}
}
}
// getAfterPanic runs a Get in which the caller's code panics (the scenario's
// setup arms it), records its result and what its error matches, then runs a
// second Get on the same client, whose result it returns.
func getAfterPanic(ctx context.Context, x *Client) (*Message, error) {
tr := x.conn.(*fakeTransport).tr
res, err := x.Get(ctx, []string{engineOID})
tr.addf("first request: %s", describeEngineResult(res, err))
var re runtime.Error
tr.addf("first request's error: matches the caller's error %t, a runtime.Error %t", errors.Is(err, errCallerFailure),
errors.As(err, &re))
return x.Get(ctx, []string{engineOID})
}
// answerRaw is an agent that answers every request with its sysDescr reply
// changed by edit as encoded octets.
func answerRaw(edit func(reply []byte) []byte) engineAgent {
return func(_ int, req []byte) []agentReply {
return []agentReply{{data: edit(replyTo(req, nil, sysDescr))}}
}
}
var sysDescr = VarBind{Name: engineOID, Value: OctetStringValue([]byte("codec agent"))}
// replySized is the reply to req of size octets, with one OctetString value.
func replySized(req []byte, size int) []byte {
n := size - 100
for {
r := replyTo(req, nil, VarBind{Name: engineOID, Value: OctetStringValue(bytes.Repeat([]byte{'x'}, n))})
if len(r) == size {
return r
}
n += size - len(r)
}
}
// errorStatusOutOfRange is the sysDescr reply to req, its request ID raised by
// idDelta, with the error status -1: the request ID decodes, then the PDU
// fails.
func errorStatusOutOfRange(req []byte, idDelta uint32) []byte {
r := replyTo(req, func(p *Message) { p.RequestID += idDelta }, sysDescr)
i := bytes.Index(r, []byte{byte(Integer), 1, 0, byte(Integer), 1, 0}) // error status and index
if i < 0 {
panic("no error status")
}
r[i+2] = 0xff
return r
}
// errEngineWrite is the error of a failing write in the engine scenarios.
var errEngineWrite = errors.New("codec write failure")
// refused is the error of a read from a UDP socket whose target port is
// closed.
var refused = &net.OpError{Op: "read", Net: "udp", Err: syscall.ECONNREFUSED}
// closedRead, closedWrite, closedSet and closedClose are the errors of a
// read, a write, a deadline and a Close on a UDP socket that net.Conn.Close
// closed.
var (
closedRead = &net.OpError{Op: "read", Net: "udp", Err: net.ErrClosed}
closedWrite = &net.OpError{Op: "write", Net: "udp", Err: net.ErrClosed}
closedSet = &net.OpError{Op: "set", Net: "udp", Err: net.ErrClosed}
closedClose = &net.OpError{Op: "close", Net: "udp", Err: net.ErrClosed}
)
// withEngineTimeout gives a context that times out after d.
func withEngineTimeout(d time.Duration) func() (context.Context, context.CancelFunc) {
return func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), d)
}
}
// nilContext gives a nil context, a caller's bug a request refuses.
func nilContext() (context.Context, context.CancelFunc) { return nil, func() {} }
// canceledContext gives a context canceled before the request starts.
func canceledContext() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx, cancel
}
// canceledAfter gives a context canceled after d. A cancellation at the
// instant an attempt's deadline passes races the read's timeout, so scenarios
// cancel between attempt boundaries.
func canceledAfter(d time.Duration) func() (context.Context, context.CancelFunc) {
return func() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(d, cancel)
return ctx, cancel
}
}
// canceledBeforeDeadline gives a context with deadline d, canceled after
// cancelAt.
func canceledBeforeDeadline(cancelAt, d time.Duration) func() (context.Context, context.CancelFunc) {
return func() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), d)
time.AfterFunc(cancelAt, cancel)
return ctx, cancel
}
}
// unreportedDeadline is a context with a deadline that it does not report as
// passed: on a real clock, the moment between the deadline and the timer that
// cancels the context, which a synctest bubble never shows.
type unreportedDeadline struct {
context.Context
deadline time.Time
}
func (c unreportedDeadline) Deadline() (time.Time, bool) { return c.deadline, true }
// withUnreportedDeadline gives an unreportedDeadline context with deadline d.
func withUnreportedDeadline(d time.Duration) func() (context.Context, context.CancelFunc) {
return func() (context.Context, context.CancelFunc) {
return unreportedDeadline{context.Background(), time.Now().Add(d)}, func() {}
}
}
// doneAtErrCall gives a context that is done with err as its Err method is
// called the n-th time, as if canceled, or its deadline passed, just then: a
// request checks its context before each attempt and after each failed one,
// so n picks a point between two attempts. It reports no deadline.
func doneAtErrCall(n int, err error) func() (context.Context, context.CancelFunc) {
return func() (context.Context, context.CancelFunc) {
return &doneAtErr{Context: context.Background(), n: int64(n), err: err, done: make(chan struct{})}, func() {}
}
}
// doneAtErr is the context of doneAtErrCall; context.AfterFunc reads it on a
// goroutine of its own.
type doneAtErr struct {
context.Context
n int64
calls atomic.Int64
err error
done chan struct{}
}
func (c *doneAtErr) Done() <-chan struct{} { return c.done }
func (c *doneAtErr) Err() error {
switch n := c.calls.Add(1); {
case n == c.n:
close(c.done)
fallthrough
case n > c.n:
return c.err
}
return nil
}
func getOIDs(oids ...string) func(ctx context.Context, x *Client) (*Message, error) {
return func(ctx context.Context, x *Client) (*Message, error) { return x.Get(ctx, oids) }
}
// engineScenarios are the request scenarios of TestEngineRequestCharacterization.
func engineScenarios() map[string]engineScenario {
twoGets := func(ctx context.Context, x *Client) (*Message, error) {
if _, err := x.Get(ctx, []string{engineOID}); err != nil {
return nil, fmt.Errorf("first Get: %w", err)
}
return x.Get(ctx, []string{engineOID})
}
maxOIDs2 := func(c *Config) { c.MaxOids = 2 }
twoOIDs := []string{engineOID, ".1.3.6.1.2.1.1.3.0"}
threeOIDs := []string{engineOID, ".1.3.6.1.2.1.1.3.0", ".1.3.6.1.2.1.1.5.0"}
scenarios := map[string]engineScenario{
// Operations.
"get": {agent: answer(sysDescr)},
"get/v1": {v1: true, agent: answer(sysDescr)},
"mk-snmp-packet": {agent: answer(sysDescr), run: func(ctx context.Context, x *Client) (*Message, error) {
return x.send(ctx, x.NewMessage(GetBulkRequest, []VarBind{{Name: ".1.3.6.1.2.1.1", Value: NullValue()}}, 2, 7))
}},
"get/invalid-oid": {agent: answer(), run: getOIDs(".1.3.6.1.x")},
// The MaxOids limit, at 2.
"get/max-oids/at-limit": {agent: answer(sysDescr), config: maxOIDs2, run: getOIDs(twoOIDs...)},
"get/max-oids/over-limit": {agent: answer(sysDescr), config: maxOIDs2, run: getOIDs(threeOIDs...)},
// A client Connect never connected.
"get/no-conn": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.conn = nil }},
// Timeouts and retries.
"timeout": {},
"timeout/no-retries": {config: func(c *Config) { c.Retries = 0 }},
// The configured Timeout bounds each attempt.
"timeout/configured": {config: func(c *Config) { c.Timeout = 3 * time.Second }},
// A zero Timeout means 1 s.
"timeout/zero": {agent: answer(sysDescr), config: func(c *Config) { c.Timeout = 0 }},
"answer/second-attempt": {agent: answerFromSecond(sysDescr)},
// Reply matching.
"answer/late": {agent: func(n int, req []byte) []agentReply {
if n == 1 {
return []agentReply{{data: replyTo(req, nil, sysDescr), after: 1500 * time.Millisecond}}
}
return nil
}},
"answer/late-by-two-attempts": {agent: func(n int, req []byte) []agentReply {
if n == 1 {
return []agentReply{{data: replyTo(req, nil, sysDescr), after: 2500 * time.Millisecond}}
}
return nil
}},
"answer/late-reply-read-by-next-request": {run: twoGets, agent: func(n int, req []byte) []agentReply {
switch n {
case 1:
return []agentReply{{data: replyTo(req, nil, sysDescr), after: 1500 * time.Millisecond}}
case 2:
return []agentReply{{data: replyTo(req, nil, sysDescr)}}
default:
return []agentReply{{data: replyTo(req, nil, sysDescr), after: 800 * time.Millisecond}}
}
}},
"answer/duplicated": {run: twoGets, agent: func(_ int, req []byte) []agentReply {
r := replyTo(req, nil, sysDescr)
return []agentReply{{data: r}, {data: r}}
}},
"answer/first-result-after-second-get": {
run: func(ctx context.Context, x *Client) (*Message, error) {
first, err := x.Get(ctx, []string{engineOID})
if err != nil {
return nil, fmt.Errorf("first Get: %w", err)
}
if _, err := x.Get(ctx, []string{engineOID}); err != nil {
return nil, fmt.Errorf("second Get: %w", err)
}
return first, nil
},
agent: func(n int, req []byte) []agentReply {
value := fmt.Sprintf("codec agent %d", n)
return []agentReply{{data: replyTo(req, nil, VarBind{Name: engineOID, Value: OctetStringValue([]byte(value))})}}
},
},
"answer/wrong-id": {agent: answerWith(func(p *Message) { p.RequestID += 100 }, sysDescr)},
"answer/zero-id": {
agent: answerWith(func(p *Message) { p.RequestID = 0 }, sysDescr),
},
"answer/v1-trap": {
agent: func(int, []byte) []agentReply {
trap := &Message{
Version: Version1, Community: "public", PDUType: Trap, VarBinds: []VarBind{sysDescr},
Enterprise: ".1.3.6.1.4.1.8072", AgentAddress: netip.MustParseAddr("127.0.0.2"), GenericTrap: 6, SpecificTrap: 1,
}
b, err := trap.Encode(nil)
if err != nil {
panic(err)
}
return []agentReply{{data: b}}
},
},
"answer/empty": {agent: answerWith(nil)},
"answer/empty-wrong-id": {
agent: answerWith(func(p *Message) { p.RequestID += 100 }),
},
"answer/empty-with-error-status-wrong-id": {agent: answerWith(func(p *Message) { p.RequestID += 100; p.ErrorStatus = GenErr })},
"answer/error-status": {agent: answerWith(func(p *Message) { p.ErrorStatus, p.ErrorIndex = NoSuchName, 1 }, VarBind{Name: engineOID, Value: NullValue()})},
// Error statuses as agents send them: the request's varbinds echoed
// (RFC 3416 section 4.2.1), none for tooBig, an index past them, and a
// status RFC 3416 does not name.
"answer/error-status/gen-err": {agent: answerWith(func(p *Message) { p.ErrorStatus, p.ErrorIndex = GenErr, 1 }, VarBind{Name: engineOID, Value: NullValue()})},
"answer/error-status/too-big": {agent: answerWith(func(p *Message) { p.ErrorStatus = TooBig })},
"answer/error-status/index-past": {agent: answerWith(func(p *Message) { p.ErrorStatus, p.ErrorIndex = NoAccess, 5 }, VarBind{Name: engineOID, Value: NullValue()})},
"answer/error-status/unknown": {agent: answerWith(func(p *Message) { p.ErrorStatus, p.ErrorIndex = InconsistentName+1, 1 }, sysDescr)},
"answer/error-status/v1-no-such-name": {
v1: true, agent: answerWith(func(p *Message) { p.ErrorStatus, p.ErrorIndex = NoSuchName, 1 }, VarBind{Name: engineOID, Value: NullValue()}),
},
"answer/not-a-response": {
agent: answerWith(func(p *Message) { p.PDUType = GetRequest }, sysDescr),
},
"answer/reflected-request": {
agent: func(_ int, req []byte) []agentReply { return []agentReply{{data: bytes.Clone(req)}} },
},
"answer/report": {
agent: answerWith(func(p *Message) { p.PDUType = Report }, sysDescr),
},
"answer/unknown-pdu-type": {
agent: answerRaw(func(r []byte) []byte {
r[bytes.IndexByte(r, byte(Response))] = 0xaf
return r
}),
},
"answer/other-version": {
agent: answerWith(func(p *Message) { p.Version = Version1 }, sysDescr),
},
// Replies that answer nothing, each followed by the answer.
"answer/other-version-then-valid": {agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replyTo(req, func(p *Message) { p.Version = Version1 }, sysDescr)}, {data: replyTo(req, nil, sysDescr)}}
}},
"answer/zero-id-then-valid": {agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replyTo(req, func(p *Message) { p.RequestID = 0 }, sysDescr)}, {data: replyTo(req, nil, sysDescr)}}
}},
"answer/empty-wrong-id-then-valid": {agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replyTo(req, func(p *Message) { p.RequestID += 100 })}, {data: replyTo(req, nil, sysDescr)}}
}},
"answer/other-version-v3": {
agent: answerWith(func(p *Message) {
p.Version, p.SecurityLevel = Version3, NoAuthNoPriv
p.SecurityParameters = SecurityParameters{UserName: "public"}
}, sysDescr),
},
"answer/other-version-v3-report": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: bareV3Report(req, usmStatsUnknownUserNames)}}
},
},
"answer/other-version-v3-unknown-engine-report": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: bareV3Report(req, usmStatsUnknownEngineIDs)}}
},
},
"answer/other-version-v3-msg-id-zero": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: bareV3Answer(req, 0, Report, VarBind{Name: usmStatsUnknownUserNames, Value: Counter32Value(1)})}}
},
},
"answer/other-version-v3-get-response": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: bareV3Answer(req, 7, Response, sysDescr)}}
},
},
"answer/other-community": {agent: answerWith(func(p *Message) { p.Community = "private" }, sysDescr)},
"answer/garbage-then-valid": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: garbage}, {data: replyTo(req, nil, sysDescr)}}
},
},
"answer/garbage": {agent: func(int, []byte) []agentReply { return []agentReply{{data: garbage}} }},
// A reply with the request's ID whose PDU does not decode, then a
// datagram another sender sent.
"answer/undecodable-then-garbage": {agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: errorStatusOutOfRange(req, 0)}, {data: garbage}}
}},
"answer/undecodable-other-request": {agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: errorStatusOutOfRange(req, 100)}}
}},
// The largest datagram the receive buffer accepts.
"answer/largest-udp": {
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replySized(req, rxBufSize-1)}}
},
},
// A datagram that fills the receive buffer, which may have been cut
// short: the attempt fails, and the retry uses the same socket.
"answer/too-big-udp": {
config: func(c *Config) { c.Retries = 1 },
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replySized(req, rxBufSize)}}
},
},
// Transport errors.
"write-error/once": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failWrite = func(n int) error { return map[int]error{1: errEngineWrite}[n] }
}},
"write-error/always": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failWrite = func(int) error { return errEngineWrite }
}},
"write-error/timeout-in-text": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failWrite = func(int) error { return errors.New("codec timeout of the write queue") }
}},
"deadline-error": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.deadlineErr = errors.New("codec deadline failure")
}},
"read-error/once": {agent: answerFromSecond(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failRead = func(n int) error { return map[int]error{1: refused}[n] }
}},
"read-error/always": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failRead = func(int) error { return refused }
}},
// The connection closed under the read and under the write: from then
// on its deadline cannot be set either.
"read-error/closed": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failRead = func(int) error {
c.deadlineErr = closedSet
return closedRead
}
}},
"write-error/closed": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failWrite = func(int) error {
c.deadlineErr = closedSet
return closedWrite
}
}},
"read-eof/udp": {agent: answerFromSecond(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failRead = func(n int) error { return map[int]error{1: io.EOF}[n] }
}},
// The request's context.
"context/canceled-before": {agent: answer(sysDescr), context: canceledContext},
// A nil context fails the request before it is sent.
"context/nil": {agent: answer(sysDescr), context: nilContext},
"context/canceled-with-cause-before": {agent: answer(sysDescr), context: func() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(context.Background())
cancel(errEngineCause)
return ctx, func() { cancel(nil) }
}},
// A context canceled with a cause during an attempt ends the request
// with context.Canceled too, not the cause.
"context/canceled-with-cause-while-waiting": {context: func() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(context.Background())
time.AfterFunc(300*time.Millisecond, func() { cancel(errEngineCause) })
return ctx, func() { cancel(nil) }
}},
"context/deadline-equal-to-timeout": {
context: withEngineTimeout(time.Second),
config: func(c *Config) { c.Retries = 0 },
},
"context/deadline-in-first-attempt": {context: withEngineTimeout(700 * time.Millisecond)},
"context/deadline-in-third-attempt": {context: withEngineTimeout(2500 * time.Millisecond)},
"context/deadline-after-all-attempts": {context: withEngineTimeout(time.Hour)},
// A context canceled after the decision to retry, before the next
// attempt starts: the attempt does not start.
"context/canceled-between-attempts": {context: doneAtErrCall(3, context.Canceled)},
// The deadline rule does not wait for the context to report its
// deadline, also when the deadlines are equal.
"context/deadline-unreported-in-first-attempt": {context: withUnreportedDeadline(700 * time.Millisecond)},
"context/deadline-unreported-equal-to-timeout": {
context: withUnreportedDeadline(time.Second),
config: func(c *Config) { c.Retries = 0 },
},
// A context whose deadline passed ends the request after an attempt
// that failed otherwise, before the decision to retry.
"context/deadline-passed-in-conn-write": {
context: withEngineTimeout(700 * time.Millisecond),
setup: func(_ *Client, c *fakeTransport) {
c.afterWrite = func(n int) {
c.tr.addf("the Conn's write #%d takes 1s", n)
time.Sleep(time.Second)
}
c.failRead = func(int) error { return refused }
},
},
// A context canceled before its deadline ends the attempt and the
// request at the cancellation, with context.Canceled.
"context/canceled-before-deadline": {context: canceledBeforeDeadline(300*time.Millisecond, 700*time.Millisecond)},
"context/canceled-while-waiting": {context: canceledAfter(300 * time.Millisecond)},
"context/canceled-in-last-attempt": {context: canceledAfter(2300 * time.Millisecond)},
// A context canceled while the reply is on its way, its interrupt held
// until after the reply: the request ends when the interrupt does, so
// that its deadline cannot reach a later request.
"context/canceled-before-a-reply": {
context: canceledAfter(50 * time.Millisecond),
agent: func(_ int, req []byte) []agentReply {
return []agentReply{{data: replyTo(req, nil, sysDescr), after: 100 * time.Millisecond}}
},
setup: func(_ *Client, c *fakeTransport) {
hold := make(chan struct{})
c.holdInterrupt = hold
go func() {
time.Sleep(200 * time.Millisecond)
c.tr.addf("interrupt released")
close(hold)
}()
},
},
// A Close while the canceled context's interrupt still sets its
// deadline, held until 200 ms: Close closes the connection without
// waiting for the interrupt, and the request ends when the interrupt
// does.
"context/canceled-then-closed-while-interrupting": {
context: canceledAfter(50 * time.Millisecond),
setup: func(x *Client, c *fakeTransport) {
hold := make(chan struct{})
c.holdInterrupt = hold
time.AfterFunc(100*time.Millisecond, func() {
c.tr.addf("Close from another goroutine")
_ = x.Close()
c.tr.addf("Close returned")
})
time.AfterFunc(200*time.Millisecond, func() {
c.tr.addf("interrupt released")
close(hold)
})
},
},
// A context canceled after its request leaves the connection alone:
// the next request, with another context, is answered.
"context/canceled-after-request": {agent: answer(sysDescr), run: func(ctx context.Context, x *Client) (*Message, error) {
first, cancel := context.WithCancel(ctx)
defer cancel()
if _, err := x.Get(first, []string{engineOID}); err != nil {
return nil, fmt.Errorf("first Get: %w", err)
}
cancel()
synctest.Wait()
return x.Get(ctx, []string{engineOID})
}},
// Close.
"close/before-request": {
agent: answer(sysDescr),
setup: func(x *Client, _ *fakeTransport) { _ = x.Close() },
},
"close/during-attempt": {
agent: answerFromSecond(sysDescr),
setup: func(x *Client, c *fakeTransport) {
c.afterWrite = func(n int) {
c.tr.addf("the Conn's write #%d closes the client", n)
_ = x.Close()
}
},
},
// A Close before the second attempt sets its deadline: the attempt
// ends without a write.
"close/between-attempts": {
agent: answerFromSecond(sysDescr),
setup: func(x *Client, c *fakeTransport) {
atDeadline(c, 2, func() {
c.tr.addf("the Conn, setting deadline #2, closes the client")
_ = x.Close()
})
},
},
// A Close after the reply was read: the reply answers the request.
"close/after-the-reply": {agent: answer(sysDescr), setup: func(x *Client, c *fakeTransport) {
c.afterRead = func(n int) {
c.tr.addf("the Conn's read #%d closes the client", n)
_ = x.Close()
}
}},
// The client closed from another goroutine, as Netdata's SNMP topology
// does when its context ends, while the request waits.
"close/from-another-goroutine": {setup: func(x *Client, _ *fakeTransport) {
go func() {
time.Sleep(300 * time.Millisecond)
_ = x.Close()
}()
}},
// Request IDs.
"request-id/wraps": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.requestID = 0x7FFFFFFF }},
"request-id/wraps-between-attempts": {agent: answerFromSecond(sysDescr), setup: func(x *Client, _ *fakeTransport) {
x.requestID = 0x7FFFFFFE
}},
"request-id/set": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.requestID = 5 }},
// The Conn's code panics in a request, which ends.
"panics/write": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) {
c.failWrite = func(n int) error {
c.tr.addf("the Conn's write #%d panics", n)
panic("codec write failure")
}
}},
// The caller's code panics in a request, which ends; the next request
// on the client is answered.
"panics/write-error": {agent: answer(sysDescr), run: getAfterPanic, setup: func(_ *Client, c *fakeTransport) {
c.failWrite = panicsOnce(c, "the Conn's write", panicWithError)
}},
"panics/after-write-runtime-error": {agent: answer(sysDescr), run: getAfterPanic, setup: func(_ *Client, c *fakeTransport) {
c.afterWrite = asAction(panicsOnce(c, "the Conn, after its write", panicOnNilMap))
}},
"panics/after-read": {agent: answer(sysDescr), run: getAfterPanic, setup: func(_ *Client, c *fakeTransport) {
c.afterRead = asAction(panicsOnce(c, "the Conn, after its read", panicWithError))
}},
// A panic between two attempts, outside either.
"panics/before-retry-deadline": {agent: answerFromSecond(sysDescr), run: getAfterPanic, setup: func(_ *Client, c *fakeTransport) {
atDeadline(c, 2, func() {
c.tr.addf("the Conn, setting deadline #2, panics")
panicWithError()
})
}},
"panics/read": {agent: answer(sysDescr), run: getAfterPanic, setup: func(_ *Client, c *fakeTransport) {
c.failRead = func(n int) error {
if n == 1 {
c.tr.addf("the Conn's read #1 panics")
panicWithError()
}
return nil
}
}},
}
return scenarios
}
// TestEngineRequestCharacterization pins what the request engine does for
// v1/v2c requests: the messages it writes, the deadline of each attempt,
// which replies it accepts and what it returns.
// testdata/engine/requests.golden holds the transcripts.
func TestEngineRequestCharacterization(t *testing.T) {
scenarios := engineScenarios()
var results []goldenCase
for _, name := range slices.Sorted(maps.Keys(scenarios)) {
sc := scenarios[name]
var dump string
synctest.Test(t, func(t *testing.T) {
dump = runEngineScenario(t, sc)
})
results = append(results, goldenCase{name: "requests/" + name, dump: dump})
}
engineGolden.check(t, "requests", results)
}
// runEngineScenario runs sc in the calling synctest bubble and returns its
// transcript.
func runEngineScenario(t *testing.T, sc engineScenario) string {
tr := newEngineTranscript(t)
c := newFakeTransport(tr, sc.agent)
config := engineConfig(Version2c)
if sc.v1 {
config.Version = Version1
}
if sc.config != nil {
sc.config(&config)
}
x := newEngineClientFrom(t, c, config)
ctx := context.Background()
if sc.context != nil {
var cancel context.CancelFunc
ctx, cancel = sc.context()
defer cancel()
}
if sc.setup != nil {
sc.setup(x, c)
}
run := sc.run
if run == nil {
run = getOIDs(engineOID)
}
tr.addf("client: %v timeout=%s retries=%d", x.config.Version, x.config.Timeout, x.config.Retries)
var res *Message
var err error
if v, _ := recoverPanic(func() { res, err = run(ctx, x) }); v != nil {
tr.addf("panic: %v", v)
} else {
tr.addf("result: %s", describeEngineResult(res, err))
}
after := fmt.Sprintf("client after: next request id=%d", (x.requestID+1)&0x7FFFFFFF)
tr.addf("%s", after)
// Let the scenario's own goroutines finish on the bubble's clock: when a
// regression ends the request before them, what they record afterwards
// shows in the transcript instead of a synctest deadlock.
time.Sleep(time.Hour)
return tr.text()
}
// TestEngineCancelWhileSettingDeadline checks that a context canceled while
// the attempt sets its deadline ends the attempt at once: the interrupt comes
// after the deadline, which cannot undo it.
func TestEngineCancelWhileSettingDeadline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := newFakeTransport(nil, nil) // the agent never answers
x := newEngineClient(t, Version2c, c)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c.beforeDeadline = func() {
c.beforeDeadline = nil
cancel()
synctest.Wait() // an interrupt registered already sets its deadline now
}
start := time.Now()
_, err := x.Get(ctx, []string{engineOID})
require.ErrorIs(t, err, context.Canceled)
assert.Equal(t, time.Duration(0), time.Since(start), "the request ends at the cancellation")
})
}
// countingContext is a context that is never done and counts the functions
// registered to run when it is done (context.AfterFunc calls its AfterFunc
// method) and those unregistered again.
type countingContext struct {
context.Context
done chan struct{}
registered, stopped int
}
func (c *countingContext) Done() <-chan struct{} { return c.done }
func (c *countingContext) AfterFunc(func()) func() bool {
c.registered++
return func() bool {
c.stopped++
return true
}
}
// TestEngineContextInterruptUnregistered checks that each attempt
// unregisters the interrupt it registers with the request's context, so that
// a context used for many requests does not keep one per attempt.
func TestEngineContextInterruptUnregistered(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := newFakeTransport(nil, answerFromSecond(sysDescr))
x := newEngineClient(t, Version2c, c)
ctx := &countingContext{Context: context.Background(), done: make(chan struct{})}
_, err := x.Get(ctx, []string{engineOID})
require.NoError(t, err)
assert.Equal(t, [2]int{2, 2}, [2]int{ctx.registered, ctx.stopped}, "registered, unregistered")
})
}
// TestEngineLateContextInterrupt checks that a context's interrupt whose
// callback runs only after its attempt ended and the next attempt registered
// leaves the next attempt alone. With one CPU, the callback that cancel starts
// runs only when the test's goroutine blocks: after the next registration.
func TestEngineLateContextInterrupt(t *testing.T) {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
synctest.Test(t, func(t *testing.T) {
c := newFakeTransport(nil, nil)
x := newEngineClient(t, Version2c, c)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ended := x.interruptible(ctx, x.conn)
cancel()
ended.end()
// The next attempt sets its deadline, then registers.
require.NoError(t, x.conn.SetDeadline(time.Time{}))
next := x.interruptible(context.Background(), x.conn)
synctest.Wait() // the late callback runs
c.mu.Lock()
deadline := c.deadline
c.mu.Unlock()
next.end()
assert.True(t, deadline.IsZero(), "the next attempt's deadline: %v", deadline)
})
}
// TestRequestPanicNil checks that a panic(nil) in a request ends it with no
// packet and an error, by default (a *runtime.PanicNilError) and under
// GODEBUG=panicnil=1, where recover returns nil: for that setting the test
// runs itself again in a child process.
func TestRequestPanicNil(t *testing.T) {
child := os.Getenv("GOSNMP_TEST_PANICNIL") != ""
if !child {
cmd := exec.Command(os.Args[0], "-test.run=^TestRequestPanicNil$", "-test.count=1", "-test.v") //nolint:gosec // the test binary itself
cmd.Env = append(os.Environ(), "GOSNMP_TEST_PANICNIL=1", "GODEBUG=panicnil=1")
out, err := cmd.CombinedOutput()
require.NoError(t, err, "%s", out)
require.Contains(t, string(out), "--- PASS: TestRequestPanicNil", "the child ran the test")
}
c := newFakeTransport(nil, answer(sysDescr))
x := newEngineClient(t, Version2c, c)
c.failWrite = func(int) error { panic(nil) } //nolint:govet // the nil panic is the point
res, err := x.Get(context.Background(), []string{engineOID})
assert.Nil(t, res)
want := "request panicked: runtime error: panic called with nil argument"
if child {
want = "request panicked: <nil>"
}
assert.EqualError(t, err, want)
}
// panicInterruptContext panics at stage: in Done or in the AfterFunc method
// context.AfterFunc calls while setting up the attempt's interrupt, or in the
// stop function that AfterFunc method returned, which ending the attempt calls.
type panicInterruptContext struct {
context.Context
done chan struct{}
stage string
value any
}
func (c *panicInterruptContext) Done() <-chan struct{} {
if c.stage == "Done" {
panic(c.value)
}
return c.done
}
func (c *panicInterruptContext) AfterFunc(func()) func() bool {
if c.stage == "AfterFunc" {
panic(c.value)
}
return func() bool { panic(c.value) }
}
// TestRequestContextPanicCleanup checks that a context that panics while the
// attempt sets up or ends its interrupts leaves no active attempt behind: after
// Close and a new connection, cancellation and Close still end the next request
// without waiting for its timeout.
func TestRequestContextPanicCleanup(t *testing.T) {
for _, stage := range []string{"Done", "AfterFunc", "stop"} {
for _, value := range []struct {
name string
panic any
}{
{name: "error", panic: errCallerFailure},
{name: "nil"},
} {
for _, interrupt := range []string{"cancel", "close"} {
t.Run(stage+"/"+value.name+"/"+interrupt, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
config := engineConfig(Version2c)
config.Timeout, config.Retries = time.Hour, 0
x := newEngineClientFrom(t, newFakeTransport(nil, nil), config)
panicking := &panicInterruptContext{
Context: context.Background(), done: make(chan struct{}),
stage: stage, value: value.panic,
}
res, err := x.Get(panicking, []string{engineOID})
require.Nil(t, res)
require.ErrorContains(t, err, "request panicked:")
if value.panic != nil {
require.ErrorIs(t, err, errCallerFailure)
}
x.mu.Lock()
active, interrupted := x.attempt.conn, x.attempt.interrupted
x.mu.Unlock()
assert.Nil(t, active, "the panic left an active attempt")
assert.Nil(t, interrupted, "the panic left an interrupt")
require.NoError(t, x.Close())
conn := newFakeTransport(nil, nil)
defer conn.Close()
x.conn, x.closed = conn, false // as Connect after Close
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wantErr := context.Canceled
conn.afterWrite = func(int) { cancel() }
if interrupt == "close" {
wantErr = net.ErrClosed
conn.afterWrite = func(int) { require.NoError(t, x.Close()) }
}
start := time.Now()
res, err = x.Get(ctx, []string{engineOID})
assert.Nil(t, res)
assert.ErrorIs(t, err, wantErr)
assert.Zero(t, time.Since(start), "the interrupt waited for the attempt's timeout")
})
})
}
}
}
}
// TestEngineRequestTimeoutError checks what a caller that classifies errors
// sees when every attempt of a request times out on a real socket: the text
// "request timeout", unwrapping to the last attempt's read deadline, a
// timeout net.Error.
func TestEngineRequestTimeoutError(t *testing.T) {