costmodel.go 51 KB

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