costmodel.go 74 KB

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