-
Notifications
You must be signed in to change notification settings - Fork 228
/
Copy pathpager_duty.go
72 lines (57 loc) · 1.8 KB
/
pager_duty.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package pagerduty
import (
"context"
"errors"
"fmt"
"github.com/PagerDuty/go-pagerduty"
"github.com/nikoksr/notify"
)
type Client interface {
CreateIncidentWithContext(ctx context.Context, from string, options *pagerduty.CreateIncidentOptions) (*pagerduty.Incident, error) //nolint:lll // acceptable in this case, alternative makes the interface even less readable
}
// Compile-time check to verify that the PagerDuty type implements the notifier.Notifier interface.
var _ notify.Notifier = &PagerDuty{}
type PagerDuty struct {
*Config
Client Client
}
func New(token string, clientOptions ...pagerduty.ClientOptions) (*PagerDuty, error) {
if token == "" {
return nil, errors.New("access token is required")
}
pagerDuty := &PagerDuty{
Config: NewConfig(),
Client: pagerduty.NewClient(token, clientOptions...),
}
return pagerDuty, nil
}
func (s *PagerDuty) Send(ctx context.Context, subject, message string) error {
if err := s.Config.OK(); err != nil {
return fmt.Errorf("invalid configuration: %w", err)
}
incident := s.IncidentOptions(subject, message)
for _, receiver := range s.Config.Receivers {
// set the service ID to the receiver
incident.Service.ID = receiver
_, err := s.Client.CreateIncidentWithContext(ctx, s.Config.FromAddress, incident)
if err != nil {
return fmt.Errorf("create pager duty incident: %w", err)
}
}
return nil
}
func (s *PagerDuty) IncidentOptions(subject, message string) *pagerduty.CreateIncidentOptions {
return &pagerduty.CreateIncidentOptions{
Title: subject,
Service: &pagerduty.APIReference{
ID: "", // service ID will be set per receiver
Type: APIReferenceType,
},
Body: &pagerduty.APIDetails{
Type: s.Config.NotificationType,
Details: message,
},
Priority: s.Config.PriorityReference(),
Urgency: s.Config.Urgency,
}
}