custom_resource_allocation.go 10 KB

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