From 0967b8c11b021f1d3bdc692829cfd2eb95136bd1 Mon Sep 17 00:00:00 2001 From: Jerjou Cheng Date: Mon, 13 Jul 2015 11:30:29 -0700 Subject: [PATCH] Move monitoring sample in, modified for ADC. --- bigquery/samples/utils.py | 4 +- monitoring/__init__.py | 0 monitoring/samples/__init__.py | 0 monitoring/samples/auth.py | 93 +++++++++++++++++++++++++++ monitoring/samples/tests/__init__.py | 0 monitoring/samples/tests/test_auth.py | 40 ++++++++++++ tests/__init__.py | 16 +++++ 7 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 monitoring/__init__.py create mode 100644 monitoring/samples/__init__.py create mode 100644 monitoring/samples/auth.py create mode 100644 monitoring/samples/tests/__init__.py create mode 100644 monitoring/samples/tests/test_auth.py diff --git a/bigquery/samples/utils.py b/bigquery/samples/utils.py index 0b375cefc034..53d26d0c6471 100644 --- a/bigquery/samples/utils.py +++ b/bigquery/samples/utils.py @@ -29,7 +29,7 @@ def get_service(): # [START poll_job] -def poll_job(service, projectId, jobId, interval=5, num_retries=5): +def poll_job(service, projectId, jobId, interval=5.0, num_retries=5): """checks the status of a job every *interval* seconds""" import time @@ -40,7 +40,7 @@ def poll_job(service, projectId, jobId, interval=5, num_retries=5): while not job_resource['status']['state'] == 'DONE': print('Job is {}, waiting {} seconds...' .format(job_resource['status']['state'], interval)) - time.sleep(interval) + time.sleep(float(interval)) job_resource = job_get.execute(num_retries=num_retries) return job_resource diff --git a/monitoring/__init__.py b/monitoring/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/monitoring/samples/__init__.py b/monitoring/samples/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/monitoring/samples/auth.py b/monitoring/samples/auth.py new file mode 100644 index 000000000000..7e4aa6201f64 --- /dev/null +++ b/monitoring/samples/auth.py @@ -0,0 +1,93 @@ +# Copyright 2015 Google Inc. All rights reserved. +# +# 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. + +"""Sample command-line program for retrieving Google Cloud Monitoring API data. + +Simple command-line program to demonstrate connecting to the Google Cloud +Monitoring API to retrieve API data, using application default credentials to +authenticate. + +This sample obtains authentication information from its environment via +application default credentials [1]. + +If you're not running the sample on Google App Engine or Compute Engine (where +the environment comes pre-authenticated as a service account), you'll have to +initialize your environment with credentials the sample can use. + +One way to do this is through the cloud console's credentials page [2]. Create +a new client ID of type 'Service account', and download its JSON key. This will +be the account the sample authenticates as. + +Once you've downloaded the service account's JSON key, you provide it to the +sample by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to +point to the key file: + +$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/json-key.json + +[1] https://developers.google.com/identity/protocols/application-default-credentials +[2] https://console.developers.google.com/project/_/apiui/credential +""" # NOQA + +# [START all] +import json +import sys + +from googleapiclient.discovery import build + +from oauth2client.client import GoogleCredentials + + +METRIC = 'compute.googleapis.com/instance/disk/read_ops_count' +YOUNGEST = '2015-01-01T00:00:00Z' + + +def ListTimeseries(project_name, service): + """Query the Timeseries.list API method. + + Args: + project_name: the name of the project you'd like to monitor. + service: the CloudMonitoring service object. + """ + + timeseries = service.timeseries() + + print 'Timeseries.list raw response:' + try: + response = timeseries.list( + project=project_name, metric=METRIC, youngest=YOUNGEST).execute() + + print json.dumps(response, + sort_keys=True, + indent=4, + separators=(',', ': ')) + except: + print 'Error:' + for error in sys.exc_info(): + print error + + +def main(project_name): + # Create and return the CloudMonitoring service object. + service = build('cloudmonitoring', 'v2beta2', + credentials=GoogleCredentials.get_application_default()) + + ListTimeseries(project_name, service) + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print "Usage: %s " % sys.argv[0] + sys.exit(1) + main(sys.argv[1]) +# [END all] diff --git a/monitoring/samples/tests/__init__.py b/monitoring/samples/tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/monitoring/samples/tests/test_auth.py b/monitoring/samples/tests/test_auth.py new file mode 100644 index 000000000000..2bc7d3b2eee5 --- /dev/null +++ b/monitoring/samples/tests/test_auth.py @@ -0,0 +1,40 @@ +# Copyright 2015, 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. + +import os +import re +import unittest + +from monitoring.samples import auth + +import tests + + +class TestTimeseriesList(tests.CloudBaseTest): + + @classmethod + def setUpClass(cls): + cls.test_project_id = os.environ.get(tests.PROJECT_ID_ENV) + + def test_main(self): + with tests.capture_stdout() as stdout: + auth.main(self.test_project_id) + output = stdout.getvalue().strip() + self.assertRegexpMatches( + output, re.compile(r'Timeseries.list raw response:\s*' + r'{\s*"kind": "[^"]+",' + r'\s*"oldest": *"[0-9]+', re.S)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/__init__.py b/tests/__init__.py index b706ae802f62..5351a4ab962d 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -16,8 +16,11 @@ """ import __builtin__ +import contextlib import json import os +import StringIO +import sys import unittest from google.appengine.datastore import datastore_stub_util @@ -101,3 +104,16 @@ def setUp(self): def tearDown(self): self.testbed.deactivate() + + +@contextlib.contextmanager +def capture_stdout(): + """Capture stdout.""" + fake_stdout = StringIO.StringIO() + old_stdout = sys.stdout + + try: + sys.stdout = fake_stdout + yield fake_stdout + finally: + sys.stdout = old_stdout