scheduling.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package scheduling
  2. /*
  3. ArozOS Cluster - placement scoring
  4. One scorer answers "which node should do this?" for every layer that has
  5. to choose: the job scheduler, write placement and the replication
  6. planner. It weighs data locality, free CPU, free memory, free disk, how
  7. much work a node already has, the network distance to the data and, for
  8. a second copy, how far the node is from the copies that already exist,
  9. and it explains every number so the choice can be shown to an admin.
  10. The weights are a cluster-wide replicated setting, so every node scores
  11. the same way and a new leader keeps the admin's tuning.
  12. */
  13. import (
  14. "encoding/json"
  15. "errors"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. "imuslab.com/arozos/mod/cluster/membership"
  21. "imuslab.com/arozos/mod/cluster/metadata"
  22. )
  23. // SettingKey is where the weights live in the replicated setting store.
  24. const SettingKey = "scheduling.weights"
  25. // Weights tune the scorer. They are fractions of one; the defaults are the
  26. // values the cluster shipped with.
  27. type Weights struct {
  28. Locality float64 `json:"locality"`
  29. CPU float64 `json:"cpu"`
  30. Memory float64 `json:"memory"`
  31. Disk float64 `json:"disk"`
  32. Queue float64 `json:"queue"`
  33. Latency float64 `json:"latency"`
  34. Degraded float64 `json:"degraded"`
  35. Preferred float64 `json:"preferred"`
  36. Diversity float64 `json:"diversity"`
  37. }
  38. // DefaultWeights is the shipped tuning.
  39. func DefaultWeights() Weights {
  40. return Weights{
  41. Locality: 0.45,
  42. CPU: 0.20,
  43. Memory: 0.10,
  44. Disk: 0.05,
  45. Queue: 0.10,
  46. Latency: 0.05,
  47. Degraded: 0.05,
  48. Preferred: 0.10,
  49. Diversity: 0.05,
  50. }
  51. }
  52. // Validate rejects nonsense weights.
  53. func (w Weights) Validate() error {
  54. vals := map[string]float64{
  55. "locality": w.Locality, "cpu": w.CPU, "memory": w.Memory, "disk": w.Disk,
  56. "queue": w.Queue, "latency": w.Latency, "degraded": w.Degraded, "preferred": w.Preferred,
  57. "diversity": w.Diversity,
  58. }
  59. for name, v := range vals {
  60. if v < 0 || v > 1 {
  61. return errors.New("weight " + name + " must be between 0 and 1")
  62. }
  63. }
  64. return nil
  65. }
  66. // Candidate is one node being considered, with everything the scorer needs.
  67. type Candidate struct {
  68. Node membership.NodeView
  69. Locality float64 //0..1, share of the input bytes already on this node
  70. Queue int //work already assigned to this node
  71. //LatencyToData is the round trip to where the data sits, in milliseconds
  72. //(negative when unknown).
  73. LatencyToData float64
  74. //Preferred features earn a bonus when the node has them.
  75. Preferred []string
  76. //FreeDisk is the largest free space of the node's volumes, 0..1 of capacity
  77. //(negative when unknown).
  78. FreeDisk float64
  79. //Diversity is how far this node is from the copies that already exist,
  80. //0..1 of one second of round trip (negative when it does not apply, for
  81. //example for the first copy or a cluster too small to spread over).
  82. Diversity float64
  83. }
  84. // Factor is one contribution to a score, for the explanation.
  85. type Factor struct {
  86. Name string `json:"name"`
  87. Value float64 `json:"value"` //the raw 0..1 measurement
  88. Weight float64 `json:"weight"` //the weight applied
  89. Points float64 `json:"points"` //what it added to (or took from) the score
  90. }
  91. // Result is a scored candidate.
  92. type Result struct {
  93. NodeID string `json:"nodeId"`
  94. NodeName string `json:"nodeName"`
  95. State string `json:"state"`
  96. Score float64 `json:"score"`
  97. Eligible bool `json:"eligible"`
  98. Reason string `json:"reason,omitempty"` //why it is not eligible
  99. Factors []Factor `json:"factors"`
  100. }
  101. // Manager holds the replicated weights and does the scoring.
  102. type Manager struct {
  103. m *membership.Manager
  104. meta *metadata.Manager
  105. mu sync.RWMutex
  106. cached Weights
  107. loaded bool
  108. }
  109. // New creates the scorer.
  110. func New(m *membership.Manager, meta *metadata.Manager) (*Manager, error) {
  111. if m == nil || meta == nil {
  112. return nil, errors.New("membership and metadata are required")
  113. }
  114. return &Manager{m: m, meta: meta, cached: DefaultWeights()}, nil
  115. }
  116. // Weights returns the cluster-wide weights (defaults until an admin sets them).
  117. func (s *Manager) Weights() Weights {
  118. if st, ok := s.meta.Setting(SettingKey); ok {
  119. //Start from the defaults so a record written by an older version,
  120. //which did not know a weight yet, keeps that weight's default
  121. w := DefaultWeights()
  122. if json.Unmarshal(st.Value, &w) == nil {
  123. s.mu.Lock()
  124. s.cached, s.loaded = w, true
  125. s.mu.Unlock()
  126. return w
  127. }
  128. }
  129. s.mu.RLock()
  130. defer s.mu.RUnlock()
  131. return s.cached
  132. }
  133. // SetWeights replicates new weights to the whole cluster.
  134. func (s *Manager) SetWeights(w Weights) error {
  135. if err := w.Validate(); err != nil {
  136. return err
  137. }
  138. js, err := json.Marshal(w)
  139. if err != nil {
  140. return err
  141. }
  142. if err := s.meta.Submit(metadata.KindSetting, &metadata.Setting{Key: SettingKey, Value: js}); err != nil {
  143. return err
  144. }
  145. s.mu.Lock()
  146. s.cached, s.loaded = w, true
  147. s.mu.Unlock()
  148. return nil
  149. }
  150. // ResetWeights restores the shipped tuning.
  151. func (s *Manager) ResetWeights() error { return s.SetWeights(DefaultWeights()) }
  152. /*
  153. Scoring
  154. */
  155. func clamp01(v float64) float64 {
  156. if v < 0 {
  157. return 0
  158. }
  159. if v > 1 {
  160. return 1
  161. }
  162. return v
  163. }
  164. // cpuFree is the share of the node's processor that is idle. A node that has
  165. // not reported health yet counts as idle so a fresh node is not punished.
  166. func cpuFree(n membership.NodeView) float64 {
  167. if n.Health.Timestamp == 0 {
  168. return 1
  169. }
  170. return 1 - n.Health.CPUUsage/100
  171. }
  172. // Score rates one candidate and explains the result.
  173. func (s *Manager) Score(c Candidate) (float64, []Factor) {
  174. w := s.Weights()
  175. factors := []Factor{}
  176. add := func(name string, value float64, weight float64) {
  177. value = clamp01(value)
  178. points := value * weight
  179. factors = append(factors, Factor{Name: name, Value: value, Weight: weight, Points: points})
  180. }
  181. sub := func(name string, value float64, weight float64) {
  182. value = clamp01(value)
  183. points := -value * weight
  184. factors = append(factors, Factor{Name: name, Value: value, Weight: weight, Points: points})
  185. }
  186. add("locality", c.Locality, w.Locality)
  187. add("cpu free", cpuFree(c.Node), w.CPU)
  188. memFree := 0.5
  189. if c.Node.Health.RAMTotal > 0 {
  190. memFree = 1 - float64(c.Node.Health.RAMUsed)/float64(c.Node.Health.RAMTotal)
  191. }
  192. add("memory free", memFree, w.Memory)
  193. diskFree := c.FreeDisk
  194. if diskFree < 0 {
  195. if c.Node.Health.DiskTotal > 0 {
  196. diskFree = float64(c.Node.Health.DiskFree) / float64(c.Node.Health.DiskTotal)
  197. } else {
  198. diskFree = 0.5
  199. }
  200. }
  201. add("disk free", diskFree, w.Disk)
  202. if len(c.Preferred) > 0 {
  203. have := 0
  204. for _, f := range c.Preferred {
  205. if c.Node.Capabilities.Has(f) {
  206. have++
  207. }
  208. }
  209. add("preferred features", float64(have)/float64(len(c.Preferred)), w.Preferred)
  210. }
  211. if c.Diversity >= 0 {
  212. //A copy is worth more on a node far from the ones that already hold
  213. //the file, because distance usually means a different site
  214. add("site diversity", c.Diversity, w.Diversity)
  215. }
  216. //Penalties
  217. queue := float64(c.Queue) / 8 //eight queued items saturate the penalty
  218. sub("queue depth", queue, w.Queue)
  219. lat := c.LatencyToData
  220. if lat < 0 {
  221. lat = c.Node.LatencyMs
  222. }
  223. if lat > 0 {
  224. //One second of round trip saturates the penalty
  225. sub("network distance", lat/1000, w.Latency)
  226. }
  227. if c.Node.State == membership.StateDegraded {
  228. sub("degraded", 1, w.Degraded)
  229. }
  230. score := 0.0
  231. for _, f := range factors {
  232. score += f.Points
  233. }
  234. return score, factors
  235. }
  236. // Rank scores every candidate and returns them best first. Candidates that
  237. // are not eligible keep their reason and sort last.
  238. func (s *Manager) Rank(candidates []Candidate, eligible func(Candidate) (bool, string)) []Result {
  239. out := []Result{}
  240. anyOnline := false
  241. for _, c := range candidates {
  242. if c.Node.State == membership.StateOnline {
  243. if ok, _ := eligible(c); ok {
  244. anyOnline = true
  245. }
  246. }
  247. }
  248. for _, c := range candidates {
  249. res := Result{NodeID: c.Node.ID, NodeName: c.Node.Name, State: string(c.Node.State), Eligible: true}
  250. if ok, why := eligible(c); !ok {
  251. res.Eligible, res.Reason = false, why
  252. } else if c.Node.State == membership.StateDegraded && anyOnline {
  253. //A struggling node only gets work when nothing healthy qualifies
  254. res.Eligible, res.Reason = false, "node is degraded and a healthy node is available"
  255. }
  256. res.Score, res.Factors = s.Score(c)
  257. out = append(out, res)
  258. }
  259. sort.SliceStable(out, func(i, j int) bool {
  260. if out[i].Eligible != out[j].Eligible {
  261. return out[i].Eligible
  262. }
  263. if out[i].Score != out[j].Score {
  264. return out[i].Score > out[j].Score
  265. }
  266. return out[i].NodeID < out[j].NodeID
  267. })
  268. return out
  269. }
  270. // Best returns the winning node of a ranking, or "" with the first reason.
  271. func Best(results []Result) (string, string) {
  272. for _, r := range results {
  273. if r.Eligible {
  274. return r.NodeID, ""
  275. }
  276. }
  277. if len(results) > 0 {
  278. return "", results[0].Reason
  279. }
  280. return "", "no node is available"
  281. }
  282. /*
  283. Status for the settings page
  284. */
  285. // NodeStatus is one row of the scheduling overview.
  286. type NodeStatus struct {
  287. ID string `json:"id"`
  288. Name string `json:"name"`
  289. State string `json:"state"`
  290. Local bool `json:"local"`
  291. LatencyMs float64 `json:"latencyMs"`
  292. CPUFree float64 `json:"cpuFree"`
  293. MemFree float64 `json:"memFree"`
  294. DiskFree float64 `json:"diskFree"`
  295. Score float64 `json:"score"`
  296. Features int `json:"features"`
  297. }
  298. // Status is the scheduling picture.
  299. type Status struct {
  300. InCluster bool `json:"inCluster"`
  301. Weights Weights `json:"weights"`
  302. Defaults Weights `json:"defaults"`
  303. Nodes []NodeStatus `json:"nodes"`
  304. Matrix map[string]map[string]float64 `json:"matrix"` //from node to node, milliseconds
  305. Updated int64 `json:"updated"`
  306. }
  307. // Status builds a preview: every node scored with no locality and no queue,
  308. // which is what an admin wants to see when tuning the weights.
  309. func (s *Manager) Status() Status {
  310. st := Status{InCluster: s.m.InCluster(), Weights: s.Weights(), Defaults: DefaultWeights(), Nodes: []NodeStatus{}, Updated: time.Now().Unix()}
  311. for _, n := range s.m.NodeViews() {
  312. c := Candidate{Node: n, FreeDisk: -1, LatencyToData: -1, Diversity: -1}
  313. score, _ := s.Score(c)
  314. row := NodeStatus{
  315. ID: n.ID, Name: n.Name, State: string(n.State), Local: n.Local,
  316. LatencyMs: n.LatencyMs, Score: score, CPUFree: cpuFree(n),
  317. Features: len(n.Capabilities.EnabledFeatures()),
  318. }
  319. if n.Health.RAMTotal > 0 {
  320. row.MemFree = 1 - float64(n.Health.RAMUsed)/float64(n.Health.RAMTotal)
  321. }
  322. if n.Health.DiskTotal > 0 {
  323. row.DiskFree = float64(n.Health.DiskFree) / float64(n.Health.DiskTotal)
  324. }
  325. st.Nodes = append(st.Nodes, row)
  326. }
  327. sort.Slice(st.Nodes, func(i, j int) bool { return st.Nodes[i].Score > st.Nodes[j].Score })
  328. if st.InCluster {
  329. //What the replication planner sees when it spreads copies over sites
  330. st.Matrix = s.m.LatencyMatrix()
  331. }
  332. return st
  333. }
  334. // ParseFeatures splits a comma separated feature list.
  335. func ParseFeatures(s string) []string {
  336. out := []string{}
  337. for _, p := range strings.Split(s, ",") {
  338. if v := strings.TrimSpace(p); v != "" {
  339. out = append(out, v)
  340. }
  341. }
  342. return out
  343. }