From 365d55f7cd764d48b1d2f4a521be9e581c2321eb Mon Sep 17 00:00:00 2001 From: arithmetic1728 Date: Thu, 10 Sep 2020 13:30:23 -0700 Subject: [PATCH] remove iot manager samples --- iot/api-client/manager/README.md | 3 + iot/api-client/manager/README.rst | 161 --- iot/api-client/manager/README.rst.in | 23 - iot/api-client/manager/manager.py | 1041 ----------------- iot/api-client/manager/manager_test.py | 506 -------- iot/api-client/manager/requirements-test.txt | 1 - iot/api-client/manager/requirements.txt | 9 - iot/api-client/manager/resources/README.md | 9 - .../manager/resources/ec_public.pem | 4 - iot/api-client/manager/resources/rsa_cert.pem | 18 - .../manager/resources/rsa_private.pem | 28 - 11 files changed, 3 insertions(+), 1800 deletions(-) create mode 100644 iot/api-client/manager/README.md delete mode 100644 iot/api-client/manager/README.rst delete mode 100644 iot/api-client/manager/README.rst.in delete mode 100644 iot/api-client/manager/manager.py delete mode 100644 iot/api-client/manager/manager_test.py delete mode 100644 iot/api-client/manager/requirements-test.txt delete mode 100644 iot/api-client/manager/requirements.txt delete mode 100644 iot/api-client/manager/resources/README.md delete mode 100644 iot/api-client/manager/resources/ec_public.pem delete mode 100644 iot/api-client/manager/resources/rsa_cert.pem delete mode 100644 iot/api-client/manager/resources/rsa_private.pem diff --git a/iot/api-client/manager/README.md b/iot/api-client/manager/README.md new file mode 100644 index 00000000000..c246fec06a9 --- /dev/null +++ b/iot/api-client/manager/README.md @@ -0,0 +1,3 @@ +These samples have been moved. + +https://github.com/googleapis/python-iot/tree/master/samples diff --git a/iot/api-client/manager/README.rst b/iot/api-client/manager/README.rst deleted file mode 100644 index 9a43aba7d23..00000000000 --- a/iot/api-client/manager/README.rst +++ /dev/null @@ -1,161 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud IoT Core 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=iot/api-client/manager/README.rst - - -This directory contains samples for Google Cloud IoT Core. `Google Cloud IoT Core`_ allows developers to easily integrate Publish and Subscribe functionality with devices and programmatically manage device authorization. - - - - -.. _Google Cloud IoT Core: https://cloud.google.com/iot/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 -++++++++++++++++++++ - -#. 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 -------------------------------------------------------------------------------- - -Manager -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. 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=iot/api-client/manager/manager.py,iot/api-client/manager/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python manager.py - - usage: manager.py [-h] [--cloud_region CLOUD_REGION] - [--pubsub_topic PUBSUB_TOPIC] [--config CONFIG] - [--device_id DEVICE_ID] - [--ec_public_key_file EC_PUBLIC_KEY_FILE] - [--project_id PROJECT_ID] [--registry_id REGISTRY_ID] - [--rsa_certificate_file RSA_CERTIFICATE_FILE] - [--service_account_json SERVICE_ACCOUNT_JSON] - [--version VERSION] [--member MEMBER] [--role ROLE] - {create-es256,create-registry,create-rsa256,create-topic,create-unauth,delete-device,delete-registry,get,get-config-versions,get-iam-permissions,get-registry,get-state,list,list-registries,patch-es256,patch-rs256,set-config,set-iam-permissions} - ... - - Example of using the Google Cloud IoT Core device manager to administer - devices. - - Usage example: - - python manager.py \ - --project_id=my-project-id \ - --cloud_region=us-central1 \ - --service_account_json=$HOME/service_account.json \ - list-registries - - positional arguments: - {create-es256,create-registry,create-rsa256,create-topic,create-unauth,delete-device,delete-registry,get,get-config-versions,get-iam-permissions,get-registry,get-state,list,list-registries,patch-es256,patch-rs256,set-config,set-iam-permissions} - create-es256 Create a new device with the given id, using ES256 for - authentication. - create-registry Gets or creates a device registry. - create-rsa256 Create a new device with the given id, using RS256 for - authentication. - create-topic Creates a PubSub Topic and grants access to Cloud IoT - Core. - create-unauth Create a new device without authentication. - delete-device Delete the device with the given id. - delete-registry Deletes the specified registry. - get Retrieve the device with the given id. - get-config-versions - Lists versions of a device config in descending order - (newest first). - get-iam-permissions - Retrieves IAM permissions for the given registry. - get-registry Retrieves a device registry. - get-state Retrieve a device's state blobs. - list List all devices in the registry. - list-registries List all registries in the project. - patch-es256 Patch the device to add an ES256 public key to the - device. - patch-rs256 Patch the device to add an RSA256 public key to the - device. - set-config Patch the device to add an RSA256 public key to the - device. - set-iam-permissions - Sets IAM permissions for the given registry to a - single role/member. - - optional arguments: - -h, --help show this help message and exit - --cloud_region CLOUD_REGION - GCP cloud region - --pubsub_topic PUBSUB_TOPIC - Google Cloud Pub/Sub topic. Format is - projects/project_id/topics/topic-id - --config CONFIG Configuration sent to a device. - --device_id DEVICE_ID - Device id. - --ec_public_key_file EC_PUBLIC_KEY_FILE - Path to public ES256 key file. - --project_id PROJECT_ID - GCP cloud project name. - --registry_id REGISTRY_ID - Registry id. If not set, a name will be generated. - --rsa_certificate_file RSA_CERTIFICATE_FILE - Path to RS256 certificate file. - --service_account_json SERVICE_ACCOUNT_JSON - Path to service account json file. - --version VERSION Version number for setting device configuration. - --member MEMBER Member used for IAM commands. - --role ROLE Role used for IAM commands. - - - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/iot/api-client/manager/README.rst.in b/iot/api-client/manager/README.rst.in deleted file mode 100644 index 8debfbce735..00000000000 --- a/iot/api-client/manager/README.rst.in +++ /dev/null @@ -1,23 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud IoT Core - short_name: Cloud IoT Core - url: https://cloud.google.com/iot/docs - description: > - `Google Cloud IoT Core`_ allows developers to easily integrate Publish and - Subscribe functionality with devices and programmatically manage device - authorization. - -setup: -- auth -- install_deps - -samples: -- name: Manager - file: manager.py - show_help: True - -cloud_client_library: false - -folder: iot/api-client/manager diff --git a/iot/api-client/manager/manager.py b/iot/api-client/manager/manager.py deleted file mode 100644 index 1701940b049..00000000000 --- a/iot/api-client/manager/manager.py +++ /dev/null @@ -1,1041 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2017 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. - - -""" -Example of using the Google Cloud IoT Core device manager to administer -devices. - -Usage example: - - python manager.py \\ - --project_id=my-project-id \\ - --cloud_region=us-central1 \\ - --service_account_json=$HOME/service_account.json \\ - list-registries -""" - -import argparse -import io -import os -import sys -import time - -from google.api_core.exceptions import AlreadyExists -from google.cloud import iot_v1 -from google.cloud import pubsub -from google.oauth2 import service_account -from googleapiclient import discovery -from googleapiclient.errors import HttpError - - -def create_iot_topic(project, topic_name): - """Creates a PubSub Topic and grants access to Cloud IoT Core.""" - pubsub_client = pubsub.PublisherClient() - topic_path = pubsub_client.topic_path(project, topic_name) - - topic = pubsub_client.create_topic(topic_path) - policy = pubsub_client.get_iam_policy(topic_path) - - policy.bindings.add( - role='roles/pubsub.publisher', - members=['serviceAccount:cloud-iot@system.gserviceaccount.com']) - - pubsub_client.set_iam_policy(topic_path, policy) - - return topic - - -def get_client(service_account_json): - """Returns an authorized API client by discovering the IoT API and creating - a service object using the service account credentials JSON.""" - api_scopes = ['https://www.googleapis.com/auth/cloud-platform'] - api_version = 'v1' - discovery_api = 'https://cloudiot.googleapis.com/$discovery/rest' - service_name = 'cloudiotcore' - - credentials = service_account.Credentials.from_service_account_file( - service_account_json) - scoped_credentials = credentials.with_scopes(api_scopes) - - discovery_url = '{}?version={}'.format( - discovery_api, api_version) - - return discovery.build( - service_name, - api_version, - discoveryServiceUrl=discovery_url, - credentials=scoped_credentials) - - -def create_rs256_device( - service_account_json, project_id, cloud_region, registry_id, device_id, - certificate_file): - """Create a new device with the given id, using RS256 for - authentication.""" - # [START iot_create_rsa_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # certificate_file = 'path/to/certificate.pem' - - client = iot_v1.DeviceManagerClient() - - parent = client.registry_path(project_id, cloud_region, registry_id) - - with io.open(certificate_file) as f: - certificate = f.read() - - # Note: You can have multiple credentials associated with a device. - device_template = { - 'id': device_id, - 'credentials': [{ - 'public_key': { - 'format': 'RSA_X509_PEM', - 'key': certificate - } - }] - } - - return client.create_device(parent, device_template) - # [END iot_create_rsa_device] - - -def create_es256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, public_key_file): - """Create a new device with the given id, using ES256 for - authentication.""" - # [START iot_create_es_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # public_key_file = 'path/to/certificate.pem' - - client = iot_v1.DeviceManagerClient() - - parent = client.registry_path(project_id, cloud_region, registry_id) - - with io.open(public_key_file) as f: - public_key = f.read() - - # Note: You can have multiple credentials associated with a device. - device_template = { - 'id': device_id, - 'credentials': [{ - 'public_key': { - 'format': 'ES256_PEM', - 'key': public_key - } - }] - } - - return client.create_device(parent, device_template) - # [END iot_create_es_device] - - -def create_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Create a device to bind to a gateway if it does not exist.""" - # [START iot_create_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - - # Check that the device doesn't already exist - client = iot_v1.DeviceManagerClient() - - exists = False - - parent = client.registry_path(project_id, cloud_region, registry_id) - - devices = list(client.list_devices(parent=parent)) - - for device in devices: - if device.id == device_id: - exists = True - - # Create the device - device_template = { - 'id': device_id, - 'gateway_config': { - 'gateway_type': 'NON_GATEWAY', - 'gateway_auth_method': 'ASSOCIATION_ONLY' - } - } - - if not exists: - res = client.create_device(parent, device_template) - print('Created Device {}'.format(res)) - else: - print('Device exists, skipping') - # [END iot_create_device] - - -def create_unauth_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Create a new device without authentication.""" - # [START iot_create_unauth_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - client = iot_v1.DeviceManagerClient() - - parent = client.registry_path(project_id, cloud_region, registry_id) - - device_template = { - 'id': device_id, - } - - return client.create_device(parent, device_template) - # [END iot_create_unauth_device] - - -def delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Delete the device with the given id.""" - # [START iot_delete_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - print('Delete device') - client = iot_v1.DeviceManagerClient() - - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - return client.delete_device(device_path) - # [END iot_delete_device] - - -def delete_registry( - service_account_json, project_id, cloud_region, registry_id): - """Deletes the specified registry.""" - # [START iot_delete_registry] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - print('Delete registry') - - client = iot_v1.DeviceManagerClient() - registry_path = client.registry_path(project_id, cloud_region, registry_id) - - try: - client.delete_device_registry(registry_path) - print('Deleted registry') - return 'Registry deleted' - except HttpError: - print('Error, registry not deleted') - raise - # [END iot_delete_registry] - - -def get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Retrieve the device with the given id.""" - # [START iot_get_device] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - print('Getting device') - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - device = client.get_device(device_path) - - print('Id : {}'.format(device.id)) - print('Name : {}'.format(device.name)) - print('Credentials:') - - if device.credentials is not None: - for credential in device.credentials: - keyinfo = credential.public_key - print('\tcertificate: \n{}'.format(keyinfo.key)) - - if keyinfo.format == 4: - keyformat = 'ES256_X509_PEM' - elif keyinfo.format == 3: - keyformat = 'RSA_PEM' - elif keyinfo.format == 2: - keyformat = 'ES256_PEM' - elif keyinfo.format == 1: - keyformat = 'RSA_X509_PEM' - else: - keyformat = 'UNSPECIFIED_PUBLIC_KEY_FORMAT' - print('\tformat : {}'.format(keyformat)) - print('\texpiration: {}'.format(credential.expiration_time)) - - print('Config:') - print('\tdata: {}'.format(device.config.binary_data)) - print('\tversion: {}'.format(device.config.version)) - print('\tcloudUpdateTime: {}'.format(device.config.cloud_update_time)) - - return device - # [END iot_get_device] - - -def get_state( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Retrieve a device's state blobs.""" - # [START iot_get_device_state] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - device = client.get_device(device_path) - print('Last state: {}'.format(device.state)) - - print('State history') - states = client.list_device_states(device_path).device_states - for state in states: - print('State: {}'.format(state)) - - return states - # [END iot_get_device_state] - - -def list_devices( - service_account_json, project_id, cloud_region, registry_id): - """List all devices in the registry.""" - # [START iot_list_devices] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - print('Listing devices') - - client = iot_v1.DeviceManagerClient() - registry_path = client.registry_path(project_id, cloud_region, registry_id) - - devices = list(client.list_devices(parent=registry_path)) - for device in devices: - print('Device: {} : {}'.format(device.num_id, device.id)) - - return devices - # [END iot_list_devices] - - -def list_registries(service_account_json, project_id, cloud_region): - """List all registries in the project.""" - # [START iot_list_registries] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - print('Listing Registries') - client = iot_v1.DeviceManagerClient() - parent = client.location_path(project_id, cloud_region) - - registries = list(client.list_device_registries(parent)) - for registry in registries: - print('id: {}\n\tname: {}'.format( - registry.id, - registry.name)) - - return registries - # [END iot_list_registries] - - -def create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id): - """ Creates a registry and returns the result. Returns an empty result if - the registry already exists.""" - # [START iot_create_registry] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # pubsub_topic = 'your-pubsub-topic' - # registry_id = 'your-registry-id' - client = iot_v1.DeviceManagerClient() - parent = client.location_path(project_id, cloud_region) - - if not pubsub_topic.startswith('projects/'): - pubsub_topic = 'projects/{}/topics/{}'.format(project_id, pubsub_topic) - - body = { - 'event_notification_configs': [{ - 'pubsub_topic_name': pubsub_topic - }], - 'id': registry_id - } - - try: - response = client.create_device_registry(parent, body) - print('Created registry') - return response - except HttpError: - print('Error, registry not created') - raise - except AlreadyExists: - print('Error, registry already exists') - raise - # [END iot_create_registry] - - -def get_registry( - service_account_json, project_id, cloud_region, registry_id): - """ Retrieves a device registry.""" - # [START iot_get_registry] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - client = iot_v1.DeviceManagerClient() - registry_path = client.registry_path(project_id, cloud_region, registry_id) - - return client.get_device_registry(registry_path) - # [END iot_get_registry] - - -def open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id): - """Gets or creates a device registry.""" - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # pubsub_topic = 'your-pubsub-topic' - # registry_id = 'your-registry-id' - print('Creating registry') - - try: - response = create_registry( - service_account_json, project_id, cloud_region, - pubsub_topic, registry_id) - except AlreadyExists: - # Device registry already exists. We just re-use the existing one. - print( - 'Registry {} already exists - looking it up instead.'.format( - registry_id)) - response = get_registry( - service_account_json, project_id, cloud_region, - registry_id) - - print('Registry {} opened: '.format(response.name)) - print(response) - - -def patch_es256_auth( - service_account_json, project_id, cloud_region, registry_id, - device_id, public_key_file): - """Patch the device to add an ES256 public key to the device.""" - # [START iot_patch_es] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # public_key_file = 'path/to/certificate.pem' - print('Patch device with ES256 certificate') - - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - public_key_bytes = '' - with io.open(public_key_file) as f: - public_key_bytes = f.read() - - key = iot_v1.types.PublicKeyCredential( - format='ES256_PEM', - key=public_key_bytes) - - cred = iot_v1.types.DeviceCredential(public_key=key) - device = client.get_device(device_path) - - device.id = b'' - device.num_id = 0 - device.credentials.append(cred) - - mask = iot_v1.types.FieldMask() - mask.paths.append('credentials') - - return client.update_device( - device=device, - update_mask=mask) - # [END iot_patch_es] - - -def patch_rsa256_auth( - service_account_json, project_id, cloud_region, registry_id, device_id, - public_key_file): - """Patch the device to add an RSA256 public key to the device.""" - # [START iot_patch_rsa] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # public_key_file = 'path/to/certificate.pem' - print('Patch device with RSA256 certificate') - - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - public_key_bytes = '' - with io.open(public_key_file) as f: - public_key_bytes = f.read() - - key = iot_v1.types.PublicKeyCredential( - format='RSA_X509_PEM', - key=public_key_bytes) - - cred = iot_v1.types.DeviceCredential(public_key=key) - device = client.get_device(device_path) - - device.id = b'' - device.num_id = 0 - device.credentials.append(cred) - - mask = iot_v1.types.FieldMask() - mask.paths.append('credentials') - - return client.update_device( - device=device, - update_mask=mask) - - # [END iot_patch_rsa] - - -def set_config( - service_account_json, project_id, cloud_region, registry_id, device_id, - version, config): - # [START iot_set_device_config] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # version = '0' - # config= 'your-config-data' - print('Set device configuration') - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - data = config.encode('utf-8') - - return client.modify_cloud_to_device_config(device_path, data, version) - # [END iot_set_device_config] - - -def get_config_versions( - service_account_json, project_id, cloud_region, registry_id, - device_id): - """Lists versions of a device config in descending order (newest first).""" - # [START iot_get_device_configs] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - configs = client.list_device_config_versions(device_path) - - for config in configs.device_configs: - print('version: {}\n\tcloudUpdateTime: {}\n\t data: {}'.format( - config.version, - config.cloud_update_time, - config.binary_data)) - - return configs - # [END iot_get_device_configs] - - -def get_iam_permissions( - service_account_json, project_id, cloud_region, registry_id): - """Retrieves IAM permissions for the given registry.""" - # [START iot_get_iam_policy] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - client = iot_v1.DeviceManagerClient() - - registry_path = client.registry_path(project_id, cloud_region, registry_id) - - policy = client.get_iam_policy(registry_path) - - return policy - # [END iot_get_iam_policy] - - -def set_iam_permissions( - service_account_json, project_id, cloud_region, registry_id, role, - member): - """Sets IAM permissions for the given registry to a single role/member.""" - # [START iot_set_iam_policy] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # role = 'viewer' - # member = 'group:dpebot@google.com' - client = iot_v1.DeviceManagerClient() - registry_path = client.registry_path(project_id, cloud_region, registry_id) - - body = { - 'bindings': - [{ - 'members': [member], - 'role': role - }] - } - - return client.set_iam_policy(registry_path, body) - # [END iot_set_iam_policy] - - -def send_command( - service_account_json, project_id, cloud_region, registry_id, device_id, - command): - """Send a command to a device.""" - # [START iot_send_command] - print('Sending command to device') - client = iot_v1.DeviceManagerClient() - device_path = client.device_path( - project_id, cloud_region, registry_id, device_id) - - # command = 'Hello IoT Core!' - data = command.encode('utf-8') - - return client.send_command_to_device(device_path, data) - # [END iot_send_command] - - -def create_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id, certificate_file, algorithm): - """Create a gateway to bind devices to.""" - # [START iot_create_gateway] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # gateway_id = 'your-gateway-id' - # certificate_file = 'path/to/certificate.pem' - # algorithm = 'ES256' - # Check that the gateway doesn't already exist - exists = False - client = iot_v1.DeviceManagerClient() - - parent = client.registry_path(project_id, cloud_region, registry_id) - devices = list(client.list_devices(parent=parent)) - - for device in devices: - if device.id == gateway_id: - exists = True - print('Device: {} : {} : {} : {}'.format( - device.id, - device.num_id, - device.config, - device.gateway_config - )) - - with io.open(certificate_file) as f: - certificate = f.read() - - if algorithm == 'ES256': - certificate_format = 'ES256_PEM' - else: - certificate_format = 'RSA_X509_PEM' - - # TODO: Auth type - device_template = { - 'id': gateway_id, - 'credentials': [{ - 'public_key': { - 'format': certificate_format, - 'key': certificate - } - }], - 'gateway_config': { - 'gateway_type': 'GATEWAY', - 'gateway_auth_method': 'ASSOCIATION_ONLY' - } - } - - if not exists: - res = client.create_device(parent, device_template) - print('Created Gateway {}'.format(res)) - else: - print('Gateway exists, skipping') - # [END iot_create_gateway] - - -def bind_device_to_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id): - """Binds a device to a gateway.""" - # [START iot_bind_device_to_gateway] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # gateway_id = 'your-gateway-id' - client = iot_v1.DeviceManagerClient() - - create_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - parent = client.registry_path(project_id, cloud_region, registry_id) - - res = client.bind_device_to_gateway(parent, gateway_id, device_id) - - print('Device Bound! {}'.format(res)) - # [END iot_bind_device_to_gateway] - - -def unbind_device_from_gateway( - service_account_json, project_id, cloud_region, registry_id, device_id, - gateway_id): - """Unbinds a device to a gateway.""" - # [START iot_unbind_device_from_gateway] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # device_id = 'your-device-id' - # gateway_id = 'your-gateway-id' - client = iot_v1.DeviceManagerClient() - - parent = client.registry_path(project_id, cloud_region, registry_id) - - res = client.unbind_device_from_gateway(parent, gateway_id, device_id) - - print('Device unbound: {}'.format(res)) - # [END iot_unbind_device_from_gateway] - - -def list_gateways( - service_account_json, project_id, cloud_region, registry_id): - """Lists gateways in a registry""" - # [START iot_list_gateways] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - client = iot_v1.DeviceManagerClient() - - path = client.registry_path(project_id, cloud_region, registry_id) - mask = iot_v1.types.FieldMask() - mask.paths.append('config') - mask.paths.append('gateway_config') - devices = list(client.list_devices(parent=path, field_mask=mask)) - - for device in devices: - if device.gateway_config is not None: - if device.gateway_config.gateway_type == 1: - print('Gateway ID: {}\n\t{}'.format(device.id, device)) - # [END iot_list_gateways] - - -def list_devices_for_gateway( - service_account_json, project_id, cloud_region, registry_id, - gateway_id): - """List devices bound to a gateway""" - # [START iot_list_devices_for_gateway] - # project_id = 'YOUR_PROJECT_ID' - # cloud_region = 'us-central1' - # registry_id = 'your-registry-id' - # gateway_id = 'your-gateway-id' - client = iot_v1.DeviceManagerClient() - - path = client.registry_path(project_id, cloud_region, registry_id) - - devices = list(client.list_devices( - parent=path, - gateway_list_options={'associations_gateway_id': gateway_id})) - - found = False - for device in devices: - found = True - print('Device: {} : {}'.format(device.num_id, device.id)) - - if not found: - print('No devices bound to gateway {}'.format(gateway_id)) - # [END iot_list_devices_for_gateway] - - -def parse_command_line_args(): - """Parse command line arguments.""" - default_registry = 'cloudiot_device_manager_example_registry_{}'.format( - int(time.time())) - - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - - # Optional arguments - parser.add_argument( - '--algorithm', - choices=('RS256', 'ES256'), - help='Which encryption algorithm to use to generate the JWT.') - parser.add_argument( - '--certificate_path', - help='Path to public certificate.') - parser.add_argument( - '--cloud_region', default='us-central1', help='GCP cloud region') - parser.add_argument( - '--pubsub_topic', - help=('Google Cloud Pub/Sub topic. ' - 'Format is projects/project_id/topics/topic-id')) - parser.add_argument( - '--config', - default=None, - help='Configuration sent to a device.') - parser.add_argument( - '--device_id', - default=None, - help='Device id.') - parser.add_argument( - '--ec_public_key_file', - default=None, - help='Path to public ES256 key file.') - parser.add_argument( - '--gateway_id', - help='Gateway identifier.') - parser.add_argument( - '--member', - default=None, - help='Member used for IAM commands.') - parser.add_argument( - '--role', - default=None, - help='Role used for IAM commands.') - parser.add_argument( - '--send_command', - default='1', - help='The command sent to the device') - parser.add_argument( - '--project_id', - default=os.environ.get("GOOGLE_CLOUD_PROJECT"), - help='GCP cloud project name.') - parser.add_argument( - '--registry_id', - default=default_registry, - help='Registry id. If not set, a name will be generated.') - parser.add_argument( - '--rsa_certificate_file', - default=None, - help='Path to RS256 certificate file.') - parser.add_argument( - '--service_account_json', - default=os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), - help='Path to service account json file.') - parser.add_argument( - '--version', - default=0, - type=int, - help='Version number for setting device configuration.') - - # Command subparser - command = parser.add_subparsers(dest='command') - - command.add_parser( - 'bind-device-to-gateway', help=bind_device_to_gateway.__doc__) - command.add_parser('create-es256', help=create_es256_device.__doc__) - command.add_parser('create-gateway', help=create_gateway.__doc__) - command.add_parser('create-registry', help=open_registry.__doc__) - command.add_parser('create-rsa256', help=create_rs256_device.__doc__) - command.add_parser('create-topic', help=create_iot_topic.__doc__) - command.add_parser('create-unauth', help=create_unauth_device.__doc__) - command.add_parser('delete-device', help=delete_device.__doc__) - command.add_parser('delete-registry', help=delete_registry.__doc__) - command.add_parser('get', help=get_device.__doc__) - command.add_parser('get-config-versions', help=get_config_versions.__doc__) - command.add_parser('get-iam-permissions', help=get_iam_permissions.__doc__) - command.add_parser('get-registry', help=get_registry.__doc__) - command.add_parser('get-state', help=get_state.__doc__) - command.add_parser('list', help=list_devices.__doc__) - command.add_parser( - 'list-devices-for-gateway', help=list_devices_for_gateway.__doc__) - command.add_parser('list-gateways', help=list_gateways.__doc__) - command.add_parser('list-registries', help=list_registries.__doc__) - command.add_parser('patch-es256', help=patch_es256_auth.__doc__) - command.add_parser('patch-rs256', help=patch_rsa256_auth.__doc__) - command.add_parser('send-command', help=send_command.__doc__) - command.add_parser('set-config', help=patch_rsa256_auth.__doc__) - command.add_parser('set-iam-permissions', help=set_iam_permissions.__doc__) - command.add_parser( - 'unbind-device-from-gateway', help=unbind_device_from_gateway.__doc__) - - return parser.parse_args() - - -def run_create(args): - """Handles commands that create devices, registries, or topics.""" - if args.command == 'create-rsa256': - create_rs256_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.rsa_certificate_file) - - elif args.command == 'create-es256': - create_es256_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.ec_public_key_file) - - elif args.command == 'create-gateway': - create_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id, args.certificate_path, args.algorithm) - - elif args.command == 'create-unauth': - create_unauth_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'create-registry': - if (args.pubsub_topic is None): - sys.exit('Error: specify --pubsub_topic') - open_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.pubsub_topic, args.registry_id) - - elif args.command == 'create-topic': - if (args.pubsub_topic is None): - sys.exit('Error: specify --pubsub_topic') - create_iot_topic(args.project_id, args.pubsub_topic) - - -def run_get(args): - if args.command == 'get': - get_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-config-versions': - get_config_versions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-state': - get_state( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - - elif args.command == 'get-iam-permissions': - print(get_iam_permissions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id)) - - elif args.command == 'get-registry': - print(get_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id)) - - -def run_list(args): - if args.command == 'list': - list_devices( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'list-devices-for-gateway': - list_devices_for_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.gateway_id) - elif args.command == 'list-gateways': - list_gateways( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'list-registries': - list_registries( - args.service_account_json, args.project_id, - args.cloud_region) - - -def run_command(args): - """Calls the program using the specified command.""" - if args.project_id is None: - print('You must specify a project ID or set the environment variable.') - return - elif args.command.startswith('create'): - run_create(args) - elif args.command.startswith('get'): - run_get(args) - elif args.command.startswith('list'): - run_list(args) - - elif args.command == 'bind-device-to-gateway': - bind_device_to_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id) - elif args.command == 'delete-device': - delete_device( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id) - elif args.command == 'delete-registry': - delete_registry( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id) - elif args.command == 'patch-es256': - if (args.ec_public_key_file is None): - sys.exit('Error: specify --ec_public_key_file') - patch_es256_auth( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.ec_public_key_file) - elif args.command == 'patch-rs256': - if (args.rsa_certificate_file is None): - sys.exit('Error: specify --rsa_certificate_file') - patch_rsa256_auth( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.rsa_certificate_file) - elif args.command == 'send-command': - send_command( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.send_command) - elif args.command == 'set-iam-permissions': - if (args.member is None): - sys.exit('Error: specify --member') - if (args.role is None): - sys.exit('Error: specify --role') - set_iam_permissions( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.role, args.member) - elif args.command == 'set-config': - if (args.config is None): - sys.exit('Error: specify --config') - if (args.version is None): - sys.exit('Error: specify --version') - set_config( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.version, args.config) - elif args.command == 'unbind-device-from-gateway': - unbind_device_from_gateway( - args.service_account_json, args.project_id, - args.cloud_region, args.registry_id, args.device_id, - args.gateway_id) - - -if __name__ == '__main__': - args = parse_command_line_args() - run_command(args) diff --git a/iot/api-client/manager/manager_test.py b/iot/api-client/manager/manager_test.py deleted file mode 100644 index 7cb3378d0a0..00000000000 --- a/iot/api-client/manager/manager_test.py +++ /dev/null @@ -1,506 +0,0 @@ -# Copyright 2017 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 datetime -import os -import sys -import time -import uuid - -from google.cloud import pubsub -import pytest - -# Add command receiver for bootstrapping device registry / device for testing -sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'mqtt_example')) # noqa -import cloudiot_mqtt_example # noqa -import manager # noqa - - -cloud_region = 'us-central1' -device_id_template = 'test-device-{}' -ca_cert_path = '../mqtt_example/resources/roots.pem' -es_cert_path = 'resources/ec_public.pem' -rsa_cert_path = 'resources/rsa_cert.pem' -rsa_private_path = 'resources/rsa_private.pem' # Must match rsa_cert -topic_id = 'test-device-events-{}'.format(uuid.uuid4()) - -project_id = os.environ['GOOGLE_CLOUD_PROJECT'] -service_account_json = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] - -pubsub_topic = 'projects/{}/topics/{}'.format(project_id, topic_id) - -# This format is used in the `clean_up_registries()` below. -registry_id = 'test-registry-{}-{}'.format(uuid.uuid4().hex, int(time.time())) - - -@pytest.fixture(scope="session", autouse=True) -def clean_up_registries(): - all_registries = list(manager.list_registries( - service_account_json, project_id, cloud_region)) - - for registry in all_registries: - registry_id = registry.id - if registry_id.find('test-registry-') == 0: - time_str = registry_id[ - registry_id.rfind('-') + 1: len(registry_id)] - test_date = datetime.datetime.utcfromtimestamp(int(time_str)) - now_date = datetime.datetime.utcfromtimestamp(int(time.time())) - difftime = now_date - test_date - - # *NOTE* Restrict to registries used in the tests older than 30 - # days to prevent thrashing in the case of async tests - if (difftime.days > 30): - client = manager.get_client(service_account_json) - gateways = client.projects().locations().registries().devices( - ).list( - parent=registry.name, - fieldMask='config,gatewayConfig' - ).execute().get('devices', []) - devices = client.projects().locations().registries().devices( - ).list(parent=registry.name).execute().get( - 'devices', []) - - # Unbind devices from each gateway and delete - for gateway in gateways: - gateway_id = gateway.get('id') - bound = client.projects().locations().registries().devices( - ).list( - parent=registry.name, - gatewayListOptions_associationsGatewayId=gateway_id - ).execute() - if 'devices' in bound: - for device in bound['devices']: - bind_request = { - 'deviceId': device.get('id'), - 'gatewayId': gateway_id - } - client.projects().locations().registries( - ).unbindDeviceFromGateway( - parent=registry.get('name'), - body=bind_request).execute() - gateway_name = '{}/devices/{}'.format( - registry.name, gateway_id) - client.projects().locations().registries().devices( - ).delete(name=gateway_name).execute() - - # Delete the devices - # Assumption is that the devices are not bound to gateways - for device in devices: - device_name = '{}/devices/{}'.format( - registry.name, device.get('id')) - print(device_name) - remove_device = True - try: - client.projects().locations().registries().devices( - ).get(name=device_name).execute() - except Exception: - remove_device = False - - if remove_device: - print('removing {}'.format(device_name)) - client.projects().locations().registries().devices( - ).delete(name=device_name).execute() - - # Delete the old test registry - client.projects().locations().registries().delete( - name=registry.name).execute() - - -@pytest.fixture(scope='module') -def test_topic(): - topic = manager.create_iot_topic(project_id, topic_id) - - yield topic - - pubsub_client = pubsub.PublisherClient() - topic_path = pubsub_client.topic_path(project_id, topic_id) - pubsub_client.delete_topic(topic_path) - - -def test_create_delete_registry(test_topic, capsys): - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.list_devices( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - - # Check that create / list worked - assert 'Created registry' in out - assert 'event_notification_config' in out - - # Clean up - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - -def test_get_iam_permissions(test_topic, capsys): - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.list_devices( - service_account_json, project_id, cloud_region, registry_id) - - # Test getting IAM permissions - print(manager.get_iam_permissions( - service_account_json, project_id, cloud_region, registry_id)) - - # Test setting IAM permissions - MEMBER = "group:dpebot@google.com" - ROLE = "roles/viewer" - print(manager.set_iam_permissions( - service_account_json, project_id, cloud_region, registry_id, - ROLE, MEMBER)) - - out, _ = capsys.readouterr() - - # Check that create / list worked - assert 'Created registry' in out - assert 'event_notification_config' in out - assert 'dpebot' in out - assert 'etag' in out - - # Clean up - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - -def test_add_delete_unauth_device(test_topic, capsys): - device_id = device_id_template.format('UNAUTH') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_unauth_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - assert 'UNAUTH' in out - - -@pytest.mark.flaky(max_runs=5, min_passes=1) -def test_add_config_unauth_device(test_topic, capsys): - device_id = device_id_template.format('UNAUTH') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_unauth_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.set_config( - service_account_json, project_id, cloud_region, registry_id, - device_id, 0, 'test') - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.get_config_versions( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - assert 'Set device configuration' in out - assert 'UNAUTH' in out - assert 'version: 2' in out - - -def test_add_delete_rs256_device(test_topic, capsys): - device_id = device_id_template.format('RSA256') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_rs256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, rsa_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.get_state( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - assert 'format : RSA_X509_PEM' in out - - -def test_add_delete_es256_device(test_topic, capsys): - device_id = device_id_template.format('ES256') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_es256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, es_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.get_state( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - assert 'format : ES256_PEM' in out - - -def test_add_patch_delete_rs256(test_topic, capsys): - device_id = device_id_template.format('PATCHME') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_rs256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, rsa_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - out, _ = capsys.readouterr() - assert 'format : RSA_X509_PEM' in out - - manager.patch_es256_auth( - service_account_json, project_id, cloud_region, registry_id, - device_id, es_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - out, _ = capsys.readouterr() - assert 'format : ES256_PEM' in out - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - -def test_add_patch_delete_es256(test_topic, capsys): - device_id = device_id_template.format('PATCHME') - manager.open_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - manager.create_es256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, es_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - out, _ = capsys.readouterr() - assert 'format : ES256_PEM' in out - - manager.patch_rsa256_auth( - service_account_json, project_id, cloud_region, registry_id, - device_id, rsa_cert_path) - - manager.get_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - out, _ = capsys.readouterr() - assert 'format : RSA_X509_PEM' in out - - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - -@pytest.mark.flaky(max_runs=5, min_passes=1) -def test_send_command(test_topic, capsys): - device_id = device_id_template.format('RSA256') - manager.create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - exists = False - devices = manager.list_devices( - service_account_json, project_id, cloud_region, registry_id) - for device in devices: - if device.id == device_id: - exists = True - - if not exists: - manager.create_rs256_device( - service_account_json, project_id, cloud_region, registry_id, - device_id, rsa_cert_path) - - # Exercize the functionality - client = cloudiot_mqtt_example.get_client( - project_id, cloud_region, registry_id, device_id, - rsa_private_path, 'RS256', ca_cert_path, - 'mqtt.googleapis.com', 443) - client.loop_start() - out, _ = capsys.readouterr() - - # Pre-process commands - for i in range(1, 5): - time.sleep(1) - - manager.send_command( - service_account_json, project_id, cloud_region, registry_id, - device_id, 'me want cookies') - out, _ = capsys.readouterr() - - # Process commands - for i in range(1, 5): - time.sleep(1) - - # Clean up - client.loop_stop() - client.disconnect() - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - assert 'Sending command to device' in out - assert '400' not in out - - -def test_create_gateway(test_topic, capsys): - gateway_id = device_id_template.format('RS256') - manager.create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - # TODO: consider adding test for ES256 - manager.create_gateway( - service_account_json, project_id, cloud_region, registry_id, - None, gateway_id, rsa_cert_path, 'RS256') - - # Clean up - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - gateway_id) - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - - assert 'Created Gateway' in out - - -def test_list_gateways(test_topic, capsys): - gateway_id = device_id_template.format('RS256') - manager.create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - - # TODO: consider adding test for ES256 - manager.create_gateway( - service_account_json, project_id, cloud_region, registry_id, - None, gateway_id, rsa_cert_path, 'RS256') - - manager.list_gateways( - service_account_json, project_id, cloud_region, registry_id) - - # Clean up - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - gateway_id) - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - - assert 'Gateway ID: {}'.format(gateway_id) in out - - -def test_bind_device_to_gateway_and_unbind(test_topic, capsys): - gateway_id = device_id_template.format('RS256') - device_id = device_id_template.format('noauthbind') - manager.create_registry( - service_account_json, project_id, cloud_region, pubsub_topic, - registry_id) - manager.create_gateway( - service_account_json, project_id, cloud_region, registry_id, - None, gateway_id, rsa_cert_path, 'RS256') - - manager.create_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - - manager.bind_device_to_gateway( - service_account_json, project_id, cloud_region, registry_id, - device_id, gateway_id) - manager.unbind_device_from_gateway( - service_account_json, project_id, cloud_region, registry_id, - device_id, gateway_id) - - # Clean up - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - device_id) - manager.delete_device( - service_account_json, project_id, cloud_region, registry_id, - gateway_id) - manager.delete_registry( - service_account_json, project_id, cloud_region, registry_id) - - out, _ = capsys.readouterr() - - assert 'Device Bound' in out - assert 'Device unbound' in out - assert 'HttpError 404' not in out diff --git a/iot/api-client/manager/requirements-test.txt b/iot/api-client/manager/requirements-test.txt deleted file mode 100644 index 7e460c8c866..00000000000 --- a/iot/api-client/manager/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==6.0.1 diff --git a/iot/api-client/manager/requirements.txt b/iot/api-client/manager/requirements.txt deleted file mode 100644 index 048caed4ebe..00000000000 --- a/iot/api-client/manager/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -cryptography==3.1 -flaky==3.7.0 -google-api-python-client==1.11.0 -google-auth-httplib2==0.0.4 -google-auth==1.21.1 -google-cloud-iot==1.0.0 -google-cloud-pubsub==1.7.0 -paho-mqtt==1.5.0 -pyjwt==1.7.1 diff --git a/iot/api-client/manager/resources/README.md b/iot/api-client/manager/resources/README.md deleted file mode 100644 index 20a0344f958..00000000000 --- a/iot/api-client/manager/resources/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Test public certificate files - -[![Open in Cloud Shell][shell_img]][shell_link] - -[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png -[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=iot/api-client/manager/resources/README.md - -The public certificates in this folder are only provided for testing and should -not be used for registering your devices. diff --git a/iot/api-client/manager/resources/ec_public.pem b/iot/api-client/manager/resources/ec_public.pem deleted file mode 100644 index 3b61697ab73..00000000000 --- a/iot/api-client/manager/resources/ec_public.pem +++ /dev/null @@ -1,4 +0,0 @@ ------BEGIN PUBLIC KEY----- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEhbN0N+3JH+3VBR/Xex4b1JzeJZgG -SUeTFIUpg/svqd+B4tYZySSYOccVJFUyL805mSgUMQ84/bYAIVybWZqvAQ== ------END PUBLIC KEY----- diff --git a/iot/api-client/manager/resources/rsa_cert.pem b/iot/api-client/manager/resources/rsa_cert.pem deleted file mode 100644 index f0c79f9c9c0..00000000000 --- a/iot/api-client/manager/resources/rsa_cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC+DCCAeCgAwIBAgIJALt7HnuYGgVcMA0GCSqGSIb3DQEBCwUAMBExDzANBgNV -BAMMBnVudXNlZDAeFw0xODEyMDMwMDE2MjNaFw0yODExMzAwMDE2MjNaMBExDzAN -BgNVBAMMBnVudXNlZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOrA -b+5XMIgwyl6+CkdJkKKp4f+2hHAOoSqQroj2MR/i41YysUbKCk8KdQSZqTBtIvrY -df7s6zDV3zmi3LBBHX6MGnz/1j5YIXlujBhsnQTRbTuUjjDx96ik2C2rR1w7okA7 -MmBsdVzRe8g5pfNQGdV0l15UaZK+qFlLg0xzasPPKmYFFUbKXeWPaKJmtw9d/l6a -8jb87fwI3LTWjZr6Bk7L4Zf1TDlTDroMvNlkW9Z9xSkcgC77EjMtC7RYxxbelaxd -qI9IdxIpmExg6pKMJEvJNA11GYhTlAxkJNh7gd0WlYvQlwDI7D6NJPbCmm4ac1P2 -AA1MFHVgxoKAFk/8V38CAwEAAaNTMFEwHQYDVR0OBBYEFC5Dlz2bTWzaJO6i1Qn8 -lTdDAigCMB8GA1UdIwQYMBaAFC5Dlz2bTWzaJO6i1Qn8lTdDAigCMA8GA1UdEwEB -/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBANmnnBQaWPhJne5kOjMe+SEsdLbG -OD9L8RmokOsRPXJbj2KoM07UUXMgUe57daYm72wDfKZpvG5qwybkkym+NnahJY+C -u9FX1dTBjM/TqPWKI817mDp5W31a+q6DXdggG+Yf6pz0dMXGGzRtSTEpLKsKtXqe -Y9f7266JCx9V5QFK14SmpIdBF38G0bcNPEvRJ6uKaVKBnU4+7o4YlQLuDczT29Tp -CXL0egUViNT9kv03Pj9iSPR6EGcmOjnSZe1SFVg9OeCauF1wuuFCxUuCkWSEkEm7 -laNke9PHHTe9BoBxKMsTFEPivhVaAf9fUp+NQxZNmdgbux9AAlJgiyU0sFg= ------END CERTIFICATE----- diff --git a/iot/api-client/manager/resources/rsa_private.pem b/iot/api-client/manager/resources/rsa_private.pem deleted file mode 100644 index 5eaf0240ce8..00000000000 --- a/iot/api-client/manager/resources/rsa_private.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDqwG/uVzCIMMpe -vgpHSZCiqeH/toRwDqEqkK6I9jEf4uNWMrFGygpPCnUEmakwbSL62HX+7Osw1d85 -otywQR1+jBp8/9Y+WCF5bowYbJ0E0W07lI4w8feopNgtq0dcO6JAOzJgbHVc0XvI -OaXzUBnVdJdeVGmSvqhZS4NMc2rDzypmBRVGyl3lj2iiZrcPXf5emvI2/O38CNy0 -1o2a+gZOy+GX9Uw5Uw66DLzZZFvWfcUpHIAu+xIzLQu0WMcW3pWsXaiPSHcSKZhM -YOqSjCRLyTQNdRmIU5QMZCTYe4HdFpWL0JcAyOw+jST2wppuGnNT9gANTBR1YMaC -gBZP/Fd/AgMBAAECggEBAOevf4kColJ3nPM+qlRLJaV09yjyUOlrduLUon1oRXmL -6wUCyPXtp5j04CLnKRUzUUezZVlxKHotSr/OnfKSgXKJAgeGVEN5paf8U+YzJBFC -RIV+C4wA84WNFBKWrbo43Nx50DFcOcSet4UYaFGoJ6cFB/PAaeW7p9lhbreAXcnb -g2z4SBsGGO2ZKZkSOcXg39GKX5S0bsEhHzIOFvPBdDQpaVAx/Bq76iBzVz1bRwGp -A3SjJn0g4V+3TcTrpRzgtCRRNPM48JeLHw6/mdVSk6gIoEbg+WTB92Z7BlTbjqhI -LPoMx3wQkg7J2gRrT0rPJIMkgdK9Q8RyWaulsRAn+gECgYEA/jfisAhn7IAPBXKz -ED56NSr174qX97SO2JrB7PO614BV8lHSoV4QI+nQCBkNVhL/SuWvqB3naImo+UOX -Smo6fmh78X+yIXKKhj9qY01jxRGcrnhA25L9gk7TFSNm7XaV2HxHq+TW6tvkL0uO -jXSH3D+u8/f+5ZCt/egNq3eU4n8CgYEA7GWgBLq8jmiz/VVLYboJ0YcJVZ5XAjfJ -vgzxdzX9hIkq5Cpt1ZpO9zE3IXClVvfECXcLpEzoHbiJkEve4dDqbSe4T4JPmpRx -BKRPWFJvTieLA912UmHRBDTrQSA/nZ5zxHsXYmN52femqCwbPWYu5czoqud+GcNq -ghj4oF9UCwECgYEAzpaHx1ntakne6yR807SSB2b0GUfdm1TFyMxqz655pesK7TMF -IlGYeDbn8cy6A7rIcAsbplk21sMX6Ai/h5+wDU3He0e0cG3umI4sXKpla56WX0om -Gsnm7eA0tTbhzBPUTeshK1V6Ob2cP7r9C4MpbRjriiN8pv3eBzpu8WrqOO0CgYAB -8bgGMe75EN1iGQB8tkX8ZirqfFnk18ad/IdD3rrOCz7CD6NFnXZGzC3S5ZVGiNUg -6sy6tjM2g10GRcl4e/phmXEHnl+/OrdPPXa1mD/4GZUoG/ssJEfOzAyfRX+gcTws -goKnuX+4DjRdr7ctoxiBpVTIiwzbc2L93Oy2jPIpAQKBgGzaYhfOlB3SWo+iSKcb -Vx++0gXru1Sgeo42TIn+6adO6DYfwVtfaScVL+Jcg7MZYY+94gnPCp+/ohVTJTvQ -JZdI9Czem64VUtSvc0DCji5gPqvgsO5YgBQrGJJrbmVwu0A6RlNbDwxCdkqHuYk4 -7vsxlbXvNufb0LjnNN0lSUU2 ------END PRIVATE KEY-----