def __init__(self,
                 project_id,
                 global_configs=None,
                 compute_client=None,
                 dry_run=False,
                 project_sema=None,
                 max_running_operations=0):
        """Initialize.

        Args:
            project_id (str): The project id for the project to enforce.
            global_configs (dict): Global configurations.
            compute_client (ComputeClient): A Compute API client.
                If not provided, one will be created using the default
                credentials.
            dry_run (bool): Set to true to ensure no actual changes are made to
                the project. EnforcePolicy will still return a ProjectResult
                proto showing the changes that would have been made.
            project_sema (threading.BoundedSemaphore): An optional semaphore
                object, used to limit the number of concurrent projects getting
                written to.
            max_running_operations (int): [DEPRECATED] Used to limit the number
                of concurrent running operations on an API.
        """
        self.project_id = project_id

        if not compute_client:
            compute_client = compute.ComputeClient(global_configs,
                                                   dry_run=dry_run)

        self.compute_client = compute_client

        self.result = enforcer_log_pb2.ProjectResult()
        self.result.status = STATUS_UNSPECIFIED
        self.result.project_id = self.project_id
        self.result.timestamp_sec = date_time.get_utc_now_microtimestamp()

        self._dry_run = dry_run

        self._project_sema = project_sema
        if max_running_operations:
            LOGGER.warning(
                'Max running operations is deprecated. Argument ignored.')

        self._operation_sema = None
    def test_enforce_single_project(self):
        """Verifies enforce_single_project returns the correct results.

      Setup:
        * Set API calls to return the different firewall rules from the new
          policy on the first call, and the expected new firewall rules on the
          second call.
        * Load a mock policy file.
        * Create a temporary directory for writing the dremel recordio table out
          to.
        * Send the policy and project to EnforceSingleProject.

      Expected Results:
        * The results proto returned matches the expected results.
      """
        self.gce_api_client.get_firewall_rules.side_effect = [
            constants.DEFAULT_FIREWALL_API_RESPONSE,
            constants.EXPECTED_FIREWALL_API_RESPONSE
        ]

        policy_filename = get_datafile_path(__file__, 'sample_policy.json')

        results = enforcer.enforce_single_project(self.enforcer, self.project,
                                                  policy_filename)

        self.expected_summary.projects_total = 1
        self.expected_summary.projects_success = 1
        self.expected_summary.projects_changed = 1
        self.expected_summary.projects_unchanged = 0

        self.assertEqual(self.expected_summary, results.summary)

        expected_results = enforcer_log_pb2.ProjectResult()
        text_format.Merge(constants.SAMPLE_ENFORCER_PROJECTRESULTS_ASCIIPB,
                          expected_results)
        expected_results.run_context = enforcer_log_pb2.ENFORCER_ONE_PROJECT
        expected_results.gce_firewall_enforcement.policy_path = policy_filename

        project_result = results.results[0]

        self.assertEqual(expected_results, project_result)
Exemplo n.º 3
0
    def setUp(self):
        """Set up."""
        super(ProjectEnforcerTest, self).setUp()
        self.enforcer = project_enforcer.ProjectEnforcer(
            self.project, compute_client=self.gce_api_client, dry_run=True)

        self.expected_proto = enforcer_log_pb2.ProjectResult(
            timestamp_sec=constants.MOCK_MICROTIMESTAMP,
            project_id=self.project)

        self.expected_rules = copy.deepcopy(
            constants.EXPECTED_FIREWALL_RULES.values())

        response_403 = httplib2.Response({
            'status': '403',
            'content-type': 'application/json'
        })
        response_403.reason = 'Failed'
        self.error_403 = errors.HttpError(response_403, '', uri='')

        self.addCleanup(mock.patch.stopall)
 def result_callback(result):
     expected_result = enforcer_log_pb2.ProjectResult()
     text_format.Merge(constants.SAMPLE_ENFORCER_PROJECTRESULTS_ASCIIPB,
                       expected_result)
     self.assertEqual(expected_result, result)
     callback_called[0] += 1