forked from prometheus-community/stackdriver_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
Add bounded concurrency for timeSeries.list fan-out #5
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
nir-sagi
wants to merge
5
commits into
master
Choose a base branch
from
nirsagi/be-2312-integrations-agent-gcp-metrics-scrape-fires-unbounded
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.
+296
−5
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
42a95b9
Add bounded concurrency for timeSeries.list fan-out
nir-sagi 193d01b
Make timeSeries.list concurrency cap scrape-wide
nir-sagi 227482a
Add rate limiter for timeSeries.list calls
nir-sagi 04f9f48
Add allow/waited counters for timeSeries.list rate limiter
nir-sagi f95c4fd
Remove .omc/ from .gitignore
nir-sagi 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,214 @@ | ||
| // Copyright 2020 The Prometheus Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package collectors | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "strings" | ||
| "sync" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
| "github.com/stretchr/testify/require" | ||
| "google.golang.org/api/monitoring/v3" | ||
| "google.golang.org/api/option" | ||
| ) | ||
|
|
||
| type noopCounterStore struct{} | ||
|
|
||
| func (noopCounterStore) Increment(*monitoring.MetricDescriptor, *ConstMetric) {} | ||
| func (noopCounterStore) ListMetrics(string) []*ConstMetric { return nil } | ||
|
|
||
| type noopHistogramStore struct{} | ||
|
|
||
| func (noopHistogramStore) Increment(*monitoring.MetricDescriptor, *HistogramMetric) {} | ||
| func (noopHistogramStore) ListMetrics(string) []*HistogramMetric { return nil } | ||
|
|
||
| // TestReportMonitoringMetrics_TimeSeriesListConcurrency verifies that the inner | ||
| // projects.timeSeries.list fan-out is bounded by TimeSeriesListConcurrency. | ||
| func TestReportMonitoringMetrics_TimeSeriesListConcurrency(t *testing.T) { | ||
| // Two prefixes fan out concurrently. With a scrape-wide limiter, total in-flight | ||
| // timeSeries.list calls must stay <= limit; a per-prefix limiter would allow up to | ||
| // limit*len(prefixes), so this guards against the semaphore leaking per prefix. | ||
| prefixes := []string{"compute.googleapis.com", "storage.googleapis.com"} | ||
| const descriptorsPerPrefix = 8 | ||
| const limit = 2 | ||
|
|
||
| var inFlight, maxInFlight, total int64 | ||
|
|
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch { | ||
| case strings.HasSuffix(r.URL.Path, "/metricDescriptors"): | ||
| // Namespace descriptor types by the requested prefix so each prefix batch is | ||
| // distinct (dedup happens per type) and produces its own timeSeries.list calls. | ||
| filter := r.URL.Query().Get("filter") | ||
| prefix := filter | ||
| if i := strings.Index(filter, `starts_with("`); i >= 0 { | ||
| rest := filter[i+len(`starts_with("`):] | ||
| if j := strings.Index(rest, `"`); j >= 0 { | ||
| prefix = rest[:j] | ||
| } | ||
| } | ||
| var sb strings.Builder | ||
| sb.WriteString(`{"metricDescriptors":[`) | ||
| for i := 0; i < descriptorsPerPrefix; i++ { | ||
| if i > 0 { | ||
| sb.WriteString(",") | ||
| } | ||
| fmt.Fprintf(&sb, `{"type":"%s/m%d","metricKind":"GAUGE","valueType":"DOUBLE"}`, prefix, i) | ||
| } | ||
| sb.WriteString(`]}`) | ||
| w.Write([]byte(sb.String())) | ||
| case strings.HasSuffix(r.URL.Path, "/timeSeries"): | ||
| atomic.AddInt64(&total, 1) | ||
| cur := atomic.AddInt64(&inFlight, 1) | ||
| for { | ||
| old := atomic.LoadInt64(&maxInFlight) | ||
| if cur <= old || atomic.CompareAndSwapInt64(&maxInFlight, old, cur) { | ||
| break | ||
| } | ||
| } | ||
| time.Sleep(20 * time.Millisecond) | ||
| atomic.AddInt64(&inFlight, -1) | ||
| w.Write([]byte(`{}`)) | ||
| default: | ||
| w.Write([]byte(`{}`)) | ||
| } | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| svc, err := monitoring.NewService(context.Background(), | ||
| option.WithEndpoint(server.URL), | ||
| option.WithoutAuthentication(), | ||
| option.WithHTTPClient(server.Client())) | ||
| require.NoError(t, err) | ||
|
|
||
| logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError})) | ||
| collector, err := NewMonitoringCollector("test-project", svc, MonitoringCollectorOptions{ | ||
| MetricTypePrefixes: prefixes, | ||
| RequestInterval: time.Minute, | ||
| TimeSeriesListConcurrency: limit, | ||
| }, logger, noopCounterStore{}, noopHistogramStore{}) | ||
| require.NoError(t, err) | ||
|
|
||
| ch := make(chan prometheus.Metric, 1024) | ||
| var drain sync.WaitGroup | ||
| drain.Add(1) | ||
| go func() { | ||
| defer drain.Done() | ||
| for range ch { | ||
| } | ||
| }() | ||
|
|
||
| require.NoError(t, collector.reportMonitoringMetrics(ch, time.Now())) | ||
| close(ch) | ||
| drain.Wait() | ||
|
|
||
| require.Equal(t, int64(descriptorsPerPrefix*len(prefixes)), atomic.LoadInt64(&total), "every descriptor should be queried") | ||
| require.LessOrEqual(t, atomic.LoadInt64(&maxInFlight), int64(limit), "concurrent timeSeries.list calls must not exceed the limit") | ||
| } | ||
|
|
||
| // TestReportMonitoringMetrics_TimeSeriesListRate verifies that the token-bucket rate limiter | ||
| // spreads projects.timeSeries.list calls over time scrape-wide. With burst=Count the first Count | ||
| // calls fire immediately and the rest are paced at Count/Duration, so the scrape cannot complete | ||
| // faster than that pacing allows — proving rate (not just concurrency) is bounded. | ||
| func TestReportMonitoringMetrics_TimeSeriesListRate(t *testing.T) { | ||
| prefixes := []string{"compute.googleapis.com", "storage.googleapis.com"} | ||
| const descriptorsPerPrefix = 8 | ||
| const rateCount = 2 | ||
| const rateDuration = 100 * time.Millisecond // 20 calls/sec, burst 2 | ||
|
|
||
| var total int64 | ||
|
|
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch { | ||
| case strings.HasSuffix(r.URL.Path, "/metricDescriptors"): | ||
| filter := r.URL.Query().Get("filter") | ||
| prefix := filter | ||
| if i := strings.Index(filter, `starts_with("`); i >= 0 { | ||
| rest := filter[i+len(`starts_with("`):] | ||
| if j := strings.Index(rest, `"`); j >= 0 { | ||
| prefix = rest[:j] | ||
| } | ||
| } | ||
| var sb strings.Builder | ||
| sb.WriteString(`{"metricDescriptors":[`) | ||
| for i := 0; i < descriptorsPerPrefix; i++ { | ||
| if i > 0 { | ||
| sb.WriteString(",") | ||
| } | ||
| fmt.Fprintf(&sb, `{"type":"%s/m%d","metricKind":"GAUGE","valueType":"DOUBLE"}`, prefix, i) | ||
| } | ||
| sb.WriteString(`]}`) | ||
| w.Write([]byte(sb.String())) | ||
| case strings.HasSuffix(r.URL.Path, "/timeSeries"): | ||
| atomic.AddInt64(&total, 1) | ||
| w.Write([]byte(`{}`)) | ||
| default: | ||
| w.Write([]byte(`{}`)) | ||
| } | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| svc, err := monitoring.NewService(context.Background(), | ||
| option.WithEndpoint(server.URL), | ||
| option.WithoutAuthentication(), | ||
| option.WithHTTPClient(server.Client())) | ||
| require.NoError(t, err) | ||
|
|
||
| logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError})) | ||
| collector, err := NewMonitoringCollector("test-project", svc, MonitoringCollectorOptions{ | ||
| MetricTypePrefixes: prefixes, | ||
| RequestInterval: time.Minute, | ||
| TimeSeriesListRateCount: rateCount, | ||
| TimeSeriesListRateDuration: rateDuration, | ||
| }, logger, noopCounterStore{}, noopHistogramStore{}) | ||
| require.NoError(t, err) | ||
|
|
||
| ch := make(chan prometheus.Metric, 1024) | ||
| var drain sync.WaitGroup | ||
| drain.Add(1) | ||
| go func() { | ||
| defer drain.Done() | ||
| for range ch { | ||
| } | ||
| }() | ||
|
|
||
| start := time.Now() | ||
| require.NoError(t, collector.reportMonitoringMetrics(ch, time.Now())) | ||
| elapsed := time.Since(start) | ||
| close(ch) | ||
| drain.Wait() | ||
|
|
||
| numCalls := descriptorsPerPrefix * len(prefixes) | ||
| // After the initial burst of rateCount, the remaining calls are paced at rateCount/rateDuration. | ||
| ratePerSecond := float64(rateCount) / rateDuration.Seconds() | ||
| minExpected := time.Duration(float64(numCalls-rateCount) / ratePerSecond * float64(time.Second)) | ||
|
|
||
| require.Equal(t, int64(numCalls), atomic.LoadInt64(&total), "every descriptor should be queried") | ||
| // Allow slack below the theoretical minimum for scheduling jitter. | ||
| require.GreaterOrEqual(t, elapsed, minExpected*8/10, "rate limiter must spread calls over time") | ||
|
|
||
| // The initial burst (rateCount) is admitted immediately; everything after is throttled. | ||
| require.Equal(t, float64(rateCount), testutil.ToFloat64(collector.timeSeriesListRateAllowedMetric), "burst calls should be counted as allowed") | ||
| require.Equal(t, float64(numCalls-rateCount), testutil.ToFloat64(collector.timeSeriesListRateWaitedMetric), "throttled calls should be counted as waited") | ||
| } |
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.