prom.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package prom
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. "github.com/opencost/opencost/core/pkg/collections"
  15. "github.com/opencost/opencost/core/pkg/log"
  16. "github.com/opencost/opencost/core/pkg/util/fileutil"
  17. "github.com/opencost/opencost/core/pkg/util/httputil"
  18. "github.com/opencost/opencost/core/pkg/version"
  19. golog "log"
  20. prometheus "github.com/prometheus/client_golang/api"
  21. )
  22. var UserAgent = fmt.Sprintf("Opencost/%s", version.Version)
  23. //--------------------------------------------------------------------------
  24. // QueryParamsDecorator
  25. //--------------------------------------------------------------------------
  26. // QueryParamsDecorator is used to decorate and return query parameters for
  27. // outgoing requests
  28. type QueryParamsDecorator = func(path string, values url.Values) url.Values
  29. //--------------------------------------------------------------------------
  30. // ClientAuth
  31. //--------------------------------------------------------------------------
  32. // ClientAuth is used to authenticate outgoing client requests.
  33. type ClientAuth struct {
  34. Username string
  35. Password string
  36. BearerToken string
  37. }
  38. // DefaultClientAuth returns a non-nil default ClientAuth instance.
  39. func DefaultClientAuth() *ClientAuth {
  40. return &ClientAuth{
  41. Username: "",
  42. Password: "",
  43. BearerToken: "",
  44. }
  45. }
  46. // Apply Applies the authentication data to the request headers
  47. func (auth *ClientAuth) Apply(req *http.Request) {
  48. if auth == nil {
  49. return
  50. }
  51. if auth.Username != "" {
  52. req.SetBasicAuth(auth.Username, auth.Password)
  53. }
  54. if auth.BearerToken != "" {
  55. token := "Bearer " + auth.BearerToken
  56. req.Header.Add("Authorization", token)
  57. }
  58. }
  59. //--------------------------------------------------------------------------
  60. // Rate Limit Options
  61. //--------------------------------------------------------------------------
  62. // MaxRetryAfterDuration is the maximum amount of time we should ever wait
  63. // during a retry. This is to prevent starvation on the request threads
  64. const MaxRetryAfterDuration = 10 * time.Second
  65. // Default header key for Mimir/Cortex-Tenant API requests
  66. const HeaderXScopeOrgId = "X-Scope-OrgID"
  67. // RateLimitRetryOpts contains retry options
  68. type RateLimitRetryOpts struct {
  69. MaxRetries int
  70. DefaultRetryWait time.Duration
  71. }
  72. // RateLimitResponseStatus contains the status of the rate limited retries
  73. type RateLimitResponseStatus struct {
  74. RetriesRemaining int
  75. WaitTime time.Duration
  76. }
  77. // String creates a string representation of the rate limit status
  78. func (rtrs *RateLimitResponseStatus) String() string {
  79. return fmt.Sprintf("Wait Time: %.2f seconds, Retries Remaining: %d", rtrs.WaitTime.Seconds(), rtrs.RetriesRemaining)
  80. }
  81. // RateLimitedError contains a list of retry statuses that occurred during
  82. // retries on a rate limited response
  83. type RateLimitedResponseError struct {
  84. RateLimitStatus []*RateLimitResponseStatus
  85. }
  86. // Error returns a string representation of the error, including the rate limit
  87. // status reports
  88. func (rlre *RateLimitedResponseError) Error() string {
  89. var sb strings.Builder
  90. sb.WriteString("Request was Rate Limited and Retries Exhausted:\n")
  91. for _, rls := range rlre.RateLimitStatus {
  92. sb.WriteString(" * ")
  93. sb.WriteString(rls.String())
  94. sb.WriteString("\n")
  95. }
  96. return sb.String()
  97. }
  98. //--------------------------------------------------------------------------
  99. // RateLimitedPrometheusClient
  100. //--------------------------------------------------------------------------
  101. // RateLimitedPrometheusClient is a prometheus client which limits the total number of
  102. // concurrent outbound requests allowed at a given moment.
  103. type RateLimitedPrometheusClient struct {
  104. id string
  105. client prometheus.Client
  106. auth *ClientAuth
  107. queue collections.BlockingQueue[*workRequest]
  108. decorator QueryParamsDecorator
  109. rateLimitRetry *RateLimitRetryOpts
  110. outbound atomic.Int32
  111. fileLogger *golog.Logger
  112. headerXScopeOrgId string
  113. }
  114. // NewRateLimitedClient creates a prometheus client which limits the number of concurrent outbound
  115. // prometheus requests.
  116. func NewRateLimitedClient(
  117. id string,
  118. client prometheus.Client,
  119. maxConcurrency int,
  120. auth *ClientAuth,
  121. decorator QueryParamsDecorator,
  122. rateLimitRetryOpts *RateLimitRetryOpts,
  123. queryLogFile string,
  124. headerXScopeOrgId string,
  125. ) (prometheus.Client, error) {
  126. queue := collections.NewBlockingQueue[*workRequest]()
  127. var logger *golog.Logger
  128. if queryLogFile != "" {
  129. exists, err := fileutil.FileExists(queryLogFile)
  130. if err != nil {
  131. log.Infof("Failed to check for existence of queryLogFile: %s: %s", queryLogFile, err)
  132. }
  133. if exists {
  134. err = os.Remove(queryLogFile)
  135. if err != nil {
  136. log.Infof("Failed to remove queryLogFile: %s: %s", queryLogFile, err)
  137. }
  138. }
  139. f, err := os.OpenFile(queryLogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  140. if err != nil {
  141. log.Infof("Failed to open queryLogFile: %s for query logging: %s", queryLogFile, err)
  142. } else {
  143. logger = golog.New(f, "query-log", golog.LstdFlags)
  144. }
  145. }
  146. // default authentication
  147. if auth == nil {
  148. auth = DefaultClientAuth()
  149. }
  150. rlpc := &RateLimitedPrometheusClient{
  151. id: id,
  152. client: client,
  153. queue: queue,
  154. decorator: decorator,
  155. rateLimitRetry: rateLimitRetryOpts,
  156. auth: auth,
  157. fileLogger: logger,
  158. headerXScopeOrgId: headerXScopeOrgId,
  159. }
  160. // Start concurrent request processing
  161. for i := 0; i < maxConcurrency; i++ {
  162. go rlpc.worker()
  163. }
  164. return rlpc, nil
  165. }
  166. // ID is used to identify the type of client
  167. func (rlpc *RateLimitedPrometheusClient) ID() string {
  168. return rlpc.id
  169. }
  170. // TotalRequests returns the total number of requests that are either waiting to be sent and/or
  171. // are currently outbound.
  172. func (rlpc *RateLimitedPrometheusClient) TotalQueuedRequests() int {
  173. return rlpc.queue.Length()
  174. }
  175. // TotalOutboundRequests returns the total number of concurrent outbound requests, which have been
  176. // sent to the server and are awaiting response.
  177. func (rlpc *RateLimitedPrometheusClient) TotalOutboundRequests() int {
  178. return int(rlpc.outbound.Load())
  179. }
  180. // Passthrough to the prometheus client API
  181. func (rlpc *RateLimitedPrometheusClient) URL(ep string, args map[string]string) *url.URL {
  182. return rlpc.client.URL(ep, args)
  183. }
  184. // EachQueuedRequest provides a mechanism to safely iterate through all queued request and return
  185. // metadata about each request.
  186. func (rlpc *RateLimitedPrometheusClient) EachQueuedRequest(f func(ctx string, query string, queueTimeMs int64)) {
  187. rlpc.queue.Each(func(_ int, req *workRequest) {
  188. f(req.contextName, req.query, time.Since(req.start).Milliseconds())
  189. })
  190. }
  191. // workRequest is used to queue requests
  192. type workRequest struct {
  193. ctx context.Context
  194. req *http.Request
  195. start time.Time
  196. respChan chan *workResponse
  197. // used as a sentinel value to close the worker goroutine
  198. closer bool
  199. // request metadata for diagnostics
  200. contextName string
  201. query string
  202. }
  203. // workResponse is the response payload returned to the Do method
  204. type workResponse struct {
  205. res *http.Response
  206. body []byte
  207. err error
  208. }
  209. // worker is used as a consumer goroutine to pull workRequest from the blocking queue and execute them
  210. func (rlpc *RateLimitedPrometheusClient) worker() {
  211. retryOpts := rlpc.rateLimitRetry
  212. retryRateLimit := retryOpts != nil
  213. for {
  214. // blocks until there is an item available
  215. we := rlpc.queue.Dequeue()
  216. // if we need to shut down all workers, we'll need to submit sentinel values
  217. // that will force the worker to return
  218. if we.closer {
  219. return
  220. }
  221. ctx := we.ctx
  222. req := we.req
  223. // decorate the raw query parameters
  224. if rlpc.decorator != nil {
  225. req.URL.RawQuery = rlpc.decorator(req.URL.Path, req.URL.Query()).Encode()
  226. }
  227. // measure time in queue
  228. timeInQueue := time.Since(we.start)
  229. // Increment outbound counter
  230. rlpc.outbound.Add(1)
  231. // Execute Request
  232. roundTripStart := time.Now()
  233. res, body, err := rlpc.client.Do(ctx, req)
  234. // If retries on rate limited response is enabled:
  235. // * Check for a 429 StatusCode OR 400 StatusCode and message containing "ThrottlingException"
  236. // * Attempt to parse a Retry-After from response headers (common on 429)
  237. // * If we couldn't determine how long to wait for a retry, use 1 second by default
  238. if res != nil && retryRateLimit {
  239. var status []*RateLimitResponseStatus
  240. var retries int = retryOpts.MaxRetries
  241. var defaultWait time.Duration = retryOpts.DefaultRetryWait
  242. for httputil.IsRateLimited(res, body) && retries > 0 {
  243. // calculate amount of time to wait before retry, in the event the default wait is used,
  244. // an exponential backoff is applied based on the number of times we've retried.
  245. retryAfter := httputil.RateLimitedRetryFor(res, defaultWait, retryOpts.MaxRetries-retries)
  246. retries--
  247. status = append(status, &RateLimitResponseStatus{RetriesRemaining: retries, WaitTime: retryAfter})
  248. log.DedupedInfof(50, "Rate Limited Prometheus Request. Waiting for: %d ms. Retries Remaining: %d", retryAfter.Milliseconds(), retries)
  249. // To prevent total starvation of request threads, hard limit wait time to 10s. We also want quota limits/throttles
  250. // to eventually pass through as an error. For example, if some quota is reached with 10 days left, we clearly
  251. // don't want to block for 10 days.
  252. if retryAfter > MaxRetryAfterDuration {
  253. retryAfter = MaxRetryAfterDuration
  254. }
  255. // execute wait and retry
  256. time.Sleep(retryAfter)
  257. res, body, err = rlpc.client.Do(ctx, req)
  258. }
  259. // if we've broken out of our retry loop and the resp is still rate limited,
  260. // then let's generate a meaningful error to pass back
  261. if retries == 0 && httputil.IsRateLimited(res, body) {
  262. err = &RateLimitedResponseError{RateLimitStatus: status}
  263. }
  264. }
  265. // Decrement outbound counter
  266. rlpc.outbound.Add(-1)
  267. LogQueryRequest(rlpc.fileLogger, req, timeInQueue, time.Since(roundTripStart))
  268. // Pass back response data over channel to caller
  269. we.respChan <- &workResponse{
  270. res: res,
  271. body: body,
  272. err: err,
  273. }
  274. }
  275. }
  276. // Rate limit and passthrough to prometheus client API
  277. func (rlpc *RateLimitedPrometheusClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
  278. if rlpc.headerXScopeOrgId != "" {
  279. req.Header.Set(HeaderXScopeOrgId, rlpc.headerXScopeOrgId)
  280. }
  281. rlpc.auth.Apply(req)
  282. respChan := make(chan *workResponse)
  283. defer close(respChan)
  284. // request names are used as a debug utility to identify requests in queue
  285. contextName := "<none>"
  286. if n, ok := httputil.GetName(req); ok {
  287. contextName = n
  288. }
  289. query, _ := httputil.GetQuery(req)
  290. rlpc.queue.Enqueue(&workRequest{
  291. ctx: ctx,
  292. req: req,
  293. start: time.Now(),
  294. respChan: respChan,
  295. closer: false,
  296. contextName: contextName,
  297. query: query,
  298. })
  299. workRes := <-respChan
  300. return workRes.res, workRes.body, workRes.err
  301. }
  302. //--------------------------------------------------------------------------
  303. // Client Helpers
  304. //--------------------------------------------------------------------------
  305. // PrometheusClientConfig contains all configurable options for creating a new prometheus client
  306. type PrometheusClientConfig struct {
  307. Timeout time.Duration
  308. KeepAlive time.Duration
  309. TLSHandshakeTimeout time.Duration
  310. TLSInsecureSkipVerify bool
  311. RateLimitRetryOpts *RateLimitRetryOpts
  312. Auth *ClientAuth
  313. QueryConcurrency int
  314. QueryLogFile string
  315. HeaderXScopeOrgId string
  316. RootCAs *x509.CertPool
  317. ClientCertificates []tls.Certificate
  318. }
  319. // NewPrometheusClient creates a new rate limited client which limits by outbound concurrent requests.
  320. func NewPrometheusClient(address string, config *PrometheusClientConfig) (prometheus.Client, error) {
  321. // may be necessary for long prometheus queries
  322. rt := httputil.NewUserAgentTransport(UserAgent, &http.Transport{
  323. Proxy: http.ProxyFromEnvironment,
  324. DialContext: (&net.Dialer{
  325. Timeout: config.Timeout,
  326. KeepAlive: config.KeepAlive,
  327. }).DialContext,
  328. TLSHandshakeTimeout: config.TLSHandshakeTimeout,
  329. TLSClientConfig: &tls.Config{
  330. InsecureSkipVerify: config.TLSInsecureSkipVerify,
  331. RootCAs: config.RootCAs,
  332. Certificates: config.ClientCertificates,
  333. MinVersion: tls.VersionTLS12,
  334. },
  335. })
  336. pc := prometheus.Config{
  337. Address: address,
  338. RoundTripper: rt,
  339. }
  340. client, err := prometheus.NewClient(pc)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return NewRateLimitedClient(
  345. PrometheusClientID,
  346. client,
  347. config.QueryConcurrency,
  348. config.Auth,
  349. nil,
  350. config.RateLimitRetryOpts,
  351. config.QueryLogFile,
  352. config.HeaderXScopeOrgId,
  353. )
  354. }
  355. // LogQueryRequest logs the query that was send to prom/thanos with the time in queue and total time after being sent
  356. func LogQueryRequest(l *golog.Logger, req *http.Request, queueTime time.Duration, sendTime time.Duration) {
  357. if l == nil {
  358. return
  359. }
  360. qp := httputil.NewQueryParams(req.URL.Query())
  361. query := qp.Get("query", "<Unknown>")
  362. l.Printf("[Queue: %fs, Outbound: %fs][Query: %s]\n", queueTime.Seconds(), sendTime.Seconds(), query)
  363. }