-
Notifications
You must be signed in to change notification settings - Fork 462
/
Copy pathutil.go
455 lines (394 loc) · 13.3 KB
/
util.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
package utils
import (
"crypto/sha1"
"encoding/base32"
"fmt"
"math"
"os"
"reflect"
"strconv"
"strings"
"time"
"unicode"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/rand"
"github.com/sirupsen/logrus"
rayiov1alpha1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1alpha1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
RayClusterSuffix = "-raycluster-"
DashboardName = "dashboard"
ServeName = "serve"
ClusterDomainEnvKey = "CLUSTER_DOMAIN"
DefaultDomainName = "cluster.local"
)
// GetClusterDomainName returns cluster's domain name
func GetClusterDomainName() string {
if domain := os.Getenv(ClusterDomainEnvKey); len(domain) > 0 {
return domain
}
// Return default domain name.
return DefaultDomainName
}
// IsCreated returns true if pod has been created and is maintained by the API server
func IsCreated(pod *corev1.Pod) bool {
return pod.Status.Phase != ""
}
// IsRunningAndReady returns true if pod is in the PodRunning Phase, if it has a condition of PodReady.
func IsRunningAndReady(pod *corev1.Pod) bool {
if pod.Status.Phase != corev1.PodRunning {
return false
}
for _, cond := range pod.Status.Conditions {
if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {
return true
}
}
return false
}
// CheckName makes sure the name does not start with a numeric value and the total length is < 63 char
func CheckName(s string) string {
maxLength := 50 // 63 - (max(8,6) + 5 ) // 6 to 8 char are consumed at the end with "-head-" or -worker- + 5 generated.
if len(s) > maxLength {
// shorten the name
offset := int(math.Abs(float64(maxLength) - float64(len(s))))
fmt.Printf("pod name is too long: len = %v, we will shorten it by offset = %v\n", len(s), offset)
s = s[offset:]
}
// cannot start with a numeric value
if unicode.IsDigit(rune(s[0])) {
s = "r" + s[1:]
}
// cannot start with a punctuation
if unicode.IsPunct(rune(s[0])) {
fmt.Println(s)
s = "r" + s[1:]
}
return s
}
// CheckLabel makes sure the label value does not start with a punctuation and the total length is < 63 char
func CheckLabel(s string) string {
maxLenght := 63
if len(s) > maxLenght {
// shorten the name
offset := int(math.Abs(float64(maxLenght) - float64(len(s))))
fmt.Printf("label value is too long: len = %v, we will shorten it by offset = %v\n", len(s), offset)
s = s[offset:]
}
// cannot start with a punctuation
if unicode.IsPunct(rune(s[0])) {
fmt.Println(s)
s = "r" + s[1:]
}
return s
}
// Before Get substring before a string.
func Before(value string, a string) string {
pos := strings.Index(value, a)
if pos == -1 {
return ""
}
return value[0:pos]
}
// FormatInt returns the string representation of i in the given base,
// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
// for digit values >= 10.
func FormatInt32(n int32) string {
return strconv.FormatInt(int64(n), 10)
}
// GetNamespace return namespace
func GetNamespace(metaData metav1.ObjectMeta) string {
if metaData.Namespace == "" {
return "default"
}
return metaData.Namespace
}
// GenerateServiceName generates a ray head service name from cluster name
func GenerateServiceName(clusterName string) string {
return CheckName(fmt.Sprintf("%s-%s-%s", clusterName, rayiov1alpha1.HeadNode, "svc"))
}
// GenerateFQDNServiceName generates a Fully Qualified Domain Name.
func GenerateFQDNServiceName(clusterName string, namespace string) string {
return fmt.Sprintf("%s.%s.svc.%s", GenerateServiceName(clusterName), namespace, GetClusterDomainName())
}
// ExtractRayIPFromFQDN extracts the head service name (i.e., RAY_IP, deprecated) from a fully qualified
// domain name (FQDN). This function is provided for backward compatibility purposes only.
func ExtractRayIPFromFQDN(fqdnRayIP string) string {
return strings.Split(fqdnRayIP, ".")[0]
}
// GenerateDashboardServiceName generates a ray head service name from cluster name
func GenerateDashboardServiceName(clusterName string) string {
return fmt.Sprintf("%s-%s-%s", clusterName, DashboardName, "svc")
}
// GenerateDashboardAgentLabel generates label value for agent service selector.
func GenerateDashboardAgentLabel(clusterName string) string {
return fmt.Sprintf("%s-%s", clusterName, DashboardName)
}
// GenerateServeServiceName generates name for serve service.
func GenerateServeServiceName(serviceName string) string {
return fmt.Sprintf("%s-%s-%s", serviceName, ServeName, "svc")
}
// GenerateServeServiceLabel generates label value for serve service selector.
func GenerateServeServiceLabel(serviceName string) string {
return fmt.Sprintf("%s-%s", serviceName, ServeName)
}
// GenerateIngressName generates an ingress name from cluster name
func GenerateIngressName(clusterName string) string {
return fmt.Sprintf("%s-%s-%s", clusterName, rayiov1alpha1.HeadNode, "ingress")
}
// GenerateRayClusterName generates a ray cluster name from ray service name
func GenerateRayClusterName(serviceName string) string {
return fmt.Sprintf("%s%s%s", serviceName, RayClusterSuffix, rand.String(5))
}
// GenerateRayJobId generates a ray job id for submission
func GenerateRayJobId(rayjob string) string {
return fmt.Sprintf("%s-%s", rayjob, rand.String(5))
}
// GenerateIdentifier generates identifier of same group pods
func GenerateIdentifier(clusterName string, nodeType rayiov1alpha1.RayNodeType) string {
return fmt.Sprintf("%s-%s", clusterName, nodeType)
}
// TODO: find target container through name instead of using index 0.
// FindRayContainerIndex finds the ray head/worker container's index in the pod
func FindRayContainerIndex(spec corev1.PodSpec) (index int) {
// We only support one container at this moment. We definitely need a better way to filter out sidecar containers.
if len(spec.Containers) > 1 {
logrus.Warnf("Pod has multiple containers, we choose index=0 as Ray container")
}
return 0
}
// CalculateDesiredReplicas calculate desired worker replicas at the cluster level
func CalculateDesiredReplicas(cluster *rayiov1alpha1.RayCluster) int32 {
count := int32(0)
for _, nodeGroup := range cluster.Spec.WorkerGroupSpecs {
count += *nodeGroup.Replicas
}
return count
}
// CalculateMinReplicas calculates min worker replicas at the cluster level
func CalculateMinReplicas(cluster *rayiov1alpha1.RayCluster) int32 {
count := int32(0)
for _, nodeGroup := range cluster.Spec.WorkerGroupSpecs {
count += *nodeGroup.MinReplicas
}
return count
}
// CalculateMaxReplicas calculates max worker replicas at the cluster level
func CalculateMaxReplicas(cluster *rayiov1alpha1.RayCluster) int32 {
count := int32(0)
for _, nodeGroup := range cluster.Spec.WorkerGroupSpecs {
count += *nodeGroup.MaxReplicas
}
return count
}
// CalculateAvailableReplicas calculates available worker replicas at the cluster level
// A worker is available if its Pod is running
func CalculateAvailableReplicas(pods corev1.PodList) int32 {
count := int32(0)
for _, pod := range pods.Items {
if val, ok := pod.Labels["ray.io/node-type"]; !ok || val != string(rayiov1alpha1.WorkerNode) {
continue
}
if pod.Status.Phase == corev1.PodRunning {
count++
}
}
return count
}
func CalculateDesiredResources(cluster *rayiov1alpha1.RayCluster) corev1.ResourceList {
desiredResourcesList := []corev1.ResourceList{{}}
headPodResource := calculatePodResource(cluster.Spec.HeadGroupSpec.Template.Spec)
for i := int32(0); i < *cluster.Spec.HeadGroupSpec.Replicas; i++ {
desiredResourcesList = append(desiredResourcesList, headPodResource)
}
for _, nodeGroup := range cluster.Spec.WorkerGroupSpecs {
podResource := calculatePodResource(nodeGroup.Template.Spec)
for i := int32(0); i < *nodeGroup.Replicas; i++ {
desiredResourcesList = append(desiredResourcesList, podResource)
}
}
return sumResourceList(desiredResourcesList)
}
func CalculateMinResources(cluster *rayiov1alpha1.RayCluster) corev1.ResourceList {
minResourcesList := []corev1.ResourceList{{}}
headPodResource := calculatePodResource(cluster.Spec.HeadGroupSpec.Template.Spec)
for i := int32(0); i < *cluster.Spec.HeadGroupSpec.Replicas; i++ {
minResourcesList = append(minResourcesList, headPodResource)
}
for _, nodeGroup := range cluster.Spec.WorkerGroupSpecs {
podResource := calculatePodResource(nodeGroup.Template.Spec)
for i := int32(0); i < *nodeGroup.MinReplicas; i++ {
minResourcesList = append(minResourcesList, podResource)
}
}
return sumResourceList(minResourcesList)
}
func calculatePodResource(podSpec corev1.PodSpec) corev1.ResourceList {
podResource := corev1.ResourceList{}
for _, container := range podSpec.Containers {
containerResource := container.Resources.Requests
for name, quantity := range container.Resources.Limits {
if _, ok := containerResource[name]; !ok {
containerResource[name] = quantity
}
}
for name, quantity := range containerResource {
if totalQuantity, ok := podResource[name]; ok {
totalQuantity.Add(quantity)
podResource[name] = totalQuantity
} else {
podResource[name] = quantity
}
}
}
return podResource
}
func sumResourceList(list []corev1.ResourceList) corev1.ResourceList {
totalResource := corev1.ResourceList{}
for _, l := range list {
for name, quantity := range l {
if value, ok := totalResource[name]; !ok {
totalResource[name] = quantity.DeepCopy()
} else {
value.Add(quantity)
totalResource[name] = value
}
}
}
return totalResource
}
func Contains(elems []string, searchTerm string) bool {
for _, s := range elems {
if searchTerm == s {
return true
}
}
return false
}
func FilterContainerByName(containers []corev1.Container, name string) (corev1.Container, error) {
for _, container := range containers {
if strings.Compare(container.Name, name) == 0 {
return container, nil
}
}
return corev1.Container{}, fmt.Errorf("can not find container %s", name)
}
// GetHeadGroupServiceAccountName returns the head group service account if it exists.
// Otherwise, it returns the name of the cluster itself.
func GetHeadGroupServiceAccountName(cluster *rayiov1alpha1.RayCluster) string {
headGroupServiceAccountName := cluster.Spec.HeadGroupSpec.Template.Spec.ServiceAccountName
if headGroupServiceAccountName != "" {
return headGroupServiceAccountName
}
return cluster.Name
}
// CheckAllPodsRunning check if all pod in a list is running
func CheckAllPodsRunning(runningPods corev1.PodList) bool {
// check if there is no pods.
if len(runningPods.Items) == 0 {
return false
}
for _, pod := range runningPods.Items {
if pod.Status.Phase != corev1.PodRunning {
return false
}
}
return true
}
func PodNotMatchingTemplate(pod corev1.Pod, template corev1.PodTemplateSpec) bool {
if pod.Status.Phase == corev1.PodRunning && pod.ObjectMeta.DeletionTimestamp == nil {
if len(template.Spec.Containers) != len(pod.Spec.Containers) {
return true
}
cmap := map[string]*corev1.Container{}
for _, container := range pod.Spec.Containers {
cmap[container.Name] = &container
}
for _, container1 := range template.Spec.Containers {
if container2, ok := cmap[container1.Name]; ok {
if container1.Image != container2.Image {
// image name do not match
return true
}
if len(container1.Resources.Requests) != len(container2.Resources.Requests) ||
len(container1.Resources.Limits) != len(container2.Resources.Limits) {
// resource entries do not match
return true
}
resources1 := []corev1.ResourceList{
container1.Resources.Requests,
container1.Resources.Limits,
}
resources2 := []corev1.ResourceList{
container2.Resources.Requests,
container2.Resources.Limits,
}
for i := range resources1 {
// we need to make sure all fields match
for name, quantity1 := range resources1[i] {
if quantity2, ok := resources2[i][name]; ok {
if quantity1.Cmp(quantity2) != 0 {
// request amount does not match
return true
}
} else {
// no such request
return true
}
}
}
// now we consider them equal
delete(cmap, container1.Name)
} else {
// container name do not match
return true
}
}
if len(cmap) != 0 {
// one or more containers do not match
return true
}
}
return false
}
// CompareJsonStruct This is a way to better compare if two objects are the same when they are json/yaml structs. reflect.DeepEqual will fail in some cases.
func CompareJsonStruct(objA interface{}, objB interface{}) bool {
a, err := json.Marshal(objA)
if err != nil {
return false
}
b, err := json.Marshal(objB)
if err != nil {
return false
}
var v1, v2 interface{}
err = json.Unmarshal(a, &v1)
if err != nil {
return false
}
err = json.Unmarshal(b, &v2)
if err != nil {
return false
}
return reflect.DeepEqual(v1, v2)
}
func ConvertUnixTimeToMetav1Time(unixTime int64) *metav1.Time {
// The Ray jobInfo returns the start_time, which is a unix timestamp in milliseconds.
// https://docs.ray.io/en/latest/cluster/jobs-package-ref.html#jobinfo
t := time.Unix(unixTime/1000, unixTime%1000*1000000)
kt := metav1.NewTime(t)
return &kt
}
// Json-serializes obj and returns its hash string
func GenerateJsonHash(obj interface{}) (string, error) {
serialObj, err := json.Marshal(obj)
if err != nil {
return "", err
}
hashBytes := sha1.Sum(serialObj)
// Convert to an ASCII string
hashStr := string(base32.HexEncoding.EncodeToString(hashBytes[:]))
return hashStr, nil
}