This repository has been archived by the owner on Apr 25, 2024. It is now read-only.
/
watcher.go
59 lines (51 loc) · 1.54 KB
/
watcher.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
/**
* Copyright (2021, ) Institute of Software, Chinese Academy of Sciences
*/
package kubesys
import (
"bufio"
"encoding/json"
)
/**
* author: wuheng@iscas.ac.cn
* date : 2021/4/8
*/
type WatchHandler interface {
DoAdded(obj map[string]interface{})
DoModified(obj map[string]interface{})
DoDeleted(obj map[string]interface{})
}
type KubernetesWatcher struct {
Client *KubernetesClient
handler WatchHandler
}
/************************************************************
*
* initialization
*
*************************************************************/
func NewKubernetesWatcher(client *KubernetesClient, handler WatchHandler) *KubernetesWatcher {
return &KubernetesWatcher{
Client: client,
handler: handler,
}
}
func (watcher *KubernetesWatcher) Watching(url string) {
watcherClient := NewKubernetesClientWithAnalyzer(url, watcher.Client.Token, watcher.Client.analyzer)
watcherClient.http = watcher.Client.http
req, _ := watcherClient.createRequest("GET", url, nil)
resp, _ := watcherClient.http.Do(req)
reader := bufio.NewReader(resp.Body)
for {
line, _ := reader.ReadBytes('\n')
var jsonObj = make(map[string]interface{})
json.Unmarshal([]byte(line), &jsonObj)
if jsonObj["type"] == "ADDED" {
watcher.handler.DoAdded(jsonObj["object"].(map[string]interface{}))
} else if jsonObj["type"] == "MODIFIED" {
watcher.handler.DoModified(jsonObj["object"].(map[string]interface{}))
} else if jsonObj["type"] == "DELETED" {
watcher.handler.DoDeleted(jsonObj["object"].(map[string]interface{}))
}
}
}