- Notifications
You must be signed in to change notification settings - Fork1k
chore: instrument github oauth2 limits#11532
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
5 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
2 changes: 1 addition & 1 deletioncli/server.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletionscoderd/coderdtest/oidctest/idp.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
7 changes: 6 additions & 1 deletioncoderd/externalauth/externalauth.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletionscoderd/promoauth/github.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package promoauth | ||
import ( | ||
"fmt" | ||
"net/http" | ||
"strconv" | ||
"time" | ||
) | ||
type rateLimits struct { | ||
Limit int | ||
Remaining int | ||
Used int | ||
Reset time.Time | ||
Resource string | ||
} | ||
// githubRateLimits checks the returned response headers and | ||
func githubRateLimits(resp *http.Response, err error) (rateLimits, bool) { | ||
if err != nil || resp == nil { | ||
return rateLimits{}, false | ||
} | ||
p := headerParser{header: resp.Header} | ||
// See | ||
// https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28#checking-the-status-of-your-rate-limit | ||
limits := rateLimits{ | ||
Limit: p.int("x-ratelimit-limit"), | ||
Remaining: p.int("x-ratelimit-remaining"), | ||
Used: p.int("x-ratelimit-used"), | ||
Resource: p.string("x-ratelimit-resource"), | ||
} | ||
if limits.Limit == 0 && | ||
limits.Remaining == 0 && | ||
limits.Used == 0 { | ||
// For some requests, github has no rate limit. In which case, | ||
// it returns all 0s. We can just omit these. | ||
return limits, false | ||
} | ||
// Reset is when the rate limit "used" will be reset to 0. | ||
// If it's unix 0, then we do not know when it will reset. | ||
// Change it to a zero time as that is easier to handle in golang. | ||
unix := p.int("x-ratelimit-reset") | ||
resetAt := time.Unix(int64(unix), 0) | ||
if unix == 0 { | ||
resetAt = time.Time{} | ||
} | ||
limits.Reset = resetAt | ||
// Unauthorized requests have their own rate limit, so we should | ||
// track them separately. | ||
if resp.StatusCode == http.StatusUnauthorized { | ||
limits.Resource += "-unauthorized" | ||
} | ||
// A 401 or 429 means too many requests. This might mess up the | ||
// "resource" string because we could hit the unauthorized limit, | ||
// and we do not want that to override the authorized one. | ||
// However, in testing, it seems a 401 is always a 401, even if | ||
// the limit is hit. | ||
if len(p.errors) > 0 { | ||
// If we are missing any headers, then do not try and guess | ||
// what the rate limits are. | ||
return limits, false | ||
} | ||
return limits, true | ||
} | ||
type headerParser struct { | ||
errors map[string]error | ||
header http.Header | ||
} | ||
func (p *headerParser) string(key string) string { | ||
if p.errors == nil { | ||
p.errors = make(map[string]error) | ||
} | ||
v := p.header.Get(key) | ||
if v == "" { | ||
p.errors[key] = fmt.Errorf("missing header %q", key) | ||
} | ||
return v | ||
} | ||
func (p *headerParser) int(key string) int { | ||
v := p.string(key) | ||
if v == "" { | ||
return -1 | ||
} | ||
i, err := strconv.Atoi(v) | ||
if err != nil { | ||
p.errors[key] = err | ||
} | ||
return i | ||
} |
107 changes: 107 additions & 0 deletionscoderd/promoauth/oauth2.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -4,6 +4,7 @@ import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"time" | ||
"github.com/prometheus/client_golang/prometheus" | ||
"github.com/prometheus/client_golang/prometheus/promauto" | ||
@@ -46,11 +47,25 @@ var _ OAuth2Config = (*Config)(nil) | ||
// Primarily to avoid any prometheus errors registering duplicate metrics. | ||
type Factory struct { | ||
metrics *metrics | ||
// optional replace now func | ||
Now func() time.Time | ||
} | ||
// metrics is the reusable metrics for all oauth2 providers. | ||
type metrics struct { | ||
externalRequestCount *prometheus.CounterVec | ||
// if the oauth supports it, rate limit metrics. | ||
// rateLimit is the defined limit per interval | ||
rateLimit *prometheus.GaugeVec | ||
rateLimitRemaining *prometheus.GaugeVec | ||
rateLimitUsed *prometheus.GaugeVec | ||
// rateLimitReset is unix time of the next interval (when the rate limit resets). | ||
rateLimitReset *prometheus.GaugeVec | ||
// rateLimitResetIn is the time in seconds until the rate limit resets. | ||
// This is included because it is sometimes more helpful to know the limit | ||
// will reset in 600seconds, rather than at 1704000000 unix time. | ||
rateLimitResetIn *prometheus.GaugeVec | ||
} | ||
func NewFactory(registry prometheus.Registerer) *Factory { | ||
@@ -68,6 +83,53 @@ func NewFactory(registry prometheus.Registerer) *Factory { | ||
"source", | ||
"status_code", | ||
}), | ||
rateLimit: factory.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "oauth2", | ||
Name: "external_requests_rate_limit_total", | ||
Help: "The total number of allowed requests per interval.", | ||
}, []string{ | ||
"name", | ||
// Resource allows different rate limits for the same oauth2 provider. | ||
// Some IDPs have different buckets for different rate limits. | ||
"resource", | ||
}), | ||
rateLimitRemaining: factory.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "oauth2", | ||
Name: "external_requests_rate_limit_remaining", | ||
Help: "The remaining number of allowed requests in this interval.", | ||
}, []string{ | ||
"name", | ||
"resource", | ||
}), | ||
rateLimitUsed: factory.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "oauth2", | ||
Name: "external_requests_rate_limit_used", | ||
Help: "The number of requests made in this interval.", | ||
}, []string{ | ||
"name", | ||
"resource", | ||
}), | ||
rateLimitReset: factory.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "oauth2", | ||
Name: "external_requests_rate_limit_next_reset_unix", | ||
Help: "Unix timestamp for when the next interval starts", | ||
}, []string{ | ||
"name", | ||
"resource", | ||
}), | ||
rateLimitResetIn: factory.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "oauth2", | ||
Name: "external_requests_rate_limit_reset_in_seconds", | ||
Help: "Seconds until the next interval", | ||
}, []string{ | ||
"name", | ||
"resource", | ||
}), | ||
}, | ||
} | ||
} | ||
@@ -80,13 +142,53 @@ func (f *Factory) New(name string, under OAuth2Config) *Config { | ||
} | ||
} | ||
// NewGithub returns a new instrumented oauth2 config for github. It tracks | ||
// rate limits as well as just the external request counts. | ||
// | ||
//nolint:bodyclose | ||
func (f *Factory) NewGithub(name string, under OAuth2Config) *Config { | ||
cfg := f.New(name, under) | ||
cfg.interceptors = append(cfg.interceptors, func(resp *http.Response, err error) { | ||
limits, ok := githubRateLimits(resp, err) | ||
if !ok { | ||
return | ||
} | ||
Emyrk marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
labels := prometheus.Labels{ | ||
"name": cfg.name, | ||
"resource": limits.Resource, | ||
} | ||
// Default to -1 for "do not know" | ||
resetIn := float64(-1) | ||
if !limits.Reset.IsZero() { | ||
now := time.Now() | ||
if f.Now != nil { | ||
now = f.Now() | ||
} | ||
resetIn = limits.Reset.Sub(now).Seconds() | ||
if resetIn < 0 { | ||
// If it just reset, just make it 0. | ||
resetIn = 0 | ||
} | ||
} | ||
f.metrics.rateLimit.With(labels).Set(float64(limits.Limit)) | ||
f.metrics.rateLimitRemaining.With(labels).Set(float64(limits.Remaining)) | ||
f.metrics.rateLimitUsed.With(labels).Set(float64(limits.Used)) | ||
f.metrics.rateLimitReset.With(labels).Set(float64(limits.Reset.Unix())) | ||
f.metrics.rateLimitResetIn.With(labels).Set(resetIn) | ||
}) | ||
return cfg | ||
} | ||
type Config struct { | ||
// Name is a human friendly name to identify the oauth2 provider. This should be | ||
// deterministic from restart to restart, as it is going to be used as a label in | ||
// prometheus metrics. | ||
name string | ||
underlying OAuth2Config | ||
metrics *metrics | ||
// interceptors are called after every request made by the oauth2 client. | ||
interceptors []func(resp *http.Response, err error) | ||
} | ||
func (c *Config) Do(ctx context.Context, source Oauth2Source, req *http.Request) (*http.Response, error) { | ||
@@ -169,5 +271,10 @@ func (i *instrumentedTripper) RoundTrip(r *http.Request) (*http.Response, error) | ||
"source": string(i.source), | ||
"status_code": fmt.Sprintf("%d", statusCode), | ||
}).Inc() | ||
// Handle any extra interceptors. | ||
for _, interceptor := range i.c.interceptors { | ||
interceptor(resp, err) | ||
} | ||
return resp, err | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.