ratelimit.go

// The ratelimit package provides an efficient token bucket implementation
// that can be used to limit the rate of arbitrary things.
// See http://en.wikipedia.org/wiki/Token_bucket.
package ratelimit

import (
    "math"
    "strconv"
    "sync"
    "time"
)

// Bucket represents a token bucket that fills at a predetermined rate.
// Methods on Bucket may be called concurrently.
//令牌桶  结构体
type Bucket struct {
    startTime    time.Time  //开始时间
    capacity     int64    //令牌桶容量
    quantum      int64     //
    fillInterval time.Duration   //

    // The mutex guards the fields following it.
    mu sync.Mutex

    // avail holds the number of available tokens
    // in the bucket, as of availTick ticks from startTime.
    // It will be negative when there are consumers
    // waiting for tokens.
    avail     int64
    availTick int64
}

// NewBucket returns a new token bucket that fills at the
// rate of one token every fillInterval, up to the given
// maximum capacity. Both arguments must be
// positive. The bucket is initially full.
func NewBucket(fillInterval time.Duration, capacity int64) *Bucket {
    return NewBucketWithQuantum(fillInterval, capacity, 1)
}

// rateMargin specifes the allowed variance of actual
// rate from specified rate. 1% seems reasonable.
const rateMargin = 0.01

// NewBucketWithRate returns a token bucket that fills the bucket
// at the rate of rate tokens per second up to the given
// maximum capacity. Because of limited clock resolution,
// at high rates, the actual rate may be up to 1% different from the
// specified rate.
func NewBucketWithRate(rate float64, capacity int64) *Bucket {
    for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) {
        fillInterval := time.Duration(1e9 * float64(quantum) / rate)
        if fillInterval <= 0 {
            continue
        }
        tb := NewBucketWithQuantum(fillInterval, capacity, quantum)
        if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin {
            return tb
        }
    }
    panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, ‘g‘, -1, 64))
}

// nextQuantum returns the next quantum to try after q.
// We grow the quantum exponentially, but slowly, so we
// get a good fit in the lower numbers.
func nextQuantum(q int64) int64 {
    q1 := q * 11 / 10
    if q1 == q {
        q1++
    }
    return q1
}

// NewBucketWithQuantum is similar to NewBucket, but allows
// the specification of the quantum size - quantum tokens
// are added every fillInterval.
func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket {
    if fillInterval <= 0 {
        panic("token bucket fill interval is not > 0")
    }
    if capacity <= 0 {
        panic("token bucket capacity is not > 0")
    }
    if quantum <= 0 {
        panic("token bucket quantum is not > 0")
    }
    return &Bucket{
        startTime:    time.Now(),
        capacity:     capacity,
        quantum:      quantum,
        avail:        capacity,
        fillInterval: fillInterval,
    }
}

// Wait takes count tokens from the bucket, waiting until they are
// available.
func (tb *Bucket) Wait(count int64) {
    if d := tb.Take(count); d > 0 {
        time.Sleep(d)
    }
}

// WaitMaxDuration is like Wait except that it will
// only take tokens from the bucket if it needs to wait
// for no greater than maxWait. It reports whether
// any tokens have been removed from the bucket
// If no tokens have been removed, it returns immediately.
func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool {
    d, ok := tb.TakeMaxDuration(count, maxWait)
    if d > 0 {
        time.Sleep(d)
    }
    return ok
}

const infinityDuration time.Duration = 0x7fffffffffffffff

// Take takes count tokens from the bucket without blocking. It returns
// the time that the caller should wait until the tokens are actually
// available.
//
// Note that if the request is irrevocable - there is no way to return
// tokens to the bucket once this method commits us to taking them.
func (tb *Bucket) Take(count int64) time.Duration {
    d, _ := tb.take(time.Now(), count, infinityDuration)
    return d
}

// TakeMaxDuration is like Take, except that
// it will only take tokens from the bucket if the wait
// time for the tokens is no greater than maxWait.
//
// If it would take longer than maxWait for the tokens
// to become available, it does nothing and reports false,
// otherwise it returns the time that the caller should
// wait until the tokens are actually available, and reports
// true.
func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) {
    return tb.take(time.Now(), count, maxWait)
}

// TakeAvailable takes up to count immediately available tokens from the
// bucket. It returns the number of tokens removed, or zero if there are
// no available tokens. It does not block.
func (tb *Bucket) TakeAvailable(count int64) int64 {
    return tb.takeAvailable(time.Now(), count)
}

// takeAvailable is the internal version of TakeAvailable - it takes the
// current time as an argument to enable easy testing.
func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 {
    if count <= 0 {
        return 0
    }
    tb.mu.Lock()
    defer tb.mu.Unlock()

    tb.adjust(now)
    if tb.avail <= 0 {
        return 0
    }
    if count > tb.avail {
        count = tb.avail
    }
    tb.avail -= count
    return count
}

// Available returns the number of available tokens. It will be negative
// when there are consumers waiting for tokens. Note that if this
// returns greater than zero, it does not guarantee that calls that take
// tokens from the buffer will succeed, as the number of available
// tokens could have changed in the meantime. This method is intended
// primarily for metrics reporting and debugging.
func (tb *Bucket) Available() int64 {
    return tb.available(time.Now())
}

// available is the internal version of available - it takes the current time as
// an argument to enable easy testing.
func (tb *Bucket) available(now time.Time) int64 {
    tb.mu.Lock()
    defer tb.mu.Unlock()
    tb.adjust(now)
    return tb.avail
}

// Capacity returns the capacity that the bucket was created with.
func (tb *Bucket) Capacity() int64 {
    return tb.capacity
}

// Rate returns the fill rate of the bucket, in tokens per second.
func (tb *Bucket) Rate() float64 {
    return 1e9 * float64(tb.quantum) / float64(tb.fillInterval)
}

// take is the internal version of Take - it takes the current time as
// an argument to enable easy testing.
func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) {
    if count <= 0 {
        return 0, true
    }
    tb.mu.Lock()
    defer tb.mu.Unlock()

    currentTick := tb.adjust(now)
    avail := tb.avail - count
    if avail >= 0 {
        tb.avail = avail
        return 0, true
    }
    // Round up the missing tokens to the nearest multiple
    // of quantum - the tokens won‘t be available until
    // that tick.
    endTick := currentTick + (-avail+tb.quantum-1)/tb.quantum
    endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval)
    waitTime := endTime.Sub(now)
    if waitTime > maxWait {
        return 0, false
    }
    tb.avail = avail
    return waitTime, true
}

// adjust adjusts the current bucket capacity based on the current time.
// It returns the current tick.
func (tb *Bucket) adjust(now time.Time) (currentTick int64) {
    currentTick = int64(now.Sub(tb.startTime) / tb.fillInterval)

    if tb.avail >= tb.capacity {
        return
    }
    tb.avail += (currentTick - tb.availTick) * tb.quantum
    if tb.avail > tb.capacity {
        tb.avail = tb.capacity
    }
    tb.availTick = currentTick
    return
}
时间: 2024-11-08 19:25:06

ratelimit.go的相关文章

使用bind新功能rate-limit防止DNS放大攻击和流量攻击

目前好多做DNS解析的服务,都采用了bind开源软件.好处就不多说了.但是在安全方面是个软肋,遭受DDOS流量攻击和放大攻击是常有的事情.在14年12月isc发布了最新的bind9.10-p1稳定版,同时对rate-limit默认支持(之前bind9.9的扩展支持版本,同样支持处于开发功能,需要在编译安装的时候./configure --enable-rrl开启rate-limit功能).rate-limit可以有效防止放大攻击和DDOS流量攻击. DDOS流量攻击就不多说了,关于放大攻击原理,

ToughRADIUS 与 RouterOS对接指南

在ToughRADIUS中增加 接入设备 配置 RouterOS 设备信息必须在 ToughRADIUS 系统中配置,不然所有认证消息会被丢弃. RouterOS radius 配置 radius 服务配置 注意,要使强制下线功能有效,务必启动授权功能,开放3799端口给 Radius. 开启RouterOS上的 radius 记账 对于记账间隔,如果是包月类型套餐,记账间隔应该设置的长一点,可以有效减轻 radius 服务器负担,如果希望获取更多的记账数据,适当的调整需要的记账间隔时间. Ro

ASA 8.0命令解析

有些朋友对配防火墙还是有问题,其实配置ASA防火墙很简单,常用的命令有hostname.interface(ip address.no shutdown.nameif.security-level).nat.global.route.static.access-list.access-group. 下面来解析一台ASA 8.0的配置 ASA Version 8.0(2)  //注意版本,8.3以后NAT命令有所变化!hostname ciscoasa   //主机名domain-name san

自己总结的 iOS ,Mac 开源项目以及库,知识点------持续更新

自己在 git  上看到一个非常好的总结的东西,但是呢, fork  了几次,就是 fork  不到我的 git 上,干脆复制进去,但是,也是认真去每一个每一个去认真看了,并且也是补充了一些,感觉非常棒,所以好东西要分享,为啥用 CN 博客,有个好处,可以随时修改,可以持续更新,不用每次都要再发表,感觉这样棒棒的 我们 自己总结的iOS.mac开源项目及库,持续更新.... github排名 https://github.com/trending,github搜索:https://github.

rsyslog配置解析

RSYSLOG is the rocket-fast system for log processing. 本地Rsyslog版本: 8.25.0-1.el6.x86_64 配置 基本语法 Rsyslog 现在支持三种配置语法格式: sysklogd legacy rsyslog RainerScript sysklogd 是老的简单格式,一些新的语法特性不支持.legacy rsyslog 是以dollar符($)开头的语法,在v6及以上的版本还在支持,一些插件和特性可能只在此语法下支持.Ra

华为5700系列交换机常用配置示例

华为S5700系列交换机,是我们项目中用的较多的一款,其中24与48口应用较多.现在将华为交换机的一些常用配置整理一下,进行记录.如有错误,请指正. 1 允许telnet(远程登录) 允许华为交换机能telnet,设置密码为[email protected] telnet server en # aaa authentication-scheme default authorization-scheme default accounting-scheme default domain defau

四、远程连接与openssh

4.1.openssh简介 传统的网络程序都是采用明文传输数据和密码,如telnet.ftp等,存在很大的安全漏洞,黑客只需要使用一些数据包截取工具就可以获得包括密码在内的重要数据.正因如此,后来才出现了SSH (Secure shell,安全命令壳).SSH是由芬兰的一家公司所研发的加密通信协议,所有SSH传输的数据都是经过加密,可以有效防止数据的窃取以及'中间人'的攻击.SSH建立在应用层和传输层基础上的安全协议,监听tcp的22号端口,属于是文本协议.OpenSSH是SSH的替代软件,完全

swift分布式存储多节点部署

1.机器 192.168.1.211    Proxy Node 192.168.1.212    Storage Node 192.168.1.213    Storage Node 192.168.1.214    Storage Node 系统为SLES11sp1 2.配置软件源 因为公司服务器无法连外网,所以配置局域网源和本地源来搭建环境 上传ISO镜像文件到各台机器 SLES-11-SP4-DVD-x86_64-GM-DVD1.iso 每台机器挂载镜像,配置本地源 # mkdir /m

消息队列_RabbitMQ-0004.深入RabbitMQ之分类告警/并行执行/RPC响应?

应用场景: 1. 通知,针对发送事件的描述,内容可以是消息的日志,也可以是真实的报告通知给另一个程序或者管理员. 说明: 首先选择交换机,如果选择fanout交换机,则需要为每种告警传输类型(邮件/微信/手机/短信)创建队列,但同时也带来坏处就是每个消息都会发送到所有队列,导致告警消息发生时,被报警消息淹没,如果选择topic交换机,则可为其创建四种严重级别告警info/warning/problem/citical,但如果使用fanout类型交换机消息会发送到所有这四个级别队列,如果使用dir