forked from rancher/cli
/
monitor.go
157 lines (126 loc) · 2.99 KB
/
monitor.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package monitor
import (
"encoding/json"
"fmt"
"net/url"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/gorilla/websocket"
"github.com/patrickmn/go-cache"
"github.com/rancher/go-rancher/v2"
)
type Event struct {
Name string `json:"name"`
ResourceType string `json:"resourceType"`
ResourceID string `json:"resourceId"`
Data map[string]interface{} `json:"data"`
}
type Monitor struct {
sync.Mutex
c *client.RancherClient
cache *cache.Cache
subCounter int
subscriptions map[int]*Subscription
}
func (m *Monitor) Subscribe() *Subscription {
m.Lock()
defer m.Unlock()
m.subCounter++
sub := &Subscription{
id: m.subCounter,
C: make(chan *Event, 1024),
}
m.subscriptions[sub.id] = sub
return sub
}
func (m *Monitor) Unsubscribe(sub *Subscription) {
m.Lock()
defer m.Unlock()
close(sub.C)
delete(m.subscriptions, sub.id)
}
type Subscription struct {
id int
C chan *Event
}
func New(c *client.RancherClient) *Monitor {
return &Monitor{
c: c,
cache: cache.New(5*time.Minute, 30*time.Second),
subscriptions: map[int]*Subscription{},
}
}
func (m *Monitor) Start() error {
schema, ok := m.c.Schemas.CheckSchema("subscribe")
if !ok {
return fmt.Errorf("Not authorized to subscribe")
}
urlString := schema.Links["collection"]
u, err := url.Parse(urlString)
if err != nil {
return err
}
switch u.Scheme {
case "http":
u.Scheme = "ws"
case "https":
u.Scheme = "wss"
}
q := u.Query()
q.Add("eventNames", "resource.change")
q.Add("eventNames", "service.kubernetes.change")
u.RawQuery = q.Encode()
conn, resp, err := m.c.Websocket(u.String(), nil)
if err != nil {
return err
}
if resp.StatusCode != 101 {
return fmt.Errorf("Bad status code: %d %s", resp.StatusCode, resp.Status)
}
logrus.Debugf("Connected to: %s", u.String())
return m.watch(conn)
}
func (m *Monitor) Get(resourceType, resourceID string, obj interface{}) (bool, error) {
val, ok := m.cache.Get(key(resourceType, resourceID))
if !ok {
return ok, nil
}
if val == nil {
return true, nil
}
content, err := json.Marshal(val)
if err != nil {
return ok, err
}
return true, json.Unmarshal(content, obj)
}
func key(a, b string) string {
return fmt.Sprintf("%s:%s", a, b)
}
func (m *Monitor) put(resourceType, resourceID string, event *Event) {
if resourceType == "" && resourceID == "" {
return
}
m.cache.Replace(key(resourceType, resourceID), event.Data["resource"], cache.DefaultExpiration)
m.Lock()
defer m.Unlock()
for _, sub := range m.subscriptions {
sub.C <- event
}
}
func (m *Monitor) watch(conn *websocket.Conn) error {
for {
v := Event{}
_, r, err := conn.NextReader()
if err != nil {
return err
}
if err := json.NewDecoder(r).Decode(&v); err != nil {
logrus.Errorf("Failed to parse json in message")
continue
}
logrus.Debugf("Event: %s %s %s", v.Name, v.ResourceType, v.ResourceID)
m.put(v.ResourceType, v.ResourceID, &v)
}
}