-
Notifications
You must be signed in to change notification settings - Fork 87
/
plugin.go
304 lines (258 loc) · 10.7 KB
/
plugin.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
301
302
303
304
/*
* Copyright 2023 The Multicluster-Scheduler 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 proxy
import (
"context"
"fmt"
"os"
"sync"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/scheduler/framework"
"admiralty.io/multicluster-scheduler/pkg/apis/multicluster/v1alpha1"
"admiralty.io/multicluster-scheduler/pkg/common"
agentconfig "admiralty.io/multicluster-scheduler/pkg/config/agent"
"admiralty.io/multicluster-scheduler/pkg/generated/clientset/versioned"
"admiralty.io/multicluster-scheduler/pkg/model/delegatepod"
)
type Plugin struct {
handle framework.Handle
clusterName string
targets map[string]*versioned.Clientset
targetNamespaces map[string]string
failedNodeNamesByPodUID map[types.UID]map[string]bool
mx sync.RWMutex
}
var _ framework.FilterPlugin = &Plugin{}
var _ framework.PostFilterPlugin = &Plugin{}
var _ framework.ReservePlugin = &Plugin{}
var _ framework.PreBindPlugin = &Plugin{}
var _ framework.PostBindPlugin = &Plugin{}
// Name is the name of the plugin used in the plugin registry and configurations.
const Name = "proxy"
// Name returns name of the plugin. It is used in logs, etc.
func (pl *Plugin) Name() string {
return Name
}
func virtualNodeNameToClusterName(nodeName string) string {
return nodeName
}
func (pl *Plugin) getCandidate(ctx context.Context, proxyPod *v1.Pod, clusterName string) (*v1alpha1.PodChaperon, error) {
target, ok := pl.targets[clusterName]
if !ok {
return nil, fmt.Errorf("no target for cluster name %s", clusterName)
}
l, err := target.MulticlusterV1alpha1().PodChaperons(proxyPod.Namespace).List(ctx, metav1.ListOptions{LabelSelector: common.LabelKeyParentUID + "=" + string(proxyPod.UID)})
if err != nil {
return nil, err
}
if len(l.Items) > 1 {
return nil, fmt.Errorf("more than one candidate in target cluster")
}
if len(l.Items) < 1 {
return nil, nil
}
return &l.Items[0], nil
}
func (pl *Plugin) allowCandidate(ctx context.Context, c *v1alpha1.PodChaperon, clusterName string) error {
target, ok := pl.targets[clusterName]
if !ok {
return fmt.Errorf("no target for cluster name %s", clusterName)
}
patch := []byte(`{"metadata":{"annotations":{"` + common.AnnotationKeyIsAllowed + `":"true"}}}`)
_, err := target.MulticlusterV1alpha1().PodChaperons(c.Namespace).Patch(ctx, c.Name, types.MergePatchType, patch, metav1.PatchOptions{})
return err
}
const filterWaitDuration = 30 * time.Second // TODO configure
func (pl *Plugin) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {
if nodeInfo.Node().Labels[common.LabelAndTaintKeyVirtualKubeletProvider] != common.VirtualKubeletProviderName {
return framework.NewStatus(framework.UnschedulableAndUnresolvable, "")
}
if pl.unreservedInAPreviousCycle(pod.UID, nodeInfo.Node().Name) {
return framework.NewStatus(framework.UnschedulableAndUnresolvable, "unreserved in a previous cycle")
}
if ns := nodeInfo.Node().Labels[common.LabelKeyTargetNamespace]; ns != "" && ns != pod.Namespace {
return framework.NewStatus(framework.UnschedulableAndUnresolvable, "target in different namespace")
}
// working without a candidate scheduler, we'll create a single candidate AFTER a virtual node is selected
if _, ok := pod.Annotations[common.AnnotationKeyNoReservation]; ok {
return nil
}
targetClusterName := virtualNodeNameToClusterName(nodeInfo.Node().Name)
ctx, cancel := context.WithTimeout(ctx, filterWaitDuration)
defer cancel()
var isReserved, isUnschedulable bool
if err := wait.PollImmediateUntil(time.Second, func() (bool, error) {
c, err := pl.getCandidate(ctx, pod, targetClusterName)
if err != nil {
// may be forbidden, or namespace doesn't exist, or target cluster is unavailable
// handled below as unschedulable
return false, err
}
// create candidate if not exists
if c == nil {
c, err := delegatepod.MakeDelegatePod(pod, pl.clusterName)
if err != nil {
return false, err
}
_, err = pl.targets[targetClusterName].MulticlusterV1alpha1().PodChaperons(c.Namespace).Create(ctx, c, metav1.CreateOptions{})
if err != nil {
// may be forbidden, or namespace doesn't exist, or target cluster is unavailable
// handled below as unschedulable
return false, err
}
return false, nil
}
_, isReserved = c.Annotations[common.AnnotationKeyIsReserved]
isUnschedulable = isCandidatePodUnschedulable(c)
klog.V(1).Infof("candidate %s is reserved? %v unschedulable? %v", c.Name, isReserved, isUnschedulable)
return isReserved || isUnschedulable, nil
}, ctx.Done()); err != nil {
// error or timeout or scheduling cycle done
return framework.NewStatus(framework.UnschedulableAndUnresolvable, err.Error())
}
if isUnschedulable {
return framework.NewStatus(framework.UnschedulableAndUnresolvable, "")
}
return nil
}
func (pl *Plugin) unreservedInAPreviousCycle(podUID types.UID, nodeName string) bool {
pl.mx.RLock()
defer pl.mx.RUnlock()
return pl.failedNodeNamesByPodUID[podUID][nodeName]
}
func (pl *Plugin) PostFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {
pl.failedNodeNamesByPodUID[pod.UID] = nil
return nil, framework.NewStatus(framework.Unschedulable)
}
func (pl *Plugin) Reserve(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) *framework.Status {
targetClusterName := virtualNodeNameToClusterName(nodeName)
c, err := pl.getCandidate(ctx, p, targetClusterName)
if err != nil {
return framework.NewStatus(framework.Error, err.Error())
}
if c == nil {
if _, ok := p.Annotations[common.AnnotationKeyNoReservation]; ok {
c, err := delegatepod.MakeDelegatePod(p, pl.clusterName)
if err != nil {
return framework.NewStatus(framework.Error, err.Error())
}
_, err = pl.targets[targetClusterName].MulticlusterV1alpha1().PodChaperons(c.Namespace).Create(ctx, c, metav1.CreateOptions{})
if err != nil {
// may be forbidden, or namespace doesn't exist, or target cluster is unavailable
return framework.NewStatus(framework.Error, err.Error())
}
return nil
}
return framework.NewStatus(framework.Error, "candidate not found")
}
if err = pl.allowCandidate(ctx, c, targetClusterName); err != nil {
return framework.NewStatus(framework.Error, err.Error())
}
return nil
}
func (pl *Plugin) Unreserve(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) {
// remember that this virtual node should be filtered out in next scheduling cycle (a.k.a. "filter a posteriori")
// unless we've filtered out all other nodes already
// in which case we reset the memory and try again to see if things have changed
pl.mx.Lock()
defer pl.mx.Unlock()
if pl.failedNodeNamesByPodUID[p.UID] == nil {
pl.failedNodeNamesByPodUID[p.UID] = map[string]bool{}
}
pl.failedNodeNamesByPodUID[p.UID][nodeName] = true
}
const preBindWaitDuration = 60 * time.Second // increased from arbitrary 30 seconds, because Fargate takes 30-60 seconds
func (pl *Plugin) PreBind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) *framework.Status {
// wait for candidate to be bound or not
targetClusterName := virtualNodeNameToClusterName(nodeName)
ctx, cancel := context.WithTimeout(ctx, preBindWaitDuration)
defer cancel()
// TODO subscribe to a controller instead of polling
if err := wait.PollImmediateUntil(time.Second, func() (bool, error) {
return pl.candidateIsBound(ctx, p, targetClusterName)
}, ctx.Done()); err != nil {
// or binding cycle done, candidate was never bound or not
return framework.NewStatus(framework.Error, err.Error())
}
return nil
}
func (pl *Plugin) candidateIsBound(ctx context.Context, p *v1.Pod, targetClusterName string) (bool, error) {
c, err := pl.getCandidate(ctx, p, targetClusterName)
if err != nil {
// TODO handle retriable vs. not retriable (we assume retriable for now)
// TODO log
return false, nil
}
if c == nil {
return false, fmt.Errorf("candidate not found")
}
for _, cond := range c.Status.Conditions {
if cond.Type == v1.PodScheduled {
if cond.Status == v1.ConditionTrue { // bound
return true, nil
} else { // binding failed
return false, fmt.Errorf("candidate binding failed")
}
}
}
return false, nil
}
func (pl *Plugin) PostBind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) {
targetClusterName := virtualNodeNameToClusterName(nodeName)
for clusterName, target := range pl.targets {
if clusterName == targetClusterName {
continue
}
if ns := pl.targetNamespaces[clusterName]; ns != "" && ns != p.Namespace {
continue
}
err := target.MulticlusterV1alpha1().PodChaperons(p.Namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: common.LabelKeyParentUID + "=" + string(p.UID)})
utilruntime.HandleError(err)
}
pl.mx.Lock()
defer pl.mx.Unlock()
delete(pl.failedNodeNamesByPodUID, p.UID)
// TODO if a proxy pod is deleted while pending, with failed node names, PostBind won't be called,
// so we're leaking memory, but there's no multi-cycle "FinalUnreserve" plugin, we'd have to listen to deletions...
}
// New initializes a new plugin and returns it.
func New(_ runtime.Object, h framework.Handle) (framework.Plugin, error) {
agentCfg := agentconfig.NewFromCRD(context.Background())
n := len(agentCfg.Targets)
targets := make(map[string]*versioned.Clientset, n)
targetNamespaces := make(map[string]string, n)
for _, target := range agentCfg.Targets {
client, err := versioned.NewForConfig(target.ClientConfig)
utilruntime.Must(err)
targets[target.VirtualNodeName] = client
targetNamespaces[target.VirtualNodeName] = target.Namespace
}
// TODO... cache podchaperons with lister
return &Plugin{
handle: h,
clusterName: os.Getenv("CLUSTER_NAME"),
targets: targets,
targetNamespaces: targetNamespaces,
failedNodeNamesByPodUID: map[types.UID]map[string]bool{},
}, nil
}