Skip to content

Commit 34e0721

Browse files
committed
Merge pull request #52 from GoogleCloudPlatform/monitoring
Move monitoring sample in, modified for ADC.
2 parents 4f41bdf + 0967b8c commit 34e0721

File tree

7 files changed

+151
-2
lines changed

7 files changed

+151
-2
lines changed

bigquery/samples/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def get_service():
2929

3030

3131
# [START poll_job]
32-
def poll_job(service, projectId, jobId, interval=5, num_retries=5):
32+
def poll_job(service, projectId, jobId, interval=5.0, num_retries=5):
3333
"""checks the status of a job every *interval* seconds"""
3434

3535
import time
@@ -40,7 +40,7 @@ def poll_job(service, projectId, jobId, interval=5, num_retries=5):
4040
while not job_resource['status']['state'] == 'DONE':
4141
print('Job is {}, waiting {} seconds...'
4242
.format(job_resource['status']['state'], interval))
43-
time.sleep(interval)
43+
time.sleep(float(interval))
4444
job_resource = job_get.execute(num_retries=num_retries)
4545

4646
return job_resource

monitoring/__init__.py

Whitespace-only changes.

monitoring/samples/__init__.py

Whitespace-only changes.

monitoring/samples/auth.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Copyright 2015 Google Inc. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Sample command-line program for retrieving Google Cloud Monitoring API data.
16+
17+
Simple command-line program to demonstrate connecting to the Google Cloud
18+
Monitoring API to retrieve API data, using application default credentials to
19+
authenticate.
20+
21+
This sample obtains authentication information from its environment via
22+
application default credentials [1].
23+
24+
If you're not running the sample on Google App Engine or Compute Engine (where
25+
the environment comes pre-authenticated as a service account), you'll have to
26+
initialize your environment with credentials the sample can use.
27+
28+
One way to do this is through the cloud console's credentials page [2]. Create
29+
a new client ID of type 'Service account', and download its JSON key. This will
30+
be the account the sample authenticates as.
31+
32+
Once you've downloaded the service account's JSON key, you provide it to the
33+
sample by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to
34+
point to the key file:
35+
36+
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/json-key.json
37+
38+
[1] https://developers.google.com/identity/protocols/application-default-credentials
39+
[2] https://console.developers.google.com/project/_/apiui/credential
40+
""" # NOQA
41+
42+
# [START all]
43+
import json
44+
import sys
45+
46+
from googleapiclient.discovery import build
47+
48+
from oauth2client.client import GoogleCredentials
49+
50+
51+
METRIC = 'compute.googleapis.com/instance/disk/read_ops_count'
52+
YOUNGEST = '2015-01-01T00:00:00Z'
53+
54+
55+
def ListTimeseries(project_name, service):
56+
"""Query the Timeseries.list API method.
57+
58+
Args:
59+
project_name: the name of the project you'd like to monitor.
60+
service: the CloudMonitoring service object.
61+
"""
62+
63+
timeseries = service.timeseries()
64+
65+
print 'Timeseries.list raw response:'
66+
try:
67+
response = timeseries.list(
68+
project=project_name, metric=METRIC, youngest=YOUNGEST).execute()
69+
70+
print json.dumps(response,
71+
sort_keys=True,
72+
indent=4,
73+
separators=(',', ': '))
74+
except:
75+
print 'Error:'
76+
for error in sys.exc_info():
77+
print error
78+
79+
80+
def main(project_name):
81+
# Create and return the CloudMonitoring service object.
82+
service = build('cloudmonitoring', 'v2beta2',
83+
credentials=GoogleCredentials.get_application_default())
84+
85+
ListTimeseries(project_name, service)
86+
87+
88+
if __name__ == '__main__':
89+
if len(sys.argv) != 2:
90+
print "Usage: %s <project-name>" % sys.argv[0]
91+
sys.exit(1)
92+
main(sys.argv[1])
93+
# [END all]

monitoring/samples/tests/__init__.py

Whitespace-only changes.

monitoring/samples/tests/test_auth.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Copyright 2015, Google, Inc.
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
import os
15+
import re
16+
import unittest
17+
18+
from monitoring.samples import auth
19+
20+
import tests
21+
22+
23+
class TestTimeseriesList(tests.CloudBaseTest):
24+
25+
@classmethod
26+
def setUpClass(cls):
27+
cls.test_project_id = os.environ.get(tests.PROJECT_ID_ENV)
28+
29+
def test_main(self):
30+
with tests.capture_stdout() as stdout:
31+
auth.main(self.test_project_id)
32+
output = stdout.getvalue().strip()
33+
self.assertRegexpMatches(
34+
output, re.compile(r'Timeseries.list raw response:\s*'
35+
r'{\s*"kind": "[^"]+",'
36+
r'\s*"oldest": *"[0-9]+', re.S))
37+
38+
39+
if __name__ == '__main__':
40+
unittest.main()

tests/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
1616
"""
1717

1818
import __builtin__
19+
import contextlib
1920
import json
2021
import os
22+
import StringIO
23+
import sys
2124
import unittest
2225

2326
from google.appengine.datastore import datastore_stub_util
@@ -101,3 +104,16 @@ def setUp(self):
101104

102105
def tearDown(self):
103106
self.testbed.deactivate()
107+
108+
109+
@contextlib.contextmanager
110+
def capture_stdout():
111+
"""Capture stdout."""
112+
fake_stdout = StringIO.StringIO()
113+
old_stdout = sys.stdout
114+
115+
try:
116+
sys.stdout = fake_stdout
117+
yield fake_stdout
118+
finally:
119+
sys.stdout = old_stdout

0 commit comments

Comments
 (0)