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

[Azure.Monitor.Query] Update MetricsQueryResourcesOptions to have StartTime and EndTime #47393

Merged
merged 4 commits into from
Dec 3, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sdk/monitor/Azure.Monitor.Query/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## 1.6.0-beta.1 (Unreleased)

### Features Added

- Add 'StartTime' and 'EndTime' parameters to 'MetricsQueryResourcesOptions' to allow for querying a specific time range
### Breaking Changes

### Bugs Fixed
Expand Down
28 changes: 28 additions & 0 deletions sdk/monitor/Azure.Monitor.Query/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,34 @@ foreach (MetricsQueryResult value in metricsQueryResults.Values)
}
```

The `MetricsQueryResourcesOptions`-typed argument also has a `StartTime` and `EndTime` property to allow for querying a specific time range. If only the `StartTime` is set, the `EndTime` default becomes the current time. When the `EndTime` is specified, the `StartTime` is necessary as well. The following example demonstrates the use of these properties:
```C# Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
string resourceId =
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>";
var client = new MetricsClient(
new Uri("https://<region>.metrics.monitor.azure.com"),
new DefaultAzureCredential());
var options = new MetricsQueryResourcesOptions
{
StartTime = DateTimeOffset.Now.AddHours(-4),
EndTime = DateTimeOffset.Now.AddHours(-1),
OrderBy = "sum asc",
Size = 10
};

Response<MetricsQueryResourcesResult> result = await client.QueryResourcesAsync(
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts",
options).ConfigureAwait(false);

MetricsQueryResourcesResult metricsQueryResults = result.Value;
foreach (MetricsQueryResult value in metricsQueryResults.Values)
{
Console.WriteLine(value.Metrics.Count);
}
```

#### Register the client with dependency injection

To register a client with the dependency injection container, invoke the corresponding extension method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,14 @@ public partial class MetricsQueryResourcesOptions
{
public MetricsQueryResourcesOptions() { }
public System.Collections.Generic.IList<string> Aggregations { get { throw null; } }
public System.DateTimeOffset? EndTime { get { throw null; } set { } }
public string Filter { get { throw null; } set { } }
public System.TimeSpan? Granularity { get { throw null; } set { } }
public string OrderBy { get { throw null; } set { } }
public System.Collections.Generic.IList<string> RollUpBy { get { throw null; } }
public int? Size { get { throw null; } set { } }
public System.DateTimeOffset? StartTime { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Azure.Monitor.Query.QueryTimeRange? TimeRange { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,14 @@ public partial class MetricsQueryResourcesOptions
{
public MetricsQueryResourcesOptions() { }
public System.Collections.Generic.IList<string> Aggregations { get { throw null; } }
public System.DateTimeOffset? EndTime { get { throw null; } set { } }
public string Filter { get { throw null; } set { } }
public System.TimeSpan? Granularity { get { throw null; } set { } }
public string OrderBy { get { throw null; } set { } }
public System.Collections.Generic.IList<string> RollUpBy { get { throw null; } }
public int? Size { get { throw null; } set { } }
public System.DateTimeOffset? StartTime { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Azure.Monitor.Query.QueryTimeRange? TimeRange { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
Expand Down
2 changes: 1 addition & 1 deletion sdk/monitor/Azure.Monitor.Query/assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "net",
"TagPrefix": "net/monitor/Azure.Monitor.Query",
"Tag": "net/monitor/Azure.Monitor.Query_26f5d5d32f"
"Tag": "net/monitor/Azure.Monitor.Query_3bd28d9e3d"
}
15 changes: 14 additions & 1 deletion sdk/monitor/Azure.Monitor.Query/src/MetricsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,24 @@ private async Task<Response<MetricsQueryResourcesResult>> ExecuteBatchAsync(IEnu

if (options != null)
{
if (options.TimeRange != null)
if (options.TimeRange.HasValue)
{
startTime = options.TimeRange.Value.Start.ToIsoString();
endTime = options.TimeRange.Value.End.ToIsoString();
}
else
{
// Use values from Start and End TimeRange properties if they are set
if (options.StartTime.HasValue)
{
startTime = options.StartTime.Value.ToIsoString();
}
if (options.EndTime.HasValue)
{
endTime = options.EndTime.Value.ToIsoString();
}
}

aggregations = MetricsClientExtensions.CommaJoin(options.Aggregations);
top = options.Size;
orderBy = options.OrderBy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Azure.Core;
using Azure.Monitor.Query.Models;

Expand All @@ -16,10 +17,20 @@ public class MetricsQueryResourcesOptions
/// <summary>
/// Gets or sets the timespan over which the metric will be queried. If only the starttime is set, the endtime default becomes the current time. When the endtime is specified, the starttime is necessary as well. Duration is disregarded.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[CodeGenMember("TimeSpan")]
// TODO: https://github.com/Azure/azure-sdk-for-net/issues/46454
public QueryTimeRange? TimeRange { get; set; }

/// <summary>
/// Gets the <see cref="StartTime"/> of the query. If only the <see cref="StartTime"/> is set, the <see cref="EndTime"/> default becomes the current time. When the <see cref="EndTime"/> is specified, the <see cref="StartTime"/> is necessary as well.
/// </summary>
public DateTimeOffset? StartTime { get; set; }

/// <summary>
/// Gets the <see cref="EndTime"/> of the query. If only the <see cref="StartTime"/> is set, the <see cref="EndTime"/> default becomes the current time. When the <see cref="EndTime"/> is specified, the <see cref="StartTime"/> is necessary as well.
/// </summary>
public DateTimeOffset? EndTime { get; set; }

/// <summary>
/// <para>
/// Gets the list of metric aggregations to retrieve.
Expand Down
64 changes: 64 additions & 0 deletions sdk/monitor/Azure.Monitor.Query/tests/MetricsClientLiveTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,5 +173,69 @@ public void MetricsQueryResourcesInvalid()
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts"));
}

[RecordedTest]
public async Task MetricsQueryResourcesWithStartTimeRangeAsync()
{
MetricsClient client = CreateMetricsClient();

var resourceId = TestEnvironment.StorageAccountId;
// If only starttime is specified, then endtime defaults to the current time.
DateTimeOffset start = Recording.UtcNow.Subtract(TimeSpan.FromHours(4));

Response<MetricsQueryResourcesResult> metricsResultsResponse = await client.QueryResourcesAsync(
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts",
options: new MetricsQueryResourcesOptions { StartTime = start }).ConfigureAwait(false);

Assert.AreEqual(200, metricsResultsResponse.GetRawResponse().Status);
MetricsQueryResourcesResult metricsQueryResults = metricsResultsResponse.Value;
Assert.AreEqual(1, metricsQueryResults.Values.Count);
Assert.AreEqual(TestEnvironment.StorageAccountId + "/providers/Microsoft.Insights/metrics/Ingress", metricsQueryResults.Values[0].Metrics[0].Id);
Assert.AreEqual("Microsoft.Storage/storageAccounts", metricsQueryResults.Values[0].Namespace);
}

[RecordedTest]
public async Task MetricsQueryResourcesWithStartTimeEndTimeRangeAsync()
{
MetricsClient client = CreateMetricsClient();

var resourceId = TestEnvironment.StorageAccountId;

DateTimeOffset start = Recording.UtcNow.Subtract(TimeSpan.FromHours(4));
DateTimeOffset end = Recording.UtcNow;

Response<MetricsQueryResourcesResult> metricsResultsResponse = await client.QueryResourcesAsync(
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts",
options: new MetricsQueryResourcesOptions { StartTime = start, EndTime = end }).ConfigureAwait(false);

Assert.AreEqual(200, metricsResultsResponse.GetRawResponse().Status);
MetricsQueryResourcesResult metricsQueryResults = metricsResultsResponse.Value;
Assert.AreEqual(1, metricsQueryResults.Values.Count);
Assert.AreEqual(TestEnvironment.StorageAccountId + "/providers/Microsoft.Insights/metrics/Ingress", metricsQueryResults.Values[0].Metrics[0].Id);
Assert.AreEqual("Microsoft.Storage/storageAccounts", metricsQueryResults.Values[0].Namespace);
}

[Test]
[SyncOnly]
public void MetricsQueryResourcesWithEndTimeRange()
{
MetricsClient client = CreateMetricsClient();

var resourceId = TestEnvironment.StorageAccountId;

// If only the endtime parameter is given, then the starttime parameter is required.
DateTimeOffset end = new DateTimeOffset(TestStartTime).Subtract(TimeSpan.FromHours(4));

Assert.Throws<AggregateException>(() =>
client.QueryResources(
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts",
options: new MetricsQueryResourcesOptions { EndTime = end }));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -307,5 +307,47 @@ public void CreateClientsWithOptions()
logsQueryClientOptions);
#endregion
}

[Test]
public async Task QueryResourcesMetricsWithOptionsStartTimeEndTime()
{
#region Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
#if SNIPPET
string resourceId =
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>";
var client = new MetricsClient(
new Uri("https://<region>.metrics.monitor.azure.com"),
new DefaultAzureCredential());
#else
string resourceId = TestEnvironment.StorageAccountId;
var client = new MetricsClient(
new Uri(TestEnvironment.ConstructMetricsClientUri()),
new DefaultAzureCredential(),
new MetricsClientOptions()
{
Audience = TestEnvironment.GetMetricsClientAudience()
});
#endif
var options = new MetricsQueryResourcesOptions
{
StartTime = DateTimeOffset.Now.AddHours(-4),
EndTime = DateTimeOffset.Now.AddHours(-1),
OrderBy = "sum asc",
Size = 10
};

Response<MetricsQueryResourcesResult> result = await client.QueryResourcesAsync(
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
metricNames: new List<string> { "Ingress" },
metricNamespace: "Microsoft.Storage/storageAccounts",
options).ConfigureAwait(false);

MetricsQueryResourcesResult metricsQueryResults = result.Value;
foreach (MetricsQueryResult value in metricsQueryResults.Values)
{
Console.WriteLine(value.Metrics.Count);
}
#endregion Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
}
}
}
Loading