costmodel.go 84 KB

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