-
Notifications
You must be signed in to change notification settings - Fork 946
Expand file tree
/
Copy pathtrainjob_controller.go
More file actions
315 lines (278 loc) · 11.1 KB
/
trainjob_controller.go
File metadata and controls
315 lines (278 loc) · 11.1 KB
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
/*
Copyright 2024 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 controller
import (
"context"
"errors"
"fmt"
"iter"
"slices"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/events"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
jobsetv1alpha2 "sigs.k8s.io/jobset/api/jobset/v1alpha2"
trainer "github.com/kubeflow/trainer/v2/pkg/apis/trainer/v1alpha1"
"github.com/kubeflow/trainer/v2/pkg/constants"
jobruntimes "github.com/kubeflow/trainer/v2/pkg/runtime"
"github.com/kubeflow/trainer/v2/pkg/util/trainjob"
)
type TrainJobWatcher interface {
NotifyTrainJobUpdate(oldJob, newJob *trainer.TrainJob)
}
type TrainJobReconciler struct {
log logr.Logger
client client.Client
recorder events.EventRecorder
runtimes map[string]jobruntimes.Runtime
watchers iter.Seq[TrainJobWatcher]
}
type TrainJobReconcilerOptions struct {
Watchers iter.Seq[TrainJobWatcher]
}
type TrainJobReconcilerOption func(*TrainJobReconcilerOptions)
func WithWatchers(watchers ...TrainJobWatcher) TrainJobReconcilerOption {
return func(o *TrainJobReconcilerOptions) {
o.Watchers = slices.Values(watchers)
}
}
var _ reconcile.Reconciler = (*TrainJobReconciler)(nil)
var _ predicate.TypedPredicate[*trainer.TrainJob] = (*TrainJobReconciler)(nil)
func NewTrainJobReconciler(client client.Client, recorder events.EventRecorder, runtimes map[string]jobruntimes.Runtime, opts ...TrainJobReconcilerOption) *TrainJobReconciler {
options := &TrainJobReconcilerOptions{}
for _, opt := range opts {
opt(options)
}
return &TrainJobReconciler{
log: ctrl.Log.WithName("trainjob-controller"),
client: client,
recorder: recorder,
runtimes: runtimes,
watchers: options.Watchers,
}
}
// +kubebuilder:rbac:groups="",resources=events,verbs=create;watch;update;patch
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;watch;update;patch
// +kubebuilder:rbac:groups=trainer.kubeflow.org,resources=trainjobs,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=trainer.kubeflow.org,resources=trainjobs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=trainer.kubeflow.org,resources=trainjobs/finalizers,verbs=get;update;patch
// +kubebuilder:rbac:groups=coordination.k8s.io,resources=leases,verbs=create;get;list;update
func (r *TrainJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var trainJob trainer.TrainJob
if err := r.client.Get(ctx, req.NamespacedName, &trainJob); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
log := ctrl.LoggerFrom(ctx).WithValues("trainJob", klog.KObj(&trainJob))
ctx = ctrl.LoggerInto(ctx, log)
log.V(2).Info("Reconciling TrainJob")
var err error
// Keep track of the origin TrainJob status
prevTrainJob := trainJob.DeepCopy()
// Let's clear the failed condition that could have been set previously.
// An external change to the TrainJob spec may transition it out of the Failed state.
removeFailedCondition(&trainJob)
runtimeRefGK := jobruntimes.RuntimeRefToRuntimeRegistryKey(trainJob.Spec.RuntimeRef)
runtime, ok := r.runtimes[runtimeRefGK]
if !ok {
err = fmt.Errorf("unsupported runtime: %s", runtimeRefGK)
setFailedCondition(&trainJob, fmt.Sprintf("unsupported runtime: %s", runtimeRefGK), trainer.TrainJobRuntimeNotSupportedReason)
} else if !trainjob.IsTrainJobFinished(&trainJob) {
err = r.reconcileObjects(ctx, runtime, &trainJob)
if err != nil {
// TODO (astefanutti): the error should be surfaced in the TrainJob status to indicate
// the creation of the runtime resources failed and the TrainJob is backed off until
// the next retry attempt.
// The event message is truncated to stay within the maximum length limit (1024 chars).
message := fmt.Sprintf("TrainJob resources reconciliation failed: %.950v", err.Error())
if len(err.Error()) > 950 {
message = fmt.Sprintf("%s ...", message)
}
r.recorder.Eventf(&trainJob, nil, corev1.EventTypeWarning, "TrainJobResourcesCreationFailed", "Reconciling", message)
}
}
setSuspendedCondition(&trainJob)
if statusErr := setTrainJobStatus(ctx, runtime, &trainJob); statusErr != nil {
err = errors.Join(err, statusErr)
}
deadlineResult := r.reconcileDeadline(ctx, &trainJob)
if !equality.Semantic.DeepEqual(trainJob.Status, prevTrainJob.Status) {
// TODO(astefanutti): Consider using SSA once controller-runtime client has SSA support
// for sub-resources. See: https://github.com/kubernetes-sigs/controller-runtime/issues/3183
err = errors.Join(err, r.client.Status().Patch(ctx, &trainJob, client.MergeFrom(prevTrainJob)))
}
if deadlineResult.RequeueAfter > 0 {
return deadlineResult, err
}
return ctrl.Result{}, err
}
func (r *TrainJobReconciler) reconcileObjects(ctx context.Context, runtime jobruntimes.Runtime, trainJob *trainer.TrainJob) error {
objects, err := runtime.NewObjects(ctx, trainJob)
if err != nil {
return err
}
for _, object := range objects {
if err := r.client.Apply(ctx, object, client.FieldOwner("trainer"), client.ForceOwnership); err != nil {
return err
}
}
return nil
}
func (r *TrainJobReconciler) reconcileDeadline(ctx context.Context, trainJob *trainer.TrainJob) ctrl.Result {
if trainJob.Spec.ActiveDeadlineSeconds == 0 || trainjob.IsTrainJobFinished(trainJob) || ptr.Deref(trainJob.Spec.Suspend, false) {
return ctrl.Result{}
}
startTime := trainJob.CreationTimestamp.Time
suspendedCond := meta.FindStatusCondition(trainJob.Status.Conditions, trainer.TrainJobSuspended)
if suspendedCond != nil && suspendedCond.Status == metav1.ConditionFalse {
startTime = suspendedCond.LastTransitionTime.Time
}
if startTime.IsZero() {
return ctrl.Result{}
}
deadline := startTime.Add(time.Duration(trainJob.Spec.ActiveDeadlineSeconds) * time.Second)
now := time.Now()
if now.After(deadline) {
ctrl.LoggerFrom(ctx).V(2).Info("TrainJob deadline exceeded, marking as failed",
"activeDeadlineSeconds", trainJob.Spec.ActiveDeadlineSeconds,
"startTime", startTime,
"deadline", deadline)
setFailedCondition(trainJob, constants.TrainJobDeadlineExceededMessage, trainer.TrainJobDeadlineExceededReason)
jobSet := &jobsetv1alpha2.JobSet{
ObjectMeta: metav1.ObjectMeta{Name: trainJob.Name, Namespace: trainJob.Namespace},
}
if err := client.IgnoreNotFound(r.client.Delete(ctx, jobSet)); err != nil {
ctrl.LoggerFrom(ctx).V(2).Info("Failed to delete JobSet after deadline exceeded", "error", err)
}
return ctrl.Result{}
}
requeueAfter := time.Until(deadline)
if requeueAfter <= 0 {
requeueAfter = 1 * time.Second
}
ctrl.LoggerFrom(ctx).V(2).Info("Scheduling deadline check",
"activeDeadlineSeconds", trainJob.Spec.ActiveDeadlineSeconds,
"requeueAfter", requeueAfter)
return ctrl.Result{RequeueAfter: requeueAfter}
}
func (r *TrainJobReconciler) Create(e event.TypedCreateEvent[*trainer.TrainJob]) bool {
r.log.WithValues("trainJob", klog.KObj(e.Object)).Info("TrainJob create event")
defer r.notifyWatchers(nil, e.Object)
return true
}
func (r *TrainJobReconciler) Delete(e event.TypedDeleteEvent[*trainer.TrainJob]) bool {
r.log.WithValues("trainJob", klog.KObj(e.Object)).Info("TrainJob delete event")
defer r.notifyWatchers(e.Object, nil)
return true
}
func (r *TrainJobReconciler) Update(e event.TypedUpdateEvent[*trainer.TrainJob]) bool {
r.log.WithValues("trainJob", klog.KObj(e.ObjectNew)).Info("TrainJob update event")
defer r.notifyWatchers(e.ObjectOld, e.ObjectNew)
return true
}
func (r *TrainJobReconciler) Generic(e event.TypedGenericEvent[*trainer.TrainJob]) bool {
r.log.WithValues("trainJob", klog.KObj(e.Object)).Info("TrainJob generic event")
return true
}
func (r *TrainJobReconciler) notifyWatchers(oldJob, newJob *trainer.TrainJob) {
for w := range r.watchers {
w.NotifyTrainJobUpdate(oldJob, newJob)
}
}
func setSuspendedCondition(trainJob *trainer.TrainJob) {
var newCond metav1.Condition
switch {
case ptr.Deref(trainJob.Spec.Suspend, false):
newCond = metav1.Condition{
Type: trainer.TrainJobSuspended,
Status: metav1.ConditionTrue,
Message: constants.TrainJobSuspendedMessage,
Reason: trainer.TrainJobSuspendedReason,
}
case meta.IsStatusConditionTrue(trainJob.Status.Conditions, trainer.TrainJobSuspended):
newCond = metav1.Condition{
Type: trainer.TrainJobSuspended,
Status: metav1.ConditionFalse,
Message: constants.TrainJobResumedMessage,
Reason: trainer.TrainJobResumedReason,
}
default:
return
}
meta.SetStatusCondition(&trainJob.Status.Conditions, newCond)
}
func setFailedCondition(trainJob *trainer.TrainJob, message, reason string) {
newCond := metav1.Condition{
Type: trainer.TrainJobFailed,
Status: metav1.ConditionTrue,
Message: message,
Reason: reason,
}
meta.SetStatusCondition(&trainJob.Status.Conditions, newCond)
}
func removeFailedCondition(trainJob *trainer.TrainJob) {
cond := meta.FindStatusCondition(trainJob.Status.Conditions, trainer.TrainJobFailed)
if cond != nil && cond.Reason == trainer.TrainJobDeadlineExceededReason {
return
}
meta.RemoveStatusCondition(&trainJob.Status.Conditions, trainer.TrainJobFailed)
}
func setTrainJobStatus(ctx context.Context, runtime jobruntimes.Runtime, trainJob *trainer.TrainJob) error {
deadlineCond := meta.FindStatusCondition(trainJob.Status.Conditions, trainer.TrainJobFailed)
if deadlineCond != nil && deadlineCond.Reason != trainer.TrainJobDeadlineExceededReason {
deadlineCond = nil
}
status, err := runtime.TrainJobStatus(ctx, trainJob)
if err != nil {
return err
}
if status != nil {
trainJob.Status = *status
}
if deadlineCond != nil {
meta.SetStatusCondition(&trainJob.Status.Conditions, *deadlineCond)
}
return nil
}
func (r *TrainJobReconciler) SetupWithManager(mgr ctrl.Manager, options controller.Options) error {
b := builder.TypedControllerManagedBy[reconcile.Request](mgr).
Named("trainjob_controller").
WithOptions(options).
WatchesRawSource(source.TypedKind(
mgr.GetCache(),
&trainer.TrainJob{},
&handler.TypedEnqueueRequestForObject[*trainer.TrainJob]{},
r,
))
for _, runtime := range r.runtimes {
for _, registrar := range runtime.EventHandlerRegistrars() {
if registrar != nil {
b = registrar(b, mgr.GetClient(), mgr.GetCache())
}
}
}
return b.Complete(r)
}