From f2e872445b656937763f07ed541238bef8ae75d4 Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Wed, 15 Mar 2023 10:35:23 -0700 Subject: [PATCH 1/5] [Monitor][Query] Add resource centric query support This regenerates with autorest and provides an API for users to query Azure Monitor logs directly from a resource instead of going through the context of a Log Analytics workspace. Signed-off-by: Paul Van Eck --- sdk/monitor/azure-monitor-query/CHANGELOG.md | 2 + sdk/monitor/azure-monitor-query/README.md | 44 +- sdk/monitor/azure-monitor-query/assets.json | 2 +- .../_generated/aio/operations/_operations.py | 1386 +++++++++++++--- .../_generated/operations/_operations.py | 1402 ++++++++++++++--- .../azure/monitor/query/_logs_query_client.py | 79 + .../query/aio/_logs_query_client_async.py | 79 + .../azure-monitor-query/samples/README.md | 13 +- .../sample_resource_logs_query_async.py | 59 + .../samples/sample_resource_logs_query.py | 49 + .../swagger/README.PYTHON.md | 9 +- .../tests/test_exceptions.py | 18 + .../tests/test_exceptions_async.py | 22 + .../tests/test_logs_client.py | 25 + .../tests/test_logs_client_async.py | 31 + 15 files changed, 2735 insertions(+), 485 deletions(-) create mode 100644 sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py create mode 100644 sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py diff --git a/sdk/monitor/azure-monitor-query/CHANGELOG.md b/sdk/monitor/azure-monitor-query/CHANGELOG.md index 25b79da8b6de..fc9ffb7dbd56 100644 --- a/sdk/monitor/azure-monitor-query/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-query/CHANGELOG.md @@ -4,6 +4,8 @@ ### Features Added +- Add the `query_resource` method to `LogsQueryClient` to allow users to query Azure resources directly without the context of a workspace. ([#29365](https://github.com/Azure/azure-sdk-for-python/pull/29365)) + ### Breaking Changes ### Bugs Fixed diff --git a/sdk/monitor/azure-monitor-query/README.md b/sdk/monitor/azure-monitor-query/README.md index c39d62341a0c..ee04f9427363 100644 --- a/sdk/monitor/azure-monitor-query/README.md +++ b/sdk/monitor/azure-monitor-query/README.md @@ -92,6 +92,7 @@ Each set of metric values is a time series with the following characteristics: - [Specify timespan](#specify-timespan) - [Handle logs query response](#handle-logs-query-response) - [Batch logs query](#batch-logs-query) +- [Resource logs query](#resource-logs-query) - [Advanced logs query scenarios](#advanced-logs-query-scenarios) - [Set logs query timeout](#set-logs-query-timeout) - [Query multiple workspaces](#query-multiple-workspaces) @@ -103,7 +104,7 @@ Each set of metric values is a time series with the following characteristics: ### Logs query -This example shows getting a logs query. To handle the response and view it in a tabular form, the [pandas](https://pypi.org/project/pandas/) library is used. See the [samples][samples] if you choose not to use pandas. +This example shows how to query a Log Analytics workspace. To handle the response and view it in a tabular form, the [pandas](https://pypi.org/project/pandas/) library is used. See the [samples][samples] if you choose not to use pandas. #### Specify timespan @@ -148,7 +149,7 @@ try: print(df) except HttpResponseError as err: print("something fatal happened") - print (err) + print(err) ``` #### Handle logs query response @@ -219,18 +220,18 @@ requests = [ LogsBatchQuery( query="AzureActivity | summarize count()", timespan=timedelta(hours=1), - workspace_id= os.environ['LOG_WORKSPACE_ID'] + workspace_id=os.environ['LOG_WORKSPACE_ID'] ), LogsBatchQuery( query= """bad query""", timespan=timedelta(days=1), - workspace_id= os.environ['LOG_WORKSPACE_ID'] + workspace_id=os.environ['LOG_WORKSPACE_ID'] ), LogsBatchQuery( query= """let Weight = 92233720368547758; range x from 1 to 3 step 1 | summarize percentilesw(x, Weight * 100, 50)""", - workspace_id= os.environ['LOG_WORKSPACE_ID'], + workspace_id=os.environ['LOG_WORKSPACE_ID'], timespan=(datetime(2021, 6, 2, tzinfo=timezone.utc), datetime(2021, 6, 5, tzinfo=timezone.utc)), # (start, end) include_statistics=True ), @@ -255,6 +256,39 @@ for res in results: ``` +### Resource logs query + +The following example demonstrates how to query logs directly from an Azure resource without the use of a Log Analytics workspace. Here, the `query_resource` method is used instead of `query_workspace`, and instead of a workspace ID, an Azure resource identifier is passed in (e.g. `/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}`). + +```python +import os +import pandas as pd +from datetime import timedelta +from azure.monitor.query import LogsQueryClient, LogsQueryStatus +from azure.core.exceptions import HttpResponseError +from azure.identity import DefaultAzureCredential + +credential = DefaultAzureCredential() +client = LogsQueryClient(credential) + +query = """AzureActivity | take 5""" + +try: + response = client.query_resource(os.environ['LOGS_RESOURCE_ID'], query, timespan=timedelta(days=1)) + if response.status == LogsQueryStatus.PARTIAL: + error = response.partial_error + data = response.partial_data + print(error) + elif response.status == LogsQueryStatus.SUCCESS: + data = response.tables + for table in data: + df = pd.DataFrame(data=table.rows, columns=table.columns) + print(df) +except HttpResponseError as err: + print("something fatal happened") + print(err) +``` + ### Advanced logs query scenarios #### Set logs query timeout diff --git a/sdk/monitor/azure-monitor-query/assets.json b/sdk/monitor/azure-monitor-query/assets.json index d9529eaeb9b0..08104720cd51 100644 --- a/sdk/monitor/azure-monitor-query/assets.json +++ b/sdk/monitor/azure-monitor-query/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/monitor/azure-monitor-query", - "Tag": "python/monitor/azure-monitor-query_86a8ec0380" + "Tag": "python/monitor/azure-monitor-query_bcd06481a4" } diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py index 9d3d19f83ae4..963bdf0fc0ce 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py @@ -30,6 +30,10 @@ build_query_batch_request, build_query_execute_request, build_query_get_request, + build_query_resource_execute_request, + build_query_resource_execute_xms_request, + build_query_resource_get_request, + build_query_resource_get_xms_request, ) if sys.version_info >= (3, 9): @@ -497,16 +501,962 @@ async def execute( return cast(JSON, deserialized) + @distributed_trace_async + async def resource_get( + self, resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource URI. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :keyword query: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :paramtype query: str + :keyword 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. Default value is None. + :paramtype timespan: ~datetime.timedelta + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + request = build_query_resource_get_request( + resource_id=resource_id, + query=query, + timespan=timespan, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + async def resource_execute( + self, + resource_id: str, + body: JSON, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :type body: JSON + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. + ] + } + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + + @overload + async def resource_execute( + self, + resource_id: str, + body: IO, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :type body: IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + + @distributed_trace_async + async def resource_execute( + self, resource_id: str, body: Union[JSON, IO], *, prefer: Optional[str] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. Is + either a JSON type or a IO type. Required. + :type body: JSON or IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. + ] + } + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_query_resource_execute_request( + resource_id=resource_id, + prefer=prefer, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + async def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "requests": [ + { + "body": { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that + are included in the query. + ] + }, + "id": "str", # The error details. Required. + "workspace": "str", # Workspace Id to be included in the + query. Required. + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "method": "str", # Optional. "POST" + "path": "str" # Optional. "/query" + } + ] + } + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. + "message": "str", # A human + readable error message. Required. + "resources": [ + "str" # Optional. + Indicates resources which were responsible for the + error. + ], + "target": "str", # Optional. + Indicates which property in the request is responsible + for the error. + "value": "str" # Optional. + Indicates which value in 'target' is responsible for the + error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON + format. + "statistics": {}, # Optional. Statistics represented + in JSON format. + "tables": [ + { + "columns": [ + { + "name": "str", # The + name of this column. Required. + "type": "str" # The + data type of this column. Required. Known values are: + "bool", "datetime", "dynamic", "int", "long", "real", + "string", "guid", "decimal", and "timespan". + } + ], + "name": "str", # The name of the + table. Required. + "rows": [ + [ + {} # The resulting + rows from this query. Required. + ] + ] + } + ] + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + + @overload + async def batch(self, body: IO, *, content_type: str = "application/json", **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Required. + :type body: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. + "message": "str", # A human + readable error message. Required. + "resources": [ + "str" # Optional. + Indicates resources which were responsible for the + error. + ], + "target": "str", # Optional. + Indicates which property in the request is responsible + for the error. + "value": "str" # Optional. + Indicates which value in 'target' is responsible for the + error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON + format. + "statistics": {}, # Optional. Statistics represented + in JSON format. + "tables": [ + { + "columns": [ + { + "name": "str", # The + name of this column. Required. + "type": "str" # The + data type of this column. Required. Known values are: + "bool", "datetime", "dynamic", "int", "long", "real", + "string", "guid", "decimal", and "timespan". + } + ], + "name": "str", # The name of the + table. Required. + "rows": [ + [ + {} # The resulting + rows from this query. Required. + ] + ] + } + ] + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + + @distributed_trace_async + async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Is either a JSON type or a IO type. Required. + :type body: JSON or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "requests": [ + { + "body": { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that + are included in the query. + ] + }, + "id": "str", # The error details. Required. + "workspace": "str", # Workspace Id to be included in the + query. Required. + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "method": "str", # Optional. "POST" + "path": "str" # Optional. "/query" + } + ] + } + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. + "message": "str", # A human + readable error message. Required. + "resources": [ + "str" # Optional. + Indicates resources which were responsible for the + error. + ], + "target": "str", # Optional. + Indicates which property in the request is responsible + for the error. + "value": "str" # Optional. + Indicates which value in 'target' is responsible for the + error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON + format. + "statistics": {}, # Optional. Statistics represented + in JSON format. + "tables": [ + { + "columns": [ + { + "name": "str", # The + name of this column. Required. + "type": "str" # The + data type of this column. Required. Known values are: + "bool", "datetime", "dynamic", "int", "long", "real", + "string", "guid", "decimal", and "timespan". + } + ], + "name": "str", # The name of the + table. Required. + "rows": [ + [ + {} # The resulting + rows from this query. Required. + ] + ] + } + ] + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_query_batch_request( + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace_async + async def resource_get_xms( + self, resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource URI. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :keyword query: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :paramtype query: str + :keyword 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. Default value is None. + :paramtype timespan: ~datetime.timedelta + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + request = build_query_resource_get_xms_request( + resource_id=resource_id, + query=query, + timespan=timespan, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + @overload - async def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + async def resource_execute_xms( + self, + resource_id: str, + body: JSON, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. :type body: JSON + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -519,113 +1469,89 @@ async def batch(self, body: JSON, *, content_type: str = "application/json", **k # JSON input template you can fill out and use as your body input. body = { - "requests": [ - { - "body": { - "query": "str", # The query to execute. Required. - "timespan": "str", # Optional. 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. - "workspaces": [ - "str" # Optional. A list of workspaces that - are included in the query. - ] - }, - "id": "str", # The error details. Required. - "workspace": "str", # Workspace Id to be included in the - query. Required. - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" - } + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. ] } # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. - "message": "str", # A human - readable error message. Required. - "resources": [ - "str" # Optional. - Indicates resources which were responsible for the - error. - ], - "target": "str", # Optional. - Indicates which property in the request is responsible - for the error. - "value": "str" # Optional. - Indicates which value in 'target' is responsible for the - error. - } - ], - "innererror": ... - }, - "render": {}, # Optional. Visualization data in JSON - format. - "statistics": {}, # Optional. Statistics represented - in JSON format. - "tables": [ - { - "columns": [ - { - "name": "str", # The - name of this column. Required. - "type": "str" # The - data type of this column. Required. Known values are: - "bool", "datetime", "dynamic", "int", "long", "real", - "string", "guid", "decimal", and "timespan". - } - ], - "name": "str", # The name of the - table. Required. - "rows": [ - [ - {} # The resulting - rows from this query. Required. - ] - ] - } + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + ] } - ] + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. } """ @overload - async def batch(self, body: IO, *, content_type: str = "application/json", **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + async def resource_execute_xms( + self, + resource_id: str, + body: IO, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. :type body: IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -638,85 +1564,71 @@ async def batch(self, body: IO, *, content_type: str = "application/json", **kwa # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. - "message": "str", # A human - readable error message. Required. - "resources": [ - "str" # Optional. - Indicates resources which were responsible for the - error. - ], - "target": "str", # Optional. - Indicates which property in the request is responsible - for the error. - "value": "str" # Optional. - Indicates which value in 'target' is responsible for the - error. - } - ], - "innererror": ... - }, - "render": {}, # Optional. Visualization data in JSON - format. - "statistics": {}, # Optional. Statistics represented - in JSON format. - "tables": [ - { - "columns": [ - { - "name": "str", # The - name of this column. Required. - "type": "str" # The - data type of this column. Required. Known values are: - "bool", "datetime", "dynamic", "int", "long", "real", - "string", "guid", "decimal", and "timespan". - } - ], - "name": "str", # The name of the - table. Required. - "rows": [ - [ - {} # The resulting - rows from this query. Required. - ] - ] - } + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + ] } - ] + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. } """ @distributed_trace_async - async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + async def resource_execute_xms( + self, resource_id: str, body: Union[JSON, IO], *, prefer: Optional[str] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Is either a JSON type or a IO type. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. Is + either a JSON type or a IO type. Required. :type body: JSON or IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str @@ -729,100 +1641,61 @@ async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: # JSON input template you can fill out and use as your body input. body = { - "requests": [ - { - "body": { - "query": "str", # The query to execute. Required. - "timespan": "str", # Optional. 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. - "workspaces": [ - "str" # Optional. A list of workspaces that - are included in the query. - ] - }, - "id": "str", # The error details. Required. - "workspace": "str", # Workspace Id to be included in the - query. Required. - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" - } + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. ] } # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. - "message": "str", # A human - readable error message. Required. - "resources": [ - "str" # Optional. - Indicates resources which were responsible for the - error. - ], - "target": "str", # Optional. - Indicates which property in the request is responsible - for the error. - "value": "str" # Optional. - Indicates which value in 'target' is responsible for the - error. - } - ], - "innererror": ... - }, - "render": {}, # Optional. Visualization data in JSON - format. - "statistics": {}, # Optional. Statistics represented - in JSON format. - "tables": [ - { - "columns": [ - { - "name": "str", # The - name of this column. Required. - "type": "str" # The - data type of this column. Required. Known values are: - "bool", "datetime", "dynamic", "int", "long", "real", - "string", "guid", "decimal", and "timespan". - } - ], - "name": "str", # The name of the - table. Required. - "rows": [ - [ - {} # The resulting - rows from this query. Required. - ] - ] - } + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + ] } - ] + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. } """ error_map = { @@ -847,7 +1720,9 @@ async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: else: _json = body - request = build_query_batch_request( + request = build_query_resource_execute_xms_request( + resource_id=resource_id, + prefer=prefer, content_type=content_type, json=_json, content=_content, @@ -856,9 +1731,8 @@ async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: ) request.url = self._client.format_url(request.url) - _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + request, stream=False, **kwargs ) response = pipeline_response.http_response diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py index b448b2e7be5c..31d0f9413905 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py @@ -90,6 +90,59 @@ def build_query_execute_request(workspace_id: str, *, prefer: Optional[str] = No return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) +def build_query_resource_get_request( + resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceId}/query" + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["query"] = _SERIALIZER.query("query", query, "str") + if timespan is not None: + _params["timespan"] = _SERIALIZER.query("timespan", timespan, "duration") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_query_resource_execute_request( + resource_id: str, *, prefer: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceId}/query" + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct headers + if prefer is not None: + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + def build_query_batch_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -107,6 +160,59 @@ def build_query_batch_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) +def build_query_resource_get_xms_request( + resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceId}/query" + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["query"] = _SERIALIZER.query("query", query, "str") + if timespan is not None: + _params["timespan"] = _SERIALIZER.query("timespan", timespan, "duration") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_query_resource_execute_xms_request( + resource_id: str, *, prefer: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/{resourceId}/query" + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct headers + if prefer is not None: + _headers["Prefer"] = _SERIALIZER.header("prefer", prefer, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + def build_metadata_get_request(workspace_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -599,16 +705,147 @@ def execute(self, workspace_id: str, body: Union[JSON, IO], *, prefer: Optional[ return cast(JSON, deserialized) + @distributed_trace + def resource_get( + self, resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource URI. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :keyword query: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :paramtype query: str + :keyword 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. Default value is None. + :paramtype timespan: ~datetime.timedelta + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + request = build_query_resource_get_request( + resource_id=resource_id, + query=query, + timespan=timespan, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + @overload - def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + def resource_execute( + self, + resource_id: str, + body: JSON, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. :type body: JSON + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -621,46 +858,560 @@ def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: # JSON input template you can fill out and use as your body input. body = { - "requests": [ - { - "body": { - "query": "str", # The query to execute. Required. - "timespan": "str", # Optional. 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. - "workspaces": [ - "str" # Optional. A list of workspaces that - are included in the query. - ] - }, - "id": "str", # The error details. Required. - "workspace": "str", # Workspace Id to be included in the - query. Required. - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" - } + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. ] } # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + + @overload + def resource_execute( + self, + resource_id: str, + body: IO, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :type body: IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + + @distributed_trace + def resource_execute( + self, resource_id: str, body: Union[JSON, IO], *, prefer: Optional[str] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. Is + either a JSON type or a IO type. Required. + :type body: JSON or IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. + ] + } + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_query_resource_execute_request( + resource_id=resource_id, + prefer=prefer, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "requests": [ + { + "body": { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that + are included in the query. + ] + }, + "id": "str", # The error details. Required. + "workspace": "str", # Workspace Id to be included in the + query. Required. + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "method": "str", # Optional. "POST" + "path": "str" # Optional. "/query" + } + ] + } + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. + "message": "str", # A human + readable error message. Required. + "resources": [ + "str" # Optional. + Indicates resources which were responsible for the + error. + ], + "target": "str", # Optional. + Indicates which property in the request is responsible + for the error. + "value": "str" # Optional. + Indicates which value in 'target' is responsible for the + error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON + format. + "statistics": {}, # Optional. Statistics represented + in JSON format. + "tables": [ + { + "columns": [ + { + "name": "str", # The + name of this column. Required. + "type": "str" # The + data type of this column. Required. Known values are: + "bool", "datetime", "dynamic", "int", "long", "real", + "string", "guid", "decimal", and "timespan". + } + ], + "name": "str", # The name of the + table. Required. + "rows": [ + [ + {} # The resulting + rows from this query. Required. + ] + ] + } + ] + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + + @overload + def batch(self, body: IO, *, content_type: str = "application/json", **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Required. + :type body: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. + "message": "str", # A human + readable error message. Required. + "resources": [ + "str" # Optional. + Indicates resources which were responsible for the + error. + ], + "target": "str", # Optional. + Indicates which property in the request is responsible + for the error. + "value": "str" # Optional. + Indicates which value in 'target' is responsible for the + error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON + format. + "statistics": {}, # Optional. Statistics represented + in JSON format. + "tables": [ + { + "columns": [ + { + "name": "str", # The + name of this column. Required. + "type": "str" # The + data type of this column. Required. Known values are: + "bool", "datetime", "dynamic", "int", "long", "real", + "string", "guid", "decimal", and "timespan". + } + ], + "name": "str", # The name of the + table. Required. + "rows": [ + [ + {} # The resulting + rows from this query. Required. + ] + ] + } + ] + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + + @distributed_trace + def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: + """Execute a batch of Analytics queries. + + Executes a batch of Analytics queries for data. `Here + `_ is an example for using POST with + an Analytics query. + + :param body: The batch request body. Is either a JSON type or a IO type. Required. + :type body: JSON or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "requests": [ + { + "body": { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that + are included in the query. + ] + }, + "id": "str", # The error details. Required. + "workspace": "str", # Workspace Id to be included in the + query. Required. + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "method": "str", # Optional. "POST" + "path": "str" # Optional. "/query" + } + ] + } + + # response body for status code(s): 200 + response == { + "responses": [ + { + "body": { + "error": { + "code": "str", # A machine readable error + code. Required. + "message": "str", # A human readable error + message. Required. + "details": [ + { + "code": "str", # The error's + code. Required. "message": "str", # A human readable error message. Required. "resources": [ @@ -704,30 +1455,307 @@ def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: ] } ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + }, + "headers": { + "str": "str" # Optional. Dictionary of + :code:``. + }, + "id": "str", # Optional. An array of responses corresponding + to each individual request in a batch. + "status": 0 # Optional. An array of responses corresponding + to each individual request in a batch. + } + ] + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IO, bytes)): + _content = body + else: + _json = body + + request = build_query_batch_request( + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @distributed_trace + def resource_get_xms( + self, resource_id: str, *, query: str, timespan: Optional[datetime.timedelta] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource URI. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :keyword query: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :paramtype query: str + :keyword 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. Default value is None. + :paramtype timespan: ~datetime.timedelta + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + request = build_query_resource_get_xms_request( + resource_id=resource_id, + query=query, + timespan=timespan, + headers=_headers, + params=_params, + ) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) + + return cast(JSON, deserialized) + + @overload + def resource_execute_xms( + self, + resource_id: str, + body: JSON, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. + + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. + + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. + :type body: JSON + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + body = { + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. ] } + + # response body for status code(s): 200 + response == { + "tables": [ + { + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. + ] + ] + } + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. + } """ @overload - def batch(self, body: IO, *, content_type: str = "application/json", **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + def resource_execute_xms( + self, + resource_id: str, + body: IO, + *, + prefer: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. + Required. :type body: IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -740,85 +1768,71 @@ def batch(self, body: IO, *, content_type: str = "application/json", **kwargs: A # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. - "message": "str", # A human - readable error message. Required. - "resources": [ - "str" # Optional. - Indicates resources which were responsible for the - error. - ], - "target": "str", # Optional. - Indicates which property in the request is responsible - for the error. - "value": "str" # Optional. - Indicates which value in 'target' is responsible for the - error. - } - ], - "innererror": ... - }, - "render": {}, # Optional. Visualization data in JSON - format. - "statistics": {}, # Optional. Statistics represented - in JSON format. - "tables": [ - { - "columns": [ - { - "name": "str", # The - name of this column. Required. - "type": "str" # The - data type of this column. Required. Known values are: - "bool", "datetime", "dynamic", "int", "long", "real", - "string", "guid", "decimal", and "timespan". - } - ], - "name": "str", # The name of the - table. Required. - "rows": [ - [ - {} # The resulting - rows from this query. Required. - ] - ] - } + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + ] } - ] + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. } """ @distributed_trace - def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: - """Execute a batch of Analytics queries. + def resource_execute_xms( + self, resource_id: str, body: Union[JSON, IO], *, prefer: Optional[str] = None, **kwargs: Any + ) -> JSON: + """Execute an Analytics query using resource ID. - Executes a batch of Analytics queries for data. `Here - `_ is an example for using POST with - an Analytics query. + Executes an Analytics query for data in the context of a resource. `Here + `_ is an + example for using POST with an Analytics query. - :param body: The batch request body. Is either a JSON type or a IO type. Required. + :param resource_id: The identifier of the resource. Required. + :type resource_id: str + :param body: The Analytics query. Learn more about the `Analytics query syntax + `_. Is + either a JSON type or a IO type. Required. :type body: JSON or IO + :keyword prefer: Optional. The prefer header to set server timeout, query statistics and + visualization information. Default value is None. + :paramtype prefer: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str @@ -831,100 +1845,61 @@ def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: # JSON input template you can fill out and use as your body input. body = { - "requests": [ - { - "body": { - "query": "str", # The query to execute. Required. - "timespan": "str", # Optional. 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. - "workspaces": [ - "str" # Optional. A list of workspaces that - are included in the query. - ] - }, - "id": "str", # The error details. Required. - "workspace": "str", # Workspace Id to be included in the - query. Required. - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" - } + "query": "str", # The query to execute. Required. + "timespan": "str", # Optional. 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. + "workspaces": [ + "str" # Optional. A list of workspaces that are included in the + query. ] } # response body for status code(s): 200 response == { - "responses": [ + "tables": [ { - "body": { - "error": { - "code": "str", # A machine readable error - code. Required. - "message": "str", # A human readable error - message. Required. - "details": [ - { - "code": "str", # The error's - code. Required. - "message": "str", # A human - readable error message. Required. - "resources": [ - "str" # Optional. - Indicates resources which were responsible for the - error. - ], - "target": "str", # Optional. - Indicates which property in the request is responsible - for the error. - "value": "str" # Optional. - Indicates which value in 'target' is responsible for the - error. - } - ], - "innererror": ... - }, - "render": {}, # Optional. Visualization data in JSON - format. - "statistics": {}, # Optional. Statistics represented - in JSON format. - "tables": [ - { - "columns": [ - { - "name": "str", # The - name of this column. Required. - "type": "str" # The - data type of this column. Required. Known values are: - "bool", "datetime", "dynamic", "int", "long", "real", - "string", "guid", "decimal", and "timespan". - } - ], - "name": "str", # The name of the - table. Required. - "rows": [ - [ - {} # The resulting - rows from this query. Required. - ] - ] - } + "columns": [ + { + "name": "str", # The name of this column. + Required. + "type": "str" # The data type of this + column. Required. Known values are: "bool", "datetime", + "dynamic", "int", "long", "real", "string", "guid", "decimal", + and "timespan". + } + ], + "name": "str", # The name of the table. Required. + "rows": [ + [ + {} # The resulting rows from this query. + Required. ] - }, - "headers": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "id": "str", # Optional. An array of responses corresponding - to each individual request in a batch. - "status": 0 # Optional. An array of responses corresponding - to each individual request in a batch. + ] } - ] + ], + "error": { + "code": "str", # A machine readable error code. Required. + "message": "str", # A human readable error message. Required. + "details": [ + { + "code": "str", # The error's code. Required. + "message": "str", # A human readable error message. + Required. + "resources": [ + "str" # Optional. Indicates resources which + were responsible for the error. + ], + "target": "str", # Optional. Indicates which + property in the request is responsible for the error. + "value": "str" # Optional. Indicates which value in + 'target' is responsible for the error. + } + ], + "innererror": ... + }, + "render": {}, # Optional. Visualization data in JSON format. + "statistics": {} # Optional. Statistics represented in JSON format. } """ error_map = { @@ -949,7 +1924,9 @@ def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: else: _json = body - request = build_query_batch_request( + request = build_query_resource_execute_xms_request( + resource_id=resource_id, + prefer=prefer, content_type=content_type, json=_json, content=_content, @@ -958,9 +1935,8 @@ def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: ) request.url = self._client.format_url(request.url) - _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + request, stream=False, **kwargs ) response = pipeline_response.http_response diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py index d9c33481fdcd..867247909ebe 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py @@ -195,6 +195,85 @@ def query_batch( raise_with=LogsQueryError, ) + @distributed_trace + def query_resource( + self, + resource_id: str, + query: str, + *, + timespan: Optional[Union[ + timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]] + ], + **kwargs: Any + ) -> Union[LogsQueryResult, LogsQueryPartialResult]: + """Execute a Kusto query on a resource. + + Returns all the Azure Monitor logs matching the given Kusto query for an Azure resource. + + :param resource_id: The identifier of the resource. The expected format is + '/subscriptions//resourceGroups//providers///'. + :type resource_id: str + :param query: The Kusto query. Learn more about the `Kusto query syntax + `_. + :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. 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 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. + :keyword bool 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. If your client requires this information, specify the preference + :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 + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_resource_logs_query.py + :start-after: [START resource_logs_query] + :end-before: [END resource_logs_query] + :language: python + :dedent: 0 + :caption: Get a response for a single query on a resource's logs. + """ + timespan_iso = construct_iso8601(timespan) + include_statistics = kwargs.pop("include_statistics", False) + include_visualization = kwargs.pop("include_visualization", False) + server_timeout = kwargs.pop("server_timeout", None) + + prefer = process_prefer( + server_timeout, include_statistics, include_visualization + ) + + body = { + "query": query, + "timespan": timespan_iso, + } + + try: + generated_response = ( + self._query_op.resource_execute( # pylint: disable=protected-access + resource_id=resource_id, body=body, prefer=prefer, **kwargs + ) + ) + except HttpResponseError as err: + process_error(err, LogsQueryError) + + response: Union[LogsQueryResult, LogsQueryPartialResult] + if not generated_response.get("error"): + response = LogsQueryResult._from_generated( # pylint: disable=protected-access + generated_response + ) + else: + response = LogsQueryPartialResult._from_generated( # pylint: disable=protected-access + generated_response, LogsQueryError + ) + return response + def close(self) -> None: """Close the :class:`~azure.monitor.query.LogsQueryClient` session.""" return self._client.close() diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py index 7c1706a0d06c..3f2a77bbc30e 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py @@ -160,6 +160,85 @@ async def query_batch( raise_with=LogsQueryError, ) + @distributed_trace_async + async def query_resource( + self, + resource_id: str, + query: str, + *, + timespan: Optional[Union[ + timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]] + ], + **kwargs: Any + ) -> Union[LogsQueryResult, LogsQueryPartialResult]: + """Execute a Kusto query on a resource. + + Returns all the Azure Monitor logs matching the given Kusto query for an Azure resource. + + :param resource_id: The identifier of the resource. The expected format is + '/subscriptions//resourceGroups//providers///'. + :type resource_id: str + :param query: The Kusto query. Learn more about the `Kusto query syntax + `_. + :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. 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 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. + :keyword bool 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. If your client requires this information, specify the preference + :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 + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_resource_logs_query_async.py + :start-after: [START resource_logs_query_async] + :end-before: [END resource_logs_query_async] + :language: python + :dedent: 0 + :caption: Get a response for a single query on a resource's logs. + """ + timespan_iso = construct_iso8601(timespan) + include_statistics = kwargs.pop("include_statistics", False) + include_visualization = kwargs.pop("include_visualization", False) + server_timeout = kwargs.pop("server_timeout", None) + + prefer = process_prefer( + server_timeout, include_statistics, include_visualization + ) + + body = { + "query": query, + "timespan": timespan_iso, + } + + try: + generated_response = ( + await self._query_op.resource_execute( # pylint: disable=protected-access + resource_id=resource_id, body=body, prefer=prefer, **kwargs + ) + ) + except HttpResponseError as err: + process_error(err, LogsQueryError) + + response: Union[LogsQueryResult, LogsQueryPartialResult] + if not generated_response.get("error"): + response = LogsQueryResult._from_generated( # pylint: disable=protected-access + generated_response + ) + else: + response = LogsQueryPartialResult._from_generated( # pylint: disable=protected-access + generated_response, LogsQueryError + ) + return response + async def __aenter__(self) -> "LogsQueryClient": await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-monitor-query/samples/README.md b/sdk/monitor/azure-monitor-query/samples/README.md index 7256329759ec..f4189e4b138e 100644 --- a/sdk/monitor/azure-monitor-query/samples/README.md +++ b/sdk/monitor/azure-monitor-query/samples/README.md @@ -16,12 +16,13 @@ The following code samples show common scenarios with the Azure Monitor Query cl ### Logs query samples -- [Send a single query with LogsQueryClient and handle the response as a table](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_logs_single_query.py) ([async sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/async_samples/sample_log_query_async.py)) -- [Send a single query with LogsQueryClient and handle the response in key-value form](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_logs_query_key_value_form.py) -- [Send a single query with LogsQueryClient without pandas](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_single_log_query_without_pandas.py) -- [Send a single query with LogsQueryClient across multiple workspaces](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_log_query_multiple_workspaces.py) -- [Send multiple queries with LogsQueryClient](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_batch_query.py) -- [Send a single query with LogsQueryClient using server timeout](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_server_timeout.py) +- [Send a single workspace query with LogsQueryClient and handle the response as a table](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_logs_single_query.py) ([async sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/async_samples/sample_log_query_async.py)) +- [Send a single workspace query with LogsQueryClient and handle the response in key-value form](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_logs_query_key_value_form.py) +- [Send a single workspace query with LogsQueryClient without pandas](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_single_log_query_without_pandas.py) +- [Send a single workspace query with LogsQueryClient across multiple workspaces](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_log_query_multiple_workspaces.py) +- [Send multiple workspace queries with LogsQueryClient](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_batch_query.py) +- [Send a single workspace query with LogsQueryClient using server timeout](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_server_timeout.py) +- [Send a single resource query with LogsQueryClient](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py) ([async sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py)) #### Notebook samples diff --git a/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py b/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py new file mode 100644 index 000000000000..79f626891faf --- /dev/null +++ b/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py @@ -0,0 +1,59 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +""" +FILE: sample_resource_logs_query_async.py +DESCRIPTION: + This sample demonstrates authenticating the LogsQueryClient and querying the logs + of a specific resource. Update the `query` variable with a query that corresponds to + your resource. +USAGE: + python sample_resource_logs_query_async.py + Set the environment variables with your own values before running the sample: + 1) LOGS_RESOURCE_ID - The resource ID. Example: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}` + +This example uses DefaultAzureCredential, which requests a token from Azure Active Directory. +For more information on DefaultAzureCredential, see https://docs.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential. + +**Note** - Although this example uses pandas to print the response, it's optional and +isn't a required package for querying. Alternatively, native Python can be used as well. +""" +import asyncio +from datetime import timedelta +import os + +import pandas as pd + +from azure.core.exceptions import HttpResponseError +from azure.identity.aio import DefaultAzureCredential +from azure.monitor.query.aio import LogsQueryClient +from azure.monitor.query import LogsQueryStatus + + +credential = DefaultAzureCredential() +client = LogsQueryClient(credential) + +# [START resource_logs_query_async] +query = """AzureActivity | take 5""" + +async def resource_logs_query(): + async with client: + try: + response = await client.query_resource(os.environ['LOGS_RESOURCE_ID'], query, timespan=timedelta(days=1)) + if response.status == LogsQueryStatus.PARTIAL: + error = response.partial_error + data = response.partial_data + print(error) + elif response.status == LogsQueryStatus.SUCCESS: + data = response.tables + for table in data: + df = pd.DataFrame(data=table.rows, columns=table.columns) + print(df) + except HttpResponseError as err: + print("something fatal happened") + print(err) + await credential.close() + +# [END resource_logs_query_async] + +if __name__ == '__main__': + asyncio.run(resource_logs_query()) diff --git a/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py b/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py new file mode 100644 index 000000000000..ecde81042f21 --- /dev/null +++ b/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py @@ -0,0 +1,49 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +""" +FILE: sample_resource_logs_query.py +DESCRIPTION: + This sample demonstrates authenticating the LogsQueryClient and querying the logs + of a specific resource. Update the `query` variable with a query that corresponds to + your resource. +USAGE: + python sample_resource_logs_query.py + Set the environment variables with your own values before running the sample: + 1) LOGS_RESOURCE_ID - The resource ID. Example: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}` + +This example uses DefaultAzureCredential, which requests a token from Azure Active Directory. +For more information on DefaultAzureCredential, see https://docs.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential. + +**Note** - Although this example uses pandas to print the response, it's optional and +isn't a required package for querying. Alternatively, native Python can be used as well. +""" +import os +import pandas as pd +from datetime import timedelta +from azure.monitor.query import LogsQueryClient, LogsQueryStatus +from azure.core.exceptions import HttpResponseError +from azure.identity import DefaultAzureCredential + + +credential = DefaultAzureCredential() +client = LogsQueryClient(credential) + +# [START resource_logs_query] +query = """AzureActivity | take 5""" + +try: + response = client.query_resource(os.environ['LOGS_RESOURCE_ID'], query, timespan=timedelta(days=1)) + if response.status == LogsQueryStatus.PARTIAL: + error = response.partial_error + data = response.partial_data + print(error) + elif response.status == LogsQueryStatus.SUCCESS: + data = response.tables + for table in data: + df = pd.DataFrame(data=table.rows, columns=table.columns) + print(df) +except HttpResponseError as err: + print("something fatal happened") + print(err) + +# [END resource_logs_query] diff --git a/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md b/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md index f3808a31c598..3d63adfaeaa6 100644 --- a/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md +++ b/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md @@ -31,7 +31,8 @@ batch: These settings apply only when `--tag=release_query` is specified on the command line. ```yaml $(tag) == 'release_query' -input-file: https://github.com/Azure/azure-rest-api-specs/blob/dba6ed1f03bda88ac6884c0a883246446cc72495/specification/operationalinsights/data-plane/Microsoft.OperationalInsights/preview/2021-05-19_Preview/OperationalInsights.json +input-file: + - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/operationalinsights/data-plane/Microsoft.OperationalInsights/preview/2022-10-27_Preview/OperationalInsights.json output-folder: ../azure/monitor/query/_generated title: MonitorQueryClient description: Azure Monitor Query Python Client @@ -43,9 +44,9 @@ These settings apply only when `--tag=release_metrics` is specified on the comma ```yaml $(tag) == 'release_metrics' input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/dba6ed1f03bda88ac6884c0a883246446cc72495/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json - - https://github.com/Azure/azure-rest-api-specs/blob/dba6ed1f03bda88ac6884c0a883246446cc72495/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json - - https://github.com/Azure/azure-rest-api-specs/blob/dba6ed1f03bda88ac6884c0a883246446cc72495/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-12-01-preview/metricNamespaces_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-12-01-preview/metricNamespaces_API.json output-folder: ../azure/monitor/query/_generated/metrics title: MonitorMetricsClient description: Azure Monitor Metrics Python Client diff --git a/sdk/monitor/azure-monitor-query/tests/test_exceptions.py b/sdk/monitor/azure-monitor-query/tests/test_exceptions.py index c2b76d3f992d..6bc757db39cc 100644 --- a/sdk/monitor/azure-monitor-query/tests/test_exceptions.py +++ b/sdk/monitor/azure-monitor-query/tests/test_exceptions.py @@ -33,6 +33,24 @@ def test_logs_single_query_partial_exception(self, recorded_test, monitor_info): assert response.partial_error.code == 'PartialError' assert response.partial_error.__class__ == LogsQueryError + def test_logs_resource_query_fatal_exception(self, recorded_test): + client = self.create_client_from_credential(LogsQueryClient, self.get_credential(LogsQueryClient)) + with pytest.raises(HttpResponseError): + client.query_resource('/bad/resource/id', 'AzureActivity', timespan=None) + + def test_logs_resource_query_partial_exception(self, recorded_test, monitor_info): + client = self.create_client_from_credential(LogsQueryClient, self.get_credential(LogsQueryClient)) + query = """let Weight = 92233720368547758; + range x from 1 to 3 step 1 + | summarize percentilesw(x, Weight * 100, 50)""" + response = client.query_resource(monitor_info['metrics_resource_id'], query, timespan=timedelta(days=1)) + assert response.__class__ == LogsQueryPartialResult + assert response.partial_error is not None + assert response.partial_data is not None + assert response.partial_error.details is not None + assert response.partial_error.code == 'PartialError' + assert response.partial_error.__class__ == LogsQueryError + def test_logs_batch_query_fatal_exception(self, recorded_test, monitor_info): credential = ClientSecretCredential( client_id = monitor_info['client_id'], diff --git a/sdk/monitor/azure-monitor-query/tests/test_exceptions_async.py b/sdk/monitor/azure-monitor-query/tests/test_exceptions_async.py index aa9d37daa6e3..0ae2429490f6 100644 --- a/sdk/monitor/azure-monitor-query/tests/test_exceptions_async.py +++ b/sdk/monitor/azure-monitor-query/tests/test_exceptions_async.py @@ -38,6 +38,28 @@ async def test_logs_single_query_partial_exception_not_allowed(self, recorded_te assert response.partial_error.code == 'PartialError' assert response.partial_error.__class__ == LogsQueryError + @pytest.mark.asyncio + async def test_logs_resource_query_fatal_exception(self, recorded_test): + client = self.create_client_from_credential( + LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True)) + async with client: + with pytest.raises(HttpResponseError): + await client.query_resource('/bad/resource/id', 'AzureActivity', timespan=None) + + @pytest.mark.asyncio + async def test_logs_resource_query_partial_exception(self, recorded_test, monitor_info): + client = self.create_client_from_credential( + LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True)) + async with client: + query = """let Weight = 92233720368547758; + range x from 1 to 3 step 1 + | summarize percentilesw(x, Weight * 100, 50)""" + response = await client.query_resource(monitor_info['metrics_resource_id'], query, timespan=timedelta(days=1)) + assert response.__class__ == LogsQueryPartialResult + assert response.partial_error is not None + assert response.partial_error.code == 'PartialError' + assert response.partial_error.__class__ == LogsQueryError + @pytest.mark.asyncio async def test_logs_batch_query_fatal_exception(self, recorded_test, monitor_info): credential = ClientSecretCredential( diff --git a/sdk/monitor/azure-monitor-query/tests/test_logs_client.py b/sdk/monitor/azure-monitor-query/tests/test_logs_client.py index 3771fa679f4a..dc08b0654920 100644 --- a/sdk/monitor/azure-monitor-query/tests/test_logs_client.py +++ b/sdk/monitor/azure-monitor-query/tests/test_logs_client.py @@ -260,3 +260,28 @@ def test_native_col_type(self): val = native_col_type('datetime', '2020-10-10') assert val is not None + + def test_logs_resource_query(self, recorded_test, monitor_info): + client = self.create_client_from_credential(LogsQueryClient, self.get_credential(LogsQueryClient)) + query = "requests | summarize count()" + + response = client.query_resource(monitor_info['metrics_resource_id'], query, timespan=None) + + assert response is not None + assert response.tables is not None + assert len(response.tables[0].rows) == 1 + + def test_logs_resource_query_additional_options(self, recorded_test, monitor_info): + client = self.create_client_from_credential(LogsQueryClient, self.get_credential(LogsQueryClient)) + query = "requests | summarize count()" + + response = client.query_resource( + monitor_info['metrics_resource_id'], + query, + timespan=None, + include_statistics=True, + include_visualization=True + ) + + assert response.visualization is not None + assert response.statistics is not None diff --git a/sdk/monitor/azure-monitor-query/tests/test_logs_client_async.py b/sdk/monitor/azure-monitor-query/tests/test_logs_client_async.py index b40fac87fcbd..af6b21c30f8a 100644 --- a/sdk/monitor/azure-monitor-query/tests/test_logs_client_async.py +++ b/sdk/monitor/azure-monitor-query/tests/test_logs_client_async.py @@ -228,3 +228,34 @@ async def test_logs_query_result_row_type(self, recorded_test, monitor_info): for row in table.rows: assert row.__class__ == LogsTableRow + + @pytest.mark.asyncio + async def test_logs_resource_query(self, recorded_test, monitor_info): + client = self.create_client_from_credential( + LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True)) + async with client: + query = "requests | summarize count()" + + response = await client.query_resource(monitor_info['metrics_resource_id'], query, timespan=None) + + assert response is not None + assert response.tables is not None + assert len(response.tables[0].rows) == 1 + + @pytest.mark.asyncio + async def test_logs_resource_query_additional_options(self, recorded_test, monitor_info): + client = self.create_client_from_credential( + LogsQueryClient, self.get_credential(LogsQueryClient, is_async=True)) + async with client: + query = "requests | summarize count()" + + response = await client.query_resource( + monitor_info['metrics_resource_id'], + query, + timespan=None, + include_statistics=True, + include_visualization=True + ) + + assert response.visualization is not None + assert response.statistics is not None From 2c7037e8483c9c4275956eb9db7020c860d6327c Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Wed, 22 Mar 2023 12:07:43 -0700 Subject: [PATCH 2/5] Add additional_workspaces argument Signed-off-by: Paul Van Eck --- sdk/monitor/azure-monitor-query/assets.json | 2 +- .../azure/monitor/query/_logs_query_client.py | 11 ++++++++--- .../monitor/query/aio/_logs_query_client_async.py | 11 ++++++++--- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/sdk/monitor/azure-monitor-query/assets.json b/sdk/monitor/azure-monitor-query/assets.json index 08104720cd51..c9c878d05b4f 100644 --- a/sdk/monitor/azure-monitor-query/assets.json +++ b/sdk/monitor/azure-monitor-query/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/monitor/azure-monitor-query", - "Tag": "python/monitor/azure-monitor-query_bcd06481a4" + "Tag": "python/monitor/azure-monitor-query_8b3197a327" } diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py index 867247909ebe..9084f0bc945f 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py @@ -92,9 +92,9 @@ def query_workspace( :keyword bool include_statistics: To get information about query statistics. :keyword bool 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. If your client requires this information, specify the preference + 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. + These can be qualified workspace names, workspace IDs, or Azure resource IDs. :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] @@ -226,7 +226,10 @@ def query_resource( :keyword bool include_statistics: To get information about query statistics. :keyword bool 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. If your client requires this information, specify the preference + 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: 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 @@ -244,6 +247,7 @@ def query_resource( include_statistics = kwargs.pop("include_statistics", False) include_visualization = kwargs.pop("include_visualization", False) server_timeout = kwargs.pop("server_timeout", None) + additional_workspaces = kwargs.pop("additional_workspaces", None) prefer = process_prefer( server_timeout, include_statistics, include_visualization @@ -252,6 +256,7 @@ def query_resource( body = { "query": query, "timespan": timespan_iso, + "workspaces": additional_workspaces } try: diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py index 3f2a77bbc30e..67816889bc33 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py @@ -78,9 +78,9 @@ async def query_workspace( :keyword bool include_statistics: To get information about query statistics. :keyword bool 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. If your client requires this information, specify the preference + 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. + These can be qualified workspace names, workspace IDs, or Azure resource IDs. :paramtype additional_workspaces: Optional[List[str]] :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 @@ -191,7 +191,10 @@ async def query_resource( :keyword bool include_statistics: To get information about query statistics. :keyword bool 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. If your client requires this information, specify the preference + 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: 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 @@ -209,6 +212,7 @@ async def query_resource( include_statistics = kwargs.pop("include_statistics", False) include_visualization = kwargs.pop("include_visualization", False) server_timeout = kwargs.pop("server_timeout", None) + additional_workspaces = kwargs.pop("additional_workspaces", None) prefer = process_prefer( server_timeout, include_statistics, include_visualization @@ -217,6 +221,7 @@ async def query_resource( body = { "query": query, "timespan": timespan_iso, + "additional_workspaces": additional_workspaces, } try: From c59d0ed6d5c20eb0d09f8ddf5182719f37cea77d Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Thu, 30 Mar 2023 15:24:58 -0700 Subject: [PATCH 3/5] Fix spacing Signed-off-by: Paul Van Eck --- .../azure/monitor/query/_logs_query_client.py | 2 +- .../azure/monitor/query/aio/_logs_query_client_async.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py index 9084f0bc945f..030cc77bb45f 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_logs_query_client.py @@ -210,7 +210,7 @@ def query_resource( Returns all the Azure Monitor logs matching the given Kusto query for an Azure resource. - :param resource_id: The identifier of the resource. The expected format is + :param resource_id: The identifier of the resource. The expected format is '/subscriptions//resourceGroups//providers///'. :type resource_id: str :param query: The Kusto query. Learn more about the `Kusto query syntax diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py index 67816889bc33..5e9a9937029c 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/aio/_logs_query_client_async.py @@ -175,7 +175,7 @@ async def query_resource( Returns all the Azure Monitor logs matching the given Kusto query for an Azure resource. - :param resource_id: The identifier of the resource. The expected format is + :param resource_id: The identifier of the resource. The expected format is '/subscriptions//resourceGroups//providers///'. :type resource_id: str :param query: The Kusto query. Learn more about the `Kusto query syntax From d596ae4479531a8b7ce1f1f22436785c1d6020cc Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Tue, 4 Apr 2023 17:50:16 -0700 Subject: [PATCH 4/5] Regen with stable swagger Signed-off-by: Paul Van Eck --- .../_generated/aio/operations/_operations.py | 24 ++++++++++++------- .../metrics/aio/operations/_operations.py | 12 +++------- .../metrics/operations/_operations.py | 20 +++++----------- .../_generated/operations/_operations.py | 24 ++++++++++++------- .../swagger/README.PYTHON.md | 8 +++---- 5 files changed, 45 insertions(+), 43 deletions(-) diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py index 963bdf0fc0ce..f0348923300b 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/aio/operations/_operations.py @@ -597,8 +597,9 @@ async def resource_get( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -916,8 +917,9 @@ async def resource_execute( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -978,8 +980,10 @@ async def batch(self, body: JSON, *, content_type: str = "application/json", **k "str": "str" # Optional. Dictionary of :code:``. }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" + "method": "POST", # Optional. Default value is "POST". An + single request in a batch. Required. + "path": "/query" # Optional. Default value is "/query". An + single request in a batch. Required. } ] } @@ -1188,8 +1192,10 @@ async def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: "str": "str" # Optional. Dictionary of :code:``. }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" + "method": "POST", # Optional. Default value is "POST". An + single request in a batch. Required. + "path": "/query" # Optional. Default value is "/query". An + single request in a batch. Required. } ] } @@ -1412,8 +1418,9 @@ async def resource_get_xms( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1731,8 +1738,9 @@ async def resource_execute_xms( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/aio/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/aio/operations/_operations.py index 9d075be9706f..8f3e2c3a81bc 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/aio/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/aio/operations/_operations.py @@ -36,10 +36,6 @@ from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -128,7 +124,7 @@ def list(self, resource_uri: str, *, metricnamespace: Optional[str] = None, **kw _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) cls: ClsType[JSON] = kwargs.pop("cls", None) error_map = { @@ -351,7 +347,7 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) cls: ClsType[JSON] = kwargs.pop("cls", None) request = build_metrics_list_request( @@ -441,9 +437,7 @@ def list(self, resource_uri: str, *, start_time: Optional[str] = None, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2017-12-01-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2017-12-01-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01-preview")) cls: ClsType[JSON] = kwargs.pop("cls", None) error_map = { diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/operations/_operations.py index 5f4b4039f207..1bd4eae71981 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/metrics/operations/_operations.py @@ -32,10 +32,6 @@ from collections.abc import MutableMapping else: from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -50,7 +46,7 @@ def build_metric_definitions_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -89,7 +85,7 @@ def build_metrics_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -133,9 +129,7 @@ def build_metric_namespaces_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2017-12-01-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2017-12-01-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -240,7 +234,7 @@ def list(self, resource_uri: str, *, metricnamespace: Optional[str] = None, **kw _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) cls: ClsType[JSON] = kwargs.pop("cls", None) error_map = { @@ -463,7 +457,7 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2018-01-01"] = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) cls: ClsType[JSON] = kwargs.pop("cls", None) request = build_metrics_list_request( @@ -553,9 +547,7 @@ def list(self, resource_uri: str, *, start_time: Optional[str] = None, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2017-12-01-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2017-12-01-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01-preview")) cls: ClsType[JSON] = kwargs.pop("cls", None) error_map = { diff --git a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py index 31d0f9413905..bd821f65b3e7 100644 --- a/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py +++ b/sdk/monitor/azure-monitor-query/azure/monitor/query/_generated/operations/_operations.py @@ -801,8 +801,9 @@ def resource_get( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1120,8 +1121,9 @@ def resource_execute( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1182,8 +1184,10 @@ def batch(self, body: JSON, *, content_type: str = "application/json", **kwargs: "str": "str" # Optional. Dictionary of :code:``. }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" + "method": "POST", # Optional. Default value is "POST". An + single request in a batch. Required. + "path": "/query" # Optional. Default value is "/query". An + single request in a batch. Required. } ] } @@ -1392,8 +1396,10 @@ def batch(self, body: Union[JSON, IO], **kwargs: Any) -> JSON: "str": "str" # Optional. Dictionary of :code:``. }, - "method": "str", # Optional. "POST" - "path": "str" # Optional. "/query" + "method": "POST", # Optional. Default value is "POST". An + single request in a batch. Required. + "path": "/query" # Optional. Default value is "/query". An + single request in a batch. Required. } ] } @@ -1616,8 +1622,9 @@ def resource_get_xms( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1935,8 +1942,9 @@ def resource_execute_xms( ) request.url = self._client.format_url(request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response diff --git a/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md b/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md index 3d63adfaeaa6..907460668c0d 100644 --- a/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md +++ b/sdk/monitor/azure-monitor-query/swagger/README.PYTHON.md @@ -32,7 +32,7 @@ These settings apply only when `--tag=release_query` is specified on the command ```yaml $(tag) == 'release_query' input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/operationalinsights/data-plane/Microsoft.OperationalInsights/preview/2022-10-27_Preview/OperationalInsights.json + - https://github.com/Azure/azure-rest-api-specs/blob/605407bc0c1a133018285f550d01175469cb3c3a/specification/operationalinsights/data-plane/Microsoft.OperationalInsights/stable/2022-10-27/OperationalInsights.json output-folder: ../azure/monitor/query/_generated title: MonitorQueryClient description: Azure Monitor Query Python Client @@ -44,9 +44,9 @@ These settings apply only when `--tag=release_metrics` is specified on the comma ```yaml $(tag) == 'release_metrics' input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json - - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json - - https://github.com/Azure/azure-rest-api-specs/blob/fc3c409825d6a31ba909a88ea34dcc13165edc9c/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-12-01-preview/metricNamespaces_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/605407bc0c1a133018285f550d01175469cb3c3a/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/605407bc0c1a133018285f550d01175469cb3c3a/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json + - https://github.com/Azure/azure-rest-api-specs/blob/605407bc0c1a133018285f550d01175469cb3c3a/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-12-01-preview/metricNamespaces_API.json output-folder: ../azure/monitor/query/_generated/metrics title: MonitorMetricsClient description: Azure Monitor Metrics Python Client From a5d4b11fa16e75811c7feed99d1dc91f582311d0 Mon Sep 17 00:00:00 2001 From: Paul Van Eck Date: Wed, 5 Apr 2023 17:44:21 -0700 Subject: [PATCH 5/5] Move code snippet starting points This provides more context and makes the code more copy/paste-able. Signed-off-by: Paul Van Eck --- .../samples/async_samples/sample_resource_logs_query_async.py | 3 ++- .../azure-monitor-query/samples/sample_resource_logs_query.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py b/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py index 79f626891faf..6184a9b64869 100644 --- a/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py +++ b/sdk/monitor/azure-monitor-query/samples/async_samples/sample_resource_logs_query_async.py @@ -18,6 +18,8 @@ isn't a required package for querying. Alternatively, native Python can be used as well. """ import asyncio + +# [START resource_logs_query_async] from datetime import timedelta import os @@ -32,7 +34,6 @@ credential = DefaultAzureCredential() client = LogsQueryClient(credential) -# [START resource_logs_query_async] query = """AzureActivity | take 5""" async def resource_logs_query(): diff --git a/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py b/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py index ecde81042f21..52af049acfd5 100644 --- a/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py +++ b/sdk/monitor/azure-monitor-query/samples/sample_resource_logs_query.py @@ -17,18 +17,18 @@ **Note** - Although this example uses pandas to print the response, it's optional and isn't a required package for querying. Alternatively, native Python can be used as well. """ +# [START resource_logs_query] import os import pandas as pd from datetime import timedelta -from azure.monitor.query import LogsQueryClient, LogsQueryStatus from azure.core.exceptions import HttpResponseError from azure.identity import DefaultAzureCredential +from azure.monitor.query import LogsQueryClient, LogsQueryStatus credential = DefaultAzureCredential() client = LogsQueryClient(credential) -# [START resource_logs_query] query = """AzureActivity | take 5""" try: