def test_list_time_series(self): # Setup Expected Response next_page_token = '' time_series_element = {} time_series = [time_series_element] expected_response = { 'next_page_token': next_page_token, 'time_series': time_series } expected_response = metric_service_pb2.ListTimeSeriesResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = monitoring_v3.MetricServiceClient(channel=channel) # Setup Request name = client.project_path('[PROJECT]') filter_ = 'filter-1274492040' interval = {} view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL paged_list_response = client.list_time_series(name, filter_, interval, view) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.time_series[0] == resources[0] assert len(channel.requests) == 1 expected_request = metric_service_pb2.ListTimeSeriesRequest( name=name, filter=filter_, interval=interval, view=view) actual_request = channel.requests[0][1] assert expected_request == actual_request
def test_iteration_headers_only(self): from google.cloud.monitoring_v3 import MetricServiceClient from google.cloud.monitoring_v3.gapic import enums from google.cloud.monitoring_v3.proto import metric_service_pb2 T0 = datetime.datetime(2016, 4, 6, 22, 5, 0) T1 = datetime.datetime(2016, 4, 6, 22, 10, 0) SERIES1 = { "metric": { "type": METRIC_TYPE, "labels": METRIC_LABELS }, "resource": { "type": RESOURCE_TYPE, "labels": RESOURCE_LABELS }, "metric_kind": METRIC_KIND, "value_type": VALUE_TYPE, } SERIES2 = { "metric": { "type": METRIC_TYPE, "labels": METRIC_LABELS2 }, "resource": { "type": RESOURCE_TYPE, "labels": RESOURCE_LABELS2 }, "metric_kind": METRIC_KIND, "value_type": VALUE_TYPE, } RESPONSE = {"time_series": [SERIES1, SERIES2], "next_page_token": ""} channel = ChannelStub(responses=[RESPONSE]) client = MetricServiceClient(channel=channel) query = self._make_one(client, PROJECT, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query.iter(headers_only=True)) self.assertEqual(len(response), 2) series1, series2 = response self.assertEqual(series1.metric.labels, METRIC_LABELS) self.assertEqual(series2.metric.labels, METRIC_LABELS2) self.assertEqual(series1.resource.labels, RESOURCE_LABELS) self.assertEqual(series2.resource.labels, RESOURCE_LABELS2) self.assertFalse(len(series1.points)) self.assertFalse(len(series2.points)) expected_request = metric_service_pb2.ListTimeSeriesRequest( name="projects/" + PROJECT, filter='metric.type = "{type}"'.format(type=METRIC_TYPE), interval=self._make_interval(T1, T0), view=enums.ListTimeSeriesRequest.TimeSeriesView.HEADERS, ) request = channel.requests[0][1] self.assertEqual(request, expected_request)
def test_iteration_empty(self): from google.cloud.monitoring_v3 import MetricServiceClient from google.cloud.monitoring_v3.gapic import enums from google.cloud.monitoring_v3.proto import metric_service_pb2 T0 = datetime.datetime(2016, 4, 6, 22, 5, 0) T1 = datetime.datetime(2016, 4, 6, 22, 10, 0) channel = ChannelStub(responses=[{'next_page_token': ''}]) client = MetricServiceClient(channel=channel) query = self._make_one(client, PROJECT, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query) self.assertEqual(len(response), 0) expected_request = metric_service_pb2.ListTimeSeriesRequest( name='projects/' + PROJECT, filter='metric.type = "{type}"'.format(type=METRIC_TYPE), interval=self._make_interval(T1, T0), view=enums.ListTimeSeriesRequest.TimeSeriesView.FULL) request = channel.requests[0][1] self.assertEqual(request, expected_request)
def test_list_time_series(self): # Setup Expected Response next_page_token = "" time_series_element = {} time_series = [time_series_element] expected_response = { "next_page_token": next_page_token, "time_series": time_series, } expected_response = metric_service_pb2.ListTimeSeriesResponse( **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]") filter_ = "filter-1274492040" interval = {} view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL paged_list_response = client.list_time_series(name, filter_, interval, view) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.time_series[0] == resources[0] assert len(channel.requests) == 1 expected_request = metric_service_pb2.ListTimeSeriesRequest( name=name, filter=filter_, interval=interval, view=view) actual_request = channel.requests[0][1] assert expected_request == actual_request
def list_time_series( self, name, filter_, interval, view, aggregation=None, order_by=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists time series that match a filter. This method does not require a Stackdriver account. Example: >>> from google.cloud import monitoring_v3 >>> from google.cloud.monitoring_v3 import enums >>> >>> client = monitoring_v3.MetricServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `filter_`: >>> filter_ = '' >>> >>> # TODO: Initialize `interval`: >>> interval = {} >>> >>> # TODO: Initialize `view`: >>> view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL >>> >>> # Iterate over all results >>> for element in client.list_time_series(name, filter_, interval, view): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_time_series(name, filter_, interval, view).pages: ... for element in page: ... # process element ... pass Args: name (str): The project on which to execute the request. The format is "projects/{project\_id\_or\_number}". filter_ (str): A `monitoring filter <https://cloud.google.com/monitoring/api/v3/filters>`__ that specifies which time series should be returned. The filter must specify a single metric type, and can additionally specify metric labels and other information. For example: :: metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND metric.labels.instance_name = "my-instance-name" interval (Union[dict, ~google.cloud.monitoring_v3.types.TimeInterval]): The time interval for which results should be returned. Only time series that contain data points in the specified interval are included in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.TimeInterval` view (~google.cloud.monitoring_v3.types.TimeSeriesView): Specifies which information is returned about the time series. aggregation (Union[dict, ~google.cloud.monitoring_v3.types.Aggregation]): Specifies the alignment of data points in individual time series as well as how to combine the retrieved time series across specified labels. By default (if no ``aggregation`` is explicitly specified), the raw time series data is returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.Aggregation` order_by (str): Unsupported: must be left blank. The points in each time series are currently returned in reverse time order (most recent to oldest). page_size (int): 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. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): 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. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.monitoring_v3.types.TimeSeries` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ if metadata is None: metadata = [] metadata = list(metadata) # Wrap the transport method to add retry and timeout logic. if "list_time_series" not in self._inner_api_calls: self._inner_api_calls[ "list_time_series"] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_time_series, default_retry=self._method_configs["ListTimeSeries"].retry, default_timeout=self._method_configs["ListTimeSeries"]. timeout, client_info=self._client_info, ) request = metric_service_pb2.ListTimeSeriesRequest( name=name, filter=filter_, interval=interval, view=view, aggregation=aggregation, order_by=order_by, page_size=page_size, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_time_series"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="time_series", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
def test_iteration(self): from google.cloud.monitoring_v3 import MetricServiceClient from google.cloud.monitoring_v3.gapic import enums from google.cloud.monitoring_v3.proto import metric_service_pb2 T0 = datetime.datetime(2016, 4, 6, 22, 5, 0) T1 = datetime.datetime(2016, 4, 6, 22, 10, 0) INTERVAL1 = self._make_interval(TS1, TS0) INTERVAL2 = self._make_interval(TS2, TS1) VALUE1 = 60 # seconds VALUE2 = 60.001 # seconds SERIES1 = { 'metric': { 'type': METRIC_TYPE, 'labels': METRIC_LABELS }, 'resource': { 'type': RESOURCE_TYPE, 'labels': RESOURCE_LABELS }, 'metric_kind': METRIC_KIND, 'value_type': VALUE_TYPE, 'points': [ { 'interval': INTERVAL2, 'value': { 'double_value': VALUE1 } }, { 'interval': INTERVAL1, 'value': { 'double_value': VALUE1 } }, ], } SERIES2 = { 'metric': { 'type': METRIC_TYPE, 'labels': METRIC_LABELS2 }, 'resource': { 'type': RESOURCE_TYPE, 'labels': RESOURCE_LABELS2 }, 'metric_kind': METRIC_KIND, 'value_type': VALUE_TYPE, 'points': [ { 'interval': INTERVAL2, 'value': { 'double_value': VALUE2 } }, { 'interval': INTERVAL1, 'value': { 'double_value': VALUE2 } }, ], } RESPONSE = {'time_series': [SERIES1, SERIES2], 'next_page_token': ''} channel = ChannelStub(responses=[RESPONSE]) client = MetricServiceClient(channel=channel) query = self._make_one(client, PROJECT, METRIC_TYPE) query = query.select_interval(start_time=T0, end_time=T1) response = list(query) self.assertEqual(len(response), 2) series1, series2 = response self.assertEqual(series1.metric.labels, METRIC_LABELS) self.assertEqual(series2.metric.labels, METRIC_LABELS2) self.assertEqual(series1.resource.labels, RESOURCE_LABELS) self.assertEqual(series2.resource.labels, RESOURCE_LABELS2) self.assertEqual([p.value.double_value for p in series1.points], [VALUE1, VALUE1]) self.assertEqual([p.value.double_value for p in series2.points], [VALUE2, VALUE2]) self.assertEqual([p.interval for p in series1.points], [INTERVAL2, INTERVAL1]) self.assertEqual([p.interval for p in series2.points], [INTERVAL2, INTERVAL1]) expected_request = metric_service_pb2.ListTimeSeriesRequest( name='projects/' + PROJECT, filter='metric.type = "{type}"'.format(type=METRIC_TYPE), interval=self._make_interval(T1, T0), view=enums.ListTimeSeriesRequest.TimeSeriesView.FULL) request = channel.requests[0][1] self.assertEqual(request, expected_request)
def list_time_series(self, name, filter_, interval, view, aggregation=None, order_by=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Lists time series that match a filter. This method does not require a Stackdriver account. Example: >>> from google.cloud import monitoring_v3 >>> from google.cloud.monitoring_v3 import enums >>> >>> client = monitoring_v3.MetricServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize ``filter_``: >>> filter_ = '' >>> >>> # TODO: Initialize ``interval``: >>> interval = {} >>> >>> # TODO: Initialize ``view``: >>> view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL >>> >>> # Iterate over all results >>> for element in client.list_time_series(name, filter_, interval, view): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_time_series(name, filter_, interval, view, options=CallOptions(page_token=INITIAL_PAGE)): ... for element in page: ... # process element ... pass Args: name (str): The project on which to execute the request. The format is \"projects/{project_id_or_number}\". filter_ (str): A `monitoring filter <https://cloud.google.com/monitoring/api/v3/filters>`_ that specifies which time series should be returned. The filter must specify a single metric type, and can additionally specify metric labels and other information. For example: :: metric.type = \"compute.googleapis.com/instance/cpu/usage_time\" AND metric.label.instance_name = \"my-instance-name\" interval (Union[dict, ~google.cloud.monitoring_v3.types.TimeInterval]): The time interval for which results should be returned. Only time series that contain data points in the specified interval are included in the response. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.TimeInterval` view (~google.cloud.monitoring_v3.types.TimeSeriesView): Specifies which information is returned about the time series. aggregation (Union[dict, ~google.cloud.monitoring_v3.types.Aggregation]): By default, the raw time series data is returned. Use this field to combine multiple time series for different views of the data. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.monitoring_v3.types.Aggregation` order_by (str): Specifies the order in which the points of the time series should be returned. By default, results are not ordered. Currently, this field must be left blank. page_size (int): 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. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): 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. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.monitoring_v3.types.TimeSeries` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ if metadata is None: metadata = [] metadata = list(metadata) # Wrap the transport method to add retry and timeout logic. if 'list_time_series' not in self._inner_api_calls: self._inner_api_calls[ 'list_time_series'] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_time_series, default_retry=self._method_configs['ListTimeSeries'].retry, default_timeout=self._method_configs['ListTimeSeries']. timeout, client_info=self._client_info, ) request = metric_service_pb2.ListTimeSeriesRequest( name=name, filter=filter_, interval=interval, view=view, aggregation=aggregation, order_by=order_by, page_size=page_size, ) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial(self._inner_api_calls['list_time_series'], retry=retry, timeout=timeout, metadata=metadata), request=request, items_field='time_series', request_token_field='page_token', response_token_field='next_page_token', ) return iterator