aboutsummaryrefslogtreecommitdiff
path: root/internal/monitor/http.go
blob: 8432401918b6d928b1866698d79544fc1dc1c412 (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
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
package monitor

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/http"
	"strings"
	"time"

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

// HTTPMonitor monitors HTTP and HTTPS endpoints
type HTTPMonitor struct {
	name           string
	monitorType    string
	target         string
	interval       time.Duration
	timeout        time.Duration
	method         string
	headers        map[string]string
	body           string
	expectedStatus int
	verifySSL      bool
	client         *http.Client
}

// NewHTTPMonitor creates a new HTTP/HTTPS monitor
func NewHTTPMonitor(cfg config.MonitorConfig) (*HTTPMonitor, error) {
	// Validate target URL
	target := cfg.Target
	if cfg.Type == "https" && !strings.HasPrefix(target, "https://") {
		if strings.HasPrefix(target, "http://") {
			target = strings.Replace(target, "http://", "https://", 1)
		} else {
			target = "https://" + target
		}
	} else if cfg.Type == "http" && !strings.HasPrefix(target, "http://") && !strings.HasPrefix(target, "https://") {
		target = "http://" + target
	}

	verifySSL := true
	if cfg.VerifySSL != nil {
		verifySSL = *cfg.VerifySSL
	}

	// Create HTTP client with custom transport
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: !verifySSL,
		},
		DialContext: (&net.Dialer{
			Timeout:   cfg.Timeout.Duration,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		TLSHandshakeTimeout:   10 * time.Second,
		ResponseHeaderTimeout: cfg.Timeout.Duration,
		ExpectContinueTimeout: 1 * time.Second,
		MaxIdleConns:          100,
		MaxIdleConnsPerHost:   10,
		IdleConnTimeout:       90 * time.Second,
	}

	client := &http.Client{
		Transport: transport,
		Timeout:   cfg.Timeout.Duration,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) >= 10 {
				return fmt.Errorf("too many redirects")
			}
			return nil
		},
	}

	return &HTTPMonitor{
		name:           cfg.Name,
		monitorType:    cfg.Type,
		target:         target,
		interval:       cfg.Interval.Duration,
		timeout:        cfg.Timeout.Duration,
		method:         cfg.Method,
		headers:        cfg.Headers,
		body:           cfg.Body,
		expectedStatus: cfg.ExpectedStatus,
		verifySSL:      verifySSL,
		client:         client,
	}, nil
}

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

// Type returns the monitor type
func (m *HTTPMonitor) Type() string {
	return m.monitorType
}

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

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

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

	// Create request
	var bodyReader io.Reader
	if m.body != "" {
		bodyReader = strings.NewReader(m.body)
	}

	req, err := http.NewRequestWithContext(ctx, m.method, m.target, bodyReader)
	if err != nil {
		result.Status = StatusDown
		result.Error = fmt.Errorf("failed to create request: %w", err)
		return result
	}

	// Set headers
	req.Header.Set("User-Agent", "Kaze-Monitor/1.0")
	for key, value := range m.headers {
		req.Header.Set(key, value)
	}

	// Perform request and measure response time
	start := time.Now()
	resp, err := m.client.Do(req)
	result.ResponseTime = time.Since(start)

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

	// Discard body to allow connection reuse
	io.Copy(io.Discard, resp.Body)

	result.StatusCode = resp.StatusCode

	// Check SSL certificate for HTTPS
	if m.monitorType == "https" && resp.TLS != nil && len(resp.TLS.PeerCertificates) > 0 {
		cert := resp.TLS.PeerCertificates[0]
		result.SSLExpiry = &cert.NotAfter
		result.SSLDaysLeft = int(time.Until(cert.NotAfter).Hours() / 24)
	}

	// Determine status based on response code
	if resp.StatusCode == m.expectedStatus {
		result.Status = StatusUp
	} else if resp.StatusCode >= 200 && resp.StatusCode < 400 {
		// Got a success code but not the expected one
		result.Status = StatusDegraded
		result.Error = fmt.Errorf("unexpected status code: got %d, expected %d", resp.StatusCode, m.expectedStatus)
	} else {
		result.Status = StatusDown
		result.Error = fmt.Errorf("bad status code: %d", resp.StatusCode)
	}

	// Check for slow response (degraded if > 2 seconds)
	if result.Status == StatusUp && result.ResponseTime > 2*time.Second {
		result.Status = StatusDegraded
		result.Error = fmt.Errorf("slow response: %v", result.ResponseTime)
	}

	return result
}