Skip to content

Commit

Permalink
Update metadata values (Azure#20365)
Browse files Browse the repository at this point in the history
* Update metadata values

* distributed trace

* oops

* Update sdk/monitor/azure-monitor-query/CHANGELOG.md

* Apply suggestions from code review
  • Loading branch information
Rakshith Bhyravabhotla authored and hodd committed Aug 30, 2021
1 parent 88eab49 commit 4e99dc6
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 64 deletions.
2 changes: 2 additions & 0 deletions sdk/monitor/azure-monitor-query/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
- `interval` and `time_grain` are renamed to `granularity`
- `orderby` is renamed to `order_by`
- `LogsQueryResult` now returns `datetime` objects for a time values.
- `LogsBatchQuery` doesn't accept a `request_id` anymore.
- `MetricsMetadataValues` is removed. A dictionary is used instead.

### Bugs Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
LogsBatchQuery,
MetricNamespace,
MetricDefinition,
MetricsMetadataValue,
TimeSeriesElement,
Metric,
MetricValue,
Expand All @@ -40,7 +39,6 @@
"MetricNamespace",
"MetricDefinition",
"MetricsResult",
"MetricsMetadataValue",
"TimeSeriesElement",
"Metric",
"MetricValue",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from typing import TYPE_CHECKING, Any, Union, Sequence, Dict, Optional
from azure.core.exceptions import HttpResponseError
from azure.core.tracing.decorator import distributed_trace

from ._generated._monitor_query_client import MonitorQueryClient

Expand Down Expand Up @@ -49,6 +50,7 @@ def __init__(self, credential, **kwargs):
)
self._query_op = self._client.query

@distributed_trace
def query(self, workspace_id, query, timespan=None, **kwargs):
# type: (str, str, Optional[timedelta], Any) -> LogsQueryResult
"""Execute an Analytics query.
Expand Down Expand Up @@ -122,6 +124,7 @@ def query(self, workspace_id, query, timespan=None, **kwargs):
except HttpResponseError as e:
process_error(e)

@distributed_trace
def query_batch(self, queries, **kwargs):
# type: (Union[Sequence[Dict], Sequence[LogsBatchQuery]], Any) -> Sequence[LogsBatchQueryResult]
"""Execute a list of analytics queries. Each request can be either a LogQueryRequest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# pylint: disable=anomalous-backslash-in-string

from typing import TYPE_CHECKING, Any, Optional
from azure.core.tracing.decorator import distributed_trace

from ._generated._monitor_query_client import (
MonitorQueryClient,
Expand Down Expand Up @@ -53,6 +54,7 @@ def __init__(self, credential, **kwargs):
self._namespace_op = self._client.metric_namespaces
self._definitions_op = self._client.metric_definitions

@distributed_trace
def query(self, resource_uri, metric_names, **kwargs):
# type: (str, list, Optional[timedelta], Any) -> MetricsResult
"""Lists the metric values for a resource.
Expand Down Expand Up @@ -122,6 +124,7 @@ def query(self, resource_uri, metric_names, **kwargs):
generated = self._metrics_op.list(resource_uri, connection_verify=False, **kwargs)
return MetricsResult._from_generated(generated) # pylint: disable=protected-access

@distributed_trace
def list_metric_namespaces(self, resource_uri, **kwargs):
# type: (str, Any) -> ItemPaged[MetricNamespace]
"""Lists the metric namespaces for the resource.
Expand All @@ -145,6 +148,7 @@ def list_metric_namespaces(self, resource_uri, **kwargs):
),
**kwargs)

@distributed_trace
def list_metric_definitions(self, resource_uri, metric_namespace=None, **kwargs):
# type: (str, str, Any) -> ItemPaged[MetricDefinition]
"""Lists the metric definitions for the resource.
Expand Down
39 changes: 5 additions & 34 deletions sdk/monitor/azure-monitor-query/azure/monitor/query/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,6 @@ class LogsBatchQuery(object):
:keyword additional_workspaces: A list of workspaces that are included in the query.
These can be qualified workspace names, workspace Ids, or Azure resource Ids.
:paramtype additional_workspaces: list[str]
:keyword request_id: The error details.
:paramtype request_id: str
:keyword int server_timeout: the server timeout. The default timeout is 3 minutes,
and the maximum timeout is 10 minutes.
:keyword bool include_statistics: To get information about query statistics.
Expand Down Expand Up @@ -201,7 +199,7 @@ def __init__(self, query, workspace_id, timespan, **kwargs): #pylint: disable=su
headers = {'Prefer': prefer}
timespan = construct_iso8601(timespan)
additional_workspaces = kwargs.pop("additional_workspaces", None)
self.id = kwargs.get("request_id", str(uuid.uuid4()))
self.id = str(uuid.uuid4())
self.body = {
"query": query, "timespan": timespan, "workspaces": additional_workspaces
}
Expand Down Expand Up @@ -494,7 +492,7 @@ class TimeSeriesElement(object):
"""A time series result type. The discriminator value is always TimeSeries in this case.
:ivar metadata_values: The metadata values returned if $filter was specified in the call.
:vartype metadata_values: list[~monitor_query_client.models.MetadataValue]
:vartype metadata_values: dict(str, str)
:ivar data: An array of data points representing the metric values. This is only returned if
a result type of data is specified.
:vartype data: list[~monitor_query_client.models.MetricValue]
Expand All @@ -518,39 +516,12 @@ def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
metadata_values=[
MetricsMetadataValue._from_generated( # pylint: disable=protected-access
mval
) for mval in generated.metadatavalues
],
metadata_values={
obj.name.value: obj.value for obj in generated.metadatavalues
},
data=[MetricValue._from_generated(val) for val in generated.data] # pylint: disable=protected-access
)

class MetricsMetadataValue(object):
"""Represents a metric metadata value.
:ivar name: The name of the metadata.
:vartype name: str
:ivar value: The value of the metadata.
:vartype value: str
"""
def __init__(
self,
**kwargs
):
# type: (Any) -> None
self.name = kwargs.get('name', None)
self.value = kwargs.get('value', None)

@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
name=generated.name.value,
value=generated.value
)


class MetricAvailability(object):
"""Metric availability specifies the time grain (aggregation interval or frequency)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from datetime import datetime, timedelta
from typing import Any, Tuple, Union, Sequence, Dict, Optional, TYPE_CHECKING
from azure.core.exceptions import HttpResponseError
from azure.core.tracing.decorator_async import distributed_trace_async

from .._generated.aio._monitor_query_client import MonitorQueryClient

from .._generated.models import BatchRequest, QueryBody as LogsQueryBody
Expand Down Expand Up @@ -38,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None:
)
self._query_op = self._client.query

@distributed_trace_async
async def query(
self,
workspace_id: str,
Expand Down Expand Up @@ -106,6 +109,7 @@ async def query(
except HttpResponseError as e:
process_error(e)

@distributed_trace_async
async def query_batch(
self,
queries: Union[Sequence[Dict], Sequence[LogsBatchQuery]],
Expand All @@ -118,7 +122,7 @@ async def query_batch(
:param queries: The list of queries that should be processed
:type queries: list[dict] or list[~azure.monitor.query.LogsBatchQuery]
:return: BatchResponse, or the result of cls(response)
:return: list of LogsBatchQueryResult objects, or the result of cls(response)
:rtype: ~list[~azure.monitor.query.LogsBatchQueryResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from typing import TYPE_CHECKING, Any, List, Optional

from azure.core.async_paging import AsyncItemPaged
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async

from .._generated.aio._monitor_query_client import (
MonitorQueryClient,
Expand Down Expand Up @@ -43,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None:
self._namespace_op = self._client.metric_namespaces
self._definitions_op = self._client.metric_definitions

@distributed_trace_async
async def query(
self,
resource_uri: str,
Expand Down Expand Up @@ -106,6 +109,7 @@ async def query(
generated = await self._metrics_op.list(resource_uri, connection_verify=False, **kwargs)
return MetricsResult._from_generated(generated) # pylint: disable=protected-access

@distributed_trace
def list_metric_namespaces(self, resource_uri: str, **kwargs: Any) -> AsyncItemPaged[MetricNamespace]:
"""Lists the metric namespaces for the resource.
Expand All @@ -128,6 +132,7 @@ def list_metric_namespaces(self, resource_uri: str, **kwargs: Any) -> AsyncItemP
),
**kwargs)

@distributed_trace
def list_metric_definitions(
self,
resource_uri: str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,25 @@
from azure.monitor.query.aio import MetricsQueryClient
from azure.identity.aio import DefaultAzureCredential

async def list_namespaces():
credential = DefaultAzureCredential(
client_id = os.environ['AZURE_CLIENT_ID'],
client_secret = os.environ['AZURE_CLIENT_SECRET'],
tenant_id = os.environ['AZURE_TENANT_ID']
)
class ListDefinitions():
async def list_definitions(self):
credential = DefaultAzureCredential()

client = MetricsQueryClient(credential)
client = MetricsQueryClient(credential)

metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.list_metric_definitions(metrics_uri)
metrics_uri = os.environ['METRICS_RESOURCE_URI']
async with client:
response = client.list_metric_definitions(metrics_uri)

async for item in response:
print(item)
for availability in item.metric_availabilities:
print(availability.time_grain)
async for item in response:
print(item.namespace)
for availability in item.metric_availabilities:
print(availability.granularity)

async def main():
sample = ListDefinitions()
await sample.list_definitions()

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(list_namespaces())
loop.run_until_complete(main())
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,23 @@
from azure.monitor.query.aio import MetricsQueryClient
from azure.identity.aio import DefaultAzureCredential

async def list_namespaces():
credential = DefaultAzureCredential(
client_id = os.environ['AZURE_CLIENT_ID'],
client_secret = os.environ['AZURE_CLIENT_SECRET'],
tenant_id = os.environ['AZURE_TENANT_ID']
)
class ListNameSpaces():
async def list_namespaces(self):
credential = DefaultAzureCredential()

client = MetricsQueryClient(credential)
client = MetricsQueryClient(credential)

metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.list_metric_namespaces(metrics_uri)
metrics_uri = os.environ['METRICS_RESOURCE_URI']
async with client:
response = client.list_metric_namespaces(metrics_uri)
async for item in response:
print(item.fully_qualified_namespace)
print(item.type)

async for item in response:
print(item.metric_namespace_name)
print(item.type)
async def main():
sample = ListNameSpaces()
await sample.list_namespaces()

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(list_namespaces())
loop.run_until_complete(main())

0 comments on commit 4e99dc6

Please sign in to comment.