costmodel.go 79 KB

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