-
Notifications
You must be signed in to change notification settings - Fork 149
/
tc.go
70 lines (56 loc) · 1.89 KB
/
tc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package tc
import (
"fmt"
"math"
"github.com/pkg/errors"
"github.com/vishvananda/netlink"
)
// TrafficShapingRule the interface traffic shaping rule
type TrafficShapingRule struct {
// rate in bytes
Rate uint64
}
func burst(rate uint64, mtu int) uint32 {
return uint32(math.Ceil(math.Max(float64(rate)/milliSeconds, float64(mtu))))
}
func time2Tick(time uint32) uint32 {
return uint32(float64(time) * float64(netlink.TickInUsec()))
}
func buffer(rate uint64, burst uint32) uint32 {
return time2Tick(uint32(float64(burst) * float64(netlink.TIME_UNITS_PER_SEC) / float64(rate)))
}
func limit(rate uint64, latency float64, buffer uint32) uint32 {
return uint32(float64(rate)*latency/float64(netlink.TIME_UNITS_PER_SEC)) + buffer
}
func latencyInUsec(latencyInMillis float64) float64 {
return float64(netlink.TIME_UNITS_PER_SEC) * (latencyInMillis / 1000.0)
}
const latencyInMillis = 25
const hardwareHeaderLen = 1500
const milliSeconds = 1000
// SetRule set the traffic rule on interface
func SetRule(dev netlink.Link, rule *TrafficShapingRule) error {
if rule.Rate <= 0 {
return fmt.Errorf("invalid rate %d", rule.Rate)
}
burst := burst(rule.Rate, dev.Attrs().MTU+hardwareHeaderLen)
buffer := buffer(rule.Rate, burst)
latency := latencyInUsec(latencyInMillis)
limit := limit(rule.Rate, latency, burst)
//log.Infof("set tc qdics add dev %v/%s root tbf rate %d burst %d", dev.Attrs().Namespace, dev.Attrs().Name, rule.Rate, burst)
tbf := &netlink.Tbf{
QdiscAttrs: netlink.QdiscAttrs{
LinkIndex: dev.Attrs().Index,
Handle: netlink.MakeHandle(1, 0),
Parent: netlink.HANDLE_ROOT,
},
Rate: rule.Rate,
Limit: uint32(limit),
Buffer: uint32(buffer),
Minburst: uint32(dev.Attrs().MTU),
}
if err := netlink.QdiscReplace(tbf); err != nil {
return errors.Wrapf(err, "can not replace qdics %+v on device %v/%s", tbf, dev.Attrs().Namespace, dev.Attrs().Name)
}
return nil
}