aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/monitor/worker.go
blob: 70855a254c4569994a4cabe482d583a6927e2668 (plain)
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
package monitor

import (
	"context"
	"encoding/json"
	"log"
	"sync"
	"time"

	"yaum/internal/alerts"
	"yaum/internal/model"
	"yaum/internal/sse"
	"yaum/internal/store"
)

type checkResult struct {
	Heartbeat model.Heartbeat
	Service   model.Service
}

type Worker struct {
	store       store.Store
	interval    time.Duration
	timeout     time.Duration
	results     chan checkResult
	broadcaster *sse.Broadcaster
	smtpCfg     *alerts.SMTPConfig
	quit        chan struct{}
	mu          sync.Mutex
	lastChecked map[int]time.Time
}

func NewWorker(s store.Store, interval, timeout time.Duration, b *sse.Broadcaster) *Worker {
	return &Worker{
		store:       s,
		interval:    interval,
		timeout:     timeout,
		results:     make(chan checkResult, 100),
		broadcaster: b,
		quit:        make(chan struct{}),
		lastChecked: make(map[int]time.Time),
	}
}

func (w *Worker) WithSMTP(cfg *alerts.SMTPConfig) *Worker {
	w.smtpCfg = cfg
	return w
}

func (w *Worker) Start(ctx context.Context) {
	granularity := w.interval
	if granularity > 10*time.Second {
		granularity = 10 * time.Second
	}
	ticker := time.NewTicker(granularity)
	defer ticker.Stop()

	log.Printf("[worker] iniciado | global_interval=%v granularity=%v timeout=%v", w.interval, granularity, w.timeout)

	go w.resultConsumer()

	w.runChecks(ctx)

	for {
		select {
		case <-ticker.C:
			w.runChecks(ctx)
		case <-w.quit:
			log.Println("[worker] encerrando...")
			return
		}
	}
}

func (w *Worker) runChecks(ctx context.Context) {
	services, err := w.store.ListActiveServices()
	if err != nil {
		log.Printf("[worker] erro ao listar servicos ativos: %v", err)
		return
	}

	now := time.Now()
	var due []model.Service

	w.mu.Lock()
	for _, svc := range services {
		svcInterval := time.Duration(svc.IntervalSeconds) * time.Second
		if svcInterval <= 0 {
			svcInterval = w.interval
		}
		last, ok := w.lastChecked[svc.ID]
		if !ok || now.Sub(last) >= svcInterval {
			w.lastChecked[svc.ID] = now
			due = append(due, svc)
		}
	}
	w.mu.Unlock()

	if len(due) == 0 {
		return
	}
	log.Printf("[worker] verificando %d servico(s) de %d ativo(s)", len(due), len(services))

	for _, svc := range due {
		go w.checkService(ctx, svc)
	}
}

func (w *Worker) resultConsumer() {
	for {
		select {
		case res := <-w.results:
			hb := res.Heartbeat
			svc := res.Service

			w.checkTransition(svc, hb)

			if err := w.store.AddHeartbeat(hb); err != nil {
				log.Printf("[worker] erro ao salvar heartbeat: %v", err)
			}

			if w.broadcaster != nil {
				data, err := json.Marshal(hb)
				if err == nil {
					w.broadcaster.Publish(data)
				}
			}

			status := "UP"
			if !hb.IsUp {
				status = "DOWN"
			}
			log.Printf("[worker] service=%d status=%s code=%d time=%dms",
				hb.ServiceID, status, hb.StatusCode, hb.ResponseTimeMs)
		case <-w.quit:
			return
		}
	}
}

func (w *Worker) checkTransition(svc model.Service, hb model.Heartbeat) {
	prev, err := w.store.GetLastHeartbeat(svc.ID)
	if err != nil || prev == nil {
		return
	}

	if prev.IsUp == hb.IsUp {
		return
	}

	log.Printf("[worker] transicao de status service=%d: %v -> %v", svc.ID, prev.IsUp, hb.IsUp)

	w.fireAlerts(svc, hb, prev.IsUp)
}

func (w *Worker) fireAlerts(svc model.Service, hb model.Heartbeat, wasUp bool) {
	if svc.DiscordWebhookURL != "" {
		go alerts.SendDiscord(svc.DiscordWebhookURL, svc, hb, wasUp)
	}
	if svc.AlertEmail != "" && w.smtpCfg != nil {
		go alerts.SendEmail(svc, hb, wasUp, w.smtpCfg)
	}
}

func (w *Worker) checkService(ctx context.Context, svc model.Service) {
	checkCtx, cancel := context.WithTimeout(ctx, w.timeout)
	defer cancel()

	hb := CheckHTTP(checkCtx, svc.URL, svc.KeywordToFind)
	hb.ServiceID = svc.ID

	w.results <- checkResult{Heartbeat: hb, Service: svc}
}

func (w *Worker) Stop() {
	close(w.quit)
}