custom_resource_allocation.go 7.3 KB

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