costmodel.go 76 KB

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