metrics.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. package costmodel
  2. import (
  3. "maps"
  4. "math"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/opencost/opencost/core/pkg/clustercache"
  10. "github.com/opencost/opencost/core/pkg/clusters"
  11. coreenv "github.com/opencost/opencost/core/pkg/env"
  12. "github.com/opencost/opencost/core/pkg/errors"
  13. "github.com/opencost/opencost/core/pkg/log"
  14. "github.com/opencost/opencost/core/pkg/source"
  15. "github.com/opencost/opencost/core/pkg/util"
  16. "github.com/opencost/opencost/core/pkg/util/atomic"
  17. "github.com/opencost/opencost/core/pkg/util/promutil"
  18. "github.com/opencost/opencost/pkg/cloud/models"
  19. "github.com/opencost/opencost/pkg/env"
  20. "github.com/opencost/opencost/pkg/metrics"
  21. promclient "github.com/prometheus/client_golang/api"
  22. "github.com/prometheus/client_golang/prometheus"
  23. dto "github.com/prometheus/client_model/go"
  24. v1 "k8s.io/api/core/v1"
  25. )
  26. //--------------------------------------------------------------------------
  27. // ClusterInfoCollector
  28. //--------------------------------------------------------------------------
  29. // ClusterInfoCollector is a prometheus collector that generates ClusterInfoMetrics
  30. type ClusterInfoCollector struct {
  31. ClusterInfo clusters.ClusterInfoProvider
  32. metricsConfig metrics.MetricsConfig
  33. }
  34. // Describe sends the super-set of all possible descriptors of metrics
  35. // collected by this Collector.
  36. func (cic ClusterInfoCollector) Describe(ch chan<- *prometheus.Desc) {
  37. disabledMetrics := cic.metricsConfig.GetDisabledMetricsMap()
  38. if _, disabled := disabledMetrics["kubecost_cluster_info"]; disabled {
  39. return
  40. }
  41. ch <- prometheus.NewDesc("kubecost_cluster_info", "Kubecost Cluster Info", []string{}, nil)
  42. }
  43. // Collect is called by the Prometheus registry when collecting metrics.
  44. func (cic ClusterInfoCollector) Collect(ch chan<- prometheus.Metric) {
  45. disabledMetrics := cic.metricsConfig.GetDisabledMetricsMap()
  46. if _, disabled := disabledMetrics["kubecost_cluster_info"]; disabled {
  47. return
  48. }
  49. clusterInfo := cic.ClusterInfo.GetClusterInfo()
  50. labels := promutil.MapToLabels(clusterInfo)
  51. m := newClusterInfoMetric("kubecost_cluster_info", labels)
  52. ch <- m
  53. }
  54. //--------------------------------------------------------------------------
  55. // ClusterInfoMetric
  56. //--------------------------------------------------------------------------
  57. // ClusterInfoMetric is a prometheus.Metric used to encode the local cluster info
  58. type ClusterInfoMetric struct {
  59. fqName string
  60. help string
  61. labels map[string]string
  62. }
  63. // Creates a new ClusterInfoMetric, implementation of prometheus.Metric
  64. func newClusterInfoMetric(fqName string, labels map[string]string) ClusterInfoMetric {
  65. return ClusterInfoMetric{
  66. fqName: fqName,
  67. labels: labels,
  68. help: "kubecost_cluster_info ClusterInfo",
  69. }
  70. }
  71. // Desc returns the descriptor for the Metric. This method idempotently
  72. // returns the same descriptor throughout the lifetime of the Metric.
  73. func (cim ClusterInfoMetric) Desc() *prometheus.Desc {
  74. l := prometheus.Labels{}
  75. return prometheus.NewDesc(cim.fqName, cim.help, promutil.LabelNamesFrom(cim.labels), l)
  76. }
  77. // Write encodes the Metric into a "Metric" Protocol Buffer data
  78. // transmission object.
  79. func (cim ClusterInfoMetric) Write(m *dto.Metric) error {
  80. h := float64(1)
  81. m.Gauge = &dto.Gauge{
  82. Value: &h,
  83. }
  84. var labels []*dto.LabelPair
  85. for k, v := range cim.labels {
  86. labels = append(labels, &dto.LabelPair{
  87. Name: toStringPtr(k),
  88. Value: toStringPtr(v),
  89. })
  90. }
  91. m.Label = labels
  92. return nil
  93. }
  94. // returns a pointer to the string provided
  95. func toStringPtr(s string) *string { return &s }
  96. //--------------------------------------------------------------------------
  97. // Cost Model Metrics Initialization
  98. //--------------------------------------------------------------------------
  99. // Only allow the metrics to be instantiated and registered once
  100. var metricsInit sync.Once
  101. var (
  102. cpuGv *prometheus.GaugeVec
  103. ramGv *prometheus.GaugeVec
  104. gpuGv *prometheus.GaugeVec
  105. gpuCountGv *prometheus.GaugeVec
  106. pvGv *prometheus.GaugeVec
  107. spotGv *prometheus.GaugeVec
  108. totalGv *prometheus.GaugeVec
  109. ramAllocGv *prometheus.GaugeVec
  110. cpuAllocGv *prometheus.GaugeVec
  111. gpuAllocGv *prometheus.GaugeVec
  112. pvAllocGv *prometheus.GaugeVec
  113. networkZoneEgressCostG prometheus.Gauge
  114. networkRegionEgressCostG prometheus.Gauge
  115. networkInternetEgressCostG prometheus.Gauge
  116. networkNatGatewayEgressCostG prometheus.Gauge
  117. networkNatGatewayIngressCostG prometheus.Gauge
  118. clusterManagementCostGv *prometheus.GaugeVec
  119. lbCostGv *prometheus.GaugeVec
  120. )
  121. // initCostModelMetrics uses a sync.Once to ensure that these metrics are only created once
  122. func initCostModelMetrics(clusterInfo clusters.ClusterInfoProvider, metricsConfig *metrics.MetricsConfig) {
  123. disabledMetrics := metricsConfig.GetDisabledMetricsMap()
  124. var toRegisterGV []*prometheus.GaugeVec
  125. var toRegisterGauge []prometheus.Gauge
  126. metricsInit.Do(func() {
  127. cpuGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  128. Name: "node_cpu_hourly_cost",
  129. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  130. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  131. if _, disabled := disabledMetrics["node_cpu_hourly_cost"]; !disabled {
  132. toRegisterGV = append(toRegisterGV, cpuGv)
  133. }
  134. ramGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  135. Name: "node_ram_hourly_cost",
  136. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  137. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  138. if _, disabled := disabledMetrics["node_ram_hourly_cost"]; !disabled {
  139. toRegisterGV = append(toRegisterGV, ramGv)
  140. }
  141. gpuGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  142. Name: "node_gpu_hourly_cost",
  143. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  144. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  145. if _, disabled := disabledMetrics["node_gpu_hourly_cost"]; !disabled {
  146. toRegisterGV = append(toRegisterGV, gpuGv)
  147. }
  148. gpuCountGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  149. Name: "node_gpu_count",
  150. Help: "node_gpu_count count of gpu on this node",
  151. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  152. if _, disabled := disabledMetrics["node_gpu_count"]; !disabled {
  153. toRegisterGV = append(toRegisterGV, gpuCountGv)
  154. }
  155. pvGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  156. Name: "pv_hourly_cost",
  157. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  158. }, []string{"volumename", "persistentvolume", "provider_id", "uid"})
  159. if _, disabled := disabledMetrics["pv_hourly_cost"]; !disabled {
  160. toRegisterGV = append(toRegisterGV, pvGv)
  161. }
  162. spotGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  163. Name: "kubecost_node_is_spot",
  164. Help: "kubecost_node_is_spot Cloud provider info about node preemptibility",
  165. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  166. if _, disabled := disabledMetrics["kubecost_node_is_spot"]; !disabled {
  167. toRegisterGV = append(toRegisterGV, spotGv)
  168. }
  169. totalGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  170. Name: "node_total_hourly_cost",
  171. Help: "node_total_hourly_cost Total node cost per hour",
  172. }, []string{"instance", "node", "instance_type", "region", "provider_id", "arch", "uid"})
  173. if _, disabled := disabledMetrics["node_total_hourly_cost"]; !disabled {
  174. toRegisterGV = append(toRegisterGV, totalGv)
  175. }
  176. ramAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  177. Name: "container_memory_allocation_bytes",
  178. Help: "container_memory_allocation_bytes Bytes of RAM used",
  179. }, []string{"namespace", "pod", "container", "instance", "node", "uid"})
  180. if _, disabled := disabledMetrics["container_memory_allocation_bytes"]; !disabled {
  181. toRegisterGV = append(toRegisterGV, ramAllocGv)
  182. }
  183. cpuAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  184. Name: "container_cpu_allocation",
  185. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  186. }, []string{"namespace", "pod", "container", "instance", "node", "uid"})
  187. if _, disabled := disabledMetrics["container_cpu_allocation"]; !disabled {
  188. toRegisterGV = append(toRegisterGV, cpuAllocGv)
  189. }
  190. gpuAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  191. Name: "container_gpu_allocation",
  192. Help: "container_gpu_allocation GPU used",
  193. }, []string{"namespace", "pod", "container", "instance", "node", "uid"})
  194. if _, disabled := disabledMetrics["container_gpu_allocation"]; !disabled {
  195. toRegisterGV = append(toRegisterGV, gpuAllocGv)
  196. }
  197. pvAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  198. Name: "pod_pvc_allocation",
  199. Help: "pod_pvc_allocation Bytes used by a PVC attached to a pod",
  200. }, []string{"namespace", "pod", "persistentvolumeclaim", "persistentvolume", "uid"})
  201. if _, disabled := disabledMetrics["pod_pvc_allocation"]; !disabled {
  202. toRegisterGV = append(toRegisterGV, pvAllocGv)
  203. }
  204. networkZoneEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{
  205. Name: "kubecost_network_zone_egress_cost",
  206. Help: "kubecost_network_zone_egress_cost Total cost per GB egress across zones",
  207. })
  208. if _, disabled := disabledMetrics["kubecost_network_zone_egress_cost"]; !disabled {
  209. toRegisterGauge = append(toRegisterGauge, networkZoneEgressCostG)
  210. }
  211. networkRegionEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{
  212. Name: "kubecost_network_region_egress_cost",
  213. Help: "kubecost_network_region_egress_cost Total cost per GB egress across regions",
  214. })
  215. if _, disabled := disabledMetrics["kubecost_network_region_egress_cost"]; !disabled {
  216. toRegisterGauge = append(toRegisterGauge, networkRegionEgressCostG)
  217. }
  218. networkInternetEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{
  219. Name: "kubecost_network_internet_egress_cost",
  220. Help: "kubecost_network_internet_egress_cost Total cost per GB of internet egress.",
  221. })
  222. if _, disabled := disabledMetrics["kubecost_network_internet_egress_cost"]; !disabled {
  223. toRegisterGauge = append(toRegisterGauge, networkInternetEgressCostG)
  224. }
  225. networkNatGatewayEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{
  226. Name: "kubecost_network_nat_gateway_egress_cost",
  227. Help: "kubecost_network_nat_gateway_egress_cost Total cost per GB of nat gateway egress.",
  228. })
  229. if _, disabled := disabledMetrics["kubecost_network_nat_gateway_egress_cost"]; !disabled {
  230. toRegisterGauge = append(toRegisterGauge, networkNatGatewayEgressCostG)
  231. }
  232. networkNatGatewayIngressCostG = prometheus.NewGauge(prometheus.GaugeOpts{
  233. Name: "kubecost_network_nat_gateway_ingress_cost",
  234. Help: "kubecost_network_nat_gateway_ingress_cost Total cost per GB of nat gateway ingress.",
  235. })
  236. if _, disabled := disabledMetrics["kubecost_network_nat_gateway_ingress_cost"]; !disabled {
  237. toRegisterGauge = append(toRegisterGauge, networkNatGatewayIngressCostG)
  238. }
  239. clusterManagementCostGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  240. Name: "kubecost_cluster_management_cost",
  241. Help: "kubecost_cluster_management_cost Hourly cost paid as a cluster management fee.",
  242. }, []string{"provisioner_name"})
  243. if _, disabled := disabledMetrics["kubecost_cluster_management_cost"]; !disabled {
  244. toRegisterGV = append(toRegisterGV, clusterManagementCostGv)
  245. }
  246. lbCostGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ // no differentiation between ELB and ALB right now
  247. Name: "kubecost_load_balancer_cost",
  248. Help: "kubecost_load_balancer_cost Hourly cost of load balancer",
  249. }, []string{"ingress_ip", "namespace", "service_name", "uid"}) // assumes one ingress IP per load balancer
  250. if _, disabled := disabledMetrics["kubecost_load_balancer_cost"]; !disabled {
  251. toRegisterGV = append(toRegisterGV, lbCostGv)
  252. }
  253. // Register cost-model metrics for emission
  254. for _, gv := range toRegisterGV {
  255. prometheus.MustRegister(gv)
  256. }
  257. for _, g := range toRegisterGauge {
  258. prometheus.MustRegister(g)
  259. }
  260. // General Metric Collectors
  261. prometheus.MustRegister(ClusterInfoCollector{
  262. ClusterInfo: clusterInfo,
  263. metricsConfig: *metricsConfig,
  264. })
  265. })
  266. }
  267. //--------------------------------------------------------------------------
  268. // CostModelMetricsEmitter
  269. //--------------------------------------------------------------------------
  270. // CostModelMetricsEmitter emits all cost-model specific metrics calculated by
  271. // the CostModel.ComputeCostData() method.
  272. type CostModelMetricsEmitter struct {
  273. PrometheusClient promclient.Client
  274. KubeClusterCache clustercache.ClusterCache
  275. CloudProvider models.Provider
  276. Model *CostModel
  277. // Metrics
  278. CPUPriceRecorder *prometheus.GaugeVec
  279. RAMPriceRecorder *prometheus.GaugeVec
  280. PersistentVolumePriceRecorder *prometheus.GaugeVec
  281. GPUPriceRecorder *prometheus.GaugeVec
  282. GPUCountRecorder *prometheus.GaugeVec
  283. PVAllocationRecorder *prometheus.GaugeVec
  284. NodeSpotRecorder *prometheus.GaugeVec
  285. NodeTotalPriceRecorder *prometheus.GaugeVec
  286. RAMAllocationRecorder *prometheus.GaugeVec
  287. CPUAllocationRecorder *prometheus.GaugeVec
  288. GPUAllocationRecorder *prometheus.GaugeVec
  289. ClusterManagementCostRecorder *prometheus.GaugeVec
  290. LBCostRecorder *prometheus.GaugeVec
  291. NetworkZoneEgressRecorder prometheus.Gauge
  292. NetworkRegionEgressRecorder prometheus.Gauge
  293. NetworkInternetEgressRecorder prometheus.Gauge
  294. NetworkNatGatewayEgressRecorder prometheus.Gauge
  295. NetworkNatGatewayIngressRecorder prometheus.Gauge
  296. // Concurrent Flow Control - Manages the run state of the metric emitter
  297. runState atomic.AtomicRunState
  298. }
  299. // NewCostModelMetricsEmitter creates a new cost-model metrics emitter. Use Start() to begin metric emission.
  300. func NewCostModelMetricsEmitter(clusterCache clustercache.ClusterCache, provider models.Provider, clusterInfo clusters.ClusterInfoProvider, model *CostModel) *CostModelMetricsEmitter {
  301. // Get metric configurations, if any
  302. metricsConfig, err := metrics.GetMetricsConfig()
  303. if err != nil {
  304. log.Infof("Failed to get metrics config before init: %s", err)
  305. }
  306. if len(metricsConfig.DisabledMetrics) > 0 {
  307. log.Infof("Starting metrics init with disabled metrics: %v", metricsConfig.DisabledMetrics)
  308. }
  309. // init will only actually execute once to register the custom gauges
  310. initCostModelMetrics(clusterInfo, metricsConfig)
  311. metrics.InitKubeMetrics(clusterInfo, clusterCache, metricsConfig, &metrics.KubeMetricsOpts{
  312. EmitKubecostControllerMetrics: true,
  313. EmitNamespaceAnnotations: coreenv.IsEmitNamespaceAnnotationsMetric(),
  314. EmitPodAnnotations: coreenv.IsEmitPodAnnotationsMetric(),
  315. EmitKubeStateMetrics: coreenv.IsEmitKsmV1Metrics(),
  316. EmitKubeStateMetricsV1Only: coreenv.IsEmitKsmV1MetricsOnly(),
  317. EmitDeprecatedMetrics: coreenv.IsEmitDeprecatedMetrics(),
  318. })
  319. metrics.InitOpencostTelemetry(metricsConfig)
  320. return &CostModelMetricsEmitter{
  321. KubeClusterCache: clusterCache,
  322. CloudProvider: provider,
  323. Model: model,
  324. CPUPriceRecorder: cpuGv,
  325. RAMPriceRecorder: ramGv,
  326. GPUPriceRecorder: gpuGv,
  327. GPUCountRecorder: gpuCountGv,
  328. PersistentVolumePriceRecorder: pvGv,
  329. NodeSpotRecorder: spotGv,
  330. NodeTotalPriceRecorder: totalGv,
  331. RAMAllocationRecorder: ramAllocGv,
  332. CPUAllocationRecorder: cpuAllocGv,
  333. GPUAllocationRecorder: gpuAllocGv,
  334. PVAllocationRecorder: pvAllocGv,
  335. NetworkZoneEgressRecorder: networkZoneEgressCostG,
  336. NetworkRegionEgressRecorder: networkRegionEgressCostG,
  337. NetworkInternetEgressRecorder: networkInternetEgressCostG,
  338. NetworkNatGatewayEgressRecorder: networkNatGatewayEgressCostG,
  339. NetworkNatGatewayIngressRecorder: networkNatGatewayIngressCostG,
  340. ClusterManagementCostRecorder: clusterManagementCostGv,
  341. LBCostRecorder: lbCostGv,
  342. }
  343. }
  344. // IsRunning returns true if metric recording is running.
  345. func (cmme *CostModelMetricsEmitter) IsRunning() bool {
  346. return cmme.runState.IsRunning()
  347. }
  348. // NodeCostAverages tracks a running average of a node's cost attributes.
  349. // The averages are used to detect and discard spurrious outliers.
  350. type NodeCostAverages struct {
  351. CpuCostAverage float64
  352. RamCostAverage float64
  353. NumCpuDataPoints float64
  354. NumRamDataPoints float64
  355. }
  356. // StartCostModelMetricRecording starts the go routine that emits metrics used to determine
  357. // cluster costs.
  358. func (cmme *CostModelMetricsEmitter) Start() bool {
  359. // wait for a reset to prevent a race between start and stop calls
  360. cmme.runState.WaitForReset()
  361. // Check to see if we're already recording, and atomically advance the run state to start if we're not
  362. if !cmme.runState.Start() {
  363. log.Errorf("Attempted to start cost model metric recording when it's already running.")
  364. return false
  365. }
  366. go func() {
  367. defer errors.HandlePanic()
  368. containerSeen := make(map[string]bool)
  369. nodeSeen := make(map[string]bool)
  370. loadBalancerSeen := make(map[string]bool)
  371. pvSeen := make(map[string]bool)
  372. pvcSeen := make(map[string]bool)
  373. nodeCostAverages := make(map[string]NodeCostAverages)
  374. getKeyFromLabelStrings := func(labels ...string) string {
  375. return strings.Join(labels, ",")
  376. }
  377. getLabelStringsFromKey := func(key string) []string {
  378. return strings.Split(key, ",")
  379. }
  380. var defaultRegion string = ""
  381. nodeList := cmme.KubeClusterCache.GetAllNodes()
  382. if len(nodeList) > 0 {
  383. var ok bool
  384. defaultRegion, ok = util.GetRegion(nodeList[0].Labels)
  385. if !ok {
  386. log.DedupedWarningf(5, "Failed to read default region from labels on node %s", nodeList[0].Name)
  387. }
  388. }
  389. for {
  390. log.Debugf("Recording prices...")
  391. podlist := cmme.KubeClusterCache.GetAllPods()
  392. podStatus := make(map[string]v1.PodPhase)
  393. podUIDs := make(map[string]string)
  394. for _, pod := range podlist {
  395. podStatus[pod.Name] = pod.Status.Phase
  396. podUIDs[pod.Name] = string(pod.UID)
  397. }
  398. // Create node UID lookup map
  399. nodeList := cmme.KubeClusterCache.GetAllNodes()
  400. nodeUIDs := make(map[string]string)
  401. for _, node := range nodeList {
  402. nodeUIDs[node.Name] = string(node.UID)
  403. }
  404. // Create PV UID lookup map
  405. pvList := cmme.KubeClusterCache.GetAllPersistentVolumes()
  406. pvUIDs := make(map[string]string)
  407. for _, pv := range pvList {
  408. pvUIDs[pv.Name] = string(pv.UID)
  409. }
  410. // Create service UID lookup map
  411. serviceList := cmme.KubeClusterCache.GetAllServices()
  412. serviceUIDs := make(map[string]string)
  413. for _, service := range serviceList {
  414. serviceKey := service.Namespace + "/" + service.Name
  415. serviceUIDs[serviceKey] = string(service.UID)
  416. }
  417. cfg, _ := cmme.CloudProvider.GetConfig()
  418. provisioner, clusterManagementCost, err := cmme.CloudProvider.ClusterManagementPricing()
  419. if err != nil {
  420. log.Errorf("Error getting cluster management cost %s", err.Error())
  421. }
  422. cmme.ClusterManagementCostRecorder.WithLabelValues(provisioner).Set(clusterManagementCost)
  423. // Record network pricing at global scope
  424. networkCosts, err := cmme.CloudProvider.NetworkPricing()
  425. if err != nil {
  426. log.Debugf("Failed to retrieve network costs: %s", err.Error())
  427. } else {
  428. cmme.NetworkZoneEgressRecorder.Set(networkCosts.ZoneNetworkEgressCost)
  429. cmme.NetworkRegionEgressRecorder.Set(networkCosts.RegionNetworkEgressCost)
  430. cmme.NetworkInternetEgressRecorder.Set(networkCosts.InternetNetworkEgressCost)
  431. cmme.NetworkNatGatewayEgressRecorder.Set(networkCosts.NatGatewayEgressCost)
  432. cmme.NetworkNatGatewayIngressRecorder.Set(networkCosts.NatGatewayIngressCost)
  433. }
  434. end := time.Now()
  435. queryWindow := env.GetMetricsEmitterQueryWindow()
  436. start := end.Add(-queryWindow)
  437. data, err := cmme.Model.ComputeCostData(start, end)
  438. if err != nil {
  439. // For an error collection, we'll just log the length of the errors (ComputeCostData already logs the
  440. // actual errors)
  441. if source.IsErrorCollection(err) {
  442. if ec, ok := err.(source.QueryErrorCollection); ok {
  443. log.Errorf("Error in price recording: %d errors occurred", len(ec.Errors()))
  444. }
  445. } else {
  446. log.Errorf("Error in price recording: %s", err)
  447. }
  448. // zero the for loop so the time.Sleep will still work
  449. data = map[string]*CostData{}
  450. }
  451. nodes, err := cmme.Model.GetNodeCost()
  452. if err != nil {
  453. log.Warnf("Error getting Node cost: %s", err)
  454. }
  455. for nodeName, node := range nodes {
  456. // Get node UID first
  457. nodeUID := nodeUIDs[nodeName]
  458. // Emit costs, guarding against NaN inputs for custom pricing.
  459. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  460. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  461. cpuCost, _ = strconv.ParseFloat(cfg.CPU, 64)
  462. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  463. cpuCost = 0
  464. }
  465. }
  466. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  467. if math.IsNaN(cpu) || math.IsInf(cpu, 0) {
  468. cpu = 1 // Assume 1 CPU
  469. }
  470. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  471. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  472. ramCost, _ = strconv.ParseFloat(cfg.RAM, 64)
  473. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  474. ramCost = 0
  475. }
  476. }
  477. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  478. if math.IsNaN(ram) || math.IsInf(ram, 0) {
  479. ram = 0
  480. }
  481. gpu, _ := strconv.ParseFloat(node.GPU, 64)
  482. if math.IsNaN(gpu) || math.IsInf(gpu, 0) {
  483. gpu = 0
  484. }
  485. gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64)
  486. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  487. gpuCost, _ = strconv.ParseFloat(cfg.GPU, 64)
  488. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  489. gpuCost = 0
  490. }
  491. }
  492. nodeType := node.InstanceType
  493. nodeRegion := node.Region
  494. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost
  495. labelKey := getKeyFromLabelStrings(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID)
  496. avgCosts, ok := nodeCostAverages[labelKey]
  497. // initialize average cost tracking for this node if there is none
  498. if !ok {
  499. avgCosts = NodeCostAverages{
  500. CpuCostAverage: cpuCost,
  501. RamCostAverage: ramCost,
  502. NumCpuDataPoints: 1,
  503. NumRamDataPoints: 1,
  504. }
  505. nodeCostAverages[labelKey] = avgCosts
  506. }
  507. cmme.GPUCountRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(gpu)
  508. cmme.GPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(gpuCost)
  509. const outlierFactor float64 = 30
  510. // don't record cpuCost, ramCost, or gpuCost in the case of wild outliers
  511. // k8s api sometimes causes cost spikes as described here:
  512. // https://github.com/opencost/opencost/issues/927
  513. cpuOutlierCutoff := outlierFactor * avgCosts.CpuCostAverage
  514. if cpuCost < cpuOutlierCutoff {
  515. cmme.CPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(cpuCost)
  516. avgCosts.CpuCostAverage = (avgCosts.CpuCostAverage*avgCosts.NumCpuDataPoints + cpuCost) / (avgCosts.NumCpuDataPoints + 1)
  517. avgCosts.NumCpuDataPoints += 1
  518. } else {
  519. log.Debugf("CPU cost outlier detected; skipping data point: %s had %f as cost, which is above %f.", nodeName, cpuCost, cpuOutlierCutoff)
  520. }
  521. ramOutlierCutoff := outlierFactor * avgCosts.RamCostAverage
  522. if ramCost < ramOutlierCutoff {
  523. cmme.RAMPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(ramCost)
  524. avgCosts.RamCostAverage = (avgCosts.RamCostAverage*avgCosts.NumRamDataPoints + ramCost) / (avgCosts.NumRamDataPoints + 1)
  525. avgCosts.NumRamDataPoints += 1
  526. } else {
  527. log.Debugf("RAM cost outlier detected; skipping data point: %s had %f as cost, which is above %f.", nodeName, ramCost, ramOutlierCutoff)
  528. }
  529. // skip redording totalCost if any constituent costs were outliers
  530. if cpuCost < cpuOutlierCutoff && ramCost < ramOutlierCutoff {
  531. cmme.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(totalCost)
  532. } else {
  533. log.Debugf("CPU and RAM outlier detected, not recording node %s total cost %f", nodeName, totalCost)
  534. }
  535. nodeCostAverages[labelKey] = avgCosts
  536. if node.IsSpot() {
  537. cmme.NodeSpotRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(1.0)
  538. } else {
  539. cmme.NodeSpotRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID, node.ArchType, nodeUID).Set(0.0)
  540. }
  541. nodeSeen[labelKey] = true
  542. }
  543. loadBalancers, err := cmme.Model.GetLBCost()
  544. if err != nil {
  545. log.Warnf("Error getting LoadBalancer cost: %s", err)
  546. }
  547. for lbKey, lb := range loadBalancers {
  548. // TODO: parse (if necessary) and calculate cost associated with loadBalancer based on dynamic cloud prices fetched into each lb struct on GetLBCost() call
  549. namespace := lbKey.Namespace
  550. serviceName := lbKey.Service
  551. ingressIP := ""
  552. if len(lb.IngressIPAddresses) > 0 {
  553. ingressIP = lb.IngressIPAddresses[0] // assumes one ingress IP per load balancer
  554. }
  555. serviceKey := namespace + "/" + serviceName
  556. serviceUID := serviceUIDs[serviceKey]
  557. cmme.LBCostRecorder.WithLabelValues(ingressIP, namespace, serviceName, serviceUID).Set(lb.Cost)
  558. labelKey := getKeyFromLabelStrings(ingressIP, namespace, serviceName, serviceUID)
  559. loadBalancerSeen[labelKey] = true
  560. }
  561. for _, costs := range data {
  562. nodeName := costs.NodeName
  563. namespace := costs.Namespace
  564. podName := costs.PodName
  565. containerName := costs.Name
  566. if costs.PVCData != nil {
  567. for _, pvc := range costs.PVCData {
  568. if pvc.Volume != nil {
  569. timesClaimed := pvc.TimesClaimed
  570. if timesClaimed == 0 {
  571. timesClaimed = 1 // unallocated PVs are unclaimed but have a full allocation
  572. }
  573. podUID := podUIDs[podName]
  574. cmme.PVAllocationRecorder.WithLabelValues(namespace, podName, pvc.Claim, pvc.VolumeName, podUID).Set(pvc.Values[0].Value / float64(timesClaimed))
  575. labelKey := getKeyFromLabelStrings(namespace, podName, pvc.Claim, pvc.VolumeName, podUID)
  576. pvcSeen[labelKey] = true
  577. }
  578. }
  579. }
  580. if len(costs.RAMAllocation) > 0 {
  581. podUID := podUIDs[podName]
  582. cmme.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName, podUID).Set(costs.RAMAllocation[0].Value)
  583. }
  584. if len(costs.CPUAllocation) > 0 {
  585. podUID := podUIDs[podName]
  586. cmme.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName, podUID).Set(costs.CPUAllocation[0].Value)
  587. }
  588. if len(costs.GPUReq) > 0 {
  589. // allocation here is set to the request because shared GPU usage not yet supported.
  590. // if VPGUs, request x (actual/virtual)
  591. vgpu := 0.0
  592. gpu := 0.0
  593. var err, verr error
  594. if matchedNode, found := nodes[nodeName]; found {
  595. vgpu, verr = strconv.ParseFloat(matchedNode.VGPU, 64)
  596. gpu, err = strconv.ParseFloat(matchedNode.GPU, 64)
  597. } else {
  598. log.Tracef("cost data for node %s had GPUReq, but there was no cost data available for the node", nodeName)
  599. log.Trace("defaulting GPU to 0 cost")
  600. }
  601. gpualloc := costs.GPUReq[0].Value
  602. if verr != nil && err != nil && vgpu != 0 {
  603. gpualloc = gpualloc * (gpu / vgpu)
  604. }
  605. podUID := podUIDs[podName]
  606. cmme.GPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName, podUID).Set(gpualloc)
  607. }
  608. podUID := podUIDs[podName]
  609. labelKey := getKeyFromLabelStrings(namespace, podName, containerName, nodeName, nodeName, podUID)
  610. if podStatus[podName] == v1.PodRunning { // Only report data for current pods
  611. containerSeen[labelKey] = true
  612. } else {
  613. containerSeen[labelKey] = false
  614. }
  615. }
  616. storageClasses := cmme.KubeClusterCache.GetAllStorageClasses()
  617. storageClassMap := make(map[string]map[string]string)
  618. for _, storageClass := range storageClasses {
  619. params := maps.Clone(storageClass.Parameters)
  620. storageClassMap[storageClass.Name] = params
  621. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  622. storageClassMap["default"] = params
  623. storageClassMap[""] = params
  624. }
  625. }
  626. pvs := cmme.KubeClusterCache.GetAllPersistentVolumes()
  627. for _, pv := range pvs {
  628. // Omit pv_hourly_cost if the volume status is failed
  629. if pv.Status.Phase == v1.VolumeFailed {
  630. continue
  631. }
  632. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  633. if !ok {
  634. log.Debugf("Unable to find parameters for storage class \"%s\". Pv \"%s\" might have an empty or invalid storageClassName.", pv.Spec.StorageClassName, pv.Name)
  635. }
  636. var region string
  637. if r, ok := util.GetRegion(pv.Labels); ok {
  638. region = r
  639. } else {
  640. region = defaultRegion
  641. }
  642. cacPv := &models.PV{
  643. Class: pv.Spec.StorageClassName,
  644. Region: region,
  645. Parameters: parameters,
  646. }
  647. cmme.Model.GetPVCost(cacPv, pv, region)
  648. c, _ := strconv.ParseFloat(cacPv.Cost, 64)
  649. pvUID := pvUIDs[pv.Name]
  650. cmme.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name, cacPv.ProviderID, pvUID).Set(c)
  651. labelKey := getKeyFromLabelStrings(pv.Name, pv.Name, cacPv.ProviderID, pvUID)
  652. pvSeen[labelKey] = true
  653. }
  654. // Remove metrics on Nodes/LoadBalancers/Containers/PVs that no
  655. // longer exist
  656. for labelString, seen := range nodeSeen {
  657. if !seen {
  658. log.Debugf("Removing metrics for %s, no data observed recently", labelString)
  659. labels := getLabelStringsFromKey(labelString)
  660. ok := cmme.NodeTotalPriceRecorder.DeleteLabelValues(labels...)
  661. if ok {
  662. log.Debugf("No data observed for node with labels %v, removed from totalprice", labels)
  663. } else {
  664. log.Warnf("Failed to remove label set %v from metric node_total_hourly_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  665. }
  666. ok = cmme.NodeSpotRecorder.DeleteLabelValues(labels...)
  667. if ok {
  668. log.Debugf("No data observed for node with labels %v, removed from spot records", labels)
  669. } else {
  670. log.Warnf("Failed to remove label set %v from metric kubecost_node_is_spot. Failure to remove stale metrics may result in inaccurate data.", labels)
  671. }
  672. ok = cmme.CPUPriceRecorder.DeleteLabelValues(labels...)
  673. if ok {
  674. log.Debugf("No data observed for node with labels %v, removed from cpuprice", labels)
  675. } else {
  676. log.Warnf("Failed to remove label set %v from metric node_cpu_hourly_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  677. }
  678. ok = cmme.GPUPriceRecorder.DeleteLabelValues(labels...)
  679. if ok {
  680. log.Debugf("No data observed for node with labels %v, removed from gpuprice", labels)
  681. } else {
  682. log.Warnf("Failed to remove label set %v from metric node_gpu_hourly_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  683. }
  684. ok = cmme.GPUCountRecorder.DeleteLabelValues(labels...)
  685. if ok {
  686. log.Debugf("No data observed for node with labels %v, removed from gpucount", labels)
  687. } else {
  688. log.Warnf("Failed to remove label set %v from metric node_gpu_count. Failure to remove stale metrics may result in inaccurate data.", labels)
  689. }
  690. ok = cmme.RAMPriceRecorder.DeleteLabelValues(labels...)
  691. if ok {
  692. log.Debugf("No data observed for node with labels %v, removed from ramprice", labels)
  693. } else {
  694. log.Warnf("Failed to remove label set %v from metric node_ram_hourly_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  695. }
  696. delete(nodeSeen, labelString)
  697. delete(nodeCostAverages, labelString)
  698. } else {
  699. nodeSeen[labelString] = false
  700. }
  701. }
  702. for labelString, seen := range loadBalancerSeen {
  703. if !seen {
  704. labels := getLabelStringsFromKey(labelString)
  705. ok := cmme.LBCostRecorder.DeleteLabelValues(labels...)
  706. if !ok {
  707. log.Warnf("Failed to remove label set %v from metric kubecost_load_balancer_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  708. }
  709. delete(loadBalancerSeen, labelString)
  710. } else {
  711. loadBalancerSeen[labelString] = false
  712. }
  713. }
  714. for labelString, seen := range containerSeen {
  715. if !seen {
  716. labels := getLabelStringsFromKey(labelString)
  717. if len(labels) >= 2 && labels[1] != unmountedPVsContainer { // special "pod" to contain the unmounted PVs - does not have RAM/CPU/...
  718. ok := cmme.RAMAllocationRecorder.DeleteLabelValues(labels...)
  719. if !ok {
  720. log.Warnf("Failed to remove label set %v from metric container_memory_allocation_bytes. Failure to remove stale metrics may result in inaccurate data.", labels)
  721. }
  722. ok = cmme.CPUAllocationRecorder.DeleteLabelValues(labels...)
  723. if !ok {
  724. log.Warnf("Failed to remove label set %v from metric container_cpu_allocation. Failure to remove stale metrics may result in inaccurate data.", labels)
  725. }
  726. ok = cmme.GPUAllocationRecorder.DeleteLabelValues(labels...)
  727. if !ok {
  728. log.Warnf("Failed to remove label set %v from metric container_gpu_allocation. Failure to remove stale metrics may result in inaccurate data.", labels)
  729. }
  730. } else {
  731. log.Debugf("Did not try to delete RAM/CPU/GPU for fake '%s' container: %v", unmountedPVsContainer, labels)
  732. }
  733. delete(containerSeen, labelString)
  734. } else {
  735. containerSeen[labelString] = false
  736. }
  737. }
  738. for labelString, seen := range pvSeen {
  739. if !seen {
  740. labels := getLabelStringsFromKey(labelString)
  741. ok := cmme.PersistentVolumePriceRecorder.DeleteLabelValues(labels...)
  742. if !ok {
  743. log.Warnf("Failed to remove label set %v from metric pv_hourly_cost. Failure to remove stale metrics may result in inaccurate data.", labels)
  744. }
  745. delete(pvSeen, labelString)
  746. } else {
  747. pvSeen[labelString] = false
  748. }
  749. }
  750. for labelString, seen := range pvcSeen {
  751. if !seen {
  752. labels := getLabelStringsFromKey(labelString)
  753. ok := cmme.PVAllocationRecorder.DeleteLabelValues(labels...)
  754. if !ok {
  755. log.Warnf("Failed to remove label set %v from metric pod_pvc_allocation. Failure to remove stale metrics may result in inaccurate data.", labels)
  756. }
  757. delete(pvcSeen, labelString)
  758. } else {
  759. pvcSeen[labelString] = false
  760. }
  761. }
  762. select {
  763. case <-time.After(time.Minute):
  764. case <-cmme.runState.OnStop():
  765. cmme.runState.Reset()
  766. return
  767. }
  768. }
  769. }()
  770. return true
  771. }
  772. // Stop halts the metrics emission loop after the current emission is completed
  773. // or if the emission is paused.
  774. func (cmme *CostModelMetricsEmitter) Stop() {
  775. cmme.runState.Stop()
  776. }