This repository has been archived by the owner on Apr 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[nginx-ingress-controller] Add support for rate limiting in ingress rule locations #1093
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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 |
---|---|---|
|
@@ -156,6 +156,12 @@ http { | |
} | ||
{{ end }} | ||
|
||
{{/* build all the required rate limit zones. Each annotation requires a dedicated zone */}} | ||
{{/* 1MB -> 16 thousand 64-byte states or about 8 thousand 128-byte states */}} | ||
{{ $zone := range (buildRateLimitZones .servers) }} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm a bit late but shouldn't this be Should I make a PR? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @louis-paul this is fixed in #1104. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great, thanks! |
||
{{ $zone }} | ||
{{ end }} | ||
|
||
{{ range $server := .servers }} | ||
server { | ||
server_name {{ $server.Name }}; | ||
|
@@ -180,7 +186,10 @@ http { | |
{{- range $location := $server.Locations }} | ||
{{- $path := buildLocation $location }} | ||
location {{ $path }} { | ||
location {{ $path }} { | ||
{{/* if the location contains a rate limit annotation, create one */}} | ||
{{ $limits := buildRateLimit $location }} | ||
{{- range $limit := $limits }} | ||
{{ $limit }}{{ end }} | ||
proxy_set_header Host $host; | ||
|
||
# Pass Real IP | ||
|
This file contains 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 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,126 @@ | ||
/* | ||
Copyright 2016 The Kubernetes Authors All rights reserved. | ||
|
||
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 ratelimit | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"strconv" | ||
|
||
"k8s.io/kubernetes/pkg/apis/extensions" | ||
) | ||
|
||
const ( | ||
limitIp = "ingress.kubernetes.io/limit-connections" | ||
limitRps = "ingress.kubernetes.io/limit-rps" | ||
|
||
// allow 5 times the specified limit as burst | ||
defBurst = 5 | ||
|
||
// 1MB -> 16 thousand 64-byte states or about 8 thousand 128-byte states | ||
// default is 5MB | ||
defSharedSize = 5 | ||
) | ||
|
||
var ( | ||
// ErrInvalidRateLimit is returned when the annotation caontains invalid values | ||
ErrInvalidRateLimit = errors.New("invalid rate limit value. Must be > 0") | ||
|
||
// ErrMissingAnnotations is returned when the ingress rule | ||
// does not contains annotations related with rate limit | ||
ErrMissingAnnotations = errors.New("no annotations present") | ||
) | ||
|
||
// RateLimit returns rate limit configuration for an Ingress rule | ||
// Is possible to limit the number of connections per IP address or | ||
// connections per second. | ||
// Note: Is possible to specify both limits | ||
type RateLimit struct { | ||
// Connections indicates a limit with the number of connections per IP address | ||
Connections Zone | ||
// RPS indicates a limit with the number of connections per second | ||
RPS Zone | ||
} | ||
|
||
// Zone returns information about the NGINX rate limit (limit_req_zone) | ||
// http://nginx.org/en/docs/http/ngx_http_limit_req_module.html#limit_req_zone | ||
type Zone struct { | ||
Name string | ||
Limit int | ||
Burst int | ||
// SharedSize amount of shared memory for the zone | ||
SharedSize int | ||
} | ||
|
||
type ingAnnotations map[string]string | ||
|
||
func (a ingAnnotations) limitIp() int { | ||
val, ok := a[limitIp] | ||
if ok { | ||
if i, err := strconv.Atoi(val); err == nil { | ||
return i | ||
} | ||
} | ||
|
||
return 0 | ||
} | ||
|
||
func (a ingAnnotations) limitRps() int { | ||
val, ok := a[limitRps] | ||
if ok { | ||
if i, err := strconv.Atoi(val); err == nil { | ||
return i | ||
} | ||
} | ||
|
||
return 0 | ||
} | ||
|
||
// ParseAnnotations parses the annotations contained in the ingress | ||
// rule used to rewrite the defined paths | ||
func ParseAnnotations(ing *extensions.Ingress) (*RateLimit, error) { | ||
if ing.GetAnnotations() == nil { | ||
return &RateLimit{}, ErrMissingAnnotations | ||
} | ||
|
||
rps := ingAnnotations(ing.GetAnnotations()).limitRps() | ||
conn := ingAnnotations(ing.GetAnnotations()).limitIp() | ||
|
||
if rps == 0 && conn == 0 { | ||
return &RateLimit{ | ||
Connections: Zone{}, | ||
RPS: Zone{}, | ||
}, ErrInvalidRateLimit | ||
} | ||
|
||
zoneName := fmt.Sprintf("%v_%v", ing.GetNamespace(), ing.GetName()) | ||
|
||
return &RateLimit{ | ||
Connections: Zone{ | ||
Name: fmt.Sprintf("%v_conn", zoneName), | ||
Limit: conn, | ||
Burst: conn * defBurst, | ||
SharedSize: defSharedSize, | ||
}, | ||
RPS: Zone{ | ||
Name: fmt.Sprintf("%v_rps", zoneName), | ||
Limit: rps, | ||
Burst: conn * defBurst, | ||
SharedSize: defSharedSize, | ||
}, | ||
}, nil | ||
} |
This file contains 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,129 @@ | ||
/* | ||
Copyright 2015 The Kubernetes Authors All rights reserved. | ||
|
||
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 ratelimit | ||
|
||
import ( | ||
"testing" | ||
|
||
"k8s.io/kubernetes/pkg/api" | ||
"k8s.io/kubernetes/pkg/apis/extensions" | ||
"k8s.io/kubernetes/pkg/util/intstr" | ||
) | ||
|
||
func buildIngress() *extensions.Ingress { | ||
defaultBackend := extensions.IngressBackend{ | ||
ServiceName: "default-backend", | ||
ServicePort: intstr.FromInt(80), | ||
} | ||
|
||
return &extensions.Ingress{ | ||
ObjectMeta: api.ObjectMeta{ | ||
Name: "foo", | ||
Namespace: api.NamespaceDefault, | ||
}, | ||
Spec: extensions.IngressSpec{ | ||
Backend: &extensions.IngressBackend{ | ||
ServiceName: "default-backend", | ||
ServicePort: intstr.FromInt(80), | ||
}, | ||
Rules: []extensions.IngressRule{ | ||
{ | ||
Host: "foo.bar.com", | ||
IngressRuleValue: extensions.IngressRuleValue{ | ||
HTTP: &extensions.HTTPIngressRuleValue{ | ||
Paths: []extensions.HTTPIngressPath{ | ||
{ | ||
Path: "/foo", | ||
Backend: defaultBackend, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func TestAnnotations(t *testing.T) { | ||
ing := buildIngress() | ||
|
||
lip := ingAnnotations(ing.GetAnnotations()).limitIp() | ||
if lip != 0 { | ||
t.Error("Expected 0 in limit by ip but %v was returned", lip) | ||
} | ||
|
||
lrps := ingAnnotations(ing.GetAnnotations()).limitRps() | ||
if lrps != 0 { | ||
t.Error("Expected 0 in limit by rps but %v was returend", lrps) | ||
} | ||
|
||
data := map[string]string{} | ||
data[limitIp] = "5" | ||
data[limitRps] = "100" | ||
ing.SetAnnotations(data) | ||
|
||
lip = ingAnnotations(ing.GetAnnotations()).limitIp() | ||
if lip != 5 { | ||
t.Error("Expected %v in limit by ip but %v was returend", lip) | ||
} | ||
|
||
lrps = ingAnnotations(ing.GetAnnotations()).limitRps() | ||
if lrps != 100 { | ||
t.Error("Expected 100 in limit by rps but %v was returend", lrps) | ||
} | ||
} | ||
|
||
func TestWithoutAnnotations(t *testing.T) { | ||
ing := buildIngress() | ||
_, err := ParseAnnotations(ing) | ||
if err == nil { | ||
t.Error("Expected error with ingress without annotations") | ||
} | ||
} | ||
|
||
func TestBadRateLimiting(t *testing.T) { | ||
ing := buildIngress() | ||
|
||
data := map[string]string{} | ||
data[limitIp] = "0" | ||
data[limitRps] = "0" | ||
ing.SetAnnotations(data) | ||
|
||
_, err := ParseAnnotations(ing) | ||
if err == nil { | ||
t.Errorf("Expected error with invalid limits (0)") | ||
} | ||
|
||
data = map[string]string{} | ||
data[limitIp] = "5" | ||
data[limitRps] = "100" | ||
ing.SetAnnotations(data) | ||
|
||
rateLimit, err := ParseAnnotations(ing) | ||
if err != nil { | ||
t.Errorf("Uxpected error: %v", err) | ||
} | ||
|
||
if rateLimit.Connections.Limit != 5 { | ||
t.Error("Expected 5 in limit by ip but %v was returend", rateLimit.Connections) | ||
} | ||
|
||
if rateLimit.RPS.Limit != 100 { | ||
t.Error("Expected 100 in limit by rps but %v was returend", rateLimit.RPS) | ||
} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
things like this feel event worthy, if it's easy enough to send an event. If the user thought they specified the right annotations but didn't, they should know their backend isn't getting ratelimited without having to debug a bunch and look around in the logs