util.go 9.2 KB
Newer Older
L
liqingping 已提交
1 2 3 4 5 6 7 8 9 10
package util

import (
	"context"
	"fmt"
	"math/rand"
	"strings"
	"time"

	corev1 "k8s.io/api/core/v1"
11
	"k8s.io/apimachinery/pkg/api/resource"
L
liqingping 已提交
12 13 14 15 16 17 18
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	utilrand "k8s.io/apimachinery/pkg/util/rand"
	"sigs.k8s.io/controller-runtime/pkg/client"

L
liqingping 已提交
19 20 21
	div1alpha1 "opendilab.org/di-orchestrator/pkg/api/v1alpha1"
	dicommon "opendilab.org/di-orchestrator/pkg/common"
	commontypes "opendilab.org/di-orchestrator/pkg/common/types"
L
liqingping 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35
)

const (
	randomLength = 5
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

func GenerateName(name string) string {
	return fmt.Sprintf("%s-%s", name, utilrand.String(randomLength))
}

L
liqingping 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
func ReplicaPodName(name, replicaType string) string {
	return fmt.Sprintf("%s-%s", name, replicaType)
}

func NamespacedName(namespace, name string) string {
	return fmt.Sprintf("%s/%s", namespace, name)
}

func SplitNamespaceName(namespaceName string) (types.NamespacedName, error) {
	strs := strings.Split(namespaceName, "/")
	if len(strs) != 2 {
		return types.NamespacedName{}, fmt.Errorf("Invalid namespace, name %s", namespaceName)
	}
	return types.NamespacedName{Namespace: strs[0], Name: strs[1]}, nil
}

L
liqingping 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64
func GetObjectFromUnstructured(obj interface{}, dest interface{}) error {
	us, ok := obj.(*unstructured.Unstructured)
	if !ok {
		return fmt.Errorf("the object %s is not unstructured", obj)
	}
	err := runtime.DefaultUnstructuredConverter.FromUnstructured(us.UnstructuredContent(), dest)
	if err != nil {
		return err
	}

	return nil
}

L
liqingping 已提交
65
func GetDefaultPortFromPod(pod *corev1.Pod) (int32, bool) {
L
liqingping 已提交
66
	for _, c := range pod.Spec.Containers {
L
liqingping 已提交
67
		if c.Name != dicommon.DefaultContainerName {
L
liqingping 已提交
68 69 70
			continue
		}
		for _, port := range c.Ports {
L
liqingping 已提交
71
			if port.Name == dicommon.DefaultPortName {
L
liqingping 已提交
72 73 74 75 76 77 78
				return port.ContainerPort, true
			}
		}
	}
	return -1, false
}

79
func AddPortToPod(pod *corev1.Pod, port corev1.ContainerPort) {
L
liqingping 已提交
80
	for i := range pod.Spec.Containers {
L
liqingping 已提交
81
		if pod.Spec.Containers[i].Name != dicommon.DefaultContainerName {
L
liqingping 已提交
82 83 84 85 86
			continue
		}
		if pod.Spec.Containers[i].Ports == nil {
			pod.Spec.Containers[i].Ports = []corev1.ContainerPort{}
		}
87
		pod.Spec.Containers[i].Ports = append(pod.Spec.Containers[i].Ports, port)
L
liqingping 已提交
88 89 90 91 92 93
	}
}

func GenLabels(jobName string) map[string]string {
	groupName := div1alpha1.GroupVersion.Group
	return map[string]string{
L
liqingping 已提交
94 95 96
		dicommon.GroupNameLabel:      groupName,
		dicommon.JobNameLabel:        strings.Replace(jobName, "/", "-", -1),
		dicommon.ControllerNameLabel: dicommon.ControllerName,
L
liqingping 已提交
97 98 99 100 101 102 103 104 105 106 107 108
	}
}

func AddLabelsToPod(pod *corev1.Pod, labels map[string]string) {
	if pod.ObjectMeta.Labels == nil {
		pod.ObjectMeta.Labels = make(map[string]string)
	}
	for k, v := range labels {
		pod.ObjectMeta.Labels[k] = v
	}
}

L
liqingping 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
func AddEnvsToPod(pod *corev1.Pod, envs map[string]string) {
	// add env
	for i := range pod.Spec.Containers {
		if len(pod.Spec.Containers[i].Env) == 0 {
			pod.Spec.Containers[i].Env = make([]corev1.EnvVar, 0)
		}
		for k, v := range envs {
			env := corev1.EnvVar{
				Name:  k,
				Value: v,
			}
			pod.Spec.Containers[i].Env = append(pod.Spec.Containers[i].Env, env)
		}
	}
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138
func GetEnvFromPod(pod *corev1.Pod, envName string) (string, bool) {
	for _, container := range pod.Spec.Containers {
		if container.Name != dicommon.DefaultContainerName {
			continue
		}
		for _, env := range container.Env {
			if env.Name == envName {
				return env.Value, true
			}
		}
	}
	return "", false
}

139
func BuildService(name, namespace string, ownRefer metav1.OwnerReference, labels map[string]string, port int32) *corev1.Service {
L
liqingping 已提交
140 141
	svc := &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
142 143 144 145
			Name:            name,
			Namespace:       namespace,
			Labels:          labels,
			OwnerReferences: []metav1.OwnerReference{ownRefer},
L
liqingping 已提交
146 147 148 149 150 151 152 153
		},
		Spec: corev1.ServiceSpec{
			Type:      corev1.ServiceTypeClusterIP,
			ClusterIP: "None",
			Selector:  labels,
			Ports: []corev1.ServicePort{
				{
					Port: port,
L
liqingping 已提交
154
					Name: dicommon.DefaultPortName,
L
liqingping 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167
				},
			},
		},
	}

	return svc
}

func ConcatURL(name, ns string, port int32) string {
	return fmt.Sprintf("%s.%s:%d", name, ns, port)
}

func GetPodAccessURL(pod *corev1.Pod, defaultPort int32) string {
L
liqingping 已提交
168
	port, found := GetDefaultPortFromPod(pod)
L
liqingping 已提交
169 170 171 172 173 174 175 176 177
	if !found {
		port = defaultPort
	}
	return ConcatURL(pod.Name, pod.Namespace, port)
}

func GetServiceAccessURL(service *corev1.Service) string {
	url := ""
	for _, port := range service.Spec.Ports {
L
liqingping 已提交
178
		if port.Name == dicommon.DefaultPortName {
L
liqingping 已提交
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
			url = ConcatURL(service.Name, service.Namespace, port.Port)
			break
		}
	}
	return url
}

func ListPods(ctx context.Context, cli client.Client, job *div1alpha1.DIJob) ([]*corev1.Pod, error) {
	podList := &corev1.PodList{}

	// generate label selector
	labelSelector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
		MatchLabels: GenLabels(job.Name),
	})
	if err != nil {
		return nil, err
	}

	// list pods of job
	err = cli.List(ctx, podList, &client.ListOptions{Namespace: job.Namespace, LabelSelector: labelSelector})
	if err != nil {
		return nil, err
	}

	pods := []*corev1.Pod{}
	for _, pod := range podList.Items {
		pods = append(pods, pod.DeepCopy())
	}
	return pods, nil
}

func ListServices(ctx context.Context, cli client.Client, job *div1alpha1.DIJob) ([]*corev1.Service, error) {
	svcList := &corev1.ServiceList{}

	// generate label selector
	labelSelector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
		MatchLabels: GenLabels(job.Name),
	})
	if err != nil {
		return nil, err
	}

	// list svcs of job
	err = cli.List(ctx, svcList, &client.ListOptions{Namespace: job.Namespace, LabelSelector: labelSelector})
	if err != nil {
		return nil, err
	}

	svcs := []*corev1.Service{}
	for _, svc := range svcList.Items {
		svcs = append(svcs, svc.DeepCopy())
	}
	return svcs, nil
}

234 235
func FilterOutTerminatingPods(pods []*corev1.Pod) []*corev1.Pod {
	results := []*corev1.Pod{}
L
liqingping 已提交
236
	for _, pod := range pods {
237
		if IsTerminating(pod) {
L
liqingping 已提交
238 239
			continue
		}
240
		results = append(results, pod)
L
liqingping 已提交
241 242
	}

243 244
	return results
}
L
liqingping 已提交
245

246 247 248 249
// IsTerminating returns true if pod's DeletionTimestamp has been set
func IsTerminating(pod *corev1.Pod) bool {
	return pod.DeletionTimestamp != nil
}
L
liqingping 已提交
250

251
func AddGPUPortsToPod(pod *corev1.Pod, total int, startPort int32) {
252 253 254 255 256 257 258
	for i := 1; i < total; i++ {
		pname := fmt.Sprintf("%s-%d", dicommon.DDPLearnerPortPrefix, i)
		pport := startPort + int32(i)
		port := corev1.ContainerPort{
			Name:          pname,
			ContainerPort: pport,
		}
259
		AddPortToPod(pod, port)
L
liqingping 已提交
260 261 262
	}
}

263
func AddGPUPortsToService(service *corev1.Service, total int, startPort int32) {
264
	// gpu 0's port has already been created
265 266 267 268 269 270 271 272
	for i := 1; i < total; i++ {
		pname := fmt.Sprintf("%s-%d", dicommon.DDPLearnerPortPrefix, i)
		pport := startPort + int32(i)
		port := corev1.ServicePort{
			Name: pname,
			Port: pport,
		}
		service.Spec.Ports = append(service.Spec.Ports, port)
L
liqingping 已提交
273
	}
274
}
L
liqingping 已提交
275

276 277 278
func SetPodResources(pod *corev1.Pod, resources commontypes.ResourceQuantity) {
	for i := range pod.Spec.Containers {
		if pod.Spec.Containers[i].Name != dicommon.DefaultContainerName {
L
liqingping 已提交
279 280
			continue
		}
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		if pod.Spec.Containers[i].Resources.Limits == nil {
			pod.Spec.Containers[i].Resources.Limits = make(corev1.ResourceList)
		}
		if pod.Spec.Containers[i].Resources.Requests == nil {
			pod.Spec.Containers[i].Resources.Requests = make(corev1.ResourceList)
		}

		// cpu and memory must not be zero
		if !resources.CPU.IsZero() {
			pod.Spec.Containers[i].Resources.Limits[corev1.ResourceCPU] = resources.CPU
			pod.Spec.Containers[i].Resources.Requests[corev1.ResourceCPU] = resources.CPU
		}
		if !resources.Memory.IsZero() {
			pod.Spec.Containers[i].Resources.Limits[corev1.ResourceMemory] = resources.Memory
			pod.Spec.Containers[i].Resources.Requests[corev1.ResourceMemory] = resources.Memory
		}
		if !resources.GPU.IsZero() {
			pod.Spec.Containers[i].Resources.Limits[corev1.ResourceName("nvidia.com/gpu")] = resources.GPU
			pod.Spec.Containers[i].Resources.Requests[corev1.ResourceName("nvidia.com/gpu")] = resources.GPU
		}
L
liqingping 已提交
301 302
	}
}
L
liqingping 已提交
303

304 305 306 307 308 309 310 311
func GetPodResources(pod *corev1.Pod) commontypes.ResourceQuantity {
	resource := commontypes.ResourceQuantity{
		CPU:    resource.MustParse("0"),
		GPU:    resource.MustParse("0"),
		Memory: resource.MustParse("0"),
	}
	for _, container := range pod.Spec.Containers {
		if container.Name != dicommon.DefaultContainerName {
L
liqingping 已提交
312 313
			continue
		}
314 315 316 317 318 319 320 321 322 323 324 325 326
		if container.Resources.Limits == nil && container.Resources.Requests == nil {
			break
		}
		if container.Resources.Requests != nil {
			resource.CPU = container.Resources.Requests[corev1.ResourceCPU].DeepCopy()
			resource.GPU = container.Resources.Requests[corev1.ResourceName("nvidia.com/gpu")].DeepCopy()
			resource.Memory = container.Resources.Requests[corev1.ResourceMemory].DeepCopy()
		}
		if container.Resources.Limits != nil {
			resource.CPU = container.Resources.Limits[corev1.ResourceCPU].DeepCopy()
			resource.GPU = container.Resources.Limits[corev1.ResourceName("nvidia.com/gpu")].DeepCopy()
			resource.Memory = container.Resources.Limits[corev1.ResourceMemory].DeepCopy()
		}
L
liqingping 已提交
327
	}
328
	return resource
L
liqingping 已提交
329
}
330 331 332 333 334 335 336 337 338 339

func NewOwnerReference(apiVersion, kind, name string, uid types.UID, controller bool) metav1.OwnerReference {
	return metav1.OwnerReference{
		APIVersion: apiVersion,
		Kind:       kind,
		Name:       name,
		UID:        uid,
		Controller: &controller,
	}
}