Skip to content

Commit 2ec9a04

Browse files
authored
fixit: clean up monitoring/snippets/v3/cloud-client (#10077)
1 parent 002e988 commit 2ec9a04

File tree

5 files changed

+179
-82
lines changed

5 files changed

+179
-82
lines changed

monitoring/snippets/v3/cloud-client/noxfile_config.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,18 @@
2222

2323
TEST_CONFIG_OVERRIDE = {
2424
# You can opt out from the test for specific Python versions.
25-
'ignored_versions': ['2.7'],
26-
25+
"ignored_versions": ["2.7"],
2726
# Declare optional test sessions you want to opt-in. Currently we
2827
# have the following optional test sessions:
2928
# 'cloud_run' # Test session for Cloud Run application.
30-
'opt_in_sessions': [],
31-
29+
"opt_in_sessions": [],
3230
# An envvar key for determining the project id to use. Change it
3331
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
3432
# build specific Cloud project. You can also use your own string
3533
# to use your own Cloud project.
36-
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
34+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
3735
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
38-
3936
# A dictionary you want to inject into your test. Don't put any
4037
# secrets here. These values will override predefined values.
41-
'envs': {},
38+
"envs": {},
4239
}

monitoring/snippets/v3/cloud-client/quickstart.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,23 @@
1313
# limitations under the License.
1414

1515

16-
def run_quickstart(project=""):
16+
def run_quickstart(project_id: str) -> bool:
17+
"""Writes a custom metric time series
18+
19+
Args:
20+
project_id: Google Cloud project id
21+
22+
Returns:
23+
True on success
24+
"""
1725
# [START monitoring_quickstart]
1826
from google.cloud import monitoring_v3
1927

2028
import time
2129

2230
client = monitoring_v3.MetricServiceClient()
2331
# project = 'my-project' # TODO: Update to your project ID.
24-
project_name = f"projects/{project}"
32+
project_name = f"projects/{project_id}"
2533

2634
series = monitoring_v3.TimeSeries()
2735
series.metric.type = "custom.googleapis.com/my_metric"
@@ -31,14 +39,15 @@ def run_quickstart(project=""):
3139
series.resource.labels["zone"] = "us-central1-f"
3240
now = time.time()
3341
seconds = int(now)
34-
nanos = int((now - seconds) * 10 ** 9)
42+
nanos = int((now - seconds) * 10**9)
3543
interval = monitoring_v3.TimeInterval(
3644
{"end_time": {"seconds": seconds, "nanos": nanos}}
3745
)
3846
point = monitoring_v3.Point({"interval": interval, "value": {"double_value": 3.14}})
3947
series.points = [point]
4048
client.create_time_series(request={"name": project_name, "time_series": [series]})
4149
print("Successfully wrote time series.")
50+
return True
4251
# [END monitoring_quickstart]
4352

4453

monitoring/snippets/v3/cloud-client/quickstart_test.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,9 @@
2222
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
2323

2424

25-
def test_quickstart(capsys):
25+
def test_quickstart(capsys) -> None:
2626
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
2727
def eventually_consistent_test():
28-
quickstart.run_quickstart(PROJECT)
29-
out, _ = capsys.readouterr()
30-
assert "wrote" in out
28+
assert quickstart.run_quickstart(PROJECT)
3129

3230
eventually_consistent_test()

monitoring/snippets/v3/cloud-client/snippets.py

Lines changed: 128 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,23 @@
1818
import time
1919
import uuid
2020

21+
from google.api import metric_pb2 # type: ignore
22+
from google.api import monitored_resource_pb2 # type: ignore
23+
from google.cloud.monitoring_v3.services.metric_service import pagers
24+
25+
2126
PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
2227

2328

24-
def create_metric_descriptor(project_id):
29+
def create_metric_descriptor(project_id: str) -> metric_pb2.MetricDescriptor:
30+
"""Creates a new metric description
31+
32+
Args:
33+
project_id: Google Cloud project id
34+
35+
Returns:
36+
A new instance of metric description.
37+
"""
2538
# [START monitoring_create_metric]
2639
from google.api import label_pb2 as ga_label
2740
from google.api import metric_pb2 as ga_metric
@@ -46,9 +59,15 @@ def create_metric_descriptor(project_id):
4659
)
4760
print("Created {}.".format(descriptor.name))
4861
# [END monitoring_create_metric]
62+
return descriptor
63+
4964

65+
def delete_metric_descriptor(descriptor_name: str) -> None:
66+
"""Deletes metric description
5067
51-
def delete_metric_descriptor(descriptor_name):
68+
Args:
69+
descriptor_name: Fully qualified descriptor name
70+
"""
5271
# [START monitoring_delete_metric]
5372
from google.cloud import monitoring_v3
5473

@@ -58,7 +77,12 @@ def delete_metric_descriptor(descriptor_name):
5877
# [END monitoring_delete_metric]
5978

6079

61-
def write_time_series(project_id):
80+
def write_time_series(project_id: str) -> None:
81+
"""Writes a custom metric time series
82+
83+
Args:
84+
project_id: Google Cloud project id
85+
"""
6286
# [START monitoring_write_timeseries]
6387
from google.cloud import monitoring_v3
6488

@@ -69,11 +93,11 @@ def write_time_series(project_id):
6993
series.metric.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
7094
series.resource.type = "gce_instance"
7195
series.resource.labels["instance_id"] = "1234567890123456789"
72-
series.resource.labels["zone"] = "us-central1-f"
96+
series.resource.labels["zone"] = "us-central1-c"
7397
series.metric.labels["TestLabel"] = "My Label Data"
7498
now = time.time()
7599
seconds = int(now)
76-
nanos = int((now - seconds) * 10 ** 9)
100+
nanos = int((now - seconds) * 10**9)
77101
interval = monitoring_v3.TimeInterval(
78102
{"end_time": {"seconds": seconds, "nanos": nanos}}
79103
)
@@ -83,7 +107,16 @@ def write_time_series(project_id):
83107
# [END monitoring_write_timeseries]
84108

85109

86-
def list_time_series(project_id):
110+
def list_time_series(project_id: str) -> pagers.ListTimeSeriesPager:
111+
"""Prints CPU utilization metric collected during last 20 minutes
112+
113+
Args:
114+
project_id: Google Cloud project id
115+
116+
Returns:
117+
Collection of time series.
118+
Iterating over this object will yield results and resolve additional pages automatically.
119+
"""
87120
# [START monitoring_read_timeseries_simple]
88121
from google.cloud import monitoring_v3
89122

@@ -92,7 +125,7 @@ def list_time_series(project_id):
92125

93126
now = time.time()
94127
seconds = int(now)
95-
nanos = int((now - seconds) * 10 ** 9)
128+
nanos = int((now - seconds) * 10**9)
96129
interval = monitoring_v3.TimeInterval(
97130
{
98131
"end_time": {"seconds": seconds, "nanos": nanos},
@@ -111,17 +144,27 @@ def list_time_series(project_id):
111144
for result in results:
112145
print(result)
113146
# [END monitoring_read_timeseries_simple]
147+
return results
148+
114149

150+
def list_time_series_header(project_id: str) -> pagers.ListTimeSeriesPager:
151+
"""Prints CPU utilization metric's headers collected during last 20 minutes
115152
116-
def list_time_series_header(project_id):
153+
Args:
154+
project_id: Google Cloud project id
155+
156+
Returns:
157+
Collection of time series.
158+
Iterating over this object will yield results and resolve additional pages automatically.
159+
"""
117160
# [START monitoring_read_timeseries_fields]
118161
from google.cloud import monitoring_v3
119162

120163
client = monitoring_v3.MetricServiceClient()
121164
project_name = f"projects/{project_id}"
122165
now = time.time()
123166
seconds = int(now)
124-
nanos = int((now - seconds) * 10 ** 9)
167+
nanos = int((now - seconds) * 10**9)
125168
interval = monitoring_v3.TimeInterval(
126169
{
127170
"end_time": {"seconds": seconds, "nanos": nanos},
@@ -139,9 +182,19 @@ def list_time_series_header(project_id):
139182
for result in results:
140183
print(result)
141184
# [END monitoring_read_timeseries_fields]
185+
return results
186+
187+
188+
def list_time_series_aggregate(project_id: str) -> pagers.ListTimeSeriesPager:
189+
"""Prints aggregated CPU utilization metric for last hour
142190
191+
Args:
192+
project_id: Google Cloud project id
143193
144-
def list_time_series_aggregate(project_id):
194+
Returns:
195+
Collection of time series.
196+
Iterating over this object will yield results and resolve additional pages automatically.
197+
"""
145198
# [START monitoring_read_timeseries_align]
146199
from google.cloud import monitoring_v3
147200

@@ -150,7 +203,7 @@ def list_time_series_aggregate(project_id):
150203

151204
now = time.time()
152205
seconds = int(now)
153-
nanos = int((now - seconds) * 10 ** 9)
206+
nanos = int((now - seconds) * 10**9)
154207
interval = monitoring_v3.TimeInterval(
155208
{
156209
"end_time": {"seconds": seconds, "nanos": nanos},
@@ -176,9 +229,19 @@ def list_time_series_aggregate(project_id):
176229
for result in results:
177230
print(result)
178231
# [END monitoring_read_timeseries_align]
232+
return results
179233

180234

181-
def list_time_series_reduce(project_id):
235+
def list_time_series_reduce(project_id: str) -> pagers.ListTimeSeriesPager:
236+
"""Prints CPU utilization for last hour using reducer
237+
238+
Args:
239+
project_id: Google Cloud project id
240+
241+
Returns:
242+
Collection of time series.
243+
Iterating over this object will yield results and resolve additional pages automatically.
244+
"""
182245
# [START monitoring_read_timeseries_reduce]
183246
from google.cloud import monitoring_v3
184247

@@ -187,7 +250,7 @@ def list_time_series_reduce(project_id):
187250

188251
now = time.time()
189252
seconds = int(now)
190-
nanos = int((now - seconds) * 10 ** 9)
253+
nanos = int((now - seconds) * 10**9)
191254
interval = monitoring_v3.TimeInterval(
192255
{
193256
"end_time": {"seconds": seconds, "nanos": nanos},
@@ -215,20 +278,43 @@ def list_time_series_reduce(project_id):
215278
for result in results:
216279
print(result)
217280
# [END monitoring_read_timeseries_reduce]
281+
return results
282+
218283

284+
def list_metric_descriptors(project_id: str) -> pagers.ListMetricDescriptorsPager:
285+
"""Gets a list of metric descriptions
219286
220-
def list_metric_descriptors(project_id):
287+
Args:
288+
project_id: Google Cloud project id
289+
290+
Returns:
291+
Collection of metric descriptors in the project.
292+
Iterating over this object will yield results and resolve additional pages automatically.
293+
"""
221294
# [START monitoring_list_descriptors]
222295
from google.cloud import monitoring_v3
223296

224297
client = monitoring_v3.MetricServiceClient()
225298
project_name = f"projects/{project_id}"
226-
for descriptor in client.list_metric_descriptors(name=project_name):
299+
descriptors = client.list_metric_descriptors(name=project_name)
300+
for descriptor in descriptors:
227301
print(descriptor.type)
228302
# [END monitoring_list_descriptors]
303+
return descriptors
304+
305+
306+
def list_monitored_resources(
307+
project_id: str,
308+
) -> pagers.ListMonitoredResourceDescriptorsPager:
309+
"""Gets a list of monitored resource descriptors
229310
311+
Args:
312+
project_id: Google Cloud project id
230313
231-
def list_monitored_resources(project_id):
314+
Returns:
315+
Collection of monitored resource descriptors.
316+
Iterating over this object will yield results and resolve additional pages automatically.
317+
"""
232318
# [START monitoring_list_resources]
233319
from google.cloud import monitoring_v3
234320

@@ -238,28 +324,51 @@ def list_monitored_resources(project_id):
238324
for descriptor in resource_descriptors:
239325
print(descriptor.type)
240326
# [END monitoring_list_resources]
327+
return resource_descriptors
241328

242329

243-
def get_monitored_resource_descriptor(project_id, resource_type_name):
330+
def get_monitored_resource_descriptor(
331+
project_id: str, resource_type_name: str
332+
) -> monitored_resource_pb2.MonitoredResourceDescriptor:
333+
"""Prints monitored resource description by type
334+
335+
Args:
336+
project_id: Google Cloud project id
337+
resource_type_name: a monitored resource type
338+
339+
Returns:
340+
An object that describes the monitored resource
341+
"""
244342
# [START monitoring_get_resource]
245343
from google.cloud import monitoring_v3
246344

247345
client = monitoring_v3.MetricServiceClient()
248346
resource_path = (
249347
f"projects/{project_id}/monitoredResourceDescriptors/{resource_type_name}"
250348
)
251-
pprint.pprint(client.get_monitored_resource_descriptor(name=resource_path))
349+
descriptor = client.get_monitored_resource_descriptor(name=resource_path)
350+
pprint.pprint(descriptor)
252351
# [END monitoring_get_resource]
352+
return descriptor
353+
354+
355+
def get_metric_descriptor(metric_name: str) -> metric_pb2.MetricDescriptor:
356+
"""Gets metric descriptor by type
253357
358+
Args:
359+
metric_name: fully qualified descriptor name
254360
255-
def get_metric_descriptor(metric_name):
361+
Returns:
362+
An object that describes the monitored metric
363+
"""
256364
# [START monitoring_get_descriptor]
257365
from google.cloud import monitoring_v3
258366

259367
client = monitoring_v3.MetricServiceClient()
260368
descriptor = client.get_metric_descriptor(name=metric_name)
261369
pprint.pprint(descriptor)
262370
# [END monitoring_get_descriptor]
371+
return descriptor
263372

264373

265374
if __name__ == "__main__":

0 commit comments

Comments
 (0)