costmodel.go 92 KB

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