costmodel.go 69 KB

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