forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubernetes.go
108 lines (86 loc) · 1.95 KB
/
kubernetes.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
package mock
import (
"encoding/json"
"sync"
"github.com/micro/go-plugins/registry/kubernetes/client"
"github.com/micro/go-plugins/registry/kubernetes/client/api"
"github.com/micro/go-plugins/registry/kubernetes/client/watch"
)
// Client ...
type Client struct {
sync.Mutex
Pods map[string]*client.Pod
events chan watch.Event
watchers []*mockWatcher
}
// UpdatePod ...
func (m *Client) UpdatePod(podName string, pod *client.Pod) (*client.Pod, error) {
p, ok := m.Pods[podName]
if !ok {
return nil, api.ErrNotFound
}
updateMetadata(p.Metadata, pod.Metadata)
pstr, _ := json.Marshal(p)
m.events <- watch.Event{
Type: watch.Modified,
Object: json.RawMessage(pstr),
}
return nil, nil
}
// ListPods ...
func (m *Client) ListPods(labels map[string]string) (*client.PodList, error) {
var pods []client.Pod
for _, v := range m.Pods {
if labelFilterMatch(v.Metadata.Labels, labels) {
pods = append(pods, *v)
}
}
return &client.PodList{
Items: pods,
}, nil
}
// WatchPods ...
func (m *Client) WatchPods(labels map[string]string) (watch.Watch, error) {
w := &mockWatcher{
results: make(chan watch.Event),
stop: make(chan bool),
}
i := len(m.watchers) // length of watchers is current index
m.watchers = append(m.watchers, w)
go func() {
<-w.stop
m.watchers = append(m.watchers[:i], m.watchers[i+1:]...)
}()
return w, nil
}
// newClient ...
func newClient() client.Kubernetes {
return &Client{}
}
// NewClient ...
func NewClient() *Client {
c := &Client{
Pods: make(map[string]*client.Pod),
events: make(chan watch.Event),
}
// broadcast events to watchers
go func() {
for e := range c.events {
for _, w := range c.watchers {
w.results <- e
}
}
}()
return c
}
// Teardown ...
func Teardown(c *Client) {
for _, p := range c.Pods {
pstr, _ := json.Marshal(p)
c.events <- watch.Event{
Type: watch.Deleted,
Object: json.RawMessage(pstr),
}
}
c.Pods = make(map[string]*client.Pod)
}