costmodel.go 79 KB

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