-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Program.cs
520 lines (483 loc) · 24.6 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/*
* Copyright (c) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using CommandLine;
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Api.MetricDescriptor.Types;
namespace GoogleCloudSamples
{
[Verb("create", HelpText = "Create a metric descriptor for this project.")]
class CreateOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric type of the metric to create.", Required = false,
Default = "custom.googleapis.com/stores/daily_sales")]
public string metricType { get; set; }
}
[Verb("list", HelpText = "List metric descriptors for this project.")]
class ListOptions : CreateAndListOptions { }
[Verb("listGroups", HelpText = "List metric groups for this project.")]
class ListGroupsOptions : CreateAndListOptions { }
[Verb("listResources", HelpText = "List monitored resources for this project.")]
class ListMonitoredResourcesOptions : CreateAndListOptions { }
class CreateAndListOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
}
[Verb("get", HelpText = "Get a metric descriptor's details.")]
class GetOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric descriptor type of the metric to display details for.", Required = true)]
public string metricType { get; set; }
}
[Verb("getResource", HelpText = "Get a monitored resource descriptor.")]
class GetMonitoredResourceOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The resource descriptor ID of the metric to display details for.", Required = true)]
public string resourceId { get; set; }
}
[Verb("write", HelpText = "Write TimeSeries data to custom metric.")]
class WriteTimeSeriesDataOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
}
[Verb("read", HelpText = "Read TimeSeries data from a metric.")]
class ReadTimeSeriesDataOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric type of the metric to read timeseries data from.", Required = false,
Default = "compute.googleapis.com/instance/cpu/utilization")]
public string metricType { get; set; }
}
[Verb("readFields", HelpText = "Reads headers of time series data.")]
class ReadTimeSeriesFieldsOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric type of the metric to read timeseries data from.", Required = false, Default = "compute.googleapis.com/instance/cpu/utilization")]
public string metricType { get; set; }
}
[Verb("readAggregate", HelpText = "Aggregates time series data that matches the specified metric type.")]
class ReadTimeSeriesAggregateOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric type of the metric to read time series data from.", Required = false, Default = "compute.googleapis.com/instance/cpu/utilization")]
public string metricType { get; set; }
}
[Verb("readReduce", HelpText = "Reduces time series data that matches the specified metric type.")]
class ReadTimeSeriesReduceOptions
{
[Value(0, HelpText = "The project ID of the project to use for monitoring operations.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric type of the metric to read time series data from.", Required = false, Default = "compute.googleapis.com/instance/cpu/utilization")]
public string metricType { get; set; }
}
[Verb("delete", HelpText = "Delete a metric descriptor for this project.")]
class DeleteOptions
{
[Value(0, HelpText = "The project ID of the project containing the metric descriptor to delete.", Required = true)]
public string projectId { get; set; }
[Value(1, HelpText = "The metric descriptor type of the metric to delete.", Required = true)]
public string metricType { get; set; }
}
public class Monitoring
{
private static readonly DateTime s_unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
// [START monitoring_create_metric]
public static object CreateMetric(string projectId,
string metricType = "custom.googleapis.com/stores/daily_sales")
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Prepare custom metric descriptor.
MetricDescriptor metricDescriptor = new MetricDescriptor();
metricDescriptor.DisplayName = "Daily Sales";
metricDescriptor.Description = "Daily sales records from all branch stores.";
metricDescriptor.MetricKind = MetricKind.Gauge;
metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
metricDescriptor.Type = metricType;
metricDescriptor.Unit = "{USD}";
LabelDescriptor labels = new LabelDescriptor();
labels.Key = "store_id";
labels.ValueType = LabelDescriptor.Types.ValueType.String;
labels.Description = "The ID of the store.";
metricDescriptor.Labels.Add(labels);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName(projectId),
};
request.MetricDescriptor = metricDescriptor;
// Make the request.
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
Console.WriteLine("Done creating metric descriptor:");
Console.WriteLine(JObject.Parse($"{response}").ToString());
return 0;
}
// [END monitoring_create_metric]
// [START monitoring_delete_metric]
public static object DeleteMetric(string projectId, string metricType)
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
// Make the request.
metricServiceClient.DeleteMetricDescriptor(name);
Console.WriteLine($"Done deleting metric descriptor: {name}");
return 0;
}
// [END monitoring_delete_metric]
// [START monitoring_list_descriptors]
public static object ListMetrics(string projectId)
{
MetricServiceClient client = MetricServiceClient.Create();
ProjectName projectName = new ProjectName(projectId);
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName);
foreach (MetricDescriptor metric in metrics)
{
Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
}
return 0;
}
// [END monitoring_list_descriptors]
// [START monitoring_get_descriptor]
public static object GetMetricDetails(string projectId, string metricType)
{
MetricServiceClient client = MetricServiceClient.Create();
MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
try
{
var response = client.GetMetricDescriptor(name);
string metric = JObject.Parse($"{response}").ToString();
Console.WriteLine($"{ metric }");
}
catch (Grpc.Core.RpcException ex)
when (ex.Status.StatusCode == Grpc.Core.StatusCode.NotFound)
{ }
return 0;
}
// [END monitoring_get_descriptor]
// [START monitoring_write_timeseries]
public static object WriteTimeSeriesData(string projectId)
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
ProjectName name = new ProjectName(projectId);
// Prepare a data point.
Point dataPoint = new Point();
TypedValue salesTotal = new TypedValue();
salesTotal.DoubleValue = 123.45;
dataPoint.Value = salesTotal;
Timestamp timeStamp = new Timestamp();
timeStamp.Seconds = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
TimeInterval interval = new TimeInterval();
interval.EndTime = timeStamp;
dataPoint.Interval = interval;
// Prepare custom metric.
Metric metric = new Metric();
metric.Type = "custom.googleapis.com/stores/daily_sales";
metric.Labels.Add("store_id", "Pittsburgh");
// Prepare monitored resource.
MonitoredResource resource = new MonitoredResource();
resource.Type = "global";
resource.Labels.Add("project_id", projectId);
// Create a new time series using inputs.
TimeSeries timeSeriesData = new TimeSeries();
timeSeriesData.Metric = metric;
timeSeriesData.Resource = resource;
timeSeriesData.Points.Add(dataPoint);
// Add newly created time series to list of time series to be written.
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries> { timeSeriesData };
// Write time series data.
metricServiceClient.CreateTimeSeries(name, timeSeries);
Console.WriteLine("Done writing time series data:");
Console.WriteLine(JObject.Parse($"{timeSeriesData}").ToString());
return 0;
}
// [END monitoring_write_timeseries]
// [START monitoring_read_timeseries_simple]
public static object ReadTimeSeriesData(string projectId,
string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
string filter = $"metric.type=\"{metricType}\"";
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName(projectId),
Filter = filter,
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
};
// Create timestamp for current time formatted in seconds.
long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
Timestamp startTimeStamp = new Timestamp();
// Set startTime to limit results to the last 20 minutes.
startTimeStamp.Seconds = timeStamp - (60 * 20);
Timestamp endTimeStamp = new Timestamp();
// Set endTime to current time.
endTimeStamp.Seconds = timeStamp;
TimeInterval interval = new TimeInterval();
interval.StartTime = startTimeStamp;
interval.EndTime = endTimeStamp;
request.Interval = interval;
// Make the request.
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required.
foreach (TimeSeries item in response)
{
Console.WriteLine(JObject.Parse($"{item}").ToString());
}
return 0;
}
// [END monitoring_read_timeseries_simple]
// [START monitoring_read_timeseries_fields]
public static object ReadTimeSeriesFields(string projectId,
string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
Console.WriteLine($"metricType{ metricType}");
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
string filter = $"metric.type=\"{metricType}\"";
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName(projectId),
Filter = filter,
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Headers,
};
// Create timestamp for current time formatted in seconds.
long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
Timestamp startTimeStamp = new Timestamp();
// Set startTime to limit results to the last 20 minutes.
startTimeStamp.Seconds = timeStamp - (60 * 20);
Timestamp endTimeStamp = new Timestamp();
// Set endTime to current time.
endTimeStamp.Seconds = timeStamp;
TimeInterval interval = new TimeInterval();
interval.StartTime = startTimeStamp;
interval.EndTime = endTimeStamp;
request.Interval = interval;
// Make the request.
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required.
Console.Write("Found data points for the following instances:");
foreach (var item in response)
{
Console.WriteLine(JObject.Parse($"{item}").ToString());
}
return 0;
}
// [END monitoring_read_timeseries_fields]
// [START monitoring_read_timeseries_align]
public static object ReadTimeSeriesAggregate(string projectId,
string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
string filter = $"metric.type=\"{metricType}\"";
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName(projectId),
Filter = filter,
Interval = new TimeInterval(),
};
// Create timestamp for current time formatted in seconds.
long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
Timestamp startTimeStamp = new Timestamp();
// Set startTime to limit results to the last 20 minutes.
startTimeStamp.Seconds = timeStamp - (60 * 20);
Timestamp endTimeStamp = new Timestamp();
// Set endTime to current time.
endTimeStamp.Seconds = timeStamp;
TimeInterval interval = new TimeInterval();
interval.StartTime = startTimeStamp;
interval.EndTime = endTimeStamp;
request.Interval = interval;
// Aggregate results per matching instance
Aggregation aggregation = new Aggregation();
Duration alignmentPeriod = new Duration();
alignmentPeriod.Seconds = 600;
aggregation.AlignmentPeriod = alignmentPeriod;
aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
// Add the aggregation to the request.
request.Aggregation = aggregation;
// Make the request.
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required.
Console.WriteLine($"{projectId} CPU utilization:");
foreach (var item in response)
{
var points = item.Points;
var labels = item.Metric.Labels;
Console.WriteLine($"{labels.Values.FirstOrDefault()}");
if (points.Count > 0)
{
Console.WriteLine($" Now: {points[0].Value.DoubleValue}");
}
if (points.Count > 1)
{
Console.WriteLine($" 10 min ago: {points[1].Value.DoubleValue}");
}
}
return 0;
}
// [END monitoring_read_timeseries_align]
// [START monitoring_read_timeseries_reduce]
public static object ReadTimeSeriesReduce(string projectId,
string metricType = "compute.googleapis.com/instance/cpu/utilization")
{
// Create client.
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s).
string filter = $"metric.type=\"{metricType}\"";
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName(projectId),
Filter = filter,
Interval = new TimeInterval(),
};
// Create timestamp for current time formatted in seconds.
long timeStamp = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
Timestamp startTimeStamp = new Timestamp();
// Set startTime to limit results to the last 20 minutes.
startTimeStamp.Seconds = timeStamp - (60 * 20);
Timestamp endTimeStamp = new Timestamp();
// Set endTime to current time.
endTimeStamp.Seconds = timeStamp;
TimeInterval interval = new TimeInterval();
interval.StartTime = startTimeStamp;
interval.EndTime = endTimeStamp;
request.Interval = interval;
// Aggregate results per matching instance.
Aggregation aggregation = new Aggregation();
Duration alignmentPeriod = new Duration();
alignmentPeriod.Seconds = 600;
aggregation.AlignmentPeriod = alignmentPeriod;
aggregation.CrossSeriesReducer = Aggregation.Types.Reducer.ReduceMean;
aggregation.PerSeriesAligner = Aggregation.Types.Aligner.AlignMean;
// Add the aggregation to the request.
request.Aggregation = aggregation;
// Make the request.
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required.
Console.WriteLine("CPU utilization:");
foreach (var item in response)
{
var points = item.Points;
Console.WriteLine("Average CPU utilization across all GCE instances:");
Console.WriteLine($" Last 10 min: {points[0].Value.DoubleValue}");
Console.WriteLine($" Last 10-20 min ago: {points[1].Value.DoubleValue}");
}
return 0;
}
// [END monitoring_read_timeseries_reduce]
// [START monitoring_list_resources]
public static object ListMonitoredResources(string projectId)
{
Console.WriteLine("Starting to List Monitored Resources...");
MetricServiceClient client = MetricServiceClient.Create();
ProjectName projectName = new ProjectName(projectId);
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor>
resources = client.ListMonitoredResourceDescriptors(projectName);
if (resources.Any())
{
foreach (MonitoredResourceDescriptor resource in resources.Take(10))
{
Console.WriteLine($"{resource.Name}: {resource.DisplayName}");
}
}
else
{
Console.WriteLine("No resources found.");
}
return 0;
}
// [END monitoring_list_resources]
// [START monitoring_get_resource]
public static object GetMonitoredResource(string projectId, string resourceId)
{
MetricServiceClient client = MetricServiceClient.Create();
MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName(projectId, resourceId);
var response = client.GetMonitoredResourceDescriptor(name);
string resource = JObject.Parse($"{response}").ToString();
Console.WriteLine($"{ resource }");
return 0;
}
// [END monitoring_get_resource]
public static object ListGroups(string projectId)
{
GroupServiceClient client = GroupServiceClient.Create();
ProjectName projectName = new ProjectName(projectId);
ListGroupsRequest request = new ListGroupsRequest { Name = projectName.ToString() };
PagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(request);
foreach (Group group in groups.Take(10))
{
Console.WriteLine($"{group.Name}: {group.DisplayName}");
}
return 0;
}
public static void Main(string[] args)
{
Parser.Default.ParseArguments<
CreateOptions, ListOptions, GetOptions,
WriteTimeSeriesDataOptions,
ReadTimeSeriesDataOptions, ReadTimeSeriesFieldsOptions,
ReadTimeSeriesAggregateOptions, ReadTimeSeriesReduceOptions,
DeleteOptions, ListMonitoredResourcesOptions,
GetMonitoredResourceOptions, ListGroupsOptions
>(args)
.MapResult(
(CreateOptions opts) => CreateMetric(opts.projectId, opts.metricType),
(ListOptions opts) => ListMetrics(opts.projectId),
(GetOptions opts) => GetMetricDetails(opts.projectId, opts.metricType),
(WriteTimeSeriesDataOptions opts) => WriteTimeSeriesData(opts.projectId),
(ReadTimeSeriesDataOptions opts) => ReadTimeSeriesData(opts.projectId, opts.metricType),
(ReadTimeSeriesFieldsOptions opts) => ReadTimeSeriesFields(opts.projectId, opts.metricType),
(ReadTimeSeriesAggregateOptions opts) => ReadTimeSeriesAggregate(opts.projectId, opts.metricType),
(ReadTimeSeriesReduceOptions opts) => ReadTimeSeriesReduce(opts.projectId, opts.metricType),
(DeleteOptions opts) => DeleteMetric(opts.projectId, opts.metricType),
(ListMonitoredResourcesOptions opts) => ListMonitoredResources(opts.projectId),
(GetMonitoredResourceOptions opts) => GetMonitoredResource(opts.projectId, opts.resourceId),
(ListGroupsOptions opts) => ListGroups(opts.projectId),
errs => 1);
}
}
}