Skip to content

Instantly share code, notes, and snippets.

@kolobaev
Created August 14, 2019 11:41
Show Gist options
  • Save kolobaev/ba8678409b5e4eb2ebe6778592b0c0ae to your computer and use it in GitHub Desktop.
Save kolobaev/ba8678409b5e4eb2ebe6778592b0c0ae to your computer and use it in GitHub Desktop.
database/redis/escalation.go
package redis
import (
"encoding/json"
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/moira-alert/moira"
"github.com/moira-alert/moira/database/redis/reply"
)
func (connector *DbConnector) AddEscalations(
ts int64, event moira.NotificationEvent, trigger moira.TriggerData, escalations []moira.EscalationData,
) error {
c := connector.pool.Get()
defer c.Close()
c.Send("MULTI")
c.Send("SET", triggerPendingEscalationsKey(trigger.ID), "")
lastIndex := len(escalations) - 1
for i, e := range escalations {
sched := &moira.ScheduledEscalationEvent{
Escalation: e,
Event: event,
Trigger: trigger,
IsFinal: i == lastIndex,
}
bytes, err := json.Marshal(sched)
if err != nil {
return err
}
offset := e.OffsetInMinutes * 60
c.Send("ZADD", scheduledEscalationsKey, ts+offset, bytes)
}
if _, err := c.Do("EXEC"); err != nil {
return fmt.Errorf("Failed to EXEC: %s", err.Error())
}
return nil
}
func (connector *DbConnector) TriggerHasPendingEscalations(ID string) (bool, error) {
c := connector.pool.Get()
defer c.Close()
return redis.Bool(c.Do("EXISTS", triggerPendingEscalationsKey(ID)))
}
func (connector *DbConnector) AckTriggerEscalations(ID string) error {
c := connector.pool.Get()
defer c.Close()
_, err := c.Do("DEL", triggerPendingEscalationsKey(ID))
return err
}
func (connector *DbConnector) FetchScheduledEscalationEvents(to int64) ([]*moira.ScheduledEscalationEvent, error) {
c := connector.pool.Get()
defer c.Close()
c.Send("MULTI")
c.Send("ZRANGEBYSCORE", scheduledEscalationsKey, "-inf", to)
c.Send("ZREMRANGEBYSCORE", scheduledEscalationsKey, "-inf", to)
response, err := redis.Values(c.Do("EXEC"))
if err != nil {
return nil, fmt.Errorf("Failed to EXEC: %s", err)
}
if len(response) == 0 {
return make([]*moira.ScheduledEscalationEvent, 0), nil
}
return reply.ScheduledEscalationEvents(response[0], nil)
}
func triggerPendingEscalationsKey(ID string) string {
return fmt.Sprintf("moira-trigger-pending-escalations:%s", ID)
}
var scheduledEscalationsKey = "moira-notifier-scheduled-escalations"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment