costmodel.go 77 KB

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