costmodel.go 78 KB

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