costmodel.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. package costmodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "maps"
  6. "math"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/opencost/opencost/core/pkg/clustercache"
  12. "github.com/opencost/opencost/core/pkg/clusters"
  13. coreenv "github.com/opencost/opencost/core/pkg/env"
  14. "github.com/opencost/opencost/core/pkg/filter/allocation"
  15. "github.com/opencost/opencost/core/pkg/log"
  16. "github.com/opencost/opencost/core/pkg/opencost"
  17. "github.com/opencost/opencost/core/pkg/source"
  18. "github.com/opencost/opencost/core/pkg/util"
  19. "github.com/opencost/opencost/core/pkg/util/promutil"
  20. costAnalyzerCloud "github.com/opencost/opencost/pkg/cloud/models"
  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. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  28. unmountedPVsContainer = "unmounted-pvs"
  29. )
  30. // isCron matches a CronJob name and captures the non-timestamp name
  31. //
  32. // We support either a 10 character timestamp OR an 8 character timestamp
  33. // because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
  34. // and batch/v1 CronJobs create Jobs with 8 character timestamps.
  35. var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
  36. type CostModel struct {
  37. Cache clustercache.ClusterCache
  38. ClusterMap clusters.ClusterMap
  39. BatchDuration time.Duration
  40. RequestGroup *singleflight.Group
  41. DataSource source.OpenCostDataSource
  42. Provider costAnalyzerCloud.Provider
  43. pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
  44. }
  45. func NewCostModel(
  46. dataSource source.OpenCostDataSource,
  47. provider costAnalyzerCloud.Provider,
  48. cache clustercache.ClusterCache,
  49. clusterMap clusters.ClusterMap,
  50. batchDuration time.Duration,
  51. ) *CostModel {
  52. // request grouping to prevent over-requesting the same data prior to caching
  53. requestGroup := new(singleflight.Group)
  54. return &CostModel{
  55. Cache: cache,
  56. ClusterMap: clusterMap,
  57. BatchDuration: batchDuration,
  58. DataSource: dataSource,
  59. Provider: provider,
  60. RequestGroup: requestGroup,
  61. }
  62. }
  63. type CostData struct {
  64. Name string `json:"name,omitempty"`
  65. PodName string `json:"podName,omitempty"`
  66. NodeName string `json:"nodeName,omitempty"`
  67. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  68. Namespace string `json:"namespace,omitempty"`
  69. Deployments []string `json:"deployments,omitempty"`
  70. Services []string `json:"services,omitempty"`
  71. Daemonsets []string `json:"daemonsets,omitempty"`
  72. Statefulsets []string `json:"statefulsets,omitempty"`
  73. Jobs []string `json:"jobs,omitempty"`
  74. RAMReq []*util.Vector `json:"ramreq,omitempty"`
  75. RAMUsed []*util.Vector `json:"ramused,omitempty"`
  76. RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
  77. CPUReq []*util.Vector `json:"cpureq,omitempty"`
  78. CPUUsed []*util.Vector `json:"cpuused,omitempty"`
  79. CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
  80. GPUReq []*util.Vector `json:"gpureq,omitempty"`
  81. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  82. NetworkData []*util.Vector `json:"network,omitempty"`
  83. Annotations map[string]string `json:"annotations,omitempty"`
  84. Labels map[string]string `json:"labels,omitempty"`
  85. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  86. ClusterID string `json:"clusterId"`
  87. ClusterName string `json:"clusterName"`
  88. }
  89. func (cd *CostData) String() string {
  90. 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",
  91. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  92. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  93. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  94. }
  95. func (cd *CostData) GetController() (name string, kind string, hasController bool) {
  96. hasController = false
  97. if len(cd.Deployments) > 0 {
  98. name = cd.Deployments[0]
  99. kind = "deployment"
  100. hasController = true
  101. } else if len(cd.Statefulsets) > 0 {
  102. name = cd.Statefulsets[0]
  103. kind = "statefulset"
  104. hasController = true
  105. } else if len(cd.Daemonsets) > 0 {
  106. name = cd.Daemonsets[0]
  107. kind = "daemonset"
  108. hasController = true
  109. } else if len(cd.Jobs) > 0 {
  110. name = cd.Jobs[0]
  111. kind = "job"
  112. hasController = true
  113. match := isCron.FindStringSubmatch(name)
  114. if match != nil {
  115. name = match[1]
  116. }
  117. }
  118. return name, kind, hasController
  119. }
  120. func (cm *CostModel) ComputeCostData(start, end time.Time) (map[string]*CostData, error) {
  121. // Cluster ID is specific to the source cluster
  122. clusterID := coreenv.GetClusterID()
  123. cp := cm.Provider
  124. ds := cm.DataSource
  125. mq := ds.Metrics()
  126. // Get Kubernetes data
  127. // Pull pod information from k8s API
  128. podlist := cm.Cache.GetAllPods()
  129. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  130. if err != nil {
  131. return nil, err
  132. }
  133. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  134. if err != nil {
  135. return nil, err
  136. }
  137. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  138. if err != nil {
  139. return nil, err
  140. }
  141. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  142. if err != nil {
  143. return nil, err
  144. }
  145. // Get metrics data
  146. resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, err := queryMetrics(mq, start, end)
  147. if err != nil {
  148. log.Warnf("ComputeCostData: continuing despite metrics errors: %s", err)
  149. }
  150. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  151. nodes, err := cm.GetNodeCost()
  152. if err != nil {
  153. log.Warnf("GetNodeCost: no node cost model available: %s", err)
  154. return nil, err
  155. }
  156. // Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
  157. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  158. pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
  159. if err != nil {
  160. log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
  161. }
  162. if pvClaimMapping != nil {
  163. err = cm.addPVData(pvClaimMapping)
  164. if err != nil {
  165. return nil, err
  166. }
  167. // copy claim mappings into zombies, then remove as they're discovered
  168. for k, v := range pvClaimMapping {
  169. unmountedPVs[k] = []*PersistentVolumeClaimData{v}
  170. }
  171. }
  172. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  173. if err != nil {
  174. log.Warnf("Unable to get Network Cost Data: %s", err.Error())
  175. networkUsageMap = make(map[string]*NetworkUsageData)
  176. }
  177. containerNameCost := make(map[string]*CostData)
  178. containers := make(map[string]bool)
  179. RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, clusterID)
  180. if err != nil {
  181. return nil, err
  182. }
  183. for key := range RAMUsedMap {
  184. containers[key] = true
  185. }
  186. CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, clusterID) // No need to normalize here, as this comes from a counter
  187. if err != nil {
  188. return nil, err
  189. }
  190. for key := range CPUUsedMap {
  191. containers[key] = true
  192. }
  193. currentContainers := make(map[string]clustercache.Pod)
  194. for _, pod := range podlist {
  195. if pod.Status.Phase != v1.PodRunning {
  196. continue
  197. }
  198. cs, err := NewContainerMetricsFromPod(pod, clusterID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. for _, c := range cs {
  203. containers[c.Key()] = true // captures any containers that existed for a time < a metrics scrape interval. We currently charge 0 for this but should charge something.
  204. currentContainers[c.Key()] = *pod
  205. }
  206. }
  207. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  208. missingContainers := make(map[string]*CostData)
  209. for key := range containers {
  210. if _, ok := containerNameCost[key]; ok {
  211. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  212. }
  213. // The _else_ case for this statement is the case in which the container has been
  214. // deleted so we have usage information but not request information. In that case,
  215. // we return partial data for CPU and RAM: only usage and not requests.
  216. if pod, ok := currentContainers[key]; ok {
  217. podName := pod.Name
  218. ns := pod.Namespace
  219. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  220. podLabels := maps.Clone(pod.Labels)
  221. if podLabels == nil {
  222. podLabels = make(map[string]string)
  223. }
  224. for k, v := range nsLabels {
  225. if _, ok := podLabels[k]; !ok {
  226. podLabels[k] = v
  227. }
  228. }
  229. nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  230. podAnnotations := pod.Annotations
  231. if podAnnotations == nil {
  232. podAnnotations = make(map[string]string)
  233. }
  234. for k, v := range nsAnnotations {
  235. if _, ok := podAnnotations[k]; !ok {
  236. podAnnotations[k] = v
  237. }
  238. }
  239. nodeName := pod.Spec.NodeName
  240. var nodeData *costAnalyzerCloud.Node
  241. if _, ok := nodes[nodeName]; ok {
  242. nodeData = nodes[nodeName]
  243. }
  244. nsKey := ns + "," + clusterID
  245. var podDeployments []string
  246. if _, ok := podDeploymentsMapping[nsKey]; ok {
  247. if ds, ok := podDeploymentsMapping[nsKey][pod.Name]; ok {
  248. podDeployments = ds
  249. } else {
  250. podDeployments = []string{}
  251. }
  252. }
  253. var podPVs []*PersistentVolumeClaimData
  254. podClaims := pod.Spec.Volumes
  255. for _, vol := range podClaims {
  256. if vol.PersistentVolumeClaim != nil {
  257. name := vol.PersistentVolumeClaim.ClaimName
  258. key := ns + "," + name + "," + clusterID
  259. if pvClaim, ok := pvClaimMapping[key]; ok {
  260. pvClaim.TimesClaimed++
  261. podPVs = append(podPVs, pvClaim)
  262. // Remove entry from potential unmounted pvs
  263. delete(unmountedPVs, key)
  264. }
  265. }
  266. }
  267. var podNetCosts []*util.Vector
  268. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  269. netCosts, err := GetNetworkCost(usage, cp)
  270. if err != nil {
  271. log.Debugf("Error pulling network costs: %s", err.Error())
  272. } else {
  273. podNetCosts = netCosts
  274. }
  275. }
  276. var podServices []string
  277. if _, ok := podServicesMapping[nsKey]; ok {
  278. if svcs, ok := podServicesMapping[nsKey][pod.Name]; ok {
  279. podServices = svcs
  280. } else {
  281. podServices = []string{}
  282. }
  283. }
  284. for i, container := range pod.Spec.Containers {
  285. containerName := container.Name
  286. // recreate the key and look up data for this container
  287. newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  288. // k8s.io/apimachinery/pkg/api/resource/amount.go and
  289. // k8s.io/apimachinery/pkg/api/resource/quantity.go for
  290. // details on the "amount" API. See
  291. // https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
  292. // for the units of memory and CPU.
  293. ramRequestBytes := container.Resources.Requests.Memory().Value()
  294. // Because information on container RAM & CPU requests isn't
  295. // coming from metrics, it won't have a timestamp associated
  296. // with it. We need to provide a timestamp.
  297. RAMReqV := []*util.Vector{
  298. {
  299. Value: float64(ramRequestBytes),
  300. Timestamp: float64(time.Now().UTC().Unix()),
  301. },
  302. }
  303. // use millicores so we can convert to cores in a float64 format
  304. cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
  305. CPUReqV := []*util.Vector{
  306. {
  307. Value: float64(cpuRequestMilliCores) / 1000,
  308. Timestamp: float64(time.Now().UTC().Unix()),
  309. },
  310. }
  311. gpuReqCount := 0.0
  312. if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
  313. gpuReqCount = g.AsApproximateFloat64()
  314. } else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
  315. gpuReqCount = g.AsApproximateFloat64()
  316. } else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
  317. gpuReqCount = g.AsApproximateFloat64()
  318. } else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
  319. gpuReqCount = g.AsApproximateFloat64()
  320. }
  321. GPUReqV := []*util.Vector{
  322. {
  323. Value: float64(gpuReqCount),
  324. Timestamp: float64(time.Now().UTC().Unix()),
  325. },
  326. }
  327. RAMUsedV, ok := RAMUsedMap[newKey]
  328. if !ok {
  329. log.Debug("no RAM usage for " + newKey)
  330. RAMUsedV = []*util.Vector{{}}
  331. }
  332. CPUUsedV, ok := CPUUsedMap[newKey]
  333. if !ok {
  334. log.Debug("no CPU usage for " + newKey)
  335. CPUUsedV = []*util.Vector{{}}
  336. }
  337. var pvReq []*PersistentVolumeClaimData
  338. var netReq []*util.Vector
  339. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  340. pvReq = podPVs
  341. netReq = podNetCosts
  342. }
  343. costs := &CostData{
  344. Name: containerName,
  345. PodName: podName,
  346. NodeName: nodeName,
  347. Namespace: ns,
  348. Deployments: podDeployments,
  349. Services: podServices,
  350. Daemonsets: getDaemonsetsOfPod(pod),
  351. Jobs: getJobsOfPod(pod),
  352. Statefulsets: getStatefulSetsOfPod(pod),
  353. NodeData: nodeData,
  354. RAMReq: RAMReqV,
  355. RAMUsed: RAMUsedV,
  356. CPUReq: CPUReqV,
  357. CPUUsed: CPUUsedV,
  358. GPUReq: GPUReqV,
  359. PVCData: pvReq,
  360. NetworkData: netReq,
  361. Annotations: podAnnotations,
  362. Labels: podLabels,
  363. NamespaceLabels: nsLabels,
  364. ClusterID: clusterID,
  365. ClusterName: cm.ClusterMap.NameFor(clusterID),
  366. }
  367. var cpuReq, cpuUse *util.Vector
  368. if len(costs.CPUReq) > 0 {
  369. cpuReq = costs.CPUReq[0]
  370. }
  371. if len(costs.CPUUsed) > 0 {
  372. cpuUse = costs.CPUUsed[0]
  373. }
  374. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  375. var ramReq, ramUse *util.Vector
  376. if len(costs.RAMReq) > 0 {
  377. ramReq = costs.RAMReq[0]
  378. }
  379. if len(costs.RAMUsed) > 0 {
  380. ramUse = costs.RAMUsed[0]
  381. }
  382. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  383. containerNameCost[newKey] = costs
  384. }
  385. } else {
  386. // The container has been deleted. Not all information is sent to metrics via ksm, so fill out what we can without k8s api
  387. log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  388. c, err := NewContainerMetricFromKey(key)
  389. if err != nil {
  390. return nil, err
  391. }
  392. // CPU and RAM requests are obtained from the Kubernetes API.
  393. // If this case has been reached, the Kubernetes API will not
  394. // have information about the pod because it no longer exists.
  395. //
  396. // The case where this matters is minimal, mainly in environments
  397. // with very short-lived pods that over-request resources.
  398. RAMReqV := []*util.Vector{{}}
  399. CPUReqV := []*util.Vector{{}}
  400. GPUReqV := []*util.Vector{{}}
  401. RAMUsedV, ok := RAMUsedMap[key]
  402. if !ok {
  403. log.Debug("no RAM usage for " + key)
  404. RAMUsedV = []*util.Vector{{}}
  405. }
  406. CPUUsedV, ok := CPUUsedMap[key]
  407. if !ok {
  408. log.Debug("no CPU usage for " + key)
  409. CPUUsedV = []*util.Vector{{}}
  410. }
  411. node, ok := nodes[c.NodeName]
  412. if !ok {
  413. log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  414. if n, ok := missingNodes[c.NodeName]; ok {
  415. node = n
  416. } else {
  417. node = &costAnalyzerCloud.Node{}
  418. missingNodes[c.NodeName] = node
  419. }
  420. }
  421. namespacelabels := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  422. namespaceAnnotations := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
  423. costs := &CostData{
  424. Name: c.ContainerName,
  425. PodName: c.PodName,
  426. NodeName: c.NodeName,
  427. NodeData: node,
  428. Namespace: c.Namespace,
  429. RAMReq: RAMReqV,
  430. RAMUsed: RAMUsedV,
  431. CPUReq: CPUReqV,
  432. CPUUsed: CPUUsedV,
  433. GPUReq: GPUReqV,
  434. Annotations: namespaceAnnotations,
  435. NamespaceLabels: namespacelabels,
  436. ClusterID: c.ClusterID,
  437. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  438. }
  439. var cpuReq, cpuUse *util.Vector
  440. if len(costs.CPUReq) > 0 {
  441. cpuReq = costs.CPUReq[0]
  442. }
  443. if len(costs.CPUUsed) > 0 {
  444. cpuUse = costs.CPUUsed[0]
  445. }
  446. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  447. var ramReq, ramUse *util.Vector
  448. if len(costs.RAMReq) > 0 {
  449. ramReq = costs.RAMReq[0]
  450. }
  451. if len(costs.RAMUsed) > 0 {
  452. ramUse = costs.RAMUsed[0]
  453. }
  454. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  455. containerNameCost[key] = costs
  456. missingContainers[key] = costs
  457. }
  458. }
  459. // Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
  460. // to pass along the cost data
  461. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  462. for k, costs := range unmounted {
  463. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  464. containerNameCost[k] = costs
  465. }
  466. err = findDeletedNodeInfo(cm.DataSource, missingNodes, start, end)
  467. if err != nil {
  468. log.Errorf("Error fetching historical node data: %s", err.Error())
  469. }
  470. err = findDeletedPodInfo(cm.DataSource, missingContainers, start, end)
  471. if err != nil {
  472. log.Errorf("Error fetching historical pod data: %s", err.Error())
  473. }
  474. return containerNameCost, err
  475. }
  476. func queryMetrics(mq source.MetricsQuerier, start, end time.Time) ([]*source.ContainerMetricResult, []*source.ContainerMetricResult, []*source.NetZoneGiBResult, []*source.NetRegionGiBResult, []*source.NetInternetGiBResult, error) {
  477. grp := source.NewQueryGroup()
  478. resChRAMUsage := source.WithGroup(grp, mq.QueryRAMUsageAvg(start, end))
  479. resChCPUUsage := source.WithGroup(grp, mq.QueryCPUUsageAvg(start, end))
  480. resChNetZoneRequests := source.WithGroup(grp, mq.QueryNetZoneGiB(start, end))
  481. resChNetRegionRequests := source.WithGroup(grp, mq.QueryNetRegionGiB(start, end))
  482. resChNetInternetRequests := source.WithGroup(grp, mq.QueryNetInternetGiB(start, end))
  483. // Process metrics query results. Handle errors using ctx.Errors.
  484. resRAMUsage, _ := resChRAMUsage.Await()
  485. resCPUUsage, _ := resChCPUUsage.Await()
  486. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  487. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  488. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  489. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  490. // NOTE: will not propagate unless coupled with errors.
  491. if grp.HasErrors() {
  492. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  493. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  494. for _, queryErr := range grp.Errors() {
  495. if queryErr.Error != nil {
  496. log.Errorf("ComputeCostData: Request Error: %s", queryErr.Error)
  497. }
  498. if queryErr.ParseError != nil {
  499. log.Errorf("ComputeCostData: Parsing Error: %s", queryErr.ParseError)
  500. }
  501. }
  502. // ErrorCollection is an collection of errors wrapped in a single error implementation
  503. // We opt to not return an error for the sake of running as a pure exporter.
  504. return resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, grp.Error()
  505. }
  506. return resRAMUsage, resCPUUsage, resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, nil
  507. }
  508. func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
  509. costs := make(map[string]*CostData)
  510. if len(unmountedPVs) == 0 {
  511. return costs
  512. }
  513. for k, pv := range unmountedPVs {
  514. keyParts := strings.Split(k, ",")
  515. if len(keyParts) != 3 {
  516. log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
  517. continue
  518. }
  519. ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
  520. namespacelabels := namespaceLabelsMapping[ns+","+clusterID]
  521. namespaceAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  522. metric := NewContainerMetricFromValues(ns, unmountedPVsContainer, unmountedPVsContainer, "", clusterID)
  523. key := metric.Key()
  524. if costData, ok := costs[key]; !ok {
  525. costs[key] = &CostData{
  526. Name: unmountedPVsContainer,
  527. PodName: unmountedPVsContainer,
  528. NodeName: "",
  529. Annotations: namespaceAnnotations,
  530. Namespace: ns,
  531. NamespaceLabels: namespacelabels,
  532. Labels: namespacelabels,
  533. ClusterID: clusterID,
  534. ClusterName: clusterMap.NameFor(clusterID),
  535. PVCData: pv,
  536. }
  537. } else {
  538. costData.PVCData = append(costData.PVCData, pv...)
  539. }
  540. }
  541. return costs
  542. }
  543. func findDeletedPodInfo(dataSource source.OpenCostDataSource, missingContainers map[string]*CostData, start, end time.Time) error {
  544. if len(missingContainers) > 0 {
  545. mq := dataSource.Metrics()
  546. podLabelsResCh := mq.QueryPodLabels(start, end)
  547. podLabelsResult, err := podLabelsResCh.Await()
  548. if err != nil {
  549. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  550. }
  551. podLabels := make(map[string]map[string]string)
  552. if podLabelsResult != nil {
  553. podLabels, err = parsePodLabels(podLabelsResult)
  554. if err != nil {
  555. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  556. }
  557. }
  558. for key, costData := range missingContainers {
  559. cm, _ := NewContainerMetricFromKey(key)
  560. labels, ok := podLabels[cm.PodName]
  561. if !ok {
  562. labels = make(map[string]string)
  563. }
  564. for k, v := range costData.NamespaceLabels {
  565. labels[k] = v
  566. }
  567. costData.Labels = labels
  568. }
  569. }
  570. return nil
  571. }
  572. func findDeletedNodeInfo(dataSource source.OpenCostDataSource, missingNodes map[string]*costAnalyzerCloud.Node, start, end time.Time) error {
  573. if len(missingNodes) > 0 {
  574. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  575. grp := source.NewQueryGroup()
  576. mq := dataSource.Metrics()
  577. cpuCostResCh := source.WithGroup(grp, mq.QueryNodeCPUPricePerHr(start, end))
  578. ramCostResCh := source.WithGroup(grp, mq.QueryNodeRAMPricePerGiBHr(start, end))
  579. gpuCostResCh := source.WithGroup(grp, mq.QueryNodeGPUPricePerHr(start, end))
  580. cpuCostRes, _ := cpuCostResCh.Await()
  581. ramCostRes, _ := ramCostResCh.Await()
  582. gpuCostRes, _ := gpuCostResCh.Await()
  583. if grp.HasErrors() {
  584. return grp.Error()
  585. }
  586. cpuCosts, err := getCost(cpuCostRes, cpuCostNode, cpuCostData)
  587. if err != nil {
  588. return err
  589. }
  590. ramCosts, err := getCost(ramCostRes, ramCostNode, ramCostData)
  591. if err != nil {
  592. return err
  593. }
  594. gpuCosts, err := getCost(gpuCostRes, gpuCostNode, gpuCostData)
  595. if err != nil {
  596. return err
  597. }
  598. if len(cpuCosts) == 0 {
  599. log.Infof("Opencost metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  600. }
  601. for node, costv := range cpuCosts {
  602. if _, ok := missingNodes[node]; ok {
  603. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  604. } else {
  605. log.DedupedWarningf(5, "Node `%s` in metrics but not k8s api", node)
  606. }
  607. }
  608. for node, costv := range ramCosts {
  609. if _, ok := missingNodes[node]; ok {
  610. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  611. }
  612. }
  613. for node, costv := range gpuCosts {
  614. if _, ok := missingNodes[node]; ok {
  615. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  616. }
  617. }
  618. }
  619. return nil
  620. }
  621. // getContainerAllocation takes the max between request and usage. This function
  622. // returns a slice containing a single element describing the container's
  623. // allocation.
  624. //
  625. // Additionally, the timestamp of the allocation will be the highest value
  626. // timestamp between the two vectors. This mitigates situations where
  627. // Timestamp=0. This should have no effect on the metrics emitted by the
  628. // CostModelMetricsEmitter
  629. func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
  630. var result []*util.Vector
  631. if req != nil && used != nil {
  632. x1 := req.Value
  633. if math.IsNaN(x1) {
  634. log.Debugf("NaN value found during %s allocation calculation for requests.", allocationType)
  635. x1 = 0.0
  636. }
  637. y1 := used.Value
  638. if math.IsNaN(y1) {
  639. log.Debugf("NaN value found during %s allocation calculation for used.", allocationType)
  640. y1 = 0.0
  641. }
  642. result = []*util.Vector{
  643. {
  644. Value: math.Max(x1, y1),
  645. Timestamp: math.Max(req.Timestamp, used.Timestamp),
  646. },
  647. }
  648. if result[0].Value == 0 && result[0].Timestamp == 0 {
  649. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  650. }
  651. } else if req != nil {
  652. result = []*util.Vector{
  653. {
  654. Value: req.Value,
  655. Timestamp: req.Timestamp,
  656. },
  657. }
  658. } else if used != nil {
  659. result = []*util.Vector{
  660. {
  661. Value: used.Value,
  662. Timestamp: used.Timestamp,
  663. },
  664. }
  665. } else {
  666. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  667. result = []*util.Vector{
  668. {
  669. Value: 0,
  670. Timestamp: float64(time.Now().UTC().Unix()),
  671. },
  672. }
  673. }
  674. return result
  675. }
  676. func (cm *CostModel) addPVData(pvClaimMapping map[string]*PersistentVolumeClaimData) error {
  677. cache := cm.Cache
  678. cloud := cm.Provider
  679. cfg, err := cloud.GetConfig()
  680. if err != nil {
  681. return err
  682. }
  683. // Pull a region from the first node
  684. var defaultRegion string
  685. nodeList := cache.GetAllNodes()
  686. if len(nodeList) > 0 {
  687. defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
  688. }
  689. storageClasses := cache.GetAllStorageClasses()
  690. storageClassMap := make(map[string]map[string]string)
  691. for _, storageClass := range storageClasses {
  692. params := storageClass.Parameters
  693. storageClassMap[storageClass.Name] = params
  694. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  695. storageClassMap["default"] = params
  696. storageClassMap[""] = params
  697. }
  698. }
  699. pvs := cache.GetAllPersistentVolumes()
  700. pvMap := make(map[string]*costAnalyzerCloud.PV)
  701. for _, pv := range pvs {
  702. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  703. if !ok {
  704. log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  705. }
  706. var region string
  707. if r, ok := util.GetRegion(pv.Labels); ok {
  708. region = r
  709. } else {
  710. region = defaultRegion
  711. }
  712. cacPv := &costAnalyzerCloud.PV{
  713. Class: pv.Spec.StorageClassName,
  714. Region: region,
  715. Parameters: parameters,
  716. }
  717. err := cm.GetPVCost(cacPv, pv, region)
  718. if err != nil {
  719. return err
  720. }
  721. pvMap[pv.Name] = cacPv
  722. }
  723. for _, pvc := range pvClaimMapping {
  724. if vol, ok := pvMap[pvc.VolumeName]; ok {
  725. pvc.Volume = vol
  726. } else {
  727. log.Debugf("PV not found, using default")
  728. pvc.Volume = &costAnalyzerCloud.PV{
  729. Cost: cfg.Storage,
  730. }
  731. }
  732. }
  733. return nil
  734. }
  735. func (cm *CostModel) GetPVCost(pv *costAnalyzerCloud.PV, kpv *clustercache.PersistentVolume, defaultRegion string) error {
  736. cp := cm.Provider
  737. cfg, err := cp.GetConfig()
  738. if err != nil {
  739. return err
  740. }
  741. key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
  742. pv.ProviderID = key.ID()
  743. pvWithCost, err := cp.PVPricing(key)
  744. if err != nil {
  745. pv.Cost = cfg.Storage
  746. return err
  747. }
  748. if pvWithCost == nil || pvWithCost.Cost == "" {
  749. pv.Cost = cfg.Storage
  750. return nil // set default cost
  751. }
  752. pv.Cost = pvWithCost.Cost
  753. return nil
  754. }
  755. func (cm *CostModel) GetPricingSourceCounts() (*costAnalyzerCloud.PricingMatchMetadata, error) {
  756. if cm.pricingMetadata != nil {
  757. return cm.pricingMetadata, nil
  758. } else {
  759. return nil, fmt.Errorf("Node costs not yet calculated")
  760. }
  761. }
  762. func (cm *CostModel) GetNodeCost() (map[string]*costAnalyzerCloud.Node, error) {
  763. cp := cm.Provider
  764. cfg, err := cp.GetConfig()
  765. if err != nil {
  766. return nil, err
  767. }
  768. nodeList := cm.Cache.GetAllNodes()
  769. nodes := make(map[string]*costAnalyzerCloud.Node)
  770. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  771. TotalNodes: 0,
  772. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  773. }
  774. for _, n := range nodeList {
  775. name := n.Name
  776. nodeLabels := n.Labels
  777. nodeLabels["providerID"] = n.SpecProviderID
  778. pmd.TotalNodes++
  779. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  780. if err != nil {
  781. log.Infof("Could not get node pricing for node %s. Falling back to default pricing", name)
  782. log.Debugf("Error getting node pricing: %s", err.Error())
  783. if cnode != nil {
  784. nodes[name] = cnode
  785. continue
  786. } else {
  787. cnode = &costAnalyzerCloud.Node{
  788. VCPUCost: cfg.CPU,
  789. RAMCost: cfg.RAM,
  790. }
  791. }
  792. }
  793. pmd.PricingTypeCounts[cnode.PricingType]++
  794. // newCnode builds upon cnode but populates/overrides certain fields.
  795. // cnode was populated leveraging cloud provider public pricing APIs.
  796. newCnode := *cnode
  797. if newCnode.InstanceType == "" {
  798. it, _ := util.GetInstanceType(n.Labels)
  799. newCnode.InstanceType = it
  800. }
  801. if newCnode.Region == "" {
  802. region, _ := util.GetRegion(n.Labels)
  803. newCnode.Region = region
  804. }
  805. if newCnode.ArchType == "" {
  806. arch, _ := util.GetArchType(n.Labels)
  807. newCnode.ArchType = arch
  808. }
  809. newCnode.ProviderID = n.SpecProviderID
  810. var cpu float64
  811. if newCnode.VCPU == "" {
  812. cpu = float64(n.Status.Capacity.Cpu().Value())
  813. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  814. } else {
  815. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  816. if err != nil {
  817. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  818. }
  819. }
  820. if math.IsNaN(cpu) {
  821. log.Warnf("cpu parsed as NaN. Setting to 0.")
  822. cpu = 0
  823. }
  824. var ram float64
  825. if newCnode.RAM == "" {
  826. newCnode.RAM = n.Status.Capacity.Memory().String()
  827. }
  828. ram = float64(n.Status.Capacity.Memory().Value())
  829. if math.IsNaN(ram) {
  830. log.Warnf("ram parsed as NaN. Setting to 0.")
  831. ram = 0
  832. }
  833. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  834. gpuc, err := strconv.ParseFloat(newCnode.GPU, 64)
  835. if err != nil {
  836. gpuc = 0.0
  837. }
  838. // The k8s API will often report more accurate results for GPU count
  839. // than cloud provider public pricing APIs. If found, override the
  840. // original value.
  841. gpuOverride, vgpuOverride, err := getGPUCount(cm.Cache, n)
  842. if err != nil {
  843. log.Warnf("Unable to get GPUCount for node %s: %s", n.Name, err.Error())
  844. }
  845. if gpuOverride > 0 {
  846. newCnode.GPU = fmt.Sprintf("%f", gpuOverride)
  847. gpuc = gpuOverride
  848. }
  849. if vgpuOverride > 0 {
  850. newCnode.VGPU = fmt.Sprintf("%f", vgpuOverride)
  851. }
  852. // Special case for SUSE rancher, since it won't behave with normal
  853. // calculations, courtesy of the instance type not being "real" (a
  854. // recognizable AWS instance type.)
  855. if newCnode.InstanceType == "rke2" {
  856. log.Infof(
  857. "Found a SUSE Rancher node %s, defaulting and skipping math",
  858. cp.GetKey(nodeLabels, n).Features(),
  859. )
  860. defaultCPUCorePrice, err := strconv.ParseFloat(cfg.CPU, 64)
  861. if err != nil {
  862. log.Errorf("Could not parse default cpu price")
  863. defaultCPUCorePrice = 0
  864. }
  865. if math.IsNaN(defaultCPUCorePrice) {
  866. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  867. defaultCPUCorePrice = 0
  868. }
  869. // Some customers may want GPU pricing to be determined by the labels affixed to their nodes. GpuPricing
  870. // passes the node's labels to the provider, which then cross-references them with the labels that the
  871. // provider knows to have label-specific costs associated with them, and returns that cost. See CSVProvider
  872. // for an example implementation.
  873. var gpuPrice float64
  874. gpuPricing, err := cp.GpuPricing(nodeLabels)
  875. if err != nil {
  876. log.Errorf("Could not determine custom GPU pricing: %s", err)
  877. gpuPrice = 0
  878. } else if len(gpuPricing) > 0 {
  879. gpuPrice, err = strconv.ParseFloat(gpuPricing, 64)
  880. if err != nil {
  881. log.Errorf("Could not parse custom GPU pricing: %s", err)
  882. gpuPrice = 0
  883. } else if math.IsNaN(gpuPrice) {
  884. log.Warnf("Custom GPU pricing parsed as NaN. Setting to 0.")
  885. gpuPrice = 0
  886. } else {
  887. log.Infof("Using custom GPU pricing for node \"%s\": %f", name, gpuPrice)
  888. }
  889. } else {
  890. gpuPrice, err = strconv.ParseFloat(cfg.GPU, 64)
  891. if err != nil {
  892. log.Errorf("Could not parse default gpu price")
  893. gpuPrice = 0
  894. }
  895. if math.IsNaN(gpuPrice) {
  896. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  897. gpuPrice = 0
  898. }
  899. }
  900. defaultRAMPrice, err := strconv.ParseFloat(cfg.RAM, 64)
  901. if err != nil {
  902. log.Errorf("Could not parse default ram price")
  903. defaultRAMPrice = 0
  904. }
  905. if math.IsNaN(defaultRAMPrice) {
  906. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  907. defaultRAMPrice = 0
  908. }
  909. defaultGPUPrice, err := strconv.ParseFloat(cfg.GPU, 64)
  910. if err != nil {
  911. log.Errorf("Could not parse default gpu price")
  912. defaultGPUPrice = 0
  913. }
  914. if math.IsNaN(defaultGPUPrice) {
  915. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  916. defaultGPUPrice = 0
  917. }
  918. // Just say no to doing the ratios!
  919. cpuCost := defaultCPUCorePrice * cpu
  920. gpuCost := gpuPrice * gpuc
  921. ramCost := defaultRAMPrice * ram
  922. nodeCost := cpuCost + gpuCost + ramCost
  923. newCnode.Cost = fmt.Sprintf("%f", nodeCost)
  924. newCnode.VCPUCost = fmt.Sprintf("%f", defaultCPUCorePrice)
  925. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  926. newCnode.RAMCost = fmt.Sprintf("%f", defaultRAMPrice)
  927. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  928. } else if newCnode.GPU != "" && newCnode.GPUCost == "" {
  929. // was the big thing to investigate. All the funky ratio math
  930. // we were doing was messing with their default pricing. for SUSE Rancher.
  931. // We reach this when a GPU is detected on a node, but no cost for
  932. // the GPU is defined in the OnDemand pricing. Calculate ratios of
  933. // CPU to RAM and GPU to RAM costs, then distribute the total node
  934. // cost among the CPU, RAM, and GPU.
  935. log.Tracef("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  936. // Some customers may want GPU pricing to be determined by the labels affixed to their nodes. GpuPricing
  937. // passes the node's labels to the provider, which then cross-references them with the labels that the
  938. // provider knows to have label-specific costs associated with them, and returns that cost. See CSVProvider
  939. // for an example implementation.
  940. gpuPricing, err := cp.GpuPricing(nodeLabels)
  941. if err != nil {
  942. log.Errorf("Could not determine custom GPU pricing: %s", err)
  943. } else if len(gpuPricing) > 0 {
  944. newCnode.GPUCost = gpuPricing
  945. log.Infof("Using custom GPU pricing for node \"%s\": %s", name, gpuPricing)
  946. }
  947. if newCnode.GPUCost == "" {
  948. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  949. if err != nil {
  950. log.Errorf("Could not parse default cpu price")
  951. defaultCPU = 0
  952. }
  953. if math.IsNaN(defaultCPU) {
  954. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  955. defaultCPU = 0
  956. }
  957. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  958. if err != nil {
  959. log.Errorf("Could not parse default ram price")
  960. defaultRAM = 0
  961. }
  962. if math.IsNaN(defaultRAM) {
  963. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  964. defaultRAM = 0
  965. }
  966. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  967. if err != nil {
  968. log.Errorf("Could not parse default gpu price")
  969. defaultGPU = 0
  970. }
  971. if math.IsNaN(defaultGPU) {
  972. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  973. defaultGPU = 0
  974. }
  975. cpuToRAMRatio := defaultCPU / defaultRAM
  976. if math.IsNaN(cpuToRAMRatio) {
  977. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  978. cpuToRAMRatio = 10
  979. }
  980. gpuToRAMRatio := defaultGPU / defaultRAM
  981. if math.IsNaN(gpuToRAMRatio) {
  982. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  983. gpuToRAMRatio = 100
  984. }
  985. ramGB := ram / 1024 / 1024 / 1024
  986. if math.IsNaN(ramGB) {
  987. log.Warnf("ramGB is NaN. Setting to 0.")
  988. ramGB = 0
  989. }
  990. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  991. if math.IsNaN(ramMultiple) {
  992. log.Warnf("ramMultiple is NaN. Setting to 0.")
  993. ramMultiple = 0
  994. }
  995. var nodePrice float64
  996. if newCnode.Cost != "" {
  997. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  998. if err != nil {
  999. log.Errorf("Could not parse total node price")
  1000. return nil, err
  1001. }
  1002. } else if newCnode.VCPUCost != "" {
  1003. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1004. if err != nil {
  1005. log.Errorf("Could not parse node vcpu price")
  1006. return nil, err
  1007. }
  1008. } else { // add case to use default pricing model when API data fails.
  1009. log.Debugf("No node price or CPUprice found, falling back to default")
  1010. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  1011. }
  1012. if math.IsNaN(nodePrice) {
  1013. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1014. nodePrice = 0
  1015. }
  1016. ramPrice := (nodePrice / ramMultiple)
  1017. if math.IsNaN(ramPrice) {
  1018. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1019. ramPrice = 0
  1020. }
  1021. cpuPrice := ramPrice * cpuToRAMRatio
  1022. gpuPrice := ramPrice * gpuToRAMRatio
  1023. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1024. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1025. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1026. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1027. }
  1028. } else if newCnode.RAMCost == "" {
  1029. // We reach this when no RAM cost is defined in the OnDemand
  1030. // pricing. It calculates a cpuToRAMRatio and ramMultiple to
  1031. // distrubte the total node cost among CPU and RAM costs.
  1032. log.Tracef("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  1033. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1034. if err != nil {
  1035. log.Warnf("Could not parse default cpu price")
  1036. defaultCPU = 0
  1037. }
  1038. if math.IsNaN(defaultCPU) {
  1039. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1040. defaultCPU = 0
  1041. }
  1042. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1043. if err != nil {
  1044. log.Warnf("Could not parse default ram price")
  1045. defaultRAM = 0
  1046. }
  1047. if math.IsNaN(defaultRAM) {
  1048. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1049. defaultRAM = 0
  1050. }
  1051. cpuToRAMRatio := defaultCPU / defaultRAM
  1052. if math.IsNaN(cpuToRAMRatio) {
  1053. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1054. cpuToRAMRatio = 10
  1055. }
  1056. ramGB := ram / 1024 / 1024 / 1024
  1057. if math.IsNaN(ramGB) {
  1058. log.Warnf("ramGB is NaN. Setting to 0.")
  1059. ramGB = 0
  1060. }
  1061. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1062. if math.IsNaN(ramMultiple) {
  1063. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1064. ramMultiple = 0
  1065. }
  1066. var nodePrice float64
  1067. if newCnode.Cost != "" {
  1068. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1069. if err != nil {
  1070. log.Warnf("Could not parse total node price")
  1071. return nil, err
  1072. }
  1073. if newCnode.GPUCost != "" {
  1074. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1075. if err != nil {
  1076. log.Warnf("Could not parse node gpu price")
  1077. return nil, err
  1078. }
  1079. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1080. }
  1081. } else if newCnode.VCPUCost != "" {
  1082. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1083. if err != nil {
  1084. log.Warnf("Could not parse node vcpu price")
  1085. return nil, err
  1086. }
  1087. } else { // add case to use default pricing model when API data fails.
  1088. log.Debugf("No node price or CPUprice found, falling back to default")
  1089. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1090. }
  1091. if math.IsNaN(nodePrice) {
  1092. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1093. nodePrice = 0
  1094. }
  1095. ramPrice := (nodePrice / ramMultiple)
  1096. if math.IsNaN(ramPrice) {
  1097. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1098. ramPrice = 0
  1099. }
  1100. cpuPrice := ramPrice * cpuToRAMRatio
  1101. if defaultRAM != 0 {
  1102. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1103. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1104. } else { // just assign the full price to CPU
  1105. if cpu != 0 {
  1106. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1107. } else {
  1108. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1109. }
  1110. }
  1111. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1112. log.Tracef("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1113. }
  1114. nodes[name] = &newCnode
  1115. }
  1116. cm.pricingMetadata = pmd
  1117. cp.ApplyReservedInstancePricing(nodes)
  1118. return nodes, nil
  1119. }
  1120. // TODO: drop some logs
  1121. func (cm *CostModel) GetLBCost() (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1122. // for fetching prices from cloud provider
  1123. // cfg, err := cp.GetConfig()
  1124. // if err != nil {
  1125. // return nil, err
  1126. // }
  1127. cp := cm.Provider
  1128. servicesList := cm.Cache.GetAllServices()
  1129. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1130. for _, service := range servicesList {
  1131. namespace := service.Namespace
  1132. name := service.Name
  1133. key := serviceKey{
  1134. Cluster: coreenv.GetClusterID(),
  1135. Namespace: namespace,
  1136. Service: name,
  1137. }
  1138. if service.Type == "LoadBalancer" {
  1139. loadBalancer, err := cp.LoadBalancerPricing()
  1140. if err != nil {
  1141. return nil, err
  1142. }
  1143. newLoadBalancer := *loadBalancer
  1144. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1145. address := loadBalancerIngress.IP
  1146. // Some cloud providers use hostname rather than IP
  1147. if address == "" {
  1148. address = loadBalancerIngress.Hostname
  1149. }
  1150. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1151. }
  1152. loadBalancerMap[key] = &newLoadBalancer
  1153. }
  1154. }
  1155. return loadBalancerMap, nil
  1156. }
  1157. func getPodServices(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1158. servicesList := cache.GetAllServices()
  1159. podServicesMapping := make(map[string]map[string][]string)
  1160. for _, service := range servicesList {
  1161. namespace := service.Namespace
  1162. name := service.Name
  1163. key := namespace + "," + clusterID
  1164. if _, ok := podServicesMapping[key]; !ok {
  1165. podServicesMapping[key] = make(map[string][]string)
  1166. }
  1167. s := labels.Nothing()
  1168. if len(service.SpecSelector) > 0 {
  1169. s = labels.Set(service.SpecSelector).AsSelectorPreValidated()
  1170. }
  1171. for _, pod := range podList {
  1172. labelSet := labels.Set(pod.Labels)
  1173. if s.Matches(labelSet) && pod.Namespace == namespace {
  1174. services, ok := podServicesMapping[key][pod.Name]
  1175. if ok {
  1176. podServicesMapping[key][pod.Name] = append(services, name)
  1177. } else {
  1178. podServicesMapping[key][pod.Name] = []string{name}
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return podServicesMapping, nil
  1184. }
  1185. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1186. ssList := cache.GetAllStatefulSets()
  1187. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1188. for _, ss := range ssList {
  1189. namespace := ss.Namespace
  1190. name := ss.Name
  1191. key := namespace + "," + clusterID
  1192. if _, ok := podSSMapping[key]; !ok {
  1193. podSSMapping[key] = make(map[string][]string)
  1194. }
  1195. s, err := metav1.LabelSelectorAsSelector(ss.SpecSelector)
  1196. if err != nil {
  1197. log.Errorf("Error doing deployment label conversion: %s", err.Error())
  1198. }
  1199. for _, pod := range podList {
  1200. labelSet := labels.Set(pod.Labels)
  1201. if s.Matches(labelSet) && pod.Namespace == namespace {
  1202. sss, ok := podSSMapping[key][pod.Name]
  1203. if ok {
  1204. podSSMapping[key][pod.Name] = append(sss, name)
  1205. } else {
  1206. podSSMapping[key][pod.Name] = []string{name}
  1207. }
  1208. }
  1209. }
  1210. }
  1211. return podSSMapping, nil
  1212. }
  1213. func getPodDeployments(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1214. deploymentsList := cache.GetAllDeployments()
  1215. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1216. for _, deployment := range deploymentsList {
  1217. namespace := deployment.Namespace
  1218. name := deployment.Name
  1219. key := namespace + "," + clusterID
  1220. if _, ok := podDeploymentsMapping[key]; !ok {
  1221. podDeploymentsMapping[key] = make(map[string][]string)
  1222. }
  1223. s, err := metav1.LabelSelectorAsSelector(deployment.SpecSelector)
  1224. if err != nil {
  1225. log.Errorf("Error doing deployment label conversion: %s", err)
  1226. }
  1227. for _, pod := range podList {
  1228. labelSet := labels.Set(pod.Labels)
  1229. if s.Matches(labelSet) && pod.Namespace == namespace {
  1230. deployments, ok := podDeploymentsMapping[key][pod.Name]
  1231. if ok {
  1232. podDeploymentsMapping[key][pod.Name] = append(deployments, name)
  1233. } else {
  1234. podDeploymentsMapping[key][pod.Name] = []string{name}
  1235. }
  1236. }
  1237. }
  1238. }
  1239. return podDeploymentsMapping, nil
  1240. }
  1241. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1242. nsToLabels := make(map[string]map[string]string)
  1243. nss := cache.GetAllNamespaces()
  1244. for _, ns := range nss {
  1245. labels := make(map[string]string)
  1246. for k, v := range ns.Labels {
  1247. labels[promutil.SanitizeLabelName(k)] = v
  1248. }
  1249. nsToLabels[ns.Name+","+clusterID] = labels
  1250. }
  1251. return nsToLabels, nil
  1252. }
  1253. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1254. nsToAnnotations := make(map[string]map[string]string)
  1255. nss := cache.GetAllNamespaces()
  1256. for _, ns := range nss {
  1257. annotations := make(map[string]string)
  1258. for k, v := range ns.Annotations {
  1259. annotations[promutil.SanitizeLabelName(k)] = v
  1260. }
  1261. nsToAnnotations[ns.Name+","+clusterID] = annotations
  1262. }
  1263. return nsToAnnotations, nil
  1264. }
  1265. func getDaemonsetsOfPod(pod clustercache.Pod) []string {
  1266. for _, ownerReference := range pod.OwnerReferences {
  1267. if ownerReference.Kind == "DaemonSet" {
  1268. return []string{ownerReference.Name}
  1269. }
  1270. }
  1271. return []string{}
  1272. }
  1273. func getJobsOfPod(pod clustercache.Pod) []string {
  1274. for _, ownerReference := range pod.OwnerReferences {
  1275. if ownerReference.Kind == "Job" {
  1276. return []string{ownerReference.Name}
  1277. }
  1278. }
  1279. return []string{}
  1280. }
  1281. func getStatefulSetsOfPod(pod clustercache.Pod) []string {
  1282. for _, ownerReference := range pod.OwnerReferences {
  1283. if ownerReference.Kind == "StatefulSet" {
  1284. return []string{ownerReference.Name}
  1285. }
  1286. }
  1287. return []string{}
  1288. }
  1289. // getGPUCount reads the node's Status and Labels (via the k8s API) to identify
  1290. // the number of GPUs and vGPUs are equipped on the node. If unable to identify
  1291. // a GPU count, it will return -1.
  1292. func getGPUCount(cache clustercache.ClusterCache, n *clustercache.Node) (float64, float64, error) {
  1293. g, hasGpu := n.Status.Capacity["nvidia.com/gpu"]
  1294. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  1295. // Case 1: Standard NVIDIA GPU
  1296. if hasGpu && g.Value() != 0 && !hasReplicas {
  1297. return float64(g.Value()), float64(g.Value()), nil
  1298. }
  1299. // Case 2: NVIDIA GPU with GPU Feature Discovery (GFD) Pod enabled.
  1300. // Ref: https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html#verifying-the-gpu-time-slicing-configuration
  1301. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L44-L45
  1302. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L103-L118
  1303. if hasReplicas {
  1304. resultGPU := 0.0
  1305. resultVGPU := 0.0
  1306. if c, ok := n.Labels["nvidia.com/gpu.count"]; ok {
  1307. var err error
  1308. resultGPU, err = strconv.ParseFloat(c, 64)
  1309. if err != nil {
  1310. return -1, -1, fmt.Errorf("could not parse label \"nvidia.com/gpu.count\": %v", err)
  1311. }
  1312. }
  1313. if s, ok := n.Status.Capacity["nvidia.com/gpu.shared"]; ok { // GFD configured `renameByDefault=true`
  1314. resultVGPU = float64(s.Value())
  1315. } else if g, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // GFD configured `renameByDefault=false`
  1316. resultVGPU = float64(g.Value())
  1317. } else {
  1318. resultVGPU = resultGPU
  1319. }
  1320. return resultGPU, resultVGPU, nil
  1321. }
  1322. // Case 3: AWS vGPU
  1323. if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  1324. vgpuCount, err := getAllocatableVGPUs(cache)
  1325. if err != nil {
  1326. return -1, -1, err
  1327. }
  1328. vgpuCoeff := 10.0
  1329. if vgpuCount > 0.0 {
  1330. vgpuCoeff = vgpuCount
  1331. }
  1332. if vgpu.Value() != 0 {
  1333. resultGPU := float64(vgpu.Value()) / vgpuCoeff
  1334. resultVGPU := float64(vgpu.Value())
  1335. return resultGPU, resultVGPU, nil
  1336. }
  1337. }
  1338. // No GPU found
  1339. return -1, -1, nil
  1340. }
  1341. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  1342. daemonsets := cache.GetAllDaemonSets()
  1343. vgpuCount := 0.0
  1344. for _, ds := range daemonsets {
  1345. dsContainerList := &ds.SpecContainers
  1346. for _, ctnr := range *dsContainerList {
  1347. if ctnr.Args != nil {
  1348. for _, arg := range ctnr.Args {
  1349. if strings.Contains(arg, "--vgpu=") {
  1350. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  1351. if err != nil {
  1352. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  1353. continue
  1354. }
  1355. vgpuCount = vgpus
  1356. return vgpuCount, nil
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. return vgpuCount, nil
  1363. }
  1364. type PersistentVolumeClaimData struct {
  1365. Class string `json:"class"`
  1366. Claim string `json:"claim"`
  1367. Namespace string `json:"namespace"`
  1368. ClusterID string `json:"clusterId"`
  1369. TimesClaimed int `json:"timesClaimed"`
  1370. VolumeName string `json:"volumeName"`
  1371. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  1372. Values []*util.Vector `json:"values"`
  1373. }
  1374. func measureTime(start time.Time, threshold time.Duration, name string) {
  1375. elapsed := time.Since(start)
  1376. if elapsed > threshold {
  1377. log.Infof("[Profiler] %s: %s", elapsed, name)
  1378. }
  1379. }
  1380. func (cm *CostModel) QueryAllocation(window opencost.Window, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy opencost.AccumulateOption, shareIdle bool, filterString string) (*opencost.AllocationSetRange, error) {
  1381. // Validate window is legal
  1382. if window.IsOpen() || window.IsNegative() {
  1383. return nil, fmt.Errorf("illegal window: %s", window)
  1384. }
  1385. var totalsStore opencost.TotalsStore
  1386. // Idle is required for proportional asset costs
  1387. if includeProportionalAssetResourceCosts {
  1388. if !includeIdle {
  1389. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  1390. }
  1391. totalsStore = opencost.NewMemoryTotalsStore()
  1392. }
  1393. // Begin with empty response
  1394. asr := opencost.NewAllocationSetRange()
  1395. // Query for AllocationSets in increments of the given step duration,
  1396. // appending each to the response.
  1397. stepStart := *window.Start()
  1398. stepEnd := stepStart.Add(step)
  1399. var isAKS bool
  1400. for window.End().After(stepStart) {
  1401. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd)
  1402. if err != nil {
  1403. return nil, fmt.Errorf("error computing allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1404. }
  1405. if includeIdle {
  1406. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  1407. if err != nil {
  1408. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1409. }
  1410. if includeProportionalAssetResourceCosts {
  1411. // AKS is a special case - there can be a maximum of 2
  1412. // load balancers (1 public and 1 private) in an AKS cluster
  1413. // therefore, when calculating PARCs for load balancers,
  1414. // we must know if this is an AKS cluster
  1415. for _, node := range assetSet.Nodes {
  1416. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  1417. isAKS = true
  1418. break
  1419. }
  1420. }
  1421. _, err := opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  1422. if err != nil {
  1423. log.Errorf("Allocation: error updating asset resource totals for %s: %s", assetSet.Window, err)
  1424. }
  1425. }
  1426. idleSet, err := computeIdleAllocations(allocSet, assetSet, idleByNode)
  1427. if err != nil {
  1428. return nil, fmt.Errorf("error computing idle allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  1429. }
  1430. for _, idleAlloc := range idleSet.Allocations {
  1431. allocSet.Insert(idleAlloc)
  1432. }
  1433. }
  1434. asr.Append(allocSet)
  1435. stepStart = stepEnd
  1436. stepEnd = stepStart.Add(step)
  1437. }
  1438. // Apply allocation filter BEFORE aggregation if provided
  1439. if filterString != "" {
  1440. parser := allocation.NewAllocationFilterParser()
  1441. filterNode, err := parser.Parse(filterString)
  1442. if err != nil {
  1443. return nil, fmt.Errorf("invalid filter: %w", err)
  1444. }
  1445. compiler := opencost.NewAllocationMatchCompiler(nil)
  1446. matcher, err := compiler.Compile(filterNode)
  1447. if err != nil {
  1448. return nil, fmt.Errorf("failed to compile filter: %w", err)
  1449. }
  1450. filteredASR := opencost.NewAllocationSetRange()
  1451. for _, as := range asr.Slice() {
  1452. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  1453. for _, alloc := range as.Allocations {
  1454. if matcher.Matches(alloc) {
  1455. filteredAS.Set(alloc)
  1456. }
  1457. }
  1458. if filteredAS.Length() > 0 {
  1459. filteredASR.Append(filteredAS)
  1460. }
  1461. }
  1462. asr = filteredASR
  1463. }
  1464. // Set aggregation options and aggregate
  1465. var shareIdleOpt string
  1466. if shareIdle {
  1467. shareIdleOpt = opencost.ShareWeighted
  1468. } else {
  1469. shareIdleOpt = opencost.ShareNone
  1470. }
  1471. opts := &opencost.AllocationAggregationOptions{
  1472. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  1473. IdleByNode: idleByNode,
  1474. IncludeAggregatedMetadata: includeAggregatedMetadata,
  1475. ShareIdle: shareIdleOpt,
  1476. }
  1477. // Aggregate
  1478. err := asr.AggregateBy(aggregate, opts)
  1479. if err != nil {
  1480. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  1481. }
  1482. // Accumulate, if requested
  1483. if accumulateBy != opencost.AccumulateOptionNone {
  1484. asr, err = asr.Accumulate(accumulateBy)
  1485. if err != nil {
  1486. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  1487. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  1488. }
  1489. // when accumulating and returning PARCs, we need the totals for the
  1490. // accumulated windows to accurately compute a fraction
  1491. if includeProportionalAssetResourceCosts {
  1492. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  1493. if err != nil {
  1494. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  1495. }
  1496. _, err = opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  1497. if err != nil {
  1498. log.Errorf("Allocation: error updating asset resource totals for %s: %s", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  1499. }
  1500. }
  1501. }
  1502. if includeProportionalAssetResourceCosts {
  1503. for _, as := range asr.Allocations {
  1504. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  1505. if !ok {
  1506. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  1507. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  1508. }
  1509. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  1510. if !ok {
  1511. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  1512. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  1513. }
  1514. var totalPublicLbCost, totalPrivateLbCost float64
  1515. if isAKS && sharedLoadBalancer {
  1516. // loop through all assetTotals, adding all load balancer costs by public and private
  1517. for _, tot := range totalStoreByNode {
  1518. if tot.PrivateLoadBalancer {
  1519. totalPrivateLbCost += tot.LoadBalancerCost
  1520. } else {
  1521. totalPublicLbCost += tot.LoadBalancerCost
  1522. }
  1523. }
  1524. }
  1525. // loop through each allocation set, using total cost from totals store
  1526. for _, alloc := range as.Allocations {
  1527. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  1528. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  1529. // for each parc , check the totals store for each
  1530. // on a totals hit, set the corresponding total and calculate percentage
  1531. var totals *opencost.AssetTotals
  1532. if totalsLoc, found := totalStoreByCluster[key]; found {
  1533. totals = totalsLoc
  1534. }
  1535. if totalsLoc, found := totalStoreByNode[key]; found {
  1536. totals = totalsLoc
  1537. }
  1538. if totals == nil {
  1539. log.Errorf("unable to locate asset totals for allocation %s, corresponding PARC is being skipped", key)
  1540. continue
  1541. }
  1542. parc.CPUTotalCost = totals.CPUCost
  1543. parc.GPUTotalCost = totals.GPUCost
  1544. parc.RAMTotalCost = totals.RAMCost
  1545. parc.PVTotalCost = totals.PersistentVolumeCost
  1546. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  1547. // Azure is a special case - use computed totals above
  1548. // use the lbAllocations in the object to determine if
  1549. // this PARC is a public or private load balancer
  1550. // then set the total accordingly
  1551. // AKS only has 1 public and 1 private load balancer
  1552. lbAlloc, found := alloc.LoadBalancers[key]
  1553. if found {
  1554. if lbAlloc.Private {
  1555. parc.LoadBalancerTotalCost = totalPrivateLbCost
  1556. } else {
  1557. parc.LoadBalancerTotalCost = totalPublicLbCost
  1558. }
  1559. }
  1560. } else {
  1561. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  1562. }
  1563. opencost.ComputePercentages(&parc)
  1564. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return asr, nil
  1570. }
  1571. func computeIdleAllocations(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet, idleByNode bool) (*opencost.AllocationSet, error) {
  1572. if !allocSet.Window.Equal(assetSet.Window) {
  1573. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  1574. }
  1575. var allocTotals map[string]*opencost.AllocationTotals
  1576. var assetTotals map[string]*opencost.AssetTotals
  1577. if idleByNode {
  1578. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationNodeProp)
  1579. assetTotals = opencost.ComputeAssetTotals(assetSet, true)
  1580. } else {
  1581. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationClusterProp)
  1582. assetTotals = opencost.ComputeAssetTotals(assetSet, false)
  1583. }
  1584. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  1585. idleSet := opencost.NewAllocationSet(start, end)
  1586. for key, assetTotal := range assetTotals {
  1587. allocTotal, ok := allocTotals[key]
  1588. if !ok {
  1589. log.Warnf("Allocation: did not find allocations for asset key: %s", key)
  1590. // Use a zero-value set of totals. This indicates either (1) an
  1591. // error computing totals, or (2) that no allocations ran on the
  1592. // given node for the given window.
  1593. allocTotal = &opencost.AllocationTotals{
  1594. Cluster: assetTotal.Cluster,
  1595. Node: assetTotal.Node,
  1596. Start: assetTotal.Start,
  1597. End: assetTotal.End,
  1598. }
  1599. }
  1600. // Insert one idle allocation for each key (whether by node or
  1601. // by cluster), defined as the difference between the total
  1602. // asset cost and the allocated cost per-resource.
  1603. name := fmt.Sprintf("%s/%s", key, opencost.IdleSuffix)
  1604. err := idleSet.Insert(&opencost.Allocation{
  1605. Name: name,
  1606. Window: idleSet.Window.Clone(),
  1607. Properties: &opencost.AllocationProperties{
  1608. Cluster: assetTotal.Cluster,
  1609. Node: assetTotal.Node,
  1610. ProviderID: assetTotal.ProviderID,
  1611. },
  1612. Start: assetTotal.Start,
  1613. End: assetTotal.End,
  1614. CPUCost: assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost(),
  1615. GPUCost: assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost(),
  1616. RAMCost: assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost(),
  1617. })
  1618. if err != nil {
  1619. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  1620. }
  1621. }
  1622. return idleSet, nil
  1623. }
  1624. func (cm *CostModel) GetDataSource() source.OpenCostDataSource {
  1625. return cm.DataSource
  1626. }