prom.go 12 KB

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