Esempio n. 1
0
    def test_stop_start_instance(self):
        key_name = data_utils.rand_name('testkey')
        pkey = self.create_key_pair(key_name)
        sec_group_name = self.create_standard_security_group()
        instance_id = self.run_instance(KeyName=key_name,
                                        ImageId=CONF.aws.image_id_ubuntu,
                                        SecurityGroups=[sec_group_name])

        ip_address = self.get_instance_ip(instance_id)
        ssh_client = ssh.Client(ip_address,
                                CONF.aws.image_user_ubuntu,
                                pkey=pkey)
        ssh_client.exec_command('last -x')

        self.client.stop_instances(InstanceIds=[instance_id])
        self.get_instance_waiter().wait_available(instance_id,
                                                  final_set=('stopped'))

        self.client.start_instances(InstanceIds=[instance_id])
        self.get_instance_waiter().wait_available(instance_id,
                                                  final_set=('running'))

        # Amazon can change auto-assigned public ip
        ip_address = self.get_instance_ip(instance_id)
        ssh_client = ssh.Client(ip_address,
                                CONF.aws.image_user_ubuntu,
                                pkey=pkey)
        data = ssh_client.exec_command('last -x')
        self.assertIn("shutdown", data)
Esempio n. 2
0
 def test_pkey_calls_paramiko_RSAKey(self, cs_mock, rsa_mock):
     cs_mock.return_value = mock.sentinel.csio
     pkey = 'mykey'
     ssh.Client('localhost', 'root', pkey=pkey)
     rsa_mock.assert_called_once_with(mock.sentinel.csio)
     cs_mock.assert_called_once_with('mykey')
     rsa_mock.reset_mock()
     cs_mock.reset_mock()
     pkey = mock.sentinel.pkey
     # Shouldn't call out to load a file from RSAKey, since
     # a sentinel isn't a basestring...
     ssh.Client('localhost', 'root', pkey=pkey)
     self.assertEqual(0, rsa_mock.call_count)
     self.assertEqual(0, cs_mock.call_count)
Esempio n. 3
0
    def get_remote_client(self, ip, username=None):
        """Get a SSH client to a remote server

        :param server_or_ip: a server object as returned by Tempest compute
            client or an IP address to connect to
        :param username: name of the Linux account on the remote server
        :return: a RemoteClient object
        """
        if username is None:
            username = CONF.validation.image_ssh_user
        password = CONF.validation.image_ssh_password
        linux_client = ssh.Client(ip, username, password)

        try:
            linux_client.test_connection_auth()
        except Exception as e:
            message = ('Initializing SSH connection to %(ip)s failed. '
                       'Error: %(error)s' % {
                           'ip': ip,
                           'error': e
                       })
            caller = misc_utils.find_test_caller()
            if caller:
                message = '(%s) %s' % (caller, message)
            LOG.exception(message)
            raise
        return linux_client
Esempio n. 4
0
def execute(cmd,
            action,
            flags='',
            params='',
            fail_ok=False,
            merge_stderr=False):
    """Executes specified command for the given action."""
    LOG.info("Executing CLI: '%s %s %s'", cmd, action, params)
    LOG.debug("using flags: '%s'", flags)

    ssh_timeout = 10
    ssh_channel_timeout = 10

    uri = CONF.identity.uri
    uri_object = urlparse.urlparse(uri)
    netloc_parts = uri_object.netloc.rsplit(':')
    ip_address = netloc_parts[0]

    username = CONF.nuage_sut.controller_user
    password = CONF.nuage_sut.controller_password

    ssh_client = ssh.Client(ip_address,
                            username,
                            password,
                            ssh_timeout,
                            channel_timeout=ssh_channel_timeout)

    cmd = ' '.join([os.path.join(cmd), flags, action, params])
    LOG.debug("running: '%s'" % cmd)

    response = ssh_client.exec_command(cmd)

    LOG.debug("Response: \n'%s'" % response)

    return response
Esempio n. 5
0
    def execute(cmd):
        """Executes specified command for the given action."""
        LOG.info("Executing: '%s" % cmd)

        ssh_timeout = 10
        ssh_channel_timeout = 10

        # TODO: derive from tempest.conf or nuage.conf
        uri = CONF.identity.uri

        uri_object = urlparse.urlparse(uri)
        netloc_parts = uri_object.netloc.rsplit(':')
        ip_address = netloc_parts[0]

        username = CONF.nuage_sut.controller_user
        password = CONF.nuage_sut.controller_password

        ssh_client = ssh.Client(ip_address,
                                username,
                                password,
                                ssh_timeout,
                                channel_timeout=ssh_channel_timeout)

        response = ssh_client.exec_command(cmd)
        LOG.debug("Response: \n'%s'" % response)

        return response
    def _test_vpnaas(self):
        # RIGHT
        right_server = self._create_server(network=self._right_network,
            create_floating_ip=False)
        right_ip = self._get_ip_on_subnet_for_port(
            right_server['port'], self._right_subnet['id'])

        # LEFT
        left_server = self._create_server()
        ssh_client = ssh.Client(left_server['fip']['floating_ip_address'],
                                CONF.validation.image_ssh_user,
                                pkey=self.keypair['private_key'],
                                ssh_key_type=CONF.validation.ssh_key_type)

        # check LEFT -> RIGHT connectivity via VPN
        self.check_remote_connectivity(ssh_client, right_ip,
                                       should_succeed=False)
        self._setup_vpn()
        self.check_remote_connectivity(ssh_client, right_ip)

        # Test VPN traffic and floating IP traffic don't interfere each other.
        if not self.inner_ipv6:
            # Assign a floating-ip and check connectivity.
            # This is NOT via VPN.
            fip = self.create_and_associate_floatingip(
                right_server['port']['id'])
            self.check_remote_connectivity(ssh_client,
                                           fip['floating_ip_address'])

            # check LEFT -> RIGHT connectivity via VPN again, to ensure
            # the above floating-ip doesn't interfere the traffic.
            self.check_remote_connectivity(ssh_client, right_ip)
Esempio n. 7
0
    def __init__(self, ip_address, username, password=None, pkey=None):
        ssh_timeout = CONF.validation.ssh_timeout
        connect_timeout = CONF.validation.connect_timeout

        self.ssh_client = ssh.Client(ip_address, username, password,
                                     ssh_timeout, pkey=pkey,
                                     channel_timeout=connect_timeout)
Esempio n. 8
0
    def test_exec_command(self):
        chan_mock, poll_mock, select_mock, client_mock = (
            self._set_mocks_for_select([[1, 0, 0]], True))

        chan_mock.recv_exit_status.return_value = 0
        chan_mock.recv.return_value = b''
        chan_mock.recv_stderr.return_value = b''

        client = ssh.Client('localhost', 'root', timeout=2)
        client.exec_command("test")

        chan_mock.fileno.assert_called_once_with()
        chan_mock.exec_command.assert_called_once_with("test")
        chan_mock.shutdown_write.assert_called_once_with()

        select_mock.assert_called_once_with()
        poll_mock.register.assert_called_once_with(chan_mock,
                                                   self.SELECT_POLLIN)
        poll_mock.poll.assert_called_once_with(10)
        chan_mock.recv_ready.assert_called_once_with()
        chan_mock.recv.assert_called_once_with(1024)
        chan_mock.recv_stderr_ready.assert_called_once_with()
        chan_mock.recv_stderr.assert_called_once_with(1024)
        chan_mock.recv_exit_status.assert_called_once_with()

        client_mock.close.assert_called_once_with()
    def test_compare_console_output(self):
        key_name = data_utils.rand_name('testkey')
        pkey = self.create_key_pair(key_name)
        sec_group_name = self.create_standard_security_group()
        instance_id = self.run_instance(KeyName=key_name,
                                        SecurityGroups=[sec_group_name])

        data_to_check = data_utils.rand_uuid()
        ip_address = self.get_instance_ip(instance_id)
        ssh_client = ssh.Client(ip_address, CONF.aws.image_user, pkey=pkey)
        cmd = 'sudo sh -c "echo \\"%s\\" >/dev/console"' % data_to_check
        ssh_client.exec_command(cmd)

        waiter = base.EC2Waiter(self.client.get_console_output)
        waiter.wait_no_exception(InstanceId=instance_id)

        def _compare_console_output():
            data = self.client.get_console_output(InstanceId=instance_id)
            self.assertEqual(instance_id, data['InstanceId'])
            self.assertIsNotNone(data['Timestamp'])
            self.assertIn('Output', data)
            self.assertIn(data_to_check, data['Output'])

        waiter = base.EC2Waiter(_compare_console_output)
        waiter.wait_no_exception()
Esempio n. 10
0
    def test_exec_command_no_select(self):
        gsc_mock = self.patch('tempest.lib.common.ssh.Client.'
                              '_get_ssh_connection')
        csp_mock = self.patch('tempest.lib.common.ssh.Client._can_system_poll')
        csp_mock.return_value = False

        select_mock = self.patch('select.poll', create=True)
        client_mock = mock.MagicMock()
        tran_mock = mock.MagicMock()
        chan_mock = mock.MagicMock()

        # Test for proper reading of STDOUT and STDERROR

        gsc_mock.return_value = client_mock
        client_mock.get_transport.return_value = tran_mock
        tran_mock.open_session().__enter__.return_value = chan_mock
        chan_mock.recv_exit_status.return_value = 0

        std_out_mock = mock.MagicMock(StringIO)
        std_err_mock = mock.MagicMock(StringIO)
        chan_mock.makefile.return_value = std_out_mock
        chan_mock.makefile_stderr.return_value = std_err_mock

        client = ssh.Client('localhost', 'root', timeout=2)
        client.exec_command("test")

        chan_mock.makefile.assert_called_once_with('rb', 1024)
        chan_mock.makefile_stderr.assert_called_once_with('rb', 1024)
        std_out_mock.read.assert_called_once_with()
        std_err_mock.read.assert_called_once_with()
        self.assertFalse(select_mock.called)
    def test_metadata(self):
        key_name = data_utils.rand_name('testkey')
        self.client.import_key_pair(KeyName=key_name,
                                    PublicKeyMaterial=PUBLIC_KEY_MATERIAL)
        self.addResourceCleanUp(self.client.delete_key_pair, KeyName=key_name)

        sec_group_name = self.create_standard_security_group()
        user_data = six.text_type(data_utils.rand_uuid()) + six.unichr(1071)
        instance_id = self.run_instance(KeyName=key_name, UserData=user_data,
                                        SecurityGroups=[sec_group_name])

        data = self.client.describe_instance_attribute(
            InstanceId=instance_id, Attribute='userData')
        self.assertEqual(
            data['UserData']['Value'],
            base64.b64encode(user_data.encode("utf-8")).decode("utf-8"))

        ip_address = self.get_instance_ip(instance_id)

        ssh_client = ssh.Client(ip_address, CONF.aws.image_user,
                                pkey=PRIVATE_KEY_MATERIAL)

        url = 'http://169.254.169.254'
        data = ssh_client.exec_command('curl %s/latest/user-data' % url)
        if isinstance(data, six.binary_type):
            data = data.decode("utf-8")
        self.assertEqual(user_data, data)

        data = ssh_client.exec_command('curl %s/latest/meta-data/ami-id' % url)
        self.assertEqual(CONF.aws.image_id, data)

        data = ssh_client.exec_command(
            'curl %s/latest/meta-data/public-keys/0/openssh-key' % url)
        # compare only keys. without 'sha-rsa' and owner
        self.assertEqual(PUBLIC_KEY_MATERIAL.split()[1], data.split()[1])
Esempio n. 12
0
    def _test_instances(self, subnet_size):
        cidr = netaddr.IPNetwork('10.20.0.0/8')
        cidr.prefixlen = subnet_size
        vpc_id, subnet_id = self.create_vpc_and_subnet(str(cidr))
        gw_id = self.create_and_attach_internet_gateway(vpc_id)
        self.prepare_vpc_default_security_group(vpc_id)
        self.prepare_route(vpc_id, gw_id)

        key_name = data_utils.rand_name('testkey')
        pkey = self.create_key_pair(key_name)

        first_ip = str(netaddr.IPAddress(cidr.first + 4))
        last_ip = str(netaddr.IPAddress(cidr.last - 1))
        instance_id1 = self.run_instance(KeyName=key_name,
                                         SubnetId=subnet_id,
                                         PrivateIpAddress=first_ip)
        instance_id2 = self.run_instance(KeyName=key_name,
                                         SubnetId=subnet_id,
                                         PrivateIpAddress=last_ip)
        instance = self.get_instance(instance_id1)
        self.assertEqual(first_ip, instance['PrivateIpAddress'])
        instance = self.get_instance(instance_id2)
        self.assertEqual(last_ip, instance['PrivateIpAddress'])

        ip_address = self.get_instance_ip(instance_id1)
        ssh_client = ssh.Client(ip_address, CONF.aws.image_user, pkey=pkey)

        waiter = base.EC2Waiter(ssh_client.exec_command)
        waiter.wait_no_exception('ping %s -c 1' % last_ip)
Esempio n. 13
0
    def test_get_ssh_connection(self):
        c_mock, aa_mock, client_mock = self._set_ssh_connection_mocks()
        s_mock = self.patch('time.sleep')

        c_mock.return_value = client_mock
        aa_mock.return_value = mock.sentinel.aa

        # Test normal case for successful connection on first try
        client = ssh.Client('localhost', 'root', timeout=2)
        client._get_ssh_connection(sleep=1)

        aa_mock.assert_called_once_with()
        client_mock.set_missing_host_key_policy.assert_called_once_with(
            mock.sentinel.aa)
        expected_connect = [
            mock.call('localhost',
                      port=22,
                      username='******',
                      pkey=None,
                      key_filename=None,
                      look_for_keys=False,
                      timeout=10.0,
                      password=None,
                      sock=None)
        ]
        self.assertEqual(expected_connect, client_mock.connect.mock_calls)
        self.assertEqual(0, s_mock.call_count)
Esempio n. 14
0
    def test_reboot_instance(self):
        key_name = data_utils.rand_name('testkey')
        pkey = self.create_key_pair(key_name)
        sec_group_name = self.create_standard_security_group()
        instance_id = self.run_instance(KeyName=key_name,
                                        ImageId=CONF.aws.image_id_ubuntu,
                                        SecurityGroups=[sec_group_name])
        ip_address = self.get_instance_ip(instance_id)

        ssh_client = ssh.Client(ip_address,
                                CONF.aws.image_user_ubuntu,
                                pkey=pkey)
        last_lines = ssh_client.exec_command('last -x').split('\n')

        self.client.reboot_instances(InstanceIds=[instance_id])

        def _last_state():
            current = ssh_client.exec_command('last -x').split('\n')
            if len(current) > len(last_lines):
                return
            raise Exception()

        waiter = base.EC2Waiter(_last_state)
        waiter.wait_no_exception()

        data = ssh_client.exec_command('last -x')
        self.assertIn("shutdown", data)
Esempio n. 15
0
    def test_vpnaas(self):
        # RIGHT
        right_server = self._create_server(network=self._right_network,
                                           create_floating_ip=False)

        # LEFT
        left_server = self._create_server()
        ssh_client = ssh.Client(left_server['fip']['floating_ip_address'],
                                CONF.validation.image_ssh_user,
                                pkey=self.keypair['private_key'])

        # check LEFT -> RIGHT connectivity via VPN
        self.check_remote_connectivity(
            ssh_client,
            right_server['port']['fixed_ips'][0]['ip_address'],
            should_succeed=False)
        self._setup_vpn()
        self.check_remote_connectivity(
            ssh_client, right_server['port']['fixed_ips'][0]['ip_address'])

        # Assign a floating-ip and check connectivity.
        # This is NOT via VPN.
        fip = self.create_and_associate_floatingip(right_server['port']['id'])
        self.check_remote_connectivity(ssh_client, fip['floating_ip_address'])

        # check LEFT -> RIGHT connectivity via VPN again, to ensure
        # the above floating-ip doesn't interfere the traffic.
        self.check_remote_connectivity(
            ssh_client, right_server['port']['fixed_ips'][0]['ip_address'])
Esempio n. 16
0
    def __init__(self, ip_address, username, password=None, pkey=None,
                 server=None, servers_client=None, ssh_timeout=300,
                 connect_timeout=60, console_output_enabled=True,
                 ssh_shell_prologue="set -eu -o pipefail; PATH=$PATH:/sbin;",
                 ping_count=1, ping_size=56, ssh_key_type='rsa'):
        """Executes commands in a VM over ssh

        :param ip_address: IP address to ssh to
        :param username: Ssh username
        :param password: Ssh password
        :param pkey: Ssh public key
        :param server: Server dict, used for debugging purposes
        :param servers_client: Servers client, used for debugging purposes
        :param ssh_timeout: Timeout in seconds to wait for the ssh banner
        :param connect_timeout: Timeout in seconds to wait for TCP connection
        :param console_output_enabled: Support serial console output?
        :param ssh_shell_prologue: Shell fragments to use before command
        :param ping_count: Number of ping packets
        :param ping_size: Packet size for ping packets
        :param ssh_key_type: ssh key type (rsa, ecdsa)
        """
        self.server = server
        self.servers_client = servers_client
        self.ip_address = ip_address
        self.console_output_enabled = console_output_enabled
        self.ssh_shell_prologue = ssh_shell_prologue
        self.ping_count = ping_count
        self.ping_size = ping_size
        self.ssh_key_type = ssh_key_type

        self.ssh_client = ssh.Client(ip_address, username, password,
                                     ssh_timeout, pkey=pkey,
                                     channel_timeout=connect_timeout,
                                     ssh_key_type=ssh_key_type)
Esempio n. 17
0
    def __init__(self,
                 ip_address,
                 username,
                 password=None,
                 pkey=None,
                 server=None,
                 servers_client=None):
        """Executes commands in a VM over ssh

        :param ip_address: IP address to ssh to
        :param username: ssh username
        :param password: ssh password (optional)
        :param pkey: ssh public key (optional)
        :param server: server dict, used for debugging purposes
        :param servers_client: servers client, used for debugging purposes
        """
        self.server = server
        self.servers_client = servers_client
        self.log_console = CONF.compute_feature_enabled.console_output
        kwargs = {}

        try:
            kwargs['ssh_key_type'] = CONF.validation.ssh_key_type
        except Exception:
            # Not all versions of tempest support the
            # "validation.ssh_key_type" config option
            pass

        self.ssh_client = ssh.Client(ip_address,
                                     username,
                                     password,
                                     pkey=pkey,
                                     **kwargs)
Esempio n. 18
0
    def _create_server_with_port_and_subport(self, vlan_network, vlan_tag):
        parent_port = self.create_port(
            self.network,
            security_groups=[self.secgroup['security_group']['id']])
        port_for_subport = self.create_port(
            vlan_network,
            security_groups=[self.secgroup['security_group']['id']],
            mac_address=parent_port['mac_address'])
        subport = {
            'port_id': port_for_subport['id'],
            'segmentation_type': 'vlan',
            'segmentation_id': vlan_tag
        }
        trunk = self.client.create_trunk(parent_port['id'],
                                         subports=[subport])['trunk']

        server, fip = self._create_server_with_fip(parent_port['id'])
        self.addCleanup(self._detach_and_delete_trunk, server, trunk)

        server_ssh_client = ssh.Client(fip['floating_ip_address'],
                                       CONF.validation.image_ssh_user,
                                       pkey=self.keypair['private_key'])

        return {
            'server': server,
            'fip': fip,
            'ssh_client': server_ssh_client,
            'subport': port_for_subport,
        }
Esempio n. 19
0
    def __init__(self,
                 ip_address,
                 username,
                 password=None,
                 pkey=None,
                 server=None,
                 servers_client=None):
        """Executes commands in a VM over ssh

        :param ip_address: IP address to ssh to
        :param username: ssh username
        :param password: ssh password (optional)
        :param pkey: ssh public key (optional)
        :param server: server dict, used for debugging purposes
        :param servers_client: servers client, used for debugging purposes
        """
        self.server = server
        self.servers_client = servers_client
        ssh_timeout = CONF.validation.ssh_timeout
        connect_timeout = CONF.validation.connect_timeout
        self.log_console = CONF.compute_feature_enabled.console_output

        self.ssh_client = ssh.Client(ip_address,
                                     username,
                                     password,
                                     ssh_timeout,
                                     pkey=pkey,
                                     channel_timeout=connect_timeout)
Esempio n. 20
0
    def test_get_ssh_connection_over_ssh(self):
        c_mock, aa_mock, client_mock = self._set_ssh_connection_mocks()
        proxy_client_mock = mock.MagicMock()
        proxy_client_mock.connect.return_value = True
        s_mock = self.patch('time.sleep')

        c_mock.side_effect = [client_mock, proxy_client_mock]
        aa_mock.return_value = mock.sentinel.aa

        proxy_client = ssh.Client('proxy-host', 'proxy-user', timeout=2)
        client = ssh.Client('localhost',
                            'root',
                            timeout=2,
                            proxy_client=proxy_client)
        client._get_ssh_connection(sleep=1)

        aa_mock.assert_has_calls([mock.call(), mock.call()])
        proxy_client_mock.set_missing_host_key_policy.assert_called_once_with(
            mock.sentinel.aa)
        proxy_expected_connect = [
            mock.call('proxy-host',
                      port=22,
                      username='******',
                      pkey=None,
                      key_filename=None,
                      look_for_keys=False,
                      timeout=10.0,
                      password=None,
                      sock=None)
        ]
        self.assertEqual(proxy_expected_connect,
                         proxy_client_mock.connect.mock_calls)
        client_mock.set_missing_host_key_policy.assert_called_once_with(
            mock.sentinel.aa)
        expected_connect = [
            mock.call('localhost',
                      port=22,
                      username='******',
                      pkey=None,
                      key_filename=None,
                      look_for_keys=False,
                      timeout=10.0,
                      password=None,
                      sock=proxy_client_mock.get_transport().open_session())
        ]
        self.assertEqual(expected_connect, client_mock.connect.mock_calls)
        self.assertEqual(0, s_mock.call_count)
Esempio n. 21
0
 def check_connectivity(self, host, ssh_user, ssh_key, servers=None):
     ssh_client = ssh.Client(host, ssh_user, pkey=ssh_key)
     try:
         ssh_client.test_connection_auth()
     except lib_exc.SSHTimeout as ssh_e:
         LOG.debug(ssh_e)
         self._log_console_output(servers)
         raise
Esempio n. 22
0
def do_ssh(command, host, ssh_user, ssh_key=None):
    ssh_client = ssh.Client(host, ssh_user, key_filename=ssh_key)
    try:
        return ssh_client.exec_command(command)
    except exceptions.SSHExecCommandFailed:
        LOG.error('do_ssh raise exception. command:%s, host:%s.'
                  % (command, host))
        return None
Esempio n. 23
0
    def test_get_ssh_connection_two_attemps(self, sleep_mock):
        c_mock, aa_mock, client_mock = self._set_ssh_connection_mocks()

        c_mock.return_value = client_mock
        client_mock.connect.side_effect = [socket.error, mock.MagicMock()]

        client = ssh.Client('localhost', 'root', timeout=1)
        client._get_ssh_connection(sleep=1)
        # We slept 2 seconds: because sleep is "1" and backoff is "1" too
        sleep_mock.assert_called_once_with(2)
        self.assertEqual(2, client_mock.connect.call_count)
Esempio n. 24
0
    def test_exec_good_command_output(self):
        chan_mock, poll_mock, _ = self._set_mocks_for_select([1, 0, 0])
        closed_prop = mock.PropertyMock(return_value=True)
        type(chan_mock).closed = closed_prop

        chan_mock.recv_exit_status.return_value = 0
        chan_mock.recv.side_effect = [self._utf8_bytes[0:1],
                                      self._utf8_bytes[1:], b'R', b'']
        chan_mock.recv_stderr.return_value = b''

        client = ssh.Client('localhost', 'root', timeout=2)
        out_data = client.exec_command("test")
        self.assertEqual(self._utf8_string + 'R', out_data)
Esempio n. 25
0
    def test_exec_bad_command_output(self):
        chan_mock, poll_mock, _ = self._set_mocks_for_select([1, 0, 0])
        closed_prop = mock.PropertyMock(return_value=True)
        type(chan_mock).closed = closed_prop

        chan_mock.recv_exit_status.return_value = 1
        chan_mock.recv.return_value = b''
        chan_mock.recv_stderr.side_effect = [b'R', self._utf8_bytes[0:1],
                                             self._utf8_bytes[1:], b'']

        client = ssh.Client('localhost', 'root', timeout=2)
        exc = self.assertRaises(exceptions.SSHExecCommandFailed,
                                client.exec_command, "test")
        self.assertIn('R' + self._utf8_string, six.text_type(exc))
Esempio n. 26
0
    def test_timeout_in_exec_command(self):
        chan_mock, poll_mock, _ = self._set_mocks_for_select([0, 0, 0], True)

        # Test for a timeout condition immediately raised
        client = ssh.Client('localhost', 'root', timeout=2)
        with testtools.ExpectedException(exceptions.TimeoutException):
            client.exec_command("test")

        chan_mock.fileno.assert_called_once_with()
        chan_mock.exec_command.assert_called_once_with("test")
        chan_mock.shutdown_write.assert_called_once_with()

        poll_mock.register.assert_called_once_with(chan_mock,
                                                   self.SELECT_POLLIN)
        poll_mock.poll.assert_called_once_with(10)
Esempio n. 27
0
 def _run_command_on_node(self, node_ip, command):
     host_ip = node_ip
     if self.proxy:
         host_ip = self.proxy
         command = ("echo '{pkey}' > {filename} && chmod 600 {filename} && "
                    "ssh -o StrictHostKeyChecking=no {ip} -i {filename} "
                    "'{cmd}' && rm {filename}".format(
                        pkey=self.private_key,
                        filename='scenario.pem',
                        ip=node_ip,
                        cmd=command))
     ssh_session = connection.Client(host_ip,
                                     self.testcase['ssh_username'],
                                     pkey=self.private_key)
     return ssh_session.exec_command(command)
Esempio n. 28
0
    def test_qos(self):
        """This is a basic test that check that a QoS policy with

           a bandwidth limit rule is applied correctly by sending
           a file from the instance to the test node.
           Then calculating the bandwidth every ~1 sec by the number of bits
           received / elapsed time.
        """

        NC_PORT = 1234

        self.setup_network_and_server()
        self.check_connectivity(self.fip['floating_ip_address'],
                                CONF.validation.image_ssh_user,
                                self.keypair['private_key'])
        rulesets = [{'protocol': 'tcp',
                     'direction': 'ingress',
                     'port_range_min': NC_PORT,
                     'port_range_max': NC_PORT,
                     'remote_ip_prefix': '0.0.0.0/0'}]
        self.create_secgroup_rules(rulesets,
                                   self.security_groups[-1]['id'])

        ssh_client = ssh.Client(self.fip['floating_ip_address'],
                                CONF.validation.image_ssh_user,
                                pkey=self.keypair['private_key'])
        policy = self.admin_manager.network_client.create_qos_policy(
                                        name='test-policy',
                                        description='test-qos-policy',
                                        shared=True)
        policy_id = policy['policy']['id']
        self.admin_manager.network_client.create_bandwidth_limit_rule(
            policy_id, max_kbps=constants.LIMIT_KILO_BITS_PER_SECOND,
            max_burst_kbps=constants.LIMIT_KILO_BITS_PER_SECOND)
        port = self.client.list_ports(network_id=self.network['id'],
                                      device_id=self.server[
                                      'server']['id'])['ports'][0]
        self.admin_manager.network_client.update_port(port['id'],
                                                      qos_policy_id=policy_id)
        self._create_file_for_bw_tests(ssh_client)
        utils.wait_until_true(lambda: self._check_bw(
            ssh_client,
            self.fip['floating_ip_address'],
            port=NC_PORT),
            timeout=120,
            sleep=1)
Esempio n. 29
0
 def check_connectivity(self,
                        ip_address,
                        username=None,
                        private_key=None,
                        should_connect=True,
                        check_icmp=True,
                        check_ssh=True,
                        check_reverse_icmp_ip=None,
                        should_reverse_connect=True):
     if should_connect:
         msg = "Timed out waiting for %s to become reachable" % ip_address
     else:
         msg = "ip address %s is reachable" % ip_address
     if check_icmp:
         ok = self.ping_ip_address(ip_address,
                                   should_succeed=should_connect)
         self.assertTrue(ok, msg=msg)
     if check_ssh:
         connect_timeout = CONF.validation.connect_timeout
         kwargs = {}
         if not should_connect:
             # Use a shorter timeout for negative case
             kwargs['timeout'] = 1
         try:
             client = ssh.Client(ip_address,
                                 username,
                                 pkey=private_key,
                                 channel_timeout=connect_timeout,
                                 **kwargs)
             client.test_connection_auth()
             self.assertTrue(should_connect, "Unexpectedly reachable")
             if check_reverse_icmp_ip:
                 cmd = 'ping -c1 -w1 %s' % check_reverse_icmp_ip
                 try:
                     client.exec_command(cmd)
                     self.assertTrue(should_reverse_connect,
                                     "Unexpectedly reachable (reverse)")
                 except lib_exc.SSHExecCommandFailed:
                     if should_reverse_connect:
                         raise
         except lib_exc.SSHTimeout:
             if should_connect:
                 raise
Esempio n. 30
0
    def test_bgp(self):
        # RIGHT
        right_server = self._create_server(network=self._right_network,
                                           create_floating_ip=False)

        # LEFT
        left_server = self._create_server()
        ssh_client = ssh.Client(left_server['fip']['floating_ip_address'],
                                CONF.validation.image_ssh_user,
                                pkey=self.keypair['private_key'],
                                ssh_key_type=CONF.validation.ssh_key_type)

        # check LEFT -> RIGHT connectivity via BGP advertised routes
        self.check_remote_connectivity(
            ssh_client,
            right_server['port']['fixed_ips'][0]['ip_address'],
            should_succeed=False)
        self._setup_bgp()
        self.check_remote_connectivity(
            ssh_client, right_server['port']['fixed_ips'][0]['ip_address'])