From 826a51cafb0f7a4703d89f13079751ed438338b6 Mon Sep 17 00:00:00 2001 From: Fabian Reinartz Date: Tue, 6 Oct 2015 12:23:48 +0200 Subject: [PATCH] Complete and use the SQL backed silence provider --- main.go | 7 ++++++- provider/sql.go | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 94bb2123..6186800a 100644 --- a/main.go +++ b/main.go @@ -41,7 +41,12 @@ func main() { alerts := provider.NewMemAlerts(data) notifies := provider.NewMemNotifies(data) - silences := provider.NewMemSilences() + // silences := provider.NewMemSilences() + silences, err := provider.NewSQLSilences() + if err != nil { + log.Fatal(err) + } + defer silences.Close() inhibitor := &Inhibitor{alerts: alerts} diff --git a/provider/sql.go b/provider/sql.go index 35b90102..d3bf8872 100644 --- a/provider/sql.go +++ b/provider/sql.go @@ -5,6 +5,7 @@ import ( "encoding/json" "github.com/cznic/ql" + "github.com/prometheus/common/log" "github.com/prometheus/common/model" "github.com/prometheus/alertmanager/types" @@ -56,6 +57,18 @@ CREATE INDEX IF NOT EXISTS silences_id ON silences (id()); ` func (s *SQLSilences) Mutes(lset model.LabelSet) bool { + sils, err := s.All() + if err != nil { + log.Errorf("retrieving silences failed: %s", err) + // In doubt, do not silence anything. + return false + } + + for _, sil := range sils { + if sil.Mutes(lset) { + return true + } + } return false } @@ -126,10 +139,38 @@ func (s *SQLSilences) Set(sil *types.Silence) (uint64, error) { return uint64(sid), nil } -func (s *SQLSilences) Del(uint64) error { +func (s *SQLSilences) Del(sid uint64) error { + tx, err := s.db.Begin() + if err != nil { + return err + } + + if _, err := tx.Exec(`DELETE FROM silences WHERE id() == $1`, sid); err != nil { + tx.Rollback() + return err + } + tx.Commit() + return nil } -func (s *SQLSilences) Get(uint64) (*types.Silence, error) { - return nil, nil +func (s *SQLSilences) Get(sid uint64) (*types.Silence, error) { + row := s.db.QueryRow(`SELECT id(), matchers, starts_at, ends_at, created_at, created_by, comment FROM silences WHERE id() == $1`, sid) + + var ( + sil types.Silence + matchers string + ) + err := row.Scan(&sil.ID, &matchers, &sil.StartsAt, &sil.EndsAt, &sil.CreatedAt, &sil.CreatedBy, &sil.Comment) + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + if err := json.Unmarshal([]byte(matchers), &sil.Matchers); err != nil { + return nil, err + } + + return &sil, nil }