allocation.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/kubecost/cost-model/pkg/env"
  6. "github.com/kubecost/cost-model/pkg/kubecost"
  7. "github.com/kubecost/cost-model/pkg/log"
  8. "github.com/kubecost/cost-model/pkg/prom"
  9. "github.com/kubecost/cost-model/pkg/thanos"
  10. "k8s.io/apimachinery/pkg/labels"
  11. )
  12. const (
  13. queryFmtMinutes = `avg(kube_pod_container_status_running{}) by (container, pod, namespace, cluster_id)[%s:%s]%s`
  14. queryFmtRAMBytesAllocated = `avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  15. queryFmtRAMRequests = `avg(avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  16. queryFmtRAMUsage = `avg(avg_over_time(container_memory_working_set_bytes{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`
  17. queryFmtCPUCoresAllocated = `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  18. queryFmtCPURequests = `avg(avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  19. queryFmtCPUUsage = `avg(rate(container_cpu_usage_seconds_total{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`
  20. queryFmtGPUsRequested = `avg(avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  21. queryFmtNodeCostPerCPUHr = `avg(avg_over_time(node_cpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`
  22. queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`
  23. queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`
  24. queryFmtNodeIsSpot = `avg_over_time(kubecost_node_is_spot[%s]%s)`
  25. queryFmtPVCInfo = `avg(kube_persistentvolumeclaim_info{volumename != ""}) by (persistentvolumeclaim, storageclass, volumename, namespace, cluster_id)[%s:%s]%s`
  26. queryFmtPVBytes = `avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s]%s)) by (persistentvolume, cluster_id)`
  27. queryFmtPodPVCAllocation = `avg(avg_over_time(pod_pvc_allocation[%s]%s)) by (persistentvolume, persistentvolumeclaim, pod, namespace, cluster_id)`
  28. queryFmtPVCBytesRequested = `avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{}[%s]%s)) by (persistentvolumeclaim, namespace, cluster_id)`
  29. queryFmtPVCostPerGiBHour = `avg(avg_over_time(pv_hourly_cost[%s]%s)) by (volumename, cluster_id)`
  30. queryFmtNetZoneGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`
  31. queryFmtNetZoneCostPerGiB = `avg(avg_over_time(kubecost_network_zone_egress_cost{}[%s]%s)) by (cluster_id)`
  32. queryFmtNetRegionGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`
  33. queryFmtNetRegionCostPerGiB = `avg(avg_over_time(kubecost_network_region_egress_cost{}[%s]%s)) by (cluster_id)`
  34. queryFmtNetInternetGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`
  35. queryFmtNetInternetCostPerGiB = `avg(avg_over_time(kubecost_network_internet_egress_cost{}[%s]%s)) by (cluster_id)`
  36. queryFmtNamespaceLabels = `avg_over_time(kube_namespace_labels[%s]%s)`
  37. queryFmtNamespaceAnnotations = `avg_over_time(kube_namespace_annotations[%s]%s)`
  38. queryFmtPodLabels = `avg_over_time(kube_pod_labels[%s]%s)`
  39. queryFmtPodAnnotations = `avg_over_time(kube_pod_annotations[%s]%s)`
  40. queryFmtServiceLabels = `avg_over_time(service_selector_labels[%s]%s)`
  41. queryFmtDeploymentLabels = `avg_over_time(deployment_match_labels[%s]%s)`
  42. queryFmtStatefulSetLabels = `avg_over_time(statefulSet_match_labels[%s]%s)`
  43. queryFmtDaemonSetLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet"}[%s]%s)) by (pod, owner_name, namespace, cluster_id)`
  44. queryFmtJobLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="Job"}[%s]%s)) by (pod, owner_name, namespace ,cluster_id)`
  45. )
  46. // TODO niko/computeallocation idle minutes = 1?
  47. // ComputeAllocation uses the CostModel instance to compute an AllocationSet
  48. // for the window defined by the given start and end times. The Allocations
  49. // returned are unaggregated (i.e. down to the container level).
  50. func (cm *CostModel) ComputeAllocation(start, end time.Time) (*kubecost.AllocationSet, error) {
  51. // Create a window spanning the requested query
  52. s, e := start, end
  53. window := kubecost.NewWindow(&s, &e)
  54. // Create an empty AllocationSet. For safety, in the case of an error, we
  55. // should prefer to return this empty set with the error. (In the case of
  56. // no error, of course we populate the set and return it.)
  57. allocSet := kubecost.NewAllocationSet(start, end)
  58. // Convert window (start, end) to (duration, offset) for querying Prometheus
  59. timesToDurations := func(s, e time.Time) (dur, off time.Duration) {
  60. now := time.Now()
  61. off = now.Sub(e)
  62. dur = e.Sub(s)
  63. return dur, off
  64. }
  65. duration, offset := timesToDurations(start, end)
  66. // If using Thanos, increase offset to 3 hours, reducing the duration by
  67. // equal measure to maintain the same starting point.
  68. thanosDur := thanos.OffsetDuration()
  69. if offset < thanosDur && env.IsThanosEnabled() {
  70. diff := thanosDur - offset
  71. offset += diff
  72. duration -= diff
  73. }
  74. // If duration < 0, return an empty set
  75. if duration < 0 {
  76. return allocSet, nil
  77. }
  78. // Negative offset means that the end time is in the future. Prometheus
  79. // fails for non-positive offset values, so shrink the duration and
  80. // remove the offset altogether.
  81. if offset < 0 {
  82. duration = duration + offset
  83. offset = 0
  84. }
  85. durStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  86. offStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  87. if offset < time.Minute {
  88. offStr = ""
  89. }
  90. // TODO niko/computeallocation dynamic resolution? add to ComputeAllocation() in allocation.Source?
  91. resStr := "1m"
  92. // resPerHr := 60
  93. startQuerying := time.Now()
  94. ctx := prom.NewContext(cm.PrometheusClient)
  95. // TODO niko/computeallocation split into required and optional queries?
  96. queryMinutes := fmt.Sprintf(queryFmtMinutes, durStr, resStr, offStr)
  97. resChMinutes := ctx.Query(queryMinutes)
  98. queryRAMBytesAllocated := fmt.Sprintf(queryFmtRAMBytesAllocated, durStr, offStr)
  99. resChRAMBytesAllocated := ctx.Query(queryRAMBytesAllocated)
  100. queryRAMRequests := fmt.Sprintf(queryFmtRAMRequests, durStr, offStr)
  101. resChRAMRequests := ctx.Query(queryRAMRequests)
  102. queryRAMUsage := fmt.Sprintf(queryFmtRAMUsage, durStr, offStr)
  103. resChRAMUsage := ctx.Query(queryRAMUsage)
  104. queryCPUCoresAllocated := fmt.Sprintf(queryFmtCPUCoresAllocated, durStr, offStr)
  105. resChCPUCoresAllocated := ctx.Query(queryCPUCoresAllocated)
  106. queryCPURequests := fmt.Sprintf(queryFmtCPURequests, durStr, offStr)
  107. resChCPURequests := ctx.Query(queryCPURequests)
  108. queryCPUUsage := fmt.Sprintf(queryFmtCPUUsage, durStr, offStr)
  109. resChCPUUsage := ctx.Query(queryCPUUsage)
  110. queryGPUsRequested := fmt.Sprintf(queryFmtGPUsRequested, durStr, offStr)
  111. resChGPUsRequested := ctx.Query(queryGPUsRequested)
  112. queryNodeCostPerCPUHr := fmt.Sprintf(queryFmtNodeCostPerCPUHr, durStr, offStr)
  113. resChNodeCostPerCPUHr := ctx.Query(queryNodeCostPerCPUHr)
  114. queryNodeCostPerRAMGiBHr := fmt.Sprintf(queryFmtNodeCostPerRAMGiBHr, durStr, offStr)
  115. resChNodeCostPerRAMGiBHr := ctx.Query(queryNodeCostPerRAMGiBHr)
  116. queryNodeCostPerGPUHr := fmt.Sprintf(queryFmtNodeCostPerGPUHr, durStr, offStr)
  117. resChNodeCostPerGPUHr := ctx.Query(queryNodeCostPerGPUHr)
  118. queryNodeIsSpot := fmt.Sprintf(queryFmtNodeIsSpot, durStr, offStr)
  119. resChNodeIsSpot := ctx.Query(queryNodeIsSpot)
  120. queryPVCInfo := fmt.Sprintf(queryFmtPVCInfo, durStr, resStr, offStr)
  121. resChPVCInfo := ctx.Query(queryPVCInfo)
  122. queryPVBytes := fmt.Sprintf(queryFmtPVBytes, durStr, offStr)
  123. resChPVBytes := ctx.Query(queryPVBytes)
  124. queryPodPVCAllocation := fmt.Sprintf(queryFmtPodPVCAllocation, durStr, offStr)
  125. resChPodPVCAllocation := ctx.Query(queryPodPVCAllocation)
  126. queryPVCBytesRequested := fmt.Sprintf(queryFmtPVCBytesRequested, durStr, offStr)
  127. resChPVCBytesRequested := ctx.Query(queryPVCBytesRequested)
  128. queryPVCostPerGiBHour := fmt.Sprintf(queryFmtPVCostPerGiBHour, durStr, offStr)
  129. resChPVCostPerGiBHour := ctx.Query(queryPVCostPerGiBHour)
  130. queryNetZoneGiB := fmt.Sprintf(queryFmtNetZoneGiB, durStr, offStr)
  131. resChNetZoneGiB := ctx.Query(queryNetZoneGiB)
  132. queryNetZoneCostPerGiB := fmt.Sprintf(queryFmtNetZoneCostPerGiB, durStr, offStr)
  133. resChNetZoneCostPerGiB := ctx.Query(queryNetZoneCostPerGiB)
  134. queryNetRegionGiB := fmt.Sprintf(queryFmtNetRegionGiB, durStr, offStr)
  135. resChNetRegionGiB := ctx.Query(queryNetRegionGiB)
  136. queryNetRegionCostPerGiB := fmt.Sprintf(queryFmtNetRegionCostPerGiB, durStr, offStr)
  137. resChNetRegionCostPerGiB := ctx.Query(queryNetRegionCostPerGiB)
  138. queryNetInternetGiB := fmt.Sprintf(queryFmtNetInternetGiB, durStr, offStr)
  139. resChNetInternetGiB := ctx.Query(queryNetInternetGiB)
  140. queryNetInternetCostPerGiB := fmt.Sprintf(queryFmtNetInternetCostPerGiB, durStr, offStr)
  141. resChNetInternetCostPerGiB := ctx.Query(queryNetInternetCostPerGiB)
  142. queryNamespaceLabels := fmt.Sprintf(queryFmtNamespaceLabels, durStr, offStr)
  143. resChNamespaceLabels := ctx.Query(queryNamespaceLabels)
  144. queryNamespaceAnnotations := fmt.Sprintf(queryFmtNamespaceAnnotations, durStr, offStr)
  145. resChNamespaceAnnotations := ctx.Query(queryNamespaceAnnotations)
  146. queryPodLabels := fmt.Sprintf(queryFmtPodLabels, durStr, offStr)
  147. resChPodLabels := ctx.Query(queryPodLabels)
  148. queryPodAnnotations := fmt.Sprintf(queryFmtPodAnnotations, durStr, offStr)
  149. resChPodAnnotations := ctx.Query(queryPodAnnotations)
  150. queryServiceLabels := fmt.Sprintf(queryFmtServiceLabels, durStr, offStr)
  151. resChServiceLabels := ctx.Query(queryServiceLabels)
  152. queryDeploymentLabels := fmt.Sprintf(queryFmtDeploymentLabels, durStr, offStr)
  153. resChDeploymentLabels := ctx.Query(queryDeploymentLabels)
  154. queryStatefulSetLabels := fmt.Sprintf(queryFmtStatefulSetLabels, durStr, offStr)
  155. resChStatefulSetLabels := ctx.Query(queryStatefulSetLabels)
  156. queryDaemonSetLabels := fmt.Sprintf(queryFmtDaemonSetLabels, durStr, offStr)
  157. resChDaemonSetLabels := ctx.Query(queryDaemonSetLabels)
  158. queryJobLabels := fmt.Sprintf(queryFmtJobLabels, durStr, offStr)
  159. resChJobLabels := ctx.Query(queryJobLabels)
  160. resMinutes, _ := resChMinutes.Await()
  161. resCPUCoresAllocated, _ := resChCPUCoresAllocated.Await()
  162. resCPURequests, _ := resChCPURequests.Await()
  163. resCPUUsage, _ := resChCPUUsage.Await()
  164. resRAMBytesAllocated, _ := resChRAMBytesAllocated.Await()
  165. resRAMRequests, _ := resChRAMRequests.Await()
  166. resRAMUsage, _ := resChRAMUsage.Await()
  167. resGPUsRequested, _ := resChGPUsRequested.Await()
  168. resNodeCostPerCPUHr, _ := resChNodeCostPerCPUHr.Await()
  169. resNodeCostPerRAMGiBHr, _ := resChNodeCostPerRAMGiBHr.Await()
  170. resNodeCostPerGPUHr, _ := resChNodeCostPerGPUHr.Await()
  171. resNodeIsSpot, _ := resChNodeIsSpot.Await()
  172. resPVBytes, _ := resChPVBytes.Await()
  173. resPVCostPerGiBHour, _ := resChPVCostPerGiBHour.Await()
  174. resPVCInfo, _ := resChPVCInfo.Await()
  175. resPVCBytesRequested, _ := resChPVCBytesRequested.Await()
  176. resPodPVCAllocation, _ := resChPodPVCAllocation.Await()
  177. resNetZoneGiB, _ := resChNetZoneGiB.Await()
  178. resNetZoneCostPerGiB, _ := resChNetZoneCostPerGiB.Await()
  179. resNetRegionGiB, _ := resChNetRegionGiB.Await()
  180. resNetRegionCostPerGiB, _ := resChNetRegionCostPerGiB.Await()
  181. resNetInternetGiB, _ := resChNetInternetGiB.Await()
  182. resNetInternetCostPerGiB, _ := resChNetInternetCostPerGiB.Await()
  183. resNamespaceLabels, _ := resChNamespaceLabels.Await()
  184. resNamespaceAnnotations, _ := resChNamespaceAnnotations.Await()
  185. resPodLabels, _ := resChPodLabels.Await()
  186. resPodAnnotations, _ := resChPodAnnotations.Await()
  187. resServiceLabels, _ := resChServiceLabels.Await()
  188. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  189. resStatefulSetLabels, _ := resChStatefulSetLabels.Await()
  190. resDaemonSetLabels, _ := resChDaemonSetLabels.Await()
  191. resJobLabels, _ := resChJobLabels.Await()
  192. log.Profile(startQuerying, "CostModel.ComputeAllocation: queries complete")
  193. defer log.Profile(time.Now(), "CostModel.ComputeAllocation: processing complete")
  194. // Build out a map of Allocations, starting with (start, end) so that we
  195. // begin with minutes, from which we compute resource allocation and cost
  196. // totals from measured rate data.
  197. allocationMap := map[containerKey]*kubecost.Allocation{}
  198. // Keep track of the allocations per pod, for the sake of splitting PVC and
  199. // Network allocation into per-Allocation from per-Pod.
  200. podAllocation := map[podKey][]*kubecost.Allocation{}
  201. // clusterStarts and clusterEnds record the earliest start and latest end
  202. // times, respectively, on a cluster-basis. These are used for unmounted
  203. // PVs and other "virtual" Allocations so that minutes are maximally
  204. // accurate during start-up or spin-down of a cluster
  205. clusterStart := map[string]time.Time{}
  206. clusterEnd := map[string]time.Time{}
  207. buildAllocationMap(window, allocationMap, podAllocation, clusterStart, clusterEnd, resMinutes)
  208. applyCPUCoresAllocated(allocationMap, resCPUCoresAllocated)
  209. applyCPUCoresRequested(allocationMap, resCPURequests)
  210. applyCPUCoresUsed(allocationMap, resCPUUsage)
  211. applyRAMBytesAllocated(allocationMap, resRAMBytesAllocated)
  212. applyRAMBytesRequested(allocationMap, resRAMRequests)
  213. applyRAMBytesUsed(allocationMap, resRAMUsage)
  214. applyGPUsRequested(allocationMap, resGPUsRequested)
  215. applyNetworkAllocation(allocationMap, podAllocation, resNetZoneGiB, resNetZoneCostPerGiB)
  216. applyNetworkAllocation(allocationMap, podAllocation, resNetRegionGiB, resNetRegionCostPerGiB)
  217. applyNetworkAllocation(allocationMap, podAllocation, resNetInternetGiB, resNetInternetCostPerGiB)
  218. // TODO niko/computeallocation pruneDuplicateData? (see costmodel.go)
  219. namespaceLabels := resToNamespaceLabels(resNamespaceLabels)
  220. podLabels := resToPodLabels(resPodLabels)
  221. namespaceAnnotations := resToNamespaceAnnotations(resNamespaceAnnotations)
  222. podAnnotations := resToPodAnnotations(resPodAnnotations)
  223. applyLabels(allocationMap, namespaceLabels, podLabels)
  224. applyAnnotations(allocationMap, namespaceAnnotations, podAnnotations)
  225. serviceLabels := getServiceLabels(resServiceLabels)
  226. applyServicesToPods(allocationMap, podLabels, serviceLabels)
  227. podDeploymentMap := labelsToPodControllerMap(podLabels, resToDeploymentLabels(resDeploymentLabels))
  228. podStatefulSetMap := labelsToPodControllerMap(podLabels, resToStatefulSetLabels(resStatefulSetLabels))
  229. podDaemonSetMap := resToPodDaemonSetMap(resDaemonSetLabels)
  230. podJobMap := resToPodJobMap(resJobLabels)
  231. applyControllersToPods(allocationMap, podDeploymentMap)
  232. applyControllersToPods(allocationMap, podStatefulSetMap)
  233. applyControllersToPods(allocationMap, podDaemonSetMap)
  234. applyControllersToPods(allocationMap, podJobMap)
  235. // TODO breakdown network costs?
  236. // Build out a map of Nodes with resource costs, discounts, and node types
  237. // for converting resource allocation data to cumulative costs.
  238. nodeMap := map[nodeKey]*Node{}
  239. applyNodeCostPerCPUHr(nodeMap, resNodeCostPerCPUHr)
  240. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr)
  241. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr)
  242. applyNodeSpot(nodeMap, resNodeIsSpot)
  243. applyNodeDiscount(nodeMap, cm)
  244. // Build out the map of all PVs with class, size and cost-per-hour.
  245. // Note: this does not record time running, which we may want to
  246. // include later for increased PV precision. (As long as the PV has
  247. // a PVC, we get time running there, so this is only inaccurate
  248. // for short-lived, unmounted PVs.)
  249. pvMap := map[pvKey]*PV{}
  250. buildPVMap(pvMap, resPVCostPerGiBHour)
  251. applyPVBytes(pvMap, resPVBytes)
  252. // Build out the map of all PVCs with time running, bytes requested,
  253. // and connect to the correct PV from pvMap. (If no PV exists, that
  254. // is noted, but does not result in any allocation/cost.)
  255. pvcMap := map[pvcKey]*PVC{}
  256. buildPVCMap(window, pvcMap, pvMap, resPVCInfo)
  257. applyPVCBytesRequested(pvcMap, resPVCBytesRequested)
  258. // Build out the relationships of pods to their PVCs. This step
  259. // populates the PVC.Count field so that PVC allocation can be
  260. // split appropriately among each pod's container allocation.
  261. podPVCMap := map[podKey][]*PVC{}
  262. buildPodPVCMap(podPVCMap, pvMap, pvcMap, podAllocation, resPodPVCAllocation)
  263. // Identify unmounted PVs (PVs without PVCs) and add one Allocation per
  264. // cluster representing each cluster's unmounted PVs (if necessary).
  265. applyUnmountedPVs(window, allocationMap, pvMap, pvcMap)
  266. for _, alloc := range allocationMap {
  267. cluster, _ := alloc.Properties.GetCluster()
  268. node, _ := alloc.Properties.GetNode()
  269. namespace, _ := alloc.Properties.GetNamespace()
  270. pod, _ := alloc.Properties.GetPod()
  271. container, _ := alloc.Properties.GetContainer()
  272. podKey := newPodKey(cluster, namespace, pod)
  273. nodeKey := newNodeKey(cluster, node)
  274. if n, ok := nodeMap[nodeKey]; !ok {
  275. if pod != kubecost.UnmountedSuffix {
  276. log.Warningf("CostModel.ComputeAllocation: failed to find node %s for %s", nodeKey, alloc.Name)
  277. }
  278. } else {
  279. alloc.CPUCost = alloc.CPUCoreHours * n.CostPerCPUHr
  280. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * n.CostPerRAMGiBHr
  281. alloc.GPUCost = alloc.GPUHours * n.CostPerGPUHr
  282. }
  283. if pvcs, ok := podPVCMap[podKey]; ok {
  284. for _, pvc := range pvcs {
  285. // Determine the (start, end) of the relationship between the
  286. // given PVC and the associated Allocation so that a precise
  287. // number of hours can be used to compute cumulative cost.
  288. s, e := alloc.Start, alloc.End
  289. if pvc.Start.After(alloc.Start) {
  290. s = pvc.Start
  291. }
  292. if pvc.End.Before(alloc.End) {
  293. e = pvc.End
  294. }
  295. minutes := e.Sub(s).Minutes()
  296. hrs := minutes / 60.0
  297. count := float64(pvc.Count)
  298. if pvc.Count < 1 {
  299. count = 1
  300. }
  301. gib := pvc.Bytes / 1024 / 1024 / 1024
  302. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  303. // Apply the size and cost of the PV to the allocation, each
  304. // weighted by count (i.e. the number of containers in the pod)
  305. alloc.PVByteHours += pvc.Bytes * hrs / count
  306. alloc.PVCost += cost / count
  307. }
  308. }
  309. alloc.TotalCost = 0.0
  310. alloc.TotalCost += alloc.CPUCost
  311. alloc.TotalCost += alloc.RAMCost
  312. alloc.TotalCost += alloc.GPUCost
  313. alloc.TotalCost += alloc.PVCost
  314. alloc.TotalCost += alloc.NetworkCost
  315. alloc.TotalCost += alloc.SharedCost
  316. alloc.TotalCost += alloc.ExternalCost
  317. // Make sure that the name is correct (node may not be present at this
  318. // point due to it missing from queryMinutes) then insert.
  319. alloc.Name = fmt.Sprintf("%s/%s/%s/%s/%s", cluster, node, namespace, pod, container)
  320. allocSet.Set(alloc)
  321. }
  322. return allocSet, nil
  323. }
  324. func buildAllocationMap(window kubecost.Window, allocationMap map[containerKey]*kubecost.Allocation, podAllocation map[podKey][]*kubecost.Allocation, clusterStart, clusterEnd map[string]time.Time, resMinutes []*prom.QueryResult) {
  325. for _, res := range resMinutes {
  326. if len(res.Values) == 0 {
  327. log.Warningf("CostModel.ComputeAllocation: empty minutes result")
  328. continue
  329. }
  330. cluster, err := res.GetString("cluster_id")
  331. if err != nil {
  332. cluster = env.GetClusterID()
  333. }
  334. labels, err := res.GetStrings("namespace", "pod", "container")
  335. if err != nil {
  336. log.Warningf("CostModel.ComputeAllocation: minutes query result missing field: %s", err)
  337. continue
  338. }
  339. namespace := labels["namespace"]
  340. pod := labels["pod"]
  341. container := labels["container"]
  342. containerKey := newContainerKey(cluster, namespace, pod, container)
  343. podKey := newPodKey(cluster, namespace, pod)
  344. // allocStart and allocEnd are the timestamps of the first and last
  345. // minutes the allocation was running, respectively. We subtract 1m
  346. // from allocStart because this point will actually represent the end
  347. // of the first minute. We don't subtract from allocEnd because it
  348. // already represents the end of the last minute.
  349. var allocStart, allocEnd time.Time
  350. for _, datum := range res.Values {
  351. t := time.Unix(int64(datum.Timestamp), 0)
  352. if allocStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  353. allocStart = t
  354. }
  355. if datum.Value > 0 && window.Contains(t) {
  356. allocEnd = t
  357. }
  358. }
  359. if allocStart.IsZero() || allocEnd.IsZero() {
  360. continue
  361. }
  362. allocStart = allocStart.Add(-time.Minute)
  363. // Set start if unset or this datum's start time is earlier than the
  364. // current earliest time.
  365. if _, ok := clusterStart[cluster]; !ok || allocStart.Before(clusterStart[cluster]) {
  366. clusterStart[cluster] = allocStart
  367. }
  368. // Set end if unset or this datum's end time is later than the
  369. // current latest time.
  370. if _, ok := clusterEnd[cluster]; !ok || allocEnd.After(clusterEnd[cluster]) {
  371. clusterEnd[cluster] = allocEnd
  372. }
  373. name := fmt.Sprintf("%s/%s/%s/%s", cluster, namespace, pod, container)
  374. alloc := &kubecost.Allocation{
  375. Name: name,
  376. Properties: kubecost.Properties{},
  377. Window: window.Clone(),
  378. Start: allocStart,
  379. End: allocEnd,
  380. }
  381. alloc.Properties.SetContainer(container)
  382. alloc.Properties.SetPod(pod)
  383. alloc.Properties.SetNamespace(namespace)
  384. alloc.Properties.SetCluster(cluster)
  385. allocationMap[containerKey] = alloc
  386. if _, ok := podAllocation[podKey]; !ok {
  387. podAllocation[podKey] = []*kubecost.Allocation{}
  388. }
  389. podAllocation[podKey] = append(podAllocation[podKey], alloc)
  390. }
  391. }
  392. func applyCPUCoresAllocated(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresAllocated []*prom.QueryResult) {
  393. for _, res := range resCPUCoresAllocated {
  394. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  395. if err != nil {
  396. log.Warningf("CostModel.ComputeAllocation: CPU allocation query result missing field: %s", err)
  397. continue
  398. }
  399. _, ok := allocationMap[key]
  400. if !ok {
  401. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified CPU allocation query result: %s", key)
  402. continue
  403. }
  404. cpuCores := res.Values[0].Value
  405. hours := allocationMap[key].Minutes() / 60.0
  406. allocationMap[key].CPUCoreHours = cpuCores * hours
  407. node, err := res.GetString("node")
  408. if err != nil {
  409. log.Warningf("CostModel.ComputeAllocation: CPU allocation query result missing 'node': %s", key)
  410. continue
  411. }
  412. allocationMap[key].Properties.SetNode(node)
  413. }
  414. }
  415. func applyCPUCoresRequested(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresRequested []*prom.QueryResult) {
  416. for _, res := range resCPUCoresRequested {
  417. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  418. if err != nil {
  419. log.Warningf("CostModel.ComputeAllocation: CPU request query result missing field: %s", err)
  420. continue
  421. }
  422. _, ok := allocationMap[key]
  423. if !ok {
  424. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified CPU request query result: %s", key)
  425. continue
  426. }
  427. allocationMap[key].CPUCoreRequestAverage = res.Values[0].Value
  428. // If CPU allocation is less than requests, set CPUCoreHours to
  429. // request level.
  430. if allocationMap[key].CPUCores() < res.Values[0].Value {
  431. allocationMap[key].CPUCoreHours = res.Values[0].Value * (allocationMap[key].Minutes() / 60.0)
  432. }
  433. node, err := res.GetString("node")
  434. if err != nil {
  435. log.Warningf("CostModel.ComputeAllocation: CPU request query result missing 'node': %s", key)
  436. continue
  437. }
  438. allocationMap[key].Properties.SetNode(node)
  439. }
  440. }
  441. func applyCPUCoresUsed(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresUsed []*prom.QueryResult) {
  442. for _, res := range resCPUCoresUsed {
  443. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod_name", "container_name")
  444. if err != nil {
  445. log.Warningf("CostModel.ComputeAllocation: CPU usage query result missing field: %s", err)
  446. continue
  447. }
  448. _, ok := allocationMap[key]
  449. if !ok {
  450. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified CPU usage query result: %s", key)
  451. continue
  452. }
  453. allocationMap[key].CPUCoreUsageAverage = res.Values[0].Value
  454. }
  455. }
  456. func applyRAMBytesAllocated(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesAllocated []*prom.QueryResult) {
  457. for _, res := range resRAMBytesAllocated {
  458. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  459. if err != nil {
  460. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing field: %s", err)
  461. continue
  462. }
  463. _, ok := allocationMap[key]
  464. if !ok {
  465. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified RAM allocation query result: %s", key)
  466. continue
  467. }
  468. ramBytes := res.Values[0].Value
  469. hours := allocationMap[key].Minutes() / 60.0
  470. allocationMap[key].RAMByteHours = ramBytes * hours
  471. node, err := res.GetString("node")
  472. if err != nil {
  473. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing 'node': %s", key)
  474. continue
  475. }
  476. allocationMap[key].Properties.SetNode(node)
  477. }
  478. }
  479. func applyRAMBytesRequested(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesRequested []*prom.QueryResult) {
  480. for _, res := range resRAMBytesRequested {
  481. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  482. if err != nil {
  483. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing field: %s", err)
  484. continue
  485. }
  486. _, ok := allocationMap[key]
  487. if !ok {
  488. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified RAM request query result: %s", key)
  489. continue
  490. }
  491. allocationMap[key].RAMBytesRequestAverage = res.Values[0].Value
  492. // If RAM allocation is less than requests, set RAMByteHours to
  493. // request level.
  494. if allocationMap[key].RAMBytes() < res.Values[0].Value {
  495. allocationMap[key].RAMByteHours = res.Values[0].Value * (allocationMap[key].Minutes() / 60.0)
  496. }
  497. node, err := res.GetString("node")
  498. if err != nil {
  499. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing 'node': %s", key)
  500. continue
  501. }
  502. allocationMap[key].Properties.SetNode(node)
  503. }
  504. }
  505. func applyRAMBytesUsed(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesUsed []*prom.QueryResult) {
  506. for _, res := range resRAMBytesUsed {
  507. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod_name", "container_name")
  508. if err != nil {
  509. log.Warningf("CostModel.ComputeAllocation: RAM usage query result missing field: %s", err)
  510. continue
  511. }
  512. _, ok := allocationMap[key]
  513. if !ok {
  514. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified RAM usage query result: %s", key)
  515. continue
  516. }
  517. allocationMap[key].RAMBytesUsageAverage = res.Values[0].Value
  518. }
  519. }
  520. func applyGPUsRequested(allocationMap map[containerKey]*kubecost.Allocation, resGPUsRequested []*prom.QueryResult) {
  521. for _, res := range resGPUsRequested {
  522. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  523. if err != nil {
  524. log.Warningf("CostModel.ComputeAllocation: GPU allocation query result missing field: %s", err)
  525. continue
  526. }
  527. _, ok := allocationMap[key]
  528. if !ok {
  529. log.DedupedWarningf(5, "CostModel.ComputeAllocation: unidentified GPU allocation query result: %s", key)
  530. continue
  531. }
  532. // TODO niko/computeallocation remove log
  533. log.Infof("CostModel.ComputeAllocation: GPU results: %s=%f", key, res.Values[0].Value)
  534. hrs := allocationMap[key].Minutes() / 60.0
  535. allocationMap[key].GPUHours = res.Values[0].Value * hrs
  536. }
  537. }
  538. func applyNetworkAllocation(allocationMap map[containerKey]*kubecost.Allocation, podAllocation map[podKey][]*kubecost.Allocation, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult) {
  539. costPerGiBByCluster := map[string]float64{}
  540. for _, res := range resNetworkCostPerGiB {
  541. cluster, err := res.GetString("cluster_id")
  542. if err != nil {
  543. cluster = env.GetClusterID()
  544. }
  545. costPerGiBByCluster[cluster] = res.Values[0].Value
  546. }
  547. for _, res := range resNetworkGiB {
  548. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  549. if err != nil {
  550. log.Warningf("CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  551. continue
  552. }
  553. allocs, ok := podAllocation[podKey]
  554. if !ok {
  555. log.Warningf("CostModel.ComputeAllocation: Network allocation query result for unidentified pod allocations: %s", podKey)
  556. continue
  557. }
  558. for _, alloc := range allocs {
  559. gib := res.Values[0].Value
  560. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  561. alloc.NetworkCost = gib * costPerGiB
  562. }
  563. }
  564. }
  565. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[string]map[string]string {
  566. namespaceLabels := map[string]map[string]string{}
  567. for _, res := range resNamespaceLabels {
  568. namespace, err := res.GetString("namespace")
  569. if err != nil {
  570. continue
  571. }
  572. if _, ok := namespaceLabels[namespace]; !ok {
  573. namespaceLabels[namespace] = map[string]string{}
  574. }
  575. for k, l := range res.GetLabels() {
  576. namespaceLabels[namespace][k] = l
  577. }
  578. }
  579. return namespaceLabels
  580. }
  581. func resToPodLabels(resPodLabels []*prom.QueryResult) map[podKey]map[string]string {
  582. podLabels := map[podKey]map[string]string{}
  583. for _, res := range resPodLabels {
  584. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  585. if err != nil {
  586. continue
  587. }
  588. if _, ok := podLabels[podKey]; !ok {
  589. podLabels[podKey] = map[string]string{}
  590. }
  591. for k, l := range res.GetLabels() {
  592. podLabels[podKey][k] = l
  593. }
  594. }
  595. return podLabels
  596. }
  597. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  598. namespaceAnnotations := map[string]map[string]string{}
  599. for _, res := range resNamespaceAnnotations {
  600. namespace, err := res.GetString("namespace")
  601. if err != nil {
  602. continue
  603. }
  604. if _, ok := namespaceAnnotations[namespace]; !ok {
  605. namespaceAnnotations[namespace] = map[string]string{}
  606. }
  607. for k, l := range res.GetAnnotations() {
  608. namespaceAnnotations[namespace][k] = l
  609. }
  610. }
  611. return namespaceAnnotations
  612. }
  613. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult) map[podKey]map[string]string {
  614. podAnnotations := map[podKey]map[string]string{}
  615. for _, res := range resPodAnnotations {
  616. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  617. if err != nil {
  618. continue
  619. }
  620. if _, ok := podAnnotations[podKey]; !ok {
  621. podAnnotations[podKey] = map[string]string{}
  622. }
  623. for k, l := range res.GetAnnotations() {
  624. podAnnotations[podKey][k] = l
  625. }
  626. }
  627. return podAnnotations
  628. }
  629. func applyLabels(allocationMap map[containerKey]*kubecost.Allocation, namespaceLabels map[string]map[string]string, podLabels map[podKey]map[string]string) {
  630. for key, alloc := range allocationMap {
  631. allocLabels, err := alloc.Properties.GetLabels()
  632. if err != nil {
  633. allocLabels = map[string]string{}
  634. }
  635. // Apply namespace labels first, then pod labels so that pod labels
  636. // overwrite namespace labels.
  637. if labels, ok := namespaceLabels[key.Namespace]; ok {
  638. for k, v := range labels {
  639. allocLabels[k] = v
  640. }
  641. }
  642. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  643. if labels, ok := podLabels[podKey]; ok {
  644. for k, v := range labels {
  645. allocLabels[k] = v
  646. }
  647. }
  648. alloc.Properties.SetLabels(allocLabels)
  649. }
  650. }
  651. func applyAnnotations(allocationMap map[containerKey]*kubecost.Allocation, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  652. for key, alloc := range allocationMap {
  653. allocAnnotations, err := alloc.Properties.GetAnnotations()
  654. if err != nil {
  655. allocAnnotations = map[string]string{}
  656. }
  657. // Apply namespace annotations first, then pod annotations so that
  658. // pod labels overwrite namespace labels.
  659. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  660. for k, v := range labels {
  661. allocAnnotations[k] = v
  662. }
  663. }
  664. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  665. if labels, ok := podAnnotations[podKey]; ok {
  666. for k, v := range labels {
  667. allocAnnotations[k] = v
  668. }
  669. }
  670. alloc.Properties.SetAnnotations(allocAnnotations)
  671. }
  672. }
  673. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  674. serviceLabels := map[serviceKey]map[string]string{}
  675. for _, res := range resServiceLabels {
  676. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service")
  677. if err != nil {
  678. continue
  679. }
  680. if _, ok := serviceLabels[serviceKey]; !ok {
  681. serviceLabels[serviceKey] = map[string]string{}
  682. }
  683. for k, l := range res.GetLabels() {
  684. serviceLabels[serviceKey][k] = l
  685. }
  686. }
  687. return serviceLabels
  688. }
  689. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  690. deploymentLabels := map[controllerKey]map[string]string{}
  691. for _, res := range resDeploymentLabels {
  692. controllerKey, err := resultDeploymentKey(res, "cluster_id", "namespace", "deployment")
  693. if err != nil {
  694. continue
  695. }
  696. if _, ok := deploymentLabels[controllerKey]; !ok {
  697. deploymentLabels[controllerKey] = map[string]string{}
  698. }
  699. for k, l := range res.GetLabels() {
  700. deploymentLabels[controllerKey][k] = l
  701. }
  702. }
  703. return deploymentLabels
  704. }
  705. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  706. statefulSetLabels := map[controllerKey]map[string]string{}
  707. for _, res := range resStatefulSetLabels {
  708. controllerKey, err := resultStatefulSetKey(res, "cluster_id", "namespace", "statefulSet")
  709. if err != nil {
  710. continue
  711. }
  712. if _, ok := statefulSetLabels[controllerKey]; !ok {
  713. statefulSetLabels[controllerKey] = map[string]string{}
  714. }
  715. for k, l := range res.GetLabels() {
  716. statefulSetLabels[controllerKey][k] = l
  717. }
  718. }
  719. return statefulSetLabels
  720. }
  721. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  722. podControllerMap := map[podKey]controllerKey{}
  723. // For each controller, turn the labels into a selector and attempt to
  724. // match it with each set of pod labels. A match indicates that the pod
  725. // belongs to the controller.
  726. for cKey, cLabels := range controllerLabels {
  727. selector := labels.Set(cLabels).AsSelectorPreValidated()
  728. for pKey, pLabels := range podLabels {
  729. // If the pod is in a different cluster or namespace, there is
  730. // no need to compare the labels.
  731. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  732. continue
  733. }
  734. podLabelSet := labels.Set(pLabels)
  735. if selector.Matches(podLabelSet) {
  736. if _, ok := podControllerMap[pKey]; ok {
  737. log.Warningf("CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  738. }
  739. podControllerMap[pKey] = cKey
  740. }
  741. }
  742. }
  743. return podControllerMap
  744. }
  745. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult) map[podKey]controllerKey {
  746. daemonSetLabels := map[podKey]controllerKey{}
  747. for _, res := range resDaemonSetLabels {
  748. controllerKey, err := resultDaemonSetKey(res, "cluster_id", "namespace", "owner_name")
  749. if err != nil {
  750. continue
  751. }
  752. pod, err := res.GetString("pod")
  753. if err != nil {
  754. log.Warningf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  755. }
  756. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  757. daemonSetLabels[podKey] = controllerKey
  758. }
  759. return daemonSetLabels
  760. }
  761. func resToPodJobMap(resJobLabels []*prom.QueryResult) map[podKey]controllerKey {
  762. jobLabels := map[podKey]controllerKey{}
  763. for _, res := range resJobLabels {
  764. controllerKey, err := resultJobKey(res, "cluster_id", "namespace", "owner_name")
  765. if err != nil {
  766. continue
  767. }
  768. pod, err := res.GetString("pod")
  769. if err != nil {
  770. log.Warningf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  771. }
  772. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  773. jobLabels[podKey] = controllerKey
  774. }
  775. return jobLabels
  776. }
  777. func applyServicesToPods(allocationMap map[containerKey]*kubecost.Allocation, podLabels map[podKey]map[string]string, serviceLabels map[serviceKey]map[string]string) {
  778. podServicesMap := map[podKey][]serviceKey{}
  779. // For each service, turn the labels into a selector and attempt to
  780. // match it with each set of pod labels. A match indicates that the pod
  781. // belongs to the service.
  782. for sKey, sLabels := range serviceLabels {
  783. selector := labels.Set(sLabels).AsSelectorPreValidated()
  784. for pKey, pLabels := range podLabels {
  785. // If the pod is in a different cluster or namespace, there is
  786. // no need to compare the labels.
  787. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  788. continue
  789. }
  790. podLabelSet := labels.Set(pLabels)
  791. if selector.Matches(podLabelSet) {
  792. if _, ok := podServicesMap[pKey]; !ok {
  793. podServicesMap[pKey] = []serviceKey{}
  794. }
  795. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  796. }
  797. }
  798. }
  799. // For each allocation, attempt to find and apply the list of services
  800. // associated with the allocation's pod.
  801. for key, alloc := range allocationMap {
  802. pKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  803. if sKeys, ok := podServicesMap[pKey]; ok {
  804. services := []string{}
  805. for _, sKey := range sKeys {
  806. services = append(services, sKey.Service)
  807. }
  808. alloc.Properties.SetServices(services)
  809. }
  810. }
  811. }
  812. func applyControllersToPods(allocationMap map[containerKey]*kubecost.Allocation, podControllerMap map[podKey]controllerKey) {
  813. for key, alloc := range allocationMap {
  814. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  815. if controllerKey, ok := podControllerMap[podKey]; ok {
  816. alloc.Properties.SetControllerKind(controllerKey.ControllerKind)
  817. alloc.Properties.SetController(controllerKey.Controller)
  818. }
  819. }
  820. }
  821. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*Node, resNodeCostPerCPUHr []*prom.QueryResult) {
  822. for _, res := range resNodeCostPerCPUHr {
  823. cluster, err := res.GetString("cluster_id")
  824. if err != nil {
  825. cluster = env.GetClusterID()
  826. }
  827. node, err := res.GetString("node")
  828. if err != nil {
  829. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  830. continue
  831. }
  832. instanceType, err := res.GetString("instance_type")
  833. if err != nil {
  834. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  835. continue
  836. }
  837. key := newNodeKey(cluster, node)
  838. if _, ok := nodeMap[key]; !ok {
  839. nodeMap[key] = &Node{
  840. Name: node,
  841. NodeType: instanceType,
  842. }
  843. }
  844. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  845. }
  846. }
  847. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*Node, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  848. for _, res := range resNodeCostPerRAMGiBHr {
  849. cluster, err := res.GetString("cluster_id")
  850. if err != nil {
  851. cluster = env.GetClusterID()
  852. }
  853. node, err := res.GetString("node")
  854. if err != nil {
  855. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  856. continue
  857. }
  858. instanceType, err := res.GetString("instance_type")
  859. if err != nil {
  860. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  861. continue
  862. }
  863. key := newNodeKey(cluster, node)
  864. if _, ok := nodeMap[key]; !ok {
  865. nodeMap[key] = &Node{
  866. Name: node,
  867. NodeType: instanceType,
  868. }
  869. }
  870. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  871. }
  872. }
  873. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*Node, resNodeCostPerGPUHr []*prom.QueryResult) {
  874. for _, res := range resNodeCostPerGPUHr {
  875. cluster, err := res.GetString("cluster_id")
  876. if err != nil {
  877. cluster = env.GetClusterID()
  878. }
  879. node, err := res.GetString("node")
  880. if err != nil {
  881. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  882. continue
  883. }
  884. instanceType, err := res.GetString("instance_type")
  885. if err != nil {
  886. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  887. continue
  888. }
  889. key := newNodeKey(cluster, node)
  890. if _, ok := nodeMap[key]; !ok {
  891. nodeMap[key] = &Node{
  892. Name: node,
  893. NodeType: instanceType,
  894. }
  895. }
  896. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  897. }
  898. }
  899. func applyNodeSpot(nodeMap map[nodeKey]*Node, resNodeIsSpot []*prom.QueryResult) {
  900. for _, res := range resNodeIsSpot {
  901. cluster, err := res.GetString("cluster_id")
  902. if err != nil {
  903. cluster = env.GetClusterID()
  904. }
  905. node, err := res.GetString("node")
  906. if err != nil {
  907. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  908. continue
  909. }
  910. key := newNodeKey(cluster, node)
  911. if _, ok := nodeMap[key]; !ok {
  912. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  913. continue
  914. }
  915. nodeMap[key].Preemptible = res.Values[0].Value > 0
  916. }
  917. }
  918. func applyNodeDiscount(nodeMap map[nodeKey]*Node, cm *CostModel) {
  919. if cm == nil {
  920. return
  921. }
  922. c, err := cm.Provider.GetConfig()
  923. if err != nil {
  924. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  925. return
  926. }
  927. discount, err := ParsePercentString(c.Discount)
  928. if err != nil {
  929. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  930. return
  931. }
  932. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  933. if err != nil {
  934. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  935. return
  936. }
  937. for _, node := range nodeMap {
  938. // TODO niko/computeallocation GKE Reserved Instances into account
  939. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  940. node.CostPerCPUHr *= (1.0 - node.Discount)
  941. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  942. }
  943. }
  944. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  945. for _, res := range resPVCostPerGiBHour {
  946. cluster, err := res.GetString("cluster_id")
  947. if err != nil {
  948. cluster = env.GetClusterID()
  949. }
  950. name, err := res.GetString("volumename")
  951. if err != nil {
  952. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  953. continue
  954. }
  955. key := newPVKey(cluster, name)
  956. pvMap[key] = &PV{
  957. Cluster: cluster,
  958. Name: name,
  959. CostPerGiBHour: res.Values[0].Value,
  960. }
  961. }
  962. }
  963. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  964. for _, res := range resPVBytes {
  965. key, err := resultPVKey(res, "cluster_id", "persistentvolume")
  966. if err != nil {
  967. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  968. continue
  969. }
  970. if _, ok := pvMap[key]; !ok {
  971. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  972. continue
  973. }
  974. pvMap[key].Bytes = res.Values[0].Value
  975. }
  976. }
  977. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  978. for _, res := range resPVCInfo {
  979. cluster, err := res.GetString("cluster_id")
  980. if err != nil {
  981. cluster = env.GetClusterID()
  982. }
  983. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  984. if err != nil {
  985. log.Warningf("CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  986. continue
  987. }
  988. namespace := values["namespace"]
  989. name := values["persistentvolumeclaim"]
  990. volume := values["volumename"]
  991. storageClass := values["storageclass"]
  992. pvKey := newPVKey(cluster, volume)
  993. pvcKey := newPVCKey(cluster, namespace, name)
  994. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  995. // the PVC was running, respectively. We subtract 1m from pvcStart
  996. // because this point will actually represent the end of the first
  997. // minute. We don't subtract from pvcEnd because it already represents
  998. // the end of the last minute.
  999. var pvcStart, pvcEnd time.Time
  1000. for _, datum := range res.Values {
  1001. t := time.Unix(int64(datum.Timestamp), 0)
  1002. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1003. pvcStart = t
  1004. }
  1005. if datum.Value > 0 && window.Contains(t) {
  1006. pvcEnd = t
  1007. }
  1008. }
  1009. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1010. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1011. }
  1012. pvcStart = pvcStart.Add(-time.Minute)
  1013. if _, ok := pvMap[pvKey]; !ok {
  1014. log.Warningf("CostModel.ComputeAllocation: PV missing for PVC info query result: %s", pvKey)
  1015. continue
  1016. }
  1017. pvMap[pvKey].StorageClass = storageClass
  1018. if _, ok := pvcMap[pvcKey]; !ok {
  1019. pvcMap[pvcKey] = &PVC{}
  1020. }
  1021. pvcMap[pvcKey].Name = name
  1022. pvcMap[pvcKey].Namespace = namespace
  1023. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1024. pvcMap[pvcKey].Start = pvcStart
  1025. pvcMap[pvcKey].End = pvcEnd
  1026. }
  1027. }
  1028. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1029. for _, res := range resPVCBytesRequested {
  1030. key, err := resultPVCKey(res, "cluster_id", "namespace", "persistentvolumeclaim")
  1031. if err != nil {
  1032. log.Warningf("CostModel.ComputeAllocation: PVC bytes requested query result missing field: %s", err)
  1033. continue
  1034. }
  1035. if _, ok := pvcMap[key]; !ok {
  1036. log.Warningf("CostModel.ComputeAllocation: PVC bytes requested result for missing PVC: %s", key)
  1037. continue
  1038. }
  1039. pvcMap[key].Bytes = res.Values[0].Value
  1040. }
  1041. }
  1042. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podAllocation map[podKey][]*kubecost.Allocation, resPodPVCAllocation []*prom.QueryResult) {
  1043. for _, res := range resPodPVCAllocation {
  1044. cluster, err := res.GetString("cluster_id")
  1045. if err != nil {
  1046. cluster = env.GetClusterID()
  1047. }
  1048. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1049. if err != nil {
  1050. log.Warningf("CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1051. continue
  1052. }
  1053. namespace := values["namespace"]
  1054. pod := values["pod"]
  1055. name := values["persistentvolumeclaim"]
  1056. volume := values["persistentvolume"]
  1057. podKey := newPodKey(cluster, namespace, pod)
  1058. pvKey := newPVKey(cluster, volume)
  1059. pvcKey := newPVCKey(cluster, namespace, name)
  1060. if _, ok := pvMap[pvKey]; !ok {
  1061. log.Warningf("CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1062. continue
  1063. }
  1064. if _, ok := podPVCMap[podKey]; !ok {
  1065. podPVCMap[podKey] = []*PVC{}
  1066. }
  1067. pvc, ok := pvcMap[pvcKey]
  1068. if !ok {
  1069. log.Warningf("CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1070. continue
  1071. }
  1072. pvc.Count = len(podAllocation[podKey])
  1073. pvc.Mounted = true
  1074. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1075. }
  1076. }
  1077. func applyUnmountedPVs(window kubecost.Window, allocationMap map[containerKey]*kubecost.Allocation, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1078. unmountedPVBytes := map[string]float64{}
  1079. unmountedPVCost := map[string]float64{}
  1080. for _, pv := range pvMap {
  1081. mounted := false
  1082. for _, pvc := range pvcMap {
  1083. if pvc.Volume == nil {
  1084. continue
  1085. }
  1086. if pvc.Volume == pv {
  1087. mounted = true
  1088. break
  1089. }
  1090. }
  1091. if !mounted {
  1092. gib := pv.Bytes / 1024 / 1024 / 1024
  1093. hrs := window.Minutes() / 60.0 // TODO niko/computeallocation PV hours, not window hours?
  1094. cost := pv.CostPerGiBHour * gib * hrs
  1095. unmountedPVCost[pv.Cluster] += cost
  1096. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1097. }
  1098. }
  1099. for cluster, amount := range unmountedPVCost {
  1100. container := kubecost.UnmountedSuffix
  1101. pod := kubecost.UnmountedSuffix
  1102. namespace := kubecost.UnmountedSuffix
  1103. node := ""
  1104. containerKey := newContainerKey(cluster, namespace, pod, container)
  1105. allocationMap[containerKey] = &kubecost.Allocation{
  1106. Name: fmt.Sprintf("%s/%s/%s/%s/%s", cluster, node, namespace, pod, container),
  1107. Properties: kubecost.Properties{
  1108. kubecost.ClusterProp: cluster,
  1109. kubecost.NodeProp: node,
  1110. kubecost.NamespaceProp: namespace,
  1111. kubecost.PodProp: pod,
  1112. kubecost.ContainerProp: container,
  1113. },
  1114. Window: window.Clone(),
  1115. Start: *window.Start(),
  1116. End: *window.End(),
  1117. PVByteHours: unmountedPVBytes[cluster] * window.Minutes() / 60.0,
  1118. PVCost: amount,
  1119. TotalCost: amount,
  1120. }
  1121. }
  1122. }
  1123. func applyUnmountedPVCs(window kubecost.Window, allocationMap map[containerKey]*kubecost.Allocation, pvcMap map[pvcKey]*PVC) {
  1124. unmountedPVCBytes := map[namespaceKey]float64{}
  1125. unmountedPVCCost := map[namespaceKey]float64{}
  1126. for _, pvc := range pvcMap {
  1127. if !pvc.Mounted && pvc.Volume != nil {
  1128. key := newNamespaceKey(pvc.Cluster, pvc.Namespace)
  1129. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1130. hrs := pvc.Minutes() / 60.0
  1131. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1132. unmountedPVCCost[key] += cost
  1133. unmountedPVCBytes[key] += pvc.Volume.Bytes
  1134. }
  1135. }
  1136. for key, amount := range unmountedPVCCost {
  1137. container := kubecost.UnmountedSuffix
  1138. pod := kubecost.UnmountedSuffix
  1139. namespace := key.Namespace
  1140. node := ""
  1141. cluster := key.Cluster
  1142. containerKey := newContainerKey(cluster, namespace, pod, container)
  1143. allocationMap[containerKey] = &kubecost.Allocation{
  1144. Name: fmt.Sprintf("%s/%s/%s/%s/%s", cluster, node, namespace, pod, container),
  1145. Properties: kubecost.Properties{
  1146. kubecost.ClusterProp: cluster,
  1147. kubecost.NodeProp: node,
  1148. kubecost.NamespaceProp: namespace,
  1149. kubecost.PodProp: pod,
  1150. kubecost.ContainerProp: container,
  1151. },
  1152. Window: window.Clone(),
  1153. Start: *window.Start(),
  1154. End: *window.End(),
  1155. PVByteHours: unmountedPVCBytes[key] * window.Minutes() / 60.0,
  1156. PVCost: amount,
  1157. TotalCost: amount,
  1158. }
  1159. }
  1160. }
  1161. // PVC describes a PersistentVolumeClaim
  1162. // TODO move to pkg/kubecost? [TODO:CLEANUP]
  1163. // TODO add PersistentVolumeClaims field to type Allocation? [TODO:CLEANUP]
  1164. type PVC struct {
  1165. Bytes float64 `json:"bytes"`
  1166. Count int `json:"count"`
  1167. Name string `json:"name"`
  1168. Cluster string `json:"cluster"`
  1169. Namespace string `json:"namespace"`
  1170. Volume *PV `json:"persistentVolume"`
  1171. Mounted bool `json:"mounted"`
  1172. Start time.Time `json:"start"`
  1173. End time.Time `json:"end"`
  1174. }
  1175. // Cost computes the cumulative cost of the PVC
  1176. func (pvc *PVC) Cost() float64 {
  1177. if pvc == nil || pvc.Volume == nil {
  1178. return 0.0
  1179. }
  1180. gib := pvc.Bytes / 1024 / 1024 / 1024
  1181. hrs := pvc.Minutes() / 60.0
  1182. return pvc.Volume.CostPerGiBHour * gib * hrs
  1183. }
  1184. // Minutes computes the number of minutes over which the PVC is defined
  1185. func (pvc *PVC) Minutes() float64 {
  1186. if pvc == nil {
  1187. return 0.0
  1188. }
  1189. return pvc.End.Sub(pvc.Start).Minutes()
  1190. }
  1191. // String returns a string representation of the PVC
  1192. func (pvc *PVC) String() string {
  1193. if pvc == nil {
  1194. return "<nil>"
  1195. }
  1196. return fmt.Sprintf("%s/%s/%s{Bytes:%.2f, Cost:%.6f, Start,End:%s}", pvc.Cluster, pvc.Namespace, pvc.Name, pvc.Bytes, pvc.Cost(), kubecost.NewWindow(&pvc.Start, &pvc.End))
  1197. }
  1198. // PV describes a PersistentVolume
  1199. // TODO move to pkg/kubecost? [TODO:CLEANUP]
  1200. type PV struct {
  1201. Bytes float64 `json:"bytes"`
  1202. CostPerGiBHour float64 `json:"costPerGiBHour"` // TODO niko/computeallocation GiB or GB?
  1203. Cluster string `json:"cluster"`
  1204. Name string `json:"name"`
  1205. StorageClass string `json:"storageClass"`
  1206. }
  1207. // String returns a string representation of the PV
  1208. func (pv *PV) String() string {
  1209. if pv == nil {
  1210. return "<nil>"
  1211. }
  1212. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  1213. }