blob: 418580ac48de2f34ebba6a88467dfc0125c11ad8 [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// Copyright 2015 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package netutil
16
17import (
18 "fmt"
19 "os/exec"
20)
21
22// DropPort drops all tcp packets that are received from the given port and sent to the given port.
23func DropPort(port int) error {
24 cmdStr := fmt.Sprintf("sudo iptables -A OUTPUT -p tcp --destination-port %d -j DROP", port)
25 if _, err := exec.Command("/bin/sh", "-c", cmdStr).Output(); err != nil {
26 return err
27 }
28 cmdStr = fmt.Sprintf("sudo iptables -A INPUT -p tcp --destination-port %d -j DROP", port)
29 _, err := exec.Command("/bin/sh", "-c", cmdStr).Output()
30 return err
31}
32
33// RecoverPort stops dropping tcp packets at given port.
34func RecoverPort(port int) error {
35 cmdStr := fmt.Sprintf("sudo iptables -D OUTPUT -p tcp --destination-port %d -j DROP", port)
36 if _, err := exec.Command("/bin/sh", "-c", cmdStr).Output(); err != nil {
37 return err
38 }
39 cmdStr = fmt.Sprintf("sudo iptables -D INPUT -p tcp --destination-port %d -j DROP", port)
40 _, err := exec.Command("/bin/sh", "-c", cmdStr).Output()
41 return err
42}
43
44// SetLatency adds latency in millisecond scale with random variations.
45func SetLatency(ms, rv int) error {
46 ifces, err := GetDefaultInterfaces()
47 if err != nil {
48 return err
49 }
50
51 if rv > ms {
52 rv = 1
53 }
54 for ifce := range ifces {
55 cmdStr := fmt.Sprintf("sudo tc qdisc add dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv)
56 _, err = exec.Command("/bin/sh", "-c", cmdStr).Output()
57 if err != nil {
58 // the rule has already been added. Overwrite it.
59 cmdStr = fmt.Sprintf("sudo tc qdisc change dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv)
60 _, err = exec.Command("/bin/sh", "-c", cmdStr).Output()
61 if err != nil {
62 return err
63 }
64 }
65 }
66 return nil
67}
68
69// RemoveLatency resets latency configurations.
70func RemoveLatency() error {
71 ifces, err := GetDefaultInterfaces()
72 if err != nil {
73 return err
74 }
75 for ifce := range ifces {
76 _, err = exec.Command("/bin/sh", "-c", fmt.Sprintf("sudo tc qdisc del dev %s root netem", ifce)).Output()
77 if err != nil {
78 return err
79 }
80 }
81 return nil
82}