prom.go 13 KB

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