costmodel.go 60 KB

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