costmodel.go 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  1. package costmodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "time"
  10. costAnalyzerCloud "github.com/opencost/opencost/pkg/cloud/models"
  11. "github.com/opencost/opencost/pkg/clustercache"
  12. "github.com/opencost/opencost/pkg/costmodel/clusters"
  13. "github.com/opencost/opencost/pkg/env"
  14. "github.com/opencost/opencost/pkg/kubecost"
  15. "github.com/opencost/opencost/pkg/log"
  16. "github.com/opencost/opencost/pkg/prom"
  17. "github.com/opencost/opencost/pkg/util"
  18. prometheus "github.com/prometheus/client_golang/api"
  19. prometheusClient "github.com/prometheus/client_golang/api"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/labels"
  23. "golang.org/x/sync/singleflight"
  24. )
  25. const (
  26. statusAPIError = 422
  27. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  28. unmountedPVsContainer = "unmounted-pvs"
  29. apiPrefix = "/api/v1"
  30. epAlertManagers = apiPrefix + "/alertmanagers"
  31. epLabelValues = apiPrefix + "/label/:name/values"
  32. epSeries = apiPrefix + "/series"
  33. epTargets = apiPrefix + "/targets"
  34. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  35. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  36. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  37. epConfig = apiPrefix + "/status/config"
  38. epFlags = apiPrefix + "/status/flags"
  39. )
  40. // isCron matches a CronJob name and captures the non-timestamp name
  41. //
  42. // We support either a 10 character timestamp OR an 8 character timestamp
  43. // because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
  44. // and batch/v1 CronJobs create Jobs with 8 character timestamps.
  45. var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
  46. type CostModel struct {
  47. Cache clustercache.ClusterCache
  48. ClusterMap clusters.ClusterMap
  49. MaxPrometheusQueryDuration time.Duration
  50. RequestGroup *singleflight.Group
  51. ScrapeInterval time.Duration
  52. PrometheusClient prometheus.Client
  53. Provider costAnalyzerCloud.Provider
  54. pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
  55. }
  56. func NewCostModel(client prometheus.Client, provider costAnalyzerCloud.Provider, cache clustercache.ClusterCache, clusterMap clusters.ClusterMap, scrapeInterval time.Duration) *CostModel {
  57. // request grouping to prevent over-requesting the same data prior to caching
  58. requestGroup := new(singleflight.Group)
  59. return &CostModel{
  60. Cache: cache,
  61. ClusterMap: clusterMap,
  62. MaxPrometheusQueryDuration: env.GetETLMaxPrometheusQueryDuration(),
  63. PrometheusClient: client,
  64. Provider: provider,
  65. RequestGroup: requestGroup,
  66. ScrapeInterval: scrapeInterval,
  67. }
  68. }
  69. type CostData struct {
  70. Name string `json:"name,omitempty"`
  71. PodName string `json:"podName,omitempty"`
  72. NodeName string `json:"nodeName,omitempty"`
  73. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  74. Namespace string `json:"namespace,omitempty"`
  75. Deployments []string `json:"deployments,omitempty"`
  76. Services []string `json:"services,omitempty"`
  77. Daemonsets []string `json:"daemonsets,omitempty"`
  78. Statefulsets []string `json:"statefulsets,omitempty"`
  79. Jobs []string `json:"jobs,omitempty"`
  80. RAMReq []*util.Vector `json:"ramreq,omitempty"`
  81. RAMUsed []*util.Vector `json:"ramused,omitempty"`
  82. RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
  83. CPUReq []*util.Vector `json:"cpureq,omitempty"`
  84. CPUUsed []*util.Vector `json:"cpuused,omitempty"`
  85. CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
  86. GPUReq []*util.Vector `json:"gpureq,omitempty"`
  87. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  88. NetworkData []*util.Vector `json:"network,omitempty"`
  89. Annotations map[string]string `json:"annotations,omitempty"`
  90. Labels map[string]string `json:"labels,omitempty"`
  91. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  92. ClusterID string `json:"clusterId"`
  93. ClusterName string `json:"clusterName"`
  94. }
  95. func (cd *CostData) String() string {
  96. return fmt.Sprintf("\n\tName: %s; PodName: %s, NodeName: %s\n\tNamespace: %s\n\tDeployments: %s\n\tServices: %s\n\tCPU (req, used, alloc): %d, %d, %d\n\tRAM (req, used, alloc): %d, %d, %d",
  97. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  98. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  99. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  100. }
  101. func (cd *CostData) GetController() (name string, kind string, hasController bool) {
  102. hasController = false
  103. if len(cd.Deployments) > 0 {
  104. name = cd.Deployments[0]
  105. kind = "deployment"
  106. hasController = true
  107. } else if len(cd.Statefulsets) > 0 {
  108. name = cd.Statefulsets[0]
  109. kind = "statefulset"
  110. hasController = true
  111. } else if len(cd.Daemonsets) > 0 {
  112. name = cd.Daemonsets[0]
  113. kind = "daemonset"
  114. hasController = true
  115. } else if len(cd.Jobs) > 0 {
  116. name = cd.Jobs[0]
  117. kind = "job"
  118. hasController = true
  119. match := isCron.FindStringSubmatch(name)
  120. if match != nil {
  121. name = match[1]
  122. }
  123. }
  124. return name, kind, hasController
  125. }
  126. const (
  127. queryRAMRequestsStr = `avg(
  128. label_replace(
  129. label_replace(
  130. avg(
  131. sum_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="",container!="POD", node!="", %s}[%s] %s)
  132. ) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
  133. ), "pod_name","$1","pod","(.+)"
  134. )
  135. ) by (namespace,container_name,pod_name,node,%s)`
  136. queryRAMUsageStr = `avg(
  137. label_replace(
  138. label_replace(
  139. label_replace(
  140. sum_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
  141. ), "container_name", "$1", "container", "(.+)"
  142. ), "pod_name", "$1", "pod", "(.+)"
  143. )
  144. ) by (namespace, container_name, pod_name, node, %s)`
  145. queryCPURequestsStr = `avg(
  146. label_replace(
  147. label_replace(
  148. avg(
  149. sum_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="",container!="POD", node!="", %s}[%s] %s)
  150. ) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
  151. ), "pod_name","$1","pod","(.+)"
  152. )
  153. ) by (namespace,container_name,pod_name,node,%s)`
  154. queryCPUUsageStr = `avg(
  155. label_replace(
  156. label_replace(
  157. label_replace(
  158. rate(
  159. container_cpu_usage_seconds_total{container!="", container!="POD", instance!="", %s}[%s] %s
  160. ), "node", "$1", "instance", "(.+)"
  161. ), "container_name", "$1", "container", "(.+)"
  162. ), "pod_name", "$1", "pod", "(.+)"
  163. )
  164. ) by (namespace, container_name, pod_name, node, %s)`
  165. queryGPURequestsStr = `avg(
  166. label_replace(
  167. label_replace(
  168. avg(
  169. sum_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s] %s)
  170. * %f
  171. ) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
  172. ), "pod_name","$1","pod","(.+)"
  173. )
  174. ) by (namespace,container_name,pod_name,node,%s)
  175. * on (pod_name, namespace, %s) group_left(container) label_replace(avg(avg_over_time(kube_pod_status_phase{phase="Running", %s}[%s] %s)) by (pod,namespace,%s), "pod_name","$1","pod","(.+)")`
  176. queryPVRequestsStr = `avg(avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, namespace, volumename, %s, kubernetes_node)
  177. *
  178. on (persistentvolumeclaim, namespace, %s, kubernetes_node) group_right(storageclass, volumename)
  179. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}) by (persistentvolumeclaim, namespace, %s, kubernetes_node, kubernetes_name)) by (persistentvolumeclaim, storageclass, namespace, %s, volumename, kubernetes_node)`
  180. // queryRAMAllocationByteHours yields the total byte-hour RAM allocation over the given
  181. // window, aggregated by container.
  182. // [line 3] sum_over_time(each byte) = [byte*scrape] by metric
  183. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  184. // [lines 2,4] sum(") by unique container key and multiply [byte*scrape] * [hours/scrape] for byte*hours
  185. // [lines 1,5] relabeling
  186. queryRAMAllocationByteHours = `
  187. label_replace(label_replace(
  188. sum(
  189. sum_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!="", %s}[%s])
  190. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  191. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  192. // queryCPUAllocationVCPUHours yields the total VCPU-hour CPU allocation over the given
  193. // window, aggregated by container.
  194. // [line 3] sum_over_time(each VCPU*mins in window) = [VCPU*scrape] by metric
  195. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  196. // [lines 2,4] sum(") by unique container key and multiply [VCPU*scrape] * [hours/scrape] for VCPU*hours
  197. // [lines 1,5] relabeling
  198. queryCPUAllocationVCPUHours = `
  199. label_replace(label_replace(
  200. sum(
  201. sum_over_time(container_cpu_allocation{container!="",container!="POD", node!="", %s}[%s])
  202. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  203. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  204. // queryPVCAllocationFmt yields the total byte-hour PVC allocation over the given window.
  205. // sum_over_time(each byte) = [byte*scrape] by metric *(scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by pod
  206. queryPVCAllocationFmt = `sum(sum_over_time(pod_pvc_allocation{%s}[%s])) by (%s, namespace, pod, persistentvolume, persistentvolumeclaim) * %f/60/60`
  207. queryPVHourlyCostFmt = `avg_over_time(pv_hourly_cost{%s}[%s])`
  208. queryNSLabels = `avg_over_time(kube_namespace_labels{%s}[%s])`
  209. queryPodLabels = `avg_over_time(kube_pod_labels{%s}[%s])`
  210. queryNSAnnotations = `avg_over_time(kube_namespace_annotations{%s}[%s])`
  211. queryPodAnnotations = `avg_over_time(kube_pod_annotations{%s}[%s])`
  212. queryDeploymentLabels = `avg_over_time(deployment_match_labels{%s}[%s])`
  213. queryStatefulsetLabels = `avg_over_time(statefulSet_match_labels{%s}[%s])`
  214. queryPodDaemonsets = `sum(kube_pod_owner{owner_kind="DaemonSet", %s}) by (namespace,pod,owner_name,%s)`
  215. queryPodJobs = `sum(kube_pod_owner{owner_kind="Job", %s}) by (namespace,pod,owner_name,%s)`
  216. queryServiceLabels = `avg_over_time(service_selector_labels{%s}[%s])`
  217. queryZoneNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  218. queryRegionNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  219. queryInternetNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  220. normalizationStr = `max(count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[%s] %s))`
  221. )
  222. func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  223. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  224. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  225. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  226. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  227. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  228. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), window, offset)
  229. // Cluster ID is specific to the source cluster
  230. clusterID := env.GetClusterID()
  231. // Submit all Prometheus queries asynchronously
  232. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
  233. resChRAMUsage := ctx.Query(queryRAMUsage)
  234. resChCPUUsage := ctx.Query(queryCPUUsage)
  235. resChNetZoneRequests := ctx.Query(queryNetZoneRequests)
  236. resChNetRegionRequests := ctx.Query(queryNetRegionRequests)
  237. resChNetInternetRequests := ctx.Query(queryNetInternetRequests)
  238. resChNormalization := ctx.Query(queryNormalization)
  239. // Pull pod information from k8s API
  240. podlist := cm.Cache.GetAllPods()
  241. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  242. if err != nil {
  243. return nil, err
  244. }
  245. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  246. if err != nil {
  247. return nil, err
  248. }
  249. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  250. if err != nil {
  251. return nil, err
  252. }
  253. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  254. if err != nil {
  255. return nil, err
  256. }
  257. // Process Prometheus query results. Handle errors using ctx.Errors.
  258. resRAMUsage, _ := resChRAMUsage.Await()
  259. resCPUUsage, _ := resChCPUUsage.Await()
  260. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  261. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  262. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  263. resNormalization, _ := resChNormalization.Await()
  264. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  265. // NOTE: will not propagate unless coupled with errors.
  266. if ctx.HasErrors() {
  267. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  268. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  269. for _, promErr := range ctx.Errors() {
  270. if promErr.Error != nil {
  271. log.Errorf("ComputeCostData: Request Error: %s", promErr.Error)
  272. }
  273. if promErr.ParseError != nil {
  274. log.Errorf("ComputeCostData: Parsing Error: %s", promErr.ParseError)
  275. }
  276. }
  277. // ErrorCollection is an collection of errors wrapped in a single error implementation
  278. // We opt to not return an error for the sake of running as a pure exporter.
  279. log.Warnf("ComputeCostData: continuing despite prometheus errors: %s", ctx.ErrorCollection().Error())
  280. }
  281. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  282. normalizationValue, err := getNormalization(resNormalization)
  283. if err != nil {
  284. // We opt to not return an error for the sake of running as a pure exporter.
  285. log.Warnf("ComputeCostData: continuing despite error parsing normalization values from %s: %s", queryNormalization, err.Error())
  286. }
  287. // Determine if there are vgpus configured and if so get the total allocatable number
  288. // If there are no vgpus, the coefficient is set to 1.0
  289. vgpuCount, err := getAllocatableVGPUs(cm.Cache)
  290. if err != nil {
  291. log.Warnf("getAllocatableVGCPUs error: %s", err.Error())
  292. }
  293. vgpuCoeff := 10.0
  294. if vgpuCount > 0.0 {
  295. vgpuCoeff = vgpuCount
  296. }
  297. nodes, err := cm.GetNodeCost(cp)
  298. if err != nil {
  299. log.Warnf("GetNodeCost: no node cost model available: " + err.Error())
  300. return nil, err
  301. }
  302. // Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
  303. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  304. pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
  305. if err != nil {
  306. log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
  307. }
  308. if pvClaimMapping != nil {
  309. err = addPVData(cm.Cache, pvClaimMapping, cp)
  310. if err != nil {
  311. return nil, err
  312. }
  313. // copy claim mappings into zombies, then remove as they're discovered
  314. for k, v := range pvClaimMapping {
  315. unmountedPVs[k] = []*PersistentVolumeClaimData{v}
  316. }
  317. }
  318. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  319. if err != nil {
  320. log.Warnf("Unable to get Network Cost Data: %s", err.Error())
  321. networkUsageMap = make(map[string]*NetworkUsageData)
  322. }
  323. containerNameCost := make(map[string]*CostData)
  324. containers := make(map[string]bool)
  325. RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, true, normalizationValue, clusterID)
  326. if err != nil {
  327. return nil, err
  328. }
  329. for key := range RAMUsedMap {
  330. containers[key] = true
  331. }
  332. CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, false, 0, clusterID) // No need to normalize here, as this comes from a counter
  333. if err != nil {
  334. return nil, err
  335. }
  336. for key := range CPUUsedMap {
  337. containers[key] = true
  338. }
  339. currentContainers := make(map[string]v1.Pod)
  340. for _, pod := range podlist {
  341. if pod.Status.Phase != v1.PodRunning {
  342. continue
  343. }
  344. cs, err := NewContainerMetricsFromPod(pod, clusterID)
  345. if err != nil {
  346. return nil, err
  347. }
  348. for _, c := range cs {
  349. 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.
  350. currentContainers[c.Key()] = *pod
  351. }
  352. }
  353. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  354. missingContainers := make(map[string]*CostData)
  355. for key := range containers {
  356. if _, ok := containerNameCost[key]; ok {
  357. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  358. }
  359. // The _else_ case for this statement is the case in which the container has been
  360. // deleted so we have usage information but not request information. In that case,
  361. // we return partial data for CPU and RAM: only usage and not requests.
  362. if pod, ok := currentContainers[key]; ok {
  363. podName := pod.GetObjectMeta().GetName()
  364. ns := pod.GetObjectMeta().GetNamespace()
  365. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  366. podLabels := pod.GetObjectMeta().GetLabels()
  367. if podLabels == nil {
  368. podLabels = make(map[string]string)
  369. }
  370. for k, v := range nsLabels {
  371. if _, ok := podLabels[k]; !ok {
  372. podLabels[k] = v
  373. }
  374. }
  375. nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  376. podAnnotations := pod.GetObjectMeta().GetAnnotations()
  377. if podAnnotations == nil {
  378. podAnnotations = make(map[string]string)
  379. }
  380. for k, v := range nsAnnotations {
  381. if _, ok := podAnnotations[k]; !ok {
  382. podAnnotations[k] = v
  383. }
  384. }
  385. nodeName := pod.Spec.NodeName
  386. var nodeData *costAnalyzerCloud.Node
  387. if _, ok := nodes[nodeName]; ok {
  388. nodeData = nodes[nodeName]
  389. }
  390. nsKey := ns + "," + clusterID
  391. var podDeployments []string
  392. if _, ok := podDeploymentsMapping[nsKey]; ok {
  393. if ds, ok := podDeploymentsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  394. podDeployments = ds
  395. } else {
  396. podDeployments = []string{}
  397. }
  398. }
  399. var podPVs []*PersistentVolumeClaimData
  400. podClaims := pod.Spec.Volumes
  401. for _, vol := range podClaims {
  402. if vol.PersistentVolumeClaim != nil {
  403. name := vol.PersistentVolumeClaim.ClaimName
  404. key := ns + "," + name + "," + clusterID
  405. if pvClaim, ok := pvClaimMapping[key]; ok {
  406. pvClaim.TimesClaimed++
  407. podPVs = append(podPVs, pvClaim)
  408. // Remove entry from potential unmounted pvs
  409. delete(unmountedPVs, key)
  410. }
  411. }
  412. }
  413. var podNetCosts []*util.Vector
  414. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  415. netCosts, err := GetNetworkCost(usage, cp)
  416. if err != nil {
  417. log.Debugf("Error pulling network costs: %s", err.Error())
  418. } else {
  419. podNetCosts = netCosts
  420. }
  421. }
  422. var podServices []string
  423. if _, ok := podServicesMapping[nsKey]; ok {
  424. if svcs, ok := podServicesMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  425. podServices = svcs
  426. } else {
  427. podServices = []string{}
  428. }
  429. }
  430. for i, container := range pod.Spec.Containers {
  431. containerName := container.Name
  432. // recreate the key and look up data for this container
  433. newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  434. // k8s.io/apimachinery/pkg/api/resource/amount.go and
  435. // k8s.io/apimachinery/pkg/api/resource/quantity.go for
  436. // details on the "amount" API. See
  437. // https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
  438. // for the units of memory and CPU.
  439. ramRequestBytes := container.Resources.Requests.Memory().Value()
  440. // Because information on container RAM & CPU requests isn't
  441. // coming from Prometheus, it won't have a timestamp associated
  442. // with it. We need to provide a timestamp.
  443. RAMReqV := []*util.Vector{
  444. {
  445. Value: float64(ramRequestBytes),
  446. Timestamp: float64(time.Now().UTC().Unix()),
  447. },
  448. }
  449. // use millicores so we can convert to cores in a float64 format
  450. cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
  451. CPUReqV := []*util.Vector{
  452. {
  453. Value: float64(cpuRequestMilliCores) / 1000,
  454. Timestamp: float64(time.Now().UTC().Unix()),
  455. },
  456. }
  457. gpuReqCount := 0.0
  458. if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
  459. gpuReqCount = g.AsApproximateFloat64()
  460. } else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
  461. gpuReqCount = g.AsApproximateFloat64()
  462. } else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
  463. // divide vgpu request/limits by total vgpus to get the portion of physical gpus requested
  464. gpuReqCount = g.AsApproximateFloat64() / vgpuCoeff
  465. } else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
  466. gpuReqCount = g.AsApproximateFloat64() / vgpuCoeff
  467. }
  468. GPUReqV := []*util.Vector{
  469. {
  470. Value: float64(gpuReqCount),
  471. Timestamp: float64(time.Now().UTC().Unix()),
  472. },
  473. }
  474. RAMUsedV, ok := RAMUsedMap[newKey]
  475. if !ok {
  476. log.Debug("no RAM usage for " + newKey)
  477. RAMUsedV = []*util.Vector{{}}
  478. }
  479. CPUUsedV, ok := CPUUsedMap[newKey]
  480. if !ok {
  481. log.Debug("no CPU usage for " + newKey)
  482. CPUUsedV = []*util.Vector{{}}
  483. }
  484. var pvReq []*PersistentVolumeClaimData
  485. var netReq []*util.Vector
  486. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  487. pvReq = podPVs
  488. netReq = podNetCosts
  489. }
  490. costs := &CostData{
  491. Name: containerName,
  492. PodName: podName,
  493. NodeName: nodeName,
  494. Namespace: ns,
  495. Deployments: podDeployments,
  496. Services: podServices,
  497. Daemonsets: getDaemonsetsOfPod(pod),
  498. Jobs: getJobsOfPod(pod),
  499. Statefulsets: getStatefulSetsOfPod(pod),
  500. NodeData: nodeData,
  501. RAMReq: RAMReqV,
  502. RAMUsed: RAMUsedV,
  503. CPUReq: CPUReqV,
  504. CPUUsed: CPUUsedV,
  505. GPUReq: GPUReqV,
  506. PVCData: pvReq,
  507. NetworkData: netReq,
  508. Annotations: podAnnotations,
  509. Labels: podLabels,
  510. NamespaceLabels: nsLabels,
  511. ClusterID: clusterID,
  512. ClusterName: cm.ClusterMap.NameFor(clusterID),
  513. }
  514. var cpuReq, cpuUse *util.Vector
  515. if len(costs.CPUReq) > 0 {
  516. cpuReq = costs.CPUReq[0]
  517. }
  518. if len(costs.CPUUsed) > 0 {
  519. cpuUse = costs.CPUUsed[0]
  520. }
  521. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  522. var ramReq, ramUse *util.Vector
  523. if len(costs.RAMReq) > 0 {
  524. ramReq = costs.RAMReq[0]
  525. }
  526. if len(costs.RAMUsed) > 0 {
  527. ramUse = costs.RAMUsed[0]
  528. }
  529. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  530. if filterNamespace == "" {
  531. containerNameCost[newKey] = costs
  532. } else if costs.Namespace == filterNamespace {
  533. containerNameCost[newKey] = costs
  534. }
  535. }
  536. } else {
  537. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  538. log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  539. c, err := NewContainerMetricFromKey(key)
  540. if err != nil {
  541. return nil, err
  542. }
  543. // CPU and RAM requests are obtained from the Kubernetes API.
  544. // If this case has been reached, the Kubernetes API will not
  545. // have information about the pod because it no longer exists.
  546. //
  547. // The case where this matters is minimal, mainly in environments
  548. // with very short-lived pods that over-request resources.
  549. RAMReqV := []*util.Vector{{}}
  550. CPUReqV := []*util.Vector{{}}
  551. GPUReqV := []*util.Vector{{}}
  552. RAMUsedV, ok := RAMUsedMap[key]
  553. if !ok {
  554. log.Debug("no RAM usage for " + key)
  555. RAMUsedV = []*util.Vector{{}}
  556. }
  557. CPUUsedV, ok := CPUUsedMap[key]
  558. if !ok {
  559. log.Debug("no CPU usage for " + key)
  560. CPUUsedV = []*util.Vector{{}}
  561. }
  562. node, ok := nodes[c.NodeName]
  563. if !ok {
  564. log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  565. if n, ok := missingNodes[c.NodeName]; ok {
  566. node = n
  567. } else {
  568. node = &costAnalyzerCloud.Node{}
  569. missingNodes[c.NodeName] = node
  570. }
  571. }
  572. namespacelabels, _ := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  573. namespaceAnnotations, _ := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
  574. costs := &CostData{
  575. Name: c.ContainerName,
  576. PodName: c.PodName,
  577. NodeName: c.NodeName,
  578. NodeData: node,
  579. Namespace: c.Namespace,
  580. RAMReq: RAMReqV,
  581. RAMUsed: RAMUsedV,
  582. CPUReq: CPUReqV,
  583. CPUUsed: CPUUsedV,
  584. GPUReq: GPUReqV,
  585. Annotations: namespaceAnnotations,
  586. NamespaceLabels: namespacelabels,
  587. ClusterID: c.ClusterID,
  588. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  589. }
  590. var cpuReq, cpuUse *util.Vector
  591. if len(costs.CPUReq) > 0 {
  592. cpuReq = costs.CPUReq[0]
  593. }
  594. if len(costs.CPUUsed) > 0 {
  595. cpuUse = costs.CPUUsed[0]
  596. }
  597. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  598. var ramReq, ramUse *util.Vector
  599. if len(costs.RAMReq) > 0 {
  600. ramReq = costs.RAMReq[0]
  601. }
  602. if len(costs.RAMUsed) > 0 {
  603. ramUse = costs.RAMUsed[0]
  604. }
  605. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  606. if filterNamespace == "" {
  607. containerNameCost[key] = costs
  608. missingContainers[key] = costs
  609. } else if costs.Namespace == filterNamespace {
  610. containerNameCost[key] = costs
  611. missingContainers[key] = costs
  612. }
  613. }
  614. }
  615. // Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
  616. // to pass along the cost data
  617. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  618. for k, costs := range unmounted {
  619. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  620. if filterNamespace == "" {
  621. containerNameCost[k] = costs
  622. } else if costs.Namespace == filterNamespace {
  623. containerNameCost[k] = costs
  624. }
  625. }
  626. err = findDeletedNodeInfo(cli, missingNodes, window, "")
  627. if err != nil {
  628. log.Errorf("Error fetching historical node data: %s", err.Error())
  629. }
  630. err = findDeletedPodInfo(cli, missingContainers, window)
  631. if err != nil {
  632. log.Errorf("Error fetching historical pod data: %s", err.Error())
  633. }
  634. return containerNameCost, err
  635. }
  636. func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
  637. costs := make(map[string]*CostData)
  638. if len(unmountedPVs) == 0 {
  639. return costs
  640. }
  641. for k, pv := range unmountedPVs {
  642. keyParts := strings.Split(k, ",")
  643. if len(keyParts) != 3 {
  644. log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
  645. continue
  646. }
  647. ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
  648. namespacelabels, _ := namespaceLabelsMapping[ns+","+clusterID]
  649. namespaceAnnotations, _ := namespaceAnnotationsMapping[ns+","+clusterID]
  650. metric := NewContainerMetricFromValues(ns, unmountedPVsContainer, unmountedPVsContainer, "", clusterID)
  651. key := metric.Key()
  652. if costData, ok := costs[key]; !ok {
  653. costs[key] = &CostData{
  654. Name: unmountedPVsContainer,
  655. PodName: unmountedPVsContainer,
  656. NodeName: "",
  657. Annotations: namespaceAnnotations,
  658. Namespace: ns,
  659. NamespaceLabels: namespacelabels,
  660. Labels: namespacelabels,
  661. ClusterID: clusterID,
  662. ClusterName: clusterMap.NameFor(clusterID),
  663. PVCData: pv,
  664. }
  665. } else {
  666. costData.PVCData = append(costData.PVCData, pv...)
  667. }
  668. }
  669. return costs
  670. }
  671. func findDeletedPodInfo(cli prometheusClient.Client, missingContainers map[string]*CostData, window string) error {
  672. if len(missingContainers) > 0 {
  673. queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{%s}[%s]`, env.GetPromClusterFilter(), window)
  674. podLabelsResult, _, err := prom.NewNamedContext(cli, prom.ComputeCostDataContextName).QuerySync(queryHistoricalPodLabels)
  675. if err != nil {
  676. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  677. }
  678. podLabels := make(map[string]map[string]string)
  679. if podLabelsResult != nil {
  680. podLabels, err = parsePodLabels(podLabelsResult)
  681. if err != nil {
  682. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  683. }
  684. }
  685. for key, costData := range missingContainers {
  686. cm, _ := NewContainerMetricFromKey(key)
  687. labels, ok := podLabels[cm.PodName]
  688. if !ok {
  689. labels = make(map[string]string)
  690. }
  691. for k, v := range costData.NamespaceLabels {
  692. labels[k] = v
  693. }
  694. costData.Labels = labels
  695. }
  696. }
  697. return nil
  698. }
  699. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window, offset string) error {
  700. if len(missingNodes) > 0 {
  701. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  702. offsetStr := ""
  703. if offset != "" {
  704. offsetStr = fmt.Sprintf("offset %s", offset)
  705. }
  706. queryHistoricalCPUCost := fmt.Sprintf(`avg(avg_over_time(node_cpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  707. queryHistoricalRAMCost := fmt.Sprintf(`avg(avg_over_time(node_ram_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  708. queryHistoricalGPUCost := fmt.Sprintf(`avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  709. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
  710. cpuCostResCh := ctx.Query(queryHistoricalCPUCost)
  711. ramCostResCh := ctx.Query(queryHistoricalRAMCost)
  712. gpuCostResCh := ctx.Query(queryHistoricalGPUCost)
  713. cpuCostRes, _ := cpuCostResCh.Await()
  714. ramCostRes, _ := ramCostResCh.Await()
  715. gpuCostRes, _ := gpuCostResCh.Await()
  716. if ctx.HasErrors() {
  717. return ctx.ErrorCollection()
  718. }
  719. cpuCosts, err := getCost(cpuCostRes)
  720. if err != nil {
  721. return err
  722. }
  723. ramCosts, err := getCost(ramCostRes)
  724. if err != nil {
  725. return err
  726. }
  727. gpuCosts, err := getCost(gpuCostRes)
  728. if err != nil {
  729. return err
  730. }
  731. if len(cpuCosts) == 0 {
  732. log.Infof("Kubecost prometheus metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  733. }
  734. for node, costv := range cpuCosts {
  735. if _, ok := missingNodes[node]; ok {
  736. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  737. } else {
  738. log.DedupedWarningf(5, "Node `%s` in prometheus but not k8s api", node)
  739. }
  740. }
  741. for node, costv := range ramCosts {
  742. if _, ok := missingNodes[node]; ok {
  743. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  744. }
  745. }
  746. for node, costv := range gpuCosts {
  747. if _, ok := missingNodes[node]; ok {
  748. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  749. }
  750. }
  751. }
  752. return nil
  753. }
  754. // getContainerAllocation takes the max between request and usage. This function
  755. // returns a slice containing a single element describing the container's
  756. // allocation.
  757. //
  758. // Additionally, the timestamp of the allocation will be the highest value
  759. // timestamp between the two vectors. This mitigates situations where
  760. // Timestamp=0. This should have no effect on the metrics emitted by the
  761. // CostModelMetricsEmitter
  762. func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
  763. var result []*util.Vector
  764. if req != nil && used != nil {
  765. x1 := req.Value
  766. if math.IsNaN(x1) {
  767. log.Warnf("NaN value found during %s allocation calculation for requests.", allocationType)
  768. x1 = 0.0
  769. }
  770. y1 := used.Value
  771. if math.IsNaN(y1) {
  772. log.Warnf("NaN value found during %s allocation calculation for used.", allocationType)
  773. y1 = 0.0
  774. }
  775. result = []*util.Vector{
  776. {
  777. Value: math.Max(x1, y1),
  778. Timestamp: math.Max(req.Timestamp, used.Timestamp),
  779. },
  780. }
  781. if result[0].Value == 0 && result[0].Timestamp == 0 {
  782. log.Warnf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  783. }
  784. } else if req != nil {
  785. result = []*util.Vector{
  786. {
  787. Value: req.Value,
  788. Timestamp: req.Timestamp,
  789. },
  790. }
  791. } else if used != nil {
  792. result = []*util.Vector{
  793. {
  794. Value: used.Value,
  795. Timestamp: used.Timestamp,
  796. },
  797. }
  798. } else {
  799. log.Warnf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  800. result = []*util.Vector{
  801. {
  802. Value: 0,
  803. Timestamp: float64(time.Now().UTC().Unix()),
  804. },
  805. }
  806. }
  807. return result
  808. }
  809. func addPVData(cache clustercache.ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  810. cfg, err := cloud.GetConfig()
  811. if err != nil {
  812. return err
  813. }
  814. // Pull a region from the first node
  815. var defaultRegion string
  816. nodeList := cache.GetAllNodes()
  817. if len(nodeList) > 0 {
  818. defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
  819. }
  820. storageClasses := cache.GetAllStorageClasses()
  821. storageClassMap := make(map[string]map[string]string)
  822. for _, storageClass := range storageClasses {
  823. params := storageClass.Parameters
  824. storageClassMap[storageClass.ObjectMeta.Name] = params
  825. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  826. storageClassMap["default"] = params
  827. storageClassMap[""] = params
  828. }
  829. }
  830. pvs := cache.GetAllPersistentVolumes()
  831. pvMap := make(map[string]*costAnalyzerCloud.PV)
  832. for _, pv := range pvs {
  833. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  834. if !ok {
  835. log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  836. }
  837. var region string
  838. if r, ok := util.GetRegion(pv.Labels); ok {
  839. region = r
  840. } else {
  841. region = defaultRegion
  842. }
  843. cacPv := &costAnalyzerCloud.PV{
  844. Class: pv.Spec.StorageClassName,
  845. Region: region,
  846. Parameters: parameters,
  847. }
  848. err := GetPVCost(cacPv, pv, cloud, region)
  849. if err != nil {
  850. return err
  851. }
  852. pvMap[pv.Name] = cacPv
  853. }
  854. for _, pvc := range pvClaimMapping {
  855. if vol, ok := pvMap[pvc.VolumeName]; ok {
  856. pvc.Volume = vol
  857. } else {
  858. log.Debugf("PV not found, using default")
  859. pvc.Volume = &costAnalyzerCloud.PV{
  860. Cost: cfg.Storage,
  861. }
  862. }
  863. }
  864. return nil
  865. }
  866. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cp costAnalyzerCloud.Provider, defaultRegion string) error {
  867. cfg, err := cp.GetConfig()
  868. if err != nil {
  869. return err
  870. }
  871. key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
  872. pv.ProviderID = key.ID()
  873. pvWithCost, err := cp.PVPricing(key)
  874. if err != nil {
  875. pv.Cost = cfg.Storage
  876. return err
  877. }
  878. if pvWithCost == nil || pvWithCost.Cost == "" {
  879. pv.Cost = cfg.Storage
  880. return nil // set default cost
  881. }
  882. pv.Cost = pvWithCost.Cost
  883. return nil
  884. }
  885. func (cm *CostModel) GetPricingSourceCounts() (*costAnalyzerCloud.PricingMatchMetadata, error) {
  886. if cm.pricingMetadata != nil {
  887. return cm.pricingMetadata, nil
  888. } else {
  889. return nil, fmt.Errorf("Node costs not yet calculated")
  890. }
  891. }
  892. func (cm *CostModel) GetNodeCost(cp costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  893. cfg, err := cp.GetConfig()
  894. if err != nil {
  895. return nil, err
  896. }
  897. nodeList := cm.Cache.GetAllNodes()
  898. nodes := make(map[string]*costAnalyzerCloud.Node)
  899. vgpuCount, err := getAllocatableVGPUs(cm.Cache)
  900. if err != nil {
  901. return nil, err
  902. }
  903. vgpuCoeff := 10.0
  904. if vgpuCount > 0.0 {
  905. vgpuCoeff = vgpuCount
  906. }
  907. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  908. TotalNodes: 0,
  909. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  910. }
  911. for _, n := range nodeList {
  912. name := n.GetObjectMeta().GetName()
  913. nodeLabels := n.GetObjectMeta().GetLabels()
  914. nodeLabels["providerID"] = n.Spec.ProviderID
  915. pmd.TotalNodes++
  916. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  917. if err != nil {
  918. log.Infof("Error getting node pricing. Error: %s", err.Error())
  919. if cnode != nil {
  920. nodes[name] = cnode
  921. continue
  922. } else {
  923. cnode = &costAnalyzerCloud.Node{
  924. VCPUCost: cfg.CPU,
  925. RAMCost: cfg.RAM,
  926. }
  927. }
  928. }
  929. if _, ok := pmd.PricingTypeCounts[cnode.PricingType]; ok {
  930. pmd.PricingTypeCounts[cnode.PricingType]++
  931. } else {
  932. pmd.PricingTypeCounts[cnode.PricingType] = 1
  933. }
  934. newCnode := *cnode
  935. if newCnode.InstanceType == "" {
  936. it, _ := util.GetInstanceType(n.Labels)
  937. newCnode.InstanceType = it
  938. }
  939. if newCnode.Region == "" {
  940. region, _ := util.GetRegion(n.Labels)
  941. newCnode.Region = region
  942. }
  943. if newCnode.ArchType == "" {
  944. arch, _ := util.GetArchType(n.Labels)
  945. newCnode.ArchType = arch
  946. }
  947. newCnode.ProviderID = n.Spec.ProviderID
  948. var cpu float64
  949. if newCnode.VCPU == "" {
  950. cpu = float64(n.Status.Capacity.Cpu().Value())
  951. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  952. } else {
  953. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  954. if err != nil {
  955. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  956. }
  957. }
  958. if math.IsNaN(cpu) {
  959. log.Warnf("cpu parsed as NaN. Setting to 0.")
  960. cpu = 0
  961. }
  962. var ram float64
  963. if newCnode.RAM == "" {
  964. newCnode.RAM = n.Status.Capacity.Memory().String()
  965. }
  966. ram = float64(n.Status.Capacity.Memory().Value())
  967. if math.IsNaN(ram) {
  968. log.Warnf("ram parsed as NaN. Setting to 0.")
  969. ram = 0
  970. }
  971. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  972. // Azure does not seem to provide a GPU count in its pricing API. GKE supports attaching multiple GPUs
  973. // So the k8s api will often report more accurate results for GPU count under status > capacity > nvidia.com/gpu than the cloud providers billing data
  974. // not all providers are guaranteed to use this, so don't overwrite a Provider assignment if we can't find something under that capacity exists
  975. gpuc := 0.0
  976. q, ok := n.Status.Capacity["nvidia.com/gpu"]
  977. if ok {
  978. gpuCount := q.Value()
  979. if gpuCount != 0 {
  980. newCnode.GPU = fmt.Sprintf("%d", gpuCount)
  981. gpuc = float64(gpuCount)
  982. }
  983. } else if g, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  984. gpuCount := g.Value()
  985. if gpuCount != 0 {
  986. newCnode.GPU = fmt.Sprintf("%d", int(float64(gpuCount)/vgpuCoeff))
  987. gpuc = float64(gpuCount) / vgpuCoeff
  988. }
  989. } else {
  990. gpuc, err = strconv.ParseFloat(newCnode.GPU, 64)
  991. if err != nil {
  992. gpuc = 0.0
  993. }
  994. }
  995. if math.IsNaN(gpuc) {
  996. log.Warnf("gpu count parsed as NaN. Setting to 0.")
  997. gpuc = 0.0
  998. }
  999. if newCnode.GPU != "" && newCnode.GPUCost == "" {
  1000. // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  1001. log.Infof("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1002. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1003. if err != nil {
  1004. log.Errorf("Could not parse default cpu price")
  1005. defaultCPU = 0
  1006. }
  1007. if math.IsNaN(defaultCPU) {
  1008. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1009. defaultCPU = 0
  1010. }
  1011. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1012. if err != nil {
  1013. log.Errorf("Could not parse default ram price")
  1014. defaultRAM = 0
  1015. }
  1016. if math.IsNaN(defaultRAM) {
  1017. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1018. defaultRAM = 0
  1019. }
  1020. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  1021. if err != nil {
  1022. log.Errorf("Could not parse default gpu price")
  1023. defaultGPU = 0
  1024. }
  1025. if math.IsNaN(defaultGPU) {
  1026. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  1027. defaultGPU = 0
  1028. }
  1029. cpuToRAMRatio := defaultCPU / defaultRAM
  1030. if math.IsNaN(cpuToRAMRatio) {
  1031. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1032. cpuToRAMRatio = 10
  1033. }
  1034. gpuToRAMRatio := defaultGPU / defaultRAM
  1035. if math.IsNaN(gpuToRAMRatio) {
  1036. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  1037. gpuToRAMRatio = 100
  1038. }
  1039. ramGB := ram / 1024 / 1024 / 1024
  1040. if math.IsNaN(ramGB) {
  1041. log.Warnf("ramGB is NaN. Setting to 0.")
  1042. ramGB = 0
  1043. }
  1044. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  1045. if math.IsNaN(ramMultiple) {
  1046. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1047. ramMultiple = 0
  1048. }
  1049. var nodePrice float64
  1050. if newCnode.Cost != "" {
  1051. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1052. if err != nil {
  1053. log.Errorf("Could not parse total node price")
  1054. return nil, err
  1055. }
  1056. } else if newCnode.VCPUCost != "" {
  1057. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1058. if err != nil {
  1059. log.Errorf("Could not parse node vcpu price")
  1060. return nil, err
  1061. }
  1062. } else { // add case to use default pricing model when API data fails.
  1063. log.Debugf("No node price or CPUprice found, falling back to default")
  1064. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  1065. }
  1066. if math.IsNaN(nodePrice) {
  1067. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1068. nodePrice = 0
  1069. }
  1070. ramPrice := (nodePrice / ramMultiple)
  1071. if math.IsNaN(ramPrice) {
  1072. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1073. ramPrice = 0
  1074. }
  1075. cpuPrice := ramPrice * cpuToRAMRatio
  1076. gpuPrice := ramPrice * gpuToRAMRatio
  1077. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1078. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1079. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1080. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1081. } else if newCnode.RAMCost == "" {
  1082. // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  1083. log.Debugf("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1084. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1085. if err != nil {
  1086. log.Warnf("Could not parse default cpu price")
  1087. defaultCPU = 0
  1088. }
  1089. if math.IsNaN(defaultCPU) {
  1090. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1091. defaultCPU = 0
  1092. }
  1093. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1094. if err != nil {
  1095. log.Warnf("Could not parse default ram price")
  1096. defaultRAM = 0
  1097. }
  1098. if math.IsNaN(defaultRAM) {
  1099. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1100. defaultRAM = 0
  1101. }
  1102. cpuToRAMRatio := defaultCPU / defaultRAM
  1103. if math.IsNaN(cpuToRAMRatio) {
  1104. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1105. cpuToRAMRatio = 10
  1106. }
  1107. ramGB := ram / 1024 / 1024 / 1024
  1108. if math.IsNaN(ramGB) {
  1109. log.Warnf("ramGB is NaN. Setting to 0.")
  1110. ramGB = 0
  1111. }
  1112. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1113. if math.IsNaN(ramMultiple) {
  1114. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1115. ramMultiple = 0
  1116. }
  1117. var nodePrice float64
  1118. if newCnode.Cost != "" {
  1119. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1120. if err != nil {
  1121. log.Warnf("Could not parse total node price")
  1122. return nil, err
  1123. }
  1124. if newCnode.GPUCost != "" {
  1125. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1126. if err != nil {
  1127. log.Warnf("Could not parse node gpu price")
  1128. return nil, err
  1129. }
  1130. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1131. }
  1132. } else if newCnode.VCPUCost != "" {
  1133. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1134. if err != nil {
  1135. log.Warnf("Could not parse node vcpu price")
  1136. return nil, err
  1137. }
  1138. } else { // add case to use default pricing model when API data fails.
  1139. log.Debugf("No node price or CPUprice found, falling back to default")
  1140. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1141. }
  1142. if math.IsNaN(nodePrice) {
  1143. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1144. nodePrice = 0
  1145. }
  1146. ramPrice := (nodePrice / ramMultiple)
  1147. if math.IsNaN(ramPrice) {
  1148. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1149. ramPrice = 0
  1150. }
  1151. cpuPrice := ramPrice * cpuToRAMRatio
  1152. if defaultRAM != 0 {
  1153. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1154. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1155. } else { // just assign the full price to CPU
  1156. if cpu != 0 {
  1157. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1158. } else {
  1159. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1160. }
  1161. }
  1162. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1163. log.Debugf("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1164. }
  1165. nodes[name] = &newCnode
  1166. }
  1167. cm.pricingMetadata = pmd
  1168. cp.ApplyReservedInstancePricing(nodes)
  1169. return nodes, nil
  1170. }
  1171. // TODO: drop some logs
  1172. func (cm *CostModel) GetLBCost(cp costAnalyzerCloud.Provider) (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1173. // for fetching prices from cloud provider
  1174. // cfg, err := cp.GetConfig()
  1175. // if err != nil {
  1176. // return nil, err
  1177. // }
  1178. servicesList := cm.Cache.GetAllServices()
  1179. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1180. for _, service := range servicesList {
  1181. namespace := service.GetObjectMeta().GetNamespace()
  1182. name := service.GetObjectMeta().GetName()
  1183. key := serviceKey{
  1184. Cluster: env.GetClusterID(),
  1185. Namespace: namespace,
  1186. Service: name,
  1187. }
  1188. if service.Spec.Type == "LoadBalancer" {
  1189. loadBalancer, err := cp.LoadBalancerPricing()
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. newLoadBalancer := *loadBalancer
  1194. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1195. address := loadBalancerIngress.IP
  1196. // Some cloud providers use hostname rather than IP
  1197. if address == "" {
  1198. address = loadBalancerIngress.Hostname
  1199. }
  1200. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1201. }
  1202. loadBalancerMap[key] = &newLoadBalancer
  1203. }
  1204. }
  1205. return loadBalancerMap, nil
  1206. }
  1207. func getPodServices(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1208. servicesList := cache.GetAllServices()
  1209. podServicesMapping := make(map[string]map[string][]string)
  1210. for _, service := range servicesList {
  1211. namespace := service.GetObjectMeta().GetNamespace()
  1212. name := service.GetObjectMeta().GetName()
  1213. key := namespace + "," + clusterID
  1214. if _, ok := podServicesMapping[key]; !ok {
  1215. podServicesMapping[key] = make(map[string][]string)
  1216. }
  1217. s := labels.Nothing()
  1218. if service.Spec.Selector != nil && len(service.Spec.Selector) > 0 {
  1219. s = labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  1220. }
  1221. for _, pod := range podList {
  1222. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1223. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1224. services, ok := podServicesMapping[key][pod.GetObjectMeta().GetName()]
  1225. if ok {
  1226. podServicesMapping[key][pod.GetObjectMeta().GetName()] = append(services, name)
  1227. } else {
  1228. podServicesMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1229. }
  1230. }
  1231. }
  1232. }
  1233. return podServicesMapping, nil
  1234. }
  1235. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1236. ssList := cache.GetAllStatefulSets()
  1237. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1238. for _, ss := range ssList {
  1239. namespace := ss.GetObjectMeta().GetNamespace()
  1240. name := ss.GetObjectMeta().GetName()
  1241. key := namespace + "," + clusterID
  1242. if _, ok := podSSMapping[key]; !ok {
  1243. podSSMapping[key] = make(map[string][]string)
  1244. }
  1245. s, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  1246. if err != nil {
  1247. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1248. }
  1249. for _, pod := range podList {
  1250. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1251. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1252. sss, ok := podSSMapping[key][pod.GetObjectMeta().GetName()]
  1253. if ok {
  1254. podSSMapping[key][pod.GetObjectMeta().GetName()] = append(sss, name)
  1255. } else {
  1256. podSSMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1257. }
  1258. }
  1259. }
  1260. }
  1261. return podSSMapping, nil
  1262. }
  1263. func getPodDeployments(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1264. deploymentsList := cache.GetAllDeployments()
  1265. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1266. for _, deployment := range deploymentsList {
  1267. namespace := deployment.GetObjectMeta().GetNamespace()
  1268. name := deployment.GetObjectMeta().GetName()
  1269. key := namespace + "," + clusterID
  1270. if _, ok := podDeploymentsMapping[key]; !ok {
  1271. podDeploymentsMapping[key] = make(map[string][]string)
  1272. }
  1273. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1274. if err != nil {
  1275. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1276. }
  1277. for _, pod := range podList {
  1278. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1279. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1280. deployments, ok := podDeploymentsMapping[key][pod.GetObjectMeta().GetName()]
  1281. if ok {
  1282. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1283. } else {
  1284. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1285. }
  1286. }
  1287. }
  1288. }
  1289. return podDeploymentsMapping, nil
  1290. }
  1291. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1292. podDeploymentsMapping := make(map[string]map[string][]string)
  1293. for depKey, depLabels := range deploymentLabels {
  1294. kt, err := NewKeyTuple(depKey)
  1295. if err != nil {
  1296. continue
  1297. }
  1298. namespace := kt.Namespace()
  1299. name := kt.Key()
  1300. clusterID := kt.ClusterID()
  1301. key := namespace + "," + clusterID
  1302. if _, ok := podDeploymentsMapping[key]; !ok {
  1303. podDeploymentsMapping[key] = make(map[string][]string)
  1304. }
  1305. s := labels.Set(depLabels).AsSelectorPreValidated()
  1306. for podKey, pLabels := range podLabels {
  1307. pkey, err := NewKeyTuple(podKey)
  1308. if err != nil {
  1309. continue
  1310. }
  1311. podNamespace := pkey.Namespace()
  1312. podName := pkey.Key()
  1313. podClusterID := pkey.ClusterID()
  1314. labelSet := labels.Set(pLabels)
  1315. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1316. deployments, ok := podDeploymentsMapping[key][podName]
  1317. if ok {
  1318. podDeploymentsMapping[key][podName] = append(deployments, name)
  1319. } else {
  1320. podDeploymentsMapping[key][podName] = []string{name}
  1321. }
  1322. }
  1323. }
  1324. }
  1325. // Remove any duplicate data created by metric names
  1326. pruneDuplicateData(podDeploymentsMapping)
  1327. return podDeploymentsMapping, nil
  1328. }
  1329. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1330. podServicesMapping := make(map[string]map[string][]string)
  1331. for servKey, servLabels := range serviceLabels {
  1332. kt, err := NewKeyTuple(servKey)
  1333. if err != nil {
  1334. continue
  1335. }
  1336. namespace := kt.Namespace()
  1337. name := kt.Key()
  1338. clusterID := kt.ClusterID()
  1339. key := namespace + "," + clusterID
  1340. if _, ok := podServicesMapping[key]; !ok {
  1341. podServicesMapping[key] = make(map[string][]string)
  1342. }
  1343. s := labels.Nothing()
  1344. if servLabels != nil && len(servLabels) > 0 {
  1345. s = labels.Set(servLabels).AsSelectorPreValidated()
  1346. }
  1347. for podKey, pLabels := range podLabels {
  1348. pkey, err := NewKeyTuple(podKey)
  1349. if err != nil {
  1350. continue
  1351. }
  1352. podNamespace := pkey.Namespace()
  1353. podName := pkey.Key()
  1354. podClusterID := pkey.ClusterID()
  1355. labelSet := labels.Set(pLabels)
  1356. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1357. services, ok := podServicesMapping[key][podName]
  1358. if ok {
  1359. podServicesMapping[key][podName] = append(services, name)
  1360. } else {
  1361. podServicesMapping[key][podName] = []string{name}
  1362. }
  1363. }
  1364. }
  1365. }
  1366. // Remove any duplicate data created by metric names
  1367. pruneDuplicateData(podServicesMapping)
  1368. return podServicesMapping, nil
  1369. }
  1370. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1371. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1372. // the '_' version. Not optimal, but takes care of the issue
  1373. func pruneDuplicateData(data map[string]map[string][]string) {
  1374. for _, podMap := range data {
  1375. for podName, values := range podMap {
  1376. podMap[podName] = pruneDuplicates(values)
  1377. }
  1378. }
  1379. }
  1380. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1381. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1382. // original value in the new slice.
  1383. func pruneDuplicates(s []string) []string {
  1384. m := sliceToSet(s)
  1385. for _, v := range s {
  1386. if strings.Contains(v, "_") {
  1387. name := strings.Replace(v, "_", "-", -1)
  1388. if !m[name] {
  1389. m[name] = true
  1390. }
  1391. delete(m, v)
  1392. }
  1393. }
  1394. return setToSlice(m)
  1395. }
  1396. // Creates a map[string]bool containing the slice values as keys
  1397. func sliceToSet(s []string) map[string]bool {
  1398. m := make(map[string]bool)
  1399. for _, v := range s {
  1400. m[v] = true
  1401. }
  1402. return m
  1403. }
  1404. func setToSlice(m map[string]bool) []string {
  1405. var result []string
  1406. for k := range m {
  1407. result = append(result, k)
  1408. }
  1409. return result
  1410. }
  1411. func costDataPassesFilters(cm clusters.ClusterMap, costs *CostData, namespace string, cluster string) bool {
  1412. passesNamespace := namespace == "" || costs.Namespace == namespace
  1413. passesCluster := cluster == "" || costs.ClusterID == cluster || costs.ClusterName == cluster
  1414. return passesNamespace && passesCluster
  1415. }
  1416. // Finds the a closest multiple less than value
  1417. func floorMultiple(value int64, multiple int64) int64 {
  1418. return (value / multiple) * multiple
  1419. }
  1420. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1421. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1422. func requestKeyFor(window kubecost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) string {
  1423. keyLayout := "2006-01-02T15:04Z"
  1424. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1425. // applying a snapped duration to a snapped start time.
  1426. durMins := int64(window.Minutes())
  1427. durMins = floorMultiple(durMins, 5)
  1428. sMins := int64(window.Start().Minute())
  1429. sOffset := sMins - floorMultiple(sMins, 5)
  1430. sTime := window.Start().Add(-time.Duration(sOffset) * time.Minute)
  1431. eTime := window.Start().Add(time.Duration(durMins) * time.Minute)
  1432. startKey := sTime.Format(keyLayout)
  1433. endKey := eTime.Format(keyLayout)
  1434. return fmt.Sprintf("%s,%s,%s,%s,%s,%t", startKey, endKey, resolution.String(), filterNamespace, filterCluster, remoteEnabled)
  1435. }
  1436. // ComputeCostDataRange executes a range query for cost data.
  1437. // Note that "offset" represents the time between the function call and "endString", and is also passed for convenience
  1438. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window kubecost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1439. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1440. // for the specific inputs to prevent multiple queries for identical data.
  1441. key := requestKeyFor(window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1442. log.Debugf("ComputeCostDataRange with Key: %s", key)
  1443. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1444. // Otherwise, start executing.
  1445. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1446. return cm.costDataRange(cli, cp, window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1447. })
  1448. data, ok := result.(map[string]*CostData)
  1449. if !ok {
  1450. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1451. }
  1452. return data, err
  1453. }
  1454. func (cm *CostModel) costDataRange(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window kubecost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1455. clusterID := env.GetClusterID()
  1456. // durHrs := end.Sub(start).Hours() + 1
  1457. if window.IsOpen() {
  1458. return nil, fmt.Errorf("illegal window: %s", window)
  1459. }
  1460. start := *window.Start()
  1461. end := *window.End()
  1462. // Snap resolution to the nearest minute
  1463. resMins := int64(math.Trunc(resolution.Minutes()))
  1464. if resMins == 0 {
  1465. return nil, fmt.Errorf("resolution must be greater than 0.0")
  1466. }
  1467. resolution = time.Duration(resMins) * time.Minute
  1468. // Warn if resolution does not evenly divide window
  1469. if int64(window.Minutes())%int64(resolution.Minutes()) != 0 {
  1470. log.Warnf("CostDataRange: window should be divisible by resolution or else samples may be missed: %s %% %s = %dm", window, resolution, int64(window.Minutes())%int64(resolution.Minutes()))
  1471. }
  1472. // Convert to Prometheus-style duration string in terms of m or h
  1473. resStr := fmt.Sprintf("%dm", resMins)
  1474. if resMins%60 == 0 {
  1475. resStr = fmt.Sprintf("%dh", resMins/60)
  1476. }
  1477. if remoteEnabled {
  1478. remoteLayout := "2006-01-02T15:04:05Z"
  1479. remoteStartStr := window.Start().Format(remoteLayout)
  1480. remoteEndStr := window.End().Format(remoteLayout)
  1481. log.Infof("Using remote database for query from %s to %s with window %s", remoteStartStr, remoteEndStr, resolution)
  1482. return CostDataRangeFromSQL("", "", resolution.String(), remoteStartStr, remoteEndStr)
  1483. }
  1484. scrapeIntervalSeconds := cm.ScrapeInterval.Seconds()
  1485. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataRangeContextName)
  1486. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1487. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1488. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1489. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1490. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1491. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1492. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, env.GetPromClusterFilter(), resStr, "", resolution.Hours(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1493. queryPVRequests := fmt.Sprintf(queryPVRequestsStr, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1494. queryPVCAllocation := fmt.Sprintf(queryPVCAllocationFmt, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1495. queryPVHourlyCost := fmt.Sprintf(queryPVHourlyCostFmt, env.GetPromClusterFilter(), resStr)
  1496. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1497. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1498. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1499. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), resStr, "")
  1500. // Submit all queries for concurrent evaluation
  1501. resChRAMRequests := ctx.QueryRange(queryRAMRequests, start, end, resolution)
  1502. resChRAMUsage := ctx.QueryRange(queryRAMUsage, start, end, resolution)
  1503. resChRAMAlloc := ctx.QueryRange(queryRAMAlloc, start, end, resolution)
  1504. resChCPURequests := ctx.QueryRange(queryCPURequests, start, end, resolution)
  1505. resChCPUUsage := ctx.QueryRange(queryCPUUsage, start, end, resolution)
  1506. resChCPUAlloc := ctx.QueryRange(queryCPUAlloc, start, end, resolution)
  1507. resChGPURequests := ctx.QueryRange(queryGPURequests, start, end, resolution)
  1508. resChPVRequests := ctx.QueryRange(queryPVRequests, start, end, resolution)
  1509. resChPVCAlloc := ctx.QueryRange(queryPVCAllocation, start, end, resolution)
  1510. resChPVHourlyCost := ctx.QueryRange(queryPVHourlyCost, start, end, resolution)
  1511. resChNetZoneRequests := ctx.QueryRange(queryNetZoneRequests, start, end, resolution)
  1512. resChNetRegionRequests := ctx.QueryRange(queryNetRegionRequests, start, end, resolution)
  1513. resChNetInternetRequests := ctx.QueryRange(queryNetInternetRequests, start, end, resolution)
  1514. resChNSLabels := ctx.QueryRange(fmt.Sprintf(queryNSLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1515. resChPodLabels := ctx.QueryRange(fmt.Sprintf(queryPodLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1516. resChNSAnnotations := ctx.QueryRange(fmt.Sprintf(queryNSAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1517. resChPodAnnotations := ctx.QueryRange(fmt.Sprintf(queryPodAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1518. resChServiceLabels := ctx.QueryRange(fmt.Sprintf(queryServiceLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1519. resChDeploymentLabels := ctx.QueryRange(fmt.Sprintf(queryDeploymentLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1520. resChStatefulsetLabels := ctx.QueryRange(fmt.Sprintf(queryStatefulsetLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1521. resChJobs := ctx.QueryRange(fmt.Sprintf(queryPodJobs, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1522. resChDaemonsets := ctx.QueryRange(fmt.Sprintf(queryPodDaemonsets, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1523. resChNormalization := ctx.QueryRange(queryNormalization, start, end, resolution)
  1524. // Pull k8s pod, controller, service, and namespace details
  1525. podlist := cm.Cache.GetAllPods()
  1526. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  1527. if err != nil {
  1528. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1529. }
  1530. podStatefulsetsMapping, err := getPodStatefulsets(cm.Cache, podlist, clusterID)
  1531. if err != nil {
  1532. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1533. }
  1534. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  1535. if err != nil {
  1536. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1537. }
  1538. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  1539. if err != nil {
  1540. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1541. }
  1542. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  1543. if err != nil {
  1544. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1545. }
  1546. // Process query results. Handle errors afterwards using ctx.Errors.
  1547. resRAMRequests, _ := resChRAMRequests.Await()
  1548. resRAMUsage, _ := resChRAMUsage.Await()
  1549. resRAMAlloc, _ := resChRAMAlloc.Await()
  1550. resCPURequests, _ := resChCPURequests.Await()
  1551. resCPUUsage, _ := resChCPUUsage.Await()
  1552. resCPUAlloc, _ := resChCPUAlloc.Await()
  1553. resGPURequests, _ := resChGPURequests.Await()
  1554. resPVRequests, _ := resChPVRequests.Await()
  1555. resPVCAlloc, _ := resChPVCAlloc.Await()
  1556. resPVHourlyCost, _ := resChPVHourlyCost.Await()
  1557. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  1558. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  1559. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  1560. resNSLabels, _ := resChNSLabels.Await()
  1561. resPodLabels, _ := resChPodLabels.Await()
  1562. resNSAnnotations, _ := resChNSAnnotations.Await()
  1563. resPodAnnotations, _ := resChPodAnnotations.Await()
  1564. resServiceLabels, _ := resChServiceLabels.Await()
  1565. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  1566. resStatefulsetLabels, _ := resChStatefulsetLabels.Await()
  1567. resDaemonsets, _ := resChDaemonsets.Await()
  1568. resJobs, _ := resChJobs.Await()
  1569. resNormalization, _ := resChNormalization.Await()
  1570. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  1571. // NOTE: will not propagate unless coupled with errors.
  1572. if ctx.HasErrors() {
  1573. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  1574. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  1575. for _, promErr := range ctx.Errors() {
  1576. if promErr.Error != nil {
  1577. log.Errorf("CostDataRange: Request Error: %s", promErr.Error)
  1578. }
  1579. if promErr.ParseError != nil {
  1580. log.Errorf("CostDataRange: Parsing Error: %s", promErr.ParseError)
  1581. }
  1582. }
  1583. // ErrorCollection is an collection of errors wrapped in a single error implementation
  1584. return nil, ctx.ErrorCollection()
  1585. }
  1586. normalizationValue, err := getNormalizations(resNormalization)
  1587. if err != nil {
  1588. msg := fmt.Sprintf("error computing normalization for start=%s, end=%s, res=%s", start, end, resolution)
  1589. return nil, prom.WrapError(err, msg)
  1590. }
  1591. pvClaimMapping, err := GetPVInfo(resPVRequests, clusterID)
  1592. if err != nil {
  1593. // Just log for compatibility with KSM less than 1.6
  1594. log.Infof("Unable to get PV Data: %s", err.Error())
  1595. }
  1596. if pvClaimMapping != nil {
  1597. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1598. if err != nil {
  1599. return nil, fmt.Errorf("pvClaimMapping: %s", err)
  1600. }
  1601. }
  1602. pvCostMapping, err := GetPVCostMetrics(resPVHourlyCost, clusterID)
  1603. if err != nil {
  1604. log.Errorf("Unable to get PV Hourly Cost Data: %s", err.Error())
  1605. }
  1606. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  1607. pvAllocationMapping, err := GetPVAllocationMetrics(resPVCAlloc, clusterID)
  1608. if err != nil {
  1609. log.Errorf("Unable to get PV Allocation Cost Data: %s", err.Error())
  1610. }
  1611. if pvAllocationMapping != nil {
  1612. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1613. for k, v := range pvAllocationMapping {
  1614. unmountedPVs[k] = v
  1615. }
  1616. }
  1617. nsLabels, err := GetNamespaceLabelsMetrics(resNSLabels, clusterID)
  1618. if err != nil {
  1619. log.Errorf("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1620. }
  1621. if nsLabels != nil {
  1622. mergeStringMap(namespaceLabelsMapping, nsLabels)
  1623. }
  1624. podLabels, err := GetPodLabelsMetrics(resPodLabels, clusterID)
  1625. if err != nil {
  1626. log.Errorf("Unable to get Pod Labels for Metrics: %s", err.Error())
  1627. }
  1628. nsAnnotations, err := GetNamespaceAnnotationsMetrics(resNSAnnotations, clusterID)
  1629. if err != nil {
  1630. log.Errorf("Unable to get Namespace Annotations for Metrics: %s", err.Error())
  1631. }
  1632. if nsAnnotations != nil {
  1633. mergeStringMap(namespaceAnnotationsMapping, nsAnnotations)
  1634. }
  1635. podAnnotations, err := GetPodAnnotationsMetrics(resPodAnnotations, clusterID)
  1636. if err != nil {
  1637. log.Errorf("Unable to get Pod Annotations for Metrics: %s", err.Error())
  1638. }
  1639. serviceLabels, err := GetServiceSelectorLabelsMetrics(resServiceLabels, clusterID)
  1640. if err != nil {
  1641. log.Errorf("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1642. }
  1643. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(resDeploymentLabels, clusterID)
  1644. if err != nil {
  1645. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1646. }
  1647. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(resStatefulsetLabels, clusterID)
  1648. if err != nil {
  1649. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1650. }
  1651. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1652. if err != nil {
  1653. log.Errorf("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1654. }
  1655. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1656. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1657. if err != nil {
  1658. log.Errorf("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1659. }
  1660. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1661. podDaemonsets, err := GetPodDaemonsetsWithMetrics(resDaemonsets, clusterID)
  1662. if err != nil {
  1663. log.Errorf("Unable to get Pod Daemonsets for Metrics: %s", err.Error())
  1664. }
  1665. podJobs, err := GetPodJobsWithMetrics(resJobs, clusterID)
  1666. if err != nil {
  1667. log.Errorf("Unable to get Pod Jobs for Metrics: %s", err.Error())
  1668. }
  1669. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1670. if err != nil {
  1671. log.Errorf("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1672. }
  1673. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1674. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  1675. if err != nil {
  1676. log.Errorf("Unable to get Network Cost Data: %s", err.Error())
  1677. networkUsageMap = make(map[string]*NetworkUsageData)
  1678. }
  1679. containerNameCost := make(map[string]*CostData)
  1680. containers := make(map[string]bool)
  1681. otherClusterPVRecorded := make(map[string]bool)
  1682. RAMReqMap, err := GetNormalizedContainerMetricVectors(resRAMRequests, normalizationValue, clusterID)
  1683. if err != nil {
  1684. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMRequests)")
  1685. }
  1686. for key := range RAMReqMap {
  1687. containers[key] = true
  1688. }
  1689. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resRAMUsage, normalizationValue, clusterID)
  1690. if err != nil {
  1691. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMUsage)")
  1692. }
  1693. for key := range RAMUsedMap {
  1694. containers[key] = true
  1695. }
  1696. CPUReqMap, err := GetNormalizedContainerMetricVectors(resCPURequests, normalizationValue, clusterID)
  1697. if err != nil {
  1698. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(CPURequests)")
  1699. }
  1700. for key := range CPUReqMap {
  1701. containers[key] = true
  1702. }
  1703. // No need to normalize here, as this comes from a counter, namely:
  1704. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1705. CPUUsedMap, err := GetContainerMetricVectors(resCPUUsage, clusterID)
  1706. if err != nil {
  1707. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUUsage)")
  1708. }
  1709. for key := range CPUUsedMap {
  1710. containers[key] = true
  1711. }
  1712. RAMAllocMap, err := GetContainerMetricVectors(resRAMAlloc, clusterID)
  1713. if err != nil {
  1714. return nil, prom.WrapError(err, "GetContainerMetricVectors(RAMAllocations)")
  1715. }
  1716. for key := range RAMAllocMap {
  1717. containers[key] = true
  1718. }
  1719. CPUAllocMap, err := GetContainerMetricVectors(resCPUAlloc, clusterID)
  1720. if err != nil {
  1721. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUAllocations)")
  1722. }
  1723. for key := range CPUAllocMap {
  1724. containers[key] = true
  1725. }
  1726. GPUReqMap, err := GetNormalizedContainerMetricVectors(resGPURequests, normalizationValue, clusterID)
  1727. if err != nil {
  1728. return nil, prom.WrapError(err, "GetContainerMetricVectors(GPURequests)")
  1729. }
  1730. for key := range GPUReqMap {
  1731. containers[key] = true
  1732. }
  1733. // Request metrics can show up after pod eviction and completion.
  1734. // This method synchronizes requests to allocations such that when
  1735. // allocation is 0, so are requests
  1736. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1737. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1738. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1739. missingContainers := make(map[string]*CostData)
  1740. for key := range containers {
  1741. if _, ok := containerNameCost[key]; ok {
  1742. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1743. }
  1744. c, _ := NewContainerMetricFromKey(key)
  1745. RAMReqV, ok := RAMReqMap[key]
  1746. if !ok {
  1747. log.Debug("no RAM requests for " + key)
  1748. RAMReqV = []*util.Vector{}
  1749. }
  1750. RAMUsedV, ok := RAMUsedMap[key]
  1751. if !ok {
  1752. log.Debug("no RAM usage for " + key)
  1753. RAMUsedV = []*util.Vector{}
  1754. }
  1755. CPUReqV, ok := CPUReqMap[key]
  1756. if !ok {
  1757. log.Debug("no CPU requests for " + key)
  1758. CPUReqV = []*util.Vector{}
  1759. }
  1760. CPUUsedV, ok := CPUUsedMap[key]
  1761. if !ok {
  1762. log.Debug("no CPU usage for " + key)
  1763. CPUUsedV = []*util.Vector{}
  1764. }
  1765. RAMAllocsV, ok := RAMAllocMap[key]
  1766. if !ok {
  1767. log.Debug("no RAM allocation for " + key)
  1768. RAMAllocsV = []*util.Vector{}
  1769. }
  1770. CPUAllocsV, ok := CPUAllocMap[key]
  1771. if !ok {
  1772. log.Debug("no CPU allocation for " + key)
  1773. CPUAllocsV = []*util.Vector{}
  1774. }
  1775. GPUReqV, ok := GPUReqMap[key]
  1776. if !ok {
  1777. log.Debug("no GPU requests for " + key)
  1778. GPUReqV = []*util.Vector{}
  1779. }
  1780. var node *costAnalyzerCloud.Node
  1781. if n, ok := missingNodes[c.NodeName]; ok {
  1782. node = n
  1783. } else {
  1784. node = &costAnalyzerCloud.Node{}
  1785. missingNodes[c.NodeName] = node
  1786. }
  1787. nsKey := c.Namespace + "," + c.ClusterID
  1788. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1789. namespaceLabels, _ := namespaceLabelsMapping[nsKey]
  1790. pLabels := podLabels[podKey]
  1791. if pLabels == nil {
  1792. pLabels = make(map[string]string)
  1793. }
  1794. for k, v := range namespaceLabels {
  1795. if _, ok := pLabels[k]; !ok {
  1796. pLabels[k] = v
  1797. }
  1798. }
  1799. namespaceAnnotations, _ := namespaceAnnotationsMapping[nsKey]
  1800. pAnnotations := podAnnotations[podKey]
  1801. if pAnnotations == nil {
  1802. pAnnotations = make(map[string]string)
  1803. }
  1804. for k, v := range namespaceAnnotations {
  1805. if _, ok := pAnnotations[k]; !ok {
  1806. pAnnotations[k] = v
  1807. }
  1808. }
  1809. var podDeployments []string
  1810. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1811. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1812. podDeployments = ds
  1813. } else {
  1814. podDeployments = []string{}
  1815. }
  1816. }
  1817. var podStatefulSets []string
  1818. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1819. if ss, ok := podStatefulsetsMapping[nsKey][c.PodName]; ok {
  1820. podStatefulSets = ss
  1821. } else {
  1822. podStatefulSets = []string{}
  1823. }
  1824. }
  1825. var podServices []string
  1826. if _, ok := podServicesMapping[nsKey]; ok {
  1827. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1828. podServices = svcs
  1829. } else {
  1830. podServices = []string{}
  1831. }
  1832. }
  1833. var podPVs []*PersistentVolumeClaimData
  1834. var podNetCosts []*util.Vector
  1835. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  1836. // cost data since that was populated by cluster data previously. We do this with
  1837. // the pod_pvc_allocation metric
  1838. podPVData, ok := pvAllocationMapping[podKey]
  1839. if !ok {
  1840. log.Debugf("Failed to locate pv allocation mapping for missing pod.")
  1841. }
  1842. // Delete the current pod key from potentially unmounted pvs
  1843. delete(unmountedPVs, podKey)
  1844. // For network costs, we'll use existing map since it should still contain the
  1845. // correct data.
  1846. var podNetworkCosts []*util.Vector
  1847. if usage, ok := networkUsageMap[podKey]; ok {
  1848. netCosts, err := GetNetworkCost(usage, cp)
  1849. if err != nil {
  1850. log.Errorf("Error pulling network costs: %s", err.Error())
  1851. } else {
  1852. podNetworkCosts = netCosts
  1853. }
  1854. }
  1855. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  1856. // Follow the pattern of only allowing claims data per pod
  1857. if !otherClusterPVRecorded[podKey] {
  1858. otherClusterPVRecorded[podKey] = true
  1859. podPVs = podPVData
  1860. podNetCosts = podNetworkCosts
  1861. }
  1862. pds := []string{}
  1863. if ds, ok := podDaemonsets[podKey]; ok {
  1864. pds = []string{ds}
  1865. }
  1866. jobs := []string{}
  1867. if job, ok := podJobs[podKey]; ok {
  1868. jobs = []string{job}
  1869. }
  1870. costs := &CostData{
  1871. Name: c.ContainerName,
  1872. PodName: c.PodName,
  1873. NodeName: c.NodeName,
  1874. NodeData: node,
  1875. Namespace: c.Namespace,
  1876. Services: podServices,
  1877. Deployments: podDeployments,
  1878. Daemonsets: pds,
  1879. Statefulsets: podStatefulSets,
  1880. Jobs: jobs,
  1881. RAMReq: RAMReqV,
  1882. RAMUsed: RAMUsedV,
  1883. CPUReq: CPUReqV,
  1884. CPUUsed: CPUUsedV,
  1885. RAMAllocation: RAMAllocsV,
  1886. CPUAllocation: CPUAllocsV,
  1887. GPUReq: GPUReqV,
  1888. Annotations: pAnnotations,
  1889. Labels: pLabels,
  1890. NamespaceLabels: namespaceLabels,
  1891. PVCData: podPVs,
  1892. NetworkData: podNetCosts,
  1893. ClusterID: c.ClusterID,
  1894. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  1895. }
  1896. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1897. containerNameCost[key] = costs
  1898. missingContainers[key] = costs
  1899. }
  1900. }
  1901. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  1902. for k, costs := range unmounted {
  1903. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  1904. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1905. containerNameCost[k] = costs
  1906. }
  1907. }
  1908. if window.Minutes() > 0 {
  1909. dur, off := window.DurationOffsetStrings()
  1910. err = findDeletedNodeInfo(cli, missingNodes, dur, off)
  1911. if err != nil {
  1912. log.Errorf("Error fetching historical node data: %s", err.Error())
  1913. }
  1914. }
  1915. return containerNameCost, nil
  1916. }
  1917. func applyAllocationToRequests(allocationMap map[string][]*util.Vector, requestMap map[string][]*util.Vector) {
  1918. // The result of the normalize operation will be a new []*util.Vector to replace the requests
  1919. normalizeOp := func(r *util.Vector, x *float64, y *float64) bool {
  1920. // Omit data (return false) if both x and y inputs don't exist
  1921. if x == nil || y == nil {
  1922. return false
  1923. }
  1924. // If the allocation value is 0, 0 out request value
  1925. if *x == 0 {
  1926. r.Value = 0
  1927. } else {
  1928. r.Value = *y
  1929. }
  1930. return true
  1931. }
  1932. // Run normalization on all request vectors in the mapping
  1933. for k, requests := range requestMap {
  1934. // Only run normalization where there are valid allocations
  1935. allocations, ok := allocationMap[k]
  1936. if !ok {
  1937. delete(requestMap, k)
  1938. continue
  1939. }
  1940. // Replace request map with normalized
  1941. requestMap[k] = util.ApplyVectorOp(allocations, requests, normalizeOp)
  1942. }
  1943. }
  1944. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  1945. cfg, err := cp.GetConfig()
  1946. if err != nil {
  1947. log.Errorf("Failed to get provider config while adding pv metrics data.")
  1948. return
  1949. }
  1950. for _, pvcDataArray := range pvAllocationMap {
  1951. for _, pvcData := range pvcDataArray {
  1952. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  1953. pvCost, ok := pvCostMap[costKey]
  1954. if !ok {
  1955. pvcData.Volume = &costAnalyzerCloud.PV{
  1956. Cost: cfg.Storage,
  1957. }
  1958. continue
  1959. }
  1960. pvcData.Volume = pvCost
  1961. }
  1962. }
  1963. }
  1964. // Add values that don't already exist in origMap from mergeMap into origMap
  1965. func mergeStringMap(origMap map[string]map[string]string, mergeMap map[string]map[string]string) {
  1966. for k, v := range mergeMap {
  1967. if _, ok := origMap[k]; !ok {
  1968. origMap[k] = v
  1969. }
  1970. }
  1971. }
  1972. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  1973. for k, v := range labels {
  1974. mainLabels[k] = v
  1975. }
  1976. }
  1977. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1978. nsToLabels := make(map[string]map[string]string)
  1979. nss := cache.GetAllNamespaces()
  1980. for _, ns := range nss {
  1981. labels := make(map[string]string)
  1982. for k, v := range ns.Labels {
  1983. labels[prom.SanitizeLabelName(k)] = v
  1984. }
  1985. nsToLabels[ns.Name+","+clusterID] = labels
  1986. }
  1987. return nsToLabels, nil
  1988. }
  1989. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1990. nsToAnnotations := make(map[string]map[string]string)
  1991. nss := cache.GetAllNamespaces()
  1992. for _, ns := range nss {
  1993. annotations := make(map[string]string)
  1994. for k, v := range ns.Annotations {
  1995. annotations[prom.SanitizeLabelName(k)] = v
  1996. }
  1997. nsToAnnotations[ns.Name+","+clusterID] = annotations
  1998. }
  1999. return nsToAnnotations, nil
  2000. }
  2001. func getDaemonsetsOfPod(pod v1.Pod) []string {
  2002. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2003. if ownerReference.Kind == "DaemonSet" {
  2004. return []string{ownerReference.Name}
  2005. }
  2006. }
  2007. return []string{}
  2008. }
  2009. func getJobsOfPod(pod v1.Pod) []string {
  2010. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2011. if ownerReference.Kind == "Job" {
  2012. return []string{ownerReference.Name}
  2013. }
  2014. }
  2015. return []string{}
  2016. }
  2017. func getStatefulSetsOfPod(pod v1.Pod) []string {
  2018. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2019. if ownerReference.Kind == "StatefulSet" {
  2020. return []string{ownerReference.Name}
  2021. }
  2022. }
  2023. return []string{}
  2024. }
  2025. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  2026. daemonsets := cache.GetAllDaemonSets()
  2027. vgpuCount := 0.0
  2028. for _, ds := range daemonsets {
  2029. dsContainerList := &ds.Spec.Template.Spec.Containers
  2030. for _, ctnr := range *dsContainerList {
  2031. if ctnr.Args != nil {
  2032. for _, arg := range ctnr.Args {
  2033. if strings.Contains(arg, "--vgpu=") {
  2034. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  2035. if err != nil {
  2036. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  2037. continue
  2038. }
  2039. vgpuCount = vgpus
  2040. return vgpuCount, nil
  2041. }
  2042. }
  2043. }
  2044. }
  2045. }
  2046. return vgpuCount, nil
  2047. }
  2048. type PersistentVolumeClaimData struct {
  2049. Class string `json:"class"`
  2050. Claim string `json:"claim"`
  2051. Namespace string `json:"namespace"`
  2052. ClusterID string `json:"clusterId"`
  2053. TimesClaimed int `json:"timesClaimed"`
  2054. VolumeName string `json:"volumeName"`
  2055. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2056. Values []*util.Vector `json:"values"`
  2057. }
  2058. func measureTime(start time.Time, threshold time.Duration, name string) {
  2059. elapsed := time.Since(start)
  2060. if elapsed > threshold {
  2061. log.Infof("[Profiler] %s: %s", elapsed, name)
  2062. }
  2063. }
  2064. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2065. elapsed := time.Since(start)
  2066. if elapsed > threshold {
  2067. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2068. }
  2069. }
  2070. func (cm *CostModel) QueryAllocation(window kubecost.Window, resolution, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy kubecost.AccumulateOption) (*kubecost.AllocationSetRange, error) {
  2071. // Validate window is legal
  2072. if window.IsOpen() || window.IsNegative() {
  2073. return nil, fmt.Errorf("illegal window: %s", window)
  2074. }
  2075. var totalsStore kubecost.TotalsStore
  2076. // Idle is required for proportional asset costs
  2077. if includeProportionalAssetResourceCosts {
  2078. if !includeIdle {
  2079. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  2080. }
  2081. totalsStore = kubecost.NewMemoryTotalsStore()
  2082. }
  2083. // Begin with empty response
  2084. asr := kubecost.NewAllocationSetRange()
  2085. // Query for AllocationSets in increments of the given step duration,
  2086. // appending each to the response.
  2087. stepStart := *window.Start()
  2088. stepEnd := stepStart.Add(step)
  2089. var isAKS bool
  2090. for window.End().After(stepStart) {
  2091. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd, resolution)
  2092. if err != nil {
  2093. return nil, fmt.Errorf("error computing allocations for %s: %w", kubecost.NewClosedWindow(stepStart, stepEnd), err)
  2094. }
  2095. if includeIdle {
  2096. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  2097. if err != nil {
  2098. return nil, fmt.Errorf("error computing assets for %s: %w", kubecost.NewClosedWindow(stepStart, stepEnd), err)
  2099. }
  2100. if includeProportionalAssetResourceCosts {
  2101. // AKS is a special case - there can be a maximum of 2
  2102. // load balancers (1 public and 1 private) in an AKS cluster
  2103. // therefore, when calculating PARCs for load balancers,
  2104. // we must know if this is an AKS cluster
  2105. for _, node := range assetSet.Nodes {
  2106. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  2107. isAKS = true
  2108. break
  2109. }
  2110. }
  2111. _, err := kubecost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2112. if err != nil {
  2113. log.Errorf("ETL: error updating asset resource totals for %s: %s", assetSet.Window, err)
  2114. }
  2115. }
  2116. idleSet, err := computeIdleAllocations(allocSet, assetSet, true)
  2117. if err != nil {
  2118. return nil, fmt.Errorf("error computing idle allocations for %s: %w", kubecost.NewClosedWindow(stepStart, stepEnd), err)
  2119. }
  2120. for _, idleAlloc := range idleSet.Allocations {
  2121. allocSet.Insert(idleAlloc)
  2122. }
  2123. }
  2124. asr.Append(allocSet)
  2125. stepStart = stepEnd
  2126. stepEnd = stepStart.Add(step)
  2127. }
  2128. // Set aggregation options and aggregate
  2129. opts := &kubecost.AllocationAggregationOptions{
  2130. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  2131. IdleByNode: idleByNode,
  2132. IncludeAggregatedMetadata: includeAggregatedMetadata,
  2133. }
  2134. // Aggregate
  2135. err := asr.AggregateBy(aggregate, opts)
  2136. if err != nil {
  2137. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  2138. }
  2139. // Accumulate, if requested
  2140. if accumulateBy != kubecost.AccumulateOptionNone {
  2141. asr, err = asr.Accumulate(accumulateBy)
  2142. if err != nil {
  2143. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2144. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2145. }
  2146. // when accumulating and returning PARCs, we need the totals for the
  2147. // accumulated windows to accurately compute a fraction
  2148. if includeProportionalAssetResourceCosts {
  2149. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  2150. if err != nil {
  2151. return nil, fmt.Errorf("error computing assets for %s: %w", kubecost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2152. }
  2153. _, err = kubecost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2154. if err != nil {
  2155. log.Errorf("ETL: error updating asset resource totals for %s: %s", kubecost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2156. }
  2157. }
  2158. }
  2159. if includeProportionalAssetResourceCosts {
  2160. for _, as := range asr.Allocations {
  2161. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  2162. if !ok {
  2163. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2164. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2165. }
  2166. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  2167. if !ok {
  2168. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2169. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2170. }
  2171. var totalPublicLbCost, totalPrivateLbCost float64
  2172. if isAKS && sharedLoadBalancer {
  2173. // loop through all assetTotals, adding all load balancer costs by public and private
  2174. for _, tot := range totalStoreByNode {
  2175. if tot.PrivateLoadBalancer {
  2176. totalPrivateLbCost += tot.LoadBalancerCost
  2177. } else {
  2178. totalPublicLbCost += tot.LoadBalancerCost
  2179. }
  2180. }
  2181. }
  2182. // loop through each allocation set, using total cost from totals store
  2183. for _, alloc := range as.Allocations {
  2184. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  2185. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  2186. // for each parc , check the totals store for each
  2187. // on a totals hit, set the corresponding total and calculate percentage
  2188. var totals *kubecost.AssetTotals
  2189. if totalsLoc, found := totalStoreByCluster[key]; found {
  2190. totals = totalsLoc
  2191. }
  2192. if totalsLoc, found := totalStoreByNode[key]; found {
  2193. totals = totalsLoc
  2194. }
  2195. if totals == nil {
  2196. log.Errorf("unable to locate asset totals for allocation %s", key)
  2197. return nil, fmt.Errorf("unable to locate allocation totals for allocation")
  2198. }
  2199. parc.CPUTotalCost = totals.CPUCost
  2200. parc.GPUTotalCost = totals.GPUCost
  2201. parc.RAMTotalCost = totals.RAMCost
  2202. parc.PVTotalCost = totals.PersistentVolumeCost
  2203. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  2204. // Azure is a special case - use computed totals above
  2205. // use the lbAllocations in the object to determine if
  2206. // this PARC is a public or private load balancer
  2207. // then set the total accordingly
  2208. // AKS only has 1 public and 1 private load balancer
  2209. lbAlloc, found := alloc.LoadBalancers[key]
  2210. if found {
  2211. if lbAlloc.Private {
  2212. parc.LoadBalancerTotalCost = totalPrivateLbCost
  2213. } else {
  2214. parc.LoadBalancerTotalCost = totalPublicLbCost
  2215. }
  2216. }
  2217. } else {
  2218. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  2219. }
  2220. kubecost.ComputePercentages(&parc)
  2221. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  2222. }
  2223. }
  2224. }
  2225. }
  2226. return asr, nil
  2227. }
  2228. func computeIdleAllocations(allocSet *kubecost.AllocationSet, assetSet *kubecost.AssetSet, idleByNode bool) (*kubecost.AllocationSet, error) {
  2229. if !allocSet.Window.Equal(assetSet.Window) {
  2230. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  2231. }
  2232. var allocTotals map[string]*kubecost.AllocationTotals
  2233. var assetTotals map[string]*kubecost.AssetTotals
  2234. if idleByNode {
  2235. allocTotals = kubecost.ComputeAllocationTotals(allocSet, kubecost.AllocationNodeProp)
  2236. assetTotals = kubecost.ComputeAssetTotals(assetSet, true)
  2237. } else {
  2238. allocTotals = kubecost.ComputeAllocationTotals(allocSet, kubecost.AllocationClusterProp)
  2239. assetTotals = kubecost.ComputeAssetTotals(assetSet, false)
  2240. }
  2241. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  2242. idleSet := kubecost.NewAllocationSet(start, end)
  2243. for key, assetTotal := range assetTotals {
  2244. allocTotal, ok := allocTotals[key]
  2245. if !ok {
  2246. log.Warnf("ETL: did not find allocations for asset key: %s", key)
  2247. // Use a zero-value set of totals. This indicates either (1) an
  2248. // error computing totals, or (2) that no allocations ran on the
  2249. // given node for the given window.
  2250. allocTotal = &kubecost.AllocationTotals{
  2251. Cluster: assetTotal.Cluster,
  2252. Node: assetTotal.Node,
  2253. Start: assetTotal.Start,
  2254. End: assetTotal.End,
  2255. }
  2256. }
  2257. // Insert one idle allocation for each key (whether by node or
  2258. // by cluster), defined as the difference between the total
  2259. // asset cost and the allocated cost per-resource.
  2260. name := fmt.Sprintf("%s/%s", key, kubecost.IdleSuffix)
  2261. err := idleSet.Insert(&kubecost.Allocation{
  2262. Name: name,
  2263. Window: idleSet.Window.Clone(),
  2264. Properties: &kubecost.AllocationProperties{
  2265. Cluster: assetTotal.Cluster,
  2266. Node: assetTotal.Node,
  2267. ProviderID: assetTotal.Node,
  2268. },
  2269. Start: assetTotal.Start,
  2270. End: assetTotal.End,
  2271. CPUCost: assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost(),
  2272. GPUCost: assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost(),
  2273. RAMCost: assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost(),
  2274. })
  2275. if err != nil {
  2276. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  2277. }
  2278. }
  2279. return idleSet, nil
  2280. }