/
core.go
366 lines (328 loc) · 12.2 KB
/
core.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
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 core
import (
"context"
"fmt"
"sync"
"time"
gochache "github.com/patrickmn/go-cache"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
informerv1 "k8s.io/client-go/informers/core/v1"
listerv1 "k8s.io/client-go/listers/core/v1"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/scheduler/framework"
"github.com/freckie/edgesched/apis/scheduling/v1alpha1"
pgclientset "github.com/freckie/edgesched/pkg/generated/clientset/versioned"
pginformer "github.com/freckie/edgesched/pkg/generated/informers/externalversions/scheduling/v1alpha1"
pglister "github.com/freckie/edgesched/pkg/generated/listers/scheduling/v1alpha1"
"github.com/freckie/edgesched/pkg/util"
)
type Status string
const (
// PodGroupNotSpecified denotes no PodGroup is specified in the Pod spec.
PodGroupNotSpecified Status = "PodGroup not specified"
// PodGroupNotFound denotes the specified PodGroup in the Pod spec is
// not found in API server.
PodGroupNotFound Status = "PodGroup not found"
Success Status = "Success"
Wait Status = "Wait"
)
// Manager defines the interfaces for PodGroup management.
type Manager interface {
PreFilter(context.Context, *corev1.Pod) error
Permit(context.Context, *corev1.Pod) Status
PostBind(context.Context, *corev1.Pod, string)
GetPodGroup(*corev1.Pod) (string, *v1alpha1.PodGroup)
GetCreationTimestamp(*corev1.Pod, time.Time) time.Time
DeletePermittedPodGroup(string)
CalculateAssignedPods(string, string) int
ActivateSiblings(pod *corev1.Pod, state *framework.CycleState)
}
// PodGroupManager defines the scheduling operation called
type PodGroupManager struct {
// pgClient is a podGroup client
pgClient pgclientset.Interface
// snapshotSharedLister is pod shared list
snapshotSharedLister framework.SharedLister
// scheduleTimeout is the default timeout for podgroup scheduling.
// If podgroup's scheduleTimeoutSeconds is set, it will be used.
scheduleTimeout *time.Duration
// permittedPG stores the podgroup name which has passed the pre resource check.
permittedPG *gochache.Cache
// pgLister is podgroup lister
pgLister pglister.PodGroupLister
// podLister is pod lister
podLister listerv1.PodLister
// reserveResourcePercentage is the reserved resource for the max finished group, range (0,100]
reserveResourcePercentage int32
sync.RWMutex
}
// NewPodGroupManager creates a new operation object.
func NewPodGroupManager(pgClient pgclientset.Interface, snapshotSharedLister framework.SharedLister, scheduleTimeout *time.Duration,
pgInformer pginformer.PodGroupInformer, podInformer informerv1.PodInformer) *PodGroupManager {
pgMgr := &PodGroupManager{
pgClient: pgClient,
snapshotSharedLister: snapshotSharedLister,
scheduleTimeout: scheduleTimeout,
pgLister: pgInformer.Lister(),
podLister: podInformer.Lister(),
permittedPG: gochache.New(3*time.Second, 3*time.Second),
}
return pgMgr
}
// ActivateSiblings stashes the pods belonging to the same PodGroup of the given pod
// in the given state, with a reserved key "kubernetes.io/pods-to-activate".
func (pgMgr *PodGroupManager) ActivateSiblings(pod *corev1.Pod, state *framework.CycleState) {
pgName := util.GetPodGroupLabel(pod)
if pgName == "" {
return
}
pods, err := pgMgr.podLister.Pods(pod.Namespace).List(
labels.SelectorFromSet(labels.Set{v1alpha1.PodGroupLabel: pgName}),
)
if err != nil {
klog.ErrorS(err, "Failed to obtain pods belong to a PodGroup", "podGroup", pgName)
return
}
for i := range pods {
if pods[i].UID == pod.UID {
pods = append(pods[:i], pods[i+1:]...)
break
}
}
if len(pods) != 0 {
if c, err := state.Read(framework.PodsToActivateKey); err == nil {
if s, ok := c.(*framework.PodsToActivate); ok {
s.Lock()
for _, pod := range pods {
namespacedName := GetNamespacedName(pod)
s.Map[namespacedName] = pod
}
s.Unlock()
}
}
}
}
// PreFilter filters out a pod if
// 1. it belongs to a podgroup that was recently denied or
// 2. the total number of pods in the podgroup is less than the minimum number of pods
// that is required to be scheduled.
func (pgMgr *PodGroupManager) PreFilter(ctx context.Context, pod *corev1.Pod) error {
klog.V(5).InfoS("Pre-filter", "pod", klog.KObj(pod))
pgFullName, pg := pgMgr.GetPodGroup(pod)
if pg == nil {
return nil
}
pods, err := pgMgr.podLister.Pods(pod.Namespace).List(
labels.SelectorFromSet(labels.Set{v1alpha1.PodGroupLabel: util.GetPodGroupLabel(pod)}),
)
if err != nil {
return fmt.Errorf("podLister list pods failed: %v", err)
}
if len(pods) < int(pg.Spec.MinMember) {
return fmt.Errorf("pre-filter pod %v cannot find enough sibling pods, "+
"current pods number: %v, minMember of group: %v", pod.Name, len(pods), pg.Spec.MinMember)
}
if pg.Spec.MinResources == nil {
return nil
}
// TODO(cwdsuzhou): This resource check may not always pre-catch unschedulable pod group.
// It only tries to PreFilter resource constraints so even if a PodGroup passed here,
// it may not necessarily pass Filter due to other constraints such as affinity/taints.
if _, ok := pgMgr.permittedPG.Get(pgFullName); ok {
return nil
}
nodes, err := pgMgr.snapshotSharedLister.NodeInfos().List()
if err != nil {
return err
}
minResources := pg.Spec.MinResources.DeepCopy()
podQuantity := resource.NewQuantity(int64(pg.Spec.MinMember), resource.DecimalSI)
minResources[corev1.ResourcePods] = *podQuantity
err = CheckClusterResource(nodes, minResources, pgFullName)
if err != nil {
klog.ErrorS(err, "Failed to PreFilter", "podGroup", klog.KObj(pg))
return err
}
pgMgr.permittedPG.Add(pgFullName, pgFullName, *pgMgr.scheduleTimeout)
return nil
}
// Permit permits a pod to run, if the minMember match, it would send a signal to chan.
func (pgMgr *PodGroupManager) Permit(ctx context.Context, pod *corev1.Pod) Status {
pgFullName, pg := pgMgr.GetPodGroup(pod)
if pgFullName == "" {
return PodGroupNotSpecified
}
if pg == nil {
// A Pod with a podGroup name but without a PodGroup found is denied.
return PodGroupNotFound
}
assigned := pgMgr.CalculateAssignedPods(pg.Name, pg.Namespace)
// The number of pods that have been assigned nodes is calculated from the snapshot.
// The current pod in not included in the snapshot during the current scheduling cycle.
if int32(assigned)+1 >= pg.Spec.MinMember {
return Success
}
return Wait
}
// PostBind updates a PodGroup's status.
// TODO: move this logic to PodGroup's controller.
func (pgMgr *PodGroupManager) PostBind(ctx context.Context, pod *corev1.Pod, nodeName string) {
pgFullName, pg := pgMgr.GetPodGroup(pod)
if pgFullName == "" || pg == nil {
return
}
pgCopy := pg.DeepCopy()
pgCopy.Status.Scheduled++
if pgCopy.Status.Scheduled >= pgCopy.Spec.MinMember {
pgCopy.Status.Phase = v1alpha1.PodGroupScheduled
} else {
pgCopy.Status.Phase = v1alpha1.PodGroupScheduling
if pgCopy.Status.ScheduleStartTime.IsZero() {
pgCopy.Status.ScheduleStartTime = metav1.Time{Time: time.Now()}
}
}
if pgCopy.Status.Phase != pg.Status.Phase {
pg, err := pgMgr.pgLister.PodGroups(pgCopy.Namespace).Get(pgCopy.Name)
if err != nil {
klog.ErrorS(err, "Failed to get PodGroup", "podGroup", klog.KObj(pgCopy))
return
}
patch, err := util.CreateMergePatch(pg, pgCopy)
if err != nil {
klog.ErrorS(err, "Failed to create merge patch", "podGroup", klog.KObj(pg), "podGroup", klog.KObj(pgCopy))
return
}
if err := pgMgr.PatchPodGroup(pg.Name, pg.Namespace, patch); err != nil {
klog.ErrorS(err, "Failed to patch", "podGroup", klog.KObj(pg))
return
}
}
}
// GetCreationTimestamp returns the creation time of a podGroup or a pod.
func (pgMgr *PodGroupManager) GetCreationTimestamp(pod *corev1.Pod, ts time.Time) time.Time {
pgName := util.GetPodGroupLabel(pod)
if len(pgName) == 0 {
return ts
}
pg, err := pgMgr.pgLister.PodGroups(pod.Namespace).Get(pgName)
if err != nil {
return ts
}
return pg.CreationTimestamp.Time
}
// DeletePermittedPodGroup deletes a podGroup that passes Pre-Filter but reaches PostFilter.
func (pgMgr *PodGroupManager) DeletePermittedPodGroup(pgFullName string) {
pgMgr.permittedPG.Delete(pgFullName)
}
// PatchPodGroup patches a podGroup.
func (pgMgr *PodGroupManager) PatchPodGroup(pgName string, namespace string, patch []byte) error {
if len(patch) == 0 {
return nil
}
_, err := pgMgr.pgClient.SchedulingV1alpha1().PodGroups(namespace).Patch(context.TODO(), pgName,
types.MergePatchType, patch, metav1.PatchOptions{})
return err
}
// GetPodGroup returns the PodGroup that a Pod belongs to in cache.
func (pgMgr *PodGroupManager) GetPodGroup(pod *corev1.Pod) (string, *v1alpha1.PodGroup) {
pgName := util.GetPodGroupLabel(pod)
if len(pgName) == 0 {
return "", nil
}
pg, err := pgMgr.pgLister.PodGroups(pod.Namespace).Get(pgName)
if err != nil {
return fmt.Sprintf("%v/%v", pod.Namespace, pgName), nil
}
return fmt.Sprintf("%v/%v", pod.Namespace, pgName), pg
}
// CalculateAssignedPods returns the number of pods that has been assigned nodes: assumed or bound.
func (pgMgr *PodGroupManager) CalculateAssignedPods(podGroupName, namespace string) int {
nodeInfos, err := pgMgr.snapshotSharedLister.NodeInfos().List()
if err != nil {
klog.ErrorS(err, "Cannot get nodeInfos from frameworkHandle")
return 0
}
var count int
for _, nodeInfo := range nodeInfos {
for _, podInfo := range nodeInfo.Pods {
pod := podInfo.Pod
if pod.Labels[v1alpha1.PodGroupLabel] == podGroupName && pod.Namespace == namespace && pod.Spec.NodeName != "" {
count++
}
}
}
return count
}
// CheckClusterResource checks if resource capacity of the cluster can satisfy <resourceRequest>.
// It returns an error detailing the resource gap if not satisfied; otherwise returns nil.
func CheckClusterResource(nodeList []*framework.NodeInfo, resourceRequest corev1.ResourceList, desiredPodGroupName string) error {
for _, info := range nodeList {
if info == nil || info.Node() == nil {
continue
}
nodeResource := util.ResourceList(getNodeResource(info, desiredPodGroupName))
for name, quant := range resourceRequest {
quant.Sub(nodeResource[name])
if quant.Sign() <= 0 {
delete(resourceRequest, name)
continue
}
resourceRequest[name] = quant
}
if len(resourceRequest) == 0 {
return nil
}
}
return fmt.Errorf("resource gap: %v", resourceRequest)
}
// GetNamespacedName returns the namespaced name.
func GetNamespacedName(obj metav1.Object) string {
return fmt.Sprintf("%v/%v", obj.GetNamespace(), obj.GetName())
}
func getNodeResource(info *framework.NodeInfo, desiredPodGroupName string) *framework.Resource {
nodeClone := info.Clone()
for _, podInfo := range info.Pods {
if podInfo == nil || podInfo.Pod == nil {
continue
}
if util.GetPodGroupFullName(podInfo.Pod) != desiredPodGroupName {
continue
}
nodeClone.RemovePod(podInfo.Pod)
}
leftResource := framework.Resource{
ScalarResources: make(map[corev1.ResourceName]int64),
}
allocatable := nodeClone.Allocatable
requested := nodeClone.Requested
leftResource.AllowedPodNumber = allocatable.AllowedPodNumber - len(nodeClone.Pods)
leftResource.MilliCPU = allocatable.MilliCPU - requested.MilliCPU
leftResource.Memory = allocatable.Memory - requested.Memory
leftResource.EphemeralStorage = allocatable.EphemeralStorage - requested.EphemeralStorage
for k, allocatableEx := range allocatable.ScalarResources {
requestEx, ok := requested.ScalarResources[k]
if !ok {
leftResource.ScalarResources[k] = allocatableEx
} else {
leftResource.ScalarResources[k] = allocatableEx - requestEx
}
}
klog.V(4).InfoS("Node left resource", "node", klog.KObj(info.Node()), "resource", leftResource)
return &leftResource
}