From c64048d73e5d0bc6ffc321b4ec13bce0f6098d47 Mon Sep 17 00:00:00 2001 From: Andrew M Bursavich Date: Sat, 31 Oct 2015 22:33:02 -0700 Subject: [PATCH] Avoid full sort when selecting host with highest priority. --- plugin/pkg/scheduler/generic_scheduler.go | 39 +++++++++++------------ 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/plugin/pkg/scheduler/generic_scheduler.go b/plugin/pkg/scheduler/generic_scheduler.go index 649d89484a9..96ef1aef112 100644 --- a/plugin/pkg/scheduler/generic_scheduler.go +++ b/plugin/pkg/scheduler/generic_scheduler.go @@ -19,7 +19,6 @@ package scheduler import ( "fmt" "math/rand" - "sort" "strings" "sync" @@ -88,20 +87,32 @@ func (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeListe return g.selectHost(priorityList) } -// This method takes a prioritized list of nodes and sorts them in reverse order based on scores -// and then picks one randomly from the nodes that had the highest score +// This method takes a prioritized list of nodes, shuffles those with the highest scores to the +// front of the list, and then picks one randomly from the nodes that had the highest score. func (g *genericScheduler) selectHost(priorityList algorithm.HostPriorityList) (string, error) { if len(priorityList) == 0 { return "", fmt.Errorf("empty priorityList") } - sort.Sort(sort.Reverse(priorityList)) + max := priorityList[0].Score + n := 0 + for i, hostEntry := range priorityList { + if hostEntry.Score < max { + continue + } + if hostEntry.Score > max { + max = hostEntry.Score + n = 0 + } + priorityList[i], priorityList[n] = priorityList[n], priorityList[i] + n++ + } + if n == 1 { + return priorityList[0].Host, nil + } - hosts := getBestHosts(priorityList) g.randomLock.Lock() defer g.randomLock.Unlock() - - ix := g.random.Int() % len(hosts) - return hosts[ix], nil + return priorityList[g.random.Intn(n)].Host, nil } // Filters the nodes to find the ones that fit based on the given predicate functions @@ -179,18 +190,6 @@ func PrioritizeNodes(pod *api.Pod, podLister algorithm.PodLister, priorityConfig return result, nil } -func getBestHosts(list algorithm.HostPriorityList) []string { - result := []string{} - for _, hostEntry := range list { - if hostEntry.Score == list[0].Score { - result = append(result, hostEntry.Host) - } else { - break - } - } - return result -} - // EqualPriority is a prioritizer function that gives an equal weight of one to all nodes func EqualPriority(_ *api.Pod, podLister algorithm.PodLister, nodeLister algorithm.NodeLister) (algorithm.HostPriorityList, error) { nodes, err := nodeLister.List()