Ejemplo n.º 1
0
 def test_get_results(self):
     """Test get results method when results exist."""
     conn_result = ConnectionResult(source=self.source,
                                    scan_task=self.scan_task)
     conn_result.save()
     self.conn_results.results.add(conn_result)
     self.conn_results.save()
     results = self.runner.get_results()
     self.assertEqual(results, conn_result)
Ejemplo n.º 2
0
    def test_expand_sys_conn_result(self):
        """Test view expand_sys_conn_result."""
        scan_job = ScanJob(scan_type=ScanTask.SCAN_TYPE_CONNECT)
        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_result = ConnectionResult(source=conn_task.source,
                                       scan_task=conn_task)
        conn_result.save()

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

        result = expand_sys_conn_result(conn_result)
        self.assertEqual(result[0]['credential']['name'], 'cred1')
Ejemplo n.º 3
0
    def _store_connect_result(self, connected, failed_hosts):
        result = {}
        conn_result = ConnectionResult(scan_task=self.scan_task,
                                       source=self.scan_task.source)
        conn_result.save()

        for success in connected:
            result[success[0]] = success[1]
            # pylint: disable=no-member
            cred = Credential.objects.get(pk=success[1]['id'])
            sys_result = SystemConnectionResult(
                name=success[0],
                status=SystemConnectionResult.SUCCESS,
                credential=cred)
            sys_result.save()
            conn_result.systems.add(sys_result)

        for failed in failed_hosts:
            result[failed] = None
            sys_result = SystemConnectionResult(
                name=failed, status=SystemConnectionResult.FAILED)
            sys_result.save()
            conn_result.systems.add(sys_result)

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

        return result
Ejemplo n.º 4
0
    def _store_connect_data(self, connected, credential):
        conn_result = ConnectionResult(source=self.scan_task.source,
                                       scan_task=self.scan_task)
        conn_result.save()

        for system in connected:
            sys_result = SystemConnectionResult(
                name=system, status=SystemConnectionResult.SUCCESS,
                credential=credential)
            sys_result.save()
            conn_result.systems.add(sys_result)

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

        # Update the scan counts
        if self.scan_task.systems_count is None:
            self.scan_task.systems_count = len(connected)
            self.scan_task.systems_scanned = 0
        self.scan_task.systems_scanned = len(connected)
        self.scan_task.save()
Ejemplo n.º 5
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 = ConnectionResults(scan_job=scan_job)
        conn_results.save()

        conn_result = ConnectionResult(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 = InspectionResults(scan_job=scan_job)
        inspect_results.save()

        inspect_result = InspectionResult(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()

        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': {
                    'scan_job': 1,
                    'results': []
                },
                'inspection_results': {
                    'scan_job': 1,
                    'results': []
                }
            })
Ejemplo n.º 6
0
    def setUp(self):
        """Create test case setup."""
        self.cred = Credential(name='cred1',
                               username='******',
                               password='******',
                               sudo_password=None,
                               ssh_keyfile=None)
        self.cred.save()

        self.source = Source(name='source1', port=22)
        self.source.save()
        self.source.credentials.add(self.cred)

        self.host = HostRange(host_range='1.2.3.4', source_id=self.source.id)
        self.host.save()

        self.source.hosts.add(self.host)

        self.connect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                          status=ScanTask.COMPLETED)
        self.connect_scan_task.systems_failed = 0
        self.connect_scan_task.save()

        self.inspect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.inspect_scan_task.systems_failed = 0
        self.inspect_scan_task.save()
        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.save()
        self.scan_job.options = scan_options
        self.scan_job.save()

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

        self.conn_results = ConnectionResults(scan_job=self.scan_job)
        self.conn_results.save()

        self.conn_result = ConnectionResult(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.inspect_results = InspectionResults(scan_job=self.scan_job)
        self.inspect_results.save()
Ejemplo n.º 7
0
class HostScannerTest(TestCase):
    """Tests against the HostScanner class and functions."""

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

        self.source = Source(name='source1', port=22)
        self.source.save()
        self.source.credentials.add(self.cred)

        self.host = HostRange(host_range='1.2.3.4', source_id=self.source.id)
        self.host.save()

        self.source.hosts.add(self.host)

        self.connect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_CONNECT,
                                          status=ScanTask.COMPLETED)
        self.connect_scan_task.systems_failed = 0
        self.connect_scan_task.save()

        self.inspect_scan_task = ScanTask(source=self.source,
                                          scan_type=ScanTask.SCAN_TYPE_INSPECT)
        self.inspect_scan_task.systems_failed = 0
        self.inspect_scan_task.save()
        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.save()
        self.scan_job.options = scan_options
        self.scan_job.save()

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

        self.conn_results = ConnectionResults(scan_job=self.scan_job)
        self.conn_results.save()

        self.conn_result = ConnectionResult(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.inspect_results = InspectionResults(scan_job=self.scan_job)
        self.inspect_results.save()

    def test_scan_inventory(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.4', cred)],
                                                  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,
                                    self.inspect_results)

        # Init for unit test as run is not called
        scanner.connect_scan_task = self.connect_scan_task
        with self.assertRaises(AnsibleError):
            scanner.inspect_scan()
            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,
                                    self.inspect_results)
        scan_task_status = scanner.run()
        mock_scan.assert_called_with()
        self.assertEqual(scan_task_status, 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,
                                        self.inspect_results)
            scan_task_status = scanner.run()
            mock_run.assert_called_with(ANY)
            self.assertEqual(scan_task_status, ScanTask.FAILED)

    def test_populate_callback(self):
        """Test the population of the callback object for inspect scan."""
        callback = ResultCallback(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)