generic_scheduler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package scheduler
  14. import (
  15. "bytes"
  16. "fmt"
  17. "sort"
  18. "strings"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "github.com/golang/glog"
  23. "k8s.io/kubernetes/pkg/api"
  24. "k8s.io/kubernetes/pkg/util"
  25. "k8s.io/kubernetes/pkg/util/errors"
  26. "k8s.io/kubernetes/pkg/util/workqueue"
  27. "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm"
  28. "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates"
  29. schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api"
  30. "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
  31. )
  32. type FailedPredicateMap map[string][]algorithm.PredicateFailureReason
  33. type FitError struct {
  34. Pod *api.Pod
  35. FailedPredicates FailedPredicateMap
  36. }
  37. var ErrNoNodesAvailable = fmt.Errorf("no nodes available to schedule pods")
  38. // Error returns detailed information of why the pod failed to fit on each node
  39. func (f *FitError) Error() string {
  40. var buf bytes.Buffer
  41. buf.WriteString(fmt.Sprintf("pod (%s) failed to fit in any node\n", f.Pod.Name))
  42. for node, predicates := range f.FailedPredicates {
  43. reasons := make([]string, 0)
  44. for _, pred := range predicates {
  45. reasons = append(reasons, pred.GetReason())
  46. }
  47. reasonMsg := fmt.Sprintf("fit failure on node (%s): %s\n", node, strings.Join(reasons, ", "))
  48. buf.WriteString(reasonMsg)
  49. }
  50. return buf.String()
  51. }
  52. type genericScheduler struct {
  53. cache schedulercache.Cache
  54. predicates map[string]algorithm.FitPredicate
  55. prioritizers []algorithm.PriorityConfig
  56. extenders []algorithm.SchedulerExtender
  57. pods algorithm.PodLister
  58. lastNodeIndexLock sync.Mutex
  59. lastNodeIndex uint64
  60. cachedNodeInfoMap map[string]*schedulercache.NodeInfo
  61. }
  62. // Schedule tries to schedule the given pod to one of node in the node list.
  63. // If it succeeds, it will return the name of the node.
  64. // If it fails, it will return a Fiterror error with reasons.
  65. func (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeLister) (string, error) {
  66. var trace *util.Trace
  67. if pod != nil {
  68. trace = util.NewTrace(fmt.Sprintf("Scheduling %s/%s", pod.Namespace, pod.Name))
  69. } else {
  70. trace = util.NewTrace("Scheduling <nil> pod")
  71. }
  72. defer trace.LogIfLong(20 * time.Millisecond)
  73. nodes, err := nodeLister.List()
  74. if err != nil {
  75. return "", err
  76. }
  77. if len(nodes) == 0 {
  78. return "", ErrNoNodesAvailable
  79. }
  80. // Used for all fit and priority funcs.
  81. err = g.cache.UpdateNodeNameToInfoMap(g.cachedNodeInfoMap)
  82. if err != nil {
  83. return "", err
  84. }
  85. trace.Step("Computing predicates")
  86. filteredNodes, failedPredicateMap, err := findNodesThatFit(pod, g.cachedNodeInfoMap, nodes, g.predicates, g.extenders)
  87. if err != nil {
  88. return "", err
  89. }
  90. if len(filteredNodes) == 0 {
  91. return "", &FitError{
  92. Pod: pod,
  93. FailedPredicates: failedPredicateMap,
  94. }
  95. }
  96. trace.Step("Prioritizing")
  97. priorityList, err := PrioritizeNodes(pod, g.cachedNodeInfoMap, g.prioritizers, filteredNodes, g.extenders)
  98. if err != nil {
  99. return "", err
  100. }
  101. trace.Step("Selecting host")
  102. return g.selectHost(priorityList)
  103. }
  104. // selectHost takes a prioritized list of nodes and then picks one
  105. // in a round-robin manner from the nodes that had the highest score.
  106. func (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList) (string, error) {
  107. if len(priorityList) == 0 {
  108. return "", fmt.Errorf("empty priorityList")
  109. }
  110. sort.Sort(sort.Reverse(priorityList))
  111. maxScore := priorityList[0].Score
  112. firstAfterMaxScore := sort.Search(len(priorityList), func(i int) bool { return priorityList[i].Score < maxScore })
  113. g.lastNodeIndexLock.Lock()
  114. ix := int(g.lastNodeIndex % uint64(firstAfterMaxScore))
  115. g.lastNodeIndex++
  116. g.lastNodeIndexLock.Unlock()
  117. return priorityList[ix].Host, nil
  118. }
  119. // Filters the nodes to find the ones that fit based on the given predicate functions
  120. // Each node is passed through the predicate functions to determine if it is a fit
  121. func findNodesThatFit(
  122. pod *api.Pod,
  123. nodeNameToInfo map[string]*schedulercache.NodeInfo,
  124. nodes []*api.Node,
  125. predicateFuncs map[string]algorithm.FitPredicate,
  126. extenders []algorithm.SchedulerExtender) ([]*api.Node, FailedPredicateMap, error) {
  127. var filtered []*api.Node
  128. failedPredicateMap := FailedPredicateMap{}
  129. if len(predicateFuncs) == 0 {
  130. filtered = nodes
  131. } else {
  132. // Create filtered list with enough space to avoid growing it
  133. // and allow assigning.
  134. filtered = make([]*api.Node, len(nodes))
  135. meta := predicates.PredicateMetadata(pod, nodeNameToInfo)
  136. errs := []error{}
  137. var predicateResultLock sync.Mutex
  138. var filteredLen int32
  139. checkNode := func(i int) {
  140. nodeName := nodes[i].Name
  141. fits, failedPredicates, err := podFitsOnNode(pod, meta, nodeNameToInfo[nodeName], predicateFuncs)
  142. if err != nil {
  143. predicateResultLock.Lock()
  144. errs = append(errs, err)
  145. predicateResultLock.Unlock()
  146. return
  147. }
  148. if fits {
  149. filtered[atomic.AddInt32(&filteredLen, 1)-1] = nodes[i]
  150. } else {
  151. predicateResultLock.Lock()
  152. failedPredicateMap[nodeName] = failedPredicates
  153. predicateResultLock.Unlock()
  154. }
  155. }
  156. workqueue.Parallelize(16, len(nodes), checkNode)
  157. filtered = filtered[:filteredLen]
  158. if len(errs) > 0 {
  159. return []*api.Node{}, FailedPredicateMap{}, errors.NewAggregate(errs)
  160. }
  161. }
  162. if len(filtered) > 0 && len(extenders) != 0 {
  163. for _, extender := range extenders {
  164. filteredList, failedMap, err := extender.Filter(pod, filtered)
  165. if err != nil {
  166. return []*api.Node{}, FailedPredicateMap{}, err
  167. }
  168. for failedNodeName, failedMsg := range failedMap {
  169. if _, found := failedPredicateMap[failedNodeName]; !found {
  170. failedPredicateMap[failedNodeName] = []algorithm.PredicateFailureReason{}
  171. }
  172. failedPredicateMap[failedNodeName] = append(failedPredicateMap[failedNodeName], predicates.NewFailureReason(failedMsg))
  173. }
  174. filtered = filteredList
  175. if len(filtered) == 0 {
  176. break
  177. }
  178. }
  179. }
  180. return filtered, failedPredicateMap, nil
  181. }
  182. // Checks whether node with a given name and NodeInfo satisfies all predicateFuncs.
  183. func podFitsOnNode(pod *api.Pod, meta interface{}, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, []algorithm.PredicateFailureReason, error) {
  184. var failedPredicates []algorithm.PredicateFailureReason
  185. for _, predicate := range predicateFuncs {
  186. fit, reasons, err := predicate(pod, meta, info)
  187. if err != nil {
  188. err := fmt.Errorf("SchedulerPredicates failed due to %v, which is unexpected.", err)
  189. return false, []algorithm.PredicateFailureReason{}, err
  190. }
  191. if !fit {
  192. failedPredicates = append(failedPredicates, reasons...)
  193. }
  194. }
  195. return len(failedPredicates) == 0, failedPredicates, nil
  196. }
  197. // Prioritizes the nodes by running the individual priority functions in parallel.
  198. // Each priority function is expected to set a score of 0-10
  199. // 0 is the lowest priority score (least preferred node) and 10 is the highest
  200. // Each priority function can also have its own weight
  201. // The node scores returned by the priority function are multiplied by the weights to get weighted scores
  202. // All scores are finally combined (added) to get the total weighted scores of all nodes
  203. func PrioritizeNodes(
  204. pod *api.Pod,
  205. nodeNameToInfo map[string]*schedulercache.NodeInfo,
  206. priorityConfigs []algorithm.PriorityConfig,
  207. nodes []*api.Node,
  208. extenders []algorithm.SchedulerExtender,
  209. ) (schedulerapi.HostPriorityList, error) {
  210. result := make(schedulerapi.HostPriorityList, 0, len(nodeNameToInfo))
  211. // If no priority configs are provided, then the EqualPriority function is applied
  212. // This is required to generate the priority list in the required format
  213. if len(priorityConfigs) == 0 && len(extenders) == 0 {
  214. return EqualPriority(pod, nodeNameToInfo, nodes)
  215. }
  216. var (
  217. mu = sync.Mutex{}
  218. wg = sync.WaitGroup{}
  219. combinedScores = make(map[string]int, len(nodeNameToInfo))
  220. errs []error
  221. )
  222. for _, priorityConfig := range priorityConfigs {
  223. // skip the priority function if the weight is specified as 0
  224. if priorityConfig.Weight == 0 {
  225. continue
  226. }
  227. wg.Add(1)
  228. go func(config algorithm.PriorityConfig) {
  229. defer wg.Done()
  230. weight := config.Weight
  231. priorityFunc := config.Function
  232. prioritizedList, err := priorityFunc(pod, nodeNameToInfo, nodes)
  233. mu.Lock()
  234. defer mu.Unlock()
  235. if err != nil {
  236. errs = append(errs, err)
  237. return
  238. }
  239. for i := range prioritizedList {
  240. host, score := prioritizedList[i].Host, prioritizedList[i].Score
  241. combinedScores[host] += score * weight
  242. }
  243. }(priorityConfig)
  244. }
  245. if len(errs) != 0 {
  246. return schedulerapi.HostPriorityList{}, errors.NewAggregate(errs)
  247. }
  248. // wait for all go routines to finish
  249. wg.Wait()
  250. if len(extenders) != 0 && nodes != nil {
  251. for _, extender := range extenders {
  252. wg.Add(1)
  253. go func(ext algorithm.SchedulerExtender) {
  254. defer wg.Done()
  255. prioritizedList, weight, err := ext.Prioritize(pod, nodes)
  256. if err != nil {
  257. // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities
  258. return
  259. }
  260. mu.Lock()
  261. for i := range *prioritizedList {
  262. host, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score
  263. combinedScores[host] += score * weight
  264. }
  265. mu.Unlock()
  266. }(extender)
  267. }
  268. }
  269. // wait for all go routines to finish
  270. wg.Wait()
  271. for host, score := range combinedScores {
  272. glog.V(10).Infof("Host %s Score %d", host, score)
  273. result = append(result, schedulerapi.HostPriority{Host: host, Score: score})
  274. }
  275. return result, nil
  276. }
  277. // EqualPriority is a prioritizer function that gives an equal weight of one to all nodes
  278. func EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) {
  279. result := make(schedulerapi.HostPriorityList, len(nodes))
  280. for _, node := range nodes {
  281. result = append(result, schedulerapi.HostPriority{
  282. Host: node.Name,
  283. Score: 1,
  284. })
  285. }
  286. return result, nil
  287. }
  288. func NewGenericScheduler(cache schedulercache.Cache, predicates map[string]algorithm.FitPredicate, prioritizers []algorithm.PriorityConfig, extenders []algorithm.SchedulerExtender) algorithm.ScheduleAlgorithm {
  289. return &genericScheduler{
  290. cache: cache,
  291. predicates: predicates,
  292. prioritizers: prioritizers,
  293. extenders: extenders,
  294. cachedNodeInfoMap: make(map[string]*schedulercache.NodeInfo),
  295. }
  296. }