costmodel.go 86 KB

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