Skip to content

Commit 77c0e87

Browse files
committed
Add IP whitelisting in request throttler
1 parent 25e57c0 commit 77c0e87

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

api.go

+7
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,12 @@ func throttleMiddleware(throttler *Throttler) gin.HandlerFunc {
9494
return func(c *gin.Context) {
9595
ip := strings.Split(c.Request.RemoteAddr, ":")[0]
9696

97+
// Bypass throttling for whitelisted IPs
98+
if throttler.Whitelisted(ip) {
99+
c.Next()
100+
return
101+
}
102+
97103
if err := throttler.Add(ip); err != nil {
98104
errorResponse(429, err, c)
99105
c.Abort()
@@ -115,6 +121,7 @@ func corsMiddleware() gin.HandlerFunc {
115121

116122
func RunApi(config *Config, client *docker.Client) {
117123
throttler := NewThrottler(config.ThrottleConcurrency, config.ThrottleQuota)
124+
throttler.SetWhitelist(config.ThrottleWhitelist)
118125
throttler.StartPeriodicFlush()
119126

120127
gin.SetMode(gin.ReleaseMode)

config.go

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ type Config struct {
2121
RunDuration time.Duration `json:"run_duration"`
2222
ThrottleQuota int `json:"throttle_quota"`
2323
ThrottleConcurrency int `json:"throttle_concurrency"`
24+
ThrottleWhitelist []string `json:"throttle_whitelist"`
2425
NetworkDisabled bool `json:"network_disabled"`
2526
MemoryLimit int64 `json:"memory_limit"`
2627
Pools []PoolConfig `json:"pools"`

config.json.example

+4
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,12 @@
66
"run_duration": 10,
77
"throttle_quota": 5,
88
"throttle_concurrency": 1,
9+
"throttle_whitelist": [
10+
"127.0.0.1"
11+
],
912
"network_disabled": false,
1013
"memory_limit": 67108864,
14+
"fetch_images": true,
1115
"pools": [
1216
{ "image": "bitrun/ruby:2.2", "capacity": 10 }
1317
]

throttler.go

+13
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ type Throttler struct {
1111
Quota int
1212
Clients map[string]int
1313
Requests map[string]int
14+
Whitelist map[string]bool
1415
*sync.Mutex
1516
}
1617

@@ -20,6 +21,7 @@ func NewThrottler(concurrency int, quota int) *Throttler {
2021
Quota: quota,
2122
Clients: make(map[string]int),
2223
Requests: make(map[string]int),
24+
Whitelist: make(map[string]bool),
2325
Mutex: &sync.Mutex{},
2426
}
2527
}
@@ -70,3 +72,14 @@ func (t *Throttler) Flush() {
7072
delete(t.Requests, k)
7173
}
7274
}
75+
76+
func (t *Throttler) SetWhitelist(ips []string) {
77+
for _, ip := range ips {
78+
t.Whitelist[ip] = true
79+
}
80+
}
81+
82+
func (t *Throttler) Whitelisted(ip string) bool {
83+
_, ok := t.Whitelist[ip]
84+
return ok
85+
}

0 commit comments

Comments
 (0)