fleet/server/webhooks/host_status.go
Tomas Touceda 8b908f6506
Issue 1599 offline webhook (#1777)
* wip

* Add tests and finish implementation

* Add proper default for periodicity, changes file, and documentation

* Fix tests and add defaults also to new installs

* EnableHostUsers should be true if undefined as well

* In some cases, periodicity can be zero because of the migrations

* Apply defaults when migrating appconfig

* Fix lint

* lint

* Address review comments
2021-08-27 11:15:36 -03:00

56 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package webhooks
import (
"context"
"fmt"
"github.com/fleetdm/fleet/v4/server"
"github.com/fleetdm/fleet/v4/server/fleet"
kitlog "github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/pkg/errors"
)
func TriggerHostStatusWebhook(
ctx context.Context,
ds fleet.Datastore,
logger kitlog.Logger,
appConfig *fleet.AppConfig,
) error {
if !appConfig.WebhookSettings.HostStatusWebhook.Enable {
return nil
}
level.Debug(logger).Log("enabled", "true")
total, unseen, err := ds.TotalAndUnseenHostsSince(appConfig.WebhookSettings.HostStatusWebhook.DaysCount)
if err != nil {
return errors.Wrap(err, "getting total and unseen hosts")
}
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. "+
"Youve been sent this message because the Host status webhook is enabled in your Fleet instance.",
percentUnseen, appConfig.WebhookSettings.HostStatusWebhook.DaysCount,
)
payload := map[string]interface{}{
"message": message,
"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 {
return errors.Wrapf(err, "posting to %s", url)
}
}
return nil
}