This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
job_controller.go
269 lines (225 loc) · 9.57 KB
/
job_controller.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
/*
Copyright 2023 The Kubeflow 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 common
import (
"strings"
apiv1 "github.com/kubeflow/common/pkg/apis/common/v1"
"github.com/kubeflow/common/pkg/controller.v1/control"
"github.com/kubeflow/common/pkg/controller.v1/expectation"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeinformers "k8s.io/client-go/informers"
kubeclientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
corelisters "k8s.io/client-go/listers/core/v1"
schedulinglisters "k8s.io/client-go/listers/scheduling/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"sigs.k8s.io/controller-runtime/pkg/client"
volcanoclient "volcano.sh/apis/pkg/client/clientset/versioned"
)
var (
// KeyFunc is the short name to DeletionHandlingMetaNamespaceKeyFunc.
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function but it should be just fine for non delete events.
KeyFunc = cache.DeletionHandlingMetaNamespaceKeyFunc
// Prometheus metrics
createdPDBCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "created_pod_disruption_policies_total",
Help: "The total number of created pod disruption policies",
})
deletedPDBCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "deleted_pod_disruption_policies_total",
Help: "The total number of deleted pod disruption policies",
})
createdPodGroupsCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "created_pod_groups_total",
Help: "The total number of created pod groups",
})
deletedPodGroupsCount = promauto.NewCounter(prometheus.CounterOpts{
Name: "deleted_pod_groups_total",
Help: "The total number of deleted pod groups",
})
)
type GangScheduler string
const (
GangSchedulerNone GangScheduler = "None"
GangSchedulerVolcano GangScheduler = "volcano"
GangSchedulerSchedulerPlugins GangScheduler = "scheduler-plugins"
)
// JobControllerConfiguration contains configuration of operator.
type JobControllerConfiguration struct {
// GangScheduling choice: None, volcano and scheduler-plugins
GangScheduling GangScheduler
}
func (c *JobControllerConfiguration) EnableGangScheduling() bool {
return c.GangScheduling != GangSchedulerNone
}
// JobController abstracts other operators to manage the lifecycle of Jobs.
// User need to first implement the ControllerInterface(objectA) and then initialize a JobController(objectB) struct with objectA
// as the parameter.
// And then call objectB.ReconcileJobs as mentioned below, the ReconcileJobs method is the entrypoint to trigger the
// reconcile logic of the job controller
//
// ReconcileJobs(
//
// job interface{},
// replicas map[apiv1.ReplicaType]*apiv1.ReplicaSpec,
// jobStatus apiv1.JobStatus,
// runPolicy *apiv1.RunPolicy) error
type JobController struct {
Controller apiv1.ControllerInterface
Config JobControllerConfiguration
// PodControl is used to add or delete pods.
PodControl control.PodControlInterface
// ServiceControl is used to add or delete services.
ServiceControl control.ServiceControlInterface
// KubeClientSet is a standard kubernetes clientset.
KubeClientSet kubeclientset.Interface
// PodGroupControl is used to add or delete PodGroup.
PodGroupControl control.PodGroupControlInterface
// PodLister can list/get pods from the shared informer's store.
PodLister corelisters.PodLister
// ServiceLister can list/get services from the shared informer's store.
ServiceLister corelisters.ServiceLister
// PriorityClassLister can list/get priorityClasses from the shared informer's store.
PriorityClassLister schedulinglisters.PriorityClassLister
// PodInformerSynced returns true if the pod store has been synced at least once.
PodInformerSynced cache.InformerSynced
// ServiceInformerSynced returns true if the service store has been synced at least once.
ServiceInformerSynced cache.InformerSynced
// PriorityClassInformerSynced returns true if the priority class store has been synced at least once.
PriorityClassInformerSynced cache.InformerSynced
// A TTLCache of pod/services creates/deletes each job expects to see
// We use Job namespace/name + ReplicaType + pods/services as an expectation key,
// For example, there is a TFJob with namespace "tf-operator" and name "tfjob-abc":
// {
// "PS": {
// "Replicas": 2,
// },
// "Worker": {
// "Replicas": 4,
// }
// }
// We will create 4 expectations:
// - "tf-operator/tfjob-abc/ps/services", expects 2 adds.
// - "tf-operator/tfjob-abc/ps/pods", expects 2 adds.
// - "tf-operator/tfjob-abc/worker/services", expects 4 adds.
// - "tf-operator/tfjob-abc/worker/pods", expects 4 adds.
Expectations expectation.ControllerExpectationsInterface
// WorkQueue is a rate limited work queue. This is used to queue work to be
// processed instead of performing it as soon as a change happens. This
// means we can ensure we only process a fixed amount of resources at a
// time, and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
WorkQueue workqueue.RateLimitingInterface
// Recorder is an event recorder for recording Event resources to the
// Kubernetes API.
Recorder record.EventRecorder
}
type GangSchedulingSetupFunc func(jc *JobController)
var GenVolcanoSetupFunc = func(vci volcanoclient.Interface) GangSchedulingSetupFunc {
return func(jc *JobController) {
jc.Config.GangScheduling = GangSchedulerVolcano
jc.PodGroupControl = control.NewVolcanoControl(vci)
}
}
var GenSchedulerPluginsSetupFunc = func(c client.Client) GangSchedulingSetupFunc {
return func(jc *JobController) {
jc.Config.GangScheduling = GangSchedulerSchedulerPlugins
jc.PodGroupControl = control.NewSchedulerPluginsControl(c)
}
}
var GenNonGangSchedulerSetupFunc = func() GangSchedulingSetupFunc {
return func(jc *JobController) {
jc.Config.GangScheduling = GangSchedulerNone
jc.PodGroupControl = nil
}
}
func NewJobController(
controllerImpl apiv1.ControllerInterface,
reconcilerSyncPeriod metav1.Duration,
kubeClientSet kubeclientset.Interface,
setupPodGroup GangSchedulingSetupFunc,
kubeInformerFactory kubeinformers.SharedInformerFactory,
workQueueName string) JobController {
log.Debug("Creating event broadcaster")
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(log.Infof)
eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeClientSet.CoreV1().Events("")})
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerImpl.ControllerName()})
podControl := control.RealPodControl{
KubeClient: kubeClientSet,
Recorder: eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerImpl.ControllerName()}),
}
serviceControl := control.RealServiceControl{
KubeClient: kubeClientSet,
Recorder: eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerImpl.ControllerName()}),
}
jc := JobController{
Controller: controllerImpl,
Config: JobControllerConfiguration{GangScheduling: GangSchedulerNone},
PodControl: podControl,
ServiceControl: serviceControl,
KubeClientSet: kubeClientSet,
Expectations: expectation.NewControllerExpectations(),
WorkQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), workQueueName),
Recorder: recorder,
}
setupPodGroup(&jc)
return jc
}
func (jc *JobController) GenOwnerReference(obj metav1.Object) *metav1.OwnerReference {
boolPtr := func(b bool) *bool { return &b }
controllerRef := &metav1.OwnerReference{
APIVersion: jc.Controller.GetAPIGroupVersion().String(),
Kind: jc.Controller.GetAPIGroupVersionKind().Kind,
Name: obj.GetName(),
UID: obj.GetUID(),
BlockOwnerDeletion: boolPtr(true),
Controller: boolPtr(true),
}
return controllerRef
}
func (jc *JobController) GenLabels(jobName string) map[string]string {
jobName = strings.Replace(jobName, "/", "-", -1)
return map[string]string{
apiv1.OperatorNameLabel: jc.Controller.ControllerName(),
apiv1.JobNameLabel: jobName,
}
}
// resolveControllerRef returns the job referenced by a ControllerRef,
// or nil if the ControllerRef could not be resolved to a matching job
// of the correct Kind.
func (jc *JobController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) metav1.Object {
// We can't look up by UID, so look up by Name and then verify UID.
// Don't even try to look up by Name if it's the wrong Kind.
if controllerRef.Kind != jc.Controller.GetAPIGroupVersionKind().Kind {
return nil
}
job, err := jc.Controller.GetJobFromInformerCache(namespace, controllerRef.Name)
if err != nil {
return nil
}
if job.GetUID() != controllerRef.UID {
// The controller we found with this Name is not the same one that the
// ControllerRef points to.
return nil
}
return job
}