costmodel.go 79 KB

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