Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Monitor][Query] Typing updates #28618

Merged
merged 3 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
from ._enums import LogsQueryStatus

if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
from collections.abc import Mapping
else:
from typing import MutableMapping # pylint: disable=ungrouped-imports
from typing import Mapping # pylint: disable=ungrouped-imports


JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
JSON = Mapping[str, Any] # pylint: disable=unsubscriptable-object


class LogsQueryError:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typing import Any, Union, Sequence, Dict, List, cast, Tuple
from typing import Any, Union, Sequence, Dict, List, cast, Tuple, Optional
from datetime import timedelta, datetime

from azure.core.credentials import TokenCredential
Expand Down Expand Up @@ -44,7 +44,7 @@ class LogsQueryClient(object): # pylint: disable=client-accepts-api-version-keyw
:param credential: The credential to authenticate the client.
:type credential: ~azure.core.credentials.TokenCredential
:keyword endpoint: The endpoint to connect to. Defaults to 'https://api.loganalytics.io'.
:paramtype endpoint: str
:paramtype endpoint: Optional[str]
"""

def __init__(self, credential: TokenCredential, **kwargs: Any) -> None:
Expand All @@ -67,8 +67,8 @@ def query_workspace(
workspace_id: str,
query: str,
*,
timespan: Union[
timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]
timespan: Optional[Union[
timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]]
],
**kwargs: Any
) -> Union[LogsQueryResult, LogsQueryPartialResult]:
Expand All @@ -83,9 +83,10 @@ def query_workspace(
<https://docs.microsoft.com/azure/data-explorer/kusto/query/>`_.
:type query: str
:keyword timespan: Required. The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
a timedelta and a start datetime, or a start datetime/end datetime. Set to None to not constrain
the query to a timespan.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
or tuple[~datetime.datetime, ~datetime.datetime] or None
: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.
Expand All @@ -94,7 +95,7 @@ def query_workspace(
visualization to show. If your client requires this information, specify the preference
: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]
:paramtype additional_workspaces: Optional[list[str]]
:return: LogsQueryResult if there is a success or LogsQueryPartialResult when there is a partial success.
:rtype: Union[~azure.monitor.query.LogsQueryResult, ~azure.monitor.query.LogsQueryPartialResult]
:raises: ~azure.core.exceptions.HttpResponseError
Expand Down Expand Up @@ -149,7 +150,7 @@ def query_batch(
self,
queries: Union[Sequence[Dict], Sequence[LogsBatchQuery]],
**kwargs: Any
) -> List[Union[LogsQueryResult, LogsQueryPartialResult, LogsQueryError]]:
) -> List[Union[LogsQueryResult, LogsQueryError, LogsQueryPartialResult]]:
"""Execute a list of Kusto queries. Each request can be either a LogsBatchQuery
object or an equivalent serialized model.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class MetricsQueryClient(object): # pylint: disable=client-accepts-api-version-k
:param credential: The credential to authenticate the client.
:type credential: ~azure.core.credentials.TokenCredential
:keyword endpoint: The endpoint to connect to. Defaults to 'https://management.azure.com'.
:paramtype endpoint: str
:paramtype endpoint: Optional[str]
"""

def __init__(self, credential: TokenCredential, **kwargs: Any) -> None:
Expand Down Expand Up @@ -66,21 +66,21 @@ def query_resource(self, resource_uri: str, metric_names: List[str], **kwargs: A
:type metric_names: list[str]
:keyword timespan: The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
:paramtype timespan: Optional[Union[~datetime.timedelta, tuple[~datetime.datetime, ~datetime.timedelta],
tuple[~datetime.datetime, ~datetime.datetime]]]
:keyword granularity: The granularity (i.e. timegrain) of the query.
:paramtype granularity: ~datetime.timedelta
:paramtype granularity: Optional[~datetime.timedelta]
:keyword aggregations: The list of aggregation types to retrieve. Use
`azure.monitor.query.MetricAggregationType` enum to get each aggregation type.
:paramtype aggregations: list[str]
:paramtype aggregations: Optional[list[str]]
:keyword max_results: The maximum number of records to retrieve.
Valid only if $filter is specified.
Defaults to 10.
:paramtype max_results: int
:paramtype max_results: Optional[int]
:keyword order_by: The aggregation to use for sorting results and the direction of the sort.
Only one order can be specified.
Examples: sum asc.
:paramtype order_by: str
:paramtype order_by: Optional[str]
:keyword filter: The **$filter** is used to reduce the set of metric data returned. Example:
Metric contains metadata A, B and C. - Return all time series of C where A = a1 and B = b1 or
b2 **$filter=A eq 'a1' and B eq 'b1' or B eq 'b2' and C eq '*'** - Invalid variant: **$filter=A
Expand All @@ -93,9 +93,9 @@ def query_resource(self, resource_uri: str, metric_names: List[str], **kwargs: A
When dimension name is **dim (test) 3** and dimension value is **dim3 (test) val**, instead of using
**$filter= "dim (test) 3 eq 'dim3 (test) val'"** use **$filter= "dim
%2528test%2529 3 eq 'dim3 %2528test%2529 val'"**. Default value is None.
:paramtype filter: str
:paramtype filter: Optional[str]
:keyword metric_namespace: Metric namespace to query metric definitions for.
:paramtype metric_namespace: str
:paramtype metric_namespace: Optional[str]
:return: A MetricsQueryResult object.
:rtype: ~azure.monitor.query.MetricsQueryResult
:raises: ~azure.core.exceptions.HttpResponseError
Expand Down Expand Up @@ -137,7 +137,7 @@ def list_metric_namespaces(self, resource_uri: str, **kwargs: Any) -> ItemPaged[
:type resource_uri: str
:keyword start_time: The start time from which to query for metric
namespaces. This should be provided as a datetime object.
:paramtype start_time: ~datetime.datetime
:paramtype start_time: Optional[~datetime.datetime]
:return: An iterator like instance of either MetricNamespace or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.monitor.query.MetricNamespace]
:raises: ~azure.core.exceptions.HttpResponseError
Expand Down Expand Up @@ -166,7 +166,7 @@ def list_metric_definitions(self, resource_uri: str, **kwargs: Any) -> ItemPaged
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:keyword namespace: Metric namespace to query metric definitions for.
:paramtype namespace: str
:paramtype namespace: Optional[str]
:return: An iterator like instance of either MetricDefinition or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.monitor.query.MetricDefinition]
:raises: ~azure.core.exceptions.HttpResponseError
Expand Down
53 changes: 24 additions & 29 deletions sdk/monitor/azure-monitor-query/azure/monitor/query/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
from ._helpers import construct_iso8601, process_row

if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
from collections.abc import Mapping
else:
from typing import MutableMapping # pylint: disable=ungrouped-imports
from typing import Mapping # pylint: disable=ungrouped-imports


JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
JSON = Mapping[str, Any] # pylint: disable=unsubscriptable-object


class LogsTableRow:
Expand Down Expand Up @@ -74,15 +74,15 @@ class LogsTable:
"""Required. The name of the table."""
rows: List[LogsTableRow]
"""Required. The resulting rows from this query."""
columns: Optional[List[str]] = None
"""The labels of columns in this table."""
columns_types: Optional[List[Any]] = None
"""The types of columns in this table."""
columns: List[str]
"""Required. The labels of columns in this table."""
columns_types: List[str]
"""Required. The types of columns in this table."""

def __init__(self, **kwargs: Any) -> None:
self.name = kwargs.pop("name", "")
self.columns = kwargs.pop("columns", None)
self.columns_types = kwargs.pop("column_types", None)
self.columns = kwargs.pop("columns", [])
self.columns_types = kwargs.pop("column_types", [])
pvaneck marked this conversation as resolved.
Show resolved Hide resolved
_rows = kwargs.pop("rows", [])
self.rows: List[LogsTableRow] = [
LogsTableRow(
Expand Down Expand Up @@ -184,7 +184,7 @@ class Metric:
"""The unit of the metric. To access these values, use the MetricUnit enum.
Possible values include "Count", "Bytes", "Seconds", "CountPerSecond", "BytesPerSecond", "Percent",
"MilliSeconds", "ByteSeconds", "Unspecified", "Cores", "MilliCores", "NanoCores", "BitsPerSecond"."""
timeseries: TimeSeriesElement
timeseries: List[TimeSeriesElement]
"""The time series returned when a data query is performed."""
display_description: str
"""Detailed description of this metric."""
Expand Down Expand Up @@ -288,43 +288,38 @@ def __getitem__(self, metric):
class LogsBatchQuery:
"""A single request in a batch. The batch query API accepts a list of these objects.

:param workspace_id: Workspace Id to be included in the query.
:param workspace_id: Workspace ID to be included in the query.
:type workspace_id: str
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:keyword timespan: Required. The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
a timedelta and a start datetime, or a start datetime/end datetime. Set to None to not constrain
the query to a timespan.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
or tuple[~datetime.datetime, ~datetime.datetime] or None
: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 int server_timeout: the server timeout. The default timeout is 3 minutes,
These can be qualified workspace names, workspace IDs, or Azure resource IDs.
:paramtype additional_workspaces: Optional[list[str]]
:keyword 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.
:keyword bool include_visualization: In the query language, it is possible to specify different
:paramtype server_timeout: Optional[int]
:keyword include_statistics: To get information about query statistics.
:paramtype include_statistics: Optional[bool]
:keyword include_visualization: In the query language, it is possible to specify different
visualization options. By default, the API does not return information regarding the type of
visualization to show.
:paramtype include_visualization: Optional[bool]
"""

id: str
"""The id of the query."""
body: Dict[str, Any]
"""The body of the query."""
headers: Dict[str, str]
"""The headers of the query."""
workspace: str
"""The workspace ID to be included in the query."""

def __init__(
self,
workspace_id: str,
query: str,
*,
timespan: Union[
timespan: Optional[Union[
annatisch marked this conversation as resolved.
Show resolved Hide resolved
timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]
],
]],
**kwargs: Any
) -> None: # pylint: disable=super-init-not-called
include_statistics = kwargs.pop("include_statistics", False)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# license information.
# --------------------------------------------------------------------------
from datetime import datetime, timedelta
from typing import Any, cast, Tuple, Union, Sequence, Dict, List
from typing import Any, cast, Tuple, Union, Sequence, Dict, List, Optional

from azure.core.credentials_async import AsyncTokenCredential
from azure.core.exceptions import HttpResponseError
Expand All @@ -30,7 +30,7 @@ class LogsQueryClient(object): # pylint: disable=client-accepts-api-version-keyw
:param credential: The credential to authenticate the client
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:keyword endpoint: The endpoint to connect to. Defaults to 'https://api.loganalytics.io/v1'.
:paramtype endpoint: str
:paramtype endpoint: Optional[str]
"""

def __init__(self, credential: AsyncTokenCredential, **kwargs: Any) -> None:
Expand All @@ -53,9 +53,9 @@ async def query_workspace(
workspace_id: str,
query: str,
*,
timespan: Union[
timespan: Optional[Union[
annatisch marked this conversation as resolved.
Show resolved Hide resolved
timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]
],
]],
**kwargs: Any
) -> Union[LogsQueryResult, LogsQueryPartialResult]:
"""Execute an Analytics query.
Expand All @@ -69,9 +69,10 @@ async def query_workspace(
<https://docs.microsoft.com/azure/data-explorer/kusto/query/>`_.
:type query: str
:keyword timespan: Required. The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
a timedelta and a start datetime, or a start datetime/end datetime. Set to None to not constrain
the query to a timespan.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
or tuple[~datetime.datetime, ~datetime.datetime] or None
: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.
Expand All @@ -80,7 +81,7 @@ async def query_workspace(
visualization to show. If your client requires this information, specify the preference
: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]
:paramtype Optional[additional_workspaces: list[str]]
pvaneck marked this conversation as resolved.
Show resolved Hide resolved
:return: LogsQueryResult if there is a success or LogsQueryPartialResult when there is a partial success.
:rtype: ~azure.monitor.query.LogsQueryResult or ~azure.monitor.query.LogsQueryPartialResult
:raises: ~azure.core.exceptions.HttpResponseError
Expand Down
Loading