costmodel.go 95 KB

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