node_selection.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. Copyright 2016 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 priorities
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strings"
  18. _ "github.com/go-sql-driver/mysql"
  19. client "github.com/influxdata/influxdb1-client/v2"
  20. "k8s.io/klog"
  21. )
  22. var (
  23. nodeSelectionPriority = &CustomAllocationPriority{"NodeSelection", nodeSelectionScorer}
  24. //customResourcePriority = &CustomAllocationPriority{"CustomRequestedPriority", customResourceScorer}
  25. // LeastRequestedPriorityMap is a priority function that favors nodes with fewer requested resources.
  26. // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and
  27. // prioritizes based on the minimum of the average of the fraction of requested to capacity.
  28. //
  29. // Details:
  30. // (cpu((capacity-sum(requested))*10/capacity) + memory((capacity-sum(requested))*10/capacity))/2
  31. NodeSelectionPriorityMap = nodeSelectionPriority.PriorityMap
  32. )
  33. // type Config struct {
  34. // Server struct {
  35. // Port string `yaml:"port"`
  36. // Host string `yaml:"host"`
  37. // } `yaml:"server"`
  38. // Database struct {
  39. // Type string `yaml:"type"`
  40. // Name string `yaml:"name"`
  41. // Username string `yaml:"username"`
  42. // Password string `yaml:"password"`
  43. // } `yaml:"database"`
  44. // MonitoringSpecs struct {
  45. // TimeInterval float32 `yaml:"interval"`
  46. // } `yaml:"monitoring"`
  47. // }
  48. // type Row struct {
  49. // ipc float32
  50. // l3m float32
  51. // reads float32
  52. // writes float32
  53. // c6res float32
  54. // }
  55. // type System struct {
  56. // ID int `json:"id"`
  57. // Uuid string `json:"uuid"`
  58. // numSockets int `json:"num_sockets"`
  59. // numCores int `json:"num_cores`
  60. // }
  61. // var nodes = map[string]string{
  62. // "kube-01": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  63. // "kube-02": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  64. // "kube-03": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  65. // "kube-04": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  66. // "kube-05": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  67. // "kube-06": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  68. // "kube-07": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  69. // "kube-08": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  70. // }
  71. // var sockets = map[string]int{
  72. // "kube-01": 0,
  73. // "kube-02": 0,
  74. // "kube-03": 0,
  75. // "kube-04": 0,
  76. // "kube-05": 0,
  77. // "kube-06": 1,
  78. // "kube-07": 0,
  79. // "kube-08": 1,
  80. // }
  81. var cores = map[string][]int{
  82. "kube-01": []int{},
  83. "kube-02": []int{},
  84. "kube-03": []int{},
  85. "kube-04": []int{},
  86. "kube-05": []int{0, 1, 2, 3},
  87. "kube-06": []int{12, 13, 14, 15, 16, 17, 18, 19},
  88. "kube-07": []int{4, 5, 6, 7, 8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31},
  89. "kube-08": []int{20, 21, 22, 23, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47},
  90. }
  91. // func readFile(cfg *Config, file string) error {
  92. // f, err := os.Open(file)
  93. // if err != nil {
  94. // klog.Infof("Config file for scheduler not found. Error: %v", err)
  95. // return err
  96. // }
  97. // defer f.Close()
  98. // decoder := yaml.NewDecoder(f)
  99. // err = decoder.Decode(&cfg)
  100. // if err != nil {
  101. // klog.Infof("Unable to decode the config file. Error: %v", err)
  102. // return err
  103. // }
  104. // return nil
  105. // }
  106. type scorerInput struct {
  107. metricName string
  108. metrics map[string]float64
  109. }
  110. func OneScorer(si scorerInput) float64 {
  111. return si.metrics[si.metricName]
  112. }
  113. // func customScoreFn(metrics map[string]float64) float64 {
  114. // return metrics["ipc"] / metrics["mem_read"] * metrics["mem_write"]
  115. // }
  116. // func onlyIPC(metrics map[string]float64) float64 {
  117. // return metrics["ipc"]
  118. // }
  119. // func onlyL3(metrics map[string]float64) float64 {
  120. // return 1 / metrics["l3m"]
  121. // }
  122. // func onlyNrg(metrics map[string]float64) float64 {
  123. // return 1 / metrics["procnrg"]
  124. // }
  125. // func calculateScore(results map[string]float64,
  126. // logicFn func(map[string]float64) float64) float64 {
  127. // res := logicFn(results)
  128. // //klog.Infof("Has score (in float) %v\n", res)
  129. // return res
  130. // }
  131. func calculateWeightedAverageCores(response *client.Response,
  132. numberOfRows, numberOfMetrics, numberOfCores int) (map[string]float64, error) {
  133. // initialize the metrics map with a constant size
  134. metrics := make(map[string]float64, numberOfMetrics)
  135. rows := response.Results[0].Series[0]
  136. for i := 1; i < len(rows.Columns); i++ {
  137. for j := 0; j < numberOfRows; j++ {
  138. avg := 0.0
  139. for k := 0; k < numberOfCores; k++ {
  140. val, err := rows.Values[j*numberOfCores+k][i].(json.Number).Float64()
  141. if err != nil {
  142. klog.Infof("Error while calculating %v", rows.Columns[i])
  143. return nil, err
  144. }
  145. //metrics[rows.Columns[i]] += val * float64(numberOfRows-j)
  146. avg += val
  147. }
  148. metrics[rows.Columns[i]] += avg * float64(numberOfRows-j)
  149. }
  150. metrics[rows.Columns[i]] = metrics[rows.Columns[i]] / float64((numberOfRows * (numberOfRows + 1) / 2))
  151. klog.Infof("%v : %v", rows.Columns[i], metrics[rows.Columns[i]])
  152. }
  153. // TODO better handling for the returning errors
  154. return metrics, nil
  155. }
  156. // func connectToInfluxDB(cfg Config) (client.Client, error) {
  157. // c, err := client.NewHTTPClient(client.HTTPConfig{
  158. // Addr: "http://" + cfg.Server.Host + ":" + cfg.Server.Port + "",
  159. // })
  160. // if err != nil {
  161. // klog.Infof("Error while connecting to InfluxDB: %v ", err.Error())
  162. // return nil, err
  163. // }
  164. // klog.Infof("Connected Successfully to InfluxDB")
  165. // return c, nil
  166. // }
  167. // This function does the following:
  168. // 1. Queries the DB with the provided metrics and cores
  169. // 2. Calculates and returns the weighted average of each of those metrics
  170. func queryInfluxDbCores(metrics []string, uuid string, socket,
  171. time int, cfg Config, c client.Client, cores []int) (map[string]float64, error) {
  172. // calculate the number of rows needed
  173. // i.e. 20sec / 0.5s interval => 40rows
  174. numberOfRows := int(float32(time) / cfg.MonitoringSpecs.TimeInterval)
  175. // EDIT
  176. // This time we will fetch data for multiple cores
  177. // so we will need more rows, proportional to the core number
  178. numberOfRows *= len(cores)
  179. // merge all the required columns
  180. columns := strings.Join(metrics, ", ")
  181. // build the cores part of the command
  182. var coresPart strings.Builder
  183. fmt.Fprintf(&coresPart, "core_id='%d'", cores[0])
  184. for i := 1; i < len(cores); i++ {
  185. fmt.Fprintf(&coresPart, " or core_id='%d'", cores[i])
  186. }
  187. // build the coommand
  188. var command strings.Builder
  189. fmt.Fprintf(&command, "SELECT %s from core_metrics where uuid = '%s' and socket_id='%d' and %s order by time desc limit %d", columns, uuid, socket, coresPart.String(), numberOfRows)
  190. q := client.NewQuery(command.String(), cfg.Database.Name, "")
  191. response, err := c.Query(q)
  192. if err != nil {
  193. klog.Infof("Error while executing the query: %v", err.Error())
  194. return nil, err
  195. }
  196. // Calculate the average for the metrics provided
  197. return calculateWeightedAverageCores(response, numberOfRows, len(metrics), len(cores))
  198. }
  199. func nodeSelectionScorer(nodeName string) (float64, error) {
  200. //return (customRequestedScore(requested.MilliCPU, allocable.MilliCPU) +
  201. //customRequestedScore(requested.Memory, allocable.Memory)) / 2
  202. //read database information
  203. var cfg Config
  204. err := readFile(&cfg, "/etc/kubernetes/scheduler-monitoringDB.yaml")
  205. if err != nil {
  206. return 0, err
  207. }
  208. /*-------------------------------------
  209. //TODO read also nodes to uuid mappings for EVOLVE
  210. -------------------------------------*/
  211. // InfluxDB
  212. c, err := connectToInfluxDB(cfg)
  213. if err != nil {
  214. return 0, err
  215. }
  216. // close the connection in the end of execution
  217. defer c.Close()
  218. //Get the uuid of this node in order to query in the database
  219. curr_uuid, ok := nodes[nodeName]
  220. socket, _ := sockets[nodeName]
  221. cores, _ := cores[nodeName]
  222. if len(cores) == 0 {
  223. return 0.0, nil
  224. }
  225. if ok {
  226. // Select Socket
  227. results, err := queryInfluxDbCores([]string{"c6res"}, curr_uuid, socket, 20, cfg, c, cores)
  228. if err != nil {
  229. klog.Infof("Error in querying or calculating average: %v", err.Error())
  230. return 0, nil
  231. }
  232. res := calculateScore(results, OneScorer)
  233. // Select Node
  234. klog.Infof("Node name %s, has score %v\n", nodeName, res)
  235. return res, nil
  236. } else {
  237. klog.Infof("Error finding the uuid: %v", ok)
  238. return 0, nil
  239. }
  240. }