Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample's for stackdriver's uptime check api. #1478

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions monitoring/api/v3/uptime-check-client/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
.. This file is automatically generated. Do not edit this file directly.

Google Stackdriver Uptime Checks API Python Samples
===============================================================================

.. image:: https://gstatic.com/cloudssh/images/open-btn.png
:target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=monitoring/api/v3/uptime-check-client/README.rst


This directory contains samples for Google Stackdriver Uptime Checks API. 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's Uptime Checks API allows you to create, delete, and list your project's Uptime Checks.




.. _Google Stackdriver Uptime Checks API: https://cloud.google.com/monitoring/uptime-checks/management

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
++++++++++++++++++++

#. Clone python-docs-samples and change directory to the sample directory you want to use.

.. code-block:: bash

$ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

#. 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
-------------------------------------------------------------------------------

Snippets
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

.. image:: https://gstatic.com/cloudssh/images/open-btn.png
:target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=monitoring/api/v3/uptime-check-client/snippets.py,monitoring/api/v3/uptime-check-client/README.rst




To run this sample:

.. code-block:: bash

$ python snippets.py

usage: snippets.py [-h]
{list-uptime-check-configs,list-uptime-check-ips,create-uptime-check,get-uptime-check-config,delete-uptime-check-config}
...

Demonstrates Uptime Check API operations.

positional arguments:
{list-uptime-check-configs,list-uptime-check-ips,create-uptime-check,get-uptime-check-config,delete-uptime-check-config}
list-uptime-check-configs
list-uptime-check-ips
create-uptime-check
get-uptime-check-config
delete-uptime-check-config

optional arguments:
-h, --help show this help message and exit





The client library
-------------------------------------------------------------------------------

This sample uses the `Google Cloud Client Library for Python`_.
You can read the documentation for more details on API usage and use GitHub
to `browse the source`_ and `report issues`_.

.. _Google Cloud Client Library for Python:
https://googlecloudplatform.github.io/google-cloud-python/
.. _browse the source:
https://github.com/GoogleCloudPlatform/google-cloud-python
.. _report issues:
https://github.com/GoogleCloudPlatform/google-cloud-python/issues


.. _Google Cloud SDK: https://cloud.google.com/sdk/
26 changes: 26 additions & 0 deletions monitoring/api/v3/uptime-check-client/README.rst.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# This file is used to generate README.rst

product:
name: Google Stackdriver Uptime Checks API
short_name: Stackdriver Uptime Checks API
url: https://cloud.google.com/monitoring/uptime-checks/management
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's Uptime Checks API allows you to create,
delete, and list your project's Uptime Checks.

setup:
- auth
- install_deps

samples:
- name: Snippets
file: snippets.py
show_help: true

cloud_client_library: true

folder: monitoring/api/v3/uptime-check-client
2 changes: 2 additions & 0 deletions monitoring/api/v3/uptime-check-client/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
google-cloud-monitoring==0.29.0
tabulate==0.8.2
172 changes: 172 additions & 0 deletions monitoring/api/v3/uptime-check-client/snippets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Copyright 2018 Google LLC
#
# 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.

from __future__ import print_function

import argparse
import os
import pprint

from google.cloud import monitoring_v3
import tabulate


# [START monitoring_uptime_check_create]
def create_uptime_check_config(project_name, host_name=None,
display_name=None):
config = monitoring_v3.types.uptime_pb2.UptimeCheckConfig()
config.display_name = display_name or 'New uptime check'
config.monitored_resource.type = 'uptime_url'
config.monitored_resource.labels.update(
{'host': host_name or 'example.com'})
config.http_check.path = '/'
config.http_check.port = 80
config.timeout.seconds = 10
config.period.seconds = 300

client = monitoring_v3.UptimeCheckServiceClient()
new_config = client.create_uptime_check_config(project_name, config)
pprint.pprint(new_config)
return new_config
# [END monitoring_uptime_check_create]


# [START monitoring_uptime_check_list_configs]
def list_uptime_check_configs(project_name):
client = monitoring_v3.UptimeCheckServiceClient()
configs = client.list_uptime_check_configs(project_name)

for config in configs:
pprint.pprint(config)
# [END monitoring_uptime_check_list_configs]


# [START monitoring_uptime_check_list_ips]
def list_uptime_check_ips():
client = monitoring_v3.UptimeCheckServiceClient()
ips = client.list_uptime_check_ips()
print(tabulate.tabulate(
[(ip.region, ip.location, ip.ip_address) for ip in ips],
('region', 'location', 'ip_address')
))
# [END monitoring_uptime_check_list_ips]


# [START monitoring_uptime_check_get]
def get_uptime_check_config(config_name):
client = monitoring_v3.UptimeCheckServiceClient()
config = client.get_uptime_check_config(config_name)
pprint.pprint(config)
# [END monitoring_uptime_check_get]


# [START monitoring_uptime_check_delete]
def delete_uptime_check_config(config_name):
client = monitoring_v3.UptimeCheckServiceClient()
client.delete_uptime_check_config(config_name)
print('Deleted ', config_name)
# [END monitoring_uptime_check_delete]


class MissingProjectIdError(Exception):
pass


def project_id():
"""Retreieves the project id from the environment variable.

Raises:
MissingProjectIdError -- When not set.

Returns:
str -- the project name
"""
project_id = os.environ['GCLOUD_PROJECT']

if not project_id:
raise MissingProjectIdError(
'Set the environment variable ' +
'GCLOUD_PROJECT to your Google Cloud Project Id.')
return project_id


def project_name():
return 'projects/' + project_id()


if __name__ == '__main__':

parser = argparse.ArgumentParser(
description='Demonstrates Uptime Check API operations.')

subparsers = parser.add_subparsers(dest='command')

list_uptime_check_configs_parser = subparsers.add_parser(
'list-uptime-check-configs',
help=list_uptime_check_configs.__doc__
)

list_uptime_check_ips_parser = subparsers.add_parser(
'list-uptime-check-ips',
help=list_uptime_check_ips.__doc__
)

create_uptime_check_config_parser = subparsers.add_parser(
'create-uptime-check',
help=create_uptime_check_config.__doc__
)
create_uptime_check_config_parser.add_argument(
'-d', '--display_name',
required=False,
)
create_uptime_check_config_parser.add_argument(
'-o', '--host_name',
required=False,
)

get_uptime_check_config_parser = subparsers.add_parser(
'get-uptime-check-config',
help=get_uptime_check_config.__doc__
)
get_uptime_check_config_parser.add_argument(
'-m', '--name',
required=True,
)

delete_uptime_check_config_parser = subparsers.add_parser(
'delete-uptime-check-config',
help=delete_uptime_check_config.__doc__
)
delete_uptime_check_config_parser.add_argument(
'-m', '--name',
required=True,
)

args = parser.parse_args()

if args.command == 'list-uptime-check-configs':
list_uptime_check_configs(project_name())

elif args.command == 'list-uptime-check-ips':
list_uptime_check_ips()

elif args.command == 'create-uptime-check':
create_uptime_check_config(project_name(), args.host_name,
args.display_name)

elif args.command == 'get-uptime-check-config':
get_uptime_check_config(args.name)

elif args.command == 'delete-uptime-check-config':
delete_uptime_check_config(args.name)
76 changes: 76 additions & 0 deletions monitoring/api/v3/uptime-check-client/snippets_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Copyright 2018 Google LLC
#
# 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.

from __future__ import print_function

import random
import string

import pytest

import snippets


def random_name(length):
return ''.join(
[random.choice(string.ascii_lowercase) for i in range(length)])


class UptimeFixture:
"""A test fixture that creates uptime check config.
"""

def __init__(self):
self.project_id = snippets.project_id()
self.project_name = snippets.project_name()

def __enter__(self):
# Create an uptime check config.
self.config = snippets.create_uptime_check_config(
self.project_name, display_name=random_name(10))
return self

def __exit__(self, type, value, traceback):
# Delete the config.
snippets.delete_uptime_check_config(self.config.name)


@pytest.fixture(scope='session')
def uptime():
with UptimeFixture() as uptime:
yield uptime


def test_create_and_delete(capsys):
# create and delete happen in uptime fixture.
with UptimeFixture():
pass


def test_get_uptime_check_config(capsys, uptime):
snippets.get_uptime_check_config(uptime.config.name)
out, _ = capsys.readouterr()
assert uptime.config.display_name in out


def test_list_uptime_check_configs(capsys, uptime):
snippets.list_uptime_check_configs(uptime.project_name)
out, _ = capsys.readouterr()
assert uptime.config.display_name in out


def test_list_uptime_check_ips(capsys):
snippets.list_uptime_check_ips()
out, _ = capsys.readouterr()
assert 'Singapore' in out