~launchpad-pqm/launchpad/devel

13588.1.1 by Aaron Bentley
Add basic local-latency script.
1
#!/usr/bin/env python
13588.1.3 by Aaron Bentley
Allow specifying delay.
2
3
__metaclass__ = type
4
14612.2.6 by William Grant
utilities
5
import subprocess
13588.1.1 by Aaron Bentley
Add basic local-latency script.
6
import sys
7
13588.1.4 by Aaron Bentley
Extract common functionality to script_commands.
8
from script_commands import (
13588.1.8 by Aaron Bentley
Remove Command.
9
    helps,
10
    run_subcommand,
13588.1.4 by Aaron Bentley
Extract common functionality to script_commands.
11
    UserError,
12
    )
13588.1.1 by Aaron Bentley
Add basic local-latency script.
13
13588.1.3 by Aaron Bentley
Allow specifying delay.
14
13588.1.2 by Aaron Bentley
Port-specific version.
15
def tc(command):
13588.1.12 by Aaron Bentley
Update docs.
16
    """Run a tc command under sudo.
17
18
    :param tc: The remainder of the command (leaving out tc).
19
    """
13588.1.13 by Aaron Bentley
Update from review.
20
    subprocess.call('sudo tc ' + command, shell=True)
13588.1.2 by Aaron Bentley
Port-specific version.
21
13588.1.3 by Aaron Bentley
Allow specifying delay.
22
13588.1.7 by Aaron Bentley
Switch to command-from-function approach.
23
@helps(delay='Length of delay in miliseconds (each way).',
24
       port='Port to induce delay on.')
25
def start(delay=500, port=443):
13588.1.12 by Aaron Bentley
Update docs.
26
    """Add artificial latency to the lo interface on the specified port."""
13588.1.7 by Aaron Bentley
Switch to command-from-function approach.
27
    tc('qdisc add dev lo root handle 1: prio')
28
    tc('qdisc add dev lo parent 1:3 handle 30: netem delay %dms' % delay)
29
    tc('filter add dev lo protocol ip parent 1:0 prio 3 u32 match ip'
30
       ' dport %d 0xffff flowid 1:3' % port)
31
    tc('filter add dev lo protocol ip parent 1:0 prio 3 u32 match ip'
32
       ' sport %d 0xffff flowid 1:3' % port)
33
34
35
def stop():
13588.1.16 by Aaron Bentley
Updates from review.
36
    """Remove latency from the lo."""
13588.1.7 by Aaron Bentley
Switch to command-from-function approach.
37
    tc('qdisc del dev lo root')
38
39
13588.1.8 by Aaron Bentley
Remove Command.
40
subcommands = {
41
    'start': start,
42
    'stop': stop,
43
    }
13588.1.4 by Aaron Bentley
Extract common functionality to script_commands.
44
13588.1.1 by Aaron Bentley
Add basic local-latency script.
45
46
47
if __name__ == "__main__":
48
    try:
13588.1.8 by Aaron Bentley
Remove Command.
49
        run_subcommand(subcommands, sys.argv[1:])
13588.1.4 by Aaron Bentley
Extract common functionality to script_commands.
50
    except UserError as e:
13588.1.1 by Aaron Bentley
Add basic local-latency script.
51
        sys.stderr.write(str(e)+'\n')