2021-08-27 14:15:36 +00:00
|
|
|
package webhooks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/fleetdm/fleet/v4/server"
|
2021-11-22 14:13:26 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
2021-08-27 14:15:36 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
|
|
|
kitlog "github.com/go-kit/kit/log"
|
|
|
|
"github.com/go-kit/kit/log/level"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TriggerHostStatusWebhook(
|
|
|
|
ctx context.Context,
|
|
|
|
ds fleet.Datastore,
|
|
|
|
logger kitlog.Logger,
|
|
|
|
) error {
|
2022-09-20 19:26:36 +00:00
|
|
|
appConfig, err := ds.AppConfig(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return ctxerr.Wrap(ctx, err, "getting app config")
|
|
|
|
}
|
|
|
|
|
2021-08-27 14:15:36 +00:00
|
|
|
if !appConfig.WebhookSettings.HostStatusWebhook.Enable {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
level.Debug(logger).Log("enabled", "true")
|
|
|
|
|
2021-09-14 12:11:07 +00:00
|
|
|
total, unseen, err := ds.TotalAndUnseenHostsSince(ctx, appConfig.WebhookSettings.HostStatusWebhook.DaysCount)
|
2021-08-27 14:15:36 +00:00
|
|
|
if err != nil {
|
2021-11-22 14:13:26 +00:00
|
|
|
return ctxerr.Wrap(ctx, err, "getting total and unseen hosts")
|
2021-08-27 14:15:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
percentUnseen := float64(unseen) * 100.0 / float64(total)
|
|
|
|
if percentUnseen >= appConfig.WebhookSettings.HostStatusWebhook.HostPercentage {
|
|
|
|
url := appConfig.WebhookSettings.HostStatusWebhook.DestinationURL
|
|
|
|
|
|
|
|
message := fmt.Sprintf(
|
|
|
|
"More than %.2f%% of your hosts have not checked into Fleet for more than %d days. "+
|
2021-11-09 21:58:22 +00:00
|
|
|
"You've been sent this message because the Host status webhook is enabled in your Fleet instance.",
|
2021-08-27 14:15:36 +00:00
|
|
|
percentUnseen, appConfig.WebhookSettings.HostStatusWebhook.DaysCount,
|
|
|
|
)
|
|
|
|
payload := map[string]interface{}{
|
2021-11-08 18:13:02 +00:00
|
|
|
"text": message,
|
2021-08-27 14:15:36 +00:00
|
|
|
"data": map[string]interface{}{
|
|
|
|
"unseen_hosts": unseen,
|
|
|
|
"total_hosts": total,
|
|
|
|
"days_unseen": appConfig.WebhookSettings.HostStatusWebhook.DaysCount,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
err = server.PostJSONWithTimeout(ctx, url, &payload)
|
|
|
|
if err != nil {
|
2021-11-22 14:13:26 +00:00
|
|
|
return ctxerr.Wrapf(ctx, err, "posting to %s", url)
|
2021-08-27 14:15:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|