diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_helpers.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_helpers.py index 2010a5f4afee..fdc4f050cc16 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_helpers.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_helpers.py @@ -4,10 +4,11 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +import re from typing import TYPE_CHECKING from azure.core.exceptions import HttpResponseError from azure.core.pipeline.policies import BearerTokenCredentialPolicy +from msrest import Serializer if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -48,3 +49,19 @@ def order_results(request_order, responses): mapping = {item.id: item for item in responses} ordered = [mapping[id] for id in request_order] return ordered + +def construct_iso8601(start=None, end=None, duration=None): + if start is not None: + start = Serializer.serialize_iso(start) + if end is not None: + end = Serializer.serialize_iso(end) + return start + '/' + end + elif duration is not None: + return start + '/' + duration + else: + raise ValueError("Start time must be provided aling with duration or end time.") + elif end is not None: + end = Serializer.serialize_iso(end) + return duration + '/' + end + else: + return duration diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_log_query_client.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_log_query_client.py index c7a36e89892b..7e0584486420 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_log_query_client.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_log_query_client.py @@ -11,7 +11,7 @@ from ._generated._monitor_query_client import MonitorQueryClient from ._generated.models import BatchRequest -from ._helpers import get_authentication_policy, process_error +from ._helpers import get_authentication_policy, process_error, construct_iso8601 from ._models import LogsQueryResults, LogsQueryRequest, LogsQueryBody, LogsBatchResults if TYPE_CHECKING: @@ -51,9 +51,13 @@ def query(self, workspace_id, query, **kwargs): :param query: The Analytics query. Learn more about the `Analytics query syntax `_. :type query: str - :keyword str timespan: Optional. The timespan over which to query data. This is an ISO8601 time - period value. This timespan is applied in addition to any that are specified in the query - expression. + :keyword datetime start_time: The start time from which to query the data. This should be accompanied + with either end_time or duration. + :keyword datetime end_time: The end time till which to query the data. This should be accompanied + with either start_time or duration. + :keyword str duration: The duration for which to query the data. This can also be accompanied + with either start_time or end_time. If start_time or end_time is not provided, the current time is + taken as the end time. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'. :keyword int server_timeout: the server timeout in seconds. The default timeout is 3 minutes, and the maximum timeout is 10 minutes. :keyword bool include_statistics: To get information about query statistics. @@ -72,7 +76,10 @@ def query(self, workspace_id, query, **kwargs): :rtype: ~azure.monitor.query.LogsQueryResults :raises: ~azure.core.exceptions.HttpResponseError """ - timespan = kwargs.pop("timespan", None) + start = kwargs.pop('start_time', None) + end = kwargs.pop('end_time', None) + duration = kwargs.pop('duration', None) + timespan = construct_iso8601(start, end, duration) include_statistics = kwargs.pop("include_statistics", False) include_render = kwargs.pop("include_render", False) server_timeout = kwargs.pop("server_timeout", None) diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_metrics_query_client.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_metrics_query_client.py index 54b2af234654..c2ea123955f6 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_metrics_query_client.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_metrics_query_client.py @@ -7,7 +7,6 @@ # pylint: disable=anomalous-backslash-in-string -from datetime import time from typing import TYPE_CHECKING, Any from ._generated._monitor_query_client import ( @@ -15,7 +14,7 @@ ) from ._models import MetricsResult, MetricDefinition, MetricNamespace -from ._helpers import get_metrics_authentication_policy +from ._helpers import get_metrics_authentication_policy, construct_iso8601 if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -44,17 +43,21 @@ def __init__(self, credential, **kwargs): self._namespace_op = self._client.metric_namespaces self._definitions_op = self._client.metric_definitions - def query(self, resource_uri, metric_names, timespan=None, **kwargs): - # type: (str, list, str, Any) -> MetricsResult + def query(self, resource_uri, metric_names, **kwargs): + # type: (str, list, Any) -> MetricsResult """Lists the metric values for a resource. :param resource_uri: The identifier of the resource. :type resource_uri: str :param metric_names: The names of the metrics to retrieve. :type metric_names: list - :param timespan: The timespan of the query. It is a string with the following format - 'startDateTime_ISO/endDateTime_ISO'. - :type timespan: str + :keyword datetime start_time: The start time from which to query the data. This should be accompanied + with either end_time or duration. + :keyword datetime end_time: The end time till which to query the data. This should be accompanied + with either start_time or duration. + :keyword str duration: The duration for which to query the data. This can also be accompanied + with either start_time or end_time. If start_time or end_time is not provided, the current time is + taken as the end time. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'. :keyword interval: The interval (i.e. timegrain) of the query. :paramtype interval: ~datetime.timedelta :keyword aggregation: The list of aggregation types (comma separated) to retrieve. @@ -86,6 +89,10 @@ def query(self, resource_uri, metric_names, timespan=None, **kwargs): :rtype: ~azure.monitor.query.MetricsResult :raises: ~azure.core.exceptions.HttpResponseError """ + start = kwargs.pop('start_time', None) + end = kwargs.pop('end_time', None) + duration = kwargs.pop('duration', None) + timespan = construct_iso8601(start, end, duration) kwargs.setdefault("metricnames", ",".join(metric_names)) kwargs.setdefault("timespan", timespan) generated = self._metrics_op.list(resource_uri, connection_verify=False, **kwargs) diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_log_query_client_async.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_log_query_client_async.py index e8eddc27c4f4..4179744a236e 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_log_query_client_async.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_log_query_client_async.py @@ -10,7 +10,7 @@ from .._generated.aio._monitor_query_client import MonitorQueryClient from .._generated.models import BatchRequest -from .._helpers import get_authentication_policy, process_error +from .._helpers import get_authentication_policy, process_error, construct_iso8601 from .._models import LogsQueryResults, LogsQueryRequest, LogsQueryBody, LogsBatchResults if TYPE_CHECKING: @@ -47,9 +47,13 @@ async def query(self, workspace_id: str, query: str, **kwargs: Any) -> LogsQuery :param query: The Analytics query. Learn more about the `Analytics query syntax `_. :type query: str - :keyword ~datetime.timedelta timespan: Optional. The timespan over which to query data. This is an ISO8601 time - period value. This timespan is applied in addition to any that are specified in the query - expression. + :keyword datetime start_time: The start time from which to query the data. This should be accompanied + with either end_time or duration. + :keyword datetime end_time: The end time till which to query the data. This should be accompanied + with either start_time or duration. + :keyword str duration: The duration for which to query the data. This can also be accompanied + with either start_time or end_time. If start_time or end_time is not provided, the current time is + taken as the end time. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'. :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. @@ -68,7 +72,10 @@ async def query(self, workspace_id: str, query: str, **kwargs: Any) -> LogsQuery :rtype: ~azure.monitor.query.LogsQueryResults :raises: ~azure.core.exceptions.HttpResponseError """ - timespan = kwargs.pop("timespan", None) + start = kwargs.pop('start_time', None) + end = kwargs.pop('end_time', None) + duration = kwargs.pop('duration', None) + timespan = construct_iso8601(start, end, duration) include_statistics = kwargs.pop("include_statistics", False) include_render = kwargs.pop("include_render", False) server_timeout = kwargs.pop("server_timeout", None) diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_metrics_query_client_async.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_metrics_query_client_async.py index e4450b5e6091..e66bd4c45c2a 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_metrics_query_client_async.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_metrics_query_client_async.py @@ -15,7 +15,7 @@ MonitorQueryClient, ) from .._models import MetricsResult, MetricDefinition, MetricNamespace -from .._helpers import get_metrics_authentication_policy +from .._helpers import get_metrics_authentication_policy, construct_iso8601 if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -41,16 +41,20 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self._namespace_op = self._client.metric_namespaces self._definitions_op = self._client.metric_definitions - async def query(self, resource_uri: str, metric_names: List, timespan :str = None, **kwargs: Any) -> MetricsResult: + async def query(self, resource_uri: str, metric_names: List, **kwargs: Any) -> MetricsResult: """Lists the metric values for a resource. :param resource_uri: The identifier of the resource. :type resource_uri: str :param metric_names: The names of the metrics to retrieve. :type metric_names: list - :param timespan: The timespan of the query. It is a string with the following format - 'startDateTime_ISO/endDateTime_ISO'. - :type timespan: str + :keyword datetime start_time: The start time from which to query the data. This should be accompanied + with either end_time or duration. + :keyword datetime end_time: The end time till which to query the data. This should be accompanied + with either start_time or duration. + :keyword str duration: The duration for which to query the data. This can also be accompanied + with either start_time or end_time. If start_time or end_time is not provided, the current time is + taken as the end time. This should be provided in a ISO8601 string format like 'PT1H', 'P1Y2M10DT2H30M'. :keyword interval: The interval (i.e. timegrain) of the query. :paramtype interval: ~datetime.timedelta :keyword aggregation: The list of aggregation types (comma separated) to retrieve. @@ -82,6 +86,10 @@ async def query(self, resource_uri: str, metric_names: List, timespan :str = Non :rtype: ~azure.monitor.query.MetricsResult :raises: ~azure.core.exceptions.HttpResponseError """ + start = kwargs.pop('start_time', None) + end = kwargs.pop('end_time', None) + duration = kwargs.pop('duration', None) + timespan = construct_iso8601(start, end, duration) kwargs.setdefault("metric_names", ",".join(metric_names)) kwargs.setdefault("timespan", timespan) generated = await self._metrics_op.list(resource_uri, connection_verify=False, **kwargs) diff --git a/sdk/monitor/azure-monitor-query/samples/sample_log_query_client.py b/sdk/monitor/azure-monitor-query/samples/sample_log_query_client.py index df37a8079306..4e34fa83f327 100644 --- a/sdk/monitor/azure-monitor-query/samples/sample_log_query_client.py +++ b/sdk/monitor/azure-monitor-query/samples/sample_log_query_client.py @@ -3,7 +3,7 @@ import os import pandas as pd -from datetime import timedelta +from datetime import datetime from azure.monitor.query import LogsQueryClient from azure.identity import ClientSecretCredential diff --git a/sdk/monitor/azure-monitor-query/samples/sample_metrics_query_client.py b/sdk/monitor/azure-monitor-query/samples/sample_metrics_query_client.py index b0b390b534fd..94e990368a03 100644 --- a/sdk/monitor/azure-monitor-query/samples/sample_metrics_query_client.py +++ b/sdk/monitor/azure-monitor-query/samples/sample_metrics_query_client.py @@ -2,6 +2,7 @@ # Licensed under the MIT License. import os +from datetime import datetime import urllib3 from azure.monitor.query import MetricsQueryClient from azure.identity import ClientSecretCredential @@ -20,7 +21,8 @@ response = client.query( metrics_uri, metric_names=["PublishSuccessCount"], - timespan='P2D' + start_time=datetime(2021, 5, 25), + duration='P1D' ) for metric in response.metrics: @@ -28,4 +30,4 @@ for time_series_element in metric.timeseries: for metric_value in time_series_element.data: print(metric_value.time_stamp) - +