costmodel.go 91 KB

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