diff --git a/monitoring/api/v2/README.rst b/monitoring/api/v2/README.rst deleted file mode 100644 index ffb937e31084..000000000000 --- a/monitoring/api/v2/README.rst +++ /dev/null @@ -1,167 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Stackdriver Monitoring Python Samples -=============================================================================== - -This directory contains samples for Stackdriver Monitoring. `Stackdriver Monitoring `_ collects metrics, events, and metadata from Google Cloud Platform, Amazon Web Services (AWS), hosted uptime probes, application instrumentation, and a variety of common application components including Cassandra, Nginx, Apache Web Server, Elasticsearch and many others. Stackdriver ingests that data and generates insights via dashboards, charts, and alerts. - - - - -.. _Stackdriver Monitoring: https://cloud.google.com/monitoring/docs - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Authenticating & basic operations -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - - -To run this sample: - -.. code-block:: bash - - $ python auth.py - - usage: auth.py [-h] project_id - - Sample command-line program for retrieving Stackdriver Monitoring API data. - - Prerequisites: To run locally, download a Service Account JSON file from - your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - - This sample is used on this page: - - https://cloud.google.com/monitoring/api/authentication - - For more information, see the README.md under /monitoring. - - positional arguments: - project_id Your Google Cloud project ID. - - optional arguments: - -h, --help show this help message and exit - - -Labeled custom metrics -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - - -To run this sample: - -.. code-block:: bash - - $ python labeled_custom_metric.py - - usage: labeled_custom_metric.py [-h] --project_id PROJECT_ID --color COLOR - --size SIZE --count COUNT - - Creates, writes, and reads a labeled custom metric. - - This is an example of how to use the Stackdriver Monitoring API to create, - write, and read a labeled custom metric. - The metric has two labels: color and size, and the data points represent - the number of shirts of the given color and size in inventory. - - Prerequisites: To run locally, download a Service Account JSON file from - your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - - From App Engine or a GCE instance with the correct scope, the Service - Account step is not required. - - Typical usage: Run the following shell commands on the instance: - python labeled_custom_metric.py --project_id / - --color yellow --size large --count 10 - - optional arguments: - -h, --help show this help message and exit - --project_id PROJECT_ID - Project ID you want to access. - --color COLOR - --size SIZE - --count COUNT - - -Lightweight custom metrics -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - - -To run this sample: - -.. code-block:: bash - - $ python labeled_custom_metric.py - - usage: labeled_custom_metric.py [-h] --project_id PROJECT_ID --color COLOR - --size SIZE --count COUNT - - Creates, writes, and reads a labeled custom metric. - - This is an example of how to use the Stackdriver Monitoring API to create, - write, and read a labeled custom metric. - The metric has two labels: color and size, and the data points represent - the number of shirts of the given color and size in inventory. - - Prerequisites: To run locally, download a Service Account JSON file from - your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - - From App Engine or a GCE instance with the correct scope, the Service - Account step is not required. - - Typical usage: Run the following shell commands on the instance: - python labeled_custom_metric.py --project_id / - --color yellow --size large --count 10 - - optional arguments: - -h, --help show this help message and exit - --project_id PROJECT_ID - Project ID you want to access. - --color COLOR - --size SIZE - --count COUNT - - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/monitoring/api/v2/README.rst.in b/monitoring/api/v2/README.rst.in deleted file mode 100644 index 42c44b5798ae..000000000000 --- a/monitoring/api/v2/README.rst.in +++ /dev/null @@ -1,28 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Stackdriver Monitoring - short_name: Stackdriver Monitoring - url: https://cloud.google.com/monitoring/docs - description: > - `Stackdriver Monitoring `_ collects metrics, events, and metadata from - Google Cloud Platform, Amazon Web Services (AWS), hosted uptime probes, - application instrumentation, and a variety of common application components - including Cassandra, Nginx, Apache Web Server, Elasticsearch and many - others. Stackdriver ingests that data and generates insights via - dashboards, charts, and alerts. - -setup: -- auth -- install_deps - -samples: -- name: Authenticating & basic operations - file: auth.py - show_help: true -- name: Labeled custom metrics - file: labeled_custom_metric.py - show_help: true -- name: Lightweight custom metrics - file: labeled_custom_metric.py - show_help: true diff --git a/monitoring/api/v2/auth.py b/monitoring/api/v2/auth.py deleted file mode 100644 index 273307d7b179..000000000000 --- a/monitoring/api/v2/auth.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env pyhton - -# 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 Stackdriver Monitoring API data. - -Prerequisites: To run locally, download a Service Account JSON file from -your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - - -This sample is used on this page: - - https://cloud.google.com/monitoring/api/authentication - -For more information, see the README.md under /monitoring. -""" - -# [START all] -import argparse -import json - -import googleapiclient.discovery - -METRIC = 'compute.googleapis.com/instance/disk/read_ops_count' -YOUNGEST = '2015-01-01T00:00:00Z' - - -def list_timeseries(project_name): - """Query the Timeseries.list API method. - - Args: - monitoring: the CloudMonitoring service object. - project_name: the name of the project you'd like to monitor. - """ - monitoring = googleapiclient.discovery.build('cloudmonitoring', 'v2beta2') - - timeseries = monitoring.timeseries() - - response = timeseries.list( - project=project_name, metric=METRIC, youngest=YOUNGEST).execute() - - print('Timeseries.list raw response:') - print(json.dumps( - response, - sort_keys=True, - indent=2, - separators=(',', ': '))) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('project_id', help='Your Google Cloud project ID.') - - args = parser.parse_args() - - list_timeseries(args.project_id) -# [END all] diff --git a/monitoring/api/v2/auth_test.py b/monitoring/api/v2/auth_test.py deleted file mode 100644 index 6349b7c07fcf..000000000000 --- a/monitoring/api/v2/auth_test.py +++ /dev/null @@ -1,31 +0,0 @@ -# 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 auth - -PROJECT = os.environ['GCLOUD_PROJECT'] - - -def test_main(capsys): - auth.list_timeseries(PROJECT) - output, _ = capsys.readouterr() - - assert re.search( - re.compile( - r'Timeseries.list raw response:\s*' - r'{\s*"kind": "[^"]+",' - r'\s*"oldest": *"[0-9]+', re.S), - output) diff --git a/monitoring/api/v2/labeled_custom_metric.py b/monitoring/api/v2/labeled_custom_metric.py deleted file mode 100644 index 563b2e877dea..000000000000 --- a/monitoring/api/v2/labeled_custom_metric.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python - -# 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. - - -"""Creates, writes, and reads a labeled custom metric. - -This is an example of how to use the Stackdriver Monitoring API to create, -write, and read a labeled custom metric. -The metric has two labels: color and size, and the data points represent -the number of shirts of the given color and size in inventory. - -Prerequisites: To run locally, download a Service Account JSON file from -your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - -From App Engine or a GCE instance with the correct scope, the Service -Account step is not required. - -Typical usage: Run the following shell commands on the instance: - python labeled_custom_metric.py --project_id / - --color yellow --size large --count 10 -""" - -import argparse -import datetime -import time - -import googleapiclient.discovery - -CUSTOM_METRIC_DOMAIN = "custom.cloudmonitoring.googleapis.com" -CUSTOM_METRIC_NAME = "{}/shirt_inventory".format(CUSTOM_METRIC_DOMAIN) - - -def format_rfc3339(datetime_instance=None): - """Formats a datetime per RFC 3339. - :param datetime_instance: Datetime instance to format, defaults to utcnow - """ - return datetime_instance.isoformat("T") + "Z" - - -def get_now_rfc3339(): - return format_rfc3339(datetime.datetime.utcnow()) - - -def create_custom_metric(client, project_id): - """Create metric descriptor for the custom metric and send it to the - API.""" - # You need to execute this operation only once. The operation is - # idempotent, so, for simplicity, this sample code calls it each time - - # Create a label descriptor for each of the metric labels. The - # "description" field should be more meaningful for your metrics. - label_descriptors = [] - for label in ["color", "size", ]: - label_descriptors.append({"key": "/{}".format(label), - "description": "The {}.".format(label)}) - - # Create the metric descriptor for the custom metric. - metric_descriptor = { - "name": CUSTOM_METRIC_NAME, - "project": project_id, - "typeDescriptor": { - "metricType": "gauge", - "valueType": "int64", - }, - "labels": label_descriptors, - "description": "The size of my shirt inventory.", - } - # Submit the custom metric creation request. - try: - request = client.metricDescriptors().create( - project=project_id, body=metric_descriptor) - request.execute() # ignore the response - except Exception as e: - print("Failed to create custom metric: exception={})".format(e)) - raise - - -def write_custom_metric(client, project_id, now_rfc3339, color, size, count): - """Write a data point to a single time series of the custom metric.""" - # Identify the particular time series to which to write the data by - # specifying the metric and values for each label. - timeseries_descriptor = { - "project": project_id, - "metric": CUSTOM_METRIC_NAME, - "labels": { - "{}/color".format(CUSTOM_METRIC_DOMAIN): color, - "{}/size".format(CUSTOM_METRIC_DOMAIN): size, - } - } - - # Specify a new data point for the time series. - timeseries_data = { - "timeseriesDesc": timeseries_descriptor, - "point": { - "start": now_rfc3339, - "end": now_rfc3339, - "int64Value": count, - } - } - - # Submit the write request. - request = client.timeseries().write( - project=project_id, body={"timeseries": [timeseries_data, ]}) - try: - request.execute() # ignore the response - except Exception as e: - print("Failed to write data to custom metric: exception={}".format(e)) - raise - - -def read_custom_metric(client, project_id, now_rfc3339, color, size): - """Read all the timeseries data points for a given set of label values.""" - # To identify a time series, specify values for in label as a list. - labels = ["{}/color=={}".format(CUSTOM_METRIC_DOMAIN, color), - "{}/size=={}".format(CUSTOM_METRIC_DOMAIN, size), ] - - # Submit the read request. - request = client.timeseries().list( - project=project_id, - metric=CUSTOM_METRIC_NAME, - youngest=now_rfc3339, - labels=labels) - - # When a custom metric is created, it may take a few seconds - # to propagate throughout the system. Retry a few times. - start = time.time() - while True: - try: - response = request.execute() - for point in response["timeseries"][0]["points"]: - print("{}: {}".format(point["end"], point["int64Value"])) - break - except Exception as e: - if time.time() < start + 20: - print("Failed to read custom metric data, retrying...") - time.sleep(3) - else: - print("Failed to read custom metric data, aborting: " - "exception={}".format(e)) - raise - - -def get_client(): - """Builds an http client authenticated with the application default - credentials.""" - client = googleapiclient.discovery.build('cloudmonitoring', 'v2beta2') - return client - - -def main(project_id, color, size, count): - now_rfc3339 = get_now_rfc3339() - - client = get_client() - - print("Labels: color: {}, size: {}.".format(color, size)) - print("Creating custom metric...") - create_custom_metric(client, project_id) - time.sleep(2) - print("Writing new data to custom metric timeseries...") - write_custom_metric(client, project_id, now_rfc3339, - color, size, count) - print("Reading data from custom metric timeseries...") - read_custom_metric(client, project_id, now_rfc3339, color, size) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter, - ) - - parser.add_argument( - '--project_id', help='Project ID you want to access.', required=True) - parser.add_argument("--color", required=True) - parser.add_argument("--size", required=True) - parser.add_argument("--count", required=True) - - args = parser.parse_args() - main(args.project_id, args.color, args.size, args.count) diff --git a/monitoring/api/v2/labeled_custom_metric_test.py b/monitoring/api/v2/labeled_custom_metric_test.py deleted file mode 100644 index 1ad2009aca40..000000000000 --- a/monitoring/api/v2/labeled_custom_metric_test.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -# 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. - -import os -import re - -import labeled_custom_metric - -PROJECT = os.environ['GCLOUD_PROJECT'] - - -def test_main(capsys): - labeled_custom_metric.main(PROJECT, "yellow", "large", "10") - output, _ = capsys.readouterr() - - assert re.search( - re.compile( - r'.*Creating.*' - r'Writing.*' - r'Reading.*', flags=re.DOTALL), - output) diff --git a/monitoring/api/v2/lightweight_custom_metric.py b/monitoring/api/v2/lightweight_custom_metric.py deleted file mode 100644 index 795cfeb96442..000000000000 --- a/monitoring/api/v2/lightweight_custom_metric.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python - -# 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. - - -"""Writes and reads a lightweight custom metric. - -This is an example of how to use the Stackdriver Monitoring API to write -and read a lightweight custom metric. Lightweight custom metrics have no -labels and you do not need to create a metric descriptor for them. - -Prerequisites: To run locally, download a Service Account JSON file from -your project and point GOOGLE_APPLICATION_CREDENTIALS to the file. - -From App Engine or a GCE instance with the correct scope, the Service -Account step is not required. - -Typical usage: Run the following shell commands on the instance: - - python lightweight_custom_metric.py --project_id= -""" - -import argparse -import datetime -import os -import time - -import googleapiclient.discovery - -CUSTOM_METRIC_NAME = "custom.cloudmonitoring.googleapis.com/pid" - - -def format_rfc3339(datetime_instance=None): - """Formats a datetime per RFC 3339. - :param datetime_instance: Datetime instanec to format, defaults to utcnow - """ - return datetime_instance.isoformat("T") + "Z" - - -def get_now_rfc3339(): - return format_rfc3339(datetime.datetime.utcnow()) - - -def main(project_id): - client = googleapiclient.discovery.build('cloudmonitoring', 'v2beta2') - - # Set up the write request. - now = get_now_rfc3339() - desc = {"project": project_id, - "metric": CUSTOM_METRIC_NAME} - point = {"start": now, - "end": now, - "doubleValue": os.getpid()} - print("Writing {} at {}".format(point["doubleValue"], now)) - - # Write a new data point. - try: - write_request = client.timeseries().write( - project=project_id, - body={"timeseries": [{"timeseriesDesc": desc, "point": point}]}) - write_request.execute() # Ignore the response. - except Exception as e: - print("Failed to write custom metric data: exception={}".format(e)) - raise - - # Read all data points from the time series. - # When a custom metric is created, it may take a few seconds - # to propagate throughout the system. Retry a few times. - print("Reading data from custom metric timeseries...") - read_request = client.timeseries().list( - project=project_id, - metric=CUSTOM_METRIC_NAME, - youngest=now) - start = time.time() - while True: - try: - read_response = read_request.execute() - for point in read_response["timeseries"][0]["points"]: - print("Point: {}: {}".format( - point["end"], point["doubleValue"])) - break - except Exception as e: - if time.time() < start + 20: - print("Failed to read custom metric data, retrying...") - time.sleep(3) - else: - print("Failed to read custom metric data, aborting: " - "exception={}".format(e)) - raise - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter - ) - - parser.add_argument( - '--project_id', help='Project ID you want to access.', required=True) - - args = parser.parse_args() - main(args.project_id) diff --git a/monitoring/api/v2/lightweight_custom_metric_test.py b/monitoring/api/v2/lightweight_custom_metric_test.py deleted file mode 100644 index d95eb47d926a..000000000000 --- a/monitoring/api/v2/lightweight_custom_metric_test.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -# 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. - -import os -import re - -import lightweight_custom_metric - -PROJECT = os.environ['GCLOUD_PROJECT'] - - -def test_main(capsys): - lightweight_custom_metric.main(PROJECT) - output, _ = capsys.readouterr() - - assert re.search( - re.compile( - r'Point:\s*'), - output) diff --git a/monitoring/api/v2/requirements.txt b/monitoring/api/v2/requirements.txt deleted file mode 100644 index 558e42c22ec8..000000000000 --- a/monitoring/api/v2/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -google-api-python-client==1.6.4 -google-auth==1.2.0 -google-auth-httplib2==0.0.2