costmodel.go 79 KB

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