costmodel.go 75 KB

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