costmodel.go 87 KB

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