custom_resource_allocation.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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.PriorityMap
  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) error {
  84. f, err := os.Open(file)
  85. if err != nil {
  86. klog.Infof("Config file for scheduler not found. Error: %v", err)
  87. return err
  88. }
  89. defer f.Close()
  90. decoder := yaml.NewDecoder(f)
  91. err = decoder.Decode(&cfg)
  92. if err != nil {
  93. klog.Infof("Unable to decode the config file. Error: %v", err)
  94. return err
  95. }
  96. return nil
  97. }
  98. func customScoreFn(metrics map[string]float64) float64 {
  99. return metrics["ipc"] / metrics["mem_read"] * metrics["mem_write"]
  100. }
  101. func onlyIPC(metrics map[string]float64) float64 {
  102. return metrics["ipc"]
  103. }
  104. func onlyL3(metrics map[string]float64) float64 {
  105. return 1 / metrics["l3m"]
  106. }
  107. func onlyNrg(metrics map[string]float64) float64 {
  108. return 1 / metrics["procnrg"]
  109. }
  110. func calculateScore(results map[string]float64,
  111. logicFn func(map[string]float64) float64) float64 {
  112. res := logicFn(results)
  113. //klog.Infof("Has score (in float) %v\n", res)
  114. return res
  115. }
  116. func calculateWeightedAverage(response *client.Response,
  117. numberOfRows, numberOfMetrics int) (map[string]float64, error) {
  118. // initialize the metrics map with a constant size
  119. metrics := make(map[string]float64, numberOfMetrics)
  120. rows := response.Results[0].Series[0]
  121. for i := 1; i < len(rows.Columns); i++ {
  122. for j := 0; j < numberOfRows; j++ {
  123. val, err := rows.Values[j][i].(json.Number).Float64()
  124. if err != nil {
  125. klog.Infof("Error while calculating %v", rows.Columns[i])
  126. return nil, err
  127. }
  128. metrics[rows.Columns[i]] += val * float64(numberOfRows-j)
  129. }
  130. metrics[rows.Columns[i]] = metrics[rows.Columns[i]] / float64((numberOfRows * (numberOfRows + 1) / 2))
  131. klog.Infof("%v : %v", rows.Columns[i], metrics[rows.Columns[i]])
  132. }
  133. // TODO better handling for the returning errors
  134. return metrics, nil
  135. }
  136. func connectToInfluxDB(cfg Config) (client.Client, error) {
  137. c, err := client.NewHTTPClient(client.HTTPConfig{
  138. Addr: "http://" + cfg.Server.Host + ":" + cfg.Server.Port + "",
  139. })
  140. if err != nil {
  141. klog.Infof("Error while connecting to InfluxDB: %v ", err.Error())
  142. return nil, err
  143. }
  144. klog.Infof("Connected Successfully to InfluxDB")
  145. return c, nil
  146. }
  147. func queryInfluxDB(metrics []string, uuid string, socket,
  148. time int, cfg Config, c client.Client) (map[string]float64, error) {
  149. // calculate the number of rows needed
  150. // i.e. 20sec / 0.5s interval => 40rows
  151. numberOfRows := int(float32(time) / cfg.MonitoringSpecs.TimeInterval)
  152. // merge all the required columns
  153. columns := strings.Join(metrics, ", ")
  154. // build the coommand
  155. 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)
  156. q := client.NewQuery(command, cfg.Database.Name, "")
  157. response, err := c.Query(q)
  158. if err != nil {
  159. klog.Infof("Error while executing the query: %v", err.Error())
  160. return nil, err
  161. }
  162. // Calculate the average for the metrics provided
  163. return calculateWeightedAverage(response, numberOfRows, len(metrics))
  164. }
  165. func customResourceScorer(nodeName string) (float64, error) {
  166. //return (customRequestedScore(requested.MilliCPU, allocable.MilliCPU) +
  167. //customRequestedScore(requested.Memory, allocable.Memory)) / 2
  168. //read database information
  169. var cfg Config
  170. err := readFile(&cfg, "/etc/kubernetes/scheduler-monitoringDB.yaml")
  171. if err != nil {
  172. return 0, err
  173. }
  174. /*-------------------------------------
  175. //TODO read also nodes to uuid mappings for EVOLVE
  176. -------------------------------------*/
  177. // InfluxDB
  178. c, err := connectToInfluxDB(cfg)
  179. if err != nil {
  180. return 0, err
  181. }
  182. // close the connection in the end of execution
  183. defer c.Close()
  184. //Get the uuid of this node in order to query in the database
  185. curr_uuid, ok := nodes[nodeName]
  186. socket, _ := sockets[nodeName]
  187. if ok {
  188. // Select Socket
  189. results, err := queryInfluxDB([]string{"ipc", "mem_read", "mem_write"}, curr_uuid, socket, 20, cfg, c)
  190. if err != nil {
  191. klog.Infof("Error in querying or calculating average: %v", err.Error())
  192. return 0, nil
  193. }
  194. res := calculateScore(results, customScoreFn)
  195. // Select Node
  196. klog.Infof("Node name %s, has score %v\n", nodeName, res)
  197. return res, nil
  198. } else {
  199. klog.Infof("Error finding the uuid: %v", ok)
  200. return 0, nil
  201. }
  202. }