Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Monitor Query] Rename MetricsClient param #34760

Merged
merged 1 commit into from Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions sdk/monitor/azure-monitor-query/CHANGELOG.md
Expand Up @@ -12,6 +12,7 @@
- `MetricsBatchQueryClient` has been renamed to `MetricsClient`. ([#33958](https://github.com/Azure/azure-sdk-for-python/pull/33958))
- Reordered the arguments for the async `MetricsClient` constructor so that `endpoint` is now the first positional argument. ([#33752](https://github.com/Azure/azure-sdk-for-python/pull/33752))
- Positional arguments in `MetricsClient.query_resources` are now required keyword-only arguments. ([#33958](https://github.com/Azure/azure-sdk-for-python/pull/33958))
- The `resource_uris` argument in `MetricsClient.query_resources` has been renamed to `resource_ids`. ([#34760](https://github.com/Azure/azure-sdk-for-python/pull/34760))
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved

### Bugs Fixed

Expand Down
18 changes: 9 additions & 9 deletions sdk/monitor/azure-monitor-query/README.md
Expand Up @@ -449,15 +449,15 @@ Interpretation of the visualization data is left to the library consumer. To use

### Metrics query

The following example gets metrics for an Event Grid subscription. The resource URI is that of an Event Grid topic.
The following example gets metrics for an Event Grid subscription. The resource ID (also known as resource URI) is that of an Event Grid topic.

The resource URI must be that of the resource for which metrics are being queried. It's normally of the format `/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>`.
The resource ID must be that of the resource for which metrics are being queried. It's normally of the format `/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>`.

To find the resource URI:
To find the resource ID/URI:

1. Navigate to your resource's page in the Azure portal.
2. From the **Overview** blade, select the **JSON View** link.
3. In the resulting JSON, copy the value of the `id` property.
1. Select the **JSON View** link in the **Overview** section.
1. Copy the value in the **Resource ID** text box at the top of the JSON view.

**NOTE**: The metrics are returned in the order of the metric_names sent.

Expand Down Expand Up @@ -551,17 +551,17 @@ from azure.core.exceptions import HttpResponseError
from azure.identity import DefaultAzureCredential
from azure.monitor.query import MetricsClient, MetricAggregationType


endpoint = "https://westus3.metrics.monitor.azure.com"
credential = DefaultAzureCredential()
client = MetricsClient(endpoint, credential)

resource_uris = [
resource_ids = [
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>",
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-2>"
]

response = client.query_resources(
resource_uris=resource_uris,
resource_ids=resource_ids,
metric_namespace="Microsoft.Storage/storageAccounts",
metric_names=["Ingress"],
timespan=timedelta(hours=2),
Expand Down Expand Up @@ -618,7 +618,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
[azure_subscription]: https://azure.microsoft.com/free/python/
[changelog]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-query/CHANGELOG.md
[kusto_query_language]: https://learn.microsoft.com/azure/data-explorer/kusto/query/
[metric_namespaces]: https://learn.microsoft.com/azure/azure-monitor/reference/supported-metrics/metrics-index#metrics-by-resource-provider
[metric_namespaces]: https://learn.microsoft.com/azure/azure-monitor/reference/supported-metrics/metrics-index#supported-metrics-and-log-categories-by-resource-type
[package]: https://aka.ms/azsdk-python-monitor-query-pypi
[pip]: https://pypi.org/project/pip/
[python_logging]: https://docs.python.org/3/library/logging.html
Expand Down
Expand Up @@ -168,22 +168,22 @@ def process_prefer(server_timeout, include_statistics, include_visualization):
return prefer.rstrip(",")


def get_subscription_id_from_resource(resource_uri: str) -> str:
"""Get the subscription ID from the provided resource URI.
def get_subscription_id_from_resource(resource_id: str) -> str:
"""Get the subscription ID from the provided resource ID.

The format of the resource URI is:
The format of the resource ID is:
/subscriptions/{subscriptionId}/resourceGroups/{group}/providers/{provider}/{type}/{name}

:param str resource_uri: The resource URI to parse.
:param str resource_id: The resource ID to parse.
:returns: The subscription ID.
:rtype: str
"""
if not resource_uri:
raise ValueError("Resource URI must not be None or empty.")
if not resource_id:
raise ValueError("Resource ID must not be None or empty.")

parts = resource_uri.split("subscriptions/")
parts = resource_id.split("subscriptions/")
if len(parts) != 2:
raise ValueError("Resource URI must contain a subscription ID.")
raise ValueError("Resource ID must contain a subscription ID.")

subscription_id = parts[1].split("/")[0]
return subscription_id
Expand Up @@ -50,7 +50,7 @@ def __init__(self, endpoint: str, credential: TokenCredential, **kwargs: Any) ->
def query_resources(
self,
*,
resource_uris: Sequence[str],
resource_ids: Sequence[str],
metric_namespace: str,
metric_names: Sequence[str],
timespan: Optional[Union[timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]]] = None,
Expand All @@ -64,8 +64,8 @@ def query_resources(
) -> List[MetricsQueryResult]:
"""Lists the metric values for multiple resources.

:keyword resource_uris: A list of resource URIs to query metrics for. Required.
:paramtype resource_uris: list[str]
:keyword resource_ids: A list of resource IDs to query metrics for. Required.
:paramtype resource_ids: list[str]
:keyword metric_namespace: Metric namespace that contains the requested metric names. Required.
:paramtype metric_namespace: str
:keyword metric_names: The names of the metrics (comma separated) to retrieve. Required.
Expand Down Expand Up @@ -116,15 +116,15 @@ def query_resources(
:dedent: 0
:caption: Get a response for a batch metrics query.
"""
if not resource_uris:
raise ValueError("resource_uris must be provided and must not be empty.")
if not resource_ids:
raise ValueError("'resource_ids' must be provided and must not be empty.")

# Metric names with commas need to be encoded.
metric_names = [x.replace(",", "%2") for x in metric_names]

start_time, end_time = get_timespan_iso8601_endpoints(timespan)
resource_id_json: JSON = {"resourceids": list(resource_uris)}
subscription_id = get_subscription_id_from_resource(resource_uris[0])
resource_id_json: JSON = {"resourceids": list(resource_ids)}
subscription_id = get_subscription_id_from_resource(resource_ids[0])

generated = self._batch_metrics_op.batch(
subscription_id,
Expand Down
Expand Up @@ -51,7 +51,7 @@ def __init__(self, endpoint: str, credential: AsyncTokenCredential, **kwargs: An
async def query_resources(
self,
*,
resource_uris: Sequence[str],
resource_ids: Sequence[str],
metric_namespace: str,
metric_names: Sequence[str],
timespan: Optional[Union[timedelta, Tuple[datetime, timedelta], Tuple[datetime, datetime]]] = None,
Expand All @@ -65,8 +65,8 @@ async def query_resources(
) -> List[MetricsQueryResult]:
"""Lists the metric values for multiple resources.

:keyword resource_uris: A list of resource URIs to query metrics for. Required.
:paramtype resource_uris: list[str]
:keyword resource_ids: A list of resource IDs to query metrics for. Required.
:paramtype resource_ids: list[str]
:keyword metric_namespace: Metric namespace that contains the requested metric names. Required.
:paramtype metric_namespace: str
:keyword metric_names: The names of the metrics (comma separated) to retrieve. Required.
Expand Down Expand Up @@ -117,15 +117,15 @@ async def query_resources(
:dedent: 0
:caption: Get a response for a batch metrics query.
"""
if not resource_uris:
raise ValueError("resource_uris must be provided and must not be empty.")
if not resource_ids:
raise ValueError("resource_ids must be provided and must not be empty.")

# Metric names with commas need to be encoded.
metric_names = [x.replace(",", "%2") for x in metric_names]

start_time, end_time = get_timespan_iso8601_endpoints(timespan)
resource_id_json: JSON = {"resourceids": list(resource_uris)}
subscription_id = get_subscription_id_from_resource(resource_uris[0])
resource_id_json: JSON = {"resourceids": list(resource_ids)}
subscription_id = get_subscription_id_from_resource(resource_ids[0])

generated = await self._batch_metrics_op.batch(
subscription_id,
Expand Down
Expand Up @@ -13,7 +13,7 @@
This example uses DefaultAzureCredential, which requests a token from Azure Active Directory.
For more information on DefaultAzureCredential, see https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential.

In this example, storage account resource URIs are queried for metrics.
In this example, storage account resources are queried for metrics.
"""
import asyncio

Expand All @@ -33,14 +33,14 @@ async def query_metrics_batch():
credential = DefaultAzureCredential()
client = MetricsClient(endpoint, credential)

resource_uris = [
resource_ids = [
'/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-1>',
'/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-2>'
]
async with client:
try:
response = await client.query_resources(
resource_uris=resource_uris,
resource_ids=resource_ids,
metric_namespace="Microsoft.Storage/storageAccounts",
metric_names=["Ingress"],
timespan=timedelta(hours=2),
Expand Down
Expand Up @@ -13,7 +13,7 @@
This example uses DefaultAzureCredential, which requests a token from Azure Active Directory.
For more information on DefaultAzureCredential, see https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#defaultazurecredential.

In this example, storage account resource URIs are queried for metrics.
In this example, storage account resources are queried for metrics.
"""

# [START send_metrics_batch_query]
Expand All @@ -30,14 +30,14 @@
credential = DefaultAzureCredential()
client = MetricsClient(endpoint, credential)

resource_uris = [
resource_ids = [
'/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-1>',
'/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<account-2>'
]

try:
response = client.query_resources(
resource_uris=resource_uris,
resource_ids=resource_ids,
metric_namespace="Microsoft.Storage/storageAccounts",
metric_names=["Ingress"],
timespan=timedelta(hours=2),
Expand Down
Expand Up @@ -19,7 +19,7 @@ class TestMetricsClient(MetricsClientTestCase):
def test_batch_metrics_auth(self, recorded_test, monitor_info):
client: MetricsClient = self.get_client(MetricsClient, self.get_credential(MetricsClient))
responses = client.query_resources(
resource_uris=[monitor_info['metrics_resource_id']],
resource_ids=[monitor_info['metrics_resource_id']],
metric_namespace=METRIC_RESOURCE_PROVIDER,
metric_names=[METRIC_NAME],
aggregations=[MetricAggregationType.COUNT],
Expand All @@ -30,7 +30,7 @@ def test_batch_metrics_auth(self, recorded_test, monitor_info):
def test_batch_metrics_granularity(self, recorded_test, monitor_info):
client: MetricsClient = self.get_client(MetricsClient, self.get_credential(MetricsClient))
responses = client.query_resources(
resource_uris=[monitor_info['metrics_resource_id']],
resource_ids=[monitor_info['metrics_resource_id']],
metric_namespace=METRIC_RESOURCE_PROVIDER,
metric_names=[METRIC_NAME],
granularity=timedelta(minutes=5),
Expand Down
Expand Up @@ -25,7 +25,7 @@ async def test_batch_metrics_auth(self, recorded_test, monitor_info):
MetricsClient, self.get_credential(MetricsClient, is_async=True))
async with client:
responses = await client.query_resources(
resource_uris=[monitor_info['metrics_resource_id']],
resource_ids=[monitor_info['metrics_resource_id']],
metric_namespace=METRIC_RESOURCE_PROVIDER,
metric_names=[METRIC_NAME],
aggregations=[MetricAggregationType.COUNT],
Expand All @@ -39,7 +39,7 @@ async def test_batch_metrics_granularity(self, recorded_test, monitor_info):
MetricsClient, self.get_credential(MetricsClient, is_async=True))
async with client:
responses = await client.query_resources(
resource_uris=[monitor_info['metrics_resource_id']],
resource_ids=[monitor_info['metrics_resource_id']],
metric_namespace=METRIC_RESOURCE_PROVIDER,
metric_names=[METRIC_NAME],
granularity=timedelta(minutes=5),
Expand Down