def setUp(self):
        """Create test case setup."""
        self.cred = Credential(
            name='cred1',
            cred_type=Credential.SATELLITE_CRED_TYPE,
            username='******',
            password='******')
        self.cred.save()

        self.source = Source(
            name='source1',
            port=443,
            hosts='["1.2.3.4"]')

        self.source.save()
        self.source.credentials.add(self.cred)

        self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                  source=self.source, sequence_number=2,
                                  start_time=datetime.utcnow())
        self.scan_task.save()
        self.scan_task.update_stats('TEST_SAT.', sys_scanned=0)

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT)
        self.scan_job.save()
        self.scan_job.tasks.add(self.scan_task)
        self.conn_results = JobConnectionResult()
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.conn_result = TaskConnectionResult(
            scan_task=self.scan_task, source=self.source)
        self.conn_result.save()

        conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT,
                             source=self.source, sequence_number=1,
                             start_time=datetime.utcnow())
        conn_task.complete()
        self.scan_task.prerequisites.add(conn_task)
        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results

        self.scan_job.save()
Beispiel #2
0
    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(name='cred1',
                               username='******',
                               password='******',
                               become_password=None,
                               ssh_keyfile=None)
        self.cred.save()

        self.source = Source(name='source1', port=22, hosts='["1.2.3.4"]')

        self.source.save()
        self.source.credentials.add(self.cred)

        self.conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                  source=self.source,
                                  sequence_number=1,
                                  start_time=datetime.utcnow())
        self.conn_task.update_stats('TEST_VC.', sys_count=5)
        self.conn_task.complete()

        self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                  source=self.source,
                                  sequence_number=2,
                                  start_time=datetime.utcnow())
        self.scan_task.save()

        self.scan_task.prerequisites.add(self.conn_task)
        self.scan_task.save()

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.scan_job.save()
        self.scan_job.tasks.add(self.scan_task)
        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results
        self.scan_job.save()
        self.runner = InspectTaskRunner(scan_job=self.scan_job,
                                        scan_task=self.scan_task)
Beispiel #3
0
    def test_expand_inspect_results(self):
        """Test view expand_inspect_results."""
        scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        scan_job.save()
        scan_job.sources.add(self.source)

        # Job in created state
        self.assertEqual(scan_job.status, ScanTask.CREATED)
        tasks = scan_job.tasks.all()
        self.assertEqual(len(tasks), 0)

        # Queue job to run
        scan_job.queue()

        inspect_task = scan_job.tasks.all()[1]

        inspect_results = JobInspectionResult()
        inspect_results.save()

        scan_job.inspection_results = inspect_results
        scan_job.save()

        inspect_result = TaskInspectionResult(source=inspect_task.source,
                                              scan_task=inspect_task)
        inspect_result.save()

        inspect_results.results.add(inspect_result)
        inspect_results.save()

        sys_result = SystemInspectionResult(
            name='Foo', status=SystemConnectionResult.SUCCESS)
        sys_result.save()

        fact = RawFact(name='foo', value='"value"')
        fact.save()
        sys_result.facts.add(fact)
        sys_result.save()

        inspect_result.systems.add(sys_result)
        inspect_result.save()

        inspect_results_json = {'results': [{}]}
        expand_inspect_results(inspect_results, inspect_results_json)
        self.assertEqual(
            inspect_results_json['results'][0]['systems'][0]['facts'][0]
            ['name'], 'foo')
Beispiel #4
0
    def test_details(self, start_scan):
        """Get ScanJob result details by primary key."""
        scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        scan_job.save()
        scan_job.sources.add(self.source)

        # Job in created state
        self.assertEqual(scan_job.status, ScanTask.CREATED)
        tasks = scan_job.tasks.all()
        self.assertEqual(len(tasks), 0)

        # Queue job to run
        scan_job.queue()

        conn_task = scan_job.tasks.first()

        conn_results = JobConnectionResult()
        conn_results.save()
        scan_job.connection_results = conn_results

        conn_result = TaskConnectionResult(source=conn_task.source,
                                           scan_task=conn_task)
        conn_result.save()

        conn_results.results.add(conn_result)
        conn_results.save()

        sys_result = SystemConnectionResult(
            name='Foo',
            credential=self.cred,
            status=SystemConnectionResult.SUCCESS)
        sys_result.save()
        conn_result.systems.add(sys_result)
        conn_result.save()

        inspect_task = scan_job.tasks.all()[1]

        inspect_results = JobInspectionResult()
        inspect_results.save()
        scan_job.inspection_results = inspect_results

        inspect_result = TaskInspectionResult(source=inspect_task.source,
                                              scan_task=inspect_task)
        inspect_result.save()

        inspect_results.results.add(inspect_result)
        inspect_results.save()

        sys_result = SystemInspectionResult(
            name='Foo', status=SystemConnectionResult.SUCCESS)
        sys_result.save()

        fact = RawFact(name='fact_key', value='"fact_value"')
        fact.save()
        sys_result.facts.add(fact)
        sys_result.save()

        inspect_result.systems.add(sys_result)
        inspect_result.save()
        scan_job.save()

        url = reverse('scanjob-detail', args=(scan_job.id, )) + 'results/'
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        json_response = response.json()
        self.assertIn('connection_results', json_response)
        self.assertIn('inspection_results', json_response)

        self.assertEqual(
            json_response, {
                'connection_results': {
                    'results': [{
                        'source': {
                            'id': 1,
                            'name': 'source1',
                            'source_type': 'network'
                        },
                        'systems': [{
                            'name': 'Foo',
                            'credential': {
                                'id': 1,
                                'name': 'cred1'
                            },
                            'status': 'success'
                        }]
                    }]
                },
                'inspection_results': {
                    'results': [{
                        'source': {
                            'id': 1,
                            'name': 'source1',
                            'source_type': 'network'
                        },
                        'systems': [{
                            'name':
                            'Foo',
                            'status':
                            'success',
                            'facts': [{
                                'name': 'fact_key',
                                'value': 'fact_value'
                            }]
                        }]
                    }]
                }
            })
Beispiel #5
0
class InspectTaskRunnerTest(TestCase):
    """Tests against the InspectTaskRunner class and functions."""

    runner = None

    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(name='cred1',
                               username='******',
                               password='******',
                               become_password=None,
                               ssh_keyfile=None)
        self.cred.save()

        self.source = Source(name='source1', port=22, hosts='["1.2.3.4"]')

        self.source.save()
        self.source.credentials.add(self.cred)

        self.conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                  source=self.source,
                                  sequence_number=1,
                                  start_time=datetime.utcnow())
        self.conn_task.update_stats('TEST_VC.', sys_count=5)
        self.conn_task.complete()

        self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                  source=self.source,
                                  sequence_number=2,
                                  start_time=datetime.utcnow())
        self.scan_task.save()

        self.scan_task.prerequisites.add(self.conn_task)
        self.scan_task.save()

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.scan_job.save()
        self.scan_job.tasks.add(self.scan_task)
        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results
        self.scan_job.save()
        self.runner = InspectTaskRunner(scan_job=self.scan_job,
                                        scan_task=self.scan_task)

    def tearDown(self):
        """Cleanup test case setup."""
        pass

    def test_get_nics(self):
        """Test the get_nics method."""
        guest = Mock()
        nics = []
        for k in range(0, 2):
            nic = Mock()
            network = Mock()
            nic.network = network
            nic.macAddress = 'mac' + str(k)
            ip_config = Mock()
            ip_addr = Mock()
            ip_addr.ipAddress = 'ip' + str(k)
            addresses = [ip_addr]
            ip_config.ipAddress = addresses
            nic.ipConfig = ip_config
            nics.append(nic)
        guest.net = nics
        mac_addresses, ip_addresses = get_nics(guest)
        self.assertEqual(mac_addresses, ['mac0', 'mac1'])
        self.assertEqual(ip_addresses, ['ip0', 'ip1'])

    def test__none(self):
        """Test get result method when no results exist."""
        results = self.runner.get_result()
        self.assertEqual(results, None)

    def test_get_result(self):
        """Test get results method when results exist."""
        inspect_result = TaskInspectionResult(source=self.source,
                                              scan_task=self.scan_task)
        inspect_result.save()
        self.inspect_results.results.add(inspect_result)
        self.inspect_results.save()
        results = self.runner.get_result()
        self.assertEqual(results, inspect_result)

    # pylint: disable=too-many-locals
    def test_get_vm_info(self):
        """Test the get vm info method."""
        data_center = 'dc1'
        cluster = 'cluster1'
        host = Mock()
        host_sum = Mock()
        host_config = Mock()
        host_config.name = 'host1'
        host_sum.config = host_config
        host_hard = Mock()
        host_hard.numCpuCores = 12
        host_hard.numCpuThreads = 24
        host_sum.hardware = host_hard
        host.summary = host_sum
        virtual_machine = Mock()
        summary = Mock()
        config = Mock()
        runtime = Mock()
        sum_guest = Mock()
        config.name = 'vm1'
        config.uuid = '1111'
        config.memorySizeMB = 1024
        config.numCpu = 2
        config.guestFullName = 'Red Hat 7'
        runtime.powerState = 'powerOn'
        sum_guest.hostName = 'hostname'
        summary.config = config
        summary.runtime = runtime
        summary.guest = sum_guest

        virtual_machine.summary = summary
        self.scan_task.update_stats('TEST_VC.',
                                    sys_count=5,
                                    sys_failed=0,
                                    sys_scanned=0)
        getnics = (['00:50:56:9e:09:8c'], ['1.2.3.4'])
        inspect_result = TaskInspectionResult(source=self.scan_task.source,
                                              scan_task=self.scan_task)
        inspect_result.save()
        self.inspect_results.results.add(inspect_result)
        self.inspect_results.save()
        with patch('scanner.vcenter.inspect.get_nics', return_value=getnics):
            self.runner.inspect_result = inspect_result
            self.runner.get_vm_info(data_center, cluster, host,
                                    virtual_machine)

            inspect_result = TaskInspectionResult.objects.filter(
                scan_task=self.scan_task.id).first()
            sys_results = inspect_result.systems.all()
            expected_facts = {
                'vm.cluster': 'cluster1',
                'vm.cpu_count': 2,
                'vm.datacenter': 'dc1',
                'vm.dns_name': 'hostname',
                'vm.host.cpu_cores': 12,
                'vm.host.cpu_count': 2,
                'vm.host.cpu_threads': 24,
                'vm.host.name': 'host1',
                'vm.ip_addresses': ['1.2.3.4'],
                'vm.mac_addresses': ['00:50:56:9e:09:8c'],
                'vm.memory_size': 1,
                'vm.name': 'vm1',
                'vm.os': 'Red Hat 7',
                'vm.state': 'powerOn',
                'vm.uuid': '1111'
            }
            sys_fact = {}
            for raw_fact in sys_results.first().facts.all():
                # Must read as JSON as this is what task.py does
                sys_fact[raw_fact.name] = json.loads(raw_fact.value)

            self.assertEqual(1, len(sys_results))
            self.assertEqual('vm1', sys_results.first().name)
            self.assertEqual(expected_facts, sys_fact)

    # pylint: disable=too-many-locals
    def test_recurse_datacenter(self):
        """Test the recurse_datacenter method."""
        inspect_result = TaskInspectionResult(source=self.scan_task.source,
                                              scan_task=self.scan_task)
        inspect_result.save()
        sys_result = SystemInspectionResult(
            name='vm1', status=SystemInspectionResult.SUCCESS)
        sys_result.save()
        inspect_result.systems.add(sys_result)
        inspect_result.save()
        self.inspect_results.results.add(inspect_result)
        self.inspect_results.save()
        vcenter = Mock()
        content = Mock()
        root_folder = Mock()
        child_entity = []
        for k in range(0, 2):
            child = Mock()
            child.name = 'dc' + str(k)
            host_folder = Mock()
            clusters = []
            for j in range(0, 1):
                cluster = Mock()
                cluster.name = 'cluster' + str(j)
                host = Mock()
                h_summary = Mock(name='h_summary')
                h_config = Mock(name='h_config')
                h_config.name = 'host1'
                h_summary.config = h_config
                host.summary = h_summary
                virtual_machine = Mock(name='vm')
                virtual_machine.summary.config.name = 'host1'
                host.vm = [virtual_machine]
                hosts = [host]
                cluster.host = hosts
                clusters.append(cluster)
            host_folder.childEntity = clusters
            child.hostFolder = host_folder
            child_entity.append(child)
        root_folder.childEntity = child_entity
        content.rootFolder = root_folder
        vcenter.RetrieveContent = Mock(return_value=content)
        with patch.object(InspectTaskRunner,
                          'get_vm_info') as mock_get_vm_info:
            self.runner.inspect_result = inspect_result
            self.runner.recurse_datacenter(vcenter)
            mock_get_vm_info.assert_called_with(ANY, ANY, ANY, ANY)

    def test_inspect(self):
        """Test the inspect method."""
        with patch('scanner.vcenter.inspect.vcenter_connect',
                   return_value=Mock()) as mock_vcenter_connect:
            with patch.object(InspectTaskRunner,
                              'recurse_datacenter') as mock_recurse:
                self.runner.connect_scan_task = self.conn_task
                self.runner.inspect()
                mock_vcenter_connect.assert_called_once_with(ANY)
                mock_recurse.assert_called_once_with(ANY)

    def test_failed_run(self):
        """Test the run method."""
        with patch.object(InspectTaskRunner,
                          'inspect',
                          side_effect=invalid_login) as mock_connect:
            status = self.runner.run()
            self.assertEqual(ScanTask.FAILED, status[1])
            mock_connect.assert_called_once_with()

    def test_prereq_failed(self):
        """Test the run method."""
        self.conn_task.status = ScanTask.FAILED
        self.conn_task.save()
        status = self.runner.run()
        self.assertEqual(ScanTask.FAILED, status[1])

    def test_run(self):
        """Test the run method."""
        with patch.object(InspectTaskRunner, 'inspect') as mock_connect:
            status = self.runner.run()
            self.assertEqual(ScanTask.COMPLETED, status[1])
            mock_connect.assert_called_once_with()
class InspectTaskRunnerTest(TestCase):
    """Tests Satellite connect capabilities."""

    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(
            name='cred1',
            cred_type=Credential.SATELLITE_CRED_TYPE,
            username='******',
            password='******')
        self.cred.save()

        self.source = Source(
            name='source1',
            port=443,
            hosts='["1.2.3.4"]')

        self.source.save()
        self.source.credentials.add(self.cred)

        self.scan_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                  source=self.source, sequence_number=2,
                                  start_time=datetime.utcnow())
        self.scan_task.save()
        self.scan_task.update_stats('TEST_SAT.', sys_scanned=0)

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT)
        self.scan_job.save()
        self.scan_job.tasks.add(self.scan_task)
        self.conn_results = JobConnectionResult()
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.conn_result = TaskConnectionResult(
            scan_task=self.scan_task, source=self.source)
        self.conn_result.save()

        conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT,
                             source=self.source, sequence_number=1,
                             start_time=datetime.utcnow())
        conn_task.complete()
        self.scan_task.prerequisites.add(conn_task)
        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results

        self.scan_job.save()

    def tearDown(self):
        """Cleanup test case setup."""
        pass

    def test_run_failed_prereq(self):
        """Test the running connect task with no source options."""
        self.scan_task.prerequisites.all().delete()
        conn_task = ScanTask(scan_type=ScanTask.SCAN_TYPE_CONNECT,
                             source=self.source, sequence_number=1)
        conn_task.status = ScanTask.FAILED
        conn_task.save()
        self.scan_task.prerequisites.add(conn_task)
        task = InspectTaskRunner(self.scan_job, self.scan_task)
        status = task.run()

        self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_no_source_options(self):
        """Test the running connect task with no source options."""
        task = InspectTaskRunner(self.scan_job, self.scan_task)
        status = task.run()

        self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_sat5_bad_status(self):
        """Test the running connect task for Satellite 5."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_5)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)
        with patch('scanner.satellite.connect.utils.status',
                   return_value=(401, None)) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_sat6_bad_status(self):
        """Test the running connect task for Sat 6 with bad status."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   return_value=(401, None)) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_sat6_bad_api_version(self):
        """Test the running connect task for Sat6 with bad api version."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   return_value=(200, 3)) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_with_conn_err(self):
        """Test the running connect task with connection error."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   side_effect=mock_conn_exception) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_with_sat_err(self):
        """Test the running connect task with satellite error."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   side_effect=mock_sat_exception) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_with_timeout(self):
        """Test the running connect task with timeout error."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   side_effect=mock_timeout_error) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_with_excep(self):
        """Test the running connect task with general exception."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   side_effect=mock_exception) as mock_sat_status:
            status = task.run()
            mock_sat_status.assert_called_once_with(ANY, ANY)
            self.assertEqual(status[1], ScanTask.FAILED)

    def test_run_with_sat(self):
        """Test the running connect task with satellite."""
        options = SourceOptions(
            satellite_version=SourceOptions.SATELLITE_VERSION_62)
        options.save()
        self.source.options = options
        self.source.save()
        task = InspectTaskRunner(self.scan_job, self.scan_task)

        with patch('scanner.satellite.connect.utils.status',
                   return_value=(200, 2)) as mock_sat_status:
            with patch.object(SatelliteSixV2, 'hosts_facts') as mock_facts:
                status = task.run()
                mock_sat_status.assert_called_once_with(ANY, ANY)
                mock_facts.assert_called_once_with()
                self.assertEqual(status[1], ScanTask.COMPLETED)
Beispiel #7
0
    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(
            name='cred1',
            username='******',
            password='******',
            ssh_keyfile=None,
            become_method=None,
            become_user=None,
            become_password=None)
        self.cred.save()

        hc_serializer = CredentialSerializer(self.cred)
        self.cred_data = hc_serializer.data

        self.source = Source(
            name='source1',
            port=22,
            hosts='["1.2.3.4"]')
        self.source.save()
        self.source.credentials.add(self.cred)

        self.host_list = [('1.2.3.4', self.cred_data)]
        self.connect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                          status=ScanTask.COMPLETED,
                                          start_time=datetime.utcnow())
        self.connect_scan_task.update_stats(
            'TEST NETWORK CONNECT.', sys_failed=0)

        self.inspect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                          start_time=datetime.utcnow())
        self.inspect_scan_task.update_stats(
            'TEST NETWORK INSPECT.', sys_failed=0)
        self.inspect_scan_task.prerequisites.add(self.connect_scan_task)
        self.inspect_scan_task.save()

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.scan_job.save()

        self.scan_job.tasks.add(self.connect_scan_task)
        self.scan_job.tasks.add(self.inspect_scan_task)
        scan_options = ScanOptions()
        scan_options.disable_optional_products = {'jboss_eap': False,
                                                  'jboss_fuse': False,
                                                  'jboss_brms': False}
        scan_options.save()
        self.scan_job.options = scan_options
        self.scan_job.save()

        self.fact_endpoint = 'http://testserver' + reverse('facts-list')

        self.conn_results = JobConnectionResult()
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.conn_result = TaskConnectionResult(
            scan_task=self.connect_scan_task, source=self.source)
        self.conn_result.save()

        success_sys = SystemConnectionResult(
            name='1.2.3.4', credential=self.cred,
            status=SystemConnectionResult.SUCCESS)
        success_sys.save()
        failed_sys = SystemConnectionResult(
            name='1.1.1.2', status=SystemConnectionResult.FAILED)
        failed_sys.save()
        self.conn_result.systems.add(success_sys)
        self.conn_result.systems.add(failed_sys)
        self.conn_result.save()
        self.conn_results.results.add(self.conn_result)
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results

        self.scan_job.save()
Beispiel #8
0
class NetworkInspectScannerTest(TestCase):
    """Tests network inspect scan task class."""

    # pylint: disable=too-many-instance-attributes, protected-access
    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(
            name='cred1',
            username='******',
            password='******',
            ssh_keyfile=None,
            become_method=None,
            become_user=None,
            become_password=None)
        self.cred.save()

        hc_serializer = CredentialSerializer(self.cred)
        self.cred_data = hc_serializer.data

        self.source = Source(
            name='source1',
            port=22,
            hosts='["1.2.3.4"]')
        self.source.save()
        self.source.credentials.add(self.cred)

        self.host_list = [('1.2.3.4', self.cred_data)]
        self.connect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                          status=ScanTask.COMPLETED,
                                          start_time=datetime.utcnow())
        self.connect_scan_task.update_stats(
            'TEST NETWORK CONNECT.', sys_failed=0)

        self.inspect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_INSPECT,
                                          start_time=datetime.utcnow())
        self.inspect_scan_task.update_stats(
            'TEST NETWORK INSPECT.', sys_failed=0)
        self.inspect_scan_task.prerequisites.add(self.connect_scan_task)
        self.inspect_scan_task.save()

        self.scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.scan_job.save()

        self.scan_job.tasks.add(self.connect_scan_task)
        self.scan_job.tasks.add(self.inspect_scan_task)
        scan_options = ScanOptions()
        scan_options.disable_optional_products = {'jboss_eap': False,
                                                  'jboss_fuse': False,
                                                  'jboss_brms': False}
        scan_options.save()
        self.scan_job.options = scan_options
        self.scan_job.save()

        self.fact_endpoint = 'http://testserver' + reverse('facts-list')

        self.conn_results = JobConnectionResult()
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.conn_result = TaskConnectionResult(
            scan_task=self.connect_scan_task, source=self.source)
        self.conn_result.save()

        success_sys = SystemConnectionResult(
            name='1.2.3.4', credential=self.cred,
            status=SystemConnectionResult.SUCCESS)
        success_sys.save()
        failed_sys = SystemConnectionResult(
            name='1.1.1.2', status=SystemConnectionResult.FAILED)
        failed_sys.save()
        self.conn_result.systems.add(success_sys)
        self.conn_result.systems.add(failed_sys)
        self.conn_result.save()
        self.conn_results.results.add(self.conn_result)
        self.conn_results.save()
        self.scan_job.connection_results = self.conn_results

        self.inspect_results = JobInspectionResult()
        self.inspect_results.save()
        self.scan_job.inspection_results = self.inspect_results

        self.scan_job.save()

    def test_scan_inventory(self):
        """Test construct ansible inventory dictionary."""
        serializer = SourceSerializer(self.source)
        source = serializer.data
        connection_port = source['port']
        inventory_dict = _construct_scan_inventory(self.host_list,
                                                   connection_port,
                                                   50)
        expected = {
            'all': {
                'children': {
                    'group_0': {
                        'hosts': {
                            '1.2.3.4': {
                                'ansible_user': '******',
                                'ansible_ssh_pass': '******',
                                'ansible_host': '1.2.3.4'}
                        }
                    }
                },
                'vars': {
                    'ansible_port': 22}
            }
        }

        self.assertEqual(inventory_dict[1], expected)

    def test_scan_inventory_grouping(self):
        """Test construct ansible inventory dictionary."""
        serializer = SourceSerializer(self.source)
        source = serializer.data
        connection_port = source['port']
        hc_serializer = CredentialSerializer(self.cred)
        cred = hc_serializer.data
        inventory_dict = _construct_scan_inventory(
            [
                ('1.2.3.1', cred),
                ('1.2.3.2', cred),
                ('1.2.3.3', cred),
                ('1.2.3.4', cred)
            ],
            connection_port,
            1)
        expected = {
            'all': {
                'children': {
                    'group_0': {
                        'hosts': {
                            '1.2.3.1': {
                                'ansible_user': '******',
                                'ansible_ssh_pass': '******',
                                'ansible_host': '1.2.3.1'}
                        }
                    },
                    'group_1': {
                        'hosts': {
                            '1.2.3.2': {
                                'ansible_user': '******',
                                'ansible_ssh_pass': '******',
                                'ansible_host': '1.2.3.2'}
                        }
                    },
                    'group_2': {
                        'hosts': {
                            '1.2.3.3': {
                                'ansible_user': '******',
                                'ansible_ssh_pass': '******',
                                'ansible_host': '1.2.3.3'}
                        }
                    },
                    'group_3': {
                        'hosts': {
                            '1.2.3.4': {
                                'ansible_user': '******',
                                'ansible_ssh_pass': '******',
                                'ansible_host': '1.2.3.4'}
                        }
                    }
                },
                'vars': {
                    'ansible_port': 22}
            }
        }

        self.assertEqual(inventory_dict[1], expected)

    @patch('scanner.network.utils.TaskQueueManager.run',
           side_effect=mock_run_failed)
    def test_inspect_scan_failure(self, mock_run):
        """Test scan flow with mocked manager and failure."""
        scanner = InspectTaskRunner(
            self.scan_job, self.inspect_scan_task)

        # Init for unit test as run is not called
        scanner.connect_scan_task = self.connect_scan_task
        with self.assertRaises(AnsibleError):
            scanner._inspect_scan(self.host_list)
            mock_run.assert_called()

    @patch('scanner.network.inspect.InspectTaskRunner._inspect_scan',
           side_effect=mock_scan_error)
    def test_inspect_scan_error(self, mock_scan):
        """Test scan flow with mocked manager and failure."""
        scanner = InspectTaskRunner(
            self.scan_job, self.inspect_scan_task)
        scan_task_status = scanner.run()
        mock_scan.assert_called_with(self.host_list)
        self.assertEqual(scan_task_status[1], ScanTask.FAILED)

    @patch('scanner.network.utils.TaskQueueManager.run',
           side_effect=mock_run_success)
    def test_inspect_scan_fail_no_facts(self, mock_run):
        """Test running a inspect scan with mocked connection."""
        expected = ([('1.2.3.4', {'name': 'cred1'})], [])
        mock_run.return_value = expected
        with requests_mock.Mocker() as mocker:
            mocker.post(self.fact_endpoint, status_code=201, json={'id': 1})
            scanner = InspectTaskRunner(
                self.scan_job, self.inspect_scan_task)
            scan_task_status = scanner.run()
            mock_run.assert_called_with(ANY)
            self.assertEqual(scan_task_status[1], ScanTask.FAILED)

    def test_populate_callback(self):
        """Test the population of the callback object for inspect scan."""
        callback = InspectResultCallback(
            scan_task=self.inspect_scan_task,
            inspect_results=self.inspect_results)
        host = Mock()
        host.name = '1.2.3.4'
        result = Mock(_host=host, _results={'rc': 3})

        callback.v2_runner_on_unreachable(result)

    def test_ssh_crash(self):
        """Simulate an ssh crash."""
        scanner = InspectTaskRunner(
            self.scan_job, self.inspect_scan_task)
        path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../../../test_util/crash.py'))
        _, result = scanner._inspect_scan(
            self.host_list,
            base_ssh_executable=path)
        self.assertEqual(result, ScanTask.FAILED)

    def test_ssh_hang(self):
        """Simulate an ssh hang."""
        scanner = InspectTaskRunner(
            self.scan_job, self.inspect_scan_task)
        path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         '../../../test_util/hang.py'))
        scanner._inspect_scan(
            self.host_list,
            roles=['redhat_release'],
            base_ssh_executable=path,
            ssh_timeout='0.1s')