-
Notifications
You must be signed in to change notification settings - Fork 849
Querier active api tracker #7216
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eeldaly
wants to merge
16
commits into
cortexproject:master
Choose a base branch
from
eeldaly:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
c399131
Add active api tracker
eeldaly 0bd714e
Update changelog
eeldaly 3b566eb
Made request tracker more generic; added query apis to tracker
eeldaly 83e2259
add prometheus copyright header for copied part
eeldaly d06e5eb
Merge branch 'master' into master
friedrichg 575b518
Add request id if not in context
eeldaly 2b585b7
fix test assert expected msg
eeldaly 5da5eeb
Add more logging fields
eeldaly 814d788
Rename log entry keys, remove request id generation
eeldaly eeeaf01
Wrap request id wrapper before oomkill logger
eeldaly 72a8720
Add test for query truncation. Fix edge case with query truncating es…
eeldaly bfbfe8d
lint
eeldaly f910102
remove debug line
eeldaly 4b9776e
Add extractor tests
eeldaly 8c32cbd
Removed default extractor
eeldaly a5cde19
rewrote trim function
eeldaly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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,115 @@ | ||
| package request_tracker | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/cortexproject/cortex/pkg/util/requestmeta" | ||
| "github.com/cortexproject/cortex/pkg/util/users" | ||
| ) | ||
|
|
||
| type Extractor interface { | ||
| Extract(r *http.Request) []byte | ||
| } | ||
|
|
||
| type ApiExtractor struct{} | ||
|
|
||
| type InstantQueryExtractor struct{} | ||
|
|
||
| type RangedQueryExtractor struct{} | ||
|
|
||
| func generateCommonMap(r *http.Request) map[string]interface{} { | ||
| ctx := r.Context() | ||
| entryMap := make(map[string]interface{}) | ||
| entryMap["timestampSec"] = time.Now().Unix() | ||
| entryMap["Path"] = r.URL.Path | ||
| entryMap["Method"] = r.Method | ||
| entryMap["TenantID"], _ = users.TenantID(ctx) | ||
| entryMap["RequestID"] = requestmeta.RequestIdFromContext(ctx) | ||
| entryMap["UserAgent"] = r.Header.Get("User-Agent") | ||
| entryMap["DashboardUID"] = r.Header.Get("X-Dashboard-UID") | ||
| entryMap["PanelId"] = r.Header.Get("X-Panel-Id") | ||
|
|
||
| return entryMap | ||
| } | ||
|
|
||
| func (e *ApiExtractor) Extract(r *http.Request) []byte { | ||
| entryMap := generateCommonMap(r) | ||
| entryMap["limit"] = r.URL.Query().Get("limit") | ||
| entryMap["start"] = r.URL.Query().Get("start") | ||
| entryMap["end"] = r.URL.Query().Get("end") | ||
|
|
||
| matches := r.URL.Query()["match[]"] | ||
| entryMap["numberOfMatches"] = len(matches) | ||
| matchesStr := strings.Join(matches, ",") | ||
|
|
||
| return generateJSONEntryWithTruncatedField(entryMap, "matches", matchesStr) | ||
| } | ||
|
|
||
| func (e *InstantQueryExtractor) Extract(r *http.Request) []byte { | ||
| entryMap := generateCommonMap(r) | ||
| entryMap["time"] = r.URL.Query().Get("time") | ||
| return generateJSONEntryWithTruncatedField(entryMap, "query", r.URL.Query().Get("query")) | ||
| } | ||
|
|
||
| func (e *RangedQueryExtractor) Extract(r *http.Request) []byte { | ||
| entryMap := generateCommonMap(r) | ||
| entryMap["start"] = r.URL.Query().Get("start") | ||
| entryMap["end"] = r.URL.Query().Get("end") | ||
| entryMap["step"] = r.URL.Query().Get("step") | ||
| return generateJSONEntryWithTruncatedField(entryMap, "query", r.URL.Query().Get("query")) | ||
| } | ||
|
|
||
| func generateJSONEntry(entryMap map[string]interface{}) []byte { | ||
| jsonEntry, err := json.Marshal(entryMap) | ||
yeya24 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if err != nil { | ||
| return []byte{} | ||
| } | ||
|
|
||
| return jsonEntry | ||
| } | ||
|
|
||
| func generateJSONEntryWithTruncatedField(entryMap map[string]interface{}, fieldName, fieldValue string) []byte { | ||
| entryMap[fieldName] = "" | ||
| minEntryJSON := generateJSONEntry(entryMap) | ||
| entryMap[fieldName] = trimForJsonMarshal(fieldValue, maxEntrySize-(len(minEntryJSON)+1)) | ||
| return generateJSONEntry(entryMap) | ||
| } | ||
|
|
||
| func trimStringByBytes(str string, size int) string { | ||
| bytesStr := []byte(str) | ||
| trimIndex := len(bytesStr) | ||
| if size < len(bytesStr) { | ||
| for !utf8.RuneStart(bytesStr[size]) { | ||
| size-- | ||
| } | ||
| trimIndex = size | ||
| } | ||
|
|
||
| return string(bytesStr[:trimIndex]) | ||
| } | ||
|
|
||
| func trimForJsonMarshal(field string, size int) string { | ||
| return trimForJsonMarshalRecursive(field, size, 0, size) | ||
| } | ||
|
|
||
| func trimForJsonMarshalRecursive(field string, size int, repeatCount int, repeatSize int) string { | ||
| //Should only repeat once since were over slightly over cutting based on the encoded size if we miss once | ||
| if repeatCount > 1 { | ||
| return "" | ||
| } | ||
|
|
||
| fieldTrimmed := trimStringByBytes(field, repeatSize) | ||
| fieldEncoded, err := json.Marshal(fieldTrimmed) | ||
| if err != nil { | ||
| return "" | ||
| } | ||
| if len(fieldEncoded) > size { | ||
| repeatSize = repeatSize - (len(fieldEncoded) - repeatSize) | ||
| return trimForJsonMarshalRecursive(fieldTrimmed, size, repeatCount+1, repeatSize) | ||
| } | ||
| return fieldTrimmed | ||
| } | ||
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,90 @@ | ||
| package request_tracker | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestGetSeriesExtractor(t *testing.T) { | ||
| extractor := &ApiExtractor{} | ||
| req := httptest.NewRequest("GET", "/api/v1/series", nil) | ||
| q := req.URL.Query() | ||
| q.Add("limit", "100") | ||
| q.Add("match[]", "up") | ||
| q.Add("match[]", "down") | ||
| req.URL.RawQuery = q.Encode() | ||
|
|
||
| result := extractor.Extract(req) | ||
| require.NotEmpty(t, result) | ||
|
|
||
| var data map[string]interface{} | ||
| require.NoError(t, json.Unmarshal(result, &data)) | ||
|
|
||
| assert.Equal(t, "100", data["limit"]) | ||
| assert.Equal(t, float64(2), data["numberOfMatches"]) | ||
| assert.Contains(t, data["matches"], "up") | ||
| } | ||
|
|
||
| func TestInstantQueryExtractor(t *testing.T) { | ||
| extractor := &InstantQueryExtractor{} | ||
| req := httptest.NewRequest("GET", "/api/v1/query", nil) | ||
| q := req.URL.Query() | ||
| q.Add("query", "up{job=\"prometheus\"}") | ||
| q.Add("time", "1234567890") | ||
| req.URL.RawQuery = q.Encode() | ||
|
|
||
| result := extractor.Extract(req) | ||
| require.NotEmpty(t, result) | ||
|
|
||
| var data map[string]interface{} | ||
| require.NoError(t, json.Unmarshal(result, &data)) | ||
|
|
||
| assert.Equal(t, "1234567890", data["time"]) | ||
| assert.Equal(t, "up{job=\"prometheus\"}", data["query"]) | ||
| } | ||
|
|
||
| func TestRangedQueryExtractor(t *testing.T) { | ||
| extractor := &RangedQueryExtractor{} | ||
| req := httptest.NewRequest("GET", "/api/v1/query_range", nil) | ||
| q := req.URL.Query() | ||
| q.Add("query", "rate(http_requests_total[5m])") | ||
| q.Add("start", "1000") | ||
| q.Add("end", "2000") | ||
| q.Add("step", "15") | ||
| req.URL.RawQuery = q.Encode() | ||
|
|
||
| result := extractor.Extract(req) | ||
| require.NotEmpty(t, result) | ||
|
|
||
| var data map[string]interface{} | ||
| require.NoError(t, json.Unmarshal(result, &data)) | ||
|
|
||
| assert.Equal(t, "1000", data["start"]) | ||
| assert.Equal(t, "2000", data["end"]) | ||
| assert.Equal(t, "15", data["step"]) | ||
| assert.Equal(t, "rate(http_requests_total[5m])", data["query"]) | ||
| } | ||
|
|
||
| func TestLongQueryTruncate(t *testing.T) { | ||
| longQuery := strings.Repeat("metric_name{label=\"value\"} or ", maxEntrySize*2) + "final_metric" | ||
| req := httptest.NewRequest("GET", "/api/v1/query", nil) | ||
| q := req.URL.Query() | ||
| q.Add("query", longQuery) | ||
| q.Add("time", "1234567890") | ||
| req.URL.RawQuery = q.Encode() | ||
|
|
||
| extractor := &InstantQueryExtractor{} | ||
| extractedData := extractor.Extract(req) | ||
|
|
||
| require.NotEmpty(t, extractedData) | ||
| assert.True(t, len(extractedData) > 0) | ||
| assert.LessOrEqual(t, len(extractedData), maxEntrySize) | ||
| assert.Contains(t, string(extractedData), "metric_name") | ||
| assert.Contains(t, string(extractedData), "1234567890") | ||
| assert.NotContains(t, string(extractedData), "final_metric") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.