costmodel.go 80 KB

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