costmodel.go 92 KB

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