Ejemplo n.º 1
0
    def test_reduce(self):
        from exceptions import LookupError, EnvironmentError

        le = LookupError(1, 2, "a")
        assert le.__reduce__() == (LookupError, (1, 2, "a"))
        le.xyz = (1, 2)
        assert le.__reduce__() == (LookupError, (1, 2, "a"), {"xyz": (1, 2)})
        ee = EnvironmentError(1, 2, "a")
        assert ee.__reduce__() == (EnvironmentError, (1, 2, "a"))
Ejemplo n.º 2
0
    def test_reduce(self):
        from exceptions import LookupError, EnvironmentError

        le = LookupError(1, 2, "a")
        assert le.__reduce__() == (LookupError, (1, 2, "a"))
        le.xyz = (1, 2)
        assert le.__reduce__() == (LookupError, (1, 2, "a"), {"xyz": (1, 2)})
        ee = EnvironmentError(1, 2, "a")
        assert ee.__reduce__() == (EnvironmentError, (1, 2, "a"))
Ejemplo n.º 3
0
 def test_environment_error(self):
     from exceptions import EnvironmentError
     ee = EnvironmentError(3, "x", "y")
     assert str(ee) == "[Errno 3] x: 'y'"
     assert str(EnvironmentError(3, "x")) == "[Errno 3] x"
     assert ee.errno == 3
     assert ee.strerror == "x"
     assert ee.filename == "y"
     assert EnvironmentError(3, "x").filename is None
Ejemplo n.º 4
0
    def __init__(self):
        credentialsFilename = "windowsazurecredentials.json"
        tmpName = os.path.join(os.getcwd(), credentialsFilename)
        if not os.path.exists(tmpName):
            if os.environ.has_key("USERPROFILE"):
                tmpName = os.path.join(os.environ["USERPROFILE"], 
                                       credentialsFilename)
            elif os.environ.has_key("HOME"):
                tmpName = os.path.join(os.environ["HOME"], 
                                       credentialsFilename)
        if not os.path.exists(tmpName):
            errMsg = "Cannot run Azure tests when the expected config file containing Azure credentials, '%s', does not exist!" % (tmpName)
            raise EnvironmentError(errMsg)

        with open(tmpName, "r") as f:
            self.ns = json.load(f)
Ejemplo n.º 5
0
    def __init__(self, interface):
        Screen.__init__(self)

        self.interface = interface
        self.ip = None
        self.measures = {
            'bytes': {
                'in': deque(maxlen=31), 'out': deque(maxlen=31), 'last_in': None, 'last_out': None
            },
            'packets': {
                'in': deque(maxlen=31), 'out': deque(maxlen=31), 'last_in': None, 'last_out': None
            },
            'errors': {
                'in': deque(maxlen=31), 'out': deque(maxlen=31), 'last_in': None, 'last_out': None
            },
            'dropped': {
                'in': deque(maxlen=31), 'out': deque(maxlen=31), 'last_in': None, 'last_out': None
            }
        }
        self.screen_config = [
            RendererConfig(UpDownRenderer(), 'bytes', 'Bytes', x_start=126, x_step=-4),
            RendererConfig(UpDownRenderer(), 'packets', 'Packets', x_start=126, x_step=-4),
            RendererConfig(UpDownRenderer(), 'errors', 'Errors', x_start=126, x_step=-4),
            RendererConfig(UpDownRenderer(), 'dropped', 'Dropped', x_start=126, x_step=-4)
        ]
        self.screen_index = 0

        interfaces = psutil.net_if_addrs()[self.interface]

        for interface in interfaces:

            if interface.family == 2:
                self.ip = interface.address
                break

        if self.ip is None:
            raise EnvironmentError()
Ejemplo n.º 6
0
def launch_namespace(cmd,
                     guest_ip_addr_str,
                     iface_number,
                     prefix_length=24,
                     host_ip_addr_str="",
                     cwd=None,
                     env=None):
    '''
  Set up and launch cmd in a new network namespace.

  Returns a pair:
   (raw socket bound to host veth interface,
    Popen object for communicating with guest namespace)

  This method uses functionality that requires CAP_NET_ADMIN capabilites. This
  means that the calling method should check that the python process was
  launched as admin/superuser.

  Parameters:
    - cmd: the string to launch, in a separate namespace
    - ip_addr_str: the ip address to assign to the namespace's interace.
                   Must be a string! not a IPAddr object
    - iface_number: unique integer for the namespace and host virtual interfaces.
  '''
    if system() != 'Linux':
        raise EnvironmentError(
            'network namespace functionality requires a Linux environment')

    uid = os.geteuid()
    if uid != 0:
        # user must have CAP_NET_ADMIN, which doesn't have to be su, but most often is
        raise EnvironmentError(
            "superuser privileges required to launch network namespace")

    host_device = "heth%s" % str(iface_number)
    guest_device = "geth%s" % str(iface_number)

    try:
        # Clean up previous network namespaces
        # (Delete the device if it already exists)
        with open(os.devnull, 'wb') as null:
            for dev in (host_device, guest_device):
                if subprocess.call(['ip', 'link', 'show', dev],
                                   stdout=null,
                                   stderr=null) == 0:
                    subprocess.check_call(['ip', 'link', 'del', dev])

        # create a veth pair and set the host end to be promiscuous
        subprocess.check_call([
            'ip', 'link', 'add', 'name', host_device, 'type', 'veth', 'peer',
            'name', guest_device
        ])
        guest_eth_addr = get_eth_address_for_interface(guest_device)
        log.debug("Guest ETH %s" % guest_eth_addr)
        host_eth_addr = get_eth_address_for_interface(host_device)
        log.debug("Host ETH %s" % host_eth_addr)

        subprocess.check_call(
            ['ip', 'link', 'set', host_device, 'promisc', 'on'])
        # Our end of the veth pair
        subprocess.check_call(['ip', 'link', 'set', host_device, 'up'])
        if host_ip_addr_str != "":
            # Set a host IP on the same subnet as the guest so that host sockets automatically get
            # bound to the correct virtual interface.
            subprocess.check_call([
                'ip', 'addr', 'add',
                "%s/%d" % (host_ip_addr_str, prefix_length), 'dev', host_device
            ])
    except subprocess.CalledProcessError:
        raise  # TODO raise a more informative exception

    # all else should have succeeded, so now we fork and unshare for the guest
    # TODO(cs): use popen_filtered here?
    guest = subprocess.Popen(["unshare", "-n", "--", "/bin/bash"],
                             stdin=subprocess.PIPE,
                             env=env,
                             cwd=cwd)

    # push down the guest device into the netns
    try:
        subprocess.check_call(
            ['ip', 'link', 'set', guest_device, 'netns',
             str(guest.pid)])
    except subprocess.CalledProcessError:
        raise  # TODO raise a more informative exception

    # Bring up the interface on the guest.
    guest.stdin.write("ip link set %s up\n" % guest_device)
    # Set the IP address of the virtual interface. Note that this has the nice
    # side effect that the host can open sockets to the IP address (since the
    # guest will begin responding to ARPs).
    guest.stdin.write("ip addr add %s/%d dev %s\n" %
                      (guest_ip_addr_str, prefix_length, guest_device))

    # Send the command.
    guest.stdin.write(cmd + "\n")

    return (guest, guest_eth_addr, host_device)