custom_resource_allocation.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. "os"
  18. "strings"
  19. _ "github.com/go-sql-driver/mysql"
  20. client "github.com/influxdata/influxdb1-client/v2"
  21. "gopkg.in/yaml.v2"
  22. "k8s.io/klog"
  23. )
  24. var (
  25. //customResourcePriority = &CustomAllocationPriority{"CustomResourceAllocation", customResourceScorer}
  26. customResourcePriority = &CustomAllocationPriority{"CustomRequestedPriority", customResourceScorer}
  27. // LeastRequestedPriorityMap is a priority function that favors nodes with fewer requested resources.
  28. // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and
  29. // prioritizes based on the minimum of the average of the fraction of requested to capacity.
  30. //
  31. // Details:
  32. // (cpu((capacity-sum(requested))*10/capacity) + memory((capacity-sum(requested))*10/capacity))/2
  33. CustomRequestedPriorityMap = customResourcePriority.CustomPriorityMap
  34. )
  35. type Config struct {
  36. Server struct {
  37. Port string `yaml:"port"`
  38. Host string `yaml:"host"`
  39. } `yaml:"server"`
  40. Database struct {
  41. Type string `yaml:"type"`
  42. Name string `yaml:"name"`
  43. Username string `yaml:"username"`
  44. Password string `yaml:"password"`
  45. } `yaml:"database"`
  46. MonitoringSpecs struct {
  47. TimeInterval float32 `yaml:"interval"`
  48. } `yaml:"monitoring"`
  49. }
  50. // type Row struct {
  51. // ipc float32
  52. // l3m float32
  53. // reads float32
  54. // writes float32
  55. // c6res float32
  56. // }
  57. // type System struct {
  58. // ID int `json:"id"`
  59. // Uuid string `json:"uuid"`
  60. // numSockets int `json:"num_sockets"`
  61. // numCores int `json:"num_cores`
  62. // }
  63. var nodes = map[string]string{
  64. "kube-01": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  65. "kube-02": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  66. "kube-03": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  67. "kube-04": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  68. "kube-05": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  69. "kube-06": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  70. "kube-07": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  71. "kube-08": "c4766d29-4dc1-11ea-9d98-0242ac110002",
  72. }
  73. var sockets = map[string]int{
  74. "kube-01": 0,
  75. "kube-02": 0,
  76. "kube-03": 0,
  77. "kube-04": 0,
  78. "kube-05": 0,
  79. "kube-06": 1,
  80. "kube-07": 0,
  81. "kube-08": 1,
  82. }
  83. func readFile(cfg *Config, file string) {
  84. f, err := os.Open("/etc/kubernetes/scheduler-monitoringDB.yaml")
  85. if err != nil {
  86. panic(err.Error())
  87. }
  88. defer f.Close()
  89. decoder := yaml.NewDecoder(f)
  90. err = decoder.Decode(&cfg)
  91. if err != nil {
  92. panic(err.Error())
  93. }
  94. }
  95. func customScoreFn(metrics map[string]float64) float64 {
  96. return metrics["mem_read"] * metrics["mem_write"] / metrics["ipc"]
  97. }
  98. func calculateScore(results map[string]float64,
  99. logicFn func(map[string]float64) float64) float64 {
  100. res := logicFn(results)
  101. klog.Infof("Has score (in float) %v\n", res)
  102. // TODO
  103. // While the final score should be an integer,
  104. // find a solution about resolving the float prflduced
  105. return res
  106. }
  107. func calculateWeightedAverage(response *client.Response,
  108. numberOfRows int, numberOfMetrics int) (map[string]float64, error) {
  109. // initialize the metrics map with a constant size
  110. metrics := make(map[string]float64, numberOfMetrics)
  111. rows := response.Results[0].Series[0]
  112. for i := 1; i < len(rows.Columns); i++ {
  113. for j := 0; j < numberOfRows; j++ {
  114. val, err := rows.Values[j][i].(json.Number).Float64()
  115. if err != nil {
  116. klog.Infof("Error while calculating %v", rows.Columns[i])
  117. return nil, err
  118. }
  119. metrics[rows.Columns[i]] += val * float64(numberOfRows-j)
  120. }
  121. metrics[rows.Columns[i]] = metrics[rows.Columns[i]] / float64((numberOfRows * (numberOfRows + 1) / 2))
  122. klog.Infof("%v : %v", rows.Columns[i], metrics[rows.Columns[i]])
  123. }
  124. // TODO better handling for the returning errors
  125. return metrics, nil
  126. }
  127. func connectToInfluxDB(cfg Config) (client.Client, error) {
  128. c, err := client.NewHTTPClient(client.HTTPConfig{
  129. Addr: "http://" + cfg.Server.Host + ":" + cfg.Server.Port + "",
  130. })
  131. if err != nil {
  132. klog.Infof("Error while connecting to InfluxDB: %v ", err.Error())
  133. return nil, err
  134. }
  135. klog.Infof("Connected Successfully to InfluxDB")
  136. return c, nil
  137. }
  138. func queryInfluxDB(metrics []string, uuid string, socket int,
  139. time int, cfg Config, c client.Client) (map[string]float64, error) {
  140. // calculate the number of rows needed
  141. // i.e. 20sec / 0.5s interval => 40rows
  142. numberOfRows := int(float32(time) / cfg.MonitoringSpecs.TimeInterval)
  143. // merge all the required columns
  144. columns := strings.Join(metrics, ", ")
  145. // build the coommand
  146. command := fmt.Sprintf("SELECT %s from socket_metrics where uuid = '%s' and socket_id='%d' order by time desc limit %d", columns, uuid, socket, numberOfRows)
  147. q := client.NewQuery(command, cfg.Database.Name, "")
  148. response, err := c.Query(q)
  149. if err != nil {
  150. klog.Infof("Error while executing the query: %v", err.Error())
  151. return nil, err
  152. }
  153. // Calculate the average for the metrics provided
  154. return calculateWeightedAverage(response, numberOfRows, len(metrics))
  155. }
  156. func customResourceScorer(nodeName string) (float64, error) {
  157. //return (customRequestedScore(requested.MilliCPU, allocable.MilliCPU) +
  158. //customRequestedScore(requested.Memory, allocable.Memory)) / 2
  159. //read database information
  160. var cfg Config
  161. readFile(&cfg, "/etc/kubernetes/scheduler-monitoringDB.yaml")
  162. /*-------------------------------------
  163. //TODO read also nodes to uuid mappings
  164. -------------------------------------*/
  165. // InfluxDB
  166. c, err := connectToInfluxDB(cfg)
  167. if err != nil {
  168. return 0, err
  169. }
  170. // close the connection in the end of execution
  171. defer c.Close()
  172. //Get the uuid of this node in order to query in the database
  173. curr_uuid, ok := nodes[nodeName]
  174. socket, _ := sockets[nodeName]
  175. if ok {
  176. results, err := queryInfluxDB([]string{"ipc", "mem_read", "mem_write"}, curr_uuid, socket, 20, cfg, c)
  177. if err != nil {
  178. klog.Infof("Error in querying or calculating average: %v", err.Error())
  179. return 0, nil
  180. }
  181. res := calculateScore(results, customScoreFn)
  182. klog.Infof("Node name %s, has score %v\n", nodeName, res)
  183. return res, nil
  184. } else {
  185. klog.Infof("Error finding the uuid: %v", ok)
  186. return 0, nil
  187. }
  188. // //Close the database connection in the end of the execution
  189. // defer db.Close()
  190. // //Get the uuid of this node in order to query in the database
  191. // curr_uuid, ok := nodes[nodeName]
  192. // //Get the metrics for the current node
  193. // if ok {
  194. // results, err := db.Query("SELECT id, num_sockets, num_cores FROM systems WHERE uuid = ?", curr_uuid)
  195. // if err != nil {
  196. // panic(err.Error()) // proper error handling instead of panic in your app
  197. // }
  198. // sys := System{}
  199. // sys.Uuid = curr_uuid
  200. // for results.Next() {
  201. // // for each row, scan the result into our tag composite object
  202. // err = results.Scan(&sys.ID, &sys.numSockets, &sys.numCores)
  203. // if err != nil {
  204. // panic(err.Error()) // proper error handling instead of panic in your app
  205. // }
  206. // // and then print out the tag's Name attribute
  207. // klog.Infof("This is the system with name: %s, id: %d and number of cores: %d", nodeName, sys.ID, sys.numCores)
  208. // }
  209. // }
  210. // res := customRequestedScore(nodeName)
  211. // klog.Infof("Node name %s, has score %d\n", nodeName, res)
  212. // return res, nil
  213. }
  214. func customRequestedScore(nodeName string) int64 {
  215. if nodeName == "kube-01" {
  216. return 10
  217. }
  218. return 0
  219. }