def test_stackdriver_disable_alert_policy(self, mock_policy_client, mock_get_creds_and_project_id): hook = stackdriver.StackdriverHook() alert_policy_enabled = AlertPolicy(**TEST_ALERT_POLICY_1) alert_policy_disabled = AlertPolicy(**TEST_ALERT_POLICY_2) mock_policy_client.return_value.list_alert_policies.return_value = [ alert_policy_enabled, alert_policy_disabled, ] hook.disable_alert_policies( filter_=TEST_FILTER, project_id=PROJECT_ID, ) mock_policy_client.return_value.list_alert_policies.assert_called_once_with( request=dict(name=f'projects/{PROJECT_ID}', filter=TEST_FILTER, order_by=None, page_size=None), retry=DEFAULT, timeout=DEFAULT, metadata=(), ) mask = FieldMask(paths=["enabled"]) alert_policy_enabled.enabled = False # pylint: disable=no-member mock_policy_client.return_value.update_alert_policy.assert_called_once_with( request=dict(alert_policy=alert_policy_enabled, update_mask=mask), retry=DEFAULT, timeout=DEFAULT, metadata=(), )
def list_alert_policies( self, project_id: str = PROVIDE_PROJECT_ID, format_: Optional[str] = None, filter_: Optional[str] = None, order_by: Optional[str] = None, page_size: Optional[int] = None, retry: Optional[str] = DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> Any: """ Fetches all the Alert Policies identified by the filter passed as filter parameter. The desired return type can be specified by the format parameter, the supported formats are "dict", "json" and None which returns python dictionary, stringified JSON and protobuf respectively. :param format_: (Optional) Desired output format of the result. The supported formats are "dict", "json" and None which returns python dictionary, stringified JSON and protobuf respectively. :param filter_: If provided, this field specifies the criteria that must be met by alert policies to be included in the response. For more details, see https://cloud.google.com/monitoring/api/v3/sorting-and-filtering. :param order_by: A comma-separated list of fields by which to sort the result. Supports the same set of field references as the ``filter`` field. Entries can be prefixed with a minus sign to sort by the field in descending order. For more details, see https://cloud.google.com/monitoring/api/v3/sorting-and-filtering. :param page_size: The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param project_id: The project to fetch alerts from. """ client = self._get_policy_client() policies_ = client.list_alert_policies( request={ 'name': f'projects/{project_id}', 'filter': filter_, 'order_by': order_by, 'page_size': page_size, }, retry=retry, timeout=timeout, metadata=metadata, ) if format_ == "dict": return [AlertPolicy.to_dict(policy) for policy in policies_] elif format_ == "json": return [AlertPolicy.to_jsoon(policy) for policy in policies_] else: return policies_
def test_stackdriver_upsert_alert_policy(self, mock_channel_client, mock_policy_client, mock_get_creds_and_project_id): hook = stackdriver.StackdriverHook() existing_alert_policy = AlertPolicy(**TEST_ALERT_POLICY_1) alert_policy_to_create = AlertPolicy(**TEST_ALERT_POLICY_2) mock_policy_client.return_value.list_alert_policies.return_value = [ existing_alert_policy ] mock_channel_client.return_value.list_notification_channels.return_value = [] hook.upsert_alert( alerts=json.dumps({ "policies": [TEST_ALERT_POLICY_1, TEST_ALERT_POLICY_2], "channels": [] }), project_id=PROJECT_ID, ) mock_channel_client.return_value.list_notification_channels.assert_called_once_with( request=dict( name=f'projects/{PROJECT_ID}', filter=None, order_by=None, page_size=None, ), retry=DEFAULT, timeout=DEFAULT, metadata=(), ) mock_policy_client.return_value.list_alert_policies.assert_called_once_with( request=dict(name=f'projects/{PROJECT_ID}', filter=None, order_by=None, page_size=None), retry=DEFAULT, timeout=DEFAULT, metadata=(), ) alert_policy_to_create.name = None alert_policy_to_create.creation_record = None alert_policy_to_create.mutation_record = None # pylint: disable=unsubscriptable-object alert_policy_to_create.conditions[0].name = None mock_policy_client.return_value.create_alert_policy.assert_called_once_with( request=dict( name=f'projects/{PROJECT_ID}', alert_policy=alert_policy_to_create, ), retry=DEFAULT, timeout=DEFAULT, metadata=(), ) existing_alert_policy.creation_record = None existing_alert_policy.mutation_record = None mock_policy_client.return_value.update_alert_policy.assert_called_once_with( request=dict(alert_policy=existing_alert_policy), retry=DEFAULT, timeout=DEFAULT, metadata=())
def execute(self, context: 'Context'): self.log.info( 'List Alert Policies: Project id: %s Format: %s Filter: %s Order By: %s Page Size: %s', self.project_id, self.format_, self.filter_, self.order_by, self.page_size, ) if self.hook is None: self.hook = StackdriverHook( gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, impersonation_chain=self.impersonation_chain, ) result = self.hook.list_alert_policies( project_id=self.project_id, format_=self.format_, filter_=self.filter_, order_by=self.order_by, page_size=self.page_size, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) return [AlertPolicy.to_dict(policy) for policy in result]
def test_execute(self, mock_hook): operator = StackdriverListAlertPoliciesOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER) mock_hook.return_value.list_alert_policies.return_value = [ AlertPolicy(name="test-name") ] result = operator.execute(None) mock_hook.return_value.list_alert_policies.assert_called_once_with( project_id=None, filter_=TEST_FILTER, format_=None, order_by=None, page_size=None, retry=DEFAULT, timeout=DEFAULT, metadata=None, ) assert [{ 'combiner': 0, 'conditions': [], 'display_name': '', 'name': 'test-name', 'notification_channels': [], 'user_labels': {}, }] == result
def upsert_alert( self, alerts: str, project_id: str = PROVIDE_PROJECT_ID, retry: Optional[str] = DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: """ Creates a new alert or updates an existing policy identified the name field in the alerts parameter. :param project_id: The project in which alert needs to be created/updated. :param alerts: A JSON string or file that specifies all the alerts that needs to be either created or updated. For more details, see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies#AlertPolicy. (templated) :param retry: A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. """ policy_client = self._get_policy_client() channel_client = self._get_channel_client() record = json.loads(alerts) existing_policies = [ policy['name'] for policy in self.list_alert_policies(project_id=project_id, format_='dict') ] existing_channels = [ channel['name'] for channel in self.list_notification_channels( project_id=project_id, format_='dict') ] policies_ = [] channels = [] for channel in record.get("channels", []): channels.append(NotificationChannel(**channel)) for policy in record.get("policies", []): policies_.append(AlertPolicy(**policy)) channel_name_map = {} for channel in channels: channel.verification_status = ( monitoring_v3.NotificationChannel.VerificationStatus. VERIFICATION_STATUS_UNSPECIFIED) if channel.name in existing_channels: channel_client.update_notification_channel( request={'notification_channel': channel}, retry=retry, timeout=timeout, metadata=metadata, ) else: old_name = channel.name channel.name = None new_channel = channel_client.create_notification_channel( request={ 'name': f'projects/{project_id}', 'notification_channel': channel }, retry=retry, timeout=timeout, metadata=metadata, ) channel_name_map[old_name] = new_channel.name for policy in policies_: policy.creation_record = None policy.mutation_record = None for i, channel in enumerate(policy.notification_channels): new_channel = channel_name_map.get(channel) if new_channel: policy.notification_channels[i] = new_channel if policy.name in existing_policies: try: policy_client.update_alert_policy( request={'alert_policy': policy}, retry=retry, timeout=timeout, metadata=metadata, ) except InvalidArgument: pass else: policy.name = None for condition in policy.conditions: condition.name = None policy_client.create_alert_policy( request={ 'name': f'projects/{project_id}', 'alert_policy': policy }, retry=retry, timeout=timeout, metadata=metadata, )