costmodel.go 74 KB

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