2019-09-04 19:37:13 -04:00
package watchdog
2019-09-06 21:59:50 -04:00
import (
2021-05-18 22:29:15 -04:00
"context"
2019-09-06 21:59:50 -04:00
"sync"
"time"
2020-10-30 21:00:03 +05:30
2022-12-06 01:41:09 -05:00
"github.com/TwiN/gatus/v5/alerting"
"github.com/TwiN/gatus/v5/config"
2023-05-02 22:41:22 -04:00
"github.com/TwiN/gatus/v5/config/connectivity"
2024-05-09 22:56:16 -04:00
"github.com/TwiN/gatus/v5/config/endpoint"
2022-12-06 01:41:09 -05:00
"github.com/TwiN/gatus/v5/config/maintenance"
"github.com/TwiN/gatus/v5/metrics"
"github.com/TwiN/gatus/v5/storage/store"
2024-11-14 01:02:53 +01:00
"github.com/TwiN/logr"
2019-09-06 21:59:50 -04:00
)
var (
2021-10-23 16:47:12 -04:00
// monitoringMutex is used to prevent multiple endpoint from being evaluated at the same time.
2020-09-04 21:31:28 -04:00
// Without this, conditions using response time may become inaccurate.
monitoringMutex sync . Mutex
2021-05-18 22:29:15 -04:00
ctx context . Context
cancelFunc context . CancelFunc
2019-09-06 21:59:50 -04:00
)
2021-10-23 16:47:12 -04:00
// Monitor loops over each endpoint and starts a goroutine to monitor each endpoint separately
2019-12-04 16:44:35 -05:00
func Monitor ( cfg * config . Config ) {
2021-05-18 22:29:15 -04:00
ctx , cancelFunc = context . WithCancel ( context . Background ())
2025-08-06 00:26:50 +08:00
extraLabels := cfg . GetUniqueExtraMetricLabels ()
2021-10-23 16:47:12 -04:00
for _ , endpoint := range cfg . Endpoints {
if endpoint . IsEnabled () {
2021-09-22 00:04:51 -04:00
// To prevent multiple requests from running at the same time, we'll wait for a little before each iteration
2021-10-28 19:35:46 -04:00
time . Sleep ( 777 * time . Millisecond )
2025-08-06 00:26:50 +08:00
go monitor ( endpoint , cfg . Alerting , cfg . Maintenance , cfg . Connectivity , cfg . DisableMonitoringLock , cfg . Metrics , extraLabels , ctx )
2021-09-19 00:52:11 +09:00
}
2020-04-06 18:58:13 -04:00
}
2025-07-30 12:18:10 -04:00
for _ , externalEndpoint := range cfg . ExternalEndpoints {
// Check if the external endpoint is enabled and is using heartbeat
// If the external endpoint does not use heartbeat, then it does not need to be monitored periodically, because
// alerting is checked every time an external endpoint is pushed to Gatus, unlike normal endpoints.
if externalEndpoint . IsEnabled () && externalEndpoint . Heartbeat . Interval > 0 {
2025-08-06 00:26:50 +08:00
go monitorExternalEndpointHeartbeat ( externalEndpoint , cfg . Alerting , cfg . Maintenance , cfg . Connectivity , cfg . DisableMonitoringLock , cfg . Metrics , ctx , extraLabels )
2025-07-30 12:18:10 -04:00
}
}
2020-04-06 18:58:13 -04:00
}
2021-10-28 19:35:46 -04:00
// monitor a single endpoint in a loop
2025-08-06 00:26:50 +08:00
func monitor ( ep * endpoint . Endpoint , alertingConfig * alerting . Config , maintenanceConfig * maintenance . Config , connectivityConfig * connectivity . Config , disableMonitoringLock bool , enabledMetrics bool , extraLabels [] string , ctx context . Context ) {
2021-05-18 22:29:15 -04:00
// Run it immediately on start
2025-08-06 00:26:50 +08:00
execute ( ep , alertingConfig , maintenanceConfig , connectivityConfig , disableMonitoringLock , enabledMetrics , extraLabels )
2021-05-18 22:29:15 -04:00
// Loop for the next executions
2025-01-29 11:23:16 +08:00
ticker := time . NewTicker ( ep . Interval )
defer ticker . Stop ()
2020-04-06 18:58:13 -04:00
for {
2021-05-18 22:29:15 -04:00
select {
case <- ctx . Done ():
2024-11-13 23:54:00 -05:00
logr . Warnf ( "[watchdog.monitor] Canceling current execution of group=%s; endpoint=%s; key=%s" , ep . Group , ep . Name , ep . Key ())
2021-05-18 22:29:15 -04:00
return
2025-01-29 11:23:16 +08:00
case <- ticker . C :
2025-08-06 00:26:50 +08:00
execute ( ep , alertingConfig , maintenanceConfig , connectivityConfig , disableMonitoringLock , enabledMetrics , extraLabels )
2020-09-04 21:31:28 -04:00
}
2021-05-18 22:29:15 -04:00
}
2024-04-08 21:00:40 -04:00
// Just in case somebody wandered all the way to here and wonders, "what about ExternalEndpoints?"
// Alerting is checked every time an external endpoint is pushed to Gatus, so they're not monitored
// periodically like they are for normal endpoints.
2021-05-18 22:29:15 -04:00
}
2025-08-06 00:26:50 +08:00
func execute ( ep * endpoint . Endpoint , alertingConfig * alerting . Config , maintenanceConfig * maintenance . Config , connectivityConfig * connectivity . Config , disableMonitoringLock bool , enabledMetrics bool , extraLabels [] string ) {
2021-05-18 22:29:15 -04:00
if ! disableMonitoringLock {
2021-10-23 16:47:12 -04:00
// By placing the lock here, we prevent multiple endpoints from being monitored at the exact same time, which
2021-05-18 22:29:15 -04:00
// could cause performance issues and return inaccurate results
monitoringMutex . Lock ()
2023-05-02 22:41:22 -04:00
defer monitoringMutex . Unlock ()
}
// If there's a connectivity checker configured, check if Gatus has internet connectivity
if connectivityConfig != nil && connectivityConfig . Checker != nil && ! connectivityConfig . Checker . IsConnected () {
2024-11-14 01:02:53 +01:00
logr . Infof ( "[watchdog.execute] No connectivity; skipping execution" )
2023-05-02 22:41:22 -04:00
return
2021-05-18 22:29:15 -04:00
}
2024-11-13 23:54:00 -05:00
logr . Debugf ( "[watchdog.execute] Monitoring group=%s; endpoint=%s; key=%s" , ep . Group , ep . Name , ep . Key ())
2024-05-09 22:56:16 -04:00
result := ep . EvaluateHealth ()
2021-05-18 22:29:15 -04:00
if enabledMetrics {
2025-08-06 00:26:50 +08:00
metrics . PublishMetricsForEndpoint ( ep , result , extraLabels )
2021-05-18 22:29:15 -04:00
}
2024-05-09 22:56:16 -04:00
UpdateEndpointStatuses ( ep , result )
2024-11-14 01:02:53 +01:00
if logr . GetThreshold () == logr . LevelDebug && ! result . Success {
2024-11-13 23:54:00 -05:00
logr . Debugf ( "[watchdog.execute] Monitored group=%s; endpoint=%s; key=%s; success=%v; errors=%d; duration=%s; body=%s" , ep . Group , ep . Name , ep . Key (), result . Success , len ( result . Errors ), result . Duration . Round ( time . Millisecond ), result . Body )
2023-03-14 20:02:31 -04:00
} else {
2024-11-13 23:54:00 -05:00
logr . Infof ( "[watchdog.execute] Monitored group=%s; endpoint=%s; key=%s; success=%v; errors=%d; duration=%s" , ep . Group , ep . Name , ep . Key (), result . Success , len ( result . Errors ), result . Duration . Round ( time . Millisecond ))
2023-03-14 20:02:31 -04:00
}
2025-02-17 12:05:13 +08:00
inEndpointMaintenanceWindow := false
for _ , maintenanceWindow := range ep . MaintenanceWindows {
if maintenanceWindow . IsUnderMaintenance () {
logr . Debug ( "[watchdog.execute] Under endpoint maintenance window" )
inEndpointMaintenanceWindow = true
}
}
if ! maintenanceConfig . IsUnderMaintenance () && ! inEndpointMaintenanceWindow {
2021-12-02 21:05:17 -05:00
// TODO: Consider moving this after the monitoring lock is unlocked? I mean, how much noise can a single alerting provider cause...
2024-11-13 23:54:00 -05:00
HandleAlerting ( ep , result , alertingConfig )
2024-11-14 01:02:53 +01:00
} else {
2024-11-13 23:54:00 -05:00
logr . Debug ( "[watchdog.execute] Not handling alerting because currently in the maintenance window" )
2021-05-18 22:29:15 -04:00
}
2024-11-13 23:54:00 -05:00
logr . Debugf ( "[watchdog.execute] Waiting for interval=%s before monitoring group=%s endpoint=%s (key=%s) again" , ep . Interval , ep . Group , ep . Name , ep . Key ())
2020-09-04 18:23:56 -04:00
}
2020-11-26 18:09:01 -05:00
2025-08-06 00:26:50 +08:00
func monitorExternalEndpointHeartbeat ( ee * endpoint . ExternalEndpoint , alertingConfig * alerting . Config , maintenanceConfig * maintenance . Config , connectivityConfig * connectivity . Config , disableMonitoringLock bool , enabledMetrics bool , ctx context . Context , extraLabels [] string ) {
2025-07-30 12:18:10 -04:00
ticker := time . NewTicker ( ee . Heartbeat . Interval )
defer ticker . Stop ()
for {
select {
case <- ctx . Done ():
logr . Warnf ( "[watchdog.monitorExternalEndpointHeartbeat] Canceling current execution of group=%s; endpoint=%s; key=%s" , ee . Group , ee . Name , ee . Key ())
return
case <- ticker . C :
2025-08-06 00:26:50 +08:00
executeExternalEndpointHeartbeat ( ee , alertingConfig , maintenanceConfig , connectivityConfig , disableMonitoringLock , enabledMetrics , extraLabels )
2025-07-30 12:18:10 -04:00
}
}
}
2025-08-06 00:26:50 +08:00
func executeExternalEndpointHeartbeat ( ee * endpoint . ExternalEndpoint , alertingConfig * alerting . Config , maintenanceConfig * maintenance . Config , connectivityConfig * connectivity . Config , disableMonitoringLock bool , enabledMetrics bool , extraLabels [] string ) {
2025-07-30 12:18:10 -04:00
if ! disableMonitoringLock {
// By placing the lock here, we prevent multiple endpoints from being monitored at the exact same time, which
// could cause performance issues and return inaccurate results
monitoringMutex . Lock ()
defer monitoringMutex . Unlock ()
}
// If there's a connectivity checker configured, check if Gatus has internet connectivity
if connectivityConfig != nil && connectivityConfig . Checker != nil && ! connectivityConfig . Checker . IsConnected () {
logr . Infof ( "[watchdog.monitorExternalEndpointHeartbeat] No connectivity; skipping execution" )
return
}
logr . Debugf ( "[watchdog.monitorExternalEndpointHeartbeat] Checking heartbeat for group=%s; endpoint=%s; key=%s" , ee . Group , ee . Name , ee . Key ())
convertedEndpoint := ee . ToEndpoint ()
hasReceivedResultWithinHeartbeatInterval , err := store . Get (). HasEndpointStatusNewerThan ( ee . Key (), time . Now (). Add ( - ee . Heartbeat . Interval ))
if err != nil {
logr . Errorf ( "[watchdog.monitorExternalEndpointHeartbeat] Failed to check if endpoint has received a result within the heartbeat interval: %s" , err . Error ())
return
}
if hasReceivedResultWithinHeartbeatInterval {
// If we received a result within the heartbeat interval, we don't want to create a successful result, so we
// skip the rest. We don't have to worry about alerting or metrics, because if the previous heartbeat failed
// while this one succeeds, it implies that there was a new result pushed, and that result being pushed
// should've resolved the alert.
logr . Infof ( "[watchdog.monitorExternalEndpointHeartbeat] Checked heartbeat for group=%s; endpoint=%s; key=%s; success=%v; errors=%d" , ee . Group , ee . Name , ee . Key (), hasReceivedResultWithinHeartbeatInterval , 0 )
return
}
// All code after this point assumes the heartbeat failed
result := & endpoint . Result {
Timestamp : time . Now (),
Success : false ,
Errors : [] string { "heartbeat: no update received within " + ee . Heartbeat . Interval . String ()},
}
if enabledMetrics {
2025-08-06 00:26:50 +08:00
metrics . PublishMetricsForEndpoint ( convertedEndpoint , result , extraLabels )
2025-07-30 12:18:10 -04:00
}
UpdateEndpointStatuses ( convertedEndpoint , result )
logr . Infof ( "[watchdog.monitorExternalEndpointHeartbeat] Checked heartbeat for group=%s; endpoint=%s; key=%s; success=%v; errors=%d; duration=%s" , ee . Group , ee . Name , ee . Key (), result . Success , len ( result . Errors ), result . Duration . Round ( time . Millisecond ))
inEndpointMaintenanceWindow := false
for _ , maintenanceWindow := range ee . MaintenanceWindows {
if maintenanceWindow . IsUnderMaintenance () {
logr . Debug ( "[watchdog.monitorExternalEndpointHeartbeat] Under endpoint maintenance window" )
inEndpointMaintenanceWindow = true
}
}
if ! maintenanceConfig . IsUnderMaintenance () && ! inEndpointMaintenanceWindow {
HandleAlerting ( convertedEndpoint , result , alertingConfig )
// Sync the failure/success counters back to the external endpoint
ee . NumberOfSuccessesInARow = convertedEndpoint . NumberOfSuccessesInARow
ee . NumberOfFailuresInARow = convertedEndpoint . NumberOfFailuresInARow
} else {
logr . Debug ( "[watchdog.monitorExternalEndpointHeartbeat] Not handling alerting because currently in the maintenance window" )
}
logr . Debugf ( "[watchdog.monitorExternalEndpointHeartbeat] Waiting for interval=%s before checking heartbeat for group=%s endpoint=%s (key=%s) again" , ee . Heartbeat . Interval , ee . Group , ee . Name , ee . Key ())
}
2021-10-23 16:47:12 -04:00
// UpdateEndpointStatuses updates the slice of endpoint statuses
2024-05-09 22:56:16 -04:00
func UpdateEndpointStatuses ( ep * endpoint . Endpoint , result * endpoint . Result ) {
if err := store . Get (). Insert ( ep , result ); err != nil {
2024-11-13 23:54:00 -05:00
logr . Errorf ( "[watchdog.UpdateEndpointStatuses] Failed to insert result in storage: %s" , err . Error ())
2021-09-22 00:04:51 -04:00
}
2020-11-26 18:09:01 -05:00
}
2021-05-18 22:29:15 -04:00
2021-10-23 16:47:12 -04:00
// Shutdown stops monitoring all endpoints
2023-08-05 06:30:15 +08:00
func Shutdown ( cfg * config . Config ) {
// Disable all the old HTTP connections
2024-05-09 22:56:16 -04:00
for _ , ep := range cfg . Endpoints {
ep . Close ()
2023-08-05 06:30:15 +08:00
}
2021-05-18 22:29:15 -04:00
cancelFunc ()
}