/
endpoint.go
194 lines (162 loc) · 4.66 KB
/
endpoint.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
package k8sclient
import (
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/aws/amazon-cloudwatch-agent/internal/containerinsightscommon"
"github.com/aws/amazon-cloudwatch-agent/internal/k8sCommon/k8sutil"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
type Service struct {
ServiceName string
Namespace string
}
func NewService(name, namespace string) Service {
return Service{ServiceName: name, Namespace: namespace}
}
type EpClient interface {
PodKeyToServiceNames() map[string][]string
ServiceToPodNum() map[Service]int
Init()
Shutdown()
}
type epClient struct {
sync.RWMutex
stopChan chan struct{}
store *ObjStore
inited bool
podKeyToServiceNamesMap map[string][]string
serviceToPodNumMap map[Service]int //only running pods will show behind endpoints
}
func (c *epClient) PodKeyToServiceNames() map[string][]string {
if !c.inited {
c.Init()
}
if c.store.Refreshed() {
c.refresh()
}
c.RLock()
defer c.RUnlock()
return c.podKeyToServiceNamesMap
}
func (c *epClient) ServiceToPodNum() map[Service]int {
if !c.inited {
c.Init()
}
if c.store.Refreshed() {
c.refresh()
}
c.RLock()
defer c.RUnlock()
return c.serviceToPodNumMap
}
func (c *epClient) refresh() {
c.Lock()
defer c.Unlock()
objsList := c.store.List()
tmpMap := make(map[string]map[string]struct{}) //pod key to service names
serviceToPodNumMapNew := make(map[Service]int)
for _, obj := range objsList {
ep := obj.(*endpointInfo)
serviceName := ep.name
namespace := ep.namespace
// each obj should be a uniq service.
// ignore the service which has 0 pods.
if len(ep.podKeyList) > 0 {
serviceToPodNumMapNew[NewService(serviceName, namespace)] = len(ep.podKeyList)
}
for _, podKey := range ep.podKeyList {
var serviceNamesMap map[string]struct{}
var ok bool
if serviceNamesMap, ok = tmpMap[podKey]; !ok {
tmpMap[podKey] = make(map[string]struct{})
}
serviceNamesMap = tmpMap[podKey]
serviceNamesMap[serviceName] = struct{}{}
}
}
podKeyToServiceNamesMapNew := make(map[string][]string)
for podKey, serviceNamesMap := range tmpMap {
serviceNamesList := make([]string, 0, len(serviceNamesMap))
for serviceName := range serviceNamesMap {
serviceNamesList = append(serviceNamesList, serviceName)
}
podKeyToServiceNamesMapNew[podKey] = serviceNamesList
}
c.podKeyToServiceNamesMap = podKeyToServiceNamesMapNew
c.serviceToPodNumMap = serviceToPodNumMapNew
}
func (c *epClient) Init() {
c.Lock()
defer c.Unlock()
if c.inited {
return
}
c.stopChan = make(chan struct{})
c.store = NewObjStore(transformFuncEndpoint)
lw := createEndpointListWatch(Get().ClientSet, metav1.NamespaceAll)
reflector := cache.NewReflector(lw, &v1.Endpoints{}, c.store, 0)
go reflector.Run(c.stopChan)
if err := wait.Poll(50*time.Millisecond, 2*time.Second, func() (done bool, err error) {
return reflector.LastSyncResourceVersion() != "", nil
}); err != nil {
log.Printf("W! Endpoint initial sync timeout: %v", err)
}
c.inited = true
}
func (c *epClient) Shutdown() {
c.Lock()
defer c.Unlock()
if !c.inited {
return
}
close(c.stopChan)
c.inited = false
}
func transformFuncEndpoint(obj interface{}) (interface{}, error) {
endpoint, ok := obj.(*v1.Endpoints)
if !ok {
return nil, errors.New(fmt.Sprintf("input obj %v is not Endpoint type", obj))
}
info := new(endpointInfo)
info.name = endpoint.Name
info.namespace = endpoint.Namespace
info.podKeyList = []string{}
if subsets := endpoint.Subsets; subsets != nil {
for _, subset := range subsets {
if addresses := subset.Addresses; addresses != nil {
for _, address := range addresses {
if targetRef := address.TargetRef; targetRef != nil && targetRef.Kind == containerinsightscommon.TypePod {
podKey := k8sutil.CreatePodKey(targetRef.Namespace, targetRef.Name)
if podKey == "" {
log.Printf("W! Invalid pod metadata, namespace: %s, podName: %s", targetRef.Namespace, targetRef.Name)
continue
}
info.podKeyList = append(info.podKeyList, podKey)
}
}
}
}
}
return info, nil
}
func createEndpointListWatch(client kubernetes.Interface, ns string) cache.ListerWatcher {
return &cache.ListWatch{
ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) {
return client.CoreV1().Endpoints(ns).List(opts)
},
WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) {
return client.CoreV1().Endpoints(ns).Watch(opts)
},
}
}