costmodel.go 76 KB

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