Ejemplo n.º 1
0
    def test_list_notification_channel_descriptors(self):
        # Setup Expected Response
        next_page_token = ""
        channel_descriptors_element = {}
        channel_descriptors = [channel_descriptors_element]
        expected_response = {
            "next_page_token": next_page_token,
            "channel_descriptors": channel_descriptors,
        }
        expected_response = notification_service_pb2.ListNotificationChannelDescriptorsResponse(
            **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.NotificationChannelServiceClient()

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

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

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.ListNotificationChannelDescriptorsRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_create_notification_channel(self):
        # Setup Expected Response
        type_ = 'type3575610'
        name_2 = 'name2-1052831874'
        display_name = 'displayName1615086568'
        description = 'description-1724546052'
        expected_response = {
            'type': type_,
            'name': name_2,
            'display_name': display_name,
            'description': description
        }
        expected_response = notification_pb2.NotificationChannel(
            **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.NotificationChannelServiceClient()

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

        response = client.create_notification_channel(name,
                                                      notification_channel)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.CreateNotificationChannelRequest(
            name=name, notification_channel=notification_channel)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Ejemplo n.º 3
0
    def test_get_notification_channel_verification_code(self):
        # Setup Expected Response
        code = "code3059181"
        expected_response = {"code": code}
        expected_response = notification_service_pb2.GetNotificationChannelVerificationCodeResponse(
            **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.NotificationChannelServiceClient()

        # Setup Request
        name = client.notification_channel_path("[PROJECT]",
                                                "[NOTIFICATION_CHANNEL]")

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.GetNotificationChannelVerificationCodeRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_update_notification_channel(self):
        # Setup Expected Response
        type_ = 'type3575610'
        name = 'name3373707'
        display_name = 'displayName1615086568'
        description = 'description-1724546052'
        expected_response = {
            'type': type_,
            'name': name,
            'display_name': display_name,
            'description': description
        }
        expected_response = notification_pb2.NotificationChannel(
            **expected_response)

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

        # Setup Request
        notification_channel = {}

        response = client.update_notification_channel(notification_channel)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.UpdateNotificationChannelRequest(
            notification_channel=notification_channel)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_list_notification_channel_descriptors(self):
        # Setup Expected Response
        next_page_token = ''
        channel_descriptors_element = {}
        channel_descriptors = [channel_descriptors_element]
        expected_response = {
            'next_page_token': next_page_token,
            'channel_descriptors': channel_descriptors
        }
        expected_response = notification_service_pb2.ListNotificationChannelDescriptorsResponse(
            **expected_response)

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

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

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

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.ListNotificationChannelDescriptorsRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Ejemplo n.º 6
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))
    def test_list_notification_channels(self):
        # Setup Expected Response
        next_page_token = ''
        notification_channels_element = {}
        notification_channels = [notification_channels_element]
        expected_response = {
            'next_page_token': next_page_token,
            'notification_channels': notification_channels
        }
        expected_response = notification_service_pb2.ListNotificationChannelsResponse(
            **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.NotificationChannelServiceClient()

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

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

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.ListNotificationChannelsRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_get_notification_channel(self):
        # Setup Expected Response
        type_ = 'type3575610'
        name_2 = 'name2-1052831874'
        display_name = 'displayName1615086568'
        description = 'description-1724546052'
        expected_response = {
            'type': type_,
            'name': name_2,
            'display_name': display_name,
            'description': description
        }
        expected_response = notification_pb2.NotificationChannel(
            **expected_response)

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

        # Setup Request
        name = client.notification_channel_path('[PROJECT]',
                                                '[NOTIFICATION_CHANNEL]')

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.GetNotificationChannelRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Ejemplo n.º 9
0
    def test_update_notification_channel(self):
        # Setup Expected Response
        type_ = "type3575610"
        name = "name3373707"
        display_name = "displayName1615086568"
        description = "description-1724546052"
        expected_response = {
            "type": type_,
            "name": name,
            "display_name": display_name,
            "description": description,
        }
        expected_response = notification_pb2.NotificationChannel(
            **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.NotificationChannelServiceClient()

        # Setup Request
        notification_channel = {}

        response = client.update_notification_channel(notification_channel)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.UpdateNotificationChannelRequest(
            notification_channel=notification_channel)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Ejemplo n.º 10
0
    def test_get_notification_channel(self):
        # Setup Expected Response
        type_ = "type3575610"
        name_2 = "name2-1052831874"
        display_name = "displayName1615086568"
        description = "description-1724546052"
        expected_response = {
            "type": type_,
            "name": name_2,
            "display_name": display_name,
            "description": description,
        }
        expected_response = notification_pb2.NotificationChannel(
            **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.NotificationChannelServiceClient()

        # Setup Request
        name = client.notification_channel_path("[PROJECT]",
                                                "[NOTIFICATION_CHANNEL]")

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

        assert len(channel.requests) == 1
        expected_request = notification_service_pb2.GetNotificationChannelRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Ejemplo n.º 11
0
 def test_list_notification_channels(self):
     client = monitoring_v3.NotificationChannelServiceClient()
     name_inside = client.project_path(PROJECT_INSIDE)
     delayed_inside = lambda: client.list_notification_channels(name_inside)
     name_outside = client.project_path(PROJECT_OUTSIDE)
     delayed_outside = lambda: client.list_notification_channels(name_outside)
     TestVPCServiceControlV3._do_test(delayed_inside, delayed_outside)
Ejemplo n.º 12
0
def list_notification_channels(project_name):
    client = monitoring_v3.NotificationChannelServiceClient()
    channels = client.list_notification_channels(name=project_name)
    print(
        tabulate.tabulate(
            [(channel.name, channel.display_name) for channel in channels],
            ("name", "display_name"),
        ))
Ejemplo n.º 13
0
 def test_get_notification_channel(self):
     client = monitoring_v3.NotificationChannelServiceClient()
     name_inside = client.notification_channel_path(
         PROJECT_INSIDE, "mock_notification_channel")
     delayed_inside = lambda: client.get_notification_channel(name_inside)
     name_outside = client.notification_channel_path(
         PROJECT_OUTSIDE, "mock_notification_channel")
     delayed_outside = lambda: client.get_notification_channel(name_outside)
     TestVPCServiceControlV3._do_test(delayed_inside, delayed_outside)
Ejemplo n.º 14
0
    def testUptimeCheckAlertingPolicyNotificationChannel(self):
        """ Test that our single notification channel was created. """
        client = monitoring_v3.NotificationChannelServiceClient()
        channels = client.list_notification_channels(project_name)
        channel_list = []
        for channel in channels:
            channel_list.append(channel)

        self.assertEqual(len(channel_list), 1)
Ejemplo n.º 15
0
 def test_create_notification_channel(self):
     client = monitoring_v3.NotificationChannelServiceClient()
     name_inside = client.project_path(PROJECT_INSIDE)
     delayed_inside = lambda: client.create_notification_channel(
         name_inside, {})
     name_outside = client.project_path(PROJECT_OUTSIDE)
     delayed_outside = lambda: client.create_notification_channel(
         name_outside, {})
     self._do_test(delayed_inside, delayed_outside)
Ejemplo n.º 16
0
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.')
    def test_update_notification_channel_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.NotificationChannelServiceClient(
            channel=channel)

        # Setup request
        notification_channel = {}

        with pytest.raises(CustomException):
            client.update_notification_channel(notification_channel)
Ejemplo n.º 18
0
 def test_verify_notification_channel(self):
     client = monitoring_v3.NotificationChannelServiceClient()
     name_inside = client.notification_channel_path(
         PROJECT_INSIDE, "mock_notification_channel")
     delayed_inside = lambda: client.verify_notification_channel(
         name_inside, "")
     name_outside = client.notification_channel_path(
         PROJECT_OUTSIDE, "mock_notification_channel")
     delayed_outside = lambda: client.verify_notification_channel(
         name_outside, "")
     self._do_test(delayed_inside, delayed_outside)
Ejemplo n.º 19
0
 def test_get_notification_channel_descriptor(self):
     client = monitoring_v3.NotificationChannelServiceClient()
     name_inside = client.notification_channel_descriptor_path(
         PROJECT_INSIDE, "mock_notification_channel_descriptor")
     delayed_inside = lambda: client.get_notification_channel_descriptor(
         name_inside)
     name_outside = client.notification_channel_descriptor_path(
         PROJECT_OUTSIDE, "mock_notification_channel_descriptor")
     delayed_outside = lambda: client.get_notification_channel_descriptor(
         name_outside)
     self._do_test(delayed_inside, delayed_outside)
Ejemplo n.º 20
0
def cleanupNotificationChannels(project_name):
    """ Deletes all notification channels. """
    client = monitoring_v3.NotificationChannelServiceClient()
    channels = True
    while channels:
        channels = list(client.list_notification_channels(project_name))
        for channel in channels:
            try:
                client.delete_notification_channel(channel.name)
            except:
                print('Could not delete notification channel: ' + channel.name)
    def test_list_notification_channels_exception(self):
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.NotificationChannelServiceClient(
            channel=channel)

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

        paged_list_response = client.list_notification_channels(name)
        with pytest.raises(CustomException):
            list(paged_list_response)
Ejemplo n.º 22
0
def delete_notification_channels(project_name, channel_ids, force=None):
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    for channel_id in channel_ids:
        channel_name = "{}/notificationChannels/{}".format(project_name, channel_id)
        try:
            channel_client.delete_notification_channel(name=channel_name, force=force)
            print("Channel {} deleted".format(channel_name))
        except ValueError:
            print("The parameters are invalid")
        except Exception as e:
            print("API call failed: {}".format(e))
    def test_get_notification_channel_descriptor_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.NotificationChannelServiceClient(
            channel=channel)

        # Setup request
        name = client.notification_channel_descriptor_path(
            '[PROJECT]', '[CHANNEL_DESCRIPTOR]')

        with pytest.raises(CustomException):
            client.get_notification_channel_descriptor(name)
Ejemplo n.º 24
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_create_notification_channel_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.NotificationChannelServiceClient(
            channel=channel)

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

        with pytest.raises(CustomException):
            client.create_notification_channel(name, notification_channel)
    def test_delete_notification_channel_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        client = monitoring_v3.NotificationChannelServiceClient(
            channel=channel)

        # Setup request
        name = client.notification_channel_path('[PROJECT]',
                                                '[NOTIFICATION_CHANNEL]')

        with pytest.raises(CustomException):
            client.delete_notification_channel(name)
Ejemplo n.º 27
0
    def test_update_notification_channel_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.NotificationChannelServiceClient()

        # Setup request
        notification_channel = {}

        with pytest.raises(CustomException):
            client.update_notification_channel(notification_channel)
    def test_delete_notification_channel_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.NotificationChannelServiceClient()

        # Setup request
        name = client.notification_channel_path("[PROJECT]", "[NOTIFICATION_CHANNEL]")

        with pytest.raises(CustomException):
            client.delete_notification_channel(name)
Ejemplo n.º 29
0
    def test_list_notification_channels_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.NotificationChannelServiceClient()

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

        paged_list_response = client.list_notification_channels(name)
        with pytest.raises(CustomException):
            list(paged_list_response)
Ejemplo n.º 30
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
        )
    )