costmodel.go 69 KB

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