costmodel.go 75 KB

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