diagnostics.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package prom
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/opencost/opencost/pkg/env"
  6. "github.com/opencost/opencost/pkg/log"
  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. )
  33. const DocumentationBaseURL = "https://github.com/kubecost/docs/blob/master/diagnostics.md"
  34. // diagnostic definitions mapping holds all of the diagnostic definitions that can be used for prometheus metrics diagnostics
  35. var diagnosticDefinitions map[string]*diagnosticDefinition = map[string]*diagnosticDefinition{
  36. CAdvisorDiagnosticMetricID: {
  37. ID: CAdvisorDiagnosticMetricID,
  38. QueryFmt: `absent_over_time(container_cpu_usage_seconds_total[5m] %s)`,
  39. Label: "cAdvsior metrics available",
  40. Description: "Determine if cAdvisor metrics are available during last 5 minutes.",
  41. DocLink: fmt.Sprintf("%s#cadvisor-metrics-available", DocumentationBaseURL),
  42. },
  43. KSMDiagnosticMetricID: {
  44. ID: KSMDiagnosticMetricID,
  45. QueryFmt: `absent_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte"}[5m] %s)`,
  46. Label: "Kube-state-metrics available",
  47. Description: "Determine if metrics from kube-state-metrics are available during last 5 minutes.",
  48. DocLink: fmt.Sprintf("%s#kube-state-metrics-metrics-available", DocumentationBaseURL),
  49. },
  50. KubecostDiagnosticMetricID: {
  51. ID: KubecostDiagnosticMetricID,
  52. QueryFmt: `absent_over_time(node_cpu_hourly_cost[5m] %s)`,
  53. Label: "Kubecost metrics available",
  54. Description: "Determine if metrics from Kubecost are available during last 5 minutes.",
  55. },
  56. NodeExporterDiagnosticMetricID: {
  57. ID: NodeExporterDiagnosticMetricID,
  58. QueryFmt: `absent_over_time(node_cpu_seconds_total[5m] %s)`,
  59. Label: "Node-exporter metrics available",
  60. Description: "Determine if metrics from node-exporter are available during last 5 minutes.",
  61. DocLink: fmt.Sprintf("%s#node-exporter-metrics-available", DocumentationBaseURL),
  62. },
  63. CAdvisorLabelDiagnosticMetricID: {
  64. ID: CAdvisorLabelDiagnosticMetricID,
  65. QueryFmt: `absent_over_time(container_cpu_usage_seconds_total{container!="",pod!=""}[5m] %s)`,
  66. Label: "Expected cAdvsior labels available",
  67. Description: "Determine if expected cAdvisor labels are present during last 5 minutes.",
  68. DocLink: fmt.Sprintf("%s#cadvisor-metrics-available", DocumentationBaseURL),
  69. },
  70. KSMVersionDiagnosticMetricID: {
  71. ID: KSMVersionDiagnosticMetricID,
  72. QueryFmt: `absent_over_time(kube_persistentvolume_capacity_bytes[5m] %s)`,
  73. Label: "Expected kube-state-metrics version found",
  74. Description: "Determine if metric in required kube-state-metrics version are present during last 5 minutes.",
  75. DocLink: fmt.Sprintf("%s#expected-kube-state-metrics-version-found", DocumentationBaseURL),
  76. },
  77. ScrapeIntervalDiagnosticMetricID: {
  78. ID: ScrapeIntervalDiagnosticMetricID,
  79. QueryFmt: `absent_over_time(prometheus_target_interval_length_seconds[5m] %s)`,
  80. Label: "Expected Prometheus self-scrape metrics available",
  81. Description: "Determine if prometheus has its own self-scraped metrics during the last 5 minutes.",
  82. },
  83. CPUThrottlingDiagnosticMetricID: {
  84. ID: CPUThrottlingDiagnosticMetricID,
  85. QueryFmt: `avg(increase(container_cpu_cfs_throttled_periods_total{container="cost-model"}[10m] %s)) by (container_name, pod_name, namespace)
  86. / avg(increase(container_cpu_cfs_periods_total{container="cost-model"}[10m] %s)) by (container_name, pod_name, namespace) > 0.2`,
  87. Label: "Kubecost is not CPU throttled",
  88. Description: "Kubecost loading slowly? A kubecost component might be CPU throttled",
  89. },
  90. KubecostRecordingRuleCPUUsageID: {
  91. ID: KubecostRecordingRuleCPUUsageID,
  92. QueryFmt: `absent_over_time(kubecost_container_cpu_usage_irate[5m] %s)`,
  93. Label: "Kubecost's CPU usage recording rule is set up",
  94. 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.",
  95. DocLink: "https://docs.kubecost.com/install-and-configure/install/custom-prom",
  96. },
  97. }
  98. // QueuedPromRequest is a representation of a request waiting to be sent by the prometheus
  99. // client.
  100. type QueuedPromRequest struct {
  101. Context string `json:"context"`
  102. Query string `json:"query"`
  103. QueueTime int64 `json:"queueTime"`
  104. }
  105. // PrometheusQueueState contains diagnostic information concerning the state of the prometheus request
  106. // queue
  107. type PrometheusQueueState struct {
  108. QueuedRequests []*QueuedPromRequest `json:"queuedRequests"`
  109. OutboundRequests int `json:"outboundRequests"`
  110. TotalRequests int `json:"totalRequests"`
  111. MaxQueryConcurrency int `json:"maxQueryConcurrency"`
  112. }
  113. // GetPrometheusQueueState is a diagnostic function that probes the prometheus request queue and gathers
  114. // query, context, and queue statistics.
  115. func GetPrometheusQueueState(client prometheus.Client) (*PrometheusQueueState, error) {
  116. rlpc, ok := client.(*RateLimitedPrometheusClient)
  117. if !ok {
  118. return nil, fmt.Errorf("Failed to get prometheus queue state for the provided client. Must be of type RateLimitedPrometheusClient.")
  119. }
  120. outbound := rlpc.TotalOutboundRequests()
  121. requests := []*QueuedPromRequest{}
  122. rlpc.queue.Each(func(_ int, req *workRequest) {
  123. requests = append(requests, &QueuedPromRequest{
  124. Context: req.contextName,
  125. Query: req.query,
  126. QueueTime: time.Since(req.start).Milliseconds(),
  127. })
  128. })
  129. return &PrometheusQueueState{
  130. QueuedRequests: requests,
  131. OutboundRequests: outbound,
  132. TotalRequests: outbound + len(requests),
  133. MaxQueryConcurrency: env.GetMaxQueryConcurrency(),
  134. }, nil
  135. }
  136. // LogPrometheusClientState logs the current state, with respect to outbound requests, if that
  137. // information is available.
  138. func LogPrometheusClientState(client prometheus.Client) {
  139. if rc, ok := client.(requestCounter); ok {
  140. queued := rc.TotalQueuedRequests()
  141. outbound := rc.TotalOutboundRequests()
  142. total := queued + outbound
  143. log.Infof("Outbound Requests: %d, Queued Requests: %d, Total Requests: %d", outbound, queued, total)
  144. }
  145. }
  146. // GetPrometheusMetrics returns a list of the state of Prometheus metric used by kubecost using the provided client
  147. func GetPrometheusMetrics(client prometheus.Client, offset string) PrometheusDiagnostics {
  148. ctx := NewNamedContext(client, DiagnosticContextName)
  149. var result []*PrometheusDiagnostic
  150. for _, definition := range diagnosticDefinitions {
  151. pd := definition.NewDiagnostic(offset)
  152. err := pd.executePrometheusDiagnosticQuery(ctx)
  153. // log the errror, append to results anyways, and continue
  154. if err != nil {
  155. log.Errorf(err.Error())
  156. }
  157. result = append(result, pd)
  158. }
  159. return result
  160. }
  161. // GetPrometheusMetricsByID returns a list of the state of specific Prometheus metrics by identifier.
  162. func GetPrometheusMetricsByID(ids []string, client prometheus.Client, offset string) PrometheusDiagnostics {
  163. ctx := NewNamedContext(client, DiagnosticContextName)
  164. var result []*PrometheusDiagnostic
  165. for _, id := range ids {
  166. if definition, ok := diagnosticDefinitions[id]; ok {
  167. pd := definition.NewDiagnostic(offset)
  168. err := pd.executePrometheusDiagnosticQuery(ctx)
  169. // log the errror, append to results anyways, and continue
  170. if err != nil {
  171. log.Errorf(err.Error())
  172. }
  173. result = append(result, pd)
  174. } else {
  175. log.Warnf("Failed to find diagnostic definition for id: %s", id)
  176. }
  177. }
  178. return result
  179. }
  180. // PrometheusDiagnostics is a PrometheusDiagnostic container with helper methods.
  181. type PrometheusDiagnostics []*PrometheusDiagnostic
  182. // HasFailure returns true if any of the diagnostic tests didn't pass.
  183. func (pd PrometheusDiagnostics) HasFailure() bool {
  184. for _, p := range pd {
  185. if !p.Passed {
  186. return true
  187. }
  188. }
  189. return false
  190. }
  191. // diagnosticDefinition is a definition of a diagnostic that can be used to create new
  192. // PrometheusDiagnostic instances using the definition's fields.
  193. type diagnosticDefinition struct {
  194. ID string
  195. QueryFmt string
  196. Label string
  197. Description string
  198. DocLink string
  199. }
  200. // NewDiagnostic creates a new PrometheusDiagnostic instance using the provided definition data.
  201. func (pdd *diagnosticDefinition) NewDiagnostic(offset string) *PrometheusDiagnostic {
  202. // FIXME: Any reasonable way to get the total number of replacements required in the query?
  203. // FIXME: All of the other queries require a single offset replace, but CPUThrottle requires two.
  204. var query string
  205. if pdd.ID == CPUThrottlingDiagnosticMetricID {
  206. query = fmt.Sprintf(pdd.QueryFmt, offset, offset)
  207. } else {
  208. query = fmt.Sprintf(pdd.QueryFmt, offset)
  209. }
  210. return &PrometheusDiagnostic{
  211. ID: pdd.ID,
  212. Query: query,
  213. Label: pdd.Label,
  214. Description: pdd.Description,
  215. DocLink: pdd.DocLink,
  216. }
  217. }
  218. // PrometheusDiagnostic holds information about a metric and the query to ensure it is functional
  219. type PrometheusDiagnostic struct {
  220. ID string `json:"id"`
  221. Query string `json:"query"`
  222. Label string `json:"label"`
  223. Description string `json:"description"`
  224. DocLink string `json:"docLink"`
  225. Result []*QueryResult `json:"result"`
  226. Passed bool `json:"passed"`
  227. }
  228. // executePrometheusDiagnosticQuery executes a PrometheusDiagnostic query using the given context
  229. func (pd *PrometheusDiagnostic) executePrometheusDiagnosticQuery(ctx *Context) error {
  230. resultCh := ctx.Query(pd.Query)
  231. result, err := resultCh.Await()
  232. if err != nil {
  233. return fmt.Errorf("prometheus diagnostic %s failed with error: %s", pd.ID, err)
  234. }
  235. if result == nil {
  236. result = []*QueryResult{}
  237. }
  238. pd.Result = result
  239. pd.Passed = len(result) == 0
  240. return nil
  241. }