generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 485
/
coscheduling.go
252 lines (222 loc) · 10.4 KB
/
coscheduling.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
/*
Copyright 2020 The Kubernetes 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 coscheduling
import (
"context"
"fmt"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
corev1helpers "k8s.io/component-helpers/scheduling/corev1"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/scheduler/framework"
"sigs.k8s.io/scheduler-plugins/apis/config"
"sigs.k8s.io/scheduler-plugins/apis/scheduling"
"sigs.k8s.io/scheduler-plugins/apis/scheduling/v1alpha1"
"sigs.k8s.io/scheduler-plugins/pkg/coscheduling/core"
pgclientset "sigs.k8s.io/scheduler-plugins/pkg/generated/clientset/versioned"
pgformers "sigs.k8s.io/scheduler-plugins/pkg/generated/informers/externalversions"
"sigs.k8s.io/scheduler-plugins/pkg/util"
)
// Coscheduling is a plugin that schedules pods in a group.
type Coscheduling struct {
frameworkHandler framework.Handle
pgMgr core.Manager
scheduleTimeout *time.Duration
}
var _ framework.QueueSortPlugin = &Coscheduling{}
var _ framework.PreFilterPlugin = &Coscheduling{}
var _ framework.PostFilterPlugin = &Coscheduling{}
var _ framework.PermitPlugin = &Coscheduling{}
var _ framework.ReservePlugin = &Coscheduling{}
var _ framework.PostBindPlugin = &Coscheduling{}
var _ framework.EnqueueExtensions = &Coscheduling{}
const (
// Name is the name of the plugin used in Registry and configurations.
Name = "Coscheduling"
)
// New initializes and returns a new Coscheduling plugin.
func New(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) {
args, ok := obj.(*config.CoschedulingArgs)
if !ok {
return nil, fmt.Errorf("want args to be of type CoschedulingArgs, got %T", obj)
}
pgClient := pgclientset.NewForConfigOrDie(handle.KubeConfig())
pgInformerFactory := pgformers.NewSharedInformerFactory(pgClient, 0)
pgInformer := pgInformerFactory.Scheduling().V1alpha1().PodGroups()
podInformer := handle.SharedInformerFactory().Core().V1().Pods()
scheduleTimeDuration := time.Duration(args.PermitWaitingTimeSeconds) * time.Second
deniedPGExpirationTime := time.Duration(args.DeniedPGExpirationTimeSeconds) * time.Second
ctx := context.TODO()
pgMgr := core.NewPodGroupManager(pgClient, handle.SnapshotSharedLister(), &scheduleTimeDuration, &deniedPGExpirationTime, pgInformer, podInformer)
plugin := &Coscheduling{
frameworkHandler: handle,
pgMgr: pgMgr,
scheduleTimeout: &scheduleTimeDuration,
}
pgInformerFactory.Start(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), pgInformer.Informer().HasSynced) {
err := fmt.Errorf("WaitForCacheSync failed")
klog.ErrorS(err, "Cannot sync caches")
return nil, err
}
return plugin, nil
}
func (cs *Coscheduling) EventsToRegister() []framework.ClusterEvent {
// To register a custom event, follow the naming convention at:
// https://git.k8s.io/kubernetes/pkg/scheduler/eventhandlers.go#L403-L410
pgGVK := fmt.Sprintf("podgroups.v1alpha1.%v", scheduling.GroupName)
return []framework.ClusterEvent{
{Resource: framework.Pod, ActionType: framework.Add},
{Resource: framework.GVK(pgGVK), ActionType: framework.Add | framework.Update},
}
}
// Name returns name of the plugin. It is used in logs, etc.
func (cs *Coscheduling) Name() string {
return Name
}
// Less is used to sort pods in the scheduling queue in the following order.
// 1. Compare the priorities of Pods.
// 2. Compare the initialization timestamps of PodGroups or Pods.
// 3. Compare the keys of PodGroups/Pods: <namespace>/<podname>.
func (cs *Coscheduling) Less(podInfo1, podInfo2 *framework.QueuedPodInfo) bool {
prio1 := corev1helpers.PodPriority(podInfo1.Pod)
prio2 := corev1helpers.PodPriority(podInfo2.Pod)
if prio1 != prio2 {
return prio1 > prio2
}
creationTime1 := cs.pgMgr.GetCreationTimestamp(podInfo1.Pod, podInfo1.InitialAttemptTimestamp)
creationTime2 := cs.pgMgr.GetCreationTimestamp(podInfo2.Pod, podInfo2.InitialAttemptTimestamp)
if creationTime1.Equal(creationTime2) {
return core.GetNamespacedName(podInfo1.Pod) < core.GetNamespacedName(podInfo2.Pod)
}
return creationTime1.Before(creationTime2)
}
// PreFilter performs the following validations.
// 1. Whether the PodGroup that the Pod belongs to is on the deny list.
// 2. Whether the total number of pods in a PodGroup is less than its `minMember`.
func (cs *Coscheduling) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) *framework.Status {
// If PreFilter fails, return framework.UnschedulableAndUnresolvable to avoid
// any preemption attempts.
if err := cs.pgMgr.PreFilter(ctx, pod); err != nil {
klog.ErrorS(err, "PreFilter failed", "pod", klog.KObj(pod))
return framework.NewStatus(framework.UnschedulableAndUnresolvable, err.Error())
}
return framework.NewStatus(framework.Success, "")
}
// PostFilter is used to rejecting a group of pods if a pod does not pass PreFilter or Filter.
func (cs *Coscheduling) PostFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod,
filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {
pgName, pg := cs.pgMgr.GetPodGroup(pod)
if pg == nil {
klog.V(4).InfoS("Pod does not belong to any group", "pod", klog.KObj(pod))
return &framework.PostFilterResult{}, framework.NewStatus(framework.Unschedulable, "can not find pod group")
}
// This indicates there are already enough Pods satisfying the PodGroup,
// so don't bother to reject the whole PodGroup.
assigned := cs.pgMgr.CalculateAssignedPods(pg.Name, pod.Namespace)
if assigned >= int(pg.Spec.MinMember) {
klog.V(4).InfoS("Assigned pods", "podGroup", klog.KObj(pg), "assigned", assigned)
return &framework.PostFilterResult{}, framework.NewStatus(framework.Unschedulable)
}
// If the gap is less than/equal 10%, we may want to try subsequent Pods
// to see they can satisfy the PodGroup
notAssignedPercentage := float32(int(pg.Spec.MinMember)-assigned) / float32(pg.Spec.MinMember)
if notAssignedPercentage <= 0.1 {
klog.V(4).InfoS("A small gap of pods to reach the quorum", "podGroup", klog.KObj(pg), "percentage", notAssignedPercentage)
return &framework.PostFilterResult{}, framework.NewStatus(framework.Unschedulable)
}
// It's based on an implicit assumption: if the nth Pod failed,
// it's inferrable other Pods belonging to the same PodGroup would be very likely to fail.
cs.frameworkHandler.IterateOverWaitingPods(func(waitingPod framework.WaitingPod) {
if waitingPod.GetPod().Namespace == pod.Namespace && waitingPod.GetPod().Labels[v1alpha1.PodGroupLabel] == pg.Name {
klog.V(3).InfoS("PostFilter rejects the pod", "podGroup", klog.KObj(pg), "pod", klog.KObj(waitingPod.GetPod()))
waitingPod.Reject(cs.Name(), "optimistic rejection in PostFilter")
}
})
cs.pgMgr.AddDeniedPodGroup(pgName)
cs.pgMgr.DeletePermittedPodGroup(pgName)
return &framework.PostFilterResult{}, framework.NewStatus(framework.Unschedulable,
fmt.Sprintf("PodGroup %v gets rejected due to Pod %v is unschedulable even after PostFilter", pgName, pod.Name))
}
// PreFilterExtensions returns a PreFilterExtensions interface if the plugin implements one.
func (cs *Coscheduling) PreFilterExtensions() framework.PreFilterExtensions {
return nil
}
// Permit is the functions invoked by the framework at "Permit" extension point.
func (cs *Coscheduling) Permit(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (*framework.Status, time.Duration) {
waitTime := *cs.scheduleTimeout
s := cs.pgMgr.Permit(ctx, pod)
var retStatus *framework.Status
switch s {
case core.PodGroupNotSpecified:
return framework.NewStatus(framework.Success, ""), 0
case core.PodGroupNotFound:
return framework.NewStatus(framework.Unschedulable, "PodGroup not found"), 0
case core.Wait:
klog.InfoS("Pod is waiting to be scheduled to node", "pod", klog.KObj(pod), "nodeName", nodeName)
_, pg := cs.pgMgr.GetPodGroup(pod)
if wait := util.GetWaitTimeDuration(pg, cs.scheduleTimeout); wait != 0 {
waitTime = wait
}
retStatus = framework.NewStatus(framework.Wait)
// We will also request to move the sibling pods back to activeQ.
cs.pgMgr.ActivateSiblings(pod, state)
case core.Success:
pgFullName := util.GetPodGroupFullName(pod)
cs.frameworkHandler.IterateOverWaitingPods(func(waitingPod framework.WaitingPod) {
if util.GetPodGroupFullName(waitingPod.GetPod()) == pgFullName {
klog.V(3).InfoS("Permit allows", "pod", klog.KObj(waitingPod.GetPod()))
waitingPod.Allow(cs.Name())
}
})
klog.V(3).InfoS("Permit allows", "pod", klog.KObj(pod))
retStatus = framework.NewStatus(framework.Success)
waitTime = 0
}
return retStatus, waitTime
}
// Reserve is the functions invoked by the framework at "reserve" extension point.
func (cs *Coscheduling) Reserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {
return nil
}
// Unreserve rejects all other Pods in the PodGroup when one of the pods in the group times out.
func (cs *Coscheduling) Unreserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) {
pgName, pg := cs.pgMgr.GetPodGroup(pod)
if pg == nil {
return
}
cs.frameworkHandler.IterateOverWaitingPods(func(waitingPod framework.WaitingPod) {
if waitingPod.GetPod().Namespace == pod.Namespace && waitingPod.GetPod().Labels[v1alpha1.PodGroupLabel] == pg.Name {
klog.V(3).InfoS("Unreserve rejects", "pod", klog.KObj(waitingPod.GetPod()), "podGroup", klog.KObj(pg))
waitingPod.Reject(cs.Name(), "rejection in Unreserve")
}
})
cs.pgMgr.AddDeniedPodGroup(pgName)
cs.pgMgr.DeletePermittedPodGroup(pgName)
}
// PostBind is called after a pod is successfully bound. These plugins are used update PodGroup when pod is bound.
func (cs *Coscheduling) PostBind(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeName string) {
klog.V(5).InfoS("PostBind", "pod", klog.KObj(pod))
cs.pgMgr.PostBind(ctx, pod, nodeName)
}
// rejectPod rejects pod in cache
func (cs *Coscheduling) rejectPod(uid types.UID) {
waitingPod := cs.frameworkHandler.GetWaitingPod(uid)
if waitingPod == nil {
return
}
waitingPod.Reject(Name, "")
}