/
server.go
300 lines (266 loc) · 9.52 KB
/
server.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package applier
import (
"context"
"encoding/json"
"fmt"
"strings"
"k8s.io/cloud-provider-alibaba-cloud/pkg/util"
"k8s.io/cloud-provider-alibaba-cloud/pkg/controller/helper"
prvd "k8s.io/cloud-provider-alibaba-cloud/pkg/provider"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/strategicpatch"
albmodel "k8s.io/cloud-provider-alibaba-cloud/pkg/model/alb"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
albsdk "github.com/aliyun/alibaba-cloud-sdk-go/services/alb"
"github.com/go-logr/logr"
)
func NewServerApplier(kubeClient client.Client, albProvider prvd.Provider, serverGroupID string, endpoints []albmodel.BackendItem, trafficPolicy string, logger logr.Logger) *serverApplier {
return &serverApplier{
kubeClient: kubeClient,
albProvider: albProvider,
serverGroupID: serverGroupID,
endpoints: endpoints,
trafficPolicy: trafficPolicy,
logger: logger,
}
}
type serverApplier struct {
kubeClient client.Client
albProvider prvd.Provider
serverGroupID string
endpoints []albmodel.BackendItem
trafficPolicy string
logger logr.Logger
}
func (s *serverApplier) Apply(ctx context.Context) error {
traceID := ctx.Value(util.TraceID)
servers, err := s.albProvider.ListALBServers(ctx, s.serverGroupID)
if err != nil {
return err
}
s.logger.V(util.SynLogLevel).Info("apply servers",
"endpoints", s.endpoints,
"traceID", traceID)
// todo matched endpoints need check and update weight
_, unmatchedResEndpoints, unmatchedSDKEndpoints := matchEndpointWithTargets(s.endpoints, servers, s.trafficPolicy)
if len(unmatchedResEndpoints) != 0 {
s.logger.V(util.SynLogLevel).Info("apply servers",
"unmatchedResEndpoints", unmatchedResEndpoints,
"traceID", traceID)
}
if len(unmatchedSDKEndpoints) != 0 {
s.logger.V(util.SynLogLevel).Info("apply servers",
"unmatchedSDKEndpoints", unmatchedSDKEndpoints,
"traceID", traceID)
}
if len(unmatchedResEndpoints) == 0 && len(unmatchedSDKEndpoints) == 0 {
return nil
}
// If the number of servers to be added and deleted is less than 40, please call the replacement method, and the others are called separately
if len(unmatchedResEndpoints) != 0 && len(unmatchedResEndpoints) < util.BatchReplaceServersMaxNum &&
len(unmatchedSDKEndpoints) != 0 && len(unmatchedSDKEndpoints) < util.BatchReplaceServersMaxNum {
if err := s.albProvider.ReplaceALBServers(ctx, s.serverGroupID, unmatchedResEndpoints, unmatchedSDKEndpoints); err != nil {
return err
}
_ = updateTargetHealthPodCondition(ctx, s.kubeClient, helper.BuildReadinessGatePodConditionType(), s.endpoints)
return nil
}
if len(unmatchedSDKEndpoints) != 0 {
if err := s.albProvider.DeregisterALBServers(ctx, s.serverGroupID, unmatchedSDKEndpoints); err != nil {
return err
}
}
if len(unmatchedResEndpoints) != 0 {
if err := s.albProvider.RegisterALBServers(ctx, s.serverGroupID, unmatchedResEndpoints); err != nil {
return err
}
_ = updateTargetHealthPodCondition(ctx, s.kubeClient, helper.BuildReadinessGatePodConditionType(), s.endpoints)
}
return nil
}
func (s *serverApplier) PostApply(ctx context.Context) error {
return nil
}
func matchEndpointWithTargets(endpoints []albmodel.BackendItem, targets []albsdk.BackendServer, trafficPolicy string) ([]endpointAndTargetPair, []albmodel.BackendItem, []albsdk.BackendServer) {
var matchedEndpointAndTargets []endpointAndTargetPair
var unmatchedEndpoints []albmodel.BackendItem
var unmatchedTargets []albsdk.BackendServer
if len(trafficPolicy) == 0 && len(endpoints) == 0 {
trafficPolicy = albmodel.ENIBackendType
}
endpointsByUID := make(map[string]albmodel.BackendItem, len(endpoints))
for _, endpoint := range endpoints {
var endpointUID string
if isEniTrafficPolicy(trafficPolicy) {
endpointUID = fmt.Sprintf("%v:%v:%v", endpoint.ServerId, endpoint.ServerIp, endpoint.Port)
} else {
endpointUID = fmt.Sprintf("%v:%v", endpoint.ServerId, endpoint.Port)
}
klog.Infof("endpointUID: %s", endpointUID)
endpointsByUID[endpointUID] = endpoint
}
targetsByUID := make(map[string]albsdk.BackendServer, len(targets))
for _, target := range targets {
var targetUID string
if isEniTrafficPolicy(trafficPolicy) {
targetUID = fmt.Sprintf("%v:%v:%v", target.ServerId, target.ServerIp, target.Port)
} else {
targetUID = fmt.Sprintf("%v:%v", target.ServerId, target.Port)
}
klog.Infof("targetUID: %s", targetUID)
targetsByUID[targetUID] = target
}
endpointUIDs := sets.StringKeySet(endpointsByUID)
targetUIDs := sets.StringKeySet(targetsByUID)
for _, uid := range endpointUIDs.Intersection(targetUIDs).List() {
endpoint := endpointsByUID[uid]
target := targetsByUID[uid]
matchedEndpointAndTargets = append(matchedEndpointAndTargets, endpointAndTargetPair{
endpoint: endpoint,
target: target,
})
}
for _, uid := range endpointUIDs.Difference(targetUIDs).List() {
unmatchedEndpoints = append(unmatchedEndpoints, endpointsByUID[uid])
}
for _, uid := range targetUIDs.Difference(endpointUIDs).List() {
target := targetsByUID[uid]
if isServerStatusRemoving(target.Status) {
continue
}
unmatchedTargets = append(unmatchedTargets, target)
}
return matchedEndpointAndTargets, unmatchedEndpoints, unmatchedTargets
}
func isServerStatusRemoving(status string) bool {
return strings.EqualFold(status, util.ServerStatusRemoving)
}
type endpointAndTargetPair struct {
endpoint albmodel.BackendItem
target albsdk.BackendServer
}
func isEniTrafficPolicy(trafficPolicy string) bool {
return strings.EqualFold(trafficPolicy, util.TrafficPolicyEni)
}
// updateTargetHealthPodCondition will updates pod's targetHealth condition for matchedEndpointAndTargets and unmatchedEndpoints.
// returns whether further probe is needed or not
func updateTargetHealthPodCondition(ctx context.Context, kubeClient client.Client, targetHealthCondType v1.PodConditionType,
endpoints []albmodel.BackendItem) error {
klog.Infof("start updateTargetHealthPodCondition")
for _, endpointAndTarget := range endpoints {
if len(endpointAndTarget.Pod.Spec.ReadinessGates) == 0 {
continue
}
epsKey := types.NamespacedName{
Namespace: endpointAndTarget.Pod.Namespace,
Name: endpointAndTarget.Pod.Name,
}
pod := &v1.Pod{}
if err := kubeClient.Get(ctx, epsKey, pod); err != nil {
if errors.IsNotFound(err) {
klog.Errorf("updateTargetHealthPodCondition %v", err.Error())
continue
}
continue
}
_, err := updateTargetHealthPodConditionForPod(ctx, kubeClient, pod, targetHealthCondType)
if err != nil {
klog.Errorf("updateTargetHealthPodConditionForPod %v", err.Error())
continue
}
}
return nil
}
// updateTargetHealthPodConditionForPod updates pod's targetHealth condition for a single pod and its matched target.
// returns whether further probe is needed or not.
func updateTargetHealthPodConditionForPod(ctx context.Context, kubeClient client.Client, pod *v1.Pod, targetHealthCondType v1.PodConditionType) (bool, error) {
if !HasAnyOfReadinessGates(pod, []v1.PodConditionType{targetHealthCondType}) {
return false, nil
}
targetHealthCondStatus := v1.ConditionTrue
var reason, message string
existingTargetHealthCond, exists := GetPodCondition(pod, targetHealthCondType)
// we skip patch pod if it matches current computed status/reason/message.
if exists &&
existingTargetHealthCond.Status == targetHealthCondStatus &&
existingTargetHealthCond.Reason == reason &&
existingTargetHealthCond.Message == message {
return true, nil
}
newTargetHealthCond := v1.PodCondition{
Type: targetHealthCondType,
Status: targetHealthCondStatus,
Reason: reason,
Message: message,
}
if !exists || existingTargetHealthCond.Status != targetHealthCondStatus {
newTargetHealthCond.LastTransitionTime = metav1.Now()
}
patch, err := buildPodConditionPatch(pod, newTargetHealthCond)
if err != nil {
return false, err
}
k8sPod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Namespace: pod.Namespace,
Name: pod.Name,
UID: pod.UID,
},
}
if err := kubeClient.Status().Patch(ctx, k8sPod, patch); err != nil {
if errors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func buildPodConditionPatch(pod *v1.Pod, condition v1.PodCondition) (client.Patch, error) {
oldData, err := json.Marshal(v1.Pod{
Status: v1.PodStatus{
Conditions: nil,
},
})
if err != nil {
return nil, err
}
newData, err := json.Marshal(v1.Pod{
ObjectMeta: metav1.ObjectMeta{UID: pod.UID}, // only put the uid in the new object to ensure it appears in the patch as a precondition
Status: v1.PodStatus{
Conditions: []v1.PodCondition{condition},
},
})
if err != nil {
return nil, err
}
patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Pod{})
if err != nil {
return nil, err
}
return client.RawPatch(types.StrategicMergePatchType, patchBytes), nil
}
// HasAnyOfReadinessGates returns whether podInfo has any of these readinessGates
func HasAnyOfReadinessGates(pod *v1.Pod, conditionTypes []v1.PodConditionType) bool {
for _, rg := range pod.Spec.ReadinessGates {
for _, conditionType := range conditionTypes {
if rg.ConditionType == conditionType {
return true
}
}
}
return false
}
// GetPodCondition will get Pod's condition.
func GetPodCondition(pod *v1.Pod, conditionType v1.PodConditionType) (v1.PodCondition, bool) {
for _, cond := range pod.Status.Conditions {
if cond.Type == conditionType {
return cond, true
}
}
return v1.PodCondition{}, false
}