costmodel.go 75 KB

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