-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
tcp_test.go
686 lines (613 loc) · 20 KB
/
tcp_test.go
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
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prober
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"net"
"os"
"runtime"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
pconfig "github.com/prometheus/common/config"
"github.com/prometheus/blackbox_exporter/config"
)
func TestTCPConnection(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
ch := make(chan (struct{}))
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
conn.Close()
ch <- struct{}{}
}()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
registry := prometheus.NewRegistry()
if !ProbeTCP(testCTX, ln.Addr().String(), config.Module{TCP: config.TCPProbe{IPProtocolFallback: true}}, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
}
func TestTCPConnectionFails(t *testing.T) {
// Invalid port number.
registry := prometheus.NewRegistry()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if ProbeTCP(testCTX, ":0", config.Module{TCP: config.TCPProbe{}}, registry, log.NewNopLogger()) {
t.Fatalf("TCP module suceeded, expected failure.")
}
}
func TestTCPConnectionWithTLS(t *testing.T) {
if os.Getenv("CI") == "true" {
t.Skip("skipping; CI is failing on ipv6 dns requests")
}
ln, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
_, listenPort, _ := net.SplitHostPort(ln.Addr().String())
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Create test certificates valid for 1 day.
certExpiry := time.Now().AddDate(0, 0, 1)
rootCertTmpl := generateCertificateTemplate(certExpiry, false)
rootCertTmpl.IsCA = true
_, rootCertPem, rootKey := generateSelfSignedCertificate(rootCertTmpl)
// CAFile must be passed via filesystem, use a tempfile.
tmpCaFile, err := ioutil.TempFile("", "cafile.pem")
if err != nil {
t.Fatalf(fmt.Sprintf("Error creating CA tempfile: %s", err))
}
if _, err := tmpCaFile.Write(rootCertPem); err != nil {
t.Fatalf(fmt.Sprintf("Error writing CA tempfile: %s", err))
}
if err := tmpCaFile.Close(); err != nil {
t.Fatalf(fmt.Sprintf("Error closing CA tempfile: %s", err))
}
defer os.Remove(tmpCaFile.Name())
ch := make(chan (struct{}))
logger := log.NewNopLogger()
// Handle server side of this test.
serverFunc := func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
defer conn.Close()
rootKeyPem := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rootKey)})
testcert, err := tls.X509KeyPair(rootCertPem, rootKeyPem)
if err != nil {
panic(fmt.Sprintf("Failed to decode TLS testing keypair: %s\n", err))
}
// Immediately upgrade to TLS.
tlsConfig := &tls.Config{
ServerName: "localhost",
Certificates: []tls.Certificate{testcert},
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
}
tlsConn := tls.Server(conn, tlsConfig)
defer tlsConn.Close()
if err := tlsConn.Handshake(); err != nil {
level.Error(logger).Log("msg", "Error TLS Handshake (server) failed", "err", err)
} else {
// Send some bytes before terminating the connection.
fmt.Fprintf(tlsConn, "Hello World!\n")
}
ch <- struct{}{}
}
// Expect name-verified TLS connection.
module := config.Module{
TCP: config.TCPProbe{
IPProtocol: "ip4",
IPProtocolFallback: true,
TLS: true,
TLSConfig: pconfig.TLSConfig{
CAFile: tmpCaFile.Name(),
InsecureSkipVerify: false,
},
},
}
registry := prometheus.NewRegistry()
go serverFunc()
// Test name-verification failure (IP without IPs in cert's SAN).
if ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module succeeded, expected failure.")
}
<-ch
registry = prometheus.NewRegistry()
go serverFunc()
// Test name-verification with name from target.
target := net.JoinHostPort("localhost", listenPort)
if !ProbeTCP(testCTX, target, module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
registry = prometheus.NewRegistry()
go serverFunc()
// Test name-verification against name from tls_config.
module.TCP.TLSConfig.ServerName = "localhost"
if !ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
// Check the resulting metrics.
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
// Check labels
expectedLabels := map[string]map[string]string{
"probe_tls_version_info": {
"version": "TLS 1.2",
},
}
checkRegistryLabels(expectedLabels, mfs, t)
// Check values
expectedResults := map[string]float64{
"probe_ssl_earliest_cert_expiry": float64(certExpiry.Unix()),
"probe_ssl_last_chain_info": 1,
"probe_tls_version_info": 1,
}
checkRegistryResults(expectedResults, mfs, t)
}
func TestTCPConnectionWithTLSAndVerifiedCertificateChain(t *testing.T) {
if os.Getenv("CI") == "true" {
t.Skip("skipping; CI is failing on ipv6 dns requests")
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
_, listenPort, _ := net.SplitHostPort(ln.Addr().String())
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// From here prepare two certificate chains where one expires before the
// other
rootPrivatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(fmt.Sprintf("Error creating rsa key: %s", err))
}
rootCertExpiry := time.Now().AddDate(0, 0, 3)
rootCertTmpl := generateCertificateTemplate(rootCertExpiry, false)
rootCertTmpl.IsCA = true
_, rootCertPem := generateSelfSignedCertificateWithPrivateKey(rootCertTmpl, rootPrivatekey)
olderRootCertExpiry := time.Now().AddDate(0, 0, 1)
olderRootCertTmpl := generateCertificateTemplate(olderRootCertExpiry, false)
olderRootCertTmpl.IsCA = true
olderRootCert, olderRootCertPem := generateSelfSignedCertificateWithPrivateKey(olderRootCertTmpl, rootPrivatekey)
serverCertExpiry := time.Now().AddDate(0, 0, 2)
serverCertTmpl := generateCertificateTemplate(serverCertExpiry, false)
_, serverCertPem, serverKey := generateSignedCertificate(serverCertTmpl, olderRootCert, rootPrivatekey)
// CAFile must be passed via filesystem, use a tempfile.
tmpCaFile, err := ioutil.TempFile("", "cafile.pem")
if err != nil {
t.Fatalf(fmt.Sprintf("Error creating CA tempfile: %s", err))
}
if _, err := tmpCaFile.Write(bytes.Join([][]byte{rootCertPem, olderRootCertPem}, []byte("\n"))); err != nil {
t.Fatalf(fmt.Sprintf("Error writing CA tempfile: %s", err))
}
if err := tmpCaFile.Close(); err != nil {
t.Fatalf(fmt.Sprintf("Error closing CA tempfile: %s", err))
}
defer os.Remove(tmpCaFile.Name())
ch := make(chan (struct{}))
logger := log.NewNopLogger()
// Handle server side of this test.
serverFunc := func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
defer conn.Close()
serverKeyPem := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(serverKey)})
// Include the older root cert in the chain
keypair, err := tls.X509KeyPair(append(serverCertPem, olderRootCertPem...), serverKeyPem)
if err != nil {
panic(fmt.Sprintf("Failed to decode TLS testing keypair: %s\n", err))
}
// Immediately upgrade to TLS.
tlsConfig := &tls.Config{
ServerName: "localhost",
Certificates: []tls.Certificate{keypair},
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
}
tlsConn := tls.Server(conn, tlsConfig)
defer tlsConn.Close()
if err := tlsConn.Handshake(); err != nil {
level.Error(logger).Log("msg", "Error TLS Handshake (server) failed", "err", err)
} else {
// Send some bytes before terminating the connection.
fmt.Fprintf(tlsConn, "Hello World!\n")
}
ch <- struct{}{}
}
// Expect name-verified TLS connection.
module := config.Module{
TCP: config.TCPProbe{
IPProtocol: "ip4",
IPProtocolFallback: true,
TLS: true,
TLSConfig: pconfig.TLSConfig{
CAFile: tmpCaFile.Name(),
InsecureSkipVerify: false,
},
},
}
registry := prometheus.NewRegistry()
go serverFunc()
// Test name-verification with name from target.
target := net.JoinHostPort("localhost", listenPort)
if !ProbeTCP(testCTX, target, module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
// Check the resulting metrics.
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
// Check values
expectedResults := map[string]float64{
"probe_ssl_earliest_cert_expiry": float64(olderRootCertExpiry.Unix()),
"probe_ssl_last_chain_expiry_timestamp_seconds": float64(serverCertExpiry.Unix()),
"probe_ssl_last_chain_info": 1,
"probe_tls_version_info": 1,
}
checkRegistryResults(expectedResults, mfs, t)
}
func TestTCPConnectionQueryResponseStartTLS(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Create test certificates valid for 1 day.
certExpiry := time.Now().AddDate(0, 0, 1)
testCertTmpl := generateCertificateTemplate(certExpiry, true)
testCertTmpl.IsCA = true
_, testCertPem, testKey := generateSelfSignedCertificate(testCertTmpl)
// CAFile must be passed via filesystem, use a tempfile.
tmpCaFile, err := ioutil.TempFile("", "cafile.pem")
if err != nil {
t.Fatalf(fmt.Sprintf("Error creating CA tempfile: %s", err))
}
if _, err := tmpCaFile.Write(testCertPem); err != nil {
t.Fatalf(fmt.Sprintf("Error writing CA tempfile: %s", err))
}
if err := tmpCaFile.Close(); err != nil {
t.Fatalf(fmt.Sprintf("Error closing CA tempfile: %s", err))
}
defer os.Remove(tmpCaFile.Name())
// Define some (bogus) example SMTP dialog with STARTTLS.
module := config.Module{
TCP: config.TCPProbe{
IPProtocolFallback: true,
QueryResponse: []config.QueryResponse{
{Expect: config.MustNewRegexp("^220.*ESMTP.*$")},
{Send: "EHLO tls.prober"},
{Expect: config.MustNewRegexp("^250-STARTTLS")},
{Send: "STARTTLS"},
{Expect: config.MustNewRegexp("^220")},
{StartTLS: true},
{Send: "EHLO tls.prober"},
{Expect: config.MustNewRegexp("^250-AUTH")},
{Send: "QUIT"},
},
TLSConfig: pconfig.TLSConfig{
CAFile: tmpCaFile.Name(),
InsecureSkipVerify: false,
},
},
}
// Handle server side of this test.
ch := make(chan (struct{}))
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
defer conn.Close()
fmt.Fprintf(conn, "220 ESMTP StartTLS pseudo-server\n")
if _, e := fmt.Fscanf(conn, "EHLO tls.prober\n"); e != nil {
panic("Error in dialog. No EHLO received.")
}
fmt.Fprintf(conn, "250-pseudo-server.example.net\n")
fmt.Fprintf(conn, "250-STARTTLS\n")
fmt.Fprintf(conn, "250 DSN\n")
if _, e := fmt.Fscanf(conn, "STARTTLS\n"); e != nil {
panic("Error in dialog. No (TLS) STARTTLS received.")
}
fmt.Fprintf(conn, "220 2.0.0 Ready to start TLS\n")
testKeyPem := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(testKey)})
testcert, err := tls.X509KeyPair(testCertPem, testKeyPem)
if err != nil {
panic(fmt.Sprintf("Failed to decode TLS testing keypair: %s\n", err))
}
// Do the server-side upgrade to TLS.
tlsConfig := &tls.Config{
ServerName: "localhost",
Certificates: []tls.Certificate{testcert},
}
tlsConn := tls.Server(conn, tlsConfig)
if err := tlsConn.Handshake(); err != nil {
panic(fmt.Sprintf("TLS Handshake (server) failed: %s\n", err))
}
defer tlsConn.Close()
// Continue encrypted.
if _, e := fmt.Fscanf(tlsConn, "EHLO"); e != nil {
panic("Error in dialog. No (TLS) EHLO received.")
}
fmt.Fprintf(tlsConn, "250-AUTH\n")
fmt.Fprintf(tlsConn, "250 DSN\n")
ch <- struct{}{}
}()
// Do the client side of this test.
registry := prometheus.NewRegistry()
if !ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
// Check the probe_ssl_earliest_cert_expiry.
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults := map[string]float64{
"probe_ssl_earliest_cert_expiry": float64(certExpiry.Unix()),
}
checkRegistryResults(expectedResults, mfs, t)
}
func TestTCPConnectionQueryResponseIRC(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
module := config.Module{
TCP: config.TCPProbe{
IPProtocolFallback: true,
QueryResponse: []config.QueryResponse{
{Send: "NICK prober"},
{Send: "USER prober prober prober :prober"},
{Expect: config.MustNewRegexp("^:[^ ]+ 001")},
},
},
}
ch := make(chan (struct{}))
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
fmt.Fprintf(conn, ":ircd.localhost NOTICE AUTH :*** Looking up your hostname...\n")
var nick, user, mode, unused, realname string
fmt.Fscanf(conn, "NICK %s", &nick)
fmt.Fscanf(conn, "USER %s %s %s :%s", &user, &mode, &unused, &realname)
fmt.Fprintf(conn, ":ircd.localhost 001 %s :Welcome to IRC!\n", nick)
conn.Close()
ch <- struct{}{}
}()
registry := prometheus.NewRegistry()
if !ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
<-ch
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
fmt.Fprintf(conn, ":ircd.localhost NOTICE AUTH :*** Looking up your hostname...\n")
var nick, user, mode, unused, realname string
fmt.Fscanf(conn, "NICK %s", &nick)
fmt.Fscanf(conn, "USER %s %s %s :%s", &user, &mode, &unused, &realname)
fmt.Fprintf(conn, "ERROR: Your IP address has been blacklisted.\n")
conn.Close()
ch <- struct{}{}
}()
registry = prometheus.NewRegistry()
if ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module succeeded, expected failure.")
}
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults := map[string]float64{
"probe_failed_due_to_regex": 1,
}
checkRegistryResults(expectedResults, mfs, t)
<-ch
}
func TestTCPConnectionQueryResponseMatching(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
time.Sleep(time.Millisecond * 100)
module := config.Module{
TCP: config.TCPProbe{
IPProtocolFallback: true,
QueryResponse: []config.QueryResponse{
{
Expect: config.MustNewRegexp("SSH-2.0-(OpenSSH_6.9p1) Debian-2"),
Send: "CONFIRM ${1}",
},
},
},
}
ch := make(chan string)
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
conn.SetDeadline(time.Now().Add(1 * time.Second))
fmt.Fprintf(conn, "SSH-2.0-OpenSSH_6.9p1 Debian-2\n")
var version string
fmt.Fscanf(conn, "CONFIRM %s", &version)
conn.Close()
ch <- version
}()
registry := prometheus.NewRegistry()
if !ProbeTCP(testCTX, ln.Addr().String(), module, registry, log.NewNopLogger()) {
t.Fatalf("TCP module failed, expected success.")
}
if got, want := <-ch, "OpenSSH_6.9p1"; got != want {
t.Fatalf("Read unexpected version: got %q, want %q", got, want)
}
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults := map[string]float64{
"probe_failed_due_to_regex": 0,
}
checkRegistryResults(expectedResults, mfs, t)
}
func TestTCPConnectionProtocol(t *testing.T) {
if os.Getenv("CI") == "true" {
t.Skip("skipping; CI is failing on ipv6 dns requests")
}
// This test assumes that listening TCP listens both IPv6 and IPv4 traffic and
// localhost resolves to both 127.0.0.1 and ::1. we must skip the test if either
// of these isn't true. This should be true for modern Linux systems.
if runtime.GOOS == "dragonfly" || runtime.GOOS == "openbsd" {
t.Skip("IPv6 socket isn't able to accept IPv4 traffic in the system.")
}
_, err := net.ResolveIPAddr("ip6", "localhost")
if err != nil {
t.Skip("\"localhost\" doesn't resolve to ::1.")
}
ln, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
testCTX, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, port, _ := net.SplitHostPort(ln.Addr().String())
// Prefer IPv4
module := config.Module{
TCP: config.TCPProbe{
IPProtocol: "ip4",
},
}
registry := prometheus.NewRegistry()
result := ProbeTCP(testCTX, net.JoinHostPort("localhost", port), module, registry, log.NewNopLogger())
if !result {
t.Fatalf("TCP protocol: \"tcp\", prefer: \"ip4\" connection test failed, expected success.")
}
mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults := map[string]float64{
"probe_ip_protocol": 4,
}
checkRegistryResults(expectedResults, mfs, t)
// Prefer IPv6
module = config.Module{
TCP: config.TCPProbe{
IPProtocol: "ip6",
},
}
registry = prometheus.NewRegistry()
result = ProbeTCP(testCTX, net.JoinHostPort("localhost", port), module, registry, log.NewNopLogger())
if !result {
t.Fatalf("TCP protocol: \"tcp\", prefer: \"ip6\" connection test failed, expected success.")
}
mfs, err = registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults = map[string]float64{
"probe_ip_protocol": 6,
}
checkRegistryResults(expectedResults, mfs, t)
// Prefer nothing
module = config.Module{
TCP: config.TCPProbe{},
}
registry = prometheus.NewRegistry()
result = ProbeTCP(testCTX, net.JoinHostPort("localhost", port), module, registry, log.NewNopLogger())
if !result {
t.Fatalf("TCP protocol: \"tcp\" connection test failed, expected success.")
}
mfs, err = registry.Gather()
if err != nil {
t.Fatal(err)
}
expectedResults = map[string]float64{
"probe_ip_protocol": 6,
}
checkRegistryResults(expectedResults, mfs, t)
}
func TestPrometheusTimeoutTCP(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error listening on socket: %s", err)
}
defer ln.Close()
ch := make(chan (struct{}))
go func() {
conn, err := ln.Accept()
if err != nil {
panic(fmt.Sprintf("Error accepting on socket: %s", err))
}
conn.Close()
ch <- struct{}{}
}()
testCTX, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
registry := prometheus.NewRegistry()
if ProbeTCP(testCTX, ln.Addr().String(), config.Module{TCP: config.TCPProbe{
IPProtocolFallback: true,
QueryResponse: []config.QueryResponse{
{
Expect: config.MustNewRegexp("SSH-2.0-(OpenSSH_6.9p1) Debian-2"),
},
},
}}, registry, log.NewNopLogger()) {
t.Fatalf("TCP module succeeded, expected timeout failure.")
}
<-ch
}