costmodel.go 79 KB

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