Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example: Add netem example with a 100ms delay #152

Merged
merged 1 commit into from
Jun 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions example_netem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"os"
"time"

"github.com/florianl/go-tc"
"github.com/florianl/go-tc/core"
Expand Down Expand Up @@ -92,3 +93,87 @@ func ExampleNetem() {
fmt.Printf("%20s\t%s\n", iface.Name, qdisc.Kind)
}
}

func ExampleNetemDelay() {
tcIface := "ExampleNetemDelay"

rtnl, err := setupDummyInterface(tcIface)
if err != nil {
fmt.Fprintf(os.Stderr, "could not setup dummy interface: %v\n", err)
return
}
defer rtnl.Close()

devID, err := net.InterfaceByName(tcIface)
if err != nil {
fmt.Fprintf(os.Stderr, "could not get interface ID: %v\n", err)
return
}
defer func(devID uint32, rtnl *rtnetlink.Conn) {
if err := rtnl.Link.Delete(devID); err != nil {
fmt.Fprintf(os.Stderr, "could not delete interface: %v\n", err)
}
}(uint32(devID.Index), rtnl)

tcnl, err := tc.Open(&tc.Config{})
if err != nil {
fmt.Fprintf(os.Stderr, "could not open rtnetlink socket: %v\n", err)
return
}
defer func() {
if err := tcnl.Close(); err != nil {
fmt.Fprintf(os.Stderr, "could not close rtnetlink socket: %v\n", err)
}
}()

tcTime, err := core.Duration2TcTime(100 * time.Millisecond)
if err != nil {
fmt.Fprintf(os.Stderr, "could not convert duration to TC time: %v\n", err)
return
}
ticks := core.Time2Tick(tcTime)

qdisc := tc.Object{
tc.Msg{
Family: unix.AF_UNSPEC,
Ifindex: uint32(devID.Index),
Handle: core.BuildHandle(0x1, 0x0),
Parent: tc.HandleRoot,
Info: 0,
},
tc.Attribute{
Kind: "netem",
// tc qdisc add dev tcDev root netem delay 100ms
Netem: &tc.Netem{
Qopt: tc.NetemQopt{
Latency: ticks,
Limit: 1000,
},
},
},
}

if err := tcnl.Qdisc().Replace(&qdisc); err != nil {
fmt.Fprintf(os.Stderr, "could not assign qdisc netem to lo: %v\n", err)
return
}
defer func() {
if err := tcnl.Qdisc().Delete(&qdisc); err != nil {
fmt.Fprintf(os.Stderr, "could not delete netem qdisc of lo: %v\n", err)
return
}
}()
qdiscs, err := tcnl.Qdisc().Get()
if err != nil {
fmt.Fprintf(os.Stderr, "could not get all qdiscs: %v\n", err)
}

for _, qdisc := range qdiscs {
iface, err := net.InterfaceByIndex(int(qdisc.Ifindex))
if err != nil {
fmt.Fprintf(os.Stderr, "could not get interface from id %d: %v", qdisc.Ifindex, err)
return
}
fmt.Printf("%20s\t%s\n", iface.Name, qdisc.Kind)
}
}
Loading