示例#1
0
def testMetricCollection():
    custom_metric_type = 'custom.googleapis.com/cbao/instance/cpu/utilization'
    api = metric_service_client.MetricServiceClient()
    name = api.project_path(PROJECT_ID)

    metric_descriptor = api_metric_pb2.MetricDescriptor(
        type=custom_metric_type,
        metric_kind=enums.MetricDescriptor.MetricKind.GAUGE,
        value_type=enums.MetricDescriptor.ValueType.BOOL)
    response = api.create_metric_descriptor(name, metric_descriptor)
    print "Metric created: \n%s\n" % response

    name = api.metric_descriptor_path_path(PROJECT_ID, custom_metric_type)
    response = api.get_metric_descriptor(name)
    print "Metric fetched: \n%s\n" % response

    print "List metrics:"
    name = api.project_path(PROJECT_ID)
    # Iterate over all results
    for metric in api.list_metric_descriptors(name):
        # process element
        print metric

    print "delete metric:"
    name = api.metric_descriptor_path_path(PROJECT_ID, custom_metric_type)
    api.delete_metric_descriptor(name)
示例#2
0
    def test_create_metric_descriptor(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        type_ = 'type3575610'
        unit = 'unit3594628'
        description = 'description-1724546052'
        display_name = 'displayName1615086568'
        expected_response = {
            'name': name_2,
            'type': type_,
            'unit': unit,
            'description': description,
            'display_name': display_name
        }
        expected_response = api_metric_pb2.MetricDescriptor(
            **expected_response)

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

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

        response = client.create_metric_descriptor(name, metric_descriptor)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = metric_service_pb2.CreateMetricDescriptorRequest(
            name=name, metric_descriptor=metric_descriptor)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
示例#3
0
    def get_metric_descriptor(self, oc_md):
        """Convert an OC metric descriptor to a SD metric descriptor."""
        try:
            metric_kind, value_type = OC_MD_TO_SD_TYPE[oc_md.type]
        except KeyError:
            raise TypeError("Unsupported metric type: {}".format(oc_md.type))

        if self.options.metric_prefix:
            display_name_prefix = self.options.metric_prefix
        else:
            display_name_prefix = DEFAULT_DISPLAY_NAME_PREFIX

        desc_labels = new_label_descriptors(
            self.options.default_monitoring_labels, oc_md.label_keys)

        descriptor = metric_pb2.MetricDescriptor(labels=desc_labels)
        metric_type = self.get_metric_type(oc_md)
        descriptor.type = metric_type
        descriptor.metric_kind = metric_kind
        descriptor.value_type = value_type
        descriptor.description = oc_md.description
        descriptor.unit = oc_md.unit
        descriptor.name = ("projects/{}/metricDescriptors/{}".format(
            self.options.project_id, metric_type))
        descriptor.display_name = ("{}/{}".format(display_name_prefix,
                                                  oc_md.name))

        return descriptor
示例#4
0
    def create(self,
               metric_type,
               metric_kind='GAUGE',
               value_type='DOUBLE',
               description='N/A'):
        """Create a metric descriptor.

        Args:
            metric_type (str): Metric type.
            metric_kind (str, optional): Metric kind.
            value_type (str, optional): Value type.
            description (str, optional): Description.

        Returns:
            obj: Metric descriptor.
        """
        descriptor = ga_metric.MetricDescriptor()
        if metric_type.startswith('custom.googleapis.com/'):
            descriptor.type = metric_type
        else:
            descriptor.type = 'custom.googleapis.com/%s' % metric_type
        descriptor.metric_kind = (getattr(
            ga_metric.MetricDescriptor.MetricKind, metric_kind))
        descriptor.value_type = (getattr(ga_metric.MetricDescriptor.ValueType,
                                         value_type))
        descriptor.description = description
        LOGGER.info(f'Creating metric descriptor "{descriptor.type}" ...')
        return self.client.create_metric_descriptor(
            name=self.project, metric_descriptor=descriptor)
示例#5
0
def create_metric_descriptor(project_id):
    # [START monitoring_create_metric]
    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{project_id}"
    descriptor = ga_metric.MetricDescriptor()
    descriptor.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
    descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
    descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
    descriptor.description = "This is a simple example of a custom metric."
    descriptor = client.create_metric_descriptor(name=project_name,
                                                 metric_descriptor=descriptor)
    print("Created {}.".format(descriptor.name))
示例#6
0
def create_metric_descriptor(project_id):
    try:
        client = monitoring_v3.MetricServiceClient()
        #list_metric_descriptors(project_id)
        project_name = f"projects/{project_id}"
        descriptor = ga_metric.MetricDescriptor()
        descriptor.type = "custom.googleapis.com/" + CUSTOM_METRIC_NAME_PREFIX + PROJECT_ID
        descriptor.display_name = CUSTOM_METRIC_DISPLAY_NAME
        descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
        descriptor.value_type = ga_metric.MetricDescriptor.ValueType.INT64
        descriptor.unit = "1"
        descriptor.description = "This measures the amount of pets requested so far."
        descriptor = client.create_metric_descriptor(
            name=project_name, metric_descriptor=descriptor
        )
        print("Created", descriptor.type)
    except Exception as e:
        print(e)
示例#7
0
    def _create_metric_descriptors(self, type_prefix, descriptors):
        '''Create metric descriptors in the cloud from a structure

        type_prefix: the prefix used to build the cloud monitoring
        metric type.  combined with the name in the descriptor to get
        the complete type.

        descriptors: a dict of dicts.  The keys are the names, used to
        fill out the type field.  The values are dicts with parameters
        for the descriptor creation.  The value dicts should specify
        metric_kind, value_type, and description.

        for example:
        type_prefix = 'custom.googleapis.com/forseti-realtime-enforcer/wooo_app'
        descriptors = {
            'count_yeah': {
                'metric_kind': ga_metric.MetricDescriptor.MetricKind.GAUGE,
                'value_type': ga_metric.MetricDescriptor.ValueType.INT64,
                'description': 'The number of yeahs currently in flight',
            },
        }

        this will produce a gauge metric of integers, with type:
        custom.googleapis.com/forseti-realtime-enforcer/wooo/count_yeah

        '''
        if not type_prefix.startswith(f'custom.googleapis.com/{self.app_name}'):
            raise ValueError(f'type_prefix must start with custom.googleapis.com/{self.app_name}/')

        if type_prefix.endswith('/'):
            raise ValueError('type_prefix must not end with a /')

        for name, d in descriptors.items():
            descriptor = ga_metric.MetricDescriptor()
            descriptor.type = f'{type_prefix}/{name}'
            for k, v in d.items():
                setattr(descriptor, k, v)

            self.client.create_metric_descriptor(
                name=f'projects/{self.project_id}',
                metric_descriptor=descriptor,
            )
示例#8
0
def create_metric(metric_name, description, monitoring_project):
    '''
    Creates a Cloud Monitoring metric based on the parameter given if the metric is not already existing

      Parameters:
        metric_name (string): Name of the metric to be created
        description (string): Description of the metric to be created
        monitoring_project (string): the project where the metrics are written to
      Returns:
        None
  '''
    client = monitoring_v3.MetricServiceClient()

    descriptor = ga_metric.MetricDescriptor()
    descriptor.type = f"custom.googleapis.com/{metric_name}"
    descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
    descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
    descriptor.description = description
    descriptor = client.create_metric_descriptor(name=monitoring_project,
                                                 metric_descriptor=descriptor)
    print("Created {}.".format(descriptor.name))
示例#9
0
    def test_create_metric_descriptor(self):
        # Setup Expected Response
        name_2 = "name2-1052831874"
        type_ = "type3575610"
        unit = "unit3594628"
        description = "description-1724546052"
        display_name = "displayName1615086568"
        expected_response = {
            "name": name_2,
            "type": type_,
            "unit": unit,
            "description": description,
            "display_name": display_name,
        }
        expected_response = api_metric_pb2.MetricDescriptor(
            **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.MetricServiceClient()

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

        response = client.create_metric_descriptor(name, metric_descriptor)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = metric_service_pb2.CreateMetricDescriptorRequest(
            name=name, metric_descriptor=metric_descriptor)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
示例#10
0
    def test_get_metric_descriptor(self):
        # Setup Expected Response
        name_2 = 'name2-1052831874'
        type_ = 'type3575610'
        unit = 'unit3594628'
        description = 'description-1724546052'
        display_name = 'displayName1615086568'
        expected_response = {
            'name': name_2,
            'type': type_,
            'unit': unit,
            'description': description,
            'display_name': display_name
        }
        expected_response = api_metric_pb2.MetricDescriptor(
            **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.MetricServiceClient()

        # Setup Request
        name = client.metric_descriptor_path('[PROJECT]',
                                             '[METRIC_DESCRIPTOR]')

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

        assert len(channel.requests) == 1
        expected_request = metric_service_pb2.GetMetricDescriptorRequest(
            name=name)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request