Beispiel #1
0
 def setUp(self):
     super(LvsQueryTestCase, self).setUp()
     self.listener_id_v4 = uuidutils.generate_uuid()
     self.pool_id_v4 = uuidutils.generate_uuid()
     self.member_id1_v4 = uuidutils.generate_uuid()
     self.member_id2_v4 = uuidutils.generate_uuid()
     self.listener_id_v6 = uuidutils.generate_uuid()
     self.pool_id_v6 = uuidutils.generate_uuid()
     self.member_id1_v6 = uuidutils.generate_uuid()
     self.member_id2_v6 = uuidutils.generate_uuid()
     cfg_content_v4 = CFG_FILE_TEMPLATE_v4 % {
         'listener_id': self.listener_id_v4,
         'ns_name': constants.AMPHORA_NAMESPACE,
         'pool_id': self.pool_id_v4,
         'member_id1': self.member_id1_v4,
         'member_id2': self.member_id2_v4
     }
     cfg_content_v6 = CFG_FILE_TEMPLATE_v6 % {
         'listener_id': self.listener_id_v6,
         'ns_name': constants.AMPHORA_NAMESPACE,
         'pool_id': self.pool_id_v6,
         'member_id1': self.member_id1_v6,
         'member_id2': self.member_id2_v6
     }
     self.useFixture(
         test_utils.OpenFixture(
             util.keepalived_lvs_cfg_path(self.listener_id_v4),
             cfg_content_v4))
     self.useFixture(
         test_utils.OpenFixture(
             util.keepalived_lvs_cfg_path(self.listener_id_v6),
             cfg_content_v6))
Beispiel #2
0
    def test_upload_certificate_md5(self, mock_makedir, mock_exists):

        # wrong file name
        rv = self.app.put('/' + api_server.VERSION +
                          '/listeners/123/certificates/test.bla',
                          data='TestTest')
        self.assertEqual(400, rv.status_code)

        mock_exists.return_value = True
        path = listener._cert_file_path('123', 'test.pem')
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):

            rv = self.app.put('/' + api_server.VERSION +
                              '/listeners/123/certificates/test.pem',
                              data='TestTest')
            self.assertEqual(200, rv.status_code)
            self.assertEqual(OK, json.loads(rv.data.decode('utf-8')))
            handle = m()
            handle.write.assert_called_once_with(six.b('TestTest'))

        mock_exists.return_value = False
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):
            rv = self.app.put('/' + api_server.VERSION +
                              '/listeners/123/certificates/test.pem',
                              data='TestTest')
            self.assertEqual(200, rv.status_code)
            self.assertEqual(OK, json.loads(rv.data.decode('utf-8')))
            handle = m()
            handle.write.assert_called_once_with(six.b('TestTest'))
            mock_makedir.assert_called_once_with('/var/lib/octavia/certs/123')
Beispiel #3
0
    def test_upload_keepalived_config(self, mock_remove,
                                      mock_rename, mock_makedirs, mock_exists):

        flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC

        mock_exists.return_value = True
        cfg_path = util.keepalived_cfg_path()
        m = self.useFixture(test_utils.OpenFixture(cfg_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')

            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            mock_open.assert_called_with(cfg_path, flags, mode)
            mock_fdopen.assert_called_with(123, 'w')
            self.assertEqual(200, rv.status_code)

        mock_exists.return_value = False
        script_path = util.keepalived_check_script_path()
        m = self.useFixture(test_utils.OpenFixture(script_path)).mock_open

        with mock.patch('os.open') as mock_open, mock.patch.object(
                os, 'fdopen', m) as mock_fdopen:
            mock_open.return_value = 123
            rv = self.app.put('/' + api_server.VERSION + '/vrrp/upload',
                              data='test')
            mode = (stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
                    stat.S_IROTH | stat.S_IXOTH)
            mock_open.assert_called_with(script_path, flags, mode)
            mock_fdopen.assert_called_with(123, 'w')
            self.assertEqual(200, rv.status_code)
Beispiel #4
0
    def test_compute_create_cert(self, mock_driver, mock_conf, mock_jinja,
                                 mock_log_cfg):
        createcompute = compute_tasks.CertComputeCreate()
        key = utils.get_compatible_server_certs_key_passphrase()
        fer = fernet.Fernet(key)
        mock_log_cfg.return_value = 'FAKE CFG'

        mock_driver.build.return_value = COMPUTE_ID
        path = '/etc/octavia/certs/ca_01.pem'
        self.useFixture(test_utils.OpenFixture(path, 'test'))
        # Test execute()
        test_cert = fer.encrypt(utils.get_compatible_value('test_cert'))
        compute_id = createcompute.execute(_amphora_mock.id,
                                           test_cert,
                                           server_group_id=SERVER_GRPOUP_ID)

        # Validate that the build method was called properly
        mock_driver.build.assert_called_once_with(
            name="amphora-" + _amphora_mock.id,
            amphora_flavor=AMP_FLAVOR_ID,
            image_tag=AMP_IMAGE_TAG,
            image_owner='',
            key_name=AMP_SSH_KEY_NAME,
            sec_groups=AMP_SEC_GROUPS,
            network_ids=AMP_NET,
            port_ids=[],
            user_data=None,
            config_drive_files={
                '/etc/rsyslog.d/10-rsyslog.conf': 'FAKE CFG',
                '/etc/octavia/certs/server.pem': fer.decrypt(test_cert),
                '/etc/octavia/certs/client_ca.pem': 'test',
                '/etc/octavia/amphora-agent.conf': 'test_conf'
            },
            server_group_id=SERVER_GRPOUP_ID,
            availability_zone=None)

        self.assertEqual(COMPUTE_ID, compute_id)

        # Test that a build exception is raised
        self.useFixture(test_utils.OpenFixture(path, 'test'))

        createcompute = compute_tasks.ComputeCreate()
        self.assertRaises(TypeError,
                          createcompute.execute,
                          _amphora_mock,
                          config_drive_files=test_cert)

        # Test revert()

        _amphora_mock.compute_id = COMPUTE_ID

        createcompute = compute_tasks.ComputeCreate()
        createcompute.revert(compute_id, _amphora_mock.id)

        # Validate that the delete method was called properly
        mock_driver.delete.assert_called_once_with(COMPUTE_ID)

        # Test that a delete exception is not raised

        createcompute.revert(COMPUTE_ID, _amphora_mock.id)
Beispiel #5
0
    def test_enter(self, mock_cdll, mock_getpid):
        CLONE_NEWNET = 0x40000000
        FAKE_NETNS = 'fake-netns'
        FAKE_PID = random.randrange(100000)
        current_netns_fd = random.randrange(100000)
        target_netns_fd = random.randrange(100000)
        mock_getpid.return_value = FAKE_PID
        mock_cdll_obj = mock.MagicMock()
        mock_cdll.return_value = mock_cdll_obj
        expected_current_netns = '/proc/{pid}/ns/net'.format(pid=FAKE_PID)
        expected_target_netns = '/var/run/netns/{netns}'.format(
            netns=FAKE_NETNS)

        netns = network_namespace.NetworkNamespace(FAKE_NETNS)

        current_mock_open = self.useFixture(
            test_utils.OpenFixture(expected_current_netns)).mock_open
        current_mock_open.return_value = current_netns_fd

        target_mock_open = self.useFixture(
            test_utils.OpenFixture(expected_target_netns)).mock_open
        handle = target_mock_open()
        handle.fileno.return_value = target_netns_fd

        netns.__enter__()

        self.assertEqual(current_netns_fd, netns.current_netns_fd)
        netns.set_netns.assert_called_once_with(target_netns_fd, CLONE_NEWNET)
Beispiel #6
0
    def test_compute_create_cert(self, mock_driver, mock_conf, mock_jinja):
        createcompute = compute_tasks.CertComputeCreate()

        mock_driver.build.return_value = COMPUTE_ID
        path = '/etc/octavia/certs/ca_01.pem'
        self.useFixture(test_utils.OpenFixture(path, 'test'))

        # Test execute()
        compute_id = createcompute.execute(_amphora_mock.id,
                                           'test_cert',
                                           server_group_id=SERVER_GRPOUP_ID)

        # Validate that the build method was called properly
        mock_driver.build.assert_called_once_with(
            name="amphora-" + _amphora_mock.id,
            amphora_flavor=AMP_FLAVOR_ID,
            image_id=AMP_IMAGE_ID,
            image_tag=AMP_IMAGE_TAG,
            image_owner='',
            key_name=AMP_SSH_KEY_NAME,
            sec_groups=AMP_SEC_GROUPS,
            network_ids=AMP_NET,
            port_ids=[],
            user_data=None,
            config_drive_files={
                '/etc/octavia/certs/server.pem': 'test_cert',
                '/etc/octavia/certs/client_ca.pem': 'test',
                '/etc/octavia/amphora-agent.conf': 'test_conf'
            },
            server_group_id=SERVER_GRPOUP_ID)

        self.assertEqual(COMPUTE_ID, compute_id)

        # Test that a build exception is raised
        self.useFixture(test_utils.OpenFixture(path, 'test'))

        createcompute = compute_tasks.ComputeCreate()
        self.assertRaises(TypeError,
                          createcompute.execute,
                          _amphora_mock,
                          config_drive_files='test_cert')

        # Test revert()

        _amphora_mock.compute_id = COMPUTE_ID

        createcompute = compute_tasks.ComputeCreate()
        createcompute.revert(compute_id, _amphora_mock.id)

        # Validate that the delete method was called properly
        mock_driver.delete.assert_called_once_with(COMPUTE_ID)

        # Test that a delete exception is not raised

        createcompute.revert(COMPUTE_ID, _amphora_mock.id)
 def setUp(self):
     super().setUp()
     self.listener_id_v4 = uuidutils.generate_uuid()
     self.pool_id_v4 = uuidutils.generate_uuid()
     self.member_id1_v4 = uuidutils.generate_uuid()
     self.member_id2_v4 = uuidutils.generate_uuid()
     self.member_id3_v4 = uuidutils.generate_uuid()
     self.member_id4_v4 = uuidutils.generate_uuid()
     self.listener_id_v6 = uuidutils.generate_uuid()
     self.pool_id_v6 = uuidutils.generate_uuid()
     self.member_id1_v6 = uuidutils.generate_uuid()
     self.member_id2_v6 = uuidutils.generate_uuid()
     self.member_id3_v6 = uuidutils.generate_uuid()
     self.member_id4_v6 = uuidutils.generate_uuid()
     self.member_id5_v6 = uuidutils.generate_uuid()
     self.disabled_listener_id = uuidutils.generate_uuid()
     cfg_content_v4 = CFG_FILE_TEMPLATE_v4 % {
         'listener_id': self.listener_id_v4,
         'ns_name': constants.AMPHORA_NAMESPACE,
         'pool_id': self.pool_id_v4,
         'member_id1': self.member_id1_v4,
         'member_id2': self.member_id2_v4,
         'member_id3': self.member_id3_v4,
         'member_id4': self.member_id4_v4,
     }
     cfg_content_v6 = CFG_FILE_TEMPLATE_v6 % {
         'listener_id': self.listener_id_v6,
         'ns_name': constants.AMPHORA_NAMESPACE,
         'pool_id': self.pool_id_v6,
         'member_id1': self.member_id1_v6,
         'member_id2': self.member_id2_v6,
         'member_id3': self.member_id3_v6,
         'member_id4': self.member_id4_v6,
         'member_id5': self.member_id5_v6
     }
     cfg_content_disabled_listener = (
         CFG_FILE_TEMPLATE_DISABLED_LISTENER % {
             'listener_id': self.listener_id_v6,
             'ns_name': constants.AMPHORA_NAMESPACE,
         })
     self.useFixture(
         test_utils.OpenFixture(
             util.keepalived_lvs_cfg_path(self.listener_id_v4),
             cfg_content_v4))
     self.useFixture(
         test_utils.OpenFixture(
             util.keepalived_lvs_cfg_path(self.listener_id_v6),
             cfg_content_v6))
     self.useFixture(
         test_utils.OpenFixture(
             util.keepalived_lvs_cfg_path(self.disabled_listener_id),
             cfg_content_disabled_listener))
 def test_get_udp_listener_status_offline_status(self, m_exist):
     m_exist.return_value = True
     pid_path = ('/var/lib/octavia/lvs/octavia-'
                 'keepalivedlvs-%s.pid' % self.FAKE_ID)
     self.useFixture(
         test_utils.OpenFixture(pid_path, self.NORMAL_PID_CONTENT))
     cfg_path = ('/var/lib/octavia/lvs/octavia-'
                 'keepalivedlvs-%s.conf' % self.FAKE_ID)
     self.useFixture(test_utils.OpenFixture(cfg_path, 'NO VS CONFIG'))
     expected = {'status': 'OFFLINE', 'type': 'UDP', 'uuid': self.FAKE_ID}
     res = self.test_keepalivedlvs.get_udp_listener_status(self.FAKE_ID)
     self.assertEqual(200, res.status_code)
     self.assertEqual(expected, res.json)
Beispiel #9
0
    def test_get_listeners_on_lb(self, mock_exists, mock_get_haproxy_pid,
                                 mock_config_path):

        fake_cfg_path = '/some/fake/cfg/file.cfg'
        mock_config_path.return_value = fake_cfg_path
        mock_get_haproxy_pid.return_value = 'fake_pid'

        # Finds two listeners
        mock_exists.side_effect = [True, True]
        fake_cfg_data = 'frontend list1\nbackend foo\nfrontend list2'
        self.useFixture(test_utils.OpenFixture(fake_cfg_path,
                                               fake_cfg_data)).mock_open
        result = self.test_loadbalancer._get_listeners_on_lb(LB_ID1)
        self.assertEqual(['list1', 'list2'], result)
        mock_exists.assert_has_calls([
            mock.call(agent_util.pid_path(LB_ID1)),
            mock.call('/proc/fake_pid')
        ])

        # No PID file, no listeners
        mock_exists.reset_mock()
        mock_exists.side_effect = [False]
        result = self.test_loadbalancer._get_listeners_on_lb(LB_ID1)
        self.assertEqual([], result)
        mock_exists.assert_called_once_with(agent_util.pid_path(LB_ID1))

        # PID file, no running process, no listeners
        mock_exists.reset_mock()
        mock_exists.side_effect = [True, False]
        result = self.test_loadbalancer._get_listeners_on_lb(LB_ID1)
        self.assertEqual([], result)
        mock_exists.assert_has_calls([
            mock.call(agent_util.pid_path(LB_ID1)),
            mock.call('/proc/fake_pid')
        ])

        # PID file, running process, no listeners
        mock_exists.reset_mock()
        mock_exists.side_effect = [True, True]
        fake_cfg_data = 'backend only'
        self.useFixture(test_utils.OpenFixture(fake_cfg_path,
                                               fake_cfg_data)).mock_open
        result = self.test_loadbalancer._get_listeners_on_lb(LB_ID1)
        self.assertEqual([], result)
        mock_exists.assert_has_calls([
            mock.call(agent_util.pid_path(LB_ID1)),
            mock.call('/proc/fake_pid')
        ])
    def test_get_udp_listener_status(self, m_exist, m_check_output,
                                     mget_mapping):
        mget_mapping.return_value = (True, {
            '10.0.0.99:82': {
                'status': 'UP',
                'Weight': '13',
                'InActConn': '0',
                'ActiveConn': '0'
            },
            '10.0.0.98:82': {
                'status': 'UP',
                'Weight': '13',
                'InActConn': '0',
                'ActiveConn': '0'
            }
        })
        pid_path = ('/var/lib/octavia/lvs/octavia-'
                    'keepalivedlvs-%s.pid' % self.FAKE_ID)
        self.useFixture(
            test_utils.OpenFixture(pid_path, self.NORMAL_PID_CONTENT))

        cfg_path = ('/var/lib/octavia/lvs/octavia-'
                    'keepalivedlvs-%s.conf' % self.FAKE_ID)
        self.useFixture(
            test_utils.OpenFixture(cfg_path, self.NORMAL_CFG_CONTENT))

        m_exist.return_value = True
        expected = {
            'status':
            'ACTIVE',
            'pools': [{
                'lvs': {
                    'members': {
                        self.MEMBER_ID1: 'UP',
                        self.MEMBER_ID2: 'UP'
                    },
                    'status': 'UP',
                    'uuid': self.POOL_ID
                }
            }],
            'type':
            'UDP',
            'uuid':
            self.FAKE_ID
        }
        res = self.test_keepalivedlvs.get_udp_listener_status(self.FAKE_ID)
        self.assertEqual(200, res.status_code)
        self.assertEqual(expected, res.json)
Beispiel #11
0
 def test_get_keepalivedlvs_pid(self, mock_path):
     fake_path = '/fake/path'
     mock_path.return_value = [fake_path]
     self.useFixture(test_utils.OpenFixture(fake_path,
                                            ' space data   ')).mock_open
     result = util.get_keepalivedlvs_pid(self.listener_id)
     self.assertEqual(' space data', result)
Beispiel #12
0
    def test_get_certificate_md5(self, mock_exists):
        CONTENT = "TestTest"

        mock_exists.side_effect = [False]
        rv = self.app.get('/' + api_server.VERSION +
                          '/listeners/123/certificates/test.pem')
        self.assertEqual(404, rv.status_code)
        self.assertEqual(dict(
            details='No certificate with filename: test.pem',
            message='Certificate Not Found'),
            json.loads(rv.data.decode('utf-8')))
        mock_exists.assert_called_with('/var/lib/octavia/certs/123/test.pem')

        # wrong file name
        mock_exists.side_effect = [True]
        rv = self.app.put('/' + api_server.VERSION +
                          '/listeners/123/certificates/test.bla',
                          data='TestTest')
        self.assertEqual(400, rv.status_code)

        mock_exists.return_value = True
        mock_exists.side_effect = None
        path = listener._cert_file_path('123', 'test.pem')
        self.useFixture(test_utils.OpenFixture(path, CONTENT))

        rv = self.app.get('/' + api_server.VERSION +
                          '/listeners/123/certificates/test.pem')
        self.assertEqual(200, rv.status_code)
        self.assertEqual(dict(md5sum=hashlib.md5(six.b(CONTENT)).hexdigest()),
                         json.loads(rv.data.decode('utf-8')))
Beispiel #13
0
    def setUp(self):
        super(TestAmphoraInfo, self).setUp()
        self.osutils_mock = mock.MagicMock()
        self.amp_info = amphora_info.AmphoraInfo(self.osutils_mock)
        self.udp_driver = mock.MagicMock()

        # setup a fake haproxy config file
        templater = jinja_cfg.JinjaTemplater(base_amp_path=self.BASE_AMP_PATH,
                                             base_crt_dir=self.BASE_CRT_PATH)
        tls_tupel = {
            'cont_id_1':
            sample_configs_combined.sample_tls_container_tuple(
                id='tls_container_id',
                certificate='imaCert1',
                private_key='imaPrivateKey1',
                primary_cn='FakeCN')
        }
        self.rendered_haproxy_cfg = templater.render_loadbalancer_obj(
            sample_configs_combined.sample_amphora_tuple(), [
                sample_configs_combined.sample_listener_tuple(
                    proto='TERMINATED_HTTPS', tls=True, sni=True)
            ], tls_tupel)
        path = util.config_path(self.LB_ID_1)
        self.useFixture(test_utils.OpenFixture(path,
                                               self.rendered_haproxy_cfg))
Beispiel #14
0
    def test_sctp_health_check_error(self, mock_build_abort_packet,
                                     mock_decode_packet, mock_socket,
                                     mock_time):
        mock_time.side_effect = [1, 2, 3, 4]
        socket_mock = mock.Mock()
        socket_mock.recvfrom = mock.Mock()
        socket_mock.recvfrom.side_effect = [socket.timeout(), (None, None)]
        mock_socket.return_value = socket_mock

        mock_decode_packet.return_value = 1234  # Unknown

        abrt_mock = mock.Mock()
        mock_build_abort_packet.return_value = abrt_mock

        mock_open = self.useFixture(
            test_utils.OpenFixture('/proc/net/protocols', 'bar\n')).mock_open

        with mock.patch('builtins.open', mock_open):
            ret = health_checker.sctp_health_check("192.168.0.27",
                                                   1234,
                                                   timeout=3)

        self.assertEqual(3, ret)  # Unknown error

        mock_decode_packet.assert_called()
        socket_mock.send.assert_called_with(abrt_mock)
Beispiel #15
0
    def test_sctp_health_check_timeout(self, mock_build_abort_packet,
                                       mock_decode_packet, mock_socket,
                                       mock_time):
        mock_time.side_effect = [1, 2, 3, 4]
        socket_mock = mock.Mock()
        socket_mock.recvfrom = mock.Mock()
        socket_mock.recvfrom.side_effect = [
            socket.timeout(),
            socket.timeout(),
            socket.timeout(),
            socket.timeout(),
        ]
        mock_socket.return_value = socket_mock

        abrt_mock = mock.Mock()
        mock_build_abort_packet.return_value = abrt_mock

        mock_open = self.useFixture(
            test_utils.OpenFixture('/proc/net/protocols', 'bar\n')).mock_open

        with mock.patch('builtins.open', mock_open):
            ret = health_checker.sctp_health_check("192.168.0.27",
                                                   1234,
                                                   timeout=3)

        self.assertEqual(2, ret)  # Timeout

        mock_decode_packet.assert_not_called()
        for call in socket_mock.send.mock_calls:
            self.assertNotEqual(mock.call(abrt_mock), call)
Beispiel #16
0
 def setUp(self):
     super().setUp()
     conf = oslo_fixture.Config(cfg.CONF)
     conf.config(group="haproxy_amphora", base_path=BASE_PATH)
     conf.config(group="amphora_agent", amphora_id=AMPHORA_ID)
     file_name = os.path.join(BASE_PATH, "stats_counters")
     self.mock_open = self.useFixture(
         test_utils.OpenFixture(file_name)).mock_open
Beispiel #17
0
    def test_upload_lvs_listener_config_with_vrrp_check_dir(
            self, m_check_output, m_os_rm, m_os_mkdir, m_exists, m_os_chmod,
            m_os_sysinit, m_copy2, mock_netns, mock_install_netns,
            mock_systemctl, mock_get_lbs, mock_get_lvs_listeners):
        m_exists.side_effect = [False, False, True, True, False, False, False]
        mock_get_lbs.return_value = []
        mock_get_lvs_listeners.return_value = [self.FAKE_ID]
        cfg_path = util.keepalived_lvs_cfg_path(self.FAKE_ID)
        m = self.useFixture(test_utils.OpenFixture(cfg_path)).mock_open

        conf = self.useFixture(oslo_fixture.Config(cfg.CONF))
        conf.config(group='controller_worker',
                    loadbalancer_topology=consts.TOPOLOGY_ACTIVE_STANDBY)

        with mock.patch('os.open') as m_open, mock.patch.object(
                os, 'fdopen', m) as m_fdopen:
            m_open.side_effect = [
                'TEST-WRITE-CFG', 'TEST-WRITE-SYSINIT',
                'TEST-WRITE-UDP-VRRP-CHECK'
            ]
            res = self.client.put(self.TEST_URL % ('123', self.FAKE_ID),
                                  data=self.NORMAL_CFG_CONTENT)
            os_mkdir_calls = [
                mock.call(util.keepalived_lvs_dir()),
                mock.call(util.keepalived_backend_check_script_dir())
            ]
            m_os_mkdir.assert_has_calls(os_mkdir_calls)

            mock_install_netns.assert_called_once()
            systemctl_calls = [
                mock.call(consts.ENABLE, consts.AMP_NETNS_SVC_PREFIX),
                mock.call(consts.ENABLE,
                          'octavia-keepalivedlvs-%s' % str(self.FAKE_ID)),
            ]
            mock_systemctl.assert_has_calls(systemctl_calls)

            m_os_chmod.assert_called_with(
                util.keepalived_backend_check_script_path(), stat.S_IEXEC)
            flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            systemd_cfg_path = util.keepalived_lvs_init_path(
                consts.INIT_SYSTEMD, self.FAKE_ID)
            script_path = os.path.join(
                util.keepalived_check_scripts_dir(),
                keepalivedlvs.KEEPALIVED_CHECK_SCRIPT_NAME)
            m_open_calls = [
                mock.call(cfg_path, flags, mode),
                mock.call(systemd_cfg_path, flags, mode),
                mock.call(script_path, flags, stat.S_IEXEC)
            ]
            m_open.assert_has_calls(m_open_calls)
            m_fdopen.assert_any_call('TEST-WRITE-CFG', 'wb')
            m_fdopen.assert_any_call('TEST-WRITE-SYSINIT', 'w')
            m_fdopen.assert_any_call('TEST-WRITE-UDP-VRRP-CHECK', 'w')

            m_os_rm.assert_called_once_with(util.haproxy_check_script_path())
            self.assertEqual(200, res.status_code)
Beispiel #18
0
    def test_vrrp_check_script_update(self, mock_sock_path, mock_get_lbs,
                                      mock_join, mock_listdir, mock_exists,
                                      mock_makedirs, mock_get_listeners):
        mock_get_lbs.return_value = ['abc', LB_ID1]
        mock_sock_path.return_value = 'listener.sock'
        mock_exists.side_effect = [False, False, True]
        mock_get_lbs.side_effect = [['abc', LB_ID1], ['abc', LB_ID1], []]
        mock_get_listeners.return_value = []

        # Test the stop action path
        cmd = 'haproxy-vrrp-check ' + ' '.join(['listener.sock']) + '; exit $?'
        path = util.keepalived_dir()
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        util.vrrp_check_script_update(LB_ID1, 'stop')

        handle = m()
        handle.write.assert_called_once_with(cmd)

        # Test the start action path
        cmd = ('haproxy-vrrp-check ' +
               ' '.join(['listener.sock', 'listener.sock']) + '; exit '
               '$?')
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open
        util.vrrp_check_script_update(LB_ID1, 'start')
        handle = m()
        handle.write.assert_called_once_with(cmd)

        # Test the path with existing keepalived directory and no LBs
        mock_makedirs.reset_mock()
        cmd = 'exit 1'
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        util.vrrp_check_script_update(LB_ID1, 'start')

        handle = m()
        handle.write.assert_called_once_with(cmd)
        mock_makedirs.assert_has_calls([
            mock.call(util.keepalived_dir(), exist_ok=True),
            mock.call(util.keepalived_check_scripts_dir(), exist_ok=True)
        ])
Beispiel #19
0
 def test_upload_server_certificate(self):
     certificate_update.BUFFER = 5  # test the while loop
     path = '/etc/octavia/certs/server.pem'
     m = self.useFixture(test_utils.OpenFixture(path)).mock_open
     with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):
         rv = self.app.put('/' + api_server.VERSION + '/certificate',
                           data='TestTest')
         self.assertEqual(202, rv.status_code)
         self.assertEqual(OK, json.loads(rv.data.decode('utf-8')))
         handle = m()
         handle.write.assert_any_call(six.b('TestT'))
         handle.write.assert_any_call(six.b('est'))
Beispiel #20
0
    def test__load(self):

        sample_loadavg = '0.09 0.11 0.10 2/630 15346'

        expected_result = ['0.09', '0.11', '0.10']

        self.useFixture(
            test_utils.OpenFixture('/proc/loadavg', contents=sample_loadavg))

        result = self.amp_info._load()

        self.assertEqual(expected_result, result)
Beispiel #21
0
    def test__cpu(self):

        sample_stat = 'cpu  252551 802 52554 7181757 7411 0 8336 0 0 0'

        expected_result = {'user': '******', 'iowait': '7411', 'nice': '802',
                           'softirq': '8336', 'idle': '7181757',
                           'system': '52554', 'total': 7503411, 'irq': '0'}

        self.useFixture(test_utils.OpenFixture('/proc/stat',
                                               contents=sample_stat))

        result = self.amp_info._cpu()

        self.assertEqual(expected_result, result)
Beispiel #22
0
    def test_get_haproxy_vip_addresses(self, mock_cfg_path):
        FAKE_PATH = 'fake_path'
        mock_cfg_path.return_value = FAKE_PATH
        self.useFixture(test_utils.OpenFixture(FAKE_PATH,
                                               'no match')).mock_open()

        # Test with no matching lines in the config file
        self.assertEqual([], util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a matching bind line
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind 203.0.113.43:1\nbogus line'
        self.useFixture(test_utils.OpenFixture(FAKE_PATH,
                                               test_data)).mock_open()
        expected_result = ['203.0.113.43']
        self.assertEqual(expected_result,
                         util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a matching bind line multiple binds
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind 203.0.113.44:1234, 203.0.113.45:4321'
        self.useFixture(test_utils.OpenFixture(FAKE_PATH,
                                               test_data)).mock_open()
        expected_result = ['203.0.113.44', '203.0.113.45']
        self.assertEqual(expected_result,
                         util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a bogus bind line
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind\nbogus line'
        self.useFixture(test_utils.OpenFixture(FAKE_PATH,
                                               test_data)).mock_open()
        self.assertEqual([], util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)
Beispiel #23
0
    def test_get_haproxy(self, mock_exists):
        CONTENT = "bibble\nbibble"
        mock_exists.side_effect = [False]
        rv = self.app.get('/' + api_server.VERSION + '/listeners/123/haproxy')
        self.assertEqual(404, rv.status_code)

        mock_exists.side_effect = [True]
        path = util.config_path('123')
        self.useFixture(test_utils.OpenFixture(path, CONTENT))

        rv = self.app.get('/' + api_server.VERSION + '/listeners/123/haproxy')
        self.assertEqual(200, rv.status_code)
        self.assertEqual(six.b(CONTENT), rv.data)
        self.assertEqual('text/plain; charset=utf-8',
                         rv.headers['Content-Type'])
Beispiel #24
0
    def test_vrrp_check_script_update(self, mock_sock_path, mock_get_listeners,
                                      mock_join, mock_listdir, mock_exists,
                                      mock_makedirs):
        mock_get_listeners.return_value = ['abc', LISTENER_ID1]
        mock_sock_path.return_value = 'listener.sock'
        mock_exists.return_value = False
        cmd = 'haproxy-vrrp-check ' + ' '.join(['listener.sock']) + '; exit $?'

        path = agent_util.keepalived_dir()
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        self.test_listener.vrrp_check_script_update(LISTENER_ID1, 'stop')
        handle = m()
        handle.write.assert_called_once_with(cmd)

        mock_get_listeners.return_value = ['abc', LISTENER_ID1]
        cmd = ('haproxy-vrrp-check ' +
               ' '.join(['listener.sock', 'listener.sock']) + '; exit '
               '$?')

        m = self.useFixture(test_utils.OpenFixture(path)).mock_open
        self.test_listener.vrrp_check_script_update(LISTENER_ID1, 'start')
        handle = m()
        handle.write.assert_called_once_with(cmd)
Beispiel #25
0
    def test_upload_udp_listener_config_no_vrrp_check_dir(
            self, m_check_output, m_os_rm, m_os_mkdir, m_exists, m_os_chmod,
            m_os_sysinit, m_copy2, mock_netns, mock_install_netns,
            mock_systemctl):
        m_exists.side_effect = [False, False, True, True, False, False]
        cfg_path = util.keepalived_lvs_cfg_path(self.FAKE_ID)
        m = self.useFixture(test_utils.OpenFixture(cfg_path)).mock_open

        with mock.patch('os.open') as m_open, mock.patch.object(
                os, 'fdopen', m) as m_fdopen:
            m_open.side_effect = ['TEST-WRITE-CFG', 'TEST-WRITE-SYSINIT']

            res = self.client.put(self.TEST_URL % ('123', self.FAKE_ID),
                                  data=self.NORMAL_CFG_CONTENT)

            mock_install_netns.assert_called_once()
            systemctl_calls = [
                mock.call(consts.ENABLE, consts.AMP_NETNS_SVC_PREFIX),
                mock.call(consts.ENABLE,
                          'octavia-keepalivedlvs-%s' % str(self.FAKE_ID)),
            ]
            mock_systemctl.assert_has_calls(systemctl_calls)
            os_mkdir_calls = [
                mock.call(util.keepalived_lvs_dir()),
                mock.call(util.keepalived_backend_check_script_dir())
            ]
            m_os_mkdir.assert_has_calls(os_mkdir_calls)

            m_os_chmod.assert_called_with(
                util.keepalived_backend_check_script_path(), stat.S_IEXEC)

            flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
            systemd_cfg_path = util.keepalived_lvs_init_path(
                consts.INIT_SYSTEMD, self.FAKE_ID)

            m_open_calls = [
                mock.call(cfg_path, flags, mode),
                mock.call(systemd_cfg_path, flags, mode)
            ]
            m_open.assert_has_calls(m_open_calls)
            m_fdopen.assert_any_call('TEST-WRITE-CFG', 'wb')
            m_fdopen.assert_any_call('TEST-WRITE-SYSINIT', 'w')
            self.assertEqual(200, res.status_code)
Beispiel #26
0
    def test_check_listener_status(self, mock_pid, mock_exists):
        mock_pid.return_value = '1245'
        mock_exists.side_effect = [True, True]
        config_path = agent_util.config_path(LISTENER_ID1)
        file_contents = 'frontend {}'.format(LISTENER_ID1)
        self.useFixture(test_utils.OpenFixture(config_path, file_contents))
        self.assertEqual(
            consts.ACTIVE,
            self.test_listener._check_listener_status(LISTENER_ID1))

        mock_exists.side_effect = [True, False]
        self.assertEqual(
            consts.ERROR,
            self.test_listener._check_listener_status(LISTENER_ID1))

        mock_exists.side_effect = [False]
        self.assertEqual(
            consts.OFFLINE,
            self.test_listener._check_listener_status(LISTENER_ID1))
Beispiel #27
0
    def test_write_port_interface_file(self):
        netns_interface = 'eth1234'
        MTU = 1450
        fixed_ips = []
        path = 'mypath'
        mock_template = mock.MagicMock()
        mock_open = self.useFixture(test_utils.OpenFixture(path)).mock_open
        mock_gen_text = mock.MagicMock()

        with mock.patch('os.open'), mock.patch.object(
                os, 'fdopen', mock_open), mock.patch.object(
                osutils.BaseOS, '_generate_network_file_text', mock_gen_text):
            self.base_os_util.write_port_interface_file(
                netns_interface=netns_interface,
                fixed_ips=fixed_ips,
                mtu=MTU,
                interface_file_path=path,
                template_port=mock_template)

        mock_gen_text.assert_called_once_with(
            netns_interface, fixed_ips, MTU, mock_template)
Beispiel #28
0
    def test_write_port_interface_file(self):
        FIXED_IP = u'192.0.2.2'
        NEXTHOP = u'192.0.2.1'
        DEST = u'198.51.100.0/24'
        host_routes = [{
            'nexthop': NEXTHOP,
            'destination': ipaddress.ip_network(DEST)
        }]
        FIXED_IP_IPV6 = u'2001:db8::2'
        NEXTHOP_IPV6 = u'2001:db8::1'
        DEST_IPV6 = u'2001:db8:51:100::/64'
        host_routes_ipv6 = [{
            'nexthop': NEXTHOP_IPV6,
            'destination': ipaddress.ip_network(DEST_IPV6)
        }]
        ip_addr = {'ip_address': FIXED_IP, 'host_routes': host_routes}
        ipv6_addr = {
            'ip_address': FIXED_IP_IPV6,
            'host_routes': host_routes_ipv6
        }

        netns_interface = 'eth1234'
        MTU = 1450
        fixed_ips = [ip_addr, ipv6_addr]
        path = 'mypath'
        mock_template = mock.MagicMock()
        mock_open = self.useFixture(test_utils.OpenFixture(path)).mock_open
        mock_gen_text = mock.MagicMock()
        mock_local_scripts = mock.MagicMock()
        mock_wr_fi = mock.MagicMock()

        with mock.patch('os.open'), mock.patch.object(
                os, 'fdopen',
                mock_open), mock.patch.object(osutils.BaseOS,
                                              '_generate_network_file_text',
                                              mock_gen_text):
            self.base_os_util.write_port_interface_file(
                netns_interface=netns_interface,
                fixed_ips=fixed_ips,
                mtu=MTU,
                interface_file_path=path,
                template_port=mock_template)

        mock_gen_text.assert_called_once_with(netns_interface, fixed_ips, MTU,
                                              mock_template)

        mock_gen_text.reset_mock()

        with mock.patch('os.open'), mock.patch.object(
                os, 'fdopen', mock_open), mock.patch.object(
                    osutils.BaseOS, '_generate_network_file_text',
                    mock_gen_text), mock.patch.object(
                        osutils.RH,
                        '_write_ifup_ifdown_local_scripts_if_possible',
                        mock_local_scripts), mock.patch.object(
                            osutils.RH, 'write_static_routes_interface_file',
                            mock_wr_fi):
            self.rh_os_util.write_port_interface_file(
                netns_interface=netns_interface,
                fixed_ips=fixed_ips,
                mtu=MTU,
                interface_file_path=path,
                template_port=mock_template)

        rh_route_name = 'route-{nic}'.format(nic=netns_interface)
        rh_real_route_path = os.path.join(
            consts.RH_AMP_NET_DIR_TEMPLATE.format(
                netns=consts.AMPHORA_NAMESPACE), rh_route_name)
        rh_route_name_ipv6 = 'route6-{nic}'.format(nic=netns_interface)
        rh_real_route_path_ipv6 = os.path.join(
            consts.RH_AMP_NET_DIR_TEMPLATE.format(
                netns=consts.AMPHORA_NAMESPACE), rh_route_name_ipv6)

        exp_routes = [{'network': ipaddress.ip_network(DEST), 'gw': NEXTHOP}]
        exp_routes_ipv6 = [{
            'network': ipaddress.ip_network(DEST_IPV6),
            'gw': NEXTHOP_IPV6
        }]
        expected_calls = [
            mock.call(rh_real_route_path, netns_interface, exp_routes,
                      mock.ANY, None, None, None),
            mock.call(rh_real_route_path_ipv6, netns_interface,
                      exp_routes_ipv6, mock.ANY, None, None, None)
        ]

        mock_gen_text.assert_called_once_with(netns_interface, fixed_ips, MTU,
                                              mock_template)
        self.assertEqual(2, mock_wr_fi.call_count)
        mock_wr_fi.assert_has_calls(expected_calls)
        mock_local_scripts.assert_called_once()
Beispiel #29
0
    def test_write_vip_interface_file(self):
        netns_interface = u'eth1234'
        FIXED_IP = u'192.0.2.2'
        SUBNET_CIDR = u'192.0.2.0/24'
        GATEWAY = u'192.51.100.1'
        DEST1 = u'198.51.100.0/24'
        DEST2 = u'203.0.113.0/24'
        NEXTHOP = u'192.0.2.1'
        MTU = 1450
        FIXED_IP_IPV6 = u'2001:0db8:0000:0000:0000:0000:0000:0001'
        # Subnet prefix is purposefully not 32, because that coincidentally
        # matches the result of any arbitrary IPv4->prefixlen conversion
        SUBNET_CIDR_IPV6 = u'2001:db8::/70'

        ip = ipaddress.ip_address(FIXED_IP)
        network = ipaddress.ip_network(SUBNET_CIDR)
        broadcast = network.broadcast_address.exploded
        netmask = network.netmask.exploded
        netmask_prefix = utils.netmask_to_prefix(netmask)

        ipv6 = ipaddress.ip_address(FIXED_IP_IPV6)
        networkv6 = ipaddress.ip_network(SUBNET_CIDR_IPV6)
        broadcastv6 = networkv6.broadcast_address.exploded
        netmaskv6 = networkv6.prefixlen

        host_routes = [{
            'gw': NEXTHOP,
            'network': ipaddress.ip_network(DEST1)
        }, {
            'gw': NEXTHOP,
            'network': ipaddress.ip_network(DEST2)
        }]

        path = self.ubuntu_os_util.get_network_interface_file(netns_interface)
        mock_open = self.useFixture(test_utils.OpenFixture(path)).mock_open
        mock_template = mock.MagicMock()

        # Test an IPv4 VIP
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', mock_open):
            self.ubuntu_os_util.write_vip_interface_file(
                interface_file_path=path,
                primary_interface=netns_interface,
                vip=FIXED_IP,
                ip=ip,
                broadcast=broadcast,
                netmask=netmask,
                gateway=GATEWAY,
                mtu=MTU,
                vrrp_ip=None,
                vrrp_version=None,
                render_host_routes=host_routes,
                template_vip=mock_template)

        mock_template.render.assert_called_once_with(
            consts=consts,
            interface=netns_interface,
            vip=FIXED_IP,
            vip_ipv6=False,
            prefix=netmask_prefix,
            broadcast=broadcast,
            netmask=netmask,
            gateway=GATEWAY,
            network=SUBNET_CIDR,
            mtu=MTU,
            vrrp_ip=None,
            vrrp_ipv6=False,
            host_routes=host_routes,
            topology="SINGLE",
        )

        # Now test with an IPv6 VIP
        mock_template.reset_mock()
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', mock_open):
            self.ubuntu_os_util.write_vip_interface_file(
                interface_file_path=path,
                primary_interface=netns_interface,
                vip=FIXED_IP_IPV6,
                ip=ipv6,
                broadcast=broadcastv6,
                netmask=netmaskv6,
                gateway=GATEWAY,
                mtu=MTU,
                vrrp_ip=None,
                vrrp_version=None,
                render_host_routes=host_routes,
                template_vip=mock_template)

        mock_template.render.assert_called_once_with(
            consts=consts,
            interface=netns_interface,
            vip=FIXED_IP_IPV6,
            vip_ipv6=True,
            prefix=netmaskv6,
            broadcast=broadcastv6,
            netmask=netmaskv6,
            gateway=GATEWAY,
            network=SUBNET_CIDR_IPV6,
            mtu=MTU,
            vrrp_ip=None,
            vrrp_ipv6=False,
            host_routes=host_routes,
            topology="SINGLE",
        )
Beispiel #30
0
    def test_parse_haproxy_config(self):
        # template_tls
        tls_tupe = sample_configs.sample_tls_container_tuple(
            id='tls_container_id',
            certificate='imaCert1',
            private_key='imaPrivateKey1',
            primary_cn='FakeCN')
        rendered_obj = self.jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_amphora_tuple(),
            sample_configs.sample_listener_tuple(proto='TERMINATED_HTTPS',
                                                 tls=True,
                                                 sni=True), tls_tupe)

        path = agent_util.config_path(LISTENER_ID1)
        self.useFixture(test_utils.OpenFixture(path, rendered_obj))

        res = self.test_listener._parse_haproxy_file(LISTENER_ID1)
        self.assertEqual('TERMINATED_HTTPS', res['mode'])
        self.assertEqual('/var/lib/octavia/sample_listener_id_1.sock',
                         res['stats_socket'])
        self.assertEqual(
            '/var/lib/octavia/certs/sample_listener_id_1/tls_container_id.pem',
            res['ssl_crt'])

        # render_template_tls_no_sni
        rendered_obj = self.jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_amphora_tuple(),
            sample_configs.sample_listener_tuple(proto='TERMINATED_HTTPS',
                                                 tls=True),
            tls_cert=sample_configs.sample_tls_container_tuple(
                id='tls_container_id',
                certificate='ImAalsdkfjCert',
                private_key='ImAsdlfksdjPrivateKey',
                primary_cn="FakeCN"))

        self.useFixture(test_utils.OpenFixture(path, rendered_obj))

        res = self.test_listener._parse_haproxy_file(LISTENER_ID1)
        self.assertEqual('TERMINATED_HTTPS', res['mode'])
        self.assertEqual(BASE_AMP_PATH + '/sample_listener_id_1.sock',
                         res['stats_socket'])
        self.assertEqual(
            BASE_CRT_PATH + '/sample_listener_id_1/tls_container_id.pem',
            res['ssl_crt'])

        # render_template_http
        rendered_obj = self.jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_amphora_tuple(),
            sample_configs.sample_listener_tuple())

        self.useFixture(test_utils.OpenFixture(path, rendered_obj))

        res = self.test_listener._parse_haproxy_file(LISTENER_ID1)
        self.assertEqual('HTTP', res['mode'])
        self.assertEqual(BASE_AMP_PATH + '/sample_listener_id_1.sock',
                         res['stats_socket'])
        self.assertIsNone(res['ssl_crt'])

        # template_https
        rendered_obj = self.jinja_cfg.render_loadbalancer_obj(
            sample_configs.sample_amphora_tuple(),
            sample_configs.sample_listener_tuple(proto='HTTPS'))
        self.useFixture(test_utils.OpenFixture(path, rendered_obj))

        res = self.test_listener._parse_haproxy_file(LISTENER_ID1)
        self.assertEqual('TCP', res['mode'])
        self.assertEqual(BASE_AMP_PATH + '/sample_listener_id_1.sock',
                         res['stats_socket'])
        self.assertIsNone(res['ssl_crt'])

        # Bogus format
        self.useFixture(test_utils.OpenFixture(path, 'Bogus'))
        try:
            res = self.test_listener._parse_haproxy_file(LISTENER_ID1)
            self.fail("No Exception?")
        except listener.ParsingError:
            pass