├── tests └── library │ ├── __init__.py │ └── client_test.py ├── setup.cfg ├── ibm_analytics_engine ├── __init__.py ├── logger.py ├── ibm_cloud_region.py ├── analytics_engines.py ├── resource_controller.py └── client.py ├── .travis.yml ├── tox.ini ├── setup.py ├── DEVELOPING.md ├── README.md ├── .gitignore ├── Development.ipynb └── LICENSE.txt /tests/library/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /ibm_analytics_engine/__init__.py: -------------------------------------------------------------------------------- 1 | """A python library for working with IBM Analytics Engine 2 | 3 | .. moduleauthor:: Chris Snow 4 | 5 | """ 6 | 7 | from __future__ import absolute_import 8 | 9 | 10 | from .logger import Logger 11 | 12 | from .client import AnalyticsEngine, AnalyticsEngineException 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.3" 5 | - "3.4" 6 | - "3.5" 7 | - "3.6" 8 | install: 9 | - pip install tox-travis 10 | - pip install python-coveralls 11 | 12 | script: 13 | - tox 14 | - coverage run --source ibm_analytics_engine setup.py test 15 | - coverage report -m 16 | 17 | after_success: 18 | - coveralls 19 | 20 | -------------------------------------------------------------------------------- /ibm_analytics_engine/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | class Logger: 5 | 6 | def get_logger(self, clazz): 7 | format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 8 | logging.basicConfig(format=format) 9 | logger = logging.getLogger(clazz) 10 | logger.setLevel(os.getenv("LOG_LEVEL", logging.INFO)) 11 | return logger 12 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # tox (https://tox.readthedocs.io/) is a tool for running tests 2 | # in multiple virtualenvs. This configuration file will run the 3 | # test suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | 6 | [tox] 7 | envlist = py27, py33, py34, py35, py36 8 | 9 | [testenv] 10 | commands = nosetests {posargs} 11 | deps = 12 | nose 13 | mock 14 | 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='ibm-analytics-engine-python', 5 | description="IBM Analytics Engine library", 6 | author='Chris Snow', 7 | author_email='chsnow123@gmail.com', 8 | url='https://github.com/snowch/ibm-analytics-engine-python', 9 | packages = ['ibm_analytics_engine'], 10 | keywords = 'IBM Analytics Engine Spark Hadoop', 11 | install_requires=[ 'requests', 'python-ambariclient' ], 12 | test_suite='nose.collector', 13 | tests_require=['nose'], 14 | classifiers=[ 15 | "License :: OSI Approved :: Apache Software License", 16 | "Programming Language :: Python", 17 | "Programming Language :: Python :: 2.7", 18 | "Programming Language :: Python :: 3.3", 19 | "Programming Language :: Python :: 3.4", 20 | "Programming Language :: Python :: 3.5", 21 | "Programming Language :: Python :: 3.6", 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /tests/library/client_test.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | from mock import Mock, patch 3 | 4 | import sys 5 | import tempfile 6 | import os 7 | import json 8 | import requests 9 | from requests.exceptions import RequestException 10 | from ibm_analytics_engine import AnalyticsEngine, AnalyticsEngineException 11 | 12 | 13 | class TestAnalyticsEngine(TestCase): 14 | 15 | def test_invalid_api_key_file(self): 16 | try: 17 | error_class = IOError 18 | except BaseException: 19 | error_class = FileNotFoundError 20 | 21 | with self.assertRaises(error_class): 22 | cf = AnalyticsEngine(api_key_filename='does_not_exist') 23 | 24 | def test_api_key_file(self): 25 | # delete=True means the file will be deleted on close 26 | tmp = tempfile.NamedTemporaryFile(delete=True) 27 | try: 28 | data = json.dumps({ 29 | "name": "iae-key", 30 | "description": "", 31 | "createdAt": "2017-11-14T12:30+0000", 32 | "apiKey": "" 33 | }).encode('utf-8') 34 | tmp.write(data) 35 | tmp.flush() 36 | cf = AnalyticsEngine(api_key_filename=tmp.name) 37 | finally: 38 | tmp.close() # deletes the file 39 | 40 | -------------------------------------------------------------------------------- /DEVELOPING.md: -------------------------------------------------------------------------------- 1 | ### DEVELOPMENT ENVIRONMENT 2 | 3 | I use [Jupyterlab](https://jupyterlab.readthedocs.io/en/stable/) for development. 4 | 5 | See [Development](./Development.ipynb) for an example development notebook. 6 | 7 | ### COVERAGE 8 | 9 | Aim for 100% test coverage to ensure library will work with all specified python versions. 10 | 11 | ### FORMATTING 12 | 13 | ``` 14 | autopep8 --in-place --aggressive --aggressive 15 | ``` 16 | 17 | #### BUILDING DOCS 18 | 19 | ``` 20 | cd docs/ 21 | make clean html 22 | open _build/html/index.html 23 | ``` 24 | 25 | ### RELEASING 26 | 27 | ``` 28 | vi setup.py # increment version 29 | git add ... 30 | git commit -m '...' 31 | git tag 0.0.9 -m "Add pypi python versions" 32 | git push origin 0.0.9 33 | python setup.py sdist upload -r pypi 34 | ``` 35 | ### Testing 36 | 37 | Run all tests: 38 | 39 | ``` 40 | tox -e py27 41 | ``` 42 | 43 | Run all tests with coverage output: 44 | 45 | ``` 46 | coverage erase && coverage run --source ibm_analytics_engine setup.py test && coverage report -m 47 | ``` 48 | 49 | Run single test. 50 | 51 | ``` 52 | pytest tests/doc/test_create_cluster.py 53 | ``` 54 | 55 | Or, with tox: 56 | 57 | ``` 58 | tox -e py27 -- tests/doc/test_list_orgs_and_spaces.py 59 | ``` 60 | 61 | Or: 62 | 63 | ``` 64 | tox -e py27 -- tests/doc/test_list_orgs_and_spaces.py:DocExampleScripts_Test.test 65 | ``` 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![Build Status](https://travis-ci.org/snowch/ibm-analytics-engine-python.svg?branch=master)](https://travis-ci.org/snowch/ibm-analytics-engine-python) 3 | [![Issues](https://img.shields.io/github/issues/snowch/ibm-analytics-engine-python/bug.svg)](https://github.com/snowch/ibm-analytics-engine-python/issues?q=is%3Aissue+is%3Aopen+label%3A"bug") 4 | [![Coverage Status](https://coveralls.io/repos/github/snowch/ibm-analytics-engine-python/badge.svg?branch=master)](https://coveralls.io/github/snowch/ibm-analytics-engine-python?branch=master) 5 | [![Pyversions](https://img.shields.io/badge/Pyversions-2.7,%203.3,%203.4,%203.5,%203.6-green.svg)](https://github.com/snowch/ibm-analytics-engine-python/blob/master/tox.ini#L7) 6 | 7 | 8 | [![StackOverflow](http://img.shields.io/badge/stackoverflow-analytics%20engine%20python%20sdk-blue.svg)]( http://stackoverflow.com/questions/tagged/analytics-engine-python-sdk ) 9 | [![Documentation Status](http://readthedocs.org/projects/ibm-analytics-engine-python/badge/?version=latest)](http://ibm-analytics-engine-python.readthedocs.io/en/latest/?badge=latest) 10 | [![Apache2 license](http://img.shields.io/badge/license-apache2-brightgreen.svg)](http://opensource.org/licenses/Apache-2.0) 11 | 12 | ---- 13 | 14 | ### Overview 15 | 16 | This project is a python library (SDK) for working with [IBM Analytics Engine (IAE)](https://console.bluemix.net/docs/services/AnalyticsEngine/index.html). 17 | 18 | #### Documentation 19 | 20 | See example [notebook](./Development.ipynb) 21 | 22 | ### Support 23 | 24 | Please create an [issue](https://github.com/snowch/ibm-analytics-engine-python/issues) for questions, bugs and feature requests. 25 | 26 | ### Contributing 27 | 28 | See [DEVELOPING.md](./DEVELOPING.md) 29 | 30 | Pull requests are welcome! 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | docs/_build/ 103 | ipython_session.py 104 | vcap*.json 105 | .DS_Store 106 | -------------------------------------------------------------------------------- /ibm_analytics_engine/ibm_cloud_region.py: -------------------------------------------------------------------------------- 1 | import sys 2 | PY3 = sys.version_info[0] == 3 3 | 4 | if PY3: 5 | string_types = str 6 | else: 7 | string_types = basestring 8 | 9 | class Region: 10 | 11 | _valid_regions = ['us-south', 'uk-south'] 12 | 13 | def __init__(self, region): 14 | assert isinstance(region, string_types), "region parameter must be a string" 15 | assert region in self._valid_regions, "Invalid region '{}'. Supported regions: {}.".format(region, self._valid_regions) 16 | 17 | self.region = region 18 | 19 | def validate_region(self, region): 20 | if region not in self._valid_regions: 21 | raise ValueError( 22 | 23 | ) 24 | 25 | def api_endpoint(self): 26 | if self.region == 'us-south': return 'https://api.ng.bluemix.net' 27 | elif self.region == 'uk-south': return 'https://api.eu-gb.bluemix.net' 28 | 29 | def iam_endpoint(self): 30 | if self.region == 'us-south': return 'https://iam.ng.bluemix.net' 31 | elif self.region == 'uk-south': return 'https://iam.ng.bluemix.net' 32 | 33 | def iae_endpoint(self): 34 | if self.region == 'us-south': return 'https://api.us-south.ae.cloud.ibm.com' 35 | elif self.region == 'uk-south': return 'https://api.eu-gb.ae.cloud.ibm.com' 36 | 37 | def rc_endpoint(self): 38 | if self.region == 'us-south': return 'https://resource-controller.ng.bluemix.net' 39 | elif self.region == 'uk-south': return 'https://resource-controller.eu-gb.bluemix.net' 40 | 41 | def rm_endpoint(self): 42 | if self.region == 'us-south': return 'https://resource-manager.ng.bluemix.net' 43 | elif self.region == 'uk-south': return 'https://resource-manager.eu-gb.bluemix.net' 44 | 45 | -------------------------------------------------------------------------------- /ibm_analytics_engine/analytics_engines.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .logger import Logger 4 | 5 | from datetime import datetime, timedelta 6 | import time 7 | import requests 8 | import json 9 | 10 | class AnalyticsEngines: 11 | 12 | def __init__(self, client, region): 13 | self.client = client 14 | self.region = region 15 | 16 | def cluster_status(self, instance_id): 17 | url = self.region.iae_endpoint() + '/v2/analytics_engines/{}/state'.format(instance_id) 18 | response = self.client._request(url=url, http_method='get', description='cluster_status') 19 | return response.json() 20 | 21 | def poll_for_completion(self, instance_id): 22 | url = self.region.iae_endpoint() + '/v2/analytics_engines/{}/state'.format(instance_id) 23 | headers = self.client._request_headers() 24 | 25 | provision_poll_timeout_mins = self.client.provision_poll_timeout_mins 26 | 27 | poll_start = datetime.now() 28 | 29 | # Status codes: https://console.bluemix.net/docs/services/AnalyticsEngine/track-instance-provisioning.html#tracking-the-status-of-the-cluster-provisioning 30 | 31 | status = self.cluster_status(instance_id)['state'] 32 | while status == 'Preparing': 33 | 34 | if (datetime.now() - poll_start).seconds > (provision_poll_timeout_mins * 60): 35 | raise TimeoutError('Failed to provision with {} minutes'.format(provision_poll_timeout_mins)) 36 | 37 | try: 38 | response = requests.get(url, headers=headers) 39 | response.raise_for_status() 40 | 41 | d = response.json() 42 | status = d['state'] 43 | 44 | except requests.exceptions.RequestException as e: 45 | self.client.log.error('Service Provision Status Response: ' + response.text) 46 | raise 47 | 48 | time.sleep(30) 49 | 50 | self.client.log.debug('provisioning completed: ' + status) 51 | 52 | # returns current non-Preparing status 53 | return { 'state': status } 54 | 55 | -------------------------------------------------------------------------------- /ibm_analytics_engine/resource_controller.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .logger import Logger 4 | 5 | from datetime import datetime, timedelta 6 | import time 7 | import requests 8 | import json 9 | 10 | try: 11 | from urllib import quote # Python 2.X 12 | except ImportError: 13 | from urllib.parse import quote # Python 3+ 14 | 15 | # API Docs https://console.stage1.bluemix.net/apidocs/resource-controller 16 | class ResourceController: 17 | 18 | def __init__(self, client, region): 19 | self.client = client 20 | self.region = region 21 | 22 | def create(self, data): 23 | url = self.region.rc_endpoint() + '/v1/resource_instances' 24 | response = self.client._request(url=url, http_method='post', description='create_resource_instances', data=data) 25 | return response.json() 26 | 27 | def list(self, region_id=None, resource_group=None, resource_plan_id=None): 28 | 29 | #TODO - return the json response from the API call 30 | return 31 | 32 | def delete(self, id): 33 | # TODO is replacing the forward slash the only encoding that is required? 34 | urlsafe_id = id.replace('/', '%2F') 35 | 36 | url = self.region.rc_endpoint() + '/v1/resource_instances/' + urlsafe_id 37 | self.client._request(url=url, http_method='delete', description='delete') 38 | 39 | # if _request fails, an exception is returned to the client with a log message 40 | 41 | return True # only response code - no json 42 | 43 | # See https://console.bluemix.net/docs/services/AnalyticsEngine/Retrieve-service-credentials-and-service-end-points.html#obtaining-the-credentials-using-the-ibm-cloud-rest-api 44 | def create_credentials(self, instance_id, key_name, service_instance_name, role): 45 | url = self.region.rc_endpoint() + '/v1/resource_keys' 46 | data = { 47 | "name": key_name, 48 | "source_crn": service_instance_name, 49 | "parameters": { 50 | "role_crn": role 51 | } 52 | } 53 | response = self.client._request(url=url, http_method='post', description='create_credentials', data=data) 54 | return response.json() 55 | 56 | # I found this api method by tracing the bx client, i.e. `IBMCLOUD_TRACE=true bx resource groups` 57 | def get_resource_groups(self): 58 | account_id = self.client._get_account_id() 59 | 60 | headers = { 61 | "IAM-Apikey": self.client.api_key, 62 | } 63 | 64 | url = self.client.region.rm_endpoint() + '/v1/resource_groups?account_id=' + account_id 65 | response = self.client._request(url=url, http_method='get', description='get_resource_groups', additional_headers=headers) 66 | return response.json() 67 | -------------------------------------------------------------------------------- /ibm_analytics_engine/client.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .logger import Logger 4 | from .ibm_cloud_region import Region 5 | 6 | from .resource_controller import ResourceController 7 | from .analytics_engines import AnalyticsEngines 8 | 9 | 10 | import requests 11 | import json 12 | from datetime import datetime, timedelta 13 | 14 | import sys 15 | PY3 = sys.version_info[0] == 3 16 | 17 | if PY3: 18 | string_types = str 19 | else: 20 | string_types = basestring 21 | 22 | class AnalyticsEngineException(Exception): 23 | def __init__(self, message, *args): 24 | self.message = message 25 | super( AnalyticsEngineException, self).__init__(message, *args) 26 | 27 | class AnalyticsEngine(object): 28 | 29 | def __init__(self, 30 | api_key = None, 31 | api_key_filename = None, 32 | region = 'us-south', 33 | provision_poll_timeout_mins = 30): 34 | 35 | self.log = Logger().get_logger(self.__class__.__name__) 36 | self.provision_poll_timeout_mins = provision_poll_timeout_mins 37 | 38 | assert api_key is not None or api_key_filename is not None, "You must provide a value for api_key or for api_key_filename" 39 | 40 | assert isinstance(region, string_types), "region parameter must be of type string" 41 | 42 | # allow tests to override the api_key_filename parameter 43 | if hasattr(AnalyticsEngine, 'api_key_filename') and AnalyticsEngine is not None: 44 | api_key_filename = AnalyticsEngine.api_key_filename 45 | 46 | if api_key_filename is not None: 47 | try: 48 | with open(api_key_filename, 'r') as api_file: 49 | d = json.load(api_file) 50 | try: 51 | self.api_key = d['apikey'] 52 | except KeyError: 53 | # The attibute name used to be 54 | self.api_key = d['apiKey'] 55 | 56 | except: 57 | self.log.error('Error retrieving "apiKey" from file {}'.format(api_key_filename)) 58 | raise 59 | else: 60 | self.api_key = api_key 61 | 62 | self.region = Region(region) 63 | self.api_endpoint = self.region.api_endpoint() 64 | self.iam_endpoint = self.region.iam_endpoint() 65 | 66 | self.resource_controller = ResourceController(self, self.region) 67 | self.analytics_engines = AnalyticsEngines(self, self.region) 68 | 69 | 70 | def _auth(self): 71 | 72 | self.log.debug('Authenticating to IAM') 73 | url = self.iam_endpoint + '/identity/token' 74 | data = "apikey={}&grant_type=urn%3Aibm%3Aparams%3Aoauth%3Agrant-type%3Aapikey".format(self.api_key) 75 | headers = { 76 | "Content-Type": "application/x-www-form-urlencoded", 77 | "Authorization": "Basic Yng6Yng=" 78 | } 79 | 80 | try: 81 | response = requests.post(url, headers=headers, data=data) 82 | response.raise_for_status() 83 | except requests.exceptions.RequestException as e: 84 | self.log.error('IAM Auth Response: ' + response.text) 85 | # TODO we should define a custom application exception for this 86 | raise 87 | 88 | self.auth_token = response.json() 89 | self.expires_at = datetime.now() + timedelta(seconds=self.auth_token['expires_in']/60) 90 | self.log.debug('Authenticated to IAM') 91 | 92 | def get_auth_token(self): 93 | if not hasattr(self, 'auth_token') or not hasattr(self, 'expires_at') or datetime.now() > self.expires_at: 94 | self._auth() 95 | return self.auth_token 96 | 97 | def _request_headers(self): 98 | 99 | auth_token = self.get_auth_token() 100 | access_token = auth_token['access_token'] 101 | token_type = auth_token['token_type'] 102 | 103 | headers = { 104 | 'accept': 'application/json', 105 | 'authorization': '{} {}'.format(token_type, access_token), 106 | 'cache-control': 'no-cache', 107 | 'content-type': 'application/json' 108 | } 109 | return headers 110 | 111 | def _request(self, url, http_method='get', data=None, description='', create_auth_headers=True, additional_headers={}): 112 | if create_auth_headers: 113 | headers = self._request_headers() 114 | else: 115 | headers = {} 116 | 117 | all_headers = {} 118 | all_headers.update(headers) 119 | all_headers.update(additional_headers) 120 | 121 | try: 122 | if http_method == 'get': 123 | response = requests.get(url, headers=all_headers) 124 | elif http_method == 'post': 125 | response = requests.post(url, headers=all_headers, data=json.dumps(data)) 126 | elif http_method == 'delete': 127 | response = requests.delete(url, headers=all_headers) 128 | 129 | response.raise_for_status() 130 | except requests.exceptions.RequestException as e: 131 | self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) 132 | raise AnalyticsEngineException(message=response.text) 133 | 134 | try: 135 | self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, json.dumps(response.json()))) 136 | except ValueError: 137 | self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text)) 138 | 139 | return response 140 | 141 | # https://console.bluemix.net/apidocs/iam-identity-token-api#get-details-of-an-api-key-by-its-value-or-id-secre 142 | def _get_account_id(self): 143 | url = self.iam_endpoint + '/v1/apikeys/details' 144 | headers = { 145 | "IAM-Apikey": self.api_key, 146 | } 147 | response = self._request(url=url, http_method='get', description='_get_account_id', additional_headers=headers) 148 | account_id = response.json()['account_id'] 149 | 150 | # For some reason, returned value seems to be: XXXXXXXY-YYYY and we only need the first part 151 | return account_id.split('-')[0][:-1] 152 | 153 | def get_resource_groups(self): 154 | return self.resource_controller.get_resource_groups() 155 | 156 | def create(self, data): 157 | return self.resource_controller.create(data) 158 | 159 | def delete(self, id): 160 | return self.resource_controller.delete(id) 161 | 162 | def cluster_status(self, instance_id, wait_until_finished_preparing = False): 163 | if wait_until_finished_preparing is True: 164 | # Wait until status is no longer 'Preparing' 165 | return self.analytics_engines.poll_for_completion(instance_id) 166 | else: 167 | return self.analytics_engines.cluster_status(instance_id) 168 | 169 | # TODO reset password 170 | # https://console.bluemix.net/docs/services/AnalyticsEngine/reset-cluster-password.html#resetting-cluster-password 171 | -------------------------------------------------------------------------------- /Development.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Introduction\n", 8 | "\n", 9 | "This notebook is used for developing the IBM Analytics Engine Library. I use [Jupyterlab](https://jupyterlab.readthedocs.io/en/stable/) for development.\n", 10 | "\n", 11 | "After changing any of the library code, restart the kernel of this notebook to pick up the changes.\n" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "### Example Code" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "#### Setup for developing the IBM Analytics Engine Library (e.g. on local machine)" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "Setup python path for working directly with the IBM Analytics Engine Library source - this step is only required for developing locally." 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 1, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "import os, sys\n", 42 | "cwd = os.getcwd()\n", 43 | "if sys.path[0] != cwd:\n", 44 | " sys.path.insert(0,cwd)\n", 45 | "# print(sys.path)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "#### Setup for using the IBM Analytics Engine Library (e.g. from Watson Studio)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 2, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "# !pip install --upgrade --quiet git+https://github.com/snowch/ibm-analytics-engine-python@master" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "#### Using the IBM Analytics Engine Library" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "Create a new resource group API client.\n", 76 | "\n", 77 | "First create an [API Key](https://console.bluemix.net/docs/iam/apikeys.html#platform-api-keys) and save it somewhere safe" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 3, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "from ibm_analytics_engine.client import AnalyticsEngine\n", 87 | "import os\n", 88 | "\n", 89 | "home_directory = os.environ['HOME']\n", 90 | "\n", 91 | "# If you are using from Watson Studio, you could alternatively use the `api_key` paramater\n", 92 | "client = AnalyticsEngine(\n", 93 | " api_key_filename = '{}/.ibmcloud/apiKey.json'.format(home_directory)\n", 94 | " )" 95 | ] 96 | }, 97 | { 98 | "cell_type": "markdown", 99 | "metadata": {}, 100 | "source": [ 101 | "Find our Resource Groups" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 4, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "data": { 111 | "text/plain": [ 112 | "[('16c478f93fbe44b2b74a5e29a4a20121', 'ibm-cloud-streaming-retail-demo'),\n", 113 | " ('3b90ff40e6cc43978189146817edc403', 'default'),\n", 114 | " ('778882adaf4a4fb0831830ccd39fdde2', 'CSnow Watson Data Demo'),\n", 115 | " ('c7a22cded9f64d7d88c25be8ae340297', 'Analyst Insights London 2018')]" 116 | ] 117 | }, 118 | "execution_count": 4, 119 | "metadata": {}, 120 | "output_type": "execute_result" 121 | } 122 | ], 123 | "source": [ 124 | "[ (rg['id'], rg['name']) for rg in client.get_resource_groups()['resources'] ]" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "Select the required resource group - this is required in the provisioning data" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 18, 137 | "metadata": {}, 138 | "outputs": [ 139 | { 140 | "name": "stdout", 141 | "output_type": "stream", 142 | "text": [ 143 | "3b90ff40e6cc43978189146817edc403\n" 144 | ] 145 | } 146 | ], 147 | "source": [ 148 | "resource_group_name = 'default'\n", 149 | "\n", 150 | "resource_group = [ (rg['id'], rg['name']) for rg in client.get_resource_groups()['resources'] if rg['name'] == resource_group_name ][0][0]\n", 151 | "print (resource_group)" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "Define cluster provisioning configuration data" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 6, 164 | "metadata": {}, 165 | "outputs": [], 166 | "source": [ 167 | "# uncomment the variables below to set COS S3\n", 168 | "#\n", 169 | "#servicename = 'myservicename'\n", 170 | "#cos_s3_userkey = 'changeme'\n", 171 | "#cos_s3_endpoint = 'changeme'\n", 172 | "#cos_s3_secretkey = 'changeme'\n", 173 | "\n", 174 | "data = {\n", 175 | " \"name\": \"MyAnalyticEngineInstance\",\n", 176 | " \"resource_plan_id\": \"3175a5cf-61e3-4e79-aa2a-dff9a4e1f0ae\",\n", 177 | " \"resource_group_id\": resource_group,\n", 178 | " \"region_id\": \"us-south\",\n", 179 | " \"parameters\": {\n", 180 | " \"hardware_config\": \"default\",\n", 181 | " \"num_compute_nodes\": \"1\",\n", 182 | " \"software_package\": \"ae-1.1-spark\",\n", 183 | " # uncomment the block below to set COS S3\n", 184 | " #\n", 185 | " #\"advanced_options\": {\n", 186 | " # \"ambari_config\": {\n", 187 | " # \"core-site\": {\n", 188 | " # \"fs.cos.{}.access.key\".format(servicename): cos_s3_userkey,\n", 189 | " # \"fs.cos.{}.endpoint\".format(servicename): cos_s3_endpoint,\n", 190 | " # \"fs.cos.{}.secret.key\".format(servicename): cos_s3_secretkey\n", 191 | " # }\n", 192 | " # }\n", 193 | " #}\n", 194 | " } \n", 195 | "}" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": {}, 201 | "source": [ 202 | "Provision the cluster - this call will return immediately, but the cluster could take 30 minutes or so to spin up" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": 7, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "create_cluster_response = client.create(data)\n", 212 | "\n", 213 | "# uncomment below to see the provisioning REST response\n", 214 | "\n", 215 | "# print(create_cluster_response)" 216 | ] 217 | }, 218 | { 219 | "cell_type": "markdown", 220 | "metadata": {}, 221 | "source": [ 222 | "Get the cluster instance ID from the provisioning response" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "# some backend apis require different types of IDS\n", 232 | "id = create_cluster_response['id']\n", 233 | "instance_id = create_cluster_response['guid']\n", 234 | "\n", 235 | "# print(id)\n", 236 | "# print(instance_id)" 237 | ] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "metadata": {}, 242 | "source": [ 243 | "Check the current status at this moment in time" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": 9, 249 | "metadata": {}, 250 | "outputs": [ 251 | { 252 | "data": { 253 | "text/plain": [ 254 | "{'state': 'Preparing'}" 255 | ] 256 | }, 257 | "execution_count": 9, 258 | "metadata": {}, 259 | "output_type": "execute_result" 260 | } 261 | ], 262 | "source": [ 263 | "client.cluster_status(instance_id) " 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "metadata": {}, 269 | "source": [ 270 | "This call will block until provisioning had finished, either successfully or unsuccessfully" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 10, 276 | "metadata": {}, 277 | "outputs": [ 278 | { 279 | "data": { 280 | "text/plain": [ 281 | "{'state': 'Active'}" 282 | ] 283 | }, 284 | "execution_count": 10, 285 | "metadata": {}, 286 | "output_type": "execute_result" 287 | } 288 | ], 289 | "source": [ 290 | "client.cluster_status(instance_id, wait_until_finished_preparing=True)" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 14, 296 | "metadata": {}, 297 | "outputs": [ 298 | { 299 | "data": { 300 | "text/plain": [ 301 | "" 302 | ] 303 | }, 304 | "execution_count": 14, 305 | "metadata": {}, 306 | "output_type": "execute_result" 307 | } 308 | ], 309 | "source": [ 310 | "client.delete(id)" 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": null, 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [] 319 | } 320 | ], 321 | "metadata": { 322 | "kernelspec": { 323 | "display_name": "Python 2", 324 | "language": "python", 325 | "name": "python2" 326 | }, 327 | "language_info": { 328 | "codemirror_mode": { 329 | "name": "ipython", 330 | "version": 3 331 | }, 332 | "file_extension": ".py", 333 | "mimetype": "text/x-python", 334 | "name": "python", 335 | "nbconvert_exporter": "python", 336 | "pygments_lexer": "ipython3", 337 | "version": "3.6.5" 338 | } 339 | }, 340 | "nbformat": 4, 341 | "nbformat_minor": 2 342 | } 343 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------