costmodel.go 73 KB

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