custom_resource_allocation.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. Copyright 2020 Achilleas Tzenetopoulos.
  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. "github.com/iwita/kube-scheduler/customcache"
  21. "k8s.io/klog"
  22. )
  23. var (
  24. customResourcePriority = &CustomAllocationPriority{"CustomResourceAllocation", customResourceScorer}
  25. //customResourcePriority = &CustomAllocationPriority{"CustomRequestedPriority", customResourceScorer}
  26. // LeastRequestedPriorityMap is a priority function that favors nodes with fewer requested resources.
  27. // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and
  28. // prioritizes based on the minimum of the average of the fraction of requested to capacity.
  29. //
  30. // Details:
  31. // (cpu((capacity-sum(requested))*10/capacity) + memory((capacity-sum(requested))*10/capacity))/2
  32. CustomRequestedPriorityMap = customResourcePriority.PriorityMap
  33. )
  34. func customScoreFn(si scorerInput) float64 {
  35. return si.metrics["ipc"] / (si.metrics["mem_read"] + si.metrics["mem_write"])
  36. }
  37. func onlyIPC(metrics map[string]float64) float64 {
  38. return metrics["ipc"]
  39. }
  40. func onlyL3(metrics map[string]float64) float64 {
  41. return 1 / metrics["l3m"]
  42. }
  43. func onlyNrg(metrics map[string]float64) float64 {
  44. return 1 / metrics["procnrg"]
  45. }
  46. func calculateScore(si scorerInput,
  47. logicFn func(scorerInput) float64) float64 {
  48. res := logicFn(si)
  49. //klog.Infof("Has score (in float) %v\n", res)
  50. return res
  51. }
  52. func calculateWeightedAverage(response *client.Response,
  53. numberOfRows, numberOfMetrics int) (map[string]float64, error) {
  54. // initialize the metrics map with a constant size
  55. metrics := make(map[string]float64, numberOfMetrics)
  56. rows := response.Results[0].Series[0]
  57. for i := 1; i < len(rows.Columns); i++ {
  58. for j := 0; j < numberOfRows; j++ {
  59. val, err := rows.Values[j][i].(json.Number).Float64()
  60. if err != nil {
  61. klog.Infof("Error while calculating %v", rows.Columns[i])
  62. return nil, err
  63. }
  64. metrics[rows.Columns[i]] += val * float64(numberOfRows-j)
  65. }
  66. metrics[rows.Columns[i]] = metrics[rows.Columns[i]] / float64((numberOfRows * (numberOfRows + 1) / 2))
  67. //klog.Infof("%v : %v", rows.Columns[i], metrics[rows.Columns[i]])
  68. }
  69. // TODO better handling for the returning errors
  70. return metrics, nil
  71. }
  72. func customScoreInfluxDB(metrics []string, uuid string, socket,
  73. numberOfRows int, cfg Config, c client.Client) (map[string]float64, error) {
  74. // calculate the number of rows needed
  75. // i.e. 20sec / 0.5s interval => 40rows
  76. //numberOfRows := int(float32(time) / cfg.MonitoringSpecs.TimeInterval)
  77. // merge all the required columns
  78. columns := strings.Join(metrics, ", ")
  79. // build the coommand
  80. var command strings.Builder
  81. fmt.Fprintf(&command, "SELECT %s from socket_metrics where uuid = '%s' and socket_id='%d' order by time desc limit %d", columns, uuid, socket, numberOfRows)
  82. //klog.Infof("%s", command.String())
  83. //q := client.NewQuery("select ipc from system_metrics", "evolve", "")
  84. q := client.NewQuery(command.String(), cfg.Database.Name, "")
  85. response, err := c.Query(q)
  86. if err != nil {
  87. klog.Infof("Error while executing the query: %v", err.Error())
  88. return nil, err
  89. }
  90. // Calculate the average for the metrics provided
  91. return calculateWeightedAverage(response, numberOfRows, len(metrics))
  92. }
  93. func InvalidateCache() {
  94. // Check if the cache needs update
  95. select {
  96. // clean the cache if 10 seconds are passed
  97. case <-customcache.LabCache.Timeout.C:
  98. klog.Infof("Time to erase")
  99. klog.Infof("Cache: %v", customcache.LabCache.Cache)
  100. //customcache.LabCache.Timeout.Stop()
  101. customcache.LabCache.CleanCache()
  102. default:
  103. }
  104. }
  105. func customResourceScorer(nodeName string) (float64, error) {
  106. //InvalidateCache()
  107. //klog.Infof("The value of the Ticker: %v", customcache.LabCache.Timeout.C)
  108. cores, _ := Cores[nodeName]
  109. var results map[string]float64
  110. // Check the cache
  111. customcache.LabCache.Mux.Lock()
  112. ipc, ok := customcache.LabCache.Cache[nodeName]["ipc"]
  113. if !ok {
  114. klog.Infof("IPC is nil")
  115. }
  116. reads, ok := customcache.LabCache.Cache[nodeName]["mem_read"]
  117. if !ok {
  118. klog.Infof("Memory Reads is nil")
  119. }
  120. writes, ok := customcache.LabCache.Cache[nodeName]["mem_write"]
  121. if !ok {
  122. klog.Infof("Memory Writes is nil")
  123. }
  124. c6res, ok := customcache.LabCache.Cache[nodeName]["c6res"]
  125. if !ok {
  126. klog.Infof("C6 state is nil")
  127. }
  128. customcache.LabCache.Mux.Unlock()
  129. // If the cache has value use it
  130. if ipc != -1 && reads != -1 && writes != -1 && c6res != -1 {
  131. results := map[string]float64{
  132. "ipc": ipc,
  133. "mem_read": reads,
  134. "mem_write": writes,
  135. "c6res": c6res,
  136. }
  137. klog.Infof("Found in the cache: ipc: %v, reads: %v, writes: %v", ipc, reads, writes)
  138. res := calculateScore(scorerInput{metrics: results}, customScoreFn)
  139. if sum := c6res * float64(len(cores)); sum < 1 {
  140. //klog.Infof("Average C6 is less than 1, so we get: %v", average["c6res"])
  141. res = res * c6res
  142. } else {
  143. res = res * 1
  144. }
  145. //Apply heterogeneity
  146. speed := links[Nodes[nodeName]][0] * links[Nodes[nodeName]][1]
  147. res = res * float64(speed)
  148. // Select Node
  149. klog.Infof("Using the cached values, Node name %s, has score %v\n", nodeName, res)
  150. return res, nil
  151. }
  152. //read database information
  153. var cfg Config
  154. err := readFile(&cfg, "/etc/kubernetes/scheduler-monitoringDB.yaml")
  155. if err != nil {
  156. return 0, err
  157. }
  158. /*-------------------------------------
  159. //TODO read also nodes to uuid mappings for EVOLVE
  160. -------------------------------------*/
  161. // InfluxDB
  162. c, err := connectToInfluxDB(cfg)
  163. if err != nil {
  164. return 0, err
  165. }
  166. // close the connection in the end of execution
  167. defer c.Close()
  168. //Get the uuid of this node in order to query in the database
  169. curr_uuid, ok := Nodes[nodeName]
  170. socket, _ := Sockets[nodeName]
  171. // cores, _ := Cores[nodeName]
  172. if ok {
  173. metrics := []string{"c6res"}
  174. time := 20
  175. numberOfRows := int(float32(time) / cfg.MonitoringSpecs.TimeInterval)
  176. // Define Core availability
  177. r, err := queryInfluxDbCores(metrics, curr_uuid, socket, numberOfRows, cfg, c, cores)
  178. if err != nil {
  179. klog.Infof("Error in querying or calculating core availability in the first stage: %v", err.Error())
  180. }
  181. average, err := calculateWeightedAverageCores(r, numberOfRows, len(metrics), len(cores))
  182. if err != nil {
  183. klog.Infof("Error defining core availability")
  184. }
  185. // Select Socket
  186. results, err = customScoreInfluxDB([]string{"ipc", "mem_read", "mem_write"}, curr_uuid, socket, numberOfRows, cfg, c)
  187. if err != nil {
  188. klog.Infof("Error in querying or calculating average for the custom score in the first stage: %v", err.Error())
  189. return 0, nil
  190. }
  191. res := calculateScore(scorerInput{metrics: results}, customScoreFn)
  192. //klog.Infof("Node: %v\t res before: %v", nodeName, res)
  193. if sum := average["c6res"] * float64(len(cores)); sum < 1 {
  194. //klog.Infof("Average C6 is less than 1, so we get: %v", average["c6res"])
  195. res = res * average["c6res"]
  196. } else {
  197. res = res * 1
  198. }
  199. //Update the cache with the new metrics
  200. err = customcache.LabCache.UpdateCache(results, average["c6res"], nodeName)
  201. if err != nil {
  202. klog.Infof(err.Error())
  203. } else {
  204. klog.Infof("Cache updated successfully for %v", nodeName)
  205. }
  206. //Apply heterogeneity
  207. speed := links[Nodes[nodeName]][0] * links[Nodes[nodeName]][1]
  208. res = res * float64(speed)
  209. // Select Node
  210. klog.Infof("Node name %s, has score %v\n", nodeName, res)
  211. return res, nil
  212. } else {
  213. klog.Infof("Error finding the uuid: %v", ok)
  214. return 0, nil
  215. }
  216. }
  217. // WARNING
  218. // c6res is not a dependable metric for isnpecting core availability
  219. // Some Systems use higher core states (e.g c7res)
  220. // func findAvailability(response *client.Response, numberOfMetrics, numberOfRows, numberOfCores int, floor float64) (map[string]float64, error) {
  221. // // initialize the metrics map with a constant size
  222. // metrics := make(map[string]float64, numberOfMetrics)
  223. // rows := response.Results[0].Series[0]
  224. // for i := 1; i < len(rows.Columns); i++ {
  225. // //klog.Infof("Name of column %v : %v\nrange of values: %v\nnumber of rows: %v\nnumber of cores %v\n", i, rows.Columns[i], len(rows.Values), numberOfRows, numberOfCores)
  226. // for j := 0; j < numberOfRows; j++ {
  227. // //avg, max := 0.0, 0.0
  228. // for k := 0; k < numberOfCores; k++ {
  229. // val, err := rows.Values[j*numberOfCores+k][i].(json.Number).Float64()
  230. // if err != nil {
  231. // klog.Infof("Error while calculating %v", rows.Columns[i])
  232. // return false, err
  233. // }
  234. // // if val > floor {
  235. // // return true, nil
  236. // // }
  237. // // sum += val
  238. // //avg += val / float64(numberOfCores)
  239. // avg += val
  240. // }
  241. // metrics[rows.Columns[i]] += avg * float64(numberOfRows-j)
  242. // }
  243. // metrics[rows.Columns[i]] = metrics[rows.Columns[i]] / float64((numberOfRows * (numberOfRows + 1) / 2))
  244. // if metrics[row.Columns[i]] > 1 {
  245. // return true, nil
  246. // }
  247. // //klog.Infof("%v : %v", rows.Columns[i], metrics[rows.Columns[i]])
  248. // }
  249. // // TODO better handling for the returning errors
  250. // return false, nil
  251. // }