costmodel.go 73 KB

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