forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
scheduling.go
356 lines (314 loc) · 13 KB
/
scheduling.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
/*
Copyright 2017 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 federatedtypes
import (
"bytes"
"fmt"
"reflect"
"sort"
"time"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
pkgruntime "k8s.io/apimachinery/pkg/runtime"
fedapi "k8s.io/kubernetes/federation/apis/federation"
federationapi "k8s.io/kubernetes/federation/apis/federation/v1beta1"
fedutil "k8s.io/kubernetes/federation/pkg/federation-controller/util"
hpautil "k8s.io/kubernetes/federation/pkg/federation-controller/util/hpa"
"k8s.io/kubernetes/federation/pkg/federation-controller/util/planner"
"k8s.io/kubernetes/federation/pkg/federation-controller/util/podanalyzer"
"k8s.io/kubernetes/federation/pkg/federation-controller/util/replicapreferences"
"github.com/golang/glog"
)
// ScheduleAction is used by the interface ScheduleObject of SchedulingAdapter
// to sync controller reconcile to convey the action type needed for the
// particular cluster local object in ScheduleObject
type ScheduleAction string
const (
ActionAdd = "add"
ActionDelete = "delete"
)
// ReplicaStatus contains the details of status fields from the cluster objects,
// which need accumulation to update the status of the federated object.
type ReplicaStatus struct {
Replicas int32
UpdatedReplicas int32
FullyLabeledReplicas int32
ReadyReplicas int32
AvailableReplicas int32
}
// ReplicaScheduleState is the result of adapter specific schedule() function,
// which is then used to update objects into clusters.
type ReplicaScheduleState struct {
isSelected bool
replicas int64
}
// ReplicaSchedulingInfo wraps the information that a replica type (rs or deployment)
// SchedulingAdapter needs to update objects per a schedule.
type ReplicaSchedulingInfo struct {
ScheduleState map[string]*ReplicaScheduleState
Status ReplicaStatus
}
// SchedulingAdapter defines operations for interacting with a
// federated type that requires more complex synchronization logic.
type SchedulingAdapter interface {
GetSchedule(obj pkgruntime.Object, key string, clusters []*federationapi.Cluster, informer fedutil.FederatedInformer) (interface{}, error)
ScheduleObject(cluster *federationapi.Cluster, clusterObj pkgruntime.Object, federationObjCopy pkgruntime.Object, schedulingInfo interface{}) (pkgruntime.Object, ScheduleAction, error)
UpdateFederatedStatus(obj pkgruntime.Object, schedulingInfo interface{}) error
// EquivalentIgnoringSchedule returns whether obj1 and obj2 are
// equivalent ignoring differences due to scheduling.
EquivalentIgnoringSchedule(obj1, obj2 pkgruntime.Object) bool
}
// replicaSchedulingAdapter is meant to be embedded in other type adapters that require
// workload scheduling with actual pod replicas.
type replicaSchedulingAdapter struct {
preferencesAnnotationName string
updateStatusFunc func(pkgruntime.Object, interface{}) error
}
func (a *replicaSchedulingAdapter) IsSchedulingAdapter() bool {
return true
}
func isSelected(names []string, name string) bool {
for _, val := range names {
if val == name {
return true
}
}
return false
}
func isObjHpaControlled(fedObj pkgruntime.Object) (bool, error) {
hpaSelectedClusters, error := hpautil.GetHpaTargetClusterList(fedObj)
if error != nil {
return false, error
}
if hpaSelectedClusters == nil {
return false, nil
}
return true, nil
}
// initializeScheduleState initializes the schedule state for consumption by schedule
// functions (schedule or simple schedule). After this initialization the state would
// already have information, if only a subset of clusters targetted by hpa, or all clusters
// need to be considered by the actual scheduling functions.
// The return bool named hpaControlled tells if this object is controlled by hpa or not.
func initializeScheduleState(fedObj pkgruntime.Object, clusterNames []string) (map[string]*ReplicaScheduleState, bool, error) {
initialState := make(map[string]*ReplicaScheduleState)
hpaControlled := false
hpaSelectedClusters, error := hpautil.GetHpaTargetClusterList(fedObj)
if error != nil {
return nil, hpaControlled, error
}
if hpaSelectedClusters != nil {
hpaControlled = true
}
for _, clusterName := range clusterNames {
replicaState := ReplicaScheduleState{
isSelected: false,
replicas: 0,
}
if hpaControlled {
if isSelected(hpaSelectedClusters.Names, clusterName) {
replicaState.isSelected = true
}
}
initialState[clusterName] = &replicaState
}
return initialState, hpaControlled, nil
}
func (a *replicaSchedulingAdapter) GetSchedule(obj pkgruntime.Object, key string, clusters []*federationapi.Cluster, informer fedutil.FederatedInformer) (interface{}, error) {
var clusterNames []string
for _, cluster := range clusters {
clusterNames = append(clusterNames, cluster.Name)
}
// Schedule the pods across the existing clusters.
objectGetter := func(clusterName, key string) (interface{}, bool, error) {
return informer.GetTargetStore().GetByKey(clusterName, key)
}
podsGetter := func(clusterName string, obj pkgruntime.Object) (*apiv1.PodList, error) {
clientset, err := informer.GetClientsetForCluster(clusterName)
if err != nil {
return nil, err
}
selectorObj := reflect.ValueOf(obj).Elem().FieldByName("Spec").FieldByName("Selector").Interface().(*metav1.LabelSelector)
selector, err := metav1.LabelSelectorAsSelector(selectorObj)
if err != nil {
return nil, fmt.Errorf("invalid selector: %v", err)
}
metadata, err := meta.Accessor(obj)
if err != nil {
return nil, err
}
return clientset.Core().Pods(metadata.GetNamespace()).List(metav1.ListOptions{LabelSelector: selector.String()})
}
initializedState, hpaControlled, err := initializeScheduleState(obj, clusterNames)
if err != nil {
return nil, err
}
if hpaControlled {
state, err := simpleSchedule(initializedState, key, objectGetter)
if err != nil {
return nil, err
}
return &ReplicaSchedulingInfo{
ScheduleState: state,
Status: ReplicaStatus{},
}, nil
}
currentReplicasPerCluster, estimatedCapacity, err := clustersReplicaState(clusterNames, key, objectGetter, podsGetter)
if err != nil {
return nil, err
}
fedPref, err := replicapreferences.GetAllocationPreferences(obj, a.preferencesAnnotationName)
if err != nil {
glog.Infof("Invalid workload-type specific preference, using default. object: %v, err: %v", obj, err)
}
if fedPref == nil {
fedPref = &fedapi.ReplicaAllocationPreferences{
Clusters: map[string]fedapi.ClusterPreferences{
"*": {Weight: 1},
},
}
}
plnr := planner.NewPlanner(fedPref)
return &ReplicaSchedulingInfo{
ScheduleState: schedule(plnr, obj, key, clusterNames, currentReplicasPerCluster, estimatedCapacity, initializedState),
Status: ReplicaStatus{},
}, nil
}
func (a *replicaSchedulingAdapter) ScheduleObject(cluster *federationapi.Cluster, clusterObj pkgruntime.Object, federationObjCopy pkgruntime.Object, schedulingInfo interface{}) (pkgruntime.Object, ScheduleAction, error) {
typedSchedulingInfo := schedulingInfo.(*ReplicaSchedulingInfo)
clusterScheduleState := typedSchedulingInfo.ScheduleState[cluster.Name]
if clusterObj != nil {
schedulingStatusVal := reflect.ValueOf(typedSchedulingInfo).Elem().FieldByName("Status")
objStatusVal := reflect.ValueOf(clusterObj).Elem().FieldByName("Status")
for i := 0; i < schedulingStatusVal.NumField(); i++ {
schedulingStatusField := schedulingStatusVal.Field(i)
schedulingStatusFieldName := schedulingStatusVal.Type().Field(i).Name
objStatusField := objStatusVal.FieldByName(schedulingStatusFieldName)
if objStatusField.IsValid() {
current := schedulingStatusField.Int()
additional := objStatusField.Int()
schedulingStatusField.SetInt(current + additional)
}
}
}
var action ScheduleAction = ""
specReplicas := int32(0)
// If the cluster has been selected (isSelected = true; for example by hpa)
// and the obj does not get any replicas, then it should create one with
// 0 replicas (which can then be scaled by hpa in that cluster).
// On the other hand we keep the action as "unassigned" if this cluster was
// not selected, and let the sync controller decide what to do.
if clusterScheduleState.isSelected {
specReplicas = int32(clusterScheduleState.replicas)
action = ActionAdd
}
reflect.ValueOf(federationObjCopy).Elem().FieldByName("Spec").FieldByName("Replicas").Set(reflect.ValueOf(&specReplicas))
return federationObjCopy, action, nil
}
func (a *replicaSchedulingAdapter) UpdateFederatedStatus(obj pkgruntime.Object, schedulingInfo interface{}) error {
return a.updateStatusFunc(obj, schedulingInfo)
}
// simpleSchedule get replicas from only those clusters which are selected (by hpa scheduler).
// This aim of this is to ensure that this controller does not update objects, which are
// targetted by hpa.
func simpleSchedule(scheduleState map[string]*ReplicaScheduleState, key string, objectGetter func(clusterName string, key string) (interface{}, bool, error)) (map[string]*ReplicaScheduleState, error) {
for clusterName, state := range scheduleState {
// Get and consider replicas only for those clusters which are selected by hpa.
if state.isSelected {
obj, exists, err := objectGetter(clusterName, key)
if err != nil {
return nil, err
}
if !exists {
continue
}
state.replicas = reflect.ValueOf(obj).Elem().FieldByName("Spec").FieldByName("Replicas").Elem().Int()
}
}
return scheduleState, nil
}
func schedule(planner *planner.Planner, obj pkgruntime.Object, key string, clusterNames []string, currentReplicasPerCluster map[string]int64, estimatedCapacity map[string]int64, initialState map[string]*ReplicaScheduleState) map[string]*ReplicaScheduleState {
// TODO: integrate real scheduler
replicas := reflect.ValueOf(obj).Elem().FieldByName("Spec").FieldByName("Replicas").Elem().Int()
scheduleResult, overflow := planner.Plan(replicas, clusterNames, currentReplicasPerCluster, estimatedCapacity, key)
// Ensure that all current clusters end up in the scheduling result.
// initialState, is preinitialized with all isSelected to false.
result := initialState
for clusterName := range currentReplicasPerCluster {
// We consider 0 replicas equaling to no need of creating a new object.
// isSchedule remains false in such case.
result[clusterName].replicas = 0
}
for clusterName, replicas := range scheduleResult {
result[clusterName].isSelected = true
result[clusterName].replicas = replicas
}
for clusterName, replicas := range overflow {
result[clusterName].isSelected = true
result[clusterName].replicas += replicas
}
if glog.V(4) {
buf := bytes.NewBufferString(fmt.Sprintf("Schedule - %q\n", key))
sort.Strings(clusterNames)
for _, clusterName := range clusterNames {
cur := currentReplicasPerCluster[clusterName]
target := scheduleResult[clusterName]
fmt.Fprintf(buf, "%s: current: %d target: %d", clusterName, cur, target)
if over, found := overflow[clusterName]; found {
fmt.Fprintf(buf, " overflow: %d", over)
}
if capacity, found := estimatedCapacity[clusterName]; found {
fmt.Fprintf(buf, " capacity: %d", capacity)
}
fmt.Fprintf(buf, "\n")
}
glog.V(4).Infof(buf.String())
}
return result
}
// clusterReplicaState returns information about the scheduling state of the pods running in the federated clusters.
func clustersReplicaState(
clusterNames []string,
key string,
objectGetter func(clusterName string, key string) (interface{}, bool, error),
podsGetter func(clusterName string, obj pkgruntime.Object) (*apiv1.PodList, error)) (currentReplicasPerCluster map[string]int64, estimatedCapacity map[string]int64, err error) {
currentReplicasPerCluster = make(map[string]int64)
estimatedCapacity = make(map[string]int64)
for _, clusterName := range clusterNames {
obj, exists, err := objectGetter(clusterName, key)
if err != nil {
return nil, nil, err
}
if !exists {
continue
}
replicas := reflect.ValueOf(obj).Elem().FieldByName("Spec").FieldByName("Replicas").Elem().Int()
readyReplicas := reflect.ValueOf(obj).Elem().FieldByName("Status").FieldByName("ReadyReplicas").Int()
if replicas == readyReplicas {
currentReplicasPerCluster[clusterName] = readyReplicas
} else {
pods, err := podsGetter(clusterName, obj.(pkgruntime.Object))
if err != nil {
return nil, nil, err
}
podStatus := podanalyzer.AnalyzePods(pods, time.Now())
currentReplicasPerCluster[clusterName] = int64(podStatus.RunningAndReady) // include pending as well?
unschedulable := int64(podStatus.Unschedulable)
if unschedulable > 0 {
estimatedCapacity[clusterName] = replicas - unschedulable
}
}
}
return currentReplicasPerCluster, estimatedCapacity, nil
}