github.com/pingcap/chaos@v0.0.0-20190710112158-c86faf4b3719/pkg/util/net/iptables.go (about)

     1  package net
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/pingcap/chaos/pkg/util/ssh"
    10  )
    11  
    12  // IPTables implements Net interface to simulate the network.
    13  type IPTables struct {
    14  	Net
    15  }
    16  
    17  // Drop drops traffic from node.
    18  func (IPTables) Drop(ctx context.Context, node string, srcNode string) error {
    19  	return ssh.Exec(ctx, node, "iptables", "-A", "INPUT", "-s", HostIP(srcNode), "-j", "DROP", "-w")
    20  }
    21  
    22  // Heal ends all traffic drops and restores network to fast operations.
    23  func (IPTables) Heal(ctx context.Context, node string) error {
    24  	if err := ssh.Exec(ctx, node, "iptables", "-F", "-w"); err != nil {
    25  		return err
    26  	}
    27  	return ssh.Exec(ctx, node, "iptables", "-X", "-w")
    28  }
    29  
    30  // Slow delays the network packets with opetions.
    31  func (IPTables) Slow(ctx context.Context, node string, opts SlowOptions) error {
    32  	mean := fmt.Sprintf("%dms", opts.Mean.Nanoseconds()/int64(time.Millisecond))
    33  	variance := fmt.Sprintf("%dms", opts.Variance.Nanoseconds()/int64(time.Millisecond))
    34  	return ssh.Exec(ctx, node, "/sbin/tc", "qdisc", "add", "dev", "eth0", "root", "netem", "delay",
    35  		mean, variance, "distribution", opts.Distribution)
    36  }
    37  
    38  // Flaky introduces randomized packet loss.
    39  func (IPTables) Flaky(ctx context.Context, node string) error {
    40  	return ssh.Exec(ctx, node, "/sbin/tc", "qdisc", "add", "dev", "eth0", "root", "netem", "loss",
    41  		"20%", "75%")
    42  }
    43  
    44  // Fast removes packet loss and delays.
    45  func (IPTables) Fast(ctx context.Context, node string) error {
    46  	output, err := ssh.CombinedOutput(ctx, node, "/sbin/tc", "qdisc", "del", "dev", "eth0", "root")
    47  	if err != nil && strings.Contains(string(output), "RTNETLINK answers: No such file or directory") {
    48  		err = nil
    49  	}
    50  	return err
    51  }