github.com/kubeflow/training-operator@v1.7.0/pkg/common/util/util.go (about) 1 // Copyright 2021 The Kubeflow Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License 14 15 package util 16 17 import ( 18 "fmt" 19 "time" 20 21 corev1 "k8s.io/api/core/v1" 22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 23 24 kubeflowv1 "github.com/kubeflow/training-operator/pkg/apis/kubeflow.org/v1" 25 commonutil "github.com/kubeflow/training-operator/pkg/util" 26 ) 27 28 type ObjectFilterFunction func(obj metav1.Object) bool 29 30 // ConvertServiceList convert service list to service point list 31 func ConvertServiceList(list []corev1.Service) []*corev1.Service { 32 if list == nil { 33 return nil 34 } 35 ret := make([]*corev1.Service, 0, len(list)) 36 for i := range list { 37 ret = append(ret, &list[i]) 38 } 39 return ret 40 } 41 42 // JobControlledPodList filter pod list owned by the job. 43 func JobControlledPodList(list []corev1.Pod, job metav1.Object) []*corev1.Pod { 44 if list == nil { 45 return nil 46 } 47 ret := make([]*corev1.Pod, 0, len(list)) 48 for i := range list { 49 if !metav1.IsControlledBy(&list[i], job) { 50 continue 51 } 52 ret = append(ret, &list[i]) 53 } 54 return ret 55 } 56 57 func GetReplicaTypes(specs map[kubeflowv1.ReplicaType]*kubeflowv1.ReplicaSpec) []kubeflowv1.ReplicaType { 58 keys := make([]kubeflowv1.ReplicaType, 0, len(specs)) 59 for k := range specs { 60 keys = append(keys, k) 61 } 62 return keys 63 } 64 65 // DurationUntilExpireTime returns the duration until job needs to be cleaned up, or -1 if it's infinite. 66 func DurationUntilExpireTime(runPolicy *kubeflowv1.RunPolicy, jobStatus kubeflowv1.JobStatus) (time.Duration, error) { 67 if !commonutil.IsSucceeded(jobStatus) && !commonutil.IsFailed(jobStatus) { 68 return -1, nil 69 } 70 currentTime := time.Now() 71 ttl := runPolicy.TTLSecondsAfterFinished 72 if ttl == nil { 73 return -1, nil 74 } 75 duration := time.Second * time.Duration(*ttl) 76 if jobStatus.CompletionTime == nil { 77 return -1, fmt.Errorf("job completion time is nil, cannot cleanup") 78 } 79 finishTime := jobStatus.CompletionTime 80 expireTime := finishTime.Add(duration) 81 if currentTime.After(expireTime) { 82 return 0, nil 83 } else { 84 return expireTime.Sub(currentTime), nil 85 } 86 }