allocator.go 5.6 KB
Newer Older
L
liqingping 已提交
1 2 3 4 5 6
package allocator

import (
	"context"
	"time"

7 8
	corev1 "k8s.io/api/core/v1"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
L
liqingping 已提交
9 10 11 12 13 14 15 16 17
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	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/source"

	ditypes "opendilab.org/di-orchestrator/pkg/allocator/types"
	div1alpha2 "opendilab.org/di-orchestrator/pkg/api/v1alpha2"
18
	"opendilab.org/di-orchestrator/pkg/common"
L
liqingping 已提交
19 20
	dihandler "opendilab.org/di-orchestrator/pkg/common/handler"
	dicontext "opendilab.org/di-orchestrator/pkg/context"
21
	diutil "opendilab.org/di-orchestrator/pkg/utils"
L
liqingping 已提交
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
)

type Allocator struct {
	Scheme           *runtime.Scheme
	ctx              dicontext.Context
	policy           ditypes.FitPolicy
	scheduleDuration time.Duration
	last             time.Time
}

func NewAllocator(scheme *runtime.Scheme, ctx dicontext.Context, policy ditypes.FitPolicy, scheduleDuration time.Duration) *Allocator {
	return &Allocator{
		Scheme:           scheme,
		ctx:              ctx,
		policy:           policy,
		scheduleDuration: scheduleDuration,
		last:             time.Now(),
	}
}

func (a *Allocator) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	log := a.ctx.Log.WithName("Reconcile")
	if !a.needReconcile() {
		log.Info("skipped reconcile since scheduling duration not meet")
		return ctrl.Result{}, nil
	}
	a.updateLastTime()

	jobkey := req.NamespacedName
	job := &div1alpha2.DIJob{}
	if err := a.ctx.Get(ctx, jobkey, job); err != nil {
		return ctrl.Result{}, err
	}

	// TODO(liqingping): implement jobinfo getter and nodeinfo getter.
57 58
	jobinfo := a.getJobInfo(job)
	nodeinfos := a.getNodeInfos()
L
liqingping 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
	jobinfos := map[string]ditypes.JobInfo{
		jobinfo.Key.String(): jobinfo,
	}
	prevAllocations := map[string]ditypes.NodeList{}
	if err := a.allocateAll(jobinfos, nodeinfos, prevAllocations); err != nil {
		return ctrl.Result{}, err
	}
	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (a *Allocator) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&div1alpha2.DIJob{}).
		Watches(
			&source.Kind{Type: &div1alpha2.DIJob{}},
			&dihandler.EventHandler{
				OnCreateHandlers: []func(obj client.Object){
77
					a.onJobAddHandler,
L
liqingping 已提交
78 79 80 81 82 83 84 85
				},
				OnUpdateHandlers: []func(old, new client.Object){},
			},
			builder.Predicates{},
		).
		Complete(a)
}

86
// return true if time elapsed is almost greater than schedule duration.
L
liqingping 已提交
87 88 89 90 91 92 93 94
func (a *Allocator) needReconcile() bool {
	return (a.scheduleDuration - time.Since(a.last)) < time.Second
}

func (a *Allocator) updateLastTime() {
	a.last = time.Now()
}

95 96 97
// onJobAddHandler handle the event when a job is created.
func (a *Allocator) onJobAddHandler(obj client.Object) {
	log := a.ctx.Log.WithName("onJobAddHandler")
L
liqingping 已提交
98 99
	job := obj.(*div1alpha2.DIJob)

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
	if err := a.allocate(job); err != nil {
		log.Error(err, "failed to allocate", "job", job.Name)
	}

}

func (a *Allocator) getJobInfo(job *div1alpha2.DIJob) ditypes.JobInfo {
	res := a.getJobResources(job)
	jobinfo := ditypes.NewJobInfo(
		types.NamespacedName{
			Namespace: job.Namespace, Name: job.Name,
		},
		res, int(job.Spec.MinReplicas), int(job.Spec.MaxReplicas),
		job.Spec.Preemptible,
	)
	return *jobinfo
}

func (a *Allocator) getJobResources(job *div1alpha2.DIJob) corev1.ResourceRequirements {
	res := common.GetDIJobDefaultResources()
	jobres := diutil.GetPodResources(&job.Spec.Template.Spec)
	if jobres.Requests != nil {
		if jobres.Requests.Cpu() != nil {
			res.Requests[corev1.ResourceCPU] = *jobres.Requests.Cpu()
		}
		if jobres.Requests.Memory() != nil {
			res.Requests[corev1.ResourceMemory] = *jobres.Requests.Memory()
		}
		res.Requests[corev1.ResourceName(common.ResourceGPU)] = jobres.Requests[corev1.ResourceName(common.ResourceGPU)]
	} else if jobres.Limits != nil {
		if jobres.Limits.Cpu() != nil {
			res.Limits[corev1.ResourceCPU] = *jobres.Limits.Cpu()
		}
		if jobres.Limits.Memory() != nil {
			res.Limits[corev1.ResourceMemory] = *jobres.Limits.Memory()
		}
		res.Limits[corev1.ResourceName(common.ResourceGPU)] = jobres.Limits[corev1.ResourceName(common.ResourceGPU)]
L
liqingping 已提交
137
	}
138 139
	if _, ok := res.Requests[corev1.ResourceName(common.ResourceGPU)]; !ok {
		res.Requests[corev1.ResourceName(common.ResourceGPU)] = res.Limits[corev1.ResourceName(common.ResourceGPU)]
L
liqingping 已提交
140
	}
141
	return res
L
liqingping 已提交
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
func (a *Allocator) getNodeInfos() map[string]ditypes.NodeInfo {
	return nil
}

func (a *Allocator) allocate(job *div1alpha2.DIJob) error {
	log := a.ctx.Log.WithName("allocate")
	status := job.Status.DeepCopy()
	jobinfo := a.getJobInfo(job)
	nodeinfos := a.getNodeInfos()
	// allocate job if preemptible, otherwise just update status.replicas
	if job.Spec.Preemptible {
		allocation, err := a.policy.Allocate(jobinfo, nodeinfos)
		if err != nil {
			return err
		}
		log.Info("allocate job "+diutil.NamespacedName(job.Namespace, job.Name), "allocation", allocation)
		if len(allocation) != 0 {
			job.Status.Allocation = allocation
		}
	} else {
		job.Status.Replicas = job.Spec.MinReplicas
	}

	if !apiequality.Semantic.DeepEqual(job.Status, *status) {
		if err := a.ctx.UpdateDIJobStatusInCluster(job); err != nil {
			return err
		}
L
liqingping 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183
	}
	return nil
}

func (a *Allocator) allocateAll(jobinfos map[string]ditypes.JobInfo, nodeinfos map[string]ditypes.NodeInfo, prevAllocations map[string]ditypes.NodeList) error {
	log := a.ctx.Log.WithName("allocateAll")
	allocations, err := a.policy.Optimize(jobinfos, nodeinfos, prevAllocations)
	if err != nil {
		return err
	}
	log.Info("new allocations", "allocations", allocations)
	return nil
}