costmodel.go 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654
  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]v1.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.GetObjectMeta().GetName()
  350. ns := pod.GetObjectMeta().GetNamespace()
  351. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  352. podLabels := pod.GetObjectMeta().GetLabels()
  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.GetObjectMeta().GetAnnotations()
  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.GetObjectMeta().GetName()]; 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.GetObjectMeta().GetName()]; 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.Warnf("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.Warnf("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.Warnf("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.Warnf("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.ObjectMeta.Name] = params
  810. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["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 *v1.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. vgpuCount, err := getAllocatableVGPUs(cm.Cache)
  885. if err != nil {
  886. return nil, err
  887. }
  888. vgpuCoeff := 10.0
  889. if vgpuCount > 0.0 {
  890. vgpuCoeff = vgpuCount
  891. }
  892. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  893. TotalNodes: 0,
  894. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  895. }
  896. for _, n := range nodeList {
  897. name := n.GetObjectMeta().GetName()
  898. nodeLabels := n.GetObjectMeta().GetLabels()
  899. nodeLabels["providerID"] = n.Spec.ProviderID
  900. pmd.TotalNodes++
  901. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  902. if err != nil {
  903. log.Infof("Error getting node pricing. Error: %s", err.Error())
  904. if cnode != nil {
  905. nodes[name] = cnode
  906. continue
  907. } else {
  908. cnode = &costAnalyzerCloud.Node{
  909. VCPUCost: cfg.CPU,
  910. RAMCost: cfg.RAM,
  911. }
  912. }
  913. }
  914. if _, ok := pmd.PricingTypeCounts[cnode.PricingType]; ok {
  915. pmd.PricingTypeCounts[cnode.PricingType]++
  916. } else {
  917. pmd.PricingTypeCounts[cnode.PricingType] = 1
  918. }
  919. newCnode := *cnode
  920. if newCnode.InstanceType == "" {
  921. it, _ := util.GetInstanceType(n.Labels)
  922. newCnode.InstanceType = it
  923. }
  924. if newCnode.Region == "" {
  925. region, _ := util.GetRegion(n.Labels)
  926. newCnode.Region = region
  927. }
  928. if newCnode.ArchType == "" {
  929. arch, _ := util.GetArchType(n.Labels)
  930. newCnode.ArchType = arch
  931. }
  932. newCnode.ProviderID = n.Spec.ProviderID
  933. var cpu float64
  934. if newCnode.VCPU == "" {
  935. cpu = float64(n.Status.Capacity.Cpu().Value())
  936. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  937. } else {
  938. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  939. if err != nil {
  940. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  941. }
  942. }
  943. if math.IsNaN(cpu) {
  944. log.Warnf("cpu parsed as NaN. Setting to 0.")
  945. cpu = 0
  946. }
  947. var ram float64
  948. if newCnode.RAM == "" {
  949. newCnode.RAM = n.Status.Capacity.Memory().String()
  950. }
  951. ram = float64(n.Status.Capacity.Memory().Value())
  952. if math.IsNaN(ram) {
  953. log.Warnf("ram parsed as NaN. Setting to 0.")
  954. ram = 0
  955. }
  956. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  957. // Azure does not seem to provide a GPU count in its pricing API. GKE supports attaching multiple GPUs
  958. // So the k8s api will often report more accurate results for GPU count under status > capacity > nvidia.com/gpu than the cloud providers billing data
  959. // not all providers are guaranteed to use this, so don't overwrite a Provider assignment if we can't find something under that capacity exists
  960. gpuc := 0.0
  961. q, ok := n.Status.Capacity["nvidia.com/gpu"]
  962. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  963. if ok && !hasReplicas {
  964. gpuCount := q.Value()
  965. if gpuCount != 0 {
  966. newCnode.GPU = fmt.Sprintf("%d", gpuCount)
  967. newCnode.VGPU = newCnode.GPU
  968. gpuc = float64(gpuCount)
  969. }
  970. } else if hasReplicas { // See https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html
  971. if q.Value() == 0 {
  972. q = n.Status.Capacity["nvidia.com/gpu.shared"]
  973. }
  974. g, ok := n.Labels["nvidia.com/gpu.count"]
  975. if ok {
  976. newCnode.GPU = g
  977. } else {
  978. newCnode.GPU = fmt.Sprintf("%d", 0)
  979. }
  980. newCnode.VGPU = fmt.Sprintf("%d", q.Value())
  981. } else if g, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  982. gpuCount := g.Value()
  983. if gpuCount != 0 {
  984. newCnode.GPU = fmt.Sprintf("%d", int(float64(gpuCount)/vgpuCoeff))
  985. newCnode.VGPU = fmt.Sprintf("%d", gpuCount)
  986. gpuc = float64(gpuCount) / vgpuCoeff
  987. }
  988. } else {
  989. gpuc, err = strconv.ParseFloat(newCnode.GPU, 64)
  990. if err != nil {
  991. gpuc = 0.0
  992. }
  993. }
  994. if math.IsNaN(gpuc) {
  995. log.Warnf("gpu count parsed as NaN. Setting to 0.")
  996. gpuc = 0.0
  997. }
  998. // Special case for SUSE rancher, since it won't behave with normal
  999. // calculations, courtesy of the instance type not being "real" (a
  1000. // recognizable AWS instance type.)
  1001. if newCnode.InstanceType == "rke2" {
  1002. log.Infof(
  1003. "Found a SUSE Rancher node %s, defaulting and skipping math",
  1004. cp.GetKey(nodeLabels, n).Features(),
  1005. )
  1006. defaultCPUCorePrice, err := strconv.ParseFloat(cfg.CPU, 64)
  1007. if err != nil {
  1008. log.Errorf("Could not parse default cpu price")
  1009. defaultCPUCorePrice = 0
  1010. }
  1011. if math.IsNaN(defaultCPUCorePrice) {
  1012. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1013. defaultCPUCorePrice = 0
  1014. }
  1015. defaultRAMPrice, err := strconv.ParseFloat(cfg.RAM, 64)
  1016. if err != nil {
  1017. log.Errorf("Could not parse default ram price")
  1018. defaultRAMPrice = 0
  1019. }
  1020. if math.IsNaN(defaultRAMPrice) {
  1021. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1022. defaultRAMPrice = 0
  1023. }
  1024. defaultGPUPrice, err := strconv.ParseFloat(cfg.GPU, 64)
  1025. if err != nil {
  1026. log.Errorf("Could not parse default gpu price")
  1027. defaultGPUPrice = 0
  1028. }
  1029. if math.IsNaN(defaultGPUPrice) {
  1030. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  1031. defaultGPUPrice = 0
  1032. }
  1033. // Just say no to doing the ratios!
  1034. cpuCost := defaultCPUCorePrice * cpu
  1035. gpuCost := defaultGPUPrice * gpuc
  1036. ramCost := defaultRAMPrice * ram
  1037. nodeCost := cpuCost + gpuCost + ramCost
  1038. newCnode.Cost = fmt.Sprintf("%f", nodeCost)
  1039. newCnode.VCPUCost = fmt.Sprintf("%f", cpuCost)
  1040. newCnode.GPUCost = fmt.Sprintf("%f", gpuCost)
  1041. newCnode.RAMCost = fmt.Sprintf("%f", ramCost)
  1042. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1043. } else if newCnode.GPU != "" && newCnode.GPUCost == "" {
  1044. // was the big thing to investigate. All the funky ratio math
  1045. // we were doing was messing with their default pricing. for SUSE Rancher.
  1046. // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  1047. log.Infof("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1048. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1049. if err != nil {
  1050. log.Errorf("Could not parse default cpu price")
  1051. defaultCPU = 0
  1052. }
  1053. if math.IsNaN(defaultCPU) {
  1054. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1055. defaultCPU = 0
  1056. }
  1057. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1058. if err != nil {
  1059. log.Errorf("Could not parse default ram price")
  1060. defaultRAM = 0
  1061. }
  1062. if math.IsNaN(defaultRAM) {
  1063. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1064. defaultRAM = 0
  1065. }
  1066. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  1067. if err != nil {
  1068. log.Errorf("Could not parse default gpu price")
  1069. defaultGPU = 0
  1070. }
  1071. if math.IsNaN(defaultGPU) {
  1072. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  1073. defaultGPU = 0
  1074. }
  1075. cpuToRAMRatio := defaultCPU / defaultRAM
  1076. if math.IsNaN(cpuToRAMRatio) {
  1077. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1078. cpuToRAMRatio = 10
  1079. }
  1080. gpuToRAMRatio := defaultGPU / defaultRAM
  1081. if math.IsNaN(gpuToRAMRatio) {
  1082. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  1083. gpuToRAMRatio = 100
  1084. }
  1085. ramGB := ram / 1024 / 1024 / 1024
  1086. if math.IsNaN(ramGB) {
  1087. log.Warnf("ramGB is NaN. Setting to 0.")
  1088. ramGB = 0
  1089. }
  1090. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  1091. if math.IsNaN(ramMultiple) {
  1092. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1093. ramMultiple = 0
  1094. }
  1095. var nodePrice float64
  1096. if newCnode.Cost != "" {
  1097. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1098. if err != nil {
  1099. log.Errorf("Could not parse total node price")
  1100. return nil, err
  1101. }
  1102. } else if newCnode.VCPUCost != "" {
  1103. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1104. if err != nil {
  1105. log.Errorf("Could not parse node vcpu price")
  1106. return nil, err
  1107. }
  1108. } else { // add case to use default pricing model when API data fails.
  1109. log.Debugf("No node price or CPUprice found, falling back to default")
  1110. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  1111. }
  1112. if math.IsNaN(nodePrice) {
  1113. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1114. nodePrice = 0
  1115. }
  1116. ramPrice := (nodePrice / ramMultiple)
  1117. if math.IsNaN(ramPrice) {
  1118. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1119. ramPrice = 0
  1120. }
  1121. cpuPrice := ramPrice * cpuToRAMRatio
  1122. gpuPrice := ramPrice * gpuToRAMRatio
  1123. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1124. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1125. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1126. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1127. } else if newCnode.RAMCost == "" {
  1128. // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  1129. log.Debugf("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1130. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1131. if err != nil {
  1132. log.Warnf("Could not parse default cpu price")
  1133. defaultCPU = 0
  1134. }
  1135. if math.IsNaN(defaultCPU) {
  1136. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1137. defaultCPU = 0
  1138. }
  1139. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1140. if err != nil {
  1141. log.Warnf("Could not parse default ram price")
  1142. defaultRAM = 0
  1143. }
  1144. if math.IsNaN(defaultRAM) {
  1145. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1146. defaultRAM = 0
  1147. }
  1148. cpuToRAMRatio := defaultCPU / defaultRAM
  1149. if math.IsNaN(cpuToRAMRatio) {
  1150. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1151. cpuToRAMRatio = 10
  1152. }
  1153. ramGB := ram / 1024 / 1024 / 1024
  1154. if math.IsNaN(ramGB) {
  1155. log.Warnf("ramGB is NaN. Setting to 0.")
  1156. ramGB = 0
  1157. }
  1158. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1159. if math.IsNaN(ramMultiple) {
  1160. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1161. ramMultiple = 0
  1162. }
  1163. var nodePrice float64
  1164. if newCnode.Cost != "" {
  1165. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1166. if err != nil {
  1167. log.Warnf("Could not parse total node price")
  1168. return nil, err
  1169. }
  1170. if newCnode.GPUCost != "" {
  1171. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1172. if err != nil {
  1173. log.Warnf("Could not parse node gpu price")
  1174. return nil, err
  1175. }
  1176. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1177. }
  1178. } else if newCnode.VCPUCost != "" {
  1179. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1180. if err != nil {
  1181. log.Warnf("Could not parse node vcpu price")
  1182. return nil, err
  1183. }
  1184. } else { // add case to use default pricing model when API data fails.
  1185. log.Debugf("No node price or CPUprice found, falling back to default")
  1186. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1187. }
  1188. if math.IsNaN(nodePrice) {
  1189. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1190. nodePrice = 0
  1191. }
  1192. ramPrice := (nodePrice / ramMultiple)
  1193. if math.IsNaN(ramPrice) {
  1194. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1195. ramPrice = 0
  1196. }
  1197. cpuPrice := ramPrice * cpuToRAMRatio
  1198. if defaultRAM != 0 {
  1199. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1200. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1201. } else { // just assign the full price to CPU
  1202. if cpu != 0 {
  1203. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1204. } else {
  1205. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1206. }
  1207. }
  1208. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1209. log.Debugf("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1210. }
  1211. nodes[name] = &newCnode
  1212. }
  1213. cm.pricingMetadata = pmd
  1214. cp.ApplyReservedInstancePricing(nodes)
  1215. return nodes, nil
  1216. }
  1217. // TODO: drop some logs
  1218. func (cm *CostModel) GetLBCost(cp costAnalyzerCloud.Provider) (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1219. // for fetching prices from cloud provider
  1220. // cfg, err := cp.GetConfig()
  1221. // if err != nil {
  1222. // return nil, err
  1223. // }
  1224. servicesList := cm.Cache.GetAllServices()
  1225. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1226. for _, service := range servicesList {
  1227. namespace := service.GetObjectMeta().GetNamespace()
  1228. name := service.GetObjectMeta().GetName()
  1229. key := serviceKey{
  1230. Cluster: env.GetClusterID(),
  1231. Namespace: namespace,
  1232. Service: name,
  1233. }
  1234. if service.Spec.Type == "LoadBalancer" {
  1235. loadBalancer, err := cp.LoadBalancerPricing()
  1236. if err != nil {
  1237. return nil, err
  1238. }
  1239. newLoadBalancer := *loadBalancer
  1240. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1241. address := loadBalancerIngress.IP
  1242. // Some cloud providers use hostname rather than IP
  1243. if address == "" {
  1244. address = loadBalancerIngress.Hostname
  1245. }
  1246. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1247. }
  1248. loadBalancerMap[key] = &newLoadBalancer
  1249. }
  1250. }
  1251. return loadBalancerMap, nil
  1252. }
  1253. func getPodServices(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1254. servicesList := cache.GetAllServices()
  1255. podServicesMapping := make(map[string]map[string][]string)
  1256. for _, service := range servicesList {
  1257. namespace := service.GetObjectMeta().GetNamespace()
  1258. name := service.GetObjectMeta().GetName()
  1259. key := namespace + "," + clusterID
  1260. if _, ok := podServicesMapping[key]; !ok {
  1261. podServicesMapping[key] = make(map[string][]string)
  1262. }
  1263. s := labels.Nothing()
  1264. if service.Spec.Selector != nil && len(service.Spec.Selector) > 0 {
  1265. s = labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  1266. }
  1267. for _, pod := range podList {
  1268. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1269. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1270. services, ok := podServicesMapping[key][pod.GetObjectMeta().GetName()]
  1271. if ok {
  1272. podServicesMapping[key][pod.GetObjectMeta().GetName()] = append(services, name)
  1273. } else {
  1274. podServicesMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1275. }
  1276. }
  1277. }
  1278. }
  1279. return podServicesMapping, nil
  1280. }
  1281. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1282. ssList := cache.GetAllStatefulSets()
  1283. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1284. for _, ss := range ssList {
  1285. namespace := ss.GetObjectMeta().GetNamespace()
  1286. name := ss.GetObjectMeta().GetName()
  1287. key := namespace + "," + clusterID
  1288. if _, ok := podSSMapping[key]; !ok {
  1289. podSSMapping[key] = make(map[string][]string)
  1290. }
  1291. s, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  1292. if err != nil {
  1293. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1294. }
  1295. for _, pod := range podList {
  1296. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1297. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1298. sss, ok := podSSMapping[key][pod.GetObjectMeta().GetName()]
  1299. if ok {
  1300. podSSMapping[key][pod.GetObjectMeta().GetName()] = append(sss, name)
  1301. } else {
  1302. podSSMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1303. }
  1304. }
  1305. }
  1306. }
  1307. return podSSMapping, nil
  1308. }
  1309. func getPodDeployments(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1310. deploymentsList := cache.GetAllDeployments()
  1311. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1312. for _, deployment := range deploymentsList {
  1313. namespace := deployment.GetObjectMeta().GetNamespace()
  1314. name := deployment.GetObjectMeta().GetName()
  1315. key := namespace + "," + clusterID
  1316. if _, ok := podDeploymentsMapping[key]; !ok {
  1317. podDeploymentsMapping[key] = make(map[string][]string)
  1318. }
  1319. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1320. if err != nil {
  1321. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1322. }
  1323. for _, pod := range podList {
  1324. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1325. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1326. deployments, ok := podDeploymentsMapping[key][pod.GetObjectMeta().GetName()]
  1327. if ok {
  1328. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1329. } else {
  1330. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1331. }
  1332. }
  1333. }
  1334. }
  1335. return podDeploymentsMapping, nil
  1336. }
  1337. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1338. podDeploymentsMapping := make(map[string]map[string][]string)
  1339. for depKey, depLabels := range deploymentLabels {
  1340. kt, err := NewKeyTuple(depKey)
  1341. if err != nil {
  1342. continue
  1343. }
  1344. namespace := kt.Namespace()
  1345. name := kt.Key()
  1346. clusterID := kt.ClusterID()
  1347. key := namespace + "," + clusterID
  1348. if _, ok := podDeploymentsMapping[key]; !ok {
  1349. podDeploymentsMapping[key] = make(map[string][]string)
  1350. }
  1351. s := labels.Set(depLabels).AsSelectorPreValidated()
  1352. for podKey, pLabels := range podLabels {
  1353. pkey, err := NewKeyTuple(podKey)
  1354. if err != nil {
  1355. continue
  1356. }
  1357. podNamespace := pkey.Namespace()
  1358. podName := pkey.Key()
  1359. podClusterID := pkey.ClusterID()
  1360. labelSet := labels.Set(pLabels)
  1361. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1362. deployments, ok := podDeploymentsMapping[key][podName]
  1363. if ok {
  1364. podDeploymentsMapping[key][podName] = append(deployments, name)
  1365. } else {
  1366. podDeploymentsMapping[key][podName] = []string{name}
  1367. }
  1368. }
  1369. }
  1370. }
  1371. // Remove any duplicate data created by metric names
  1372. pruneDuplicateData(podDeploymentsMapping)
  1373. return podDeploymentsMapping, nil
  1374. }
  1375. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1376. podServicesMapping := make(map[string]map[string][]string)
  1377. for servKey, servLabels := range serviceLabels {
  1378. kt, err := NewKeyTuple(servKey)
  1379. if err != nil {
  1380. continue
  1381. }
  1382. namespace := kt.Namespace()
  1383. name := kt.Key()
  1384. clusterID := kt.ClusterID()
  1385. key := namespace + "," + clusterID
  1386. if _, ok := podServicesMapping[key]; !ok {
  1387. podServicesMapping[key] = make(map[string][]string)
  1388. }
  1389. s := labels.Nothing()
  1390. if servLabels != nil && len(servLabels) > 0 {
  1391. s = labels.Set(servLabels).AsSelectorPreValidated()
  1392. }
  1393. for podKey, pLabels := range podLabels {
  1394. pkey, err := NewKeyTuple(podKey)
  1395. if err != nil {
  1396. continue
  1397. }
  1398. podNamespace := pkey.Namespace()
  1399. podName := pkey.Key()
  1400. podClusterID := pkey.ClusterID()
  1401. labelSet := labels.Set(pLabels)
  1402. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1403. services, ok := podServicesMapping[key][podName]
  1404. if ok {
  1405. podServicesMapping[key][podName] = append(services, name)
  1406. } else {
  1407. podServicesMapping[key][podName] = []string{name}
  1408. }
  1409. }
  1410. }
  1411. }
  1412. // Remove any duplicate data created by metric names
  1413. pruneDuplicateData(podServicesMapping)
  1414. return podServicesMapping, nil
  1415. }
  1416. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1417. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1418. // the '_' version. Not optimal, but takes care of the issue
  1419. func pruneDuplicateData(data map[string]map[string][]string) {
  1420. for _, podMap := range data {
  1421. for podName, values := range podMap {
  1422. podMap[podName] = pruneDuplicates(values)
  1423. }
  1424. }
  1425. }
  1426. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1427. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1428. // original value in the new slice.
  1429. func pruneDuplicates(s []string) []string {
  1430. m := sliceToSet(s)
  1431. for _, v := range s {
  1432. if strings.Contains(v, "_") {
  1433. name := strings.Replace(v, "_", "-", -1)
  1434. if !m[name] {
  1435. m[name] = true
  1436. }
  1437. delete(m, v)
  1438. }
  1439. }
  1440. return setToSlice(m)
  1441. }
  1442. // Creates a map[string]bool containing the slice values as keys
  1443. func sliceToSet(s []string) map[string]bool {
  1444. m := make(map[string]bool)
  1445. for _, v := range s {
  1446. m[v] = true
  1447. }
  1448. return m
  1449. }
  1450. func setToSlice(m map[string]bool) []string {
  1451. var result []string
  1452. for k := range m {
  1453. result = append(result, k)
  1454. }
  1455. return result
  1456. }
  1457. func costDataPassesFilters(cm clusters.ClusterMap, costs *CostData, namespace string, cluster string) bool {
  1458. passesNamespace := namespace == "" || costs.Namespace == namespace
  1459. passesCluster := cluster == "" || costs.ClusterID == cluster || costs.ClusterName == cluster
  1460. return passesNamespace && passesCluster
  1461. }
  1462. // Finds the a closest multiple less than value
  1463. func floorMultiple(value int64, multiple int64) int64 {
  1464. return (value / multiple) * multiple
  1465. }
  1466. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1467. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1468. func requestKeyFor(window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string, remoteEnabled bool) string {
  1469. keyLayout := "2006-01-02T15:04Z"
  1470. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1471. // applying a snapped duration to a snapped start time.
  1472. durMins := int64(window.Minutes())
  1473. durMins = floorMultiple(durMins, 5)
  1474. sMins := int64(window.Start().Minute())
  1475. sOffset := sMins - floorMultiple(sMins, 5)
  1476. sTime := window.Start().Add(-time.Duration(sOffset) * time.Minute)
  1477. eTime := window.Start().Add(time.Duration(durMins) * time.Minute)
  1478. startKey := sTime.Format(keyLayout)
  1479. endKey := eTime.Format(keyLayout)
  1480. return fmt.Sprintf("%s,%s,%s,%s,%s,%t", startKey, endKey, resolution.String(), filterNamespace, filterCluster, remoteEnabled)
  1481. }
  1482. // ComputeCostDataRange executes a range query for cost data.
  1483. // Note that "offset" represents the time between the function call and "endString", and is also passed for convenience
  1484. 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) {
  1485. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1486. // for the specific inputs to prevent multiple queries for identical data.
  1487. key := requestKeyFor(window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1488. log.Debugf("ComputeCostDataRange with Key: %s", key)
  1489. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1490. // Otherwise, start executing.
  1491. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1492. return cm.costDataRange(cli, cp, window, resolution, filterNamespace, filterCluster, remoteEnabled)
  1493. })
  1494. data, ok := result.(map[string]*CostData)
  1495. if !ok {
  1496. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1497. }
  1498. return data, err
  1499. }
  1500. 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) {
  1501. clusterID := env.GetClusterID()
  1502. // durHrs := end.Sub(start).Hours() + 1
  1503. if window.IsOpen() {
  1504. return nil, fmt.Errorf("illegal window: %s", window)
  1505. }
  1506. start := *window.Start()
  1507. end := *window.End()
  1508. // Snap resolution to the nearest minute
  1509. resMins := int64(math.Trunc(resolution.Minutes()))
  1510. if resMins == 0 {
  1511. return nil, fmt.Errorf("resolution must be greater than 0.0")
  1512. }
  1513. resolution = time.Duration(resMins) * time.Minute
  1514. // Warn if resolution does not evenly divide window
  1515. if int64(window.Minutes())%int64(resolution.Minutes()) != 0 {
  1516. 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()))
  1517. }
  1518. // Convert to Prometheus-style duration string in terms of m or h
  1519. resStr := fmt.Sprintf("%dm", resMins)
  1520. if resMins%60 == 0 {
  1521. resStr = fmt.Sprintf("%dh", resMins/60)
  1522. }
  1523. if remoteEnabled {
  1524. remoteLayout := "2006-01-02T15:04:05Z"
  1525. remoteStartStr := window.Start().Format(remoteLayout)
  1526. remoteEndStr := window.End().Format(remoteLayout)
  1527. log.Infof("Using remote database for query from %s to %s with window %s", remoteStartStr, remoteEndStr, resolution)
  1528. return CostDataRangeFromSQL("", "", resolution.String(), remoteStartStr, remoteEndStr)
  1529. }
  1530. scrapeIntervalSeconds := cm.ScrapeInterval.Seconds()
  1531. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataRangeContextName)
  1532. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1533. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1534. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1535. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1536. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1537. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1538. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1539. queryPVRequests := fmt.Sprintf(queryPVRequestsStr, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1540. queryPVCAllocation := fmt.Sprintf(queryPVCAllocationFmt, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1541. queryPVHourlyCost := fmt.Sprintf(queryPVHourlyCostFmt, env.GetPromClusterFilter(), resStr)
  1542. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1543. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1544. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1545. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), resStr, "")
  1546. // Submit all queries for concurrent evaluation
  1547. resChRAMRequests := ctx.QueryRange(queryRAMRequests, start, end, resolution)
  1548. resChRAMUsage := ctx.QueryRange(queryRAMUsage, start, end, resolution)
  1549. resChRAMAlloc := ctx.QueryRange(queryRAMAlloc, start, end, resolution)
  1550. resChCPURequests := ctx.QueryRange(queryCPURequests, start, end, resolution)
  1551. resChCPUUsage := ctx.QueryRange(queryCPUUsage, start, end, resolution)
  1552. resChCPUAlloc := ctx.QueryRange(queryCPUAlloc, start, end, resolution)
  1553. resChGPURequests := ctx.QueryRange(queryGPURequests, start, end, resolution)
  1554. resChPVRequests := ctx.QueryRange(queryPVRequests, start, end, resolution)
  1555. resChPVCAlloc := ctx.QueryRange(queryPVCAllocation, start, end, resolution)
  1556. resChPVHourlyCost := ctx.QueryRange(queryPVHourlyCost, start, end, resolution)
  1557. resChNetZoneRequests := ctx.QueryRange(queryNetZoneRequests, start, end, resolution)
  1558. resChNetRegionRequests := ctx.QueryRange(queryNetRegionRequests, start, end, resolution)
  1559. resChNetInternetRequests := ctx.QueryRange(queryNetInternetRequests, start, end, resolution)
  1560. resChNSLabels := ctx.QueryRange(fmt.Sprintf(queryNSLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1561. resChPodLabels := ctx.QueryRange(fmt.Sprintf(queryPodLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1562. resChNSAnnotations := ctx.QueryRange(fmt.Sprintf(queryNSAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1563. resChPodAnnotations := ctx.QueryRange(fmt.Sprintf(queryPodAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1564. resChServiceLabels := ctx.QueryRange(fmt.Sprintf(queryServiceLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1565. resChDeploymentLabels := ctx.QueryRange(fmt.Sprintf(queryDeploymentLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1566. resChStatefulsetLabels := ctx.QueryRange(fmt.Sprintf(queryStatefulsetLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1567. resChJobs := ctx.QueryRange(fmt.Sprintf(queryPodJobs, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1568. resChDaemonsets := ctx.QueryRange(fmt.Sprintf(queryPodDaemonsets, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1569. resChNormalization := ctx.QueryRange(queryNormalization, start, end, resolution)
  1570. // Pull k8s pod, controller, service, and namespace details
  1571. podlist := cm.Cache.GetAllPods()
  1572. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  1573. if err != nil {
  1574. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1575. }
  1576. podStatefulsetsMapping, err := getPodStatefulsets(cm.Cache, podlist, clusterID)
  1577. if err != nil {
  1578. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1579. }
  1580. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  1581. if err != nil {
  1582. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1583. }
  1584. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  1585. if err != nil {
  1586. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1587. }
  1588. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  1589. if err != nil {
  1590. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1591. }
  1592. // Process query results. Handle errors afterwards using ctx.Errors.
  1593. resRAMRequests, _ := resChRAMRequests.Await()
  1594. resRAMUsage, _ := resChRAMUsage.Await()
  1595. resRAMAlloc, _ := resChRAMAlloc.Await()
  1596. resCPURequests, _ := resChCPURequests.Await()
  1597. resCPUUsage, _ := resChCPUUsage.Await()
  1598. resCPUAlloc, _ := resChCPUAlloc.Await()
  1599. resGPURequests, _ := resChGPURequests.Await()
  1600. resPVRequests, _ := resChPVRequests.Await()
  1601. resPVCAlloc, _ := resChPVCAlloc.Await()
  1602. resPVHourlyCost, _ := resChPVHourlyCost.Await()
  1603. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  1604. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  1605. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  1606. resNSLabels, _ := resChNSLabels.Await()
  1607. resPodLabels, _ := resChPodLabels.Await()
  1608. resNSAnnotations, _ := resChNSAnnotations.Await()
  1609. resPodAnnotations, _ := resChPodAnnotations.Await()
  1610. resServiceLabels, _ := resChServiceLabels.Await()
  1611. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  1612. resStatefulsetLabels, _ := resChStatefulsetLabels.Await()
  1613. resDaemonsets, _ := resChDaemonsets.Await()
  1614. resJobs, _ := resChJobs.Await()
  1615. resNormalization, _ := resChNormalization.Await()
  1616. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  1617. // NOTE: will not propagate unless coupled with errors.
  1618. if ctx.HasErrors() {
  1619. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  1620. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  1621. for _, promErr := range ctx.Errors() {
  1622. if promErr.Error != nil {
  1623. log.Errorf("CostDataRange: Request Error: %s", promErr.Error)
  1624. }
  1625. if promErr.ParseError != nil {
  1626. log.Errorf("CostDataRange: Parsing Error: %s", promErr.ParseError)
  1627. }
  1628. }
  1629. // ErrorCollection is an collection of errors wrapped in a single error implementation
  1630. return nil, ctx.ErrorCollection()
  1631. }
  1632. normalizationValue, err := getNormalizations(resNormalization)
  1633. if err != nil {
  1634. msg := fmt.Sprintf("error computing normalization for start=%s, end=%s, res=%s", start, end, resolution)
  1635. return nil, prom.WrapError(err, msg)
  1636. }
  1637. pvClaimMapping, err := GetPVInfo(resPVRequests, clusterID)
  1638. if err != nil {
  1639. // Just log for compatibility with KSM less than 1.6
  1640. log.Infof("Unable to get PV Data: %s", err.Error())
  1641. }
  1642. if pvClaimMapping != nil {
  1643. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1644. if err != nil {
  1645. return nil, fmt.Errorf("pvClaimMapping: %s", err)
  1646. }
  1647. }
  1648. pvCostMapping, err := GetPVCostMetrics(resPVHourlyCost, clusterID)
  1649. if err != nil {
  1650. log.Errorf("Unable to get PV Hourly Cost Data: %s", err.Error())
  1651. }
  1652. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  1653. pvAllocationMapping, err := GetPVAllocationMetrics(resPVCAlloc, clusterID)
  1654. if err != nil {
  1655. log.Errorf("Unable to get PV Allocation Cost Data: %s", err.Error())
  1656. }
  1657. if pvAllocationMapping != nil {
  1658. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1659. for k, v := range pvAllocationMapping {
  1660. unmountedPVs[k] = v
  1661. }
  1662. }
  1663. nsLabels, err := GetNamespaceLabelsMetrics(resNSLabels, clusterID)
  1664. if err != nil {
  1665. log.Errorf("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1666. }
  1667. if nsLabels != nil {
  1668. mergeStringMap(namespaceLabelsMapping, nsLabels)
  1669. }
  1670. podLabels, err := GetPodLabelsMetrics(resPodLabels, clusterID)
  1671. if err != nil {
  1672. log.Errorf("Unable to get Pod Labels for Metrics: %s", err.Error())
  1673. }
  1674. nsAnnotations, err := GetNamespaceAnnotationsMetrics(resNSAnnotations, clusterID)
  1675. if err != nil {
  1676. log.Errorf("Unable to get Namespace Annotations for Metrics: %s", err.Error())
  1677. }
  1678. if nsAnnotations != nil {
  1679. mergeStringMap(namespaceAnnotationsMapping, nsAnnotations)
  1680. }
  1681. podAnnotations, err := GetPodAnnotationsMetrics(resPodAnnotations, clusterID)
  1682. if err != nil {
  1683. log.Errorf("Unable to get Pod Annotations for Metrics: %s", err.Error())
  1684. }
  1685. serviceLabels, err := GetServiceSelectorLabelsMetrics(resServiceLabels, clusterID)
  1686. if err != nil {
  1687. log.Errorf("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1688. }
  1689. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(resDeploymentLabels, clusterID)
  1690. if err != nil {
  1691. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1692. }
  1693. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(resStatefulsetLabels, clusterID)
  1694. if err != nil {
  1695. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1696. }
  1697. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1698. if err != nil {
  1699. log.Errorf("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1700. }
  1701. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1702. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1703. if err != nil {
  1704. log.Errorf("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1705. }
  1706. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1707. podDaemonsets, err := GetPodDaemonsetsWithMetrics(resDaemonsets, clusterID)
  1708. if err != nil {
  1709. log.Errorf("Unable to get Pod Daemonsets for Metrics: %s", err.Error())
  1710. }
  1711. podJobs, err := GetPodJobsWithMetrics(resJobs, clusterID)
  1712. if err != nil {
  1713. log.Errorf("Unable to get Pod Jobs for Metrics: %s", err.Error())
  1714. }
  1715. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1716. if err != nil {
  1717. log.Errorf("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1718. }
  1719. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1720. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  1721. if err != nil {
  1722. log.Errorf("Unable to get Network Cost Data: %s", err.Error())
  1723. networkUsageMap = make(map[string]*NetworkUsageData)
  1724. }
  1725. containerNameCost := make(map[string]*CostData)
  1726. containers := make(map[string]bool)
  1727. otherClusterPVRecorded := make(map[string]bool)
  1728. RAMReqMap, err := GetNormalizedContainerMetricVectors(resRAMRequests, normalizationValue, clusterID)
  1729. if err != nil {
  1730. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMRequests)")
  1731. }
  1732. for key := range RAMReqMap {
  1733. containers[key] = true
  1734. }
  1735. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resRAMUsage, normalizationValue, clusterID)
  1736. if err != nil {
  1737. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(RAMUsage)")
  1738. }
  1739. for key := range RAMUsedMap {
  1740. containers[key] = true
  1741. }
  1742. CPUReqMap, err := GetNormalizedContainerMetricVectors(resCPURequests, normalizationValue, clusterID)
  1743. if err != nil {
  1744. return nil, prom.WrapError(err, "GetNormalizedContainerMetricVectors(CPURequests)")
  1745. }
  1746. for key := range CPUReqMap {
  1747. containers[key] = true
  1748. }
  1749. // No need to normalize here, as this comes from a counter, namely:
  1750. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1751. CPUUsedMap, err := GetContainerMetricVectors(resCPUUsage, clusterID)
  1752. if err != nil {
  1753. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUUsage)")
  1754. }
  1755. for key := range CPUUsedMap {
  1756. containers[key] = true
  1757. }
  1758. RAMAllocMap, err := GetContainerMetricVectors(resRAMAlloc, clusterID)
  1759. if err != nil {
  1760. return nil, prom.WrapError(err, "GetContainerMetricVectors(RAMAllocations)")
  1761. }
  1762. for key := range RAMAllocMap {
  1763. containers[key] = true
  1764. }
  1765. CPUAllocMap, err := GetContainerMetricVectors(resCPUAlloc, clusterID)
  1766. if err != nil {
  1767. return nil, prom.WrapError(err, "GetContainerMetricVectors(CPUAllocations)")
  1768. }
  1769. for key := range CPUAllocMap {
  1770. containers[key] = true
  1771. }
  1772. GPUReqMap, err := GetNormalizedContainerMetricVectors(resGPURequests, normalizationValue, clusterID)
  1773. if err != nil {
  1774. return nil, prom.WrapError(err, "GetContainerMetricVectors(GPURequests)")
  1775. }
  1776. for key := range GPUReqMap {
  1777. containers[key] = true
  1778. }
  1779. // Request metrics can show up after pod eviction and completion.
  1780. // This method synchronizes requests to allocations such that when
  1781. // allocation is 0, so are requests
  1782. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1783. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1784. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1785. missingContainers := make(map[string]*CostData)
  1786. for key := range containers {
  1787. if _, ok := containerNameCost[key]; ok {
  1788. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1789. }
  1790. c, _ := NewContainerMetricFromKey(key)
  1791. RAMReqV, ok := RAMReqMap[key]
  1792. if !ok {
  1793. log.Debug("no RAM requests for " + key)
  1794. RAMReqV = []*util.Vector{}
  1795. }
  1796. RAMUsedV, ok := RAMUsedMap[key]
  1797. if !ok {
  1798. log.Debug("no RAM usage for " + key)
  1799. RAMUsedV = []*util.Vector{}
  1800. }
  1801. CPUReqV, ok := CPUReqMap[key]
  1802. if !ok {
  1803. log.Debug("no CPU requests for " + key)
  1804. CPUReqV = []*util.Vector{}
  1805. }
  1806. CPUUsedV, ok := CPUUsedMap[key]
  1807. if !ok {
  1808. log.Debug("no CPU usage for " + key)
  1809. CPUUsedV = []*util.Vector{}
  1810. }
  1811. RAMAllocsV, ok := RAMAllocMap[key]
  1812. if !ok {
  1813. log.Debug("no RAM allocation for " + key)
  1814. RAMAllocsV = []*util.Vector{}
  1815. }
  1816. CPUAllocsV, ok := CPUAllocMap[key]
  1817. if !ok {
  1818. log.Debug("no CPU allocation for " + key)
  1819. CPUAllocsV = []*util.Vector{}
  1820. }
  1821. GPUReqV, ok := GPUReqMap[key]
  1822. if !ok {
  1823. log.Debug("no GPU requests for " + key)
  1824. GPUReqV = []*util.Vector{}
  1825. }
  1826. var node *costAnalyzerCloud.Node
  1827. if n, ok := missingNodes[c.NodeName]; ok {
  1828. node = n
  1829. } else {
  1830. node = &costAnalyzerCloud.Node{}
  1831. missingNodes[c.NodeName] = node
  1832. }
  1833. nsKey := c.Namespace + "," + c.ClusterID
  1834. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1835. namespaceLabels, _ := namespaceLabelsMapping[nsKey]
  1836. pLabels := podLabels[podKey]
  1837. if pLabels == nil {
  1838. pLabels = make(map[string]string)
  1839. }
  1840. for k, v := range namespaceLabels {
  1841. if _, ok := pLabels[k]; !ok {
  1842. pLabels[k] = v
  1843. }
  1844. }
  1845. namespaceAnnotations, _ := namespaceAnnotationsMapping[nsKey]
  1846. pAnnotations := podAnnotations[podKey]
  1847. if pAnnotations == nil {
  1848. pAnnotations = make(map[string]string)
  1849. }
  1850. for k, v := range namespaceAnnotations {
  1851. if _, ok := pAnnotations[k]; !ok {
  1852. pAnnotations[k] = v
  1853. }
  1854. }
  1855. var podDeployments []string
  1856. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1857. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1858. podDeployments = ds
  1859. } else {
  1860. podDeployments = []string{}
  1861. }
  1862. }
  1863. var podStatefulSets []string
  1864. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1865. if ss, ok := podStatefulsetsMapping[nsKey][c.PodName]; ok {
  1866. podStatefulSets = ss
  1867. } else {
  1868. podStatefulSets = []string{}
  1869. }
  1870. }
  1871. var podServices []string
  1872. if _, ok := podServicesMapping[nsKey]; ok {
  1873. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1874. podServices = svcs
  1875. } else {
  1876. podServices = []string{}
  1877. }
  1878. }
  1879. var podPVs []*PersistentVolumeClaimData
  1880. var podNetCosts []*util.Vector
  1881. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  1882. // cost data since that was populated by cluster data previously. We do this with
  1883. // the pod_pvc_allocation metric
  1884. podPVData, ok := pvAllocationMapping[podKey]
  1885. if !ok {
  1886. log.Debugf("Failed to locate pv allocation mapping for missing pod.")
  1887. }
  1888. // Delete the current pod key from potentially unmounted pvs
  1889. delete(unmountedPVs, podKey)
  1890. // For network costs, we'll use existing map since it should still contain the
  1891. // correct data.
  1892. var podNetworkCosts []*util.Vector
  1893. if usage, ok := networkUsageMap[podKey]; ok {
  1894. netCosts, err := GetNetworkCost(usage, cp)
  1895. if err != nil {
  1896. log.Errorf("Error pulling network costs: %s", err.Error())
  1897. } else {
  1898. podNetworkCosts = netCosts
  1899. }
  1900. }
  1901. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  1902. // Follow the pattern of only allowing claims data per pod
  1903. if !otherClusterPVRecorded[podKey] {
  1904. otherClusterPVRecorded[podKey] = true
  1905. podPVs = podPVData
  1906. podNetCosts = podNetworkCosts
  1907. }
  1908. pds := []string{}
  1909. if ds, ok := podDaemonsets[podKey]; ok {
  1910. pds = []string{ds}
  1911. }
  1912. jobs := []string{}
  1913. if job, ok := podJobs[podKey]; ok {
  1914. jobs = []string{job}
  1915. }
  1916. costs := &CostData{
  1917. Name: c.ContainerName,
  1918. PodName: c.PodName,
  1919. NodeName: c.NodeName,
  1920. NodeData: node,
  1921. Namespace: c.Namespace,
  1922. Services: podServices,
  1923. Deployments: podDeployments,
  1924. Daemonsets: pds,
  1925. Statefulsets: podStatefulSets,
  1926. Jobs: jobs,
  1927. RAMReq: RAMReqV,
  1928. RAMUsed: RAMUsedV,
  1929. CPUReq: CPUReqV,
  1930. CPUUsed: CPUUsedV,
  1931. RAMAllocation: RAMAllocsV,
  1932. CPUAllocation: CPUAllocsV,
  1933. GPUReq: GPUReqV,
  1934. Annotations: pAnnotations,
  1935. Labels: pLabels,
  1936. NamespaceLabels: namespaceLabels,
  1937. PVCData: podPVs,
  1938. NetworkData: podNetCosts,
  1939. ClusterID: c.ClusterID,
  1940. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  1941. }
  1942. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1943. containerNameCost[key] = costs
  1944. missingContainers[key] = costs
  1945. }
  1946. }
  1947. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  1948. for k, costs := range unmounted {
  1949. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  1950. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1951. containerNameCost[k] = costs
  1952. }
  1953. }
  1954. if window.Minutes() > 0 {
  1955. dur, off := window.DurationOffsetStrings()
  1956. err = findDeletedNodeInfo(cli, missingNodes, dur, off)
  1957. if err != nil {
  1958. log.Errorf("Error fetching historical node data: %s", err.Error())
  1959. }
  1960. }
  1961. return containerNameCost, nil
  1962. }
  1963. func applyAllocationToRequests(allocationMap map[string][]*util.Vector, requestMap map[string][]*util.Vector) {
  1964. // The result of the normalize operation will be a new []*util.Vector to replace the requests
  1965. normalizeOp := func(r *util.Vector, x *float64, y *float64) bool {
  1966. // Omit data (return false) if both x and y inputs don't exist
  1967. if x == nil || y == nil {
  1968. return false
  1969. }
  1970. // If the allocation value is 0, 0 out request value
  1971. if *x == 0 {
  1972. r.Value = 0
  1973. } else {
  1974. r.Value = *y
  1975. }
  1976. return true
  1977. }
  1978. // Run normalization on all request vectors in the mapping
  1979. for k, requests := range requestMap {
  1980. // Only run normalization where there are valid allocations
  1981. allocations, ok := allocationMap[k]
  1982. if !ok {
  1983. delete(requestMap, k)
  1984. continue
  1985. }
  1986. // Replace request map with normalized
  1987. requestMap[k] = util.ApplyVectorOp(allocations, requests, normalizeOp)
  1988. }
  1989. }
  1990. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  1991. cfg, err := cp.GetConfig()
  1992. if err != nil {
  1993. log.Errorf("Failed to get provider config while adding pv metrics data.")
  1994. return
  1995. }
  1996. for _, pvcDataArray := range pvAllocationMap {
  1997. for _, pvcData := range pvcDataArray {
  1998. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  1999. pvCost, ok := pvCostMap[costKey]
  2000. if !ok {
  2001. pvcData.Volume = &costAnalyzerCloud.PV{
  2002. Cost: cfg.Storage,
  2003. }
  2004. continue
  2005. }
  2006. pvcData.Volume = pvCost
  2007. }
  2008. }
  2009. }
  2010. // Add values that don't already exist in origMap from mergeMap into origMap
  2011. func mergeStringMap(origMap map[string]map[string]string, mergeMap map[string]map[string]string) {
  2012. for k, v := range mergeMap {
  2013. if _, ok := origMap[k]; !ok {
  2014. origMap[k] = v
  2015. }
  2016. }
  2017. }
  2018. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  2019. for k, v := range labels {
  2020. mainLabels[k] = v
  2021. }
  2022. }
  2023. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2024. nsToLabels := make(map[string]map[string]string)
  2025. nss := cache.GetAllNamespaces()
  2026. for _, ns := range nss {
  2027. labels := make(map[string]string)
  2028. for k, v := range ns.Labels {
  2029. labels[promutil.SanitizeLabelName(k)] = v
  2030. }
  2031. nsToLabels[ns.Name+","+clusterID] = labels
  2032. }
  2033. return nsToLabels, nil
  2034. }
  2035. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2036. nsToAnnotations := make(map[string]map[string]string)
  2037. nss := cache.GetAllNamespaces()
  2038. for _, ns := range nss {
  2039. annotations := make(map[string]string)
  2040. for k, v := range ns.Annotations {
  2041. annotations[promutil.SanitizeLabelName(k)] = v
  2042. }
  2043. nsToAnnotations[ns.Name+","+clusterID] = annotations
  2044. }
  2045. return nsToAnnotations, nil
  2046. }
  2047. func getDaemonsetsOfPod(pod v1.Pod) []string {
  2048. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2049. if ownerReference.Kind == "DaemonSet" {
  2050. return []string{ownerReference.Name}
  2051. }
  2052. }
  2053. return []string{}
  2054. }
  2055. func getJobsOfPod(pod v1.Pod) []string {
  2056. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2057. if ownerReference.Kind == "Job" {
  2058. return []string{ownerReference.Name}
  2059. }
  2060. }
  2061. return []string{}
  2062. }
  2063. func getStatefulSetsOfPod(pod v1.Pod) []string {
  2064. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2065. if ownerReference.Kind == "StatefulSet" {
  2066. return []string{ownerReference.Name}
  2067. }
  2068. }
  2069. return []string{}
  2070. }
  2071. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  2072. daemonsets := cache.GetAllDaemonSets()
  2073. vgpuCount := 0.0
  2074. for _, ds := range daemonsets {
  2075. dsContainerList := &ds.Spec.Template.Spec.Containers
  2076. for _, ctnr := range *dsContainerList {
  2077. if ctnr.Args != nil {
  2078. for _, arg := range ctnr.Args {
  2079. if strings.Contains(arg, "--vgpu=") {
  2080. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  2081. if err != nil {
  2082. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  2083. continue
  2084. }
  2085. vgpuCount = vgpus
  2086. return vgpuCount, nil
  2087. }
  2088. }
  2089. }
  2090. }
  2091. }
  2092. return vgpuCount, nil
  2093. }
  2094. type PersistentVolumeClaimData struct {
  2095. Class string `json:"class"`
  2096. Claim string `json:"claim"`
  2097. Namespace string `json:"namespace"`
  2098. ClusterID string `json:"clusterId"`
  2099. TimesClaimed int `json:"timesClaimed"`
  2100. VolumeName string `json:"volumeName"`
  2101. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2102. Values []*util.Vector `json:"values"`
  2103. }
  2104. func measureTime(start time.Time, threshold time.Duration, name string) {
  2105. elapsed := time.Since(start)
  2106. if elapsed > threshold {
  2107. log.Infof("[Profiler] %s: %s", elapsed, name)
  2108. }
  2109. }
  2110. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2111. elapsed := time.Since(start)
  2112. if elapsed > threshold {
  2113. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2114. }
  2115. }
  2116. func (cm *CostModel) QueryAllocation(window opencost.Window, resolution, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy opencost.AccumulateOption) (*opencost.AllocationSetRange, error) {
  2117. // Validate window is legal
  2118. if window.IsOpen() || window.IsNegative() {
  2119. return nil, fmt.Errorf("illegal window: %s", window)
  2120. }
  2121. var totalsStore opencost.TotalsStore
  2122. // Idle is required for proportional asset costs
  2123. if includeProportionalAssetResourceCosts {
  2124. if !includeIdle {
  2125. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  2126. }
  2127. totalsStore = opencost.NewMemoryTotalsStore()
  2128. }
  2129. // Begin with empty response
  2130. asr := opencost.NewAllocationSetRange()
  2131. // Query for AllocationSets in increments of the given step duration,
  2132. // appending each to the response.
  2133. stepStart := *window.Start()
  2134. stepEnd := stepStart.Add(step)
  2135. var isAKS bool
  2136. for window.End().After(stepStart) {
  2137. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd, resolution)
  2138. if err != nil {
  2139. return nil, fmt.Errorf("error computing allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2140. }
  2141. if includeIdle {
  2142. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  2143. if err != nil {
  2144. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2145. }
  2146. if includeProportionalAssetResourceCosts {
  2147. // AKS is a special case - there can be a maximum of 2
  2148. // load balancers (1 public and 1 private) in an AKS cluster
  2149. // therefore, when calculating PARCs for load balancers,
  2150. // we must know if this is an AKS cluster
  2151. for _, node := range assetSet.Nodes {
  2152. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  2153. isAKS = true
  2154. break
  2155. }
  2156. }
  2157. _, err := opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2158. if err != nil {
  2159. log.Errorf("ETL: error updating asset resource totals for %s: %s", assetSet.Window, err)
  2160. }
  2161. }
  2162. idleSet, err := computeIdleAllocations(allocSet, assetSet, true)
  2163. if err != nil {
  2164. return nil, fmt.Errorf("error computing idle allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2165. }
  2166. for _, idleAlloc := range idleSet.Allocations {
  2167. allocSet.Insert(idleAlloc)
  2168. }
  2169. }
  2170. asr.Append(allocSet)
  2171. stepStart = stepEnd
  2172. stepEnd = stepStart.Add(step)
  2173. }
  2174. // Set aggregation options and aggregate
  2175. opts := &opencost.AllocationAggregationOptions{
  2176. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  2177. IdleByNode: idleByNode,
  2178. IncludeAggregatedMetadata: includeAggregatedMetadata,
  2179. }
  2180. // Aggregate
  2181. err := asr.AggregateBy(aggregate, opts)
  2182. if err != nil {
  2183. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  2184. }
  2185. // Accumulate, if requested
  2186. if accumulateBy != opencost.AccumulateOptionNone {
  2187. asr, err = asr.Accumulate(accumulateBy)
  2188. if err != nil {
  2189. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2190. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2191. }
  2192. // when accumulating and returning PARCs, we need the totals for the
  2193. // accumulated windows to accurately compute a fraction
  2194. if includeProportionalAssetResourceCosts {
  2195. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  2196. if err != nil {
  2197. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2198. }
  2199. _, err = opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2200. if err != nil {
  2201. log.Errorf("ETL: error updating asset resource totals for %s: %s", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2202. }
  2203. }
  2204. }
  2205. if includeProportionalAssetResourceCosts {
  2206. for _, as := range asr.Allocations {
  2207. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  2208. if !ok {
  2209. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2210. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2211. }
  2212. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  2213. if !ok {
  2214. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2215. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2216. }
  2217. var totalPublicLbCost, totalPrivateLbCost float64
  2218. if isAKS && sharedLoadBalancer {
  2219. // loop through all assetTotals, adding all load balancer costs by public and private
  2220. for _, tot := range totalStoreByNode {
  2221. if tot.PrivateLoadBalancer {
  2222. totalPrivateLbCost += tot.LoadBalancerCost
  2223. } else {
  2224. totalPublicLbCost += tot.LoadBalancerCost
  2225. }
  2226. }
  2227. }
  2228. // loop through each allocation set, using total cost from totals store
  2229. for _, alloc := range as.Allocations {
  2230. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  2231. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  2232. // for each parc , check the totals store for each
  2233. // on a totals hit, set the corresponding total and calculate percentage
  2234. var totals *opencost.AssetTotals
  2235. if totalsLoc, found := totalStoreByCluster[key]; found {
  2236. totals = totalsLoc
  2237. }
  2238. if totalsLoc, found := totalStoreByNode[key]; found {
  2239. totals = totalsLoc
  2240. }
  2241. if totals == nil {
  2242. log.Errorf("unable to locate asset totals for allocation %s, corresponding PARC is being skipped", key)
  2243. continue
  2244. }
  2245. parc.CPUTotalCost = totals.CPUCost
  2246. parc.GPUTotalCost = totals.GPUCost
  2247. parc.RAMTotalCost = totals.RAMCost
  2248. parc.PVTotalCost = totals.PersistentVolumeCost
  2249. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  2250. // Azure is a special case - use computed totals above
  2251. // use the lbAllocations in the object to determine if
  2252. // this PARC is a public or private load balancer
  2253. // then set the total accordingly
  2254. // AKS only has 1 public and 1 private load balancer
  2255. lbAlloc, found := alloc.LoadBalancers[key]
  2256. if found {
  2257. if lbAlloc.Private {
  2258. parc.LoadBalancerTotalCost = totalPrivateLbCost
  2259. } else {
  2260. parc.LoadBalancerTotalCost = totalPublicLbCost
  2261. }
  2262. }
  2263. } else {
  2264. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  2265. }
  2266. opencost.ComputePercentages(&parc)
  2267. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  2268. }
  2269. }
  2270. }
  2271. }
  2272. return asr, nil
  2273. }
  2274. func computeIdleAllocations(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet, idleByNode bool) (*opencost.AllocationSet, error) {
  2275. if !allocSet.Window.Equal(assetSet.Window) {
  2276. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  2277. }
  2278. var allocTotals map[string]*opencost.AllocationTotals
  2279. var assetTotals map[string]*opencost.AssetTotals
  2280. if idleByNode {
  2281. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationNodeProp)
  2282. assetTotals = opencost.ComputeAssetTotals(assetSet, true)
  2283. } else {
  2284. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationClusterProp)
  2285. assetTotals = opencost.ComputeAssetTotals(assetSet, false)
  2286. }
  2287. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  2288. idleSet := opencost.NewAllocationSet(start, end)
  2289. for key, assetTotal := range assetTotals {
  2290. allocTotal, ok := allocTotals[key]
  2291. if !ok {
  2292. log.Warnf("ETL: did not find allocations for asset key: %s", key)
  2293. // Use a zero-value set of totals. This indicates either (1) an
  2294. // error computing totals, or (2) that no allocations ran on the
  2295. // given node for the given window.
  2296. allocTotal = &opencost.AllocationTotals{
  2297. Cluster: assetTotal.Cluster,
  2298. Node: assetTotal.Node,
  2299. Start: assetTotal.Start,
  2300. End: assetTotal.End,
  2301. }
  2302. }
  2303. // Insert one idle allocation for each key (whether by node or
  2304. // by cluster), defined as the difference between the total
  2305. // asset cost and the allocated cost per-resource.
  2306. name := fmt.Sprintf("%s/%s", key, opencost.IdleSuffix)
  2307. err := idleSet.Insert(&opencost.Allocation{
  2308. Name: name,
  2309. Window: idleSet.Window.Clone(),
  2310. Properties: &opencost.AllocationProperties{
  2311. Cluster: assetTotal.Cluster,
  2312. Node: assetTotal.Node,
  2313. ProviderID: assetTotal.Node,
  2314. },
  2315. Start: assetTotal.Start,
  2316. End: assetTotal.End,
  2317. CPUCost: assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost(),
  2318. GPUCost: assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost(),
  2319. RAMCost: assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost(),
  2320. })
  2321. if err != nil {
  2322. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  2323. }
  2324. }
  2325. return idleSet, nil
  2326. }