예제 #1
0
 def test_list_alert_policies(self):
     client = monitoring_v3.AlertPolicyServiceClient()
     name_inside = client.project_path(PROJECT_INSIDE)
     delayed_inside = lambda: client.list_alert_policies(name_inside)
     name_outside = client.project_path(PROJECT_OUTSIDE)
     delayed_outside = lambda: client.list_alert_policies(name_outside)
     self._do_test(delayed_inside, delayed_outside)
    def test_update_alert_policy(self):
        # Setup Expected Response
        name = "name3373707"
        display_name = "displayName1615086568"
        expected_response = {"name": name, "display_name": display_name}
        expected_response = alert_pb2.AlertPolicy(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup Request
        alert_policy = {}

        response = client.update_alert_policy(alert_policy)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.UpdateAlertPolicyRequest(
            alert_policy=alert_policy
        )
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_create_alert_policy(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        display_name = 'displayName1615086568'
        expected_response = {'name': name_2, 'display_name': display_name}
        expected_response = alert_pb2.AlertPolicy(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch('google.api_core.grpc_helpers.create_channel')
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup Request
        name = client.project_path('[PROJECT]')
        alert_policy = {}

        response = client.create_alert_policy(name, alert_policy)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.CreateAlertPolicyRequest(
            name=name, alert_policy=alert_policy)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_list_alert_policies(self):
        # Setup Expected Response
        next_page_token = ""
        alert_policies_element = {}
        alert_policies = [alert_policies_element]
        expected_response = {
            "next_page_token": next_page_token,
            "alert_policies": alert_policies,
        }
        expected_response = alert_service_pb2.ListAlertPoliciesResponse(
            **expected_response
        )

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup Request
        name = client.project_path("[PROJECT]")

        paged_list_response = client.list_alert_policies(name)
        resources = list(paged_list_response)
        assert len(resources) == 1

        assert expected_response.alert_policies[0] == resources[0]

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.ListAlertPoliciesRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
예제 #5
0
 def test_get_alert_policy(self):
     client = monitoring_v3.AlertPolicyServiceClient()
     name_inside = client.alert_policy_path(PROJECT_INSIDE, "mock_alert_policy")
     delayed_inside = lambda: client.get_alert_policy(name_inside)
     name_outside = client.alert_policy_path(PROJECT_OUTSIDE, "mock_alert_policy")
     delayed_outside = lambda: client.get_alert_policy(name_outside)
     TestVPCServiceControlV3._do_test(delayed_inside, delayed_outside)
예제 #6
0
 def test_create_alert_policy(self):
     client = monitoring_v3.AlertPolicyServiceClient()
     name_inside = client.project_path(PROJECT_INSIDE)
     delayed_inside = lambda: client.create_alert_policy(name_inside, {})
     name_outside = client.project_path(PROJECT_OUTSIDE)
     delayed_outside = lambda: client.create_alert_policy(name_outside, {})
     TestVPCServiceControlV3._do_test(delayed_inside, delayed_outside)
    def test_list_alert_policies(self):
        # Setup Expected Response
        next_page_token = ''
        alert_policies_element = {}
        alert_policies = [alert_policies_element]
        expected_response = {
            'next_page_token': next_page_token,
            'alert_policies': alert_policies
        }
        expected_response = alert_service_pb2.ListAlertPoliciesResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup Request
        name = client.project_path('[PROJECT]')

        paged_list_response = client.list_alert_policies(name)
        resources = list(paged_list_response)
        assert len(resources) == 1

        assert expected_response.alert_policies[0] == resources[0]

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.ListAlertPoliciesRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
예제 #8
0
def enable_alert_policies(project_name, enable, filter_=None):
    """Enable or disable alert policies in a project.

    Arguments:
        project_name (str)
        enable (bool): Enable or disable the policies.
        filter_ (str, optional): Only enable/disable alert policies that match
            this filter_.  See
            https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
    """

    client = monitoring_v3.AlertPolicyServiceClient()
    policies = client.list_alert_policies(
        request={"name": project_name, "filter": filter_}
    )

    for policy in policies:
        if bool(enable) == policy.enabled:
            print(
                "Policy",
                policy.name,
                "is already",
                "enabled" if policy.enabled else "disabled",
            )
        else:
            policy.enabled = bool(enable)
            mask = field_mask.FieldMask()
            mask.paths.append("enabled")
            client.update_alert_policy(alert_policy=policy, update_mask=mask)
            print("Enabled" if enable else "Disabled", policy.name)
예제 #9
0
def structured_backup(
        folder=backup_folder(),
        project_name=project_name(), permissions=0o755):
    folder = os.path.join(folder,
                          datetime.datetime.now().strftime("%Y%m%d%H%M"))
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()

    if os.path.exists(folder):
        raise FileExistsError

    os.mkdir(folder)
    os.mkdir(os.path.join(folder, "policies"), permissions)
    os.mkdir(os.path.join(folder, "channels"), permissions)

    for policy in alert_client.list_alert_policies(project_name):
        json.dump(policy,
                  open(
                      os.path.join(folder, "policies",
                                   __sanitize_filename(policy.display_name)),
                      'wt'),
                  cls=ProtoEncoder,
                  indent=2)
    for channel in channel_client.list_notification_channels(project_name):
        json.dump(channel,
                  open(
                      os.path.join(folder, "channels",
                                   __sanitize_filename(channel.display_name)),
                      'wt'),
                  cls=ProtoEncoder,
                  indent=2)
    print('Backed up alert policies and notification channels to {}.'.format(
        folder))
예제 #10
0
def list_alert_policies(project_name):
    client = monitoring_v3.AlertPolicyServiceClient()
    policies = client.list_alert_policies(name=project_name)
    print(
        tabulate.tabulate(
            [(policy.name, policy.display_name) for policy in policies],
            ("name", "display_name"),
        ))
    def test_list_alert_policies_exception(self):
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup request
        name = client.project_path('[PROJECT]')

        paged_list_response = client.list_alert_policies(name)
        with pytest.raises(CustomException):
            list(paged_list_response)
    def test_update_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup request
        alert_policy = {}

        with pytest.raises(CustomException):
            client.update_alert_policy(alert_policy)
    def test_delete_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup request
        name = client.alert_policy_path('[PROJECT]', '[ALERT_POLICY]')

        with pytest.raises(CustomException):
            client.delete_alert_policy(name)
예제 #14
0
    def testUptimeCheckAlertingPolicy(self):
        """ Test that an alerting policy was created. """
        client = monitoring_v3.AlertPolicyServiceClient()
        policies = client.list_alert_policies(project_name)
        found_uptime_alert = False
        for policy in policies:
            if policy.display_name == 'HTTP Uptime Check Alerting Policy':
                found_uptime_alert = True

        self.assertTrue(found_uptime_alert)
예제 #15
0
def cleanupPolicies(project_name):
    """ Delete all alerting policies for both uptime checks and SLOs. """
    client = monitoring_v3.AlertPolicyServiceClient()
    policies = True
    while policies:
        policies = list(client.list_alert_policies(project_name))
        for policy in policies:
            try:
                client.delete_alert_policy(policy.name)
            except:
                print('Could not delete alerting policy: ' + policy.name)
    def test_create_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup request
        name = client.project_path('[PROJECT]')
        alert_policy = {}

        with pytest.raises(CustomException):
            client.create_alert_policy(name, alert_policy)
예제 #17
0
파일: snippets.py 프로젝트: rotiller/stt
def backup(project_name):
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    record = {
        'project_name': project_name,
        'policies': list(alert_client.list_alert_policies(project_name)),
        'channels':
        list(channel_client.list_notification_channels(project_name))
    }
    json.dump(record, open('backup.json', 'wt'), cls=ProtoEncoder, indent=2)
    print('Backed up alert policies and notification channels to backup.json.')
예제 #18
0
 def test_update_alert_policy(self):
     client = monitoring_v3.AlertPolicyServiceClient()
     name_inside = client.alert_policy_path(PROJECT_INSIDE,
                                            "mock_alert_policy")
     delayed_inside = lambda: client.update_alert_policy(
         {"name": name_inside})
     name_outside = client.alert_policy_path(PROJECT_OUTSIDE,
                                             "mock_alert_policy")
     delayed_outside = lambda: client.update_alert_policy(
         {"name": name_outside})
     self._do_test(delayed_inside, delayed_outside)
예제 #19
0
def create_ca_monitor_policy(project_id: str) -> None:
    """
    Create a monitoring policy that notifies you 30 days before a managed CA expires.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
    """

    alertPolicyServiceClient = monitoring_v3.AlertPolicyServiceClient()
    notificationChannelServiceClient = monitoring_v3.NotificationChannelServiceClient(
    )

    # Query which indicates the resource to monitor and the constraints.
    # Here, the alert policy notifies you 30 days before a managed CA expires.
    # For more information on creating queries, see: https://cloud.google.com/monitoring/mql/alerts
    query = (
        "fetch privateca.googleapis.com/CertificateAuthority"
        "| metric 'privateca.googleapis.com/ca/cert_chain_expiration'"
        "| group_by 5m,"
        "[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]"
        "| every 5m"
        "| condition val() < 2.592e+06 's'")

    # Create a notification channel.
    notification_channel = monitoring_v3.NotificationChannel(
        type_="email",
        labels={"email_address": "*****@*****.**"},
    )
    channel = notificationChannelServiceClient.create_notification_channel(
        name=notificationChannelServiceClient.common_project_path(project_id),
        notification_channel=notification_channel,
    )

    # Set the query and notification channel.
    alert_policy = monitoring_v3.AlertPolicy(
        display_name="policy-name",
        conditions=[
            monitoring_v3.AlertPolicy.Condition(
                display_name="ca-cert-chain-expiration",
                condition_monitoring_query_language=monitoring_v3.AlertPolicy.
                Condition.MonitoringQueryLanguageCondition(query=query, ),
            )
        ],
        combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND,
        notification_channels=[channel.name],
    )

    policy = alertPolicyServiceClient.create_alert_policy(
        name=notificationChannelServiceClient.common_project_path(project_id),
        alert_policy=alert_policy,
    )

    print("Monitoring policy successfully created!", policy.name)
    def test_list_alert_policies_exception(self):
        channel = ChannelStub(responses=[CustomException()])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup request
        name = client.project_path("[PROJECT]")

        paged_list_response = client.list_alert_policies(name)
        with pytest.raises(CustomException):
            list(paged_list_response)
    def test_update_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup request
        alert_policy = {}

        with pytest.raises(CustomException):
            client.update_alert_policy(alert_policy)
    def test_delete_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup request
        name = client.alert_policy_path("[PROJECT]", "[ALERT_POLICY]")

        with pytest.raises(CustomException):
            client.delete_alert_policy(name)
예제 #23
0
def backup(project_name, backup_filename):
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    record = {
        "project_name": project_name,
        "policies": list(alert_client.list_alert_policies(name=project_name)),
        "channels": list(channel_client.list_notification_channels(name=project_name)),
    }
    json.dump(record, open(backup_filename, "wt"), cls=ProtoEncoder, indent=2)
    print(
        "Backed up alert policies and notification channels to {}.".format(
            backup_filename
        )
    )
    def test_delete_alert_policy(self):
        channel = ChannelStub()
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup Request
        name = client.alert_policy_path('[PROJECT]', '[ALERT_POLICY]')

        client.delete_alert_policy(name)

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.DeleteAlertPolicyRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_create_alert_policy_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        patch = mock.patch('google.api_core.grpc_helpers.create_channel')
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup request
        name = client.project_path('[PROJECT]')
        alert_policy = {}

        with pytest.raises(CustomException):
            client.create_alert_policy(name, alert_policy)
예제 #26
0
파일: snippets.py 프로젝트: rotiller/stt
def replace_notification_channels(project_name, alert_policy_id, channel_ids):
    _, project_id = project_name.split('/')
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    policy = monitoring_v3.types.alert_pb2.AlertPolicy()
    policy.name = alert_client.alert_policy_path(project_id, alert_policy_id)

    for channel_id in channel_ids:
        policy.notification_channels.append(
            channel_client.notification_channel_path(project_id, channel_id))

    mask = monitoring_v3.types.field_mask_pb2.FieldMask()
    mask.paths.append('notification_channels')
    updated_policy = alert_client.update_alert_policy(policy, mask)
    print('Updated', updated_policy.name)
    def test_delete_alert_policy(self):
        channel = ChannelStub()
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = monitoring_v3.AlertPolicyServiceClient()

        # Setup Request
        name = client.alert_policy_path("[PROJECT]", "[ALERT_POLICY]")

        client.delete_alert_policy(name)

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.DeleteAlertPolicyRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
예제 #28
0
def replace_notification_channels(project_name, alert_policy_id, channel_ids):
    _, project_id = project_name.split("/")
    alert_client = monitoring_v3.AlertPolicyServiceClient()
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    policy = monitoring_v3.AlertPolicy()
    policy.name = alert_client.alert_policy_path(project_id, alert_policy_id)

    for channel_id in channel_ids:
        policy.notification_channels.append(
            channel_client.notification_channel_path(project_id, channel_id))

    mask = field_mask.FieldMask()
    mask.paths.append("notification_channels")
    updated_policy = alert_client.update_alert_policy(alert_policy=policy,
                                                      update_mask=mask)
    print("Updated", updated_policy.name)
예제 #29
0
    def __init__(self):
        self.project_id = snippets.project_id()
        self.project_name = snippets.project_name()
        self.alert_policy_client = monitoring_v3.AlertPolicyServiceClient()
        self.notification_channel_client = (
            monitoring_v3.NotificationChannelServiceClient()
        )

        # delete all existing policies older than 1 hour prior to testing
        for policy in self.alert_policy_client.list_alert_policies(name=self.project_name):
            seconds_since_creation = datetime.timestamp(datetime.utcnow())-datetime.timestamp(policy.creation_record.mutate_time)
            if seconds_since_creation > 3600:
                try:
                    self.alert_policy_client.delete_alert_policy(
                        name=policy.name
                    )
                except NotFound:
                    print("Ignored NotFound when deleting a policy.")
    def test_get_alert_policy(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        display_name = 'displayName1615086568'
        expected_response = {'name': name_2, 'display_name': display_name}
        expected_response = alert_pb2.AlertPolicy(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = monitoring_v3.AlertPolicyServiceClient(channel=channel)

        # Setup Request
        name = client.alert_policy_path('[PROJECT]', '[ALERT_POLICY]')

        response = client.get_alert_policy(name)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = alert_service_pb2.GetAlertPolicyRequest(name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request