/
forwarder.go
83 lines (77 loc) · 2.36 KB
/
forwarder.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
73
74
75
76
77
78
79
80
81
82
83
package eventer
import (
"fmt"
"strings"
"github.com/appscode/envconfig"
"github.com/appscode/go-notify"
"github.com/appscode/go-notify/unified"
"github.com/appscode/go/log"
stringz "github.com/appscode/go/strings"
"github.com/appscode/kubed/pkg/config"
"github.com/ghodss/yaml"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type EventForwarder struct {
ClusterName string
Receivers []config.Receiver
Loader envconfig.LoaderFunc
}
func (f *EventForwarder) ForwardEvent(e *apiv1.Event) error {
bytes, err := yaml.Marshal(e)
if err != nil {
return err
}
host := ""
if e.Source.Host != "" {
host = "on host " + e.Source.Host
}
for _, receiver := range f.Receivers {
emailSub := fmt.Sprintf("[%s, %s]: %s %s/%s %s %s", stringz.Val(f.ClusterName, "?"), e.Source.Component, e.InvolvedObject.Kind, e.InvolvedObject.Namespace, e.InvolvedObject.Name, e.Reason, host)
chatSub := fmt.Sprintf("[%s, %s] %s %s/%s %s %s: %s", stringz.Val(f.ClusterName, "?"), e.Source.Component, e.InvolvedObject.Kind, e.InvolvedObject.Namespace, e.InvolvedObject.Name, e.Reason, host, e.Message)
if err := f.send(emailSub, chatSub, string(bytes), receiver); err != nil {
log.Errorln(err)
}
}
return nil
}
func (f *EventForwarder) Forward(t metav1.TypeMeta, meta metav1.ObjectMeta, eventType string, v interface{}) error {
bytes, err := yaml.Marshal(v)
if err != nil {
return err
}
for _, receiver := range f.Receivers {
sub := fmt.Sprintf("[%s]: %s %s %s/%s %s", stringz.Val(f.ClusterName, "?"), t.APIVersion, t.Kind, meta.Namespace, meta.Name, eventType)
if err := f.send(sub, sub, string(bytes), receiver); err != nil {
log.Errorln(err)
}
}
return nil
}
func (f *EventForwarder) send(emailSub, chatSub, body string, receiver config.Receiver) error {
notifier, err := unified.LoadVia(strings.ToLower(receiver.Notifier), f.Loader)
if err != nil {
return err
}
switch n := notifier.(type) {
case notify.ByEmail:
return n.To(receiver.To[0], receiver.To[1:]...).
WithSubject(emailSub).
WithBody(body).
WithNoTracking().
Send()
case notify.BySMS:
return n.To(receiver.To[0], receiver.To[1:]...).
WithBody(emailSub).
Send()
case notify.ByChat:
return n.To(receiver.To[0], receiver.To[1:]...).
WithBody(chatSub).
Send()
case notify.ByPush:
return n.To(receiver.To...).
WithBody(chatSub).
Send()
}
return nil
}