costmodel.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "os"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. costAnalyzerCloud "github.com/kubecost/cost-model/cloud"
  15. prometheusClient "github.com/prometheus/client_golang/api"
  16. v1 "k8s.io/api/core/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/labels"
  19. "k8s.io/client-go/kubernetes"
  20. "k8s.io/client-go/tools/cache"
  21. "k8s.io/client-go/util/workqueue"
  22. "k8s.io/klog"
  23. )
  24. const (
  25. statusAPIError = 422
  26. apiPrefix = "/api/v1"
  27. epAlertManagers = apiPrefix + "/alertmanagers"
  28. epQuery = apiPrefix + "/query"
  29. epQueryRange = apiPrefix + "/query_range"
  30. epLabelValues = apiPrefix + "/label/:name/values"
  31. epSeries = apiPrefix + "/series"
  32. epTargets = apiPrefix + "/targets"
  33. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  34. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  35. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  36. epConfig = apiPrefix + "/status/config"
  37. epFlags = apiPrefix + "/status/flags"
  38. remoteEnabled = "REMOTE_WRITE_ENABLED"
  39. )
  40. type CostModel struct {
  41. Controller *Controller
  42. }
  43. func NewCostModel(podListWatcher cache.ListerWatcher) *CostModel {
  44. cm := &CostModel{}
  45. cm.ContainerWatcher(podListWatcher)
  46. return cm
  47. }
  48. func (cm *CostModel) ContainerWatcher(podListWatcher cache.ListerWatcher) {
  49. // create the workqueue
  50. queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
  51. // Bind the workqueue to a cache with the help of an informer. This way we make sure that
  52. // whenever the cache is updated, the pod key is added to the workqueue.
  53. // Note that when we finally process the item from the workqueue, we might see a newer version
  54. // of the Pod than the version which was responsible for triggering the update.
  55. indexer, informer := cache.NewIndexerInformer(podListWatcher, &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{
  56. AddFunc: func(obj interface{}) {
  57. key, err := cache.MetaNamespaceKeyFunc(obj)
  58. if err == nil {
  59. queue.Add(key)
  60. }
  61. },
  62. UpdateFunc: func(old interface{}, new interface{}) {
  63. key, err := cache.MetaNamespaceKeyFunc(new)
  64. if err == nil {
  65. queue.Add(key)
  66. }
  67. },
  68. DeleteFunc: func(obj interface{}) {
  69. // IndexerInformer uses a delta queue, therefore for deletes we have to use this
  70. // key function.
  71. key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
  72. if err == nil {
  73. queue.Add(key)
  74. }
  75. },
  76. }, cache.Indexers{})
  77. cm.Controller = NewController(queue, indexer, informer)
  78. // Now let's start the controller
  79. stop := make(chan struct{})
  80. //defer close(stop)
  81. go cm.Controller.Run(1, stop)
  82. }
  83. type CostData struct {
  84. Name string `json:"name,omitempty"`
  85. PodName string `json:"podName,omitempty"`
  86. NodeName string `json:"nodeName,omitempty"`
  87. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  88. Namespace string `json:"namespace,omitempty"`
  89. Deployments []string `json:"deployments,omitempty"`
  90. Services []string `json:"services,omitempty"`
  91. Daemonsets []string `json:"daemonsets,omitempty"`
  92. Statefulsets []string `json:"statefulsets,omitempty"`
  93. Jobs []string `json:"jobs,omitempty"`
  94. RAMReq []*Vector `json:"ramreq,omitempty"`
  95. RAMUsed []*Vector `json:"ramused,omitempty"`
  96. CPUReq []*Vector `json:"cpureq,omitempty"`
  97. CPUUsed []*Vector `json:"cpuused,omitempty"`
  98. RAMAllocation []*Vector `json:"ramallocated,omitempty"`
  99. CPUAllocation []*Vector `json:"cpuallocated,omitempty"`
  100. GPUReq []*Vector `json:"gpureq,omitempty"`
  101. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  102. Labels map[string]string `json:"labels,omitempty"`
  103. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  104. }
  105. type Vector struct {
  106. Timestamp float64 `json:"timestamp"`
  107. Value float64 `json:"value"`
  108. }
  109. const (
  110. queryRAMRequestsStr = `avg(
  111. label_replace(
  112. label_replace(
  113. avg(
  114. count_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  115. *
  116. avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  117. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  118. ), "pod_name","$1","pod","(.+)"
  119. )
  120. ) by (namespace,container_name,pod_name,node)`
  121. queryRAMUsageStr = `sort_desc(
  122. avg(
  123. label_replace(count_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  124. *
  125. label_replace(avg_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  126. ) by (namespace,container_name,pod_name,node)
  127. )`
  128. queryCPURequestsStr = `avg(
  129. label_replace(
  130. label_replace(
  131. avg(
  132. count_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  133. *
  134. avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  135. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  136. ), "pod_name","$1","pod","(.+)"
  137. )
  138. ) by (namespace,container_name,pod_name,node)`
  139. queryCPUUsageStr = `avg(
  140. label_replace(
  141. rate(
  142. container_cpu_usage_seconds_total{container_name!="",container_name!="POD",instance!=""}[%s] %s
  143. ) , "node", "$1", "instance", "(.+)"
  144. )
  145. ) by (namespace,container_name,pod_name,node)`
  146. queryGPURequestsStr = `avg(
  147. label_replace(
  148. label_replace(
  149. avg(
  150. count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  151. *
  152. avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  153. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  154. ), "pod_name","$1","pod","(.+)"
  155. )
  156. ) by (namespace,container_name,pod_name,node)`
  157. queryPVRequestsStr = `avg(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass, namespace, volumename)
  158. *
  159. on (persistentvolumeclaim, namespace) group_right(storageclass, volumename)
  160. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes) by (persistentvolumeclaim, namespace)`
  161. normalizationStr = `max(count_over_time(kube_pod_container_resource_requests_memory_bytes{}[%s] %s))`
  162. )
  163. type PrometheusMetadata struct {
  164. Running bool `json:"running"`
  165. KubecostDataExists bool `json:"kubecostDataExists"`
  166. }
  167. // ValidatePrometheus tells the model what data prometheus has on it.
  168. func ValidatePrometheus(cli prometheusClient.Client) (*PrometheusMetadata, error) {
  169. data, err := query(cli, "up")
  170. if err != nil {
  171. return &PrometheusMetadata{
  172. Running: false,
  173. KubecostDataExists: false,
  174. }, err
  175. }
  176. v, kcmetrics, err := getUptimeData(data)
  177. if err != nil {
  178. return &PrometheusMetadata{
  179. Running: false,
  180. KubecostDataExists: false,
  181. }, err
  182. }
  183. if len(v) > 0 {
  184. return &PrometheusMetadata{
  185. Running: true,
  186. KubecostDataExists: kcmetrics,
  187. }, nil
  188. } else {
  189. return &PrometheusMetadata{
  190. Running: false,
  191. KubecostDataExists: false,
  192. }, fmt.Errorf("No running jobs found on Prometheus at %s", cli.URL(epQuery, nil).Path)
  193. }
  194. }
  195. func getUptimeData(qr interface{}) ([]*Vector, bool, error) {
  196. data, ok := qr.(map[string]interface{})["data"]
  197. if !ok {
  198. e, err := wrapPrometheusError(qr)
  199. if err != nil {
  200. return nil, false, err
  201. }
  202. return nil, false, fmt.Errorf(e)
  203. }
  204. r, ok := data.(map[string]interface{})["result"]
  205. if !ok {
  206. return nil, false, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  207. }
  208. results, ok := r.([]interface{})
  209. if !ok {
  210. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  211. }
  212. jobData := []*Vector{}
  213. kubecostMetrics := false
  214. for _, val := range results {
  215. // For now, just do this for validation. TODO: This can be parsed to figure out the exact running jobs.
  216. metrics, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  217. if !ok {
  218. return nil, false, fmt.Errorf("Prometheus vector does not have metric labels")
  219. }
  220. jobname, ok := metrics["job"]
  221. if !ok {
  222. return nil, false, fmt.Errorf("up query does not have job names")
  223. }
  224. if jobname == "kubecost" {
  225. kubecostMetrics = true
  226. }
  227. value, ok := val.(map[string]interface{})["value"]
  228. if !ok {
  229. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  230. }
  231. dataPoint, ok := value.([]interface{})
  232. if !ok || len(dataPoint) != 2 {
  233. return nil, false, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  234. }
  235. strVal := dataPoint[1].(string)
  236. v, _ := strconv.ParseFloat(strVal, 64)
  237. toReturn := &Vector{
  238. Timestamp: dataPoint[0].(float64),
  239. Value: v,
  240. }
  241. jobData = append(jobData, toReturn)
  242. }
  243. return jobData, kubecostMetrics, nil
  244. }
  245. func ComputeUptimes(cli prometheusClient.Client) (map[string]float64, error) {
  246. res, err := query(cli, `container_start_time_seconds{container_name != "POD",container_name != ""}`)
  247. if err != nil {
  248. return nil, err
  249. }
  250. vectors, err := getContainerMetricVector(res, false, 0)
  251. if err != nil {
  252. return nil, err
  253. }
  254. results := make(map[string]float64)
  255. for key, vector := range vectors {
  256. if err != nil {
  257. return nil, err
  258. }
  259. val := vector[0].Value
  260. uptime := time.Now().Sub(time.Unix(int64(val), 0)).Seconds()
  261. results[key] = uptime
  262. }
  263. return results, nil
  264. }
  265. func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  266. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, window, offset, window, offset)
  267. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, window, offset, window, offset)
  268. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, window, offset, window, offset)
  269. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, window, offset)
  270. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, window, offset, window, offset)
  271. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  272. normalization := fmt.Sprintf(normalizationStr, window, offset)
  273. var wg sync.WaitGroup
  274. wg.Add(8)
  275. var promErr error
  276. var resultRAMRequests interface{}
  277. go func() {
  278. resultRAMRequests, promErr = query(cli, queryRAMRequests)
  279. defer wg.Done()
  280. }()
  281. var resultRAMUsage interface{}
  282. go func() {
  283. resultRAMUsage, promErr = query(cli, queryRAMUsage)
  284. defer wg.Done()
  285. }()
  286. var resultCPURequests interface{}
  287. go func() {
  288. resultCPURequests, promErr = query(cli, queryCPURequests)
  289. defer wg.Done()
  290. }()
  291. var resultCPUUsage interface{}
  292. go func() {
  293. resultCPUUsage, promErr = query(cli, queryCPUUsage)
  294. defer wg.Done()
  295. }()
  296. var resultGPURequests interface{}
  297. go func() {
  298. resultGPURequests, promErr = query(cli, queryGPURequests)
  299. defer wg.Done()
  300. }()
  301. var resultPVRequests interface{}
  302. go func() {
  303. resultPVRequests, promErr = query(cli, queryPVRequests)
  304. defer wg.Done()
  305. }()
  306. var normalizationResult interface{}
  307. go func() {
  308. normalizationResult, promErr = query(cli, normalization)
  309. defer wg.Done()
  310. }()
  311. podDeploymentsMapping := make(map[string]map[string][]string)
  312. podServicesMapping := make(map[string]map[string][]string)
  313. namespaceLabelsMapping := make(map[string]map[string]string)
  314. podlist := cm.Controller.GetAll()
  315. var k8sErr error
  316. go func() {
  317. defer wg.Done()
  318. podDeploymentsMapping, k8sErr = getPodDeployments(clientset, podlist)
  319. if k8sErr != nil {
  320. return
  321. }
  322. podServicesMapping, k8sErr = getPodServices(clientset, podlist)
  323. if k8sErr != nil {
  324. return
  325. }
  326. namespaceLabelsMapping, k8sErr = getNamespaceLabels(clientset)
  327. if k8sErr != nil {
  328. return
  329. }
  330. }()
  331. wg.Wait()
  332. if promErr != nil {
  333. return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  334. }
  335. if k8sErr != nil {
  336. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  337. }
  338. normalizationValue, err := getNormalization(normalizationResult)
  339. if err != nil {
  340. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  341. }
  342. nodes, err := getNodeCost(clientset, cloud)
  343. if err != nil {
  344. klog.V(1).Infof("Warning, no Node cost model available: " + err.Error())
  345. return nil, err
  346. }
  347. pvClaimMapping, err := getPVInfoVector(resultPVRequests)
  348. if err != nil {
  349. klog.Infof("Unable to get PV Data: %s", err.Error())
  350. }
  351. if pvClaimMapping != nil {
  352. err = addPVData(clientset, pvClaimMapping, cloud)
  353. if err != nil {
  354. return nil, err
  355. }
  356. }
  357. containerNameCost := make(map[string]*CostData)
  358. containers := make(map[string]bool)
  359. RAMReqMap, err := getContainerMetricVector(resultRAMRequests, true, normalizationValue)
  360. if err != nil {
  361. return nil, err
  362. }
  363. for key := range RAMReqMap {
  364. containers[key] = true
  365. }
  366. RAMUsedMap, err := getContainerMetricVector(resultRAMUsage, true, normalizationValue)
  367. if err != nil {
  368. return nil, err
  369. }
  370. for key := range RAMUsedMap {
  371. containers[key] = true
  372. }
  373. CPUReqMap, err := getContainerMetricVector(resultCPURequests, true, normalizationValue)
  374. if err != nil {
  375. return nil, err
  376. }
  377. for key := range CPUReqMap {
  378. containers[key] = true
  379. }
  380. GPUReqMap, err := getContainerMetricVector(resultGPURequests, true, normalizationValue)
  381. if err != nil {
  382. return nil, err
  383. }
  384. for key := range GPUReqMap {
  385. containers[key] = true
  386. }
  387. CPUUsedMap, err := getContainerMetricVector(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
  388. if err != nil {
  389. return nil, err
  390. }
  391. for key := range CPUUsedMap {
  392. containers[key] = true
  393. }
  394. currentContainers := make(map[string]v1.Pod)
  395. for _, pod := range podlist {
  396. if pod.Status.Phase != v1.PodRunning {
  397. continue
  398. }
  399. cs, err := newContainerMetricsFromPod(*pod)
  400. if err != nil {
  401. return nil, err
  402. }
  403. for _, c := range cs {
  404. containers[c.Key()] = true // captures any containers that existed for a time < a prometheus scrape interval. We currently charge 0 for this but should charge something.
  405. currentContainers[c.Key()] = *pod
  406. }
  407. }
  408. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  409. for key := range containers {
  410. if _, ok := containerNameCost[key]; ok {
  411. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  412. }
  413. if pod, ok := currentContainers[key]; ok {
  414. podName := pod.GetObjectMeta().GetName()
  415. ns := pod.GetObjectMeta().GetNamespace()
  416. nsLabels := namespaceLabelsMapping[ns]
  417. podLabels := pod.GetObjectMeta().GetLabels()
  418. for k, v := range nsLabels {
  419. if _, ok := podLabels[k]; !ok {
  420. podLabels[k] = v
  421. }
  422. }
  423. nodeName := pod.Spec.NodeName
  424. var nodeData *costAnalyzerCloud.Node
  425. if _, ok := nodes[nodeName]; ok {
  426. nodeData = nodes[nodeName]
  427. }
  428. var podDeployments []string
  429. if _, ok := podDeploymentsMapping[ns]; ok {
  430. if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  431. podDeployments = ds
  432. } else {
  433. podDeployments = []string{}
  434. }
  435. }
  436. var podPVs []*PersistentVolumeClaimData
  437. podClaims := pod.Spec.Volumes
  438. for _, vol := range podClaims {
  439. if vol.PersistentVolumeClaim != nil {
  440. name := vol.PersistentVolumeClaim.ClaimName
  441. if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
  442. podPVs = append(podPVs, pvClaim)
  443. }
  444. }
  445. }
  446. var podServices []string
  447. if _, ok := podServicesMapping[ns]; ok {
  448. if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  449. podServices = svcs
  450. } else {
  451. podServices = []string{}
  452. }
  453. }
  454. for i, container := range pod.Spec.Containers {
  455. containerName := container.Name
  456. // recreate the key and look up data for this container
  457. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName).Key()
  458. RAMReqV, ok := RAMReqMap[newKey]
  459. if !ok {
  460. klog.V(4).Info("no RAM requests for " + newKey)
  461. RAMReqV = []*Vector{&Vector{}}
  462. }
  463. RAMUsedV, ok := RAMUsedMap[newKey]
  464. if !ok {
  465. klog.V(4).Info("no RAM usage for " + newKey)
  466. RAMUsedV = []*Vector{&Vector{}}
  467. }
  468. CPUReqV, ok := CPUReqMap[newKey]
  469. if !ok {
  470. klog.V(4).Info("no CPU requests for " + newKey)
  471. CPUReqV = []*Vector{&Vector{}}
  472. }
  473. GPUReqV, ok := GPUReqMap[newKey]
  474. if !ok {
  475. klog.V(4).Info("no GPU requests for " + newKey)
  476. GPUReqV = []*Vector{&Vector{}}
  477. }
  478. CPUUsedV, ok := CPUUsedMap[newKey]
  479. if !ok {
  480. klog.V(4).Info("no CPU usage for " + newKey)
  481. CPUUsedV = []*Vector{&Vector{}}
  482. }
  483. var pvReq []*PersistentVolumeClaimData
  484. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  485. pvReq = podPVs
  486. }
  487. costs := &CostData{
  488. Name: containerName,
  489. PodName: podName,
  490. NodeName: nodeName,
  491. Namespace: ns,
  492. Deployments: podDeployments,
  493. Services: podServices,
  494. Daemonsets: getDaemonsetsOfPod(pod),
  495. Jobs: getJobsOfPod(pod),
  496. Statefulsets: getStatefulSetsOfPod(pod),
  497. NodeData: nodeData,
  498. RAMReq: RAMReqV,
  499. RAMUsed: RAMUsedV,
  500. CPUReq: CPUReqV,
  501. CPUUsed: CPUUsedV,
  502. GPUReq: GPUReqV,
  503. PVCData: pvReq,
  504. Labels: podLabels,
  505. NamespaceLabels: nsLabels,
  506. }
  507. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  508. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  509. if filterNamespace == "" {
  510. containerNameCost[newKey] = costs
  511. } else if costs.Namespace == filterNamespace {
  512. containerNameCost[newKey] = costs
  513. }
  514. }
  515. } else {
  516. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  517. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  518. c, err := NewContainerMetricFromKey(key)
  519. if err != nil {
  520. return nil, err
  521. }
  522. RAMReqV, ok := RAMReqMap[key]
  523. if !ok {
  524. klog.V(4).Info("no RAM requests for " + key)
  525. RAMReqV = []*Vector{&Vector{}}
  526. }
  527. RAMUsedV, ok := RAMUsedMap[key]
  528. if !ok {
  529. klog.V(4).Info("no RAM usage for " + key)
  530. RAMUsedV = []*Vector{&Vector{}}
  531. }
  532. CPUReqV, ok := CPUReqMap[key]
  533. if !ok {
  534. klog.V(4).Info("no CPU requests for " + key)
  535. CPUReqV = []*Vector{&Vector{}}
  536. }
  537. GPUReqV, ok := GPUReqMap[key]
  538. if !ok {
  539. klog.V(4).Info("no GPU requests for " + key)
  540. GPUReqV = []*Vector{&Vector{}}
  541. }
  542. CPUUsedV, ok := CPUUsedMap[key]
  543. if !ok {
  544. klog.V(4).Info("no CPU usage for " + key)
  545. CPUUsedV = []*Vector{&Vector{}}
  546. }
  547. node, ok := nodes[c.NodeName]
  548. if !ok {
  549. klog.V(2).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  550. if n, ok := missingNodes[c.NodeName]; ok {
  551. node = n
  552. } else {
  553. node = &costAnalyzerCloud.Node{}
  554. missingNodes[c.NodeName] = node
  555. }
  556. }
  557. costs := &CostData{
  558. Name: c.ContainerName,
  559. PodName: c.PodName,
  560. NodeName: c.NodeName,
  561. NodeData: node,
  562. Namespace: c.Namespace,
  563. RAMReq: RAMReqV,
  564. RAMUsed: RAMUsedV,
  565. CPUReq: CPUReqV,
  566. CPUUsed: CPUUsedV,
  567. GPUReq: GPUReqV,
  568. }
  569. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  570. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  571. if filterNamespace == "" {
  572. containerNameCost[key] = costs
  573. } else if costs.Namespace == filterNamespace {
  574. containerNameCost[key] = costs
  575. }
  576. }
  577. }
  578. err = findDeletedNodeInfo(cli, missingNodes, window)
  579. if err != nil {
  580. return nil, err
  581. }
  582. return containerNameCost, err
  583. }
  584. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window string) error {
  585. if len(missingNodes) > 0 {
  586. q := make([]string, 0, len(missingNodes))
  587. for nodename := range missingNodes {
  588. klog.V(3).Infof("Finding data for deleted node %v", nodename)
  589. q = append(q, nodename)
  590. }
  591. l := strings.Join(q, "|")
  592. queryHistoricalCPUCost := fmt.Sprintf(`avg_over_time(node_cpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  593. queryHistoricalRAMCost := fmt.Sprintf(`avg_over_time(node_ram_hourly_cost{instance=~"%s"}[%s])`, l, window)
  594. queryHistoricalGPUCost := fmt.Sprintf(`avg_over_time(node_gpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  595. cpuCostResult, err := query(cli, queryHistoricalCPUCost)
  596. if err != nil {
  597. return fmt.Errorf("Error fetching cpu cost data: " + err.Error())
  598. }
  599. ramCostResult, err := query(cli, queryHistoricalRAMCost)
  600. if err != nil {
  601. return fmt.Errorf("Error fetching ram cost data: " + err.Error())
  602. }
  603. gpuCostResult, err := query(cli, queryHistoricalGPUCost)
  604. if err != nil {
  605. return fmt.Errorf("Error fetching gpu cost data: " + err.Error())
  606. }
  607. cpuCosts, err := getCost(cpuCostResult)
  608. if err != nil {
  609. return err
  610. }
  611. ramCosts, err := getCost(ramCostResult)
  612. if err != nil {
  613. return err
  614. }
  615. gpuCosts, err := getCost(gpuCostResult)
  616. if err != nil {
  617. return err
  618. }
  619. if len(cpuCosts) == 0 {
  620. klog.V(1).Infof("Historical data for node prices not available. Ingest this server's /metrics endpoint to get that data.")
  621. }
  622. for node, costv := range cpuCosts {
  623. if _, ok := missingNodes[node]; ok {
  624. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  625. }
  626. }
  627. for node, costv := range ramCosts {
  628. if _, ok := missingNodes[node]; ok {
  629. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  630. }
  631. }
  632. for node, costv := range gpuCosts {
  633. if _, ok := missingNodes[node]; ok {
  634. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  635. }
  636. }
  637. }
  638. return nil
  639. }
  640. func getContainerAllocation(req []*Vector, used []*Vector) []*Vector {
  641. if req == nil || len(req) == 0 {
  642. for _, usedV := range used {
  643. if usedV.Timestamp == 0 {
  644. continue
  645. }
  646. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  647. }
  648. return used
  649. }
  650. if used == nil || len(used) == 0 {
  651. for _, reqV := range req {
  652. if reqV.Timestamp == 0 {
  653. continue
  654. }
  655. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  656. }
  657. return req
  658. }
  659. var allocation []*Vector
  660. var timestamps []float64
  661. reqMap := make(map[float64]float64)
  662. for _, reqV := range req {
  663. if reqV.Timestamp == 0 {
  664. continue
  665. }
  666. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  667. reqMap[reqV.Timestamp] = reqV.Value
  668. timestamps = append(timestamps, reqV.Timestamp)
  669. }
  670. usedMap := make(map[float64]float64)
  671. for _, usedV := range used {
  672. if usedV.Timestamp == 0 {
  673. continue
  674. }
  675. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  676. usedMap[usedV.Timestamp] = usedV.Value
  677. if _, ok := reqMap[usedV.Timestamp]; !ok { // no need to double add, since we'll range over sorted timestamps and check.
  678. timestamps = append(timestamps, usedV.Timestamp)
  679. }
  680. }
  681. sort.Float64s(timestamps)
  682. for _, t := range timestamps {
  683. rv, okR := reqMap[t]
  684. uv, okU := usedMap[t]
  685. allocationVector := &Vector{
  686. Timestamp: t,
  687. }
  688. if okR && okU {
  689. allocationVector.Value = math.Max(rv, uv)
  690. } else if okR {
  691. allocationVector.Value = rv
  692. } else if okU {
  693. allocationVector.Value = uv
  694. }
  695. allocation = append(allocation, allocationVector)
  696. }
  697. return allocation
  698. }
  699. func addPVData(clientset kubernetes.Interface, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  700. storageClasses, err := clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  701. if err != nil {
  702. return err
  703. }
  704. storageClassMap := make(map[string]map[string]string)
  705. for _, storageClass := range storageClasses.Items {
  706. params := storageClass.Parameters
  707. storageClassMap[storageClass.ObjectMeta.Name] = params
  708. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  709. storageClassMap["default"] = params
  710. storageClassMap[""] = params
  711. }
  712. }
  713. pvs, err := clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  714. if err != nil {
  715. return err
  716. }
  717. pvMap := make(map[string]*costAnalyzerCloud.PV)
  718. for _, pv := range pvs.Items {
  719. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  720. if !ok {
  721. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  722. }
  723. cacPv := &costAnalyzerCloud.PV{
  724. Class: pv.Spec.StorageClassName,
  725. Region: pv.Labels[v1.LabelZoneRegion],
  726. Parameters: parameters,
  727. }
  728. err := GetPVCost(cacPv, &pv, cloud)
  729. if err != nil {
  730. return err
  731. }
  732. pvMap[pv.Name] = cacPv
  733. }
  734. for _, pvc := range pvClaimMapping {
  735. pvc.Volume = pvMap[pvc.VolumeName]
  736. }
  737. return nil
  738. }
  739. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cloud costAnalyzerCloud.Provider) error {
  740. cfg, err := cloud.GetConfig()
  741. key := cloud.GetPVKey(kpv, pv.Parameters)
  742. pvWithCost, err := cloud.PVPricing(key)
  743. if err != nil {
  744. return err
  745. }
  746. if pvWithCost == nil || pvWithCost.Cost == "" {
  747. pv.Cost = cfg.Storage
  748. return nil // set default cost
  749. }
  750. pv.Cost = pvWithCost.Cost
  751. return nil
  752. }
  753. func getNodeCost(clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  754. cfg, err := cloud.GetConfig()
  755. if err != nil {
  756. return nil, err
  757. }
  758. nodeList, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  759. if err != nil {
  760. return nil, err
  761. }
  762. nodes := make(map[string]*costAnalyzerCloud.Node)
  763. for _, n := range nodeList.Items {
  764. name := n.GetObjectMeta().GetName()
  765. nodeLabels := n.GetObjectMeta().GetLabels()
  766. nodeLabels["providerID"] = n.Spec.ProviderID
  767. cnode, err := cloud.NodePricing(cloud.GetKey(nodeLabels))
  768. if err != nil {
  769. klog.V(1).Infof("Error getting node. Error: " + err.Error())
  770. nodes[name] = cnode
  771. continue
  772. }
  773. newCnode := *cnode
  774. var cpu float64
  775. if newCnode.VCPU == "" {
  776. cpu = float64(n.Status.Capacity.Cpu().Value())
  777. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  778. } else {
  779. cpu, _ = strconv.ParseFloat(newCnode.VCPU, 64)
  780. }
  781. var ram float64
  782. if newCnode.RAM == "" {
  783. newCnode.RAM = n.Status.Capacity.Memory().String()
  784. }
  785. ram = float64(n.Status.Capacity.Memory().Value())
  786. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  787. if newCnode.GPU != "" && newCnode.GPUCost == "" { // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  788. klog.V(4).Infof("GPU without cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  789. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  790. if err != nil {
  791. klog.V(3).Infof("Could not parse default cpu price")
  792. return nil, err
  793. }
  794. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  795. if err != nil {
  796. klog.V(3).Infof("Could not parse default ram price")
  797. return nil, err
  798. }
  799. defaultGPU, err := strconv.ParseFloat(cfg.RAM, 64)
  800. if err != nil {
  801. klog.V(3).Infof("Could not parse default gpu price")
  802. return nil, err
  803. }
  804. cpuToRAMRatio := defaultCPU / defaultRAM
  805. gpuToRAMRatio := defaultGPU / defaultRAM
  806. ramGB := ram / 1024 / 1024 / 1024
  807. ramMultiple := gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  808. var nodePrice float64
  809. if newCnode.Cost != "" {
  810. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  811. if err != nil {
  812. klog.V(3).Infof("Could not parse total node price")
  813. return nil, err
  814. }
  815. } else {
  816. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  817. if err != nil {
  818. klog.V(3).Infof("Could not parse node vcpu price")
  819. return nil, err
  820. }
  821. }
  822. ramPrice := (nodePrice / ramMultiple)
  823. cpuPrice := ramPrice * cpuToRAMRatio
  824. gpuPrice := ramPrice * gpuToRAMRatio
  825. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  826. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  827. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  828. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  829. } else {
  830. if newCnode.RAMCost == "" { // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  831. klog.V(4).Infof("No RAM cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  832. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  833. if err != nil {
  834. klog.V(3).Infof("Could not parse default cpu price")
  835. return nil, err
  836. }
  837. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  838. if err != nil {
  839. klog.V(3).Infof("Could not parse default ram price")
  840. return nil, err
  841. }
  842. cpuToRAMRatio := defaultCPU / defaultRAM
  843. ramGB := ram / 1024 / 1024 / 1024
  844. ramMultiple := cpu*cpuToRAMRatio + ramGB
  845. var nodePrice float64
  846. if newCnode.Cost != "" {
  847. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  848. if err != nil {
  849. klog.V(3).Infof("Could not parse total node price")
  850. return nil, err
  851. }
  852. } else {
  853. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  854. if err != nil {
  855. klog.V(3).Infof("Could not parse node vcpu price")
  856. return nil, err
  857. }
  858. }
  859. ramPrice := (nodePrice / ramMultiple)
  860. cpuPrice := ramPrice * cpuToRAMRatio
  861. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  862. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  863. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  864. klog.V(4).Infof("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  865. }
  866. }
  867. nodes[name] = &newCnode
  868. }
  869. return nodes, nil
  870. }
  871. func getPodServices(clientset kubernetes.Interface, podList []*v1.Pod) (map[string]map[string][]string, error) {
  872. servicesList, err := clientset.CoreV1().Services("").List(metav1.ListOptions{})
  873. if err != nil {
  874. return nil, err
  875. }
  876. podServicesMapping := make(map[string]map[string][]string)
  877. for _, service := range servicesList.Items {
  878. namespace := service.GetObjectMeta().GetNamespace()
  879. name := service.GetObjectMeta().GetName()
  880. if _, ok := podServicesMapping[namespace]; !ok {
  881. podServicesMapping[namespace] = make(map[string][]string)
  882. }
  883. s := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  884. for _, pod := range podList {
  885. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  886. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  887. services, ok := podServicesMapping[namespace][pod.GetObjectMeta().GetName()]
  888. if ok {
  889. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = append(services, name)
  890. } else {
  891. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  892. }
  893. }
  894. }
  895. }
  896. return podServicesMapping, nil
  897. }
  898. func getPodDeployments(clientset kubernetes.Interface, podList []*v1.Pod) (map[string]map[string][]string, error) {
  899. deploymentsList, err := clientset.AppsV1().Deployments("").List(metav1.ListOptions{})
  900. if err != nil {
  901. return nil, err
  902. }
  903. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  904. for _, deployment := range deploymentsList.Items {
  905. namespace := deployment.GetObjectMeta().GetNamespace()
  906. name := deployment.GetObjectMeta().GetName()
  907. if _, ok := podDeploymentsMapping[namespace]; !ok {
  908. podDeploymentsMapping[namespace] = make(map[string][]string)
  909. }
  910. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  911. if err != nil {
  912. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  913. }
  914. for _, pod := range podList {
  915. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  916. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  917. deployments, ok := podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()]
  918. if ok {
  919. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = append(deployments, name)
  920. } else {
  921. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  922. }
  923. }
  924. }
  925. }
  926. return podDeploymentsMapping, nil
  927. }
  928. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider,
  929. startString, endString, windowString string, filterNamespace string) (map[string]*CostData, error) {
  930. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, windowString, "", windowString, "")
  931. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, windowString, "", windowString, "")
  932. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, windowString, "", windowString, "")
  933. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, windowString, "")
  934. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, windowString, "", windowString, "")
  935. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  936. normalization := fmt.Sprintf(normalizationStr, windowString, "")
  937. layout := "2006-01-02T15:04:05.000Z"
  938. start, err := time.Parse(layout, startString)
  939. if err != nil {
  940. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  941. return nil, err
  942. }
  943. end, err := time.Parse(layout, endString)
  944. if err != nil {
  945. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  946. return nil, err
  947. }
  948. window, err := time.ParseDuration(windowString)
  949. if err != nil {
  950. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  951. return nil, err
  952. }
  953. remoteEnabled := os.Getenv(remoteEnabled)
  954. if remoteEnabled == "true" && (end.Sub(start) > time.Hour*168) {
  955. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  956. return CostDataRangeFromSQL("", "", windowString, startString, endString)
  957. }
  958. var wg sync.WaitGroup
  959. wg.Add(8)
  960. var promErr error
  961. var resultRAMRequests interface{}
  962. go func() {
  963. resultRAMRequests, promErr = QueryRange(cli, queryRAMRequests, start, end, window)
  964. defer wg.Done()
  965. }()
  966. var resultRAMUsage interface{}
  967. go func() {
  968. resultRAMUsage, promErr = QueryRange(cli, queryRAMUsage, start, end, window)
  969. defer wg.Done()
  970. }()
  971. var resultCPURequests interface{}
  972. go func() {
  973. resultCPURequests, promErr = QueryRange(cli, queryCPURequests, start, end, window)
  974. defer wg.Done()
  975. }()
  976. var resultCPUUsage interface{}
  977. go func() {
  978. resultCPUUsage, promErr = QueryRange(cli, queryCPUUsage, start, end, window)
  979. defer wg.Done()
  980. }()
  981. var resultGPURequests interface{}
  982. go func() {
  983. resultGPURequests, promErr = QueryRange(cli, queryGPURequests, start, end, window)
  984. defer wg.Done()
  985. }()
  986. var resultPVRequests interface{}
  987. go func() {
  988. resultPVRequests, promErr = QueryRange(cli, queryPVRequests, start, end, window)
  989. defer wg.Done()
  990. }()
  991. var normalizationResult interface{}
  992. go func() {
  993. normalizationResult, promErr = query(cli, normalization)
  994. defer wg.Done()
  995. }()
  996. podDeploymentsMapping := make(map[string]map[string][]string)
  997. podServicesMapping := make(map[string]map[string][]string)
  998. namespaceLabelsMapping := make(map[string]map[string]string)
  999. podlist := cm.Controller.GetAll()
  1000. var k8sErr error
  1001. go func() {
  1002. podDeploymentsMapping, k8sErr = getPodDeployments(clientset, podlist)
  1003. if k8sErr != nil {
  1004. return
  1005. }
  1006. podServicesMapping, k8sErr = getPodServices(clientset, podlist)
  1007. if k8sErr != nil {
  1008. return
  1009. }
  1010. namespaceLabelsMapping, k8sErr = getNamespaceLabels(clientset)
  1011. if k8sErr != nil {
  1012. return
  1013. }
  1014. wg.Done()
  1015. }()
  1016. wg.Wait()
  1017. if promErr != nil {
  1018. return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  1019. }
  1020. if k8sErr != nil {
  1021. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  1022. }
  1023. normalizationValue, err := getNormalization(normalizationResult)
  1024. if err != nil {
  1025. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  1026. }
  1027. nodes, err := getNodeCost(clientset, cloud)
  1028. if err != nil {
  1029. klog.V(1).Infof("Warning, no cost model available: " + err.Error())
  1030. return nil, err
  1031. }
  1032. pvClaimMapping, err := getPVInfoVectors(resultPVRequests)
  1033. if err != nil {
  1034. // Just log for compatibility with KSM less than 1.6
  1035. klog.Infof("Unable to get PV Data: %s", err.Error())
  1036. }
  1037. if pvClaimMapping != nil {
  1038. err = addPVData(clientset, pvClaimMapping, cloud)
  1039. if err != nil {
  1040. return nil, err
  1041. }
  1042. }
  1043. containerNameCost := make(map[string]*CostData)
  1044. containers := make(map[string]bool)
  1045. RAMReqMap, err := GetContainerMetricVectors(resultRAMRequests, true, normalizationValue)
  1046. if err != nil {
  1047. return nil, err
  1048. }
  1049. for key := range RAMReqMap {
  1050. containers[key] = true
  1051. }
  1052. RAMUsedMap, err := GetContainerMetricVectors(resultRAMUsage, true, normalizationValue)
  1053. if err != nil {
  1054. return nil, err
  1055. }
  1056. for key := range RAMUsedMap {
  1057. containers[key] = true
  1058. }
  1059. CPUReqMap, err := GetContainerMetricVectors(resultCPURequests, true, normalizationValue)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. for key := range CPUReqMap {
  1064. containers[key] = true
  1065. }
  1066. GPUReqMap, err := GetContainerMetricVectors(resultGPURequests, true, normalizationValue)
  1067. if err != nil {
  1068. return nil, err
  1069. }
  1070. for key := range GPUReqMap {
  1071. containers[key] = true
  1072. }
  1073. CPUUsedMap, err := GetContainerMetricVectors(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
  1074. if err != nil {
  1075. return nil, err
  1076. }
  1077. for key := range CPUUsedMap {
  1078. containers[key] = true
  1079. }
  1080. currentContainers := make(map[string]v1.Pod)
  1081. for _, pod := range podlist {
  1082. if pod.Status.Phase != v1.PodRunning {
  1083. continue
  1084. }
  1085. cs, err := newContainerMetricsFromPod(*pod)
  1086. if err != nil {
  1087. return nil, err
  1088. }
  1089. for _, c := range cs {
  1090. containers[c.Key()] = true // captures any containers that existed for a time < a prometheus scrape interval. We currently charge 0 for this but should charge something.
  1091. currentContainers[c.Key()] = *pod
  1092. }
  1093. }
  1094. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1095. for key := range containers {
  1096. if _, ok := containerNameCost[key]; ok {
  1097. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1098. }
  1099. if pod, ok := currentContainers[key]; ok {
  1100. podName := pod.GetObjectMeta().GetName()
  1101. ns := pod.GetObjectMeta().GetNamespace()
  1102. nodeName := pod.Spec.NodeName
  1103. var nodeData *costAnalyzerCloud.Node
  1104. if _, ok := nodes[nodeName]; ok {
  1105. nodeData = nodes[nodeName]
  1106. }
  1107. var podDeployments []string
  1108. if _, ok := podDeploymentsMapping[ns]; ok {
  1109. if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1110. podDeployments = ds
  1111. } else {
  1112. podDeployments = []string{}
  1113. }
  1114. }
  1115. var podPVs []*PersistentVolumeClaimData
  1116. podClaims := pod.Spec.Volumes
  1117. for _, vol := range podClaims {
  1118. if vol.PersistentVolumeClaim != nil {
  1119. name := vol.PersistentVolumeClaim.ClaimName
  1120. if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
  1121. podPVs = append(podPVs, pvClaim)
  1122. }
  1123. }
  1124. }
  1125. var podServices []string
  1126. if _, ok := podServicesMapping[ns]; ok {
  1127. if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1128. podServices = svcs
  1129. } else {
  1130. podServices = []string{}
  1131. }
  1132. }
  1133. nsLabels := namespaceLabelsMapping[ns]
  1134. podLabels := pod.GetObjectMeta().GetLabels()
  1135. for k, v := range nsLabels {
  1136. if _, ok := podLabels[k]; !ok {
  1137. podLabels[k] = v
  1138. }
  1139. }
  1140. for i, container := range pod.Spec.Containers {
  1141. containerName := container.Name
  1142. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName).Key()
  1143. RAMReqV, ok := RAMReqMap[newKey]
  1144. if !ok {
  1145. klog.V(4).Info("no RAM requests for " + newKey)
  1146. RAMReqV = []*Vector{}
  1147. }
  1148. RAMUsedV, ok := RAMUsedMap[newKey]
  1149. if !ok {
  1150. klog.V(4).Info("no RAM usage for " + newKey)
  1151. RAMUsedV = []*Vector{}
  1152. }
  1153. CPUReqV, ok := CPUReqMap[newKey]
  1154. if !ok {
  1155. klog.V(4).Info("no CPU requests for " + newKey)
  1156. CPUReqV = []*Vector{}
  1157. }
  1158. GPUReqV, ok := GPUReqMap[newKey]
  1159. if !ok {
  1160. klog.V(4).Info("no GPU requests for " + newKey)
  1161. GPUReqV = []*Vector{}
  1162. }
  1163. CPUUsedV, ok := CPUUsedMap[newKey]
  1164. if !ok {
  1165. klog.V(4).Info("no CPU usage for " + newKey)
  1166. CPUUsedV = []*Vector{}
  1167. }
  1168. var pvReq []*PersistentVolumeClaimData
  1169. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  1170. pvReq = podPVs
  1171. }
  1172. costs := &CostData{
  1173. Name: containerName,
  1174. PodName: podName,
  1175. NodeName: nodeName,
  1176. Namespace: ns,
  1177. Deployments: podDeployments,
  1178. Services: podServices,
  1179. Daemonsets: getDaemonsetsOfPod(pod),
  1180. Jobs: getJobsOfPod(pod),
  1181. Statefulsets: getStatefulSetsOfPod(pod),
  1182. NodeData: nodeData,
  1183. RAMReq: RAMReqV,
  1184. RAMUsed: RAMUsedV,
  1185. CPUReq: CPUReqV,
  1186. CPUUsed: CPUUsedV,
  1187. GPUReq: GPUReqV,
  1188. PVCData: pvReq,
  1189. Labels: podLabels,
  1190. NamespaceLabels: nsLabels,
  1191. }
  1192. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1193. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1194. if filterNamespace == "" {
  1195. containerNameCost[newKey] = costs
  1196. } else if costs.Namespace == filterNamespace {
  1197. containerNameCost[newKey] = costs
  1198. }
  1199. }
  1200. } else {
  1201. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  1202. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  1203. c, _ := NewContainerMetricFromKey(key)
  1204. RAMReqV, ok := RAMReqMap[key]
  1205. if !ok {
  1206. klog.V(4).Info("no RAM requests for " + key)
  1207. RAMReqV = []*Vector{}
  1208. }
  1209. RAMUsedV, ok := RAMUsedMap[key]
  1210. if !ok {
  1211. klog.V(4).Info("no RAM usage for " + key)
  1212. RAMUsedV = []*Vector{}
  1213. }
  1214. CPUReqV, ok := CPUReqMap[key]
  1215. if !ok {
  1216. klog.V(4).Info("no CPU requests for " + key)
  1217. CPUReqV = []*Vector{}
  1218. }
  1219. GPUReqV, ok := GPUReqMap[key]
  1220. if !ok {
  1221. klog.V(4).Info("no GPU requests for " + key)
  1222. GPUReqV = []*Vector{}
  1223. }
  1224. CPUUsedV, ok := CPUUsedMap[key]
  1225. if !ok {
  1226. klog.V(4).Info("no CPU usage for " + key)
  1227. CPUUsedV = []*Vector{}
  1228. }
  1229. node, ok := nodes[c.NodeName]
  1230. if !ok {
  1231. klog.V(2).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  1232. if n, ok := missingNodes[c.NodeName]; ok {
  1233. node = n
  1234. } else {
  1235. node = &costAnalyzerCloud.Node{}
  1236. missingNodes[c.NodeName] = node
  1237. }
  1238. }
  1239. costs := &CostData{
  1240. Name: c.ContainerName,
  1241. PodName: c.PodName,
  1242. NodeName: c.NodeName,
  1243. NodeData: node,
  1244. Namespace: c.Namespace,
  1245. RAMReq: RAMReqV,
  1246. RAMUsed: RAMUsedV,
  1247. CPUReq: CPUReqV,
  1248. CPUUsed: CPUUsedV,
  1249. GPUReq: GPUReqV,
  1250. }
  1251. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1252. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1253. if filterNamespace == "" {
  1254. containerNameCost[key] = costs
  1255. } else if costs.Namespace == filterNamespace {
  1256. containerNameCost[key] = costs
  1257. }
  1258. }
  1259. }
  1260. w := end.Sub(start)
  1261. if w.Minutes() > 0 {
  1262. wStr := fmt.Sprintf("%dm", int(w.Minutes()))
  1263. err = findDeletedNodeInfo(cli, missingNodes, wStr)
  1264. if err != nil {
  1265. return nil, err
  1266. }
  1267. }
  1268. return containerNameCost, err
  1269. }
  1270. func getNamespaceLabels(clientset kubernetes.Interface) (map[string]map[string]string, error) {
  1271. nsToLabels := make(map[string]map[string]string)
  1272. nss, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})
  1273. if err != nil {
  1274. return nil, err
  1275. }
  1276. for _, ns := range nss.Items {
  1277. nsToLabels[ns.Name] = ns.Labels
  1278. }
  1279. return nsToLabels, nil
  1280. }
  1281. func getDaemonsetsOfPod(pod v1.Pod) []string {
  1282. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1283. if ownerReference.Kind == "DaemonSet" {
  1284. return []string{ownerReference.Name}
  1285. }
  1286. }
  1287. return []string{}
  1288. }
  1289. func getJobsOfPod(pod v1.Pod) []string {
  1290. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1291. if ownerReference.Kind == "Job" {
  1292. return []string{ownerReference.Name}
  1293. }
  1294. }
  1295. return []string{}
  1296. }
  1297. func getStatefulSetsOfPod(pod v1.Pod) []string {
  1298. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1299. if ownerReference.Kind == "StatefulSet" {
  1300. return []string{ownerReference.Name}
  1301. }
  1302. }
  1303. return []string{}
  1304. }
  1305. type PersistentVolumeClaimData struct {
  1306. Class string `json:"class"`
  1307. Claim string `json:"claim"`
  1308. Namespace string `json:"namespace"`
  1309. VolumeName string `json:"volumeName"`
  1310. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  1311. Values []*Vector `json:"values"`
  1312. }
  1313. func getCost(qr interface{}) (map[string][]*Vector, error) {
  1314. toReturn := make(map[string][]*Vector)
  1315. for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
  1316. metricInterface, ok := val.(map[string]interface{})["metric"]
  1317. if !ok {
  1318. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1319. }
  1320. metricMap, ok := metricInterface.(map[string]interface{})
  1321. if !ok {
  1322. return nil, fmt.Errorf("Metric field is improperly formatted")
  1323. }
  1324. instance, ok := metricMap["instance"]
  1325. if !ok {
  1326. return nil, fmt.Errorf("Instance field does not exist in data result vector")
  1327. }
  1328. instanceStr, ok := instance.(string)
  1329. if !ok {
  1330. return nil, fmt.Errorf("Instance is improperly formatted")
  1331. }
  1332. dataPoint, ok := val.(map[string]interface{})["value"]
  1333. if !ok {
  1334. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1335. }
  1336. value, ok := dataPoint.([]interface{})
  1337. if !ok || len(value) != 2 {
  1338. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1339. }
  1340. var vectors []*Vector
  1341. strVal := value[1].(string)
  1342. v, _ := strconv.ParseFloat(strVal, 64)
  1343. vectors = append(vectors, &Vector{
  1344. Timestamp: value[0].(float64),
  1345. Value: v,
  1346. })
  1347. toReturn[instanceStr] = vectors
  1348. }
  1349. return toReturn, nil
  1350. }
  1351. func getPVInfoVectors(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1352. pvmap := make(map[string]*PersistentVolumeClaimData)
  1353. data, ok := qr.(map[string]interface{})["data"]
  1354. if !ok {
  1355. e, err := wrapPrometheusError(qr)
  1356. if err != nil {
  1357. return nil, err
  1358. }
  1359. return nil, fmt.Errorf(e)
  1360. }
  1361. d, ok := data.(map[string]interface{})
  1362. if !ok {
  1363. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1364. }
  1365. result, ok := d["result"]
  1366. if !ok {
  1367. return nil, fmt.Errorf("Result field not present in prometheus response")
  1368. }
  1369. results, ok := result.([]interface{})
  1370. if !ok {
  1371. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1372. }
  1373. for _, val := range results {
  1374. metricInterface, ok := val.(map[string]interface{})["metric"]
  1375. if !ok {
  1376. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1377. }
  1378. metricMap, ok := metricInterface.(map[string]interface{})
  1379. if !ok {
  1380. return nil, fmt.Errorf("Metric field is improperly formatted")
  1381. }
  1382. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1383. if !ok {
  1384. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1385. }
  1386. pvclaimStr, ok := pvclaim.(string)
  1387. if !ok {
  1388. return nil, fmt.Errorf("Claim field improperly formatted")
  1389. }
  1390. pvnamespace, ok := metricMap["namespace"]
  1391. if !ok {
  1392. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1393. }
  1394. pvnamespaceStr, ok := pvnamespace.(string)
  1395. if !ok {
  1396. return nil, fmt.Errorf("Namespace field improperly formatted")
  1397. }
  1398. pv, ok := metricMap["volumename"]
  1399. if !ok {
  1400. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1401. pv = ""
  1402. }
  1403. pvStr, ok := pv.(string)
  1404. if !ok {
  1405. return nil, fmt.Errorf("Volumename field improperly formatted")
  1406. }
  1407. pvclass, ok := metricMap["storageclass"]
  1408. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1409. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1410. pvclass = ""
  1411. }
  1412. pvclassStr, ok := pvclass.(string)
  1413. if !ok {
  1414. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1415. }
  1416. values, ok := val.(map[string]interface{})["values"].([]interface{})
  1417. if !ok {
  1418. return nil, fmt.Errorf("Values field is improperly formatted")
  1419. }
  1420. var vectors []*Vector
  1421. for _, value := range values {
  1422. dataPoint, ok := value.([]interface{})
  1423. if !ok || len(dataPoint) != 2 {
  1424. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1425. }
  1426. strVal := dataPoint[1].(string)
  1427. v, _ := strconv.ParseFloat(strVal, 64)
  1428. vectors = append(vectors, &Vector{
  1429. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1430. Value: v,
  1431. })
  1432. }
  1433. key := pvnamespaceStr + "," + pvclaimStr
  1434. pvmap[key] = &PersistentVolumeClaimData{
  1435. Class: pvclassStr,
  1436. Claim: pvclaimStr,
  1437. Namespace: pvnamespaceStr,
  1438. VolumeName: pvStr,
  1439. Values: vectors,
  1440. }
  1441. }
  1442. return pvmap, nil
  1443. }
  1444. func getPVInfoVector(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1445. pvmap := make(map[string]*PersistentVolumeClaimData)
  1446. data, ok := qr.(map[string]interface{})["data"]
  1447. if !ok {
  1448. e, err := wrapPrometheusError(qr)
  1449. if err != nil {
  1450. return nil, err
  1451. }
  1452. return nil, fmt.Errorf(e)
  1453. }
  1454. d, ok := data.(map[string]interface{})
  1455. if !ok {
  1456. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1457. }
  1458. result, ok := d["result"]
  1459. if !ok {
  1460. return nil, fmt.Errorf("Result field not present in prometheus response")
  1461. }
  1462. results, ok := result.([]interface{})
  1463. if !ok {
  1464. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1465. }
  1466. for _, val := range results {
  1467. metricInterface, ok := val.(map[string]interface{})["metric"]
  1468. if !ok {
  1469. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1470. }
  1471. metricMap, ok := metricInterface.(map[string]interface{})
  1472. if !ok {
  1473. return nil, fmt.Errorf("Metric field is improperly formatted")
  1474. }
  1475. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1476. if !ok {
  1477. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1478. }
  1479. pvclaimStr, ok := pvclaim.(string)
  1480. if !ok {
  1481. return nil, fmt.Errorf("Claim field improperly formatted")
  1482. }
  1483. pvnamespace, ok := metricMap["namespace"]
  1484. if !ok {
  1485. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1486. }
  1487. pvnamespaceStr, ok := pvnamespace.(string)
  1488. if !ok {
  1489. return nil, fmt.Errorf("Namespace field improperly formatted")
  1490. }
  1491. pv, ok := metricMap["volumename"]
  1492. if !ok {
  1493. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1494. pv = ""
  1495. }
  1496. pvStr, ok := pv.(string)
  1497. if !ok {
  1498. return nil, fmt.Errorf("Volumename field improperly formatted")
  1499. }
  1500. pvclass, ok := metricMap["storageclass"]
  1501. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1502. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1503. pvclass = ""
  1504. }
  1505. pvclassStr, ok := pvclass.(string)
  1506. if !ok {
  1507. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1508. }
  1509. dataPoint, ok := val.(map[string]interface{})["value"]
  1510. if !ok {
  1511. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1512. }
  1513. value, ok := dataPoint.([]interface{})
  1514. if !ok || len(value) != 2 {
  1515. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1516. }
  1517. var vectors []*Vector
  1518. strVal := value[1].(string)
  1519. v, _ := strconv.ParseFloat(strVal, 64)
  1520. vectors = append(vectors, &Vector{
  1521. Timestamp: value[0].(float64),
  1522. Value: v,
  1523. })
  1524. key := pvnamespaceStr + "," + pvclaimStr
  1525. pvmap[key] = &PersistentVolumeClaimData{
  1526. Class: pvclassStr,
  1527. Claim: pvclaimStr,
  1528. Namespace: pvnamespaceStr,
  1529. VolumeName: pvStr,
  1530. Values: vectors,
  1531. }
  1532. }
  1533. return pvmap, nil
  1534. }
  1535. func QueryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
  1536. u := cli.URL(epQueryRange, nil)
  1537. q := u.Query()
  1538. q.Set("query", query)
  1539. q.Set("start", start.Format(time.RFC3339Nano))
  1540. q.Set("end", end.Format(time.RFC3339Nano))
  1541. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  1542. u.RawQuery = q.Encode()
  1543. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  1544. if err != nil {
  1545. return nil, err
  1546. }
  1547. _, body, err := cli.Do(context.Background(), req)
  1548. if err != nil {
  1549. klog.V(1).Infof("ERROR" + err.Error())
  1550. }
  1551. if err != nil {
  1552. return nil, err
  1553. }
  1554. var toReturn interface{}
  1555. err = json.Unmarshal(body, &toReturn)
  1556. if err != nil {
  1557. klog.V(1).Infof("ERROR" + err.Error())
  1558. }
  1559. return toReturn, err
  1560. }
  1561. func query(cli prometheusClient.Client, query string) (interface{}, error) {
  1562. u := cli.URL(epQuery, nil)
  1563. q := u.Query()
  1564. q.Set("query", query)
  1565. u.RawQuery = q.Encode()
  1566. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  1567. if err != nil {
  1568. return nil, err
  1569. }
  1570. _, body, err := cli.Do(context.Background(), req)
  1571. if err != nil {
  1572. return nil, err
  1573. }
  1574. var toReturn interface{}
  1575. err = json.Unmarshal(body, &toReturn)
  1576. if err != nil {
  1577. klog.V(1).Infof("ERROR" + err.Error())
  1578. }
  1579. return toReturn, err
  1580. }
  1581. //todo: don't cast, implement unmarshaler interface
  1582. func getNormalization(qr interface{}) (float64, error) {
  1583. data, ok := qr.(map[string]interface{})["data"]
  1584. if !ok {
  1585. e, err := wrapPrometheusError(qr)
  1586. if err != nil {
  1587. return 0, err
  1588. }
  1589. return 0, fmt.Errorf(e)
  1590. }
  1591. results, ok := data.(map[string]interface{})["result"].([]interface{})
  1592. if !ok {
  1593. return 0, fmt.Errorf("Result field not found in normalization response, aborting")
  1594. }
  1595. if len(results) > 0 {
  1596. dataPoint := results[0].(map[string]interface{})["value"].([]interface{})
  1597. if len(dataPoint) == 2 {
  1598. strNorm := dataPoint[1].(string)
  1599. val, _ := strconv.ParseFloat(strNorm, 64)
  1600. return val, nil
  1601. }
  1602. return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1603. }
  1604. return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
  1605. }
  1606. type ContainerMetric struct {
  1607. Namespace string
  1608. PodName string
  1609. ContainerName string
  1610. NodeName string
  1611. }
  1612. func (c *ContainerMetric) Key() string {
  1613. return c.Namespace + "," + c.PodName + "," + c.ContainerName + "," + c.NodeName
  1614. }
  1615. func NewContainerMetricFromKey(key string) (*ContainerMetric, error) {
  1616. s := strings.Split(key, ",")
  1617. if len(s) == 4 {
  1618. return &ContainerMetric{
  1619. Namespace: s[0],
  1620. PodName: s[1],
  1621. ContainerName: s[2],
  1622. NodeName: s[3],
  1623. }, nil
  1624. }
  1625. return nil, fmt.Errorf("Not a valid key")
  1626. }
  1627. func newContainerMetricFromValues(ns string, podName string, containerName string, nodeName string) *ContainerMetric {
  1628. return &ContainerMetric{
  1629. Namespace: ns,
  1630. PodName: podName,
  1631. ContainerName: containerName,
  1632. NodeName: nodeName,
  1633. }
  1634. }
  1635. func newContainerMetricsFromPod(pod v1.Pod) ([]*ContainerMetric, error) {
  1636. podName := pod.GetObjectMeta().GetName()
  1637. ns := pod.GetObjectMeta().GetNamespace()
  1638. node := pod.Spec.NodeName
  1639. var cs []*ContainerMetric
  1640. for _, container := range pod.Spec.Containers {
  1641. containerName := container.Name
  1642. cs = append(cs, &ContainerMetric{
  1643. Namespace: ns,
  1644. PodName: podName,
  1645. ContainerName: containerName,
  1646. NodeName: node,
  1647. })
  1648. }
  1649. return cs, nil
  1650. }
  1651. func newContainerMetricFromPrometheus(metrics map[string]interface{}) (*ContainerMetric, error) {
  1652. cName, ok := metrics["container_name"]
  1653. if !ok {
  1654. return nil, fmt.Errorf("Prometheus vector does not have container name")
  1655. }
  1656. containerName, ok := cName.(string)
  1657. if !ok {
  1658. return nil, fmt.Errorf("Prometheus vector does not have string container name")
  1659. }
  1660. pName, ok := metrics["pod_name"]
  1661. if !ok {
  1662. return nil, fmt.Errorf("Prometheus vector does not have pod name")
  1663. }
  1664. podName, ok := pName.(string)
  1665. if !ok {
  1666. return nil, fmt.Errorf("Prometheus vector does not have string pod name")
  1667. }
  1668. ns, ok := metrics["namespace"]
  1669. if !ok {
  1670. return nil, fmt.Errorf("Prometheus vector does not have namespace")
  1671. }
  1672. namespace, ok := ns.(string)
  1673. if !ok {
  1674. return nil, fmt.Errorf("Prometheus vector does not have string namespace")
  1675. }
  1676. node, ok := metrics["node"]
  1677. if !ok {
  1678. klog.V(4).Info("Prometheus vector does not have node name")
  1679. node = ""
  1680. }
  1681. nodeName, ok := node.(string)
  1682. if !ok {
  1683. return nil, fmt.Errorf("Prometheus vector does not have string node")
  1684. }
  1685. return &ContainerMetric{
  1686. ContainerName: containerName,
  1687. PodName: podName,
  1688. Namespace: namespace,
  1689. NodeName: nodeName,
  1690. }, nil
  1691. }
  1692. func getContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1693. data, ok := qr.(map[string]interface{})["data"]
  1694. if !ok {
  1695. e, err := wrapPrometheusError(qr)
  1696. if err != nil {
  1697. return nil, err
  1698. }
  1699. return nil, fmt.Errorf(e)
  1700. }
  1701. r, ok := data.(map[string]interface{})["result"]
  1702. if !ok {
  1703. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1704. }
  1705. results, ok := r.([]interface{})
  1706. if !ok {
  1707. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1708. }
  1709. containerData := make(map[string][]*Vector)
  1710. for _, val := range results {
  1711. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1712. if !ok {
  1713. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1714. }
  1715. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1716. if err != nil {
  1717. return nil, err
  1718. }
  1719. value, ok := val.(map[string]interface{})["value"]
  1720. if !ok {
  1721. return nil, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  1722. }
  1723. dataPoint, ok := value.([]interface{})
  1724. if !ok || len(dataPoint) != 2 {
  1725. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1726. }
  1727. strVal := dataPoint[1].(string)
  1728. v, _ := strconv.ParseFloat(strVal, 64)
  1729. if normalize && normalizationValue != 0 {
  1730. v = v / normalizationValue
  1731. }
  1732. toReturn := &Vector{
  1733. Timestamp: dataPoint[0].(float64),
  1734. Value: v,
  1735. }
  1736. klog.V(4).Info("key: " + containerMetric.Key())
  1737. containerData[containerMetric.Key()] = []*Vector{toReturn}
  1738. }
  1739. return containerData, nil
  1740. }
  1741. func GetContainerMetricVectors(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1742. data, ok := qr.(map[string]interface{})["data"]
  1743. if !ok {
  1744. e, err := wrapPrometheusError(qr)
  1745. if err != nil {
  1746. return nil, err
  1747. }
  1748. return nil, fmt.Errorf(e)
  1749. }
  1750. r, ok := data.(map[string]interface{})["result"]
  1751. if !ok {
  1752. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1753. }
  1754. results, ok := r.([]interface{})
  1755. if !ok {
  1756. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1757. }
  1758. containerData := make(map[string][]*Vector)
  1759. for _, val := range results {
  1760. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1761. if !ok {
  1762. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1763. }
  1764. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1765. if err != nil {
  1766. return nil, err
  1767. }
  1768. vs, ok := val.(map[string]interface{})["values"]
  1769. if !ok {
  1770. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a field in the vector")
  1771. }
  1772. values, ok := vs.([]interface{})
  1773. if !ok {
  1774. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a slice")
  1775. }
  1776. var vectors []*Vector
  1777. for _, value := range values {
  1778. dataPoint, ok := value.([]interface{})
  1779. if !ok || len(dataPoint) != 2 {
  1780. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1781. }
  1782. strVal := dataPoint[1].(string)
  1783. v, _ := strconv.ParseFloat(strVal, 64)
  1784. if normalize && normalizationValue != 0 {
  1785. v = v / normalizationValue
  1786. }
  1787. vectors = append(vectors, &Vector{
  1788. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1789. Value: v,
  1790. })
  1791. }
  1792. containerData[containerMetric.Key()] = vectors
  1793. }
  1794. return containerData, nil
  1795. }
  1796. func wrapPrometheusError(qr interface{}) (string, error) {
  1797. e, ok := qr.(map[string]interface{})["error"]
  1798. if !ok {
  1799. return "", fmt.Errorf("Unexpected response from Prometheus")
  1800. }
  1801. eStr, ok := e.(string)
  1802. return eStr, nil
  1803. }