Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions doc/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,74 @@ A `GET` request for `http://my.freno.service:9777/check/archive/mysql/main1` may
```

Extra info such as the threshold or actual replication lag value is irrelevant for automated requests, which should just know whether they're allowed to proceed or not. For humans this is beneficial input.

## Requested measurements and required dependencies

For a configured MySQL store, `MetricName`, `Value`, and `Threshold` always
describe the requested store (or its configured fallback), even when a required
dependency blocks admission. Existing replication-delay clients can continue to
read lag seconds from `Value`; a primary's running-thread count never replaces
the requested store's lag.

`Dependencies` contains the required metrics on both accepted and rejected
checks, including when the requested metric fails. Each includes its own name,
value, threshold, status, and any evaluated nested dependencies. Freno retains
the first failure as the admission decision; later checks only complete the
diagnostic response and do not set additional low-priority throttling state.
These checks use collected measurements already held by Freno,
not additional database queries per request. A directly requested primary store
still returns primary pressure in its own `Value`; it is not a replication-lag
endpoint.

For example, healthy replica lag with an overloaded required primary returns
HTTP 429 and a body containing:

```json
{
"StatusCode": 429,
"MetricName": "mysql/repositories",
"Value": 0.05,
"Threshold": 1,
"Message": "Threshold exceeded",
"BlockingMetricName": "mysql/repositories-primary",
"Dependencies": [
{
"StatusCode": 429,
"MetricName": "mysql/repositories-primary",
"Value": 80,
"Threshold": 75,
"Message": "Threshold exceeded"
}
]
}
```

Admission still follows the first failing check: the requested metric first,
then required dependencies in configured order. The top-level
`BlockingMetricName` identifies the first blocker; the existing `Message`
explains the rejection. Dependency entries contain the existing result fields
without repeating the blocking metric. Rejection counters and logs retain
the blocking metric's identity and value, rather than the top-level lag.
Recovery and shared-domain health can still cause HTTP 429 when the current
pressure is below the throttle threshold.

A probe failure is reported through the failing metric's `StatusCode` and
`Message`. For compatibility with existing clients, `Value` remains numeric
and retains the legacy error-path value; that value is not a valid measurement.
The overall status can also describe a dependency failure while the requested
lag is valid; `BlockingMetricName` identifies which metric blocked admission.
The original missing-host fail-open/fail-closed setting remains in effect.

An unchanged Ruby `replication_delay` client reads only `Value`; it does not
honor admission status or error messages. This change preserves
its numeric contract and removes pressure/lag unit confusion, but does not make
that client handle unavailable lag differently. Write admission must still use
the status-based check.

The opt-in Go test `TestRubyClientLagPressureCompatibility` runs the actual Ruby
client against an in-process Freno HTTP server. Set `FRENO_RUBY_CLIENT_PATH` to an
unchanged client checkout, provide Ruby with Faraday, and run:

```sh
go test ./pkg/throttle -run '^TestRubyClientLagPressureCompatibility$' -v
```
14 changes: 9 additions & 5 deletions pkg/throttle/api_dependencies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestHTTPMySQLPrimaryDependencies(t *testing.T) {
wantValue float64
wantThreshold float64
}{
{"required primary blocks", "RequiredClusters", http.StatusTooManyRequests, "mysql/primary", 60, 50},
{"required primary blocks", "RequiredClusters", http.StatusTooManyRequests, "mysql/replicas", 1, 5},
{"removed shadow field is ignored", "ShadowRequiredClusters", http.StatusOK, "mysql/replicas", 1, 5},
} {
t.Run(test.name, func(t *testing.T) {
Expand Down Expand Up @@ -127,13 +127,17 @@ func TestHTTPMySQLPrimaryRecoveryAfterProbeError(t *testing.T) {
if status != step.wantStatus || result.Message != step.wantMessage {
t.Fatalf("at %s: unexpected HTTP check: %+v", step.elapsed, result)
}
wantMetric := "mysql/primary"
if status == http.StatusOK {
wantMetric = "mysql/replicas"
}
wantMetric := "mysql/replicas"
if result.MetricName != wantMetric {
t.Fatalf("metric = %q, want %q", result.MetricName, wantMetric)
}
if result.Value != 1 || result.Threshold != 5 || len(result.Dependencies) != 1 {
t.Fatalf("lag fields or primary measurement lost: %+v", result)
}
value, _ := step.metric.Get()
if result.Dependencies[0].Value != value {
t.Fatalf("primary value = %g, want %g", result.Dependencies[0].Value, value)
}
t.Logf("at %s: HTTP %d, metric=%s, message=%q", step.elapsed, status, result.MetricName, result.Message)
})
}
Expand Down
46 changes: 31 additions & 15 deletions pkg/throttle/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type CheckFlags struct {
OverrideThreshold float64
LowPriority bool
OKIfNotExists bool
observationOnly bool
}

var StandardCheckFlags = &CheckFlags{}
Expand Down Expand Up @@ -69,7 +70,7 @@ func (check *ThrottlerCheck) checkAppMetricResult(appName string, storeType stri
}
checkResult = newMetricCheckResult(value, threshold, err, failOnNoHosts)
if err == nil && value > threshold {
if !flags.LowPriority && !flags.ReadCheck && appName != frenoAppName {
if !flags.LowPriority && !flags.ReadCheck && !flags.observationOnly && appName != frenoAppName {
// low priority requests will henceforth be denied
go check.throttler.nonLowPriorityAppRequestsThrottled.SetDefault(metricName, true)
}
Expand Down Expand Up @@ -103,29 +104,43 @@ func (check *ThrottlerCheck) checkMySQLCluster(
return check.throttler.getMySQLClusterMetrics(clusterName)
}
rootResult := check.checkAppMetricResult(appName, "mysql", clusterName, metricResultFunc, flags)
if rootResult.StatusCode != http.StatusOK {
clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName]
if clusterSettings == nil {
return rootResult
}

clusterSettings := config.Settings().Stores.MySQL.Clusters[clusterName]
var blocker *CheckResult
if rootResult.StatusCode != http.StatusOK {
blocker = rootResult
}
for _, requiredCluster := range clusterSettings.RequiredClusters {
requiredFlags := *flags
requiredFlags.ReadCheck = false
requiredFlags.OverrideThreshold = 0
requiredFlags.observationOnly = flags.observationOnly || blocker != nil
requiredResult := check.checkMySQLCluster(appName, requiredCluster, &requiredFlags, checkedClusters)
if requiredResult != nil {
rootResult.Dependencies = append(rootResult.Dependencies, requiredResult)
}
if requiredResult == nil || requiredResult.StatusCode == http.StatusOK {
continue
}
if requiredResult.StatusCode == http.StatusNotFound {
checkResult := NewErrorCheckResult(
http.StatusInternalServerError,
fmt.Errorf("required MySQL cluster metric %q is unavailable", requiredCluster),
)
checkResult.MetricName = fmt.Sprintf("mysql/%s", requiredCluster)
checkResult.rejectionReason = "missing_metric"
return checkResult
err := fmt.Errorf("required MySQL cluster metric %q is unavailable", requiredCluster)
requiredResult.StatusCode = http.StatusInternalServerError
requiredResult.Error = err
requiredResult.Message = err.Error()
requiredResult.rejectionReason = "missing_metric"
}
return requiredResult
if blocker == nil {
blocker = requiredResult
}
}
if blocker != nil && blocker != rootResult {
rootResult.StatusCode = blocker.StatusCode
rootResult.Error = blocker.Error
rootResult.Message = blocker.Message
rootResult.blockingResult = blocker.rejectionResult()
}
return rootResult
}
Expand Down Expand Up @@ -163,18 +178,19 @@ func (check *ThrottlerCheck) Check(appName string, storeType string, storeName s
}

if checkResult.StatusCode == http.StatusTooManyRequests && appName != frenoAppName && appName != frenoShareDmainAppName {
rejection := checkResult.rejectionResult()
reason := "other"
switch {
case errors.Is(checkResult.Error, base.RecoveryNotCompleteError):
case errors.Is(rejection.Error, base.RecoveryNotCompleteError):
reason = "recovery"
case errors.Is(checkResult.Error, base.ThresholdExceededError) && checkResult.Value > checkResult.Threshold:
case errors.Is(rejection.Error, base.ThresholdExceededError) && rejection.Value > rejection.Threshold:
reason = "threshold"
}
metricName := strings.ReplaceAll(checkResult.MetricName, "/", ".")
metricName := strings.ReplaceAll(rejection.MetricName, "/", ".")
metrics.GetOrRegisterCounter(fmt.Sprintf("check.rejected.%s.%s.total", metricName, reason), nil).Inc(1)
}
if storeType == "mysql" {
check.recordMySQLRejection(appName, storeName, checkResult)
check.recordMySQLRejection(appName, storeName, checkResult.rejectionResult())
}

go func(statusCode int) {
Expand Down
195 changes: 195 additions & 0 deletions pkg/throttle/check_response_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package throttle

import (
"encoding/json"
"errors"
"net/http"
"testing"
"time"

"github.com/github/freno/pkg/base"
"github.com/github/freno/pkg/config"
"github.com/stretchr/testify/assert"
)

func TestCheckKeepsRequestedMeasurementAndReportsDependencies(t *testing.T) {
original := config.Settings().Stores.MySQL
t.Cleanup(func() { config.Settings().Stores.MySQL = original })
config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{
Clusters: map[string]*config.MySQLClusterConfigurationSettings{
"replicas": {RequiredClusters: []string{"primary", "other"}},
"primary": {FailOnNoHosts: true},
"other": {},
},
}
for _, test := range []struct {
name string
replica base.MetricResult
primary base.MetricResult
shared bool
wantStatus int
wantBlocker string
wantMessage string
wantLag interface{}
wantPrimary interface{}
}{
{"healthy", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), false, 200, "", "", 0.05, float64(23)},
{"primary overload", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(80), false, 429, "mysql/primary", "Threshold exceeded", 0.05, float64(80)},
{"primary recovery", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(35, base.RecoveryNotCompleteError), false, 429, "mysql/primary", "Recovery period not complete", 0.05, float64(35)},
{"primary shared health", base.NewSimpleMetricResult(0.05), base.NewSimpleMetricResult(23), true, 429, "mysql/primary", "Threshold exceeded", 0.05, float64(23)},
{"primary probe error", base.NewSimpleMetricResult(0.05), base.NewErrorMetricResult(999, errors.New("probe failed")), false, 500, "mysql/primary", "probe failed", 0.05, float64(999)},
{"primary no hosts", base.NewSimpleMetricResult(0.05), base.NoHostsMetricResult, false, 500, "mysql/primary", "No hosts found", 0.05, float64(0)},
{"primary missing", base.NewSimpleMetricResult(0.05), base.NoSuchMetric, false, 500, "mysql/primary", `required MySQL cluster metric "primary" is unavailable`, 0.05, float64(0)},
{"lag overload includes pressure", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "Threshold exceeded", float64(6), float64(23)},
{"lag recovery includes pressure", base.NewErrorMetricResult(2, base.RecoveryNotCompleteError), base.NewSimpleMetricResult(23), false, 429, "mysql/replicas", "Recovery period not complete", float64(2), float64(23)},
{"both overloaded keeps first blocker", base.NewSimpleMetricResult(6), base.NewSimpleMetricResult(80), false, 429, "mysql/replicas", "Threshold exceeded", float64(6), float64(80)},
{"lag error includes pressure", base.NewErrorMetricResult(999, errors.New("lag failed")), base.NewSimpleMetricResult(23), false, 500, "mysql/replicas", "lag failed", float64(999), float64(23)},
{"both unavailable", base.NoMetricResultYet, base.NoMetricResultYet, false, 500, "mysql/replicas", "Metric not collected yet", float64(0), float64(0)},
{"legacy lag no-hosts fail-open is unchanged", base.NoHostsMetricResult, base.NewSimpleMetricResult(23), false, 200, "", "No hosts found", float64(0), float64(23)},
} {
t.Run(test.name, func(t *testing.T) {
throttler := NewThrottler()
setTestMySQLClusterMetric(throttler, "replicas", 0.05, 5)
setTestMySQLClusterMetric(throttler, "primary", 23, 50)
setTestMySQLClusterMetric(throttler, "other", 10, 20)
throttler.aggregatedMetrics.SetDefault("mysql/replicas", test.replica)
throttler.aggregatedMetrics.SetDefault("mysql/primary", test.primary)
if test.shared {
throttler.shareDomainMetricHealth.SetDefault("mysql/primary", &base.MetricHealth{SecondsSinceLastHealthy: 1})
}
checked := make(map[string]bool)
result := NewThrottlerCheck(throttler).checkMySQLCluster("test-app", "replicas", StandardCheckFlags, checked)
assert.Equal(t, test.wantStatus, result.StatusCode)
assert.Equal(t, "mysql/replicas", result.MetricName)
data, err := json.Marshal(result)
if !assert.NoError(t, err) {
return
}
var body map[string]interface{}
if !assert.NoError(t, json.Unmarshal(data, &body)) {
return
}
assert.Equal(t, test.wantLag, body["Value"])
assert.Equal(t, float64(5), body["Threshold"])
assert.Equal(t, test.wantMessage, body["Message"])
assert.NotContains(t, body, "MeasurementAvailable")
assert.NotContains(t, body, "MeasurementError")
assert.NotContains(t, body, "RejectionReason")
if test.wantBlocker == "" {
assert.NotContains(t, body, "BlockingMetricName")
} else {
assert.Equal(t, test.wantBlocker, body["BlockingMetricName"])
}
if !assert.Len(t, result.Dependencies, 2) {
return
}
assert.Equal(t, map[string]bool{"replicas": true, "primary": true, "other": true}, checked)
assert.Equal(t, "mysql/primary", result.Dependencies[0].MetricName)
assert.Equal(t, 10.0, result.Dependencies[1].Value)
dependencies := body["Dependencies"].([]interface{})
primary := dependencies[0].(map[string]interface{})
assert.Equal(t, test.wantPrimary, primary["Value"])
assert.NotContains(t, primary, "MeasurementAvailable")
assert.NotContains(t, primary, "MeasurementError")
assert.NotContains(t, primary, "RejectionReason")
assert.NotContains(t, primary, "BlockingMetricName")
assert.Equal(t, result.Dependencies[0].Message, primary["Message"])
})
}
}

func TestDiagnosticDependenciesDoNotSetLowPriorityThrottlingState(t *testing.T) {
original := config.Settings().Stores.MySQL
t.Cleanup(func() { config.Settings().Stores.MySQL = original })
config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{
Clusters: map[string]*config.MySQLClusterConfigurationSettings{
"replicas": {RequiredClusters: []string{"primary", "other"}},
"primary": {},
"other": {},
},
}
for _, test := range []struct {
name string
lag float64
blocker string
diagnostics []string
}{
{"lag blocks first", 6, "mysql/replicas", []string{"mysql/primary", "mysql/other"}},
{"primary blocks first", 0.05, "mysql/primary", []string{"mysql/other"}},
} {
t.Run(test.name, func(t *testing.T) {
throttler := NewThrottler()
setTestMySQLClusterMetric(throttler, "replicas", test.lag, 5)
setTestMySQLClusterMetric(throttler, "primary", 80, 50)
setTestMySQLClusterMetric(throttler, "other", 30, 20)
result := NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags)
assert.Equal(t, http.StatusTooManyRequests, result.StatusCode)
assert.Equal(t, test.blocker, result.rejectionResult().MetricName)
assert.Len(t, result.Dependencies, 2)
assert.Eventually(t, func() bool {
_, exists := throttler.nonLowPriorityAppRequestsThrottled.Get(test.blocker)
return exists
}, time.Second, time.Millisecond)
assert.Never(t, func() bool {
for _, metric := range test.diagnostics {
if _, exists := throttler.nonLowPriorityAppRequestsThrottled.Get(metric); exists {
return true
}
}
return false
}, 50*time.Millisecond, time.Millisecond)
})
}
}

func TestNestedDependenciesKeepLagAndBlockerIdentity(t *testing.T) {
original := config.Settings().Stores.MySQL
t.Cleanup(func() { config.Settings().Stores.MySQL = original })
config.Settings().Stores.MySQL = config.MySQLConfigurationSettings{
Clusters: map[string]*config.MySQLClusterConfigurationSettings{
"replicas": {RequiredClusters: []string{"intermediate"}},
"intermediate": {RequiredClusters: []string{"primary"}},
"primary": {},
},
}
throttler := NewThrottler()
setTestMySQLClusterMetric(throttler, "replicas", 0.05, 1)
setTestMySQLClusterMetric(throttler, "intermediate", 0.1, 1)
setTestMySQLClusterMetric(throttler, "primary", 80, 75)
result := NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags)
assert.Equal(t, http.StatusTooManyRequests, result.StatusCode)
assert.Equal(t, 0.05, result.Value)
assert.Equal(t, "mysql/replicas", result.MetricName)
if !assert.Len(t, result.Dependencies, 1) {
return
}
assert.Equal(t, 0.1, result.Dependencies[0].Value)
assert.Equal(t, "mysql/primary", result.rejectionResult().MetricName)
assert.Equal(t, 80.0, result.rejectionResult().Value)
data, err := json.Marshal(result)
if !assert.NoError(t, err) {
return
}
var body map[string]interface{}
if !assert.NoError(t, json.Unmarshal(data, &body)) {
return
}
assert.Equal(t, "mysql/primary", body["BlockingMetricName"])
intermediate := body["Dependencies"].([]interface{})[0].(map[string]interface{})
primary := intermediate["Dependencies"].([]interface{})[0].(map[string]interface{})
for _, dependency := range []map[string]interface{}{intermediate, primary} {
assert.NotContains(t, dependency, "BlockingMetricName")
assert.NotContains(t, dependency, "RejectionReason")
assert.NotContains(t, dependency, "MeasurementError")
}

throttler.aggregatedMetrics.Delete("mysql/intermediate")
result = NewThrottlerCheck(throttler).Check("test-app", "mysql", "replicas", "", StandardCheckFlags)
assert.Equal(t, http.StatusInternalServerError, result.StatusCode)
assert.Equal(t, 0.05, result.Value)
assert.Equal(t, "mysql/intermediate", result.rejectionResult().MetricName)
if !assert.Len(t, result.Dependencies, 1) || !assert.Len(t, result.Dependencies[0].Dependencies, 1) {
return
}
assert.Equal(t, 80.0, result.Dependencies[0].Dependencies[0].Value)
}
Loading