/chromium-webcl/src/media/tools/constrained_network_server/cn.py

https://bitbucket.org/peixuan/chromium_r197479_base · Python · 123 lines · 72 code · 24 blank · 27 comment · 10 complexity · 76d7c8dc0399ff7949cc551a0d7b577a MD5 · raw file

  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """A script for configuring constraint networks.
  6. Sets up a constrained network configuration on a specific port. Traffic on this
  7. port will be redirected to another local server port.
  8. The configuration includes bandwidth, latency, and packet loss.
  9. """
  10. import collections
  11. import logging
  12. import optparse
  13. import traffic_control
  14. # Default logging is ERROR. Use --verbose to enable DEBUG logging.
  15. _DEFAULT_LOG_LEVEL = logging.ERROR
  16. Dispatcher = collections.namedtuple('Dispatcher', ['dispatch', 'requires_ports',
  17. 'desc'])
  18. # Map of command names to traffic_control functions.
  19. COMMANDS = {
  20. # Adds a new constrained network configuration.
  21. 'add': Dispatcher(traffic_control.CreateConstrainedPort,
  22. requires_ports=True, desc='Add a new constrained port.'),
  23. # Deletes an existing constrained network configuration.
  24. 'del': Dispatcher(traffic_control.DeleteConstrainedPort,
  25. requires_ports=True, desc='Delete a constrained port.'),
  26. # Deletes all constrained network configurations.
  27. 'teardown': Dispatcher(traffic_control.TearDown,
  28. requires_ports=False,
  29. desc='Teardown all constrained ports.')
  30. }
  31. def _ParseArgs():
  32. """Define and parse command-line arguments.
  33. Returns:
  34. tuple as (command, configuration):
  35. command: one of the possible commands to setup, delete or teardown the
  36. constrained network.
  37. configuration: a map of constrained network properties to their values.
  38. """
  39. parser = optparse.OptionParser()
  40. indent_first = parser.formatter.indent_increment
  41. opt_width = parser.formatter.help_position - indent_first
  42. cmd_usage = []
  43. for s in COMMANDS:
  44. cmd_usage.append('%*s%-*s%s' %
  45. (indent_first, '', opt_width, s, COMMANDS[s].desc))
  46. parser.usage = ('usage: %%prog {%s} [options]\n\n%s' %
  47. ('|'.join(COMMANDS.keys()), '\n'.join(cmd_usage)))
  48. parser.add_option('--port', type='int',
  49. help='The port to apply traffic control constraints to.')
  50. parser.add_option('--server-port', type='int',
  51. help='Port to forward traffic on --port to.')
  52. parser.add_option('--bandwidth', type='int',
  53. help='Bandwidth of the network in kbit/s.')
  54. parser.add_option('--latency', type='int',
  55. help=('Latency (delay) added to each outgoing packet in '
  56. 'ms.'))
  57. parser.add_option('--loss', type='int',
  58. help='Packet-loss percentage on outgoing packets. ')
  59. parser.add_option('--interface', type='string',
  60. help=('Interface to setup constraints on. Use "lo" for a '
  61. 'local client.'))
  62. parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
  63. default=False, help='Turn on verbose output.')
  64. options, args = parser.parse_args()
  65. _SetLogger(options.verbose)
  66. # Check a valid command was entered
  67. if not args or args[0].lower() not in COMMANDS:
  68. parser.error('Please specify a command {%s}.' % '|'.join(COMMANDS.keys()))
  69. user_cmd = args[0].lower()
  70. # Check if required options are available
  71. if COMMANDS[user_cmd].requires_ports:
  72. if not (options.port and options.server_port):
  73. parser.error('Please provide port and server-port values.')
  74. config = {
  75. 'port': options.port,
  76. 'server_port': options.server_port,
  77. 'interface': options.interface,
  78. 'latency': options.latency,
  79. 'bandwidth': options.bandwidth,
  80. 'loss': options.loss
  81. }
  82. return user_cmd, config
  83. def _SetLogger(verbose):
  84. log_level = _DEFAULT_LOG_LEVEL
  85. if verbose:
  86. log_level = logging.DEBUG
  87. logging.basicConfig(level=log_level, format='%(message)s')
  88. def Main():
  89. """Get the command and configuration of the network to set up."""
  90. user_cmd, config = _ParseArgs()
  91. try:
  92. COMMANDS[user_cmd].dispatch(config)
  93. except traffic_control.TrafficControlError as e:
  94. logging.error('Error: %s\n\nOutput: %s', e.msg, e.error)
  95. if __name__ == '__main__':
  96. Main()