driftctl/pkg/alerter/alerter.go

76 lines
1.5 KiB
Go
Raw Normal View History

2020-12-16 12:02:02 +00:00
package alerter
import (
"fmt"
"github.com/cloudskiff/driftctl/pkg/resource"
)
type AlerterInterface interface {
SendAlert(key string, alert Alert)
}
2020-12-16 12:02:02 +00:00
type Alerter struct {
alerts Alerts
alertsCh chan Alerts
doneCh chan bool
}
func NewAlerter() *Alerter {
var alerter = &Alerter{
alerts: make(Alerts),
alertsCh: make(chan Alerts),
doneCh: make(chan bool),
}
go alerter.run()
return alerter
}
func (a *Alerter) run() {
defer func() { a.doneCh <- true }()
for alert := range a.alertsCh {
for k, v := range alert {
if val, ok := a.alerts[k]; ok {
a.alerts[k] = append(val, v...)
} else {
a.alerts[k] = v
}
}
}
}
func (a *Alerter) SetAlerts(alerts Alerts) {
a.alerts = alerts
}
2021-01-11 16:33:23 +00:00
func (a *Alerter) Retrieve() Alerts {
2020-12-16 12:02:02 +00:00
close(a.alertsCh)
<-a.doneCh
return a.alerts
}
func (a *Alerter) SendAlert(key string, alert Alert) {
a.alertsCh <- Alerts{
key: []Alert{alert},
}
}
2021-08-09 14:03:04 +00:00
func (a *Alerter) IsResourceIgnored(res *resource.Resource) bool {
alert, alertExists := a.alerts[fmt.Sprintf("%s.%s", res.ResourceType(), res.ResourceId())]
wildcardAlert, wildcardAlertExists := a.alerts[res.ResourceType()]
2020-12-16 12:02:02 +00:00
shouldIgnoreAlert := a.shouldBeIgnored(alert)
shouldIgnoreWildcardAlert := a.shouldBeIgnored(wildcardAlert)
return (alertExists && shouldIgnoreAlert) || (wildcardAlertExists && shouldIgnoreWildcardAlert)
}
func (a *Alerter) shouldBeIgnored(alert []Alert) bool {
for _, a := range alert {
if a.ShouldIgnoreResource() {
2020-12-16 12:02:02 +00:00
return true
}
}
return false
}