-
Notifications
You must be signed in to change notification settings - Fork 674
/
ray.go
686 lines (593 loc) · 22.5 KB
/
ray.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package ray
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1"
"gopkg.in/yaml.v2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/flyteorg/flyte/flyteidl/gen/pb-go/flyteidl/core"
"github.com/flyteorg/flyte/flyteidl/gen/pb-go/flyteidl/plugins"
flyteerr "github.com/flyteorg/flyte/flyteplugins/go/tasks/errors"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/logs"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery"
pluginsCore "github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/core"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/flytek8s"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/flytek8s/config"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/k8s"
"github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/tasklog"
pluginsUtils "github.com/flyteorg/flyte/flyteplugins/go/tasks/pluginmachinery/utils"
"github.com/flyteorg/flyte/flytestdlib/utils"
)
const (
rayStateMountPath = "/tmp/ray"
defaultRayStateVolName = "system-ray-state"
rayTaskType = "ray"
KindRayJob = "RayJob"
IncludeDashboard = "include-dashboard"
NodeIPAddress = "node-ip-address"
DashboardHost = "dashboard-host"
DisableUsageStatsStartParameter = "disable-usage-stats"
DisableUsageStatsStartParameterVal = "true"
)
var logTemplateRegexes = struct {
RayClusterName *regexp.Regexp
RayJobID *regexp.Regexp
}{
tasklog.MustCreateRegex("rayClusterName"),
tasklog.MustCreateRegex("rayJobID"),
}
type rayJobResourceHandler struct{}
func (rayJobResourceHandler) GetProperties() k8s.PluginProperties {
return k8s.PluginProperties{}
}
// BuildResource Creates a new ray job resource
func (rayJobResourceHandler) BuildResource(ctx context.Context, taskCtx pluginsCore.TaskExecutionContext) (client.Object, error) {
taskTemplate, err := taskCtx.TaskReader().Read(ctx)
if err != nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification, "unable to fetch task specification [%v]", err.Error())
} else if taskTemplate == nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification, "nil task specification")
}
rayJob := plugins.RayJob{}
err = utils.UnmarshalStructToPb(taskTemplate.GetCustom(), &rayJob)
if err != nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification, "invalid TaskSpecification [%v], Err: [%v]", taskTemplate.GetCustom(), err.Error())
}
podSpec, objectMeta, primaryContainerName, err := flytek8s.ToK8sPodSpec(ctx, taskCtx)
if err != nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification, "Unable to create pod spec: [%v]", err.Error())
}
var primaryContainer *v1.Container
var primaryContainerIdx int
for idx, c := range podSpec.Containers {
if c.Name == primaryContainerName {
c := c
primaryContainer = &c
primaryContainerIdx = idx
break
}
}
if primaryContainer == nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification, "Unable to get primary container from the pod: [%v]", err.Error())
}
cfg := GetConfig()
headNodeRayStartParams := make(map[string]string)
if rayJob.GetRayCluster().GetHeadGroupSpec() != nil && rayJob.RayCluster.HeadGroupSpec.RayStartParams != nil {
headNodeRayStartParams = rayJob.GetRayCluster().GetHeadGroupSpec().GetRayStartParams()
} else if headNode := cfg.Defaults.HeadNode; len(headNode.StartParameters) > 0 {
headNodeRayStartParams = headNode.StartParameters
}
if _, exist := headNodeRayStartParams[IncludeDashboard]; !exist {
headNodeRayStartParams[IncludeDashboard] = strconv.FormatBool(GetConfig().IncludeDashboard)
}
if _, exist := headNodeRayStartParams[NodeIPAddress]; !exist {
headNodeRayStartParams[NodeIPAddress] = cfg.Defaults.HeadNode.IPAddress
}
if _, exist := headNodeRayStartParams[DashboardHost]; !exist {
headNodeRayStartParams[DashboardHost] = cfg.DashboardHost
}
if _, exists := headNodeRayStartParams[DisableUsageStatsStartParameter]; !exists && !cfg.EnableUsageStats {
headNodeRayStartParams[DisableUsageStatsStartParameter] = DisableUsageStatsStartParameterVal
}
podSpec.ServiceAccountName = cfg.ServiceAccount
rayjob, err := constructRayJob(taskCtx, &rayJob, objectMeta, *podSpec, headNodeRayStartParams, primaryContainerIdx, *primaryContainer)
return rayjob, err
}
func constructRayJob(taskCtx pluginsCore.TaskExecutionContext, rayJob *plugins.RayJob, objectMeta *metav1.ObjectMeta, taskPodSpec v1.PodSpec, headNodeRayStartParams map[string]string, primaryContainerIdx int, primaryContainer v1.Container) (*rayv1.RayJob, error) {
enableIngress := true
cfg := GetConfig()
headPodSpec := taskPodSpec.DeepCopy()
headPodTemplate, err := buildHeadPodTemplate(
&headPodSpec.Containers[primaryContainerIdx],
headPodSpec,
objectMeta,
taskCtx,
rayJob.GetRayCluster().GetHeadGroupSpec(),
)
if err != nil {
return nil, err
}
rayClusterSpec := rayv1.RayClusterSpec{
HeadGroupSpec: rayv1.HeadGroupSpec{
Template: headPodTemplate,
ServiceType: v1.ServiceType(cfg.ServiceType),
EnableIngress: &enableIngress,
RayStartParams: headNodeRayStartParams,
},
WorkerGroupSpecs: []rayv1.WorkerGroupSpec{},
EnableInTreeAutoscaling: &rayJob.RayCluster.EnableAutoscaling,
}
for _, spec := range rayJob.GetRayCluster().GetWorkerGroupSpec() {
workerPodSpec := taskPodSpec.DeepCopy()
workerPodTemplate, err := buildWorkerPodTemplate(
&workerPodSpec.Containers[primaryContainerIdx],
workerPodSpec,
objectMeta,
taskCtx,
spec,
)
if err != nil {
return nil, err
}
workerNodeRayStartParams := make(map[string]string)
if spec.RayStartParams != nil {
workerNodeRayStartParams = spec.GetRayStartParams()
} else if workerNode := cfg.Defaults.WorkerNode; len(workerNode.StartParameters) > 0 {
workerNodeRayStartParams = workerNode.StartParameters
}
if _, exist := workerNodeRayStartParams[NodeIPAddress]; !exist {
workerNodeRayStartParams[NodeIPAddress] = cfg.Defaults.WorkerNode.IPAddress
}
if _, exists := workerNodeRayStartParams[DisableUsageStatsStartParameter]; !exists && !cfg.EnableUsageStats {
workerNodeRayStartParams[DisableUsageStatsStartParameter] = DisableUsageStatsStartParameterVal
}
minReplicas := spec.GetMinReplicas()
if minReplicas > spec.GetReplicas() {
minReplicas = spec.GetReplicas()
}
maxReplicas := spec.GetMaxReplicas()
if maxReplicas < spec.GetReplicas() {
maxReplicas = spec.GetReplicas()
}
workerNodeSpec := rayv1.WorkerGroupSpec{
GroupName: spec.GetGroupName(),
MinReplicas: &minReplicas,
MaxReplicas: &maxReplicas,
Replicas: &spec.Replicas,
RayStartParams: workerNodeRayStartParams,
Template: workerPodTemplate,
}
rayClusterSpec.WorkerGroupSpecs = append(rayClusterSpec.WorkerGroupSpecs, workerNodeSpec)
}
serviceAccountName := flytek8s.GetServiceAccountNameFromTaskExecutionMetadata(taskCtx.TaskExecutionMetadata())
if len(serviceAccountName) == 0 || cfg.ServiceAccount != "" {
serviceAccountName = cfg.ServiceAccount
}
rayClusterSpec.HeadGroupSpec.Template.Spec.ServiceAccountName = serviceAccountName
for index := range rayClusterSpec.WorkerGroupSpecs {
rayClusterSpec.WorkerGroupSpecs[index].Template.Spec.ServiceAccountName = serviceAccountName
}
shutdownAfterJobFinishes := cfg.ShutdownAfterJobFinishes
ttlSecondsAfterFinished := &cfg.TTLSecondsAfterFinished
if rayJob.GetShutdownAfterJobFinishes() {
shutdownAfterJobFinishes = true
ttlSecondsAfterFinished = &rayJob.TtlSecondsAfterFinished
}
submitterPodSpec := taskPodSpec.DeepCopy()
submitterPodTemplate := buildSubmitterPodTemplate(submitterPodSpec, objectMeta, taskCtx)
// TODO: This is for backward compatibility. Remove this block once runtime_env is removed from ray proto.
var runtimeEnvYaml string
runtimeEnvYaml = rayJob.GetRuntimeEnvYaml()
// If runtime_env exists but runtime_env_yaml does not, convert runtime_env to runtime_env_yaml
if rayJob.GetRuntimeEnv() != "" && rayJob.GetRuntimeEnvYaml() == "" {
runtimeEnvYaml, err = convertBase64RuntimeEnvToYaml(rayJob.GetRuntimeEnv())
if err != nil {
return nil, err
}
}
jobSpec := rayv1.RayJobSpec{
RayClusterSpec: &rayClusterSpec,
Entrypoint: strings.Join(primaryContainer.Args, " "),
ShutdownAfterJobFinishes: shutdownAfterJobFinishes,
TTLSecondsAfterFinished: *ttlSecondsAfterFinished,
RuntimeEnvYAML: runtimeEnvYaml,
SubmitterPodTemplate: &submitterPodTemplate,
}
return &rayv1.RayJob{
TypeMeta: metav1.TypeMeta{
Kind: KindRayJob,
APIVersion: rayv1.SchemeGroupVersion.String(),
},
Spec: jobSpec,
ObjectMeta: *objectMeta,
}, nil
}
func convertBase64RuntimeEnvToYaml(s string) (string, error) {
// Decode from base64
data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", err
}
// Unmarshal JSON
var obj map[string]interface{}
err = json.Unmarshal(data, &obj)
if err != nil {
return "", err
}
// Convert to YAML
y, err := yaml.Marshal(&obj)
if err != nil {
return "", err
}
return string(y), nil
}
func injectLogsSidecar(primaryContainer *v1.Container, podSpec *v1.PodSpec) {
cfg := GetConfig()
if cfg.LogsSidecar == nil {
return
}
sidecar := cfg.LogsSidecar.DeepCopy()
// Ray logs integration
var rayStateVolMount *v1.VolumeMount
// Look for an existing volume mount on the primary container, mounted at /tmp/ray
for _, vm := range primaryContainer.VolumeMounts {
if vm.MountPath == rayStateMountPath {
vm := vm
rayStateVolMount = &vm
break
}
}
// No existing volume mount exists at /tmp/ray. We create a new volume and volume
// mount and add it to the pod and container specs respectively
if rayStateVolMount == nil {
vol := v1.Volume{
Name: defaultRayStateVolName,
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
}
podSpec.Volumes = append(podSpec.Volumes, vol)
volMount := v1.VolumeMount{
Name: defaultRayStateVolName,
MountPath: rayStateMountPath,
}
primaryContainer.VolumeMounts = append(primaryContainer.VolumeMounts, volMount)
rayStateVolMount = &volMount
}
// We need to mirror the ray state volume mount into the sidecar as readonly,
// so that we can read the logs written by the head node.
readOnlyRayStateVolMount := *rayStateVolMount.DeepCopy()
readOnlyRayStateVolMount.ReadOnly = true
// Update volume mounts on sidecar
// If one already exists with the desired mount path, simply replace it. Otherwise,
// add it to sidecar's volume mounts.
foundExistingSidecarVolMount := false
for idx, vm := range sidecar.VolumeMounts {
if vm.MountPath == rayStateMountPath {
foundExistingSidecarVolMount = true
sidecar.VolumeMounts[idx] = readOnlyRayStateVolMount
}
}
if !foundExistingSidecarVolMount {
sidecar.VolumeMounts = append(sidecar.VolumeMounts, readOnlyRayStateVolMount)
}
// Add sidecar to containers
podSpec.Containers = append(podSpec.Containers, *sidecar)
}
func buildHeadPodTemplate(primaryContainer *v1.Container, basePodSpec *v1.PodSpec, objectMeta *metav1.ObjectMeta, taskCtx pluginsCore.TaskExecutionContext, spec *plugins.HeadGroupSpec) (v1.PodTemplateSpec, error) {
// Some configs are copy from https://github.com/ray-project/kuberay/blob/b72e6bdcd9b8c77a9dc6b5da8560910f3a0c3ffd/apiserver/pkg/util/cluster.go#L97
// They should always be the same, so we could hard code here.
primaryContainer.Name = "ray-head"
envs := []v1.EnvVar{
{
Name: "MY_POD_IP",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "status.podIP",
},
},
},
}
primaryContainer.Args = []string{}
primaryContainer.Env = append(primaryContainer.Env, envs...)
ports := []v1.ContainerPort{
{
Name: "redis",
ContainerPort: 6379,
},
{
Name: "head",
ContainerPort: 10001,
},
{
Name: "dashboard",
ContainerPort: 8265,
},
}
primaryContainer.Ports = append(primaryContainer.Ports, ports...)
// Inject a sidecar for capturing and exposing Ray job logs
injectLogsSidecar(primaryContainer, basePodSpec)
basePodSpec, err := mergeCustomPodSpec(primaryContainer, basePodSpec, spec.GetK8SPod())
if err != nil {
return v1.PodTemplateSpec{}, err
}
basePodSpec = flytek8s.AddTolerationsForExtendedResources(basePodSpec)
podTemplateSpec := v1.PodTemplateSpec{
Spec: *basePodSpec,
ObjectMeta: *objectMeta,
}
cfg := config.GetK8sPluginConfig()
podTemplateSpec.SetLabels(pluginsUtils.UnionMaps(cfg.DefaultLabels, podTemplateSpec.GetLabels(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetLabels())))
podTemplateSpec.SetAnnotations(pluginsUtils.UnionMaps(cfg.DefaultAnnotations, podTemplateSpec.GetAnnotations(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetAnnotations())))
return podTemplateSpec, nil
}
func buildSubmitterPodTemplate(podSpec *v1.PodSpec, objectMeta *metav1.ObjectMeta, taskCtx pluginsCore.TaskExecutionContext) v1.PodTemplateSpec {
submitterPodSpec := podSpec.DeepCopy()
podTemplateSpec := v1.PodTemplateSpec{
ObjectMeta: *objectMeta,
Spec: *submitterPodSpec,
}
cfg := config.GetK8sPluginConfig()
podTemplateSpec.SetLabels(pluginsUtils.UnionMaps(cfg.DefaultLabels, podTemplateSpec.GetLabels(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetLabels())))
podTemplateSpec.SetAnnotations(pluginsUtils.UnionMaps(cfg.DefaultAnnotations, podTemplateSpec.GetAnnotations(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetAnnotations())))
return podTemplateSpec
}
func buildWorkerPodTemplate(primaryContainer *v1.Container, basePodSpec *v1.PodSpec, objectMetadata *metav1.ObjectMeta, taskCtx pluginsCore.TaskExecutionContext, spec *plugins.WorkerGroupSpec) (v1.PodTemplateSpec, error) {
// Some configs are copy from https://github.com/ray-project/kuberay/blob/b72e6bdcd9b8c77a9dc6b5da8560910f3a0c3ffd/apiserver/pkg/util/cluster.go#L185
// They should always be the same, so we could hard code here.
primaryContainer.Name = "ray-worker"
primaryContainer.Args = []string{}
envs := []v1.EnvVar{
{
Name: "RAY_DISABLE_DOCKER_CPU_WARNING",
Value: "1",
},
{
Name: "TYPE",
Value: "worker",
},
{
Name: "CPU_REQUEST",
ValueFrom: &v1.EnvVarSource{
ResourceFieldRef: &v1.ResourceFieldSelector{
ContainerName: "ray-worker",
Resource: "requests.cpu",
},
},
},
{
Name: "CPU_LIMITS",
ValueFrom: &v1.EnvVarSource{
ResourceFieldRef: &v1.ResourceFieldSelector{
ContainerName: "ray-worker",
Resource: "limits.cpu",
},
},
},
{
Name: "MEMORY_REQUESTS",
ValueFrom: &v1.EnvVarSource{
ResourceFieldRef: &v1.ResourceFieldSelector{
ContainerName: "ray-worker",
Resource: "requests.cpu",
},
},
},
{
Name: "MEMORY_LIMITS",
ValueFrom: &v1.EnvVarSource{
ResourceFieldRef: &v1.ResourceFieldSelector{
ContainerName: "ray-worker",
Resource: "limits.cpu",
},
},
},
{
Name: "MY_POD_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "metadata.name",
},
},
},
{
Name: "MY_POD_IP",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "status.podIP",
},
},
},
}
primaryContainer.Env = append(primaryContainer.Env, envs...)
primaryContainer.Lifecycle = &v1.Lifecycle{
PreStop: &v1.LifecycleHandler{
Exec: &v1.ExecAction{
Command: []string{
"/bin/sh", "-c", "ray stop",
},
},
},
}
ports := []v1.ContainerPort{
{
Name: "redis",
ContainerPort: 6379,
},
{
Name: "head",
ContainerPort: 10001,
},
{
Name: "dashboard",
ContainerPort: 8265,
},
}
primaryContainer.Ports = append(primaryContainer.Ports, ports...)
basePodSpec, err := mergeCustomPodSpec(primaryContainer, basePodSpec, spec.GetK8SPod())
if err != nil {
return v1.PodTemplateSpec{}, err
}
basePodSpec = flytek8s.AddTolerationsForExtendedResources(basePodSpec)
cfg := config.GetK8sPluginConfig()
podTemplateSpec := v1.PodTemplateSpec{
Spec: *basePodSpec,
ObjectMeta: *objectMetadata,
}
podTemplateSpec.SetLabels(pluginsUtils.UnionMaps(cfg.DefaultLabels, podTemplateSpec.GetLabels(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetLabels())))
podTemplateSpec.SetAnnotations(pluginsUtils.UnionMaps(cfg.DefaultAnnotations, podTemplateSpec.GetAnnotations(), pluginsUtils.CopyMap(taskCtx.TaskExecutionMetadata().GetAnnotations())))
return podTemplateSpec, nil
}
// Merges a ray head/worker node custom pod specs onto task's generated pod spec
func mergeCustomPodSpec(primaryContainer *v1.Container, podSpec *v1.PodSpec, k8sPod *core.K8SPod) (*v1.PodSpec, error) {
if k8sPod == nil {
return podSpec, nil
}
if k8sPod.GetPodSpec() == nil {
return podSpec, nil
}
var customPodSpec *v1.PodSpec
err := utils.UnmarshalStructToObj(k8sPod.GetPodSpec(), &customPodSpec)
if err != nil {
return nil, flyteerr.Errorf(flyteerr.BadTaskSpecification,
"Unable to unmarshal pod spec [%v], Err: [%v]", k8sPod.GetPodSpec(), err.Error())
}
for _, container := range customPodSpec.Containers {
if container.Name != primaryContainer.Name { // Only support the primary container for now
continue
}
// Just handle resources for now
if len(container.Resources.Requests) > 0 || len(container.Resources.Limits) > 0 {
primaryContainer.Resources = container.Resources
}
}
return podSpec, nil
}
func (rayJobResourceHandler) BuildIdentityResource(ctx context.Context, taskCtx pluginsCore.TaskExecutionMetadata) (client.Object, error) {
return &rayv1.RayJob{
TypeMeta: metav1.TypeMeta{
Kind: KindRayJob,
APIVersion: rayv1.SchemeGroupVersion.String(),
},
}, nil
}
func getEventInfoForRayJob(logConfig logs.LogConfig, pluginContext k8s.PluginContext, rayJob *rayv1.RayJob) (*pluginsCore.TaskInfo, error) {
logPlugin, err := logs.InitializeLogPlugins(&logConfig)
if err != nil {
return nil, fmt.Errorf("failed to initialize log plugins. Error: %w", err)
}
var taskLogs []*core.TaskLog
taskExecID := pluginContext.TaskExecutionMetadata().GetTaskExecutionID()
input := tasklog.Input{
Namespace: rayJob.Namespace,
TaskExecutionID: taskExecID,
ExtraTemplateVars: []tasklog.TemplateVar{},
}
if rayJob.Status.JobId != "" {
input.ExtraTemplateVars = append(
input.ExtraTemplateVars,
tasklog.TemplateVar{
Regex: logTemplateRegexes.RayJobID,
Value: rayJob.Status.JobId,
},
)
}
if rayJob.Status.RayClusterName != "" {
input.ExtraTemplateVars = append(
input.ExtraTemplateVars,
tasklog.TemplateVar{
Regex: logTemplateRegexes.RayClusterName,
Value: rayJob.Status.RayClusterName,
},
)
}
// TODO: Retrieve the name of head pod from rayJob.status, and add it to task logs
// RayJob CRD does not include the name of the worker or head pod for now
logOutput, err := logPlugin.GetTaskLogs(input)
if err != nil {
return nil, fmt.Errorf("failed to generate task logs. Error: %w", err)
}
taskLogs = append(taskLogs, logOutput.TaskLogs...)
// Handling for Ray Dashboard
dashboardURLTemplate := GetConfig().DashboardURLTemplate
if dashboardURLTemplate != nil &&
rayJob.Status.DashboardURL != "" &&
rayJob.Status.JobStatus == rayv1.JobStatusRunning {
dashboardURLOutput, err := dashboardURLTemplate.GetTaskLogs(input)
if err != nil {
return nil, fmt.Errorf("failed to generate Ray dashboard link. Error: %w", err)
}
taskLogs = append(taskLogs, dashboardURLOutput.TaskLogs...)
}
return &pluginsCore.TaskInfo{Logs: taskLogs}, nil
}
func (plugin rayJobResourceHandler) GetTaskPhase(ctx context.Context, pluginContext k8s.PluginContext, resource client.Object) (pluginsCore.PhaseInfo, error) {
rayJob := resource.(*rayv1.RayJob)
info, err := getEventInfoForRayJob(GetConfig().Logs, pluginContext, rayJob)
if err != nil {
return pluginsCore.PhaseInfoUndefined, err
}
if len(rayJob.Status.JobDeploymentStatus) == 0 {
return pluginsCore.PhaseInfoQueuedWithTaskInfo(time.Now(), pluginsCore.DefaultPhaseVersion, "Scheduling", info), nil
}
var phaseInfo pluginsCore.PhaseInfo
// KubeRay creates a Ray cluster first, and then submits a Ray job to the cluster
switch rayJob.Status.JobDeploymentStatus {
case rayv1.JobDeploymentStatusInitializing:
phaseInfo, err = pluginsCore.PhaseInfoInitializing(rayJob.CreationTimestamp.Time, pluginsCore.DefaultPhaseVersion, "cluster is creating", info), nil
case rayv1.JobDeploymentStatusRunning:
phaseInfo, err = pluginsCore.PhaseInfoRunning(pluginsCore.DefaultPhaseVersion, info), nil
case rayv1.JobDeploymentStatusComplete:
phaseInfo, err = pluginsCore.PhaseInfoSuccess(info), nil
case rayv1.JobDeploymentStatusSuspended:
phaseInfo, err = pluginsCore.PhaseInfoQueuedWithTaskInfo(time.Now(), pluginsCore.DefaultPhaseVersion, "Suspended", info), nil
case rayv1.JobDeploymentStatusSuspending:
phaseInfo, err = pluginsCore.PhaseInfoQueuedWithTaskInfo(time.Now(), pluginsCore.DefaultPhaseVersion, "Suspending", info), nil
case rayv1.JobDeploymentStatusFailed:
failInfo := fmt.Sprintf("Failed to run Ray job %s with error: [%s] %s", rayJob.Name, rayJob.Status.Reason, rayJob.Status.Message)
phaseInfo, err = pluginsCore.PhaseInfoFailure(flyteerr.TaskFailedWithError, failInfo, info), nil
default:
// We already handle all known deployment status, so this should never happen unless a future version of ray
// introduced a new job status.
phaseInfo, err = pluginsCore.PhaseInfoUndefined, fmt.Errorf("unknown job deployment status: %s", rayJob.Status.JobDeploymentStatus)
}
phaseVersionUpdateErr := k8s.MaybeUpdatePhaseVersionFromPluginContext(&phaseInfo, &pluginContext)
if phaseVersionUpdateErr != nil {
return phaseInfo, phaseVersionUpdateErr
}
return phaseInfo, err
}
func init() {
if err := rayv1.AddToScheme(scheme.Scheme); err != nil {
panic(err)
}
pluginmachinery.PluginRegistry().RegisterK8sPlugin(
k8s.PluginEntry{
ID: rayTaskType,
RegisteredTaskTypes: []pluginsCore.TaskType{rayTaskType},
ResourceToWatch: &rayv1.RayJob{},
Plugin: rayJobResourceHandler{},
IsDefault: false,
CustomKubeClient: func(ctx context.Context) (pluginsCore.KubeClient, error) {
remoteConfig := GetConfig().RemoteClusterConfig
if !remoteConfig.Enabled {
// use controller-runtime KubeClient
return nil, nil
}
kubeConfig, err := k8s.KubeClientConfig(remoteConfig.Endpoint, remoteConfig.Auth)
if err != nil {
return nil, err
}
return k8s.NewDefaultKubeClient(kubeConfig)
},
})
}