costmodel.go 74 KB

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