aboutsummaryrefslogtreecommitdiff
path: root/internal/monitor/tcp.go
blob: f93ae100a21f2fedbfa5a62e076e4574ada08a9b (plain) (blame)
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
package monitor

import (
	"context"
	"fmt"
	"net"
	"time"

	"github.com/Fuwn/kaze/internal/config"
)

// TCPMonitor monitors TCP endpoints
type TCPMonitor struct {
	name     string
	target   string
	interval time.Duration
	timeout  time.Duration
}

// NewTCPMonitor creates a new TCP monitor
func NewTCPMonitor(cfg config.MonitorConfig) (*TCPMonitor, error) {
	// Validate target format (should be host:port)
	_, _, err := net.SplitHostPort(cfg.Target)
	if err != nil {
		return nil, fmt.Errorf("invalid TCP target %q: must be host:port format: %w", cfg.Target, err)
	}

	return &TCPMonitor{
		name:     cfg.Name,
		target:   cfg.Target,
		interval: cfg.Interval.Duration,
		timeout:  cfg.Timeout.Duration,
	}, nil
}

// Name returns the monitor's name
func (m *TCPMonitor) Name() string {
	return m.name
}

// Type returns the monitor type
func (m *TCPMonitor) Type() string {
	return "tcp"
}

// Target returns the monitor target
func (m *TCPMonitor) Target() string {
	return m.target
}

// Interval returns the check interval
func (m *TCPMonitor) Interval() time.Duration {
	return m.interval
}

// Check performs the TCP connection check
func (m *TCPMonitor) Check(ctx context.Context) *Result {
	result := &Result{
		MonitorName: m.name,
		Timestamp:   time.Now(),
	}

	// Create a dialer with timeout
	dialer := &net.Dialer{
		Timeout: m.timeout,
	}

	// Attempt to connect
	start := time.Now()
	conn, err := dialer.DialContext(ctx, "tcp", m.target)
	result.ResponseTime = time.Since(start)

	if err != nil {
		result.Status = StatusDown
		result.Error = fmt.Errorf("connection failed: %w", err)
		return result
	}
	defer conn.Close()

	result.Status = StatusUp

	// Check for slow response (degraded if > 1 second for TCP)
	if result.ResponseTime > 1*time.Second {
		result.Status = StatusDegraded
		result.Error = fmt.Errorf("slow connection: %v", result.ResponseTime)
	}

	return result
}