costmodel.go 95 KB

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