costmodel.go 72 KB

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