diagnostics.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package prom
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/core/pkg/log"
  5. "github.com/opencost/opencost/core/pkg/source"
  6. "github.com/opencost/opencost/pkg/env"
  7. prometheus "github.com/prometheus/client_golang/api"
  8. )
  9. // Prometheus Metric Diagnostic IDs
  10. const (
  11. // CAdvisorDiagnosticMetricID is the identifier of the metric used to determine if cAdvisor is being scraped.
  12. CAdvisorDiagnosticMetricID = "cadvisorMetric"
  13. // CAdvisorLabelDiagnosticMetricID is the identifier of the metric used to determine if cAdvisor labels are correct.
  14. CAdvisorLabelDiagnosticMetricID = "cadvisorLabel"
  15. // KSMDiagnosticMetricID is the identifier for the metric used to determine if KSM metrics are being scraped.
  16. KSMDiagnosticMetricID = "ksmMetric"
  17. // KSMVersionDiagnosticMetricID is the identifier for the metric used to determine if KSM version is correct.
  18. KSMVersionDiagnosticMetricID = "ksmVersion"
  19. // KubecostDiagnosticMetricID is the identifier for the metric used to determine if Kubecost metrics are being scraped.
  20. KubecostDiagnosticMetricID = "kubecostMetric"
  21. // NodeExporterDiagnosticMetricID is the identifier for the metric used to determine if NodeExporter metrics are being scraped.
  22. NodeExporterDiagnosticMetricID = "neMetric"
  23. // ScrapeIntervalDiagnosticMetricID is the identifier for the metric used to determine if prometheus has its own self-scraped
  24. // metrics.
  25. ScrapeIntervalDiagnosticMetricID = "scrapeInterval"
  26. // CPUThrottlingDiagnosticMetricID is the identifier for the metric used to determine if CPU throttling is being applied to the
  27. // cost-model container.
  28. CPUThrottlingDiagnosticMetricID = "cpuThrottling"
  29. // KubecostRecordingRuleCPUUsageID is the identifier for the query used to
  30. // determine of the CPU usage recording rule is set up correctly.
  31. KubecostRecordingRuleCPUUsageID = "kubecostRecordingRuleCPUUsage"
  32. // CAdvisorWorkingSetBytesMetricID is the identifier for the query used to determine
  33. // if cAdvisor working set bytes data is being scraped
  34. CAdvisorWorkingSetBytesMetricID = "cadvisorWorkingSetBytesMetric"
  35. // KSMCPUCapacityMetricID is the identifier for the query used to determine if
  36. // KSM CPU capacity data is being scraped
  37. KSMCPUCapacityMetricID = "ksmCpuCapacityMetric"
  38. // KSMAllocatableCPUCoresMetricID is the identifier for the query used to determine
  39. // if KSM allocatable CPU core data is being scraped
  40. KSMAllocatableCPUCoresMetricID = "ksmAllocatableCpuCoresMetric"
  41. )
  42. const DocumentationBaseURL = "https://www.opencost.io/docs/"
  43. // diagnostic definitions mapping holds all of the diagnostic definitions that can be used for prometheus metrics diagnostics
  44. var diagnosticDefinitions map[string]*diagnosticDefinition = map[string]*diagnosticDefinition{
  45. CAdvisorDiagnosticMetricID: {
  46. ID: CAdvisorDiagnosticMetricID,
  47. QueryFmt: `absent_over_time(container_cpu_usage_seconds_total{%s}[5m] %s)`,
  48. Label: "cAdvisor metrics available",
  49. Description: "Determine if cAdvisor metrics are available during last 5 minutes.",
  50. DocLink: fmt.Sprintf("%s#cadvisor-metrics-available", DocumentationBaseURL),
  51. },
  52. KSMDiagnosticMetricID: {
  53. ID: KSMDiagnosticMetricID,
  54. QueryFmt: `absent_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[5m] %s)`,
  55. Label: "Kube-state-metrics available",
  56. Description: "Determine if metrics from kube-state-metrics are available during last 5 minutes.",
  57. DocLink: fmt.Sprintf("%s#kube-state-metrics-metrics-available", DocumentationBaseURL),
  58. },
  59. KubecostDiagnosticMetricID: {
  60. ID: KubecostDiagnosticMetricID,
  61. QueryFmt: `absent_over_time(node_cpu_hourly_cost{%s}[5m] %s)`,
  62. Label: "Kubecost metrics available",
  63. Description: "Determine if metrics from Kubecost are available during last 5 minutes.",
  64. },
  65. NodeExporterDiagnosticMetricID: {
  66. ID: NodeExporterDiagnosticMetricID,
  67. QueryFmt: `absent_over_time(node_cpu_seconds_total{%s}[5m] %s)`,
  68. Label: "Node-exporter metrics available",
  69. Description: "Determine if metrics from node-exporter are available during last 5 minutes.",
  70. DocLink: fmt.Sprintf("%s#node-exporter-metrics-available", DocumentationBaseURL),
  71. },
  72. CAdvisorLabelDiagnosticMetricID: {
  73. ID: CAdvisorLabelDiagnosticMetricID,
  74. QueryFmt: `absent_over_time(container_cpu_usage_seconds_total{container!="",pod!="", %s}[5m] %s)`,
  75. Label: "Expected cAdvisor labels available",
  76. Description: "Determine if expected cAdvisor labels are present during last 5 minutes.",
  77. DocLink: fmt.Sprintf("%s#cadvisor-metrics-available", DocumentationBaseURL),
  78. },
  79. KSMVersionDiagnosticMetricID: {
  80. ID: KSMVersionDiagnosticMetricID,
  81. QueryFmt: `absent_over_time(kube_persistentvolume_capacity_bytes{%s}[5m] %s)`,
  82. Label: "Expected kube-state-metrics version found",
  83. Description: "Determine if metric in required kube-state-metrics version are present during last 5 minutes.",
  84. DocLink: fmt.Sprintf("%s#expected-kube-state-metrics-version-found", DocumentationBaseURL),
  85. },
  86. ScrapeIntervalDiagnosticMetricID: {
  87. ID: ScrapeIntervalDiagnosticMetricID,
  88. QueryFmt: `absent_over_time(prometheus_target_interval_length_seconds{%s}[5m] %s)`,
  89. Label: "Expected Prometheus self-scrape metrics available",
  90. Description: "Determine if prometheus has its own self-scraped metrics during the last 5 minutes.",
  91. },
  92. CPUThrottlingDiagnosticMetricID: {
  93. ID: CPUThrottlingDiagnosticMetricID,
  94. QueryFmt: `avg(increase(container_cpu_cfs_throttled_periods_total{container="cost-model", %s}[10m] %s)) by (container_name, pod_name, namespace)
  95. / avg(increase(container_cpu_cfs_periods_total{container="cost-model",%s}[10m] %s)) by (container_name, pod_name, namespace) > 0.2`,
  96. Label: "Kubecost is not CPU throttled",
  97. Description: "Kubecost loading slowly? A kubecost component might be CPU throttled",
  98. },
  99. KubecostRecordingRuleCPUUsageID: {
  100. ID: KubecostRecordingRuleCPUUsageID,
  101. QueryFmt: `absent_over_time(kubecost_container_cpu_usage_irate{%s}[5m] %s)`,
  102. Label: "Kubecost's CPU usage recording rule is set up",
  103. Description: "If the 'kubecost_container_cpu_usage_irate' recording rule is not set up, Allocation pipeline build may put pressure on your Prometheus due to the use of a subquery.",
  104. DocLink: "https://www.opencost.io/docs/installation/prometheus",
  105. },
  106. CAdvisorWorkingSetBytesMetricID: {
  107. ID: CAdvisorWorkingSetBytesMetricID,
  108. QueryFmt: `absent_over_time(container_memory_working_set_bytes{container="cost-model", container!="POD", instance!="", %s}[5m] %s)`,
  109. Label: "cAdvisor working set bytes metrics available",
  110. Description: "Determine if cAdvisor working set bytes metrics are available during last 5 minutes.",
  111. },
  112. KSMCPUCapacityMetricID: {
  113. ID: KSMCPUCapacityMetricID,
  114. QueryFmt: `absent_over_time(kube_node_status_capacity_cpu_cores{%s}[5m] %s)`,
  115. Label: "KSM had CPU capacity during the last 5 minutes",
  116. Description: "Determine if KSM had CPU capacity during the last 5 minutes",
  117. },
  118. KSMAllocatableCPUCoresMetricID: {
  119. ID: KSMAllocatableCPUCoresMetricID,
  120. QueryFmt: `absent_over_time(kube_node_status_allocatable_cpu_cores{%s}[5m] %s)`,
  121. Label: "KSM had allocatable CPU cores during the last 5 minutes",
  122. Description: "Determine if KSM had allocatable CPU cores during the last 5 minutes",
  123. },
  124. }
  125. // RequestCounter is used to determine if the prometheus client keeps track of
  126. // the concurrent outbound requests
  127. type RequestCounter interface {
  128. TotalQueuedRequests() int
  129. TotalOutboundRequests() int
  130. }
  131. // QueuedPromRequest is a representation of a request waiting to be sent by the prometheus
  132. // client.
  133. type QueuedPromRequest struct {
  134. Context string `json:"context"`
  135. Query string `json:"query"`
  136. QueueTime int64 `json:"queueTime"`
  137. }
  138. // PrometheusQueueState contains diagnostic information concerning the state of the prometheus request
  139. // queue
  140. type PrometheusQueueState struct {
  141. QueuedRequests []*QueuedPromRequest `json:"queuedRequests"`
  142. OutboundRequests int `json:"outboundRequests"`
  143. TotalRequests int `json:"totalRequests"`
  144. MaxQueryConcurrency int `json:"maxQueryConcurrency"`
  145. }
  146. // GetPrometheusQueueState is a diagnostic function that probes the prometheus request queue and gathers
  147. // query, context, and queue statistics.
  148. func GetPrometheusQueueState(client prometheus.Client, config *OpenCostPrometheusConfig) (*PrometheusQueueState, error) {
  149. rlpc, ok := client.(*RateLimitedPrometheusClient)
  150. if !ok {
  151. return nil, fmt.Errorf("Failed to get prometheus queue state for the provided client. Must be of type RateLimitedPrometheusClient.")
  152. }
  153. outbound := rlpc.TotalOutboundRequests()
  154. requests := []*QueuedPromRequest{}
  155. rlpc.EachQueuedRequest(func(ctx string, query string, queueTimeMs int64) {
  156. requests = append(requests, &QueuedPromRequest{
  157. Context: ctx,
  158. Query: query,
  159. QueueTime: queueTimeMs,
  160. })
  161. })
  162. return &PrometheusQueueState{
  163. QueuedRequests: requests,
  164. OutboundRequests: outbound,
  165. TotalRequests: outbound + len(requests),
  166. MaxQueryConcurrency: config.ClientConfig.QueryConcurrency,
  167. }, nil
  168. }
  169. // LogPrometheusClientState logs the current state, with respect to outbound requests, if that
  170. // information is available.
  171. func LogPrometheusClientState(client prometheus.Client) {
  172. if rc, ok := client.(RequestCounter); ok {
  173. queued := rc.TotalQueuedRequests()
  174. outbound := rc.TotalOutboundRequests()
  175. total := queued + outbound
  176. log.Infof("Outbound Requests: %d, Queued Requests: %d, Total Requests: %d", outbound, queued, total)
  177. }
  178. }
  179. // GetPrometheusMetrics returns a list of the state of Prometheus metric used by kubecost using the provided client
  180. func GetPrometheusMetrics(client prometheus.Client, config *OpenCostPrometheusConfig, offset string) PrometheusDiagnostics {
  181. ctx := NewNamedContext(client, config, DiagnosticContextName)
  182. var result []*PrometheusDiagnostic
  183. for _, definition := range diagnosticDefinitions {
  184. pd := definition.NewDiagnostic(offset)
  185. err := pd.executePrometheusDiagnosticQuery(ctx)
  186. // log the errror, append to results anyways, and continue
  187. if err != nil {
  188. log.Errorf("error: %s", err.Error())
  189. }
  190. result = append(result, pd)
  191. }
  192. return result
  193. }
  194. // GetPrometheusMetricsByID returns a list of the state of specific Prometheus metrics by identifier.
  195. func GetPrometheusMetricsByID(ids []string, client prometheus.Client, config *OpenCostPrometheusConfig, offset string) PrometheusDiagnostics {
  196. ctx := NewNamedContext(client, config, DiagnosticContextName)
  197. var result []*PrometheusDiagnostic
  198. for _, id := range ids {
  199. if definition, ok := diagnosticDefinitions[id]; ok {
  200. pd := definition.NewDiagnostic(offset)
  201. err := pd.executePrometheusDiagnosticQuery(ctx)
  202. // log the errror, append to results anyways, and continue
  203. if err != nil {
  204. log.Errorf("error: %s", err.Error())
  205. }
  206. result = append(result, pd)
  207. } else {
  208. log.Warnf("Failed to find diagnostic definition for id: %s", id)
  209. }
  210. }
  211. return result
  212. }
  213. // PrometheusDiagnostics is a PrometheusDiagnostic container with helper methods.
  214. type PrometheusDiagnostics []*PrometheusDiagnostic
  215. // HasFailure returns true if any of the diagnostic tests didn't pass.
  216. func (pd PrometheusDiagnostics) HasFailure() bool {
  217. for _, p := range pd {
  218. if !p.Passed {
  219. return true
  220. }
  221. }
  222. return false
  223. }
  224. // diagnosticDefinition is a definition of a diagnostic that can be used to create new
  225. // PrometheusDiagnostic instances using the definition's fields.
  226. type diagnosticDefinition struct {
  227. ID string
  228. QueryFmt string
  229. Label string
  230. Description string
  231. DocLink string
  232. }
  233. // NewDiagnostic creates a new PrometheusDiagnostic instance using the provided definition data.
  234. func (pdd *diagnosticDefinition) NewDiagnostic(offset string) *PrometheusDiagnostic {
  235. // FIXME: Any reasonable way to get the total number of replacements required in the query?
  236. // FIXME: All of the other queries require a single offset replace, but CPUThrottle requires two.
  237. var query string
  238. filter := env.GetPromClusterFilter()
  239. if pdd.ID == CPUThrottlingDiagnosticMetricID {
  240. query = fmt.Sprintf(pdd.QueryFmt, filter, offset, filter, offset)
  241. } else {
  242. query = fmt.Sprintf(pdd.QueryFmt, filter, offset)
  243. }
  244. return &PrometheusDiagnostic{
  245. ID: pdd.ID,
  246. Query: query,
  247. Label: pdd.Label,
  248. Description: pdd.Description,
  249. DocLink: pdd.DocLink,
  250. }
  251. }
  252. // PrometheusDiagnostic holds information about a metric and the query to ensure it is functional
  253. type PrometheusDiagnostic struct {
  254. ID string `json:"id"`
  255. Query string `json:"query"`
  256. Label string `json:"label"`
  257. Description string `json:"description"`
  258. DocLink string `json:"docLink"`
  259. Result []*source.QueryResult `json:"result"`
  260. Passed bool `json:"passed"`
  261. }
  262. // executePrometheusDiagnosticQuery executes a PrometheusDiagnostic query using the given context
  263. func (pd *PrometheusDiagnostic) executePrometheusDiagnosticQuery(ctx *Context) error {
  264. resultCh := ctx.Query(pd.Query)
  265. result, err := resultCh.Await()
  266. if err != nil {
  267. return fmt.Errorf("prometheus diagnostic %s failed with error: %s", pd.ID, err)
  268. }
  269. if result == nil {
  270. result = []*source.QueryResult{}
  271. }
  272. pd.Result = result
  273. pd.Passed = len(result) == 0
  274. return nil
  275. }