Currently, I am trying to get Azure Cosmos DB SQL API account data volume. I fount solution using PowerShell Get-AzMetric command. Does anybody know how it can be solved using .NET SDK or REST API?
Currently, I am trying to get Azure Cosmos DB SQL API account data volume. I fount solution using PowerShell Get-AzMetric command. Does anybody know how it can be solved using .NET SDK or REST API?
Does anybody know how it can be solved using .NET SDK or REST API?
Azure PowerShell is simply a wrapper over REST API. If you run your PowerShell Cmdlet with -Debug parameter, you should see the REST API call being made by the Cmdlet to fetch the data.
For example, if I trace the request/response through Azure Portal for checking the storage size of my database, I noticed the following request is being sent:
https://management.azure.com/subscriptions/<my-subscription-id>/resourceGroups/<my-resource-group>/providers/Microsoft.DocumentDb/databaseAccounts/<my-cosmosdb-account-name>/databases/<my database rid e.g 2942BA==>/metrics?
api-version=2014-04-01&
$filter=(name.value eq 'Available Storage' or name.value eq 'Data Size' or name.value eq 'Index Size')
and endTime eq 2020-04-10T09%3A10%3A00.000Z
and startTime eq 2020-04-10T08%3A10%3A00.000Z and timeGrain eq duration'PT5M'
You could do the same and find out the exact REST API call being made.
The rest api is provided by Gaurav and you can retrieve Monitor metrics and metric definitions using the Azure .NET SDK releases 0.16.0-preview and 0.16.1-preview.
The following code is get Azure Cosmos DB database size. Fore more details, you could refer to this article.
var tenantId = "xxxxxxxx";
var clientSecret = "xxxxxxxx";
var clientId = "xxxxxxxx";
var subscriptionId = "xxxxxxxx";
var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret).GetAwaiter().GetResult();
var monitorClient = new MonitorClient(serviceCreds);
monitorClient.SubscriptionId = subscriptionId;
var resourceUrl = $"subscriptions/xxxxxxxx/resourceGroups/xxxxxxxx/providers/Microsoft.DocumentDB/databaseAccounts/xxxxxxxx/databases/xxxxxx/metrics";
var metricNames = "name.value eq 'Data Size'";
string timeGrain = " and timeGrain eq duration'PT5M'";
string startDate = string.Format(" and startTime eq {0}", DateTime.Now.AddHours(-3).ToString("o"));
string endDate = string.Format(" and endTime eq {0}", DateTime.Now.ToString("o"));
var odataFilterMetrics = new ODataQuery<Metric>(
string.Format(
"{0}{1}{2}{3}",
metricNames,
timeGrain,
startDate,
endDate));
var metrics = monitorClient.Metrics.ListAsync(resourceUrl, odataFilterMetrics).Result;
This can also be achieved by using the REST API of cosmos db, when you make request, x-ms-resource-usage header in the response object has this data
x-ms-resource-usage :
- documentSize=5577
- documentsSize=4422147
- documentsCount=4889177
- collectionSize=5711285