prom.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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/core/pkg/collections"
  14. "github.com/opencost/opencost/core/pkg/log"
  15. "github.com/opencost/opencost/core/pkg/util/fileutil"
  16. "github.com/opencost/opencost/core/pkg/util/httputil"
  17. "github.com/opencost/opencost/core/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 err != nil {
  127. log.Infof("Failed to check for existence of queryLogFile: %s: %s", queryLogFile, err)
  128. }
  129. if exists {
  130. err = os.Remove(queryLogFile)
  131. if err != nil {
  132. log.Infof("Failed to remove queryLogFile: %s: %s", queryLogFile, err)
  133. }
  134. }
  135. f, err := os.OpenFile(queryLogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  136. if err != nil {
  137. log.Infof("Failed to open queryLogFile: %s for query logging: %s", queryLogFile, err)
  138. } else {
  139. logger = golog.New(f, "query-log", golog.LstdFlags)
  140. }
  141. }
  142. // default authentication
  143. if auth == nil {
  144. auth = &ClientAuth{
  145. Username: "",
  146. Password: "",
  147. BearerToken: "",
  148. }
  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. // workRequest is used to queue requests
  185. type workRequest struct {
  186. ctx context.Context
  187. req *http.Request
  188. start time.Time
  189. respChan chan *workResponse
  190. // used as a sentinel value to close the worker goroutine
  191. closer bool
  192. // request metadata for diagnostics
  193. contextName string
  194. query string
  195. }
  196. // workResponse is the response payload returned to the Do method
  197. type workResponse struct {
  198. res *http.Response
  199. body []byte
  200. err error
  201. }
  202. // worker is used as a consumer goroutine to pull workRequest from the blocking queue and execute them
  203. func (rlpc *RateLimitedPrometheusClient) worker() {
  204. retryOpts := rlpc.rateLimitRetry
  205. retryRateLimit := retryOpts != nil
  206. for {
  207. // blocks until there is an item available
  208. we := rlpc.queue.Dequeue()
  209. // if we need to shut down all workers, we'll need to submit sentinel values
  210. // that will force the worker to return
  211. if we.closer {
  212. return
  213. }
  214. ctx := we.ctx
  215. req := we.req
  216. // decorate the raw query parameters
  217. if rlpc.decorator != nil {
  218. req.URL.RawQuery = rlpc.decorator(req.URL.Path, req.URL.Query()).Encode()
  219. }
  220. // measure time in queue
  221. timeInQueue := time.Since(we.start)
  222. // Increment outbound counter
  223. rlpc.outbound.Add(1)
  224. // Execute Request
  225. roundTripStart := time.Now()
  226. res, body, err := rlpc.client.Do(ctx, req)
  227. // If retries on rate limited response is enabled:
  228. // * Check for a 429 StatusCode OR 400 StatusCode and message containing "ThrottlingException"
  229. // * Attempt to parse a Retry-After from response headers (common on 429)
  230. // * If we couldn't determine how long to wait for a retry, use 1 second by default
  231. if res != nil && retryRateLimit {
  232. var status []*RateLimitResponseStatus
  233. var retries int = retryOpts.MaxRetries
  234. var defaultWait time.Duration = retryOpts.DefaultRetryWait
  235. for httputil.IsRateLimited(res, body) && retries > 0 {
  236. // calculate amount of time to wait before retry, in the event the default wait is used,
  237. // an exponential backoff is applied based on the number of times we've retried.
  238. retryAfter := httputil.RateLimitedRetryFor(res, defaultWait, retryOpts.MaxRetries-retries)
  239. retries--
  240. status = append(status, &RateLimitResponseStatus{RetriesRemaining: retries, WaitTime: retryAfter})
  241. log.DedupedInfof(50, "Rate Limited Prometheus Request. Waiting for: %d ms. Retries Remaining: %d", retryAfter.Milliseconds(), retries)
  242. // To prevent total starvation of request threads, hard limit wait time to 10s. We also want quota limits/throttles
  243. // to eventually pass through as an error. For example, if some quota is reached with 10 days left, we clearly
  244. // don't want to block for 10 days.
  245. if retryAfter > MaxRetryAfterDuration {
  246. retryAfter = MaxRetryAfterDuration
  247. }
  248. // execute wait and retry
  249. time.Sleep(retryAfter)
  250. res, body, err = rlpc.client.Do(ctx, req)
  251. }
  252. // if we've broken out of our retry loop and the resp is still rate limited,
  253. // then let's generate a meaningful error to pass back
  254. if retries == 0 && httputil.IsRateLimited(res, body) {
  255. err = &RateLimitedResponseError{RateLimitStatus: status}
  256. }
  257. }
  258. // Decrement outbound counter
  259. rlpc.outbound.Add(-1)
  260. LogQueryRequest(rlpc.fileLogger, req, timeInQueue, time.Since(roundTripStart))
  261. // Pass back response data over channel to caller
  262. we.respChan <- &workResponse{
  263. res: res,
  264. body: body,
  265. err: err,
  266. }
  267. }
  268. }
  269. // Rate limit and passthrough to prometheus client API
  270. func (rlpc *RateLimitedPrometheusClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
  271. if rlpc.headerXScopeOrgId != "" {
  272. req.Header.Set(HeaderXScopeOrgId, rlpc.headerXScopeOrgId)
  273. }
  274. rlpc.auth.Apply(req)
  275. respChan := make(chan *workResponse)
  276. defer close(respChan)
  277. // request names are used as a debug utility to identify requests in queue
  278. contextName := "<none>"
  279. if n, ok := httputil.GetName(req); ok {
  280. contextName = n
  281. }
  282. query, _ := httputil.GetQuery(req)
  283. rlpc.queue.Enqueue(&workRequest{
  284. ctx: ctx,
  285. req: req,
  286. start: time.Now(),
  287. respChan: respChan,
  288. closer: false,
  289. contextName: contextName,
  290. query: query,
  291. })
  292. workRes := <-respChan
  293. return workRes.res, workRes.body, workRes.err
  294. }
  295. //--------------------------------------------------------------------------
  296. // Client Helpers
  297. //--------------------------------------------------------------------------
  298. // PrometheusClientConfig contains all configurable options for creating a new prometheus client
  299. type PrometheusClientConfig struct {
  300. Timeout time.Duration
  301. KeepAlive time.Duration
  302. TLSHandshakeTimeout time.Duration
  303. TLSInsecureSkipVerify bool
  304. RateLimitRetryOpts *RateLimitRetryOpts
  305. Auth *ClientAuth
  306. QueryConcurrency int
  307. QueryLogFile string
  308. HeaderXScopeOrgId string
  309. }
  310. // NewPrometheusClient creates a new rate limited client which limits by outbound concurrent requests.
  311. func NewPrometheusClient(address string, config *PrometheusClientConfig) (prometheus.Client, error) {
  312. // may be necessary for long prometheus queries
  313. rt := httputil.NewUserAgentTransport(UserAgent, &http.Transport{
  314. Proxy: http.ProxyFromEnvironment,
  315. DialContext: (&net.Dialer{
  316. Timeout: config.Timeout,
  317. KeepAlive: config.KeepAlive,
  318. }).DialContext,
  319. TLSHandshakeTimeout: config.TLSHandshakeTimeout,
  320. TLSClientConfig: &tls.Config{
  321. InsecureSkipVerify: config.TLSInsecureSkipVerify,
  322. },
  323. })
  324. pc := prometheus.Config{
  325. Address: address,
  326. RoundTripper: rt,
  327. }
  328. client, err := prometheus.NewClient(pc)
  329. if err != nil {
  330. return nil, err
  331. }
  332. return NewRateLimitedClient(
  333. PrometheusClientID,
  334. client,
  335. config.QueryConcurrency,
  336. config.Auth,
  337. nil,
  338. config.RateLimitRetryOpts,
  339. config.QueryLogFile,
  340. config.HeaderXScopeOrgId,
  341. )
  342. }
  343. // LogQueryRequest logs the query that was send to prom/thanos with the time in queue and total time after being sent
  344. func LogQueryRequest(l *golog.Logger, req *http.Request, queueTime time.Duration, sendTime time.Duration) {
  345. if l == nil {
  346. return
  347. }
  348. qp := httputil.NewQueryParams(req.URL.Query())
  349. query := qp.Get("query", "<Unknown>")
  350. l.Printf("[Queue: %fs, Outbound: %fs][Query: %s]\n", queueTime.Seconds(), sendTime.Seconds(), query)
  351. }