Skip to content

Commit 1309fee

Browse files
authored
[Azure.Monitor.Query] Update MetricsQueryResourcesOptions to have StartTime and EndTime (Azure#47393)
1 parent 469fc55 commit 1309fee

File tree

9 files changed

+168
-4
lines changed

9 files changed

+168
-4
lines changed

sdk/monitor/Azure.Monitor.Query/CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## 1.6.0-beta.1 (Unreleased)
44

55
### Features Added
6-
6+
- Add 'StartTime' and 'EndTime' parameters to 'MetricsQueryResourcesOptions' to allow for querying a specific time range
77
### Breaking Changes
88

99
### Bugs Fixed

sdk/monitor/Azure.Monitor.Query/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,34 @@ foreach (MetricsQueryResult value in metricsQueryResults.Values)
721721
}
722722
```
723723

724+
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:
725+
```C# Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
726+
string resourceId =
727+
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>";
728+
var client = new MetricsClient(
729+
new Uri("https://<region>.metrics.monitor.azure.com"),
730+
new DefaultAzureCredential());
731+
var options = new MetricsQueryResourcesOptions
732+
{
733+
StartTime = DateTimeOffset.Now.AddHours(-4),
734+
EndTime = DateTimeOffset.Now.AddHours(-1),
735+
OrderBy = "sum asc",
736+
Size = 10
737+
};
738+
739+
Response<MetricsQueryResourcesResult> result = await client.QueryResourcesAsync(
740+
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
741+
metricNames: new List<string> { "Ingress" },
742+
metricNamespace: "Microsoft.Storage/storageAccounts",
743+
options).ConfigureAwait(false);
744+
745+
MetricsQueryResourcesResult metricsQueryResults = result.Value;
746+
foreach (MetricsQueryResult value in metricsQueryResults.Values)
747+
{
748+
Console.WriteLine(value.Metrics.Count);
749+
}
750+
```
751+
724752
#### Register the client with dependency injection
725753

726754
To register a client with the dependency injection container, invoke the corresponding extension method.

sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.net8.0.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,14 @@ public partial class MetricsQueryResourcesOptions
157157
{
158158
public MetricsQueryResourcesOptions() { }
159159
public System.Collections.Generic.IList<string> Aggregations { get { throw null; } }
160+
public System.DateTimeOffset? EndTime { get { throw null; } set { } }
160161
public string Filter { get { throw null; } set { } }
161162
public System.TimeSpan? Granularity { get { throw null; } set { } }
162163
public string OrderBy { get { throw null; } set { } }
163164
public System.Collections.Generic.IList<string> RollUpBy { get { throw null; } }
164165
public int? Size { get { throw null; } set { } }
166+
public System.DateTimeOffset? StartTime { get { throw null; } set { } }
167+
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
165168
public Azure.Monitor.Query.QueryTimeRange? TimeRange { get { throw null; } set { } }
166169
}
167170
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]

sdk/monitor/Azure.Monitor.Query/api/Azure.Monitor.Query.netstandard2.0.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,14 @@ public partial class MetricsQueryResourcesOptions
157157
{
158158
public MetricsQueryResourcesOptions() { }
159159
public System.Collections.Generic.IList<string> Aggregations { get { throw null; } }
160+
public System.DateTimeOffset? EndTime { get { throw null; } set { } }
160161
public string Filter { get { throw null; } set { } }
161162
public System.TimeSpan? Granularity { get { throw null; } set { } }
162163
public string OrderBy { get { throw null; } set { } }
163164
public System.Collections.Generic.IList<string> RollUpBy { get { throw null; } }
164165
public int? Size { get { throw null; } set { } }
166+
public System.DateTimeOffset? StartTime { get { throw null; } set { } }
167+
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
165168
public Azure.Monitor.Query.QueryTimeRange? TimeRange { get { throw null; } set { } }
166169
}
167170
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]

sdk/monitor/Azure.Monitor.Query/assets.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22
"AssetsRepo": "Azure/azure-sdk-assets",
33
"AssetsRepoPrefixPath": "net",
44
"TagPrefix": "net/monitor/Azure.Monitor.Query",
5-
"Tag": "net/monitor/Azure.Monitor.Query_26f5d5d32f"
5+
"Tag": "net/monitor/Azure.Monitor.Query_3bd28d9e3d"
66
}

sdk/monitor/Azure.Monitor.Query/src/MetricsClient.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,24 @@ private async Task<Response<MetricsQueryResourcesResult>> ExecuteBatchAsync(IEnu
148148

149149
if (options != null)
150150
{
151-
if (options.TimeRange != null)
151+
if (options.TimeRange.HasValue)
152152
{
153153
startTime = options.TimeRange.Value.Start.ToIsoString();
154154
endTime = options.TimeRange.Value.End.ToIsoString();
155155
}
156+
else
157+
{
158+
// Use values from Start and End TimeRange properties if they are set
159+
if (options.StartTime.HasValue)
160+
{
161+
startTime = options.StartTime.Value.ToIsoString();
162+
}
163+
if (options.EndTime.HasValue)
164+
{
165+
endTime = options.EndTime.Value.ToIsoString();
166+
}
167+
}
168+
156169
aggregations = MetricsClientExtensions.CommaJoin(options.Aggregations);
157170
top = options.Size;
158171
orderBy = options.OrderBy;

sdk/monitor/Azure.Monitor.Query/src/MetricsQueryResourcesOptions.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Collections.Generic;
6+
using System.ComponentModel;
67
using Azure.Core;
78
using Azure.Monitor.Query.Models;
89

@@ -16,10 +17,20 @@ public class MetricsQueryResourcesOptions
1617
/// <summary>
1718
/// 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.
1819
/// </summary>
20+
[EditorBrowsable(EditorBrowsableState.Never)]
1921
[CodeGenMember("TimeSpan")]
20-
// TODO: https://github.com/Azure/azure-sdk-for-net/issues/46454
2122
public QueryTimeRange? TimeRange { get; set; }
2223

24+
/// <summary>
25+
/// 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.
26+
/// </summary>
27+
public DateTimeOffset? StartTime { get; set; }
28+
29+
/// <summary>
30+
/// 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.
31+
/// </summary>
32+
public DateTimeOffset? EndTime { get; set; }
33+
2334
/// <summary>
2435
/// <para>
2536
/// Gets the list of metric aggregations to retrieve.

sdk/monitor/Azure.Monitor.Query/tests/MetricsClientLiveTests.cs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,5 +173,69 @@ public void MetricsQueryResourcesInvalid()
173173
metricNames: new List<string> { "Ingress" },
174174
metricNamespace: "Microsoft.Storage/storageAccounts"));
175175
}
176+
177+
[RecordedTest]
178+
public async Task MetricsQueryResourcesWithStartTimeRangeAsync()
179+
{
180+
MetricsClient client = CreateMetricsClient();
181+
182+
var resourceId = TestEnvironment.StorageAccountId;
183+
// If only starttime is specified, then endtime defaults to the current time.
184+
DateTimeOffset start = Recording.UtcNow.Subtract(TimeSpan.FromHours(4));
185+
186+
Response<MetricsQueryResourcesResult> metricsResultsResponse = await client.QueryResourcesAsync(
187+
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
188+
metricNames: new List<string> { "Ingress" },
189+
metricNamespace: "Microsoft.Storage/storageAccounts",
190+
options: new MetricsQueryResourcesOptions { StartTime = start }).ConfigureAwait(false);
191+
192+
Assert.AreEqual(200, metricsResultsResponse.GetRawResponse().Status);
193+
MetricsQueryResourcesResult metricsQueryResults = metricsResultsResponse.Value;
194+
Assert.AreEqual(1, metricsQueryResults.Values.Count);
195+
Assert.AreEqual(TestEnvironment.StorageAccountId + "/providers/Microsoft.Insights/metrics/Ingress", metricsQueryResults.Values[0].Metrics[0].Id);
196+
Assert.AreEqual("Microsoft.Storage/storageAccounts", metricsQueryResults.Values[0].Namespace);
197+
}
198+
199+
[RecordedTest]
200+
public async Task MetricsQueryResourcesWithStartTimeEndTimeRangeAsync()
201+
{
202+
MetricsClient client = CreateMetricsClient();
203+
204+
var resourceId = TestEnvironment.StorageAccountId;
205+
206+
DateTimeOffset start = Recording.UtcNow.Subtract(TimeSpan.FromHours(4));
207+
DateTimeOffset end = Recording.UtcNow;
208+
209+
Response<MetricsQueryResourcesResult> metricsResultsResponse = await client.QueryResourcesAsync(
210+
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
211+
metricNames: new List<string> { "Ingress" },
212+
metricNamespace: "Microsoft.Storage/storageAccounts",
213+
options: new MetricsQueryResourcesOptions { StartTime = start, EndTime = end }).ConfigureAwait(false);
214+
215+
Assert.AreEqual(200, metricsResultsResponse.GetRawResponse().Status);
216+
MetricsQueryResourcesResult metricsQueryResults = metricsResultsResponse.Value;
217+
Assert.AreEqual(1, metricsQueryResults.Values.Count);
218+
Assert.AreEqual(TestEnvironment.StorageAccountId + "/providers/Microsoft.Insights/metrics/Ingress", metricsQueryResults.Values[0].Metrics[0].Id);
219+
Assert.AreEqual("Microsoft.Storage/storageAccounts", metricsQueryResults.Values[0].Namespace);
220+
}
221+
222+
[Test]
223+
[SyncOnly]
224+
public void MetricsQueryResourcesWithEndTimeRange()
225+
{
226+
MetricsClient client = CreateMetricsClient();
227+
228+
var resourceId = TestEnvironment.StorageAccountId;
229+
230+
// If only the endtime parameter is given, then the starttime parameter is required.
231+
DateTimeOffset end = new DateTimeOffset(TestStartTime).Subtract(TimeSpan.FromHours(4));
232+
233+
Assert.Throws<AggregateException>(() =>
234+
client.QueryResources(
235+
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
236+
metricNames: new List<string> { "Ingress" },
237+
metricNamespace: "Microsoft.Storage/storageAccounts",
238+
options: new MetricsQueryResourcesOptions { EndTime = end }));
239+
}
176240
}
177241
}

sdk/monitor/Azure.Monitor.Query/tests/MetricsQueryClientSamples.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,5 +307,47 @@ public void CreateClientsWithOptions()
307307
logsQueryClientOptions);
308308
#endregion
309309
}
310+
311+
[Test]
312+
public async Task QueryResourcesMetricsWithOptionsStartTimeEndTime()
313+
{
314+
#region Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
315+
#if SNIPPET
316+
string resourceId =
317+
"/subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/storageAccounts/<resource-name-1>";
318+
var client = new MetricsClient(
319+
new Uri("https://<region>.metrics.monitor.azure.com"),
320+
new DefaultAzureCredential());
321+
#else
322+
string resourceId = TestEnvironment.StorageAccountId;
323+
var client = new MetricsClient(
324+
new Uri(TestEnvironment.ConstructMetricsClientUri()),
325+
new DefaultAzureCredential(),
326+
new MetricsClientOptions()
327+
{
328+
Audience = TestEnvironment.GetMetricsClientAudience()
329+
});
330+
#endif
331+
var options = new MetricsQueryResourcesOptions
332+
{
333+
StartTime = DateTimeOffset.Now.AddHours(-4),
334+
EndTime = DateTimeOffset.Now.AddHours(-1),
335+
OrderBy = "sum asc",
336+
Size = 10
337+
};
338+
339+
Response<MetricsQueryResourcesResult> result = await client.QueryResourcesAsync(
340+
resourceIds: new List<ResourceIdentifier> { new ResourceIdentifier(resourceId) },
341+
metricNames: new List<string> { "Ingress" },
342+
metricNamespace: "Microsoft.Storage/storageAccounts",
343+
options).ConfigureAwait(false);
344+
345+
MetricsQueryResourcesResult metricsQueryResults = result.Value;
346+
foreach (MetricsQueryResult value in metricsQueryResults.Values)
347+
{
348+
Console.WriteLine(value.Metrics.Count);
349+
}
350+
#endregion Snippet:QueryResourcesMetricsWithOptionsStartTimeEndTime
351+
}
310352
}
311353
}

0 commit comments

Comments
 (0)