qa_iptables.py 3.57 KB
Newer Older
1 2 3 4
#!/usr/bin/python -u
#

# Copyright (C) 2013 Google Inc.
5
# All rights reserved.
6
#
7 8 9
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
10
#
11 12
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
13
#
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44


"""Manipulates nodes using `iptables` to simulate non-standard network
conditions.

"""

import uuid

from qa_utils import AssertCommand

# String used as a comment for produced `iptables` results
IPTABLES_COMMENT_MARKER = "ganeti_qa_script"


class RulesContext(object):
Niklas Hambuechen's avatar
Niklas Hambuechen committed
45
  def __init__(self):
46 47 48
    self._nodes = set()

  def __enter__(self):
Niklas Hambuechen's avatar
Niklas Hambuechen committed
49
    self.marker = IPTABLES_COMMENT_MARKER + "_" + str(uuid.uuid4())
50 51 52
    return Rules(self)

  def __exit__(self, ext_type, exc_val, exc_tb):
Niklas Hambuechen's avatar
Niklas Hambuechen committed
53
    CleanRules(self._nodes, self.marker)
54

Niklas Hambuechen's avatar
Niklas Hambuechen committed
55
  def AddNode(self, node):
56 57 58 59 60 61 62 63 64 65 66 67
    self._nodes.add(node)


class Rules(object):
  """Allows to introduce iptable rules and dispose them at the end of a block.

  Don't instantiate this class directly. Use `with RulesContext() as r` instead.
  """

  def __init__(self, ctx=None):
    self._ctx = ctx
    if self._ctx is not None:
Niklas Hambuechen's avatar
Niklas Hambuechen committed
68
      self.marker = self._ctx.marker
69
    else:
Niklas Hambuechen's avatar
Niklas Hambuechen committed
70
      self.marker = IPTABLES_COMMENT_MARKER
71

Niklas Hambuechen's avatar
Niklas Hambuechen committed
72
  def AddNode(self, node):
73
    if self._ctx is not None:
Niklas Hambuechen's avatar
Niklas Hambuechen committed
74
      self._ctx.AddNode(node)
75 76 77 78 79 80 81

  def AppendRule(self, node, chain, rule, table="filter"):
    """Appends an `iptables` rule to a given node
    """
    AssertCommand(["iptables", "-t", table, "-A", chain] +
                  rule +
                  ["-m", "comment",
Niklas Hambuechen's avatar
Niklas Hambuechen committed
82
                   "--comment", self.marker],
83
                  node=node)
Niklas Hambuechen's avatar
Niklas Hambuechen committed
84
    self.AddNode(node)
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

  def RedirectPort(self, node, host, port, new_port):
    """Adds a rule to a master node that makes a destination host+port visible
    under a different port number.

    """
    self.AppendRule(node, "OUTPUT",
                    ["--protocol", "tcp",
                     "--destination", host, "--dport", str(port),
                     "--jump", "DNAT",
                     "--to-destination", ":" + str(new_port)],
                    table="nat")


GLOBAL_RULES = Rules()


def CleanRules(nodes, marker=IPTABLES_COMMENT_MARKER):
  """Removes all QA `iptables` rules matching a given marker from a given node.

  If no marker is given, the global default is used, which clean all custom
  markers.
  """
  if not hasattr(nodes, '__iter__'):
    nodes = [nodes]
  for node in nodes:
    AssertCommand(("iptables-save | grep -v '%s' | iptables-restore" %
                    (marker, )),
                  node=node)