-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
333 lines (296 loc) · 18.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Sql.Fluent;
using Microsoft.Azure.Management.Sql.Fluent.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GettingSqlServerMetrics
{
public class Program
{
private static readonly string sqlServerName = SdkContext.RandomResourceName("sqlserver", 20);
private static readonly string rgName = SdkContext.RandomResourceName("rgsql", 20);
private static readonly string administratorLogin = "sqladmin3423";
private static readonly string administratorPassword = Utilities.CreatePassword();
private static readonly string storageName = SdkContext.RandomResourceName("sqlserver", 20);
private static readonly string dbName = "dbSample";
private static readonly string epName = "epSample";
/**
* Azure SQL sample for getting SQL Server and Databases metrics
* - Create a primary SQL Server with a sample database.
* - Run some queries on the sample database.
* - Create a new table and insert some values into the database.
* - List the SQL subscription usage metrics, the database usage metrics and the other database metrics
* - Use the Monitor Service Fluent APIs to list the SQL Server metrics and the SQL Database metrics
* - Delete Sql Server
*/
public static void RunSample(IAzure azure)
{
string sqlServerName = SdkContext.RandomResourceName("sqlserver", 20);
string rgName = SdkContext.RandomResourceName("rgsql", 20);
Region region = Region.USSouthCentral;
DateTime startTime = DateTime.Now.ToUniversalTime().Subtract(new TimeSpan(1, 0, 0, 0));
try
{
// ============================================================
// Create a SQL Server with one database from a sample.
var sqlServer = azure.SqlServers.Define(sqlServerName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithAdministratorLogin(administratorLogin)
.WithAdministratorPassword(administratorPassword)
.DefineFirewallRule("allowAll")
.WithIPAddressRange("0.0.0.1", "255.255.255.255")
.Attach()
.DefineElasticPool(epName)
.WithStandardPool()
.Attach()
.DefineDatabase(dbName)
.WithExistingElasticPool(epName)
.FromSample(SampleName.AdventureWorksLT)
.Attach()
.Create();
Utilities.PrintSqlServer(sqlServer);
var connectionString = $"user id={administratorLogin};" +
$"password={administratorPassword};" +
$"server={sqlServer.FullyQualifiedDomainName};" +
$"database={dbName}; " +
"Trusted_Connection=False;" +
"Encrypt=True;" +
"connection timeout=30";
// ============================================================
// Create a connection to the SQL Server.
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
// ============================================================
// Create and execute a "select" SQL statement on the sample database.
try
{
sqlConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer",
sqlConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Utilities.Log(myReader["Title"].ToString() + " " +
myReader["FirstName"].ToString() + " " +
myReader["LastName"].ToString());
}
// ============================================================
// Create and execute an "INSERT" SQL statement on the sample database.
string insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES "
+ "('Bike', 'B1', 'Blue', 50, 120, '2016-01-01');";
SqlCommand prepsInsertProduct = new SqlCommand(insertSql, sqlConnection);
prepsInsertProduct.ExecuteNonQuery();
// ============================================================
// Create a new table into the SQL Server database and insert one value.
Utilities.Log("Creating a new table into the SQL Server database and insert one value");
string sqlCreateTableCommand = "CREATE TABLE [Sample_Test] ([Name] [varchar](30) NOT NULL)";
SqlCommand createTable = new SqlCommand(sqlCreateTableCommand, sqlConnection);
createTable.ExecuteNonQuery();
string sqlInsertCommand = "INSERT INTO Sample_Test VALUES ('Test')";
SqlCommand insertValue = new SqlCommand(sqlInsertCommand, sqlConnection);
createTable.ExecuteNonQuery();
// ============================================================
// Run a "select" query for the new table.
Utilities.Log("Running a \"SELECT\" query for the new table");
string sqlSelectNewTableCommand = "SELECT * FROM Sample_Test;";
SqlCommand selectCommand = new SqlCommand(sqlSelectNewTableCommand, sqlConnection);
myReader = selectCommand.ExecuteReader();
while (myReader.Read())
{
Utilities.Log(myReader["Name"].ToString());
}
SdkContext.DelayProvider.Delay(6 * 60 * 1000);
// ============================================================
// List the SQL subscription usage metrics for the current selected region.
Utilities.Log("Listing the SQL subscription usage metrics for the current selected region");
var subscriptionUsageMetrics = azure.SqlServers.ListUsageByRegion(region);
foreach (var usageMetric in subscriptionUsageMetrics)
{
Utilities.PrintSqlMetric(usageMetric);
}
// ============================================================
// List the SQL database usage metrics for the sample database.
Utilities.Log("Listing the SQL database usage metrics for the sample database");
var db = sqlServer.Databases.Get(dbName);
var databaseUsageMetrics = db.ListUsageMetrics();
foreach (var usageMetric in databaseUsageMetrics)
{
Utilities.PrintSqlMetric(usageMetric);
}
// ============================================================
// List the SQL database CPU metrics for the sample database.
Utilities.Log("Listing the SQL database CPU metrics for the sample database");
DateTime endTime = DateTime.Now.ToUniversalTime();
string filter = $"name/value eq 'cpu_percent' and startTime eq '{startTime}' and endTime eq '{endTime}'";
var dbMetrics = db.ListMetrics(filter);
foreach (var metric in dbMetrics)
{
Utilities.PrintSqlMetric(metric);
}
// ============================================================
// List the SQL database metrics for the sample database.
Utilities.Log("Listing the SQL database metrics for the sample database");
filter = $"startTime eq '{startTime}' and endTime eq '{endTime}'";
dbMetrics = db.ListMetrics(filter);
foreach (var metric in dbMetrics)
{
Utilities.PrintSqlMetric(metric);
}
// ============================================================
// Use Monitor Service to list the SQL server metrics.
Utilities.Log("Using Monitor Service to list the SQL server metrics");
var metricDefinitions = azure.MetricDefinitions.ListByResource(sqlServer.Id);
var ep = sqlServer.ElasticPools.Get(epName);
foreach (var metricDefinition in metricDefinitions)
{
// find metric definition for "DTU used" and "Storage used"
if (metricDefinition.Name.LocalizedValue.Equals("dtu used", StringComparison.OrdinalIgnoreCase)
|| metricDefinition.Name.LocalizedValue.Equals("storage used", StringComparison.OrdinalIgnoreCase))
{
// get metric records
var metricCollection = metricDefinition.DefineQuery()
.StartingFrom(startTime)
.EndsBefore(endTime)
.WithAggregation("Average")
.WithInterval(TimeSpan.FromMinutes(5))
.WithOdataFilter($"ElasticPoolResourceId eq '{ep.Id}'")
.Execute();
Utilities.Log($"SQL server \"{sqlServer.Name}\" {metricDefinition.Name.LocalizedValue} metrics\n");
Utilities.Log("\tNamespacse: " + metricCollection.Namespace);
Utilities.Log("\tQuery time: " + metricCollection.Timespan);
Utilities.Log("\tTime Grain: " + metricCollection.Interval);
Utilities.Log("\tCost: " + metricCollection.Cost);
foreach (var metric in metricCollection.Metrics)
{
Utilities.Log("\tMetric: " + metric.Name.LocalizedValue);
Utilities.Log("\tType: " + metric.Type);
Utilities.Log("\tUnit: " + metric.Unit);
Utilities.Log("\tTime Series: ");
foreach (var timeElement in metric.Timeseries)
{
Utilities.Log("\t\tMetadata: ");
foreach (var metadata in timeElement.Metadatavalues)
{
Utilities.Log("\t\t\t" + metadata.Name.LocalizedValue + ": " + metadata.Value);
}
Utilities.Log("\t\tData: ");
foreach (var data in timeElement.Data)
{
Utilities.Log("\t\t\t" + data.TimeStamp
+ " : (Min) " + data.Minimum
+ " : (Max) " + data.Maximum
+ " : (Avg) " + data.Average
+ " : (Total) " + data.Total
+ " : (Count) " + data.Count);
}
}
}
}
}
// ============================================================
// Use Monitor Service to list the SQL Database metrics.
Utilities.Log("Using Monitor Service to list the SQL Database metrics");
metricDefinitions = azure.MetricDefinitions.ListByResource(db.Id);
foreach (var metricDefinition in metricDefinitions)
{
// find metric definition for "dtu used", "cpu used" and "storage"
if (metricDefinition.Name.LocalizedValue.Equals("dtu used", StringComparison.OrdinalIgnoreCase)
|| metricDefinition.Name.LocalizedValue.Equals("cpu used", StringComparison.OrdinalIgnoreCase)
|| metricDefinition.Name.LocalizedValue.Equals("storage used", StringComparison.OrdinalIgnoreCase))
{
// get metric records
var metricCollection = metricDefinition.DefineQuery()
.StartingFrom(startTime)
.EndsBefore(endTime)
.Execute();
Utilities.Log("Metrics for '" + db.Id + "':");
Utilities.Log("\tNamespacse: " + metricCollection.Namespace);
Utilities.Log("\tQuery time: " + metricCollection.Timespan);
Utilities.Log("\tTime Grain: " + metricCollection.Interval);
Utilities.Log("\tCost: " + metricCollection.Cost);
foreach (var metric in metricCollection.Metrics)
{
Utilities.Log("\tMetric: " + metric.Name.LocalizedValue);
Utilities.Log("\tType: " + metric.Type);
Utilities.Log("\tUnit: " + metric.Unit);
Utilities.Log("\tTime Series: ");
foreach (var timeElement in metric.Timeseries)
{
Utilities.Log("\t\tMetadata: ");
foreach (var metadata in timeElement.Metadatavalues)
{
Utilities.Log("\t\t\t" + metadata.Name.LocalizedValue + ": " + metadata.Value);
}
Utilities.Log("\t\tData: ");
foreach (var data in timeElement.Data)
{
Utilities.Log("\t\t\t" + data.TimeStamp
+ " : (Min) " + data.Minimum
+ " : (Max) " + data.Maximum
+ " : (Avg) " + data.Average
+ " : (Total) " + data.Total
+ " : (Count) " + data.Count);
}
}
}
}
}
sqlConnection.Close();
}
catch (Exception e)
{
Utilities.Log(e.ToString());
}
}
// Delete the SQL Server.
Utilities.Log("Deleting a Sql Server");
azure.SqlServers.DeleteById(sqlServer.Id);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e.ToString());
}
}
}
}