-
Notifications
You must be signed in to change notification settings - Fork 103
/
pod_single_port_sd.go
256 lines (210 loc) · 6.57 KB
/
pod_single_port_sd.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
Copyright 2022 The Katalyst Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package service_discovery
import (
"context"
"fmt"
"net"
"sync"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
katalystbase "github.com/kubewharf/katalyst-core/cmd/base"
"github.com/kubewharf/katalyst-core/pkg/config/generic"
"github.com/kubewharf/katalyst-core/pkg/util/native"
)
func init() { RegisterSDManagerInitializers(ServiceDiscoveryPodSinglePort, NewPodSinglePortSDManager) }
const ServiceDiscoveryPodSinglePort = "pod-single-port"
const (
defaultPodReSyncPeriod = time.Hour * 24
defaultPodSyncPeriod = time.Second * 3
)
type podSinglePortSDManager struct {
sync.RWMutex
endpoints map[string]string
portName string
ctx context.Context
podLister corelisters.PodLister
syncedFunc cache.InformerSynced
}
func NewPodSinglePortSDManager(ctx context.Context, agentCtx *katalystbase.GenericContext,
conf *generic.ServiceDiscoveryConf) (ServiceDiscoveryManager, error) {
klog.Infof("%v sd manager enabled with pod selector: %v", ServiceDiscoveryPodSinglePort, conf.PodLister.String())
podFactory := informers.NewSharedInformerFactoryWithOptions(agentCtx.Client.KubeClient, defaultPodReSyncPeriod,
informers.WithTweakListOptions(func(options *metav1.ListOptions) {
options.LabelSelector = conf.PodLister.String()
}))
podInformer := podFactory.Core().V1().Pods()
m := &podSinglePortSDManager{
portName: conf.PodSinglePortSDConf.PortName,
ctx: ctx,
endpoints: make(map[string]string),
podLister: podInformer.Lister(),
syncedFunc: podInformer.Informer().HasSynced,
}
podInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
switch t := obj.(type) {
case *v1.Pod:
return native.PodIsReady(t)
case cache.DeletedFinalStateUnknown:
if pod, ok := t.Obj.(*v1.Pod); ok {
return native.PodIsReady(pod)
}
utilruntime.HandleError(fmt.Errorf("unable to convert object %T to *v1.Pod", obj))
return false
default:
utilruntime.HandleError(fmt.Errorf("unable to handle object: %T", obj))
return false
}
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: m.addPod,
UpdateFunc: m.updatePod,
DeleteFunc: m.deletePod,
},
})
podFactory.Start(ctx.Done())
return m, nil
}
func (m *podSinglePortSDManager) Name() string { return ServiceDiscoveryPodSinglePort }
func (m *podSinglePortSDManager) GetEndpoints() ([]string, error) {
m.RLock()
defer m.RUnlock()
endpoints := make([]string, 0, len(m.endpoints))
for _, ep := range m.endpoints {
endpoints = append(endpoints, ep)
}
return endpoints, nil
}
func (m *podSinglePortSDManager) Run() error {
if !cache.WaitForCacheSync(m.ctx.Done(), m.syncedFunc) {
return fmt.Errorf("unable to sync caches for podSinglePortSDManager")
}
go wait.Until(m.sync, defaultPodSyncPeriod, m.ctx.Done())
return nil
}
func (m *podSinglePortSDManager) addPod(obj interface{}) {
pod, ok := obj.(*v1.Pod)
if !ok {
klog.ErrorS(nil, "Cannot convert to *v1.Pod", "obj", obj)
return
}
klog.V(6).Infof("add pod %v", pod.Name)
m.addEndpoint(pod)
}
func (m *podSinglePortSDManager) updatePod(_, newObj interface{}) {
newPod, ok := newObj.(*v1.Pod)
if !ok {
klog.ErrorS(nil, "Cannot convert to *v1.Pod", "obj", newObj)
return
}
klog.V(6).Infof("update pod %v", newPod.Name)
m.addEndpoint(newPod)
}
func (m *podSinglePortSDManager) deletePod(obj interface{}) {
pod, ok := obj.(*v1.Pod)
if !ok {
klog.ErrorS(nil, "Cannot convert to *v1.Pod", "obj", obj)
return
}
klog.V(6).Infof("delete pod %v", pod.Name)
m.removeEndpoint(pod)
}
func (m *podSinglePortSDManager) removeEndpoint(pod *v1.Pod) {
m.Lock()
defer m.Unlock()
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(pod)
if err != nil {
klog.Errorf("couldn't get key for pod %#v: %v", pod, err)
return
}
delete(m.endpoints, key)
}
func (m *podSinglePortSDManager) addEndpoint(pod *v1.Pod) {
m.Lock()
defer m.Unlock()
m.addEndpointWithoutLock(pod)
}
func (m *podSinglePortSDManager) addEndpointWithoutLock(pod *v1.Pod) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(pod)
if err != nil {
klog.Errorf("couldn't get key for pod %#v: %v", pod, err)
return
} else if _, exist := m.endpoints[key]; exist {
return
}
endpoint, err := m.getPodEndpoint(pod)
if err != nil {
klog.ErrorS(err, "get new endpoint failed", "pod", pod.Name)
return
}
klog.Infof("add endpoint %s for pod %v", endpoint, key)
m.endpoints[key] = endpoint
}
func (m *podSinglePortSDManager) getPodEndpoint(pod *v1.Pod) (string, error) {
port, ok := native.ParseHostPortForPod(pod, m.portName)
if !ok {
return "", fmt.Errorf("pod has invalid valid port:%v", m.portName)
}
hostIPs, ok := native.GetPodHostIPs(pod)
if !ok {
return "", fmt.Errorf("pod has invalid valid host-ip")
}
for _, hostIP := range hostIPs {
url := fmt.Sprintf("[%s]:%d", hostIP, port)
if conn, err := net.DialTimeout("tcp", url, time.Second*5); err == nil {
if conn != nil {
_ = conn.Close()
}
return url, nil
} else {
klog.Errorf("pod %v dial %v failed: %v", pod.Name, url, err)
}
}
return "", fmt.Errorf("invalid endpoint exits")
}
func (m *podSinglePortSDManager) sync() {
m.Lock()
defer m.Unlock()
for key := range m.endpoints {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
klog.Errorf("failed to split namespace and name from key %s", key)
continue
}
if _, err := m.podLister.Pods(namespace).Get(name); err != nil {
if errors.IsNotFound(err) {
delete(m.endpoints, key)
} else {
klog.Errorf("failed to get pod %s: %s", key, err)
}
}
}
pods, err := m.podLister.List(labels.Everything())
if err != nil {
klog.Errorf("failed to list pods: %v", err)
return
}
for _, pod := range pods {
m.addEndpointWithoutLock(pod)
}
}