| 1 | package vnet |
| 2 | |
| 3 | import ( |
| 4 | "math/rand" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | // LossFilter is a wrapper around NICs, that drops some of the packets passed to |
| 9 | // onInboundChunk |
| 10 | type LossFilter struct { |
| 11 | NIC |
| 12 | chance int |
| 13 | } |
| 14 | |
| 15 | // NewLossFilter creates a new LossFilter that drops every packet with a |
| 16 | // probability of chance/100. Every packet that is not dropped is passed on to |
| 17 | // the given NIC. |
| 18 | func NewLossFilter(nic NIC, chance int) (*LossFilter, error) { |
| 19 | f := &LossFilter{ |
| 20 | NIC: nic, |
| 21 | chance: chance, |
| 22 | } |
| 23 | rand.Seed(time.Now().UTC().UnixNano()) |
| 24 | return f, nil |
| 25 | } |
| 26 | |
| 27 | func (f *LossFilter) onInboundChunk(c Chunk) { |
| 28 | if rand.Intn(100) < f.chance { //nolint:gosec |
| 29 | return |
| 30 | } |
| 31 | |
| 32 | f.NIC.onInboundChunk(c) |
| 33 | } |