hplefthandclient-1.0.1/0000775000175000017500000000000012263071672015271 5ustar stackstack00000000000000hplefthandclient-1.0.1/hplefthandclient.egg-info/0000775000175000017500000000000012263071672022277 5ustar stackstack00000000000000hplefthandclient-1.0.1/hplefthandclient.egg-info/top_level.txt0000664000175000017500000000002112263071672025022 0ustar stackstack00000000000000hplefthandclient hplefthandclient-1.0.1/hplefthandclient.egg-info/SOURCES.txt0000664000175000017500000000155512263071672024171 0ustar stackstack00000000000000LICENSE.txt README.rst setup.py docs/Makefile docs/changelog.rst docs/conf.py docs/hplefthandclient.rst docs/index.rst docs/installation.rst docs/make.bat docs/tutorial.rst docs/_static/empty_dir docs/api/index.rst docs/api/hplefthandclient/client.rst docs/api/hplefthandclient/exceptions.rst docs/api/hplefthandclient/http.rst docs/api/hplefthandclient/index.rst hplefthandclient/__init__.py hplefthandclient/client.py hplefthandclient/exceptions.py hplefthandclient/http.py hplefthandclient.egg-info/PKG-INFO hplefthandclient.egg-info/SOURCES.txt hplefthandclient.egg-info/dependency_links.txt hplefthandclient.egg-info/requires.txt hplefthandclient.egg-info/top_level.txt samples/README.rst samples/test_client.py samples/utils.py test/README.rst test/config.ini test/test_HPLeftHandClient_base.py test/test_HPLeftHandClient_volume.py test/test_HPLeftHandMockServer_flask.pyhplefthandclient-1.0.1/hplefthandclient.egg-info/dependency_links.txt0000664000175000017500000000000112263071672026345 0ustar stackstack00000000000000 hplefthandclient-1.0.1/hplefthandclient.egg-info/PKG-INFO0000664000175000017500000000146512263071672023402 0ustar stackstack00000000000000Metadata-Version: 1.1 Name: hplefthandclient Version: 1.0.1 Summary: HP LeftHand/StoreVirtual HTTP REST Client Home-page: http://packages.python.org/hplefthandclient Author: Kurt Martin Author-email: kurt.f.martin@hp.com License: Apache License, Version 2.0 Description: UNKNOWN Keywords: hp,lefthand,storevirtual,rest Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Environment :: Web Environment Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.0 Classifier: Topic :: Internet :: WWW/HTTP Requires: httplib2(>=0.6.0) Provides: hplefthandclient hplefthandclient-1.0.1/hplefthandclient.egg-info/requires.txt0000664000175000017500000000002112263071672024670 0ustar stackstack00000000000000httplib2 >= 0.6.0hplefthandclient-1.0.1/README.rst0000664000175000017500000000241612263053020016746 0ustar stackstack00000000000000HP LeftHand/StoreVirtual REST Client =================== This is a Client library that can talk to the HP LeftHand/StoreVirtual Storage array. The HP LeftHand storage array has a REST web service interface. This client library implements a simple interface to talk with that REST interface using the python httplib2 http library. Requirements ============ This branch requires 11.5 version of the LeftHand OS firmware. Capabilities ============ * Get Volume(s) * Get Volume by Name * Create Volume * Delete Volume * Modify Volume * Clone Volume * Get Snapshot(s) * Delete Shapshot * Get Shapshot by Name * Create Snapshot * Delete Snapshot * Clone Snapshot * Get Cluster(s) * Get Cluster by Name * Get Server(s) * Get Server by Name * Create Server * Delete Server * Add Server Access * Remove Server Access Installation ============ :: $ python setup.py install Unit Tests ========== :: $ pip install nose $ pip install nose-testconfig $ cd test $ nosetests --tc-file config.ini Folders ======= * docs -- contains the documentation. * hplefthandlient -- the actual client.py library * test -- unit tests * samples -- some sample uses Documentation ============= To view the built documentation point your browser to :: python-hplefthand/docs/_build/html/index.html hplefthandclient-1.0.1/test/0000775000175000017500000000000012263071672016250 5ustar stackstack00000000000000hplefthandclient-1.0.1/test/config.ini0000664000175000017500000000026712263053020020206 0ustar stackstack00000000000000[TEST] flask_url=http://localhost:5001/lhos user=administrator pass=hpinvent unit=false debug=false start_flask_server=true cluster=ClusterVSA309 lhos_url=http://10.10.22.7:8080/lhos hplefthandclient-1.0.1/test/README.rst0000664000175000017500000000024512263053020017723 0ustar stackstack00000000000000Unit tests ========== 1. pip install nose 2. pip install nose-testconfig 3. use config.ini to configure unit tests 3. run tests with nosetests --tc-file config.ini hplefthandclient-1.0.1/test/test_HPLeftHandClient_volume.py0000664000175000017500000002147612263053020024321 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2009-2012 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test class of LeftHand Client handling volumes & snapshots """ import sys import os sys.path.insert(0, os.path.realpath(os.path.abspath('../'))) from hplefthandclient import exceptions import test_HPLeftHandClient_base VOLUME_NAME1 = 'VOLUME1_UNIT_TEST' VOLUME_NAME2 = 'VOLUME2_UNIT_TEST' VOLUME_NAME3 = 'VOLUME3_UNIT_TEST' SNAP_NAME1 = 'SNAP_UNIT_TEST' class HPLeftHandClientVolumeTestCase(test_HPLeftHandClient_base. HPLeftHandClientBaseTestCase): cluster_id = 0 GB_TO_BYTES = 1073741824 def setUp(self): super(HPLeftHandClientVolumeTestCase, self).setUp() try: cluster_info = self.cl.getClusterByName( test_HPLeftHandClient_base. HPLeftHandClientBaseTestCase.cluster) self.cluster_id = cluster_info['id'] except Exception: pass def tearDown(self): try: volume_info = self.cl.getVolumeByName(VOLUME_NAME1) self.cl.deleteVolume(volume_info['id']) except Exception as ex: print ex pass try: volume_info = self.cl.getVolumeByName(VOLUME_NAME2) self.cl.deleteVolume(volume_info['id']) except Exception as ex: print ex pass super(HPLeftHandClientVolumeTestCase, self).tearDown() def test_1_create_volume(self): self.printHeader('create_volume') try: #add one optional = {'description': 'test volume', 'isThinProvisioned': True} self.cl.createVolume(VOLUME_NAME1, self.cluster_id, 1 * self.GB_TO_BYTES, optional) except Exception as ex: print ex self.fail('Failed to create volume') return try: #check vol1 = self.cl.getVolumeByName(VOLUME_NAME1) self.assertIsNotNone(vol1) volName = vol1['name'] self.assertEqual(VOLUME_NAME1, volName) except Exception as ex: print ex self.fail('Failed to get volume') return try: #add another optional = {'description': 'test volume2', 'isThinProvisioned': True} self.cl.createVolume(VOLUME_NAME2, self.cluster_id, 1 * self.GB_TO_BYTES, optional) except Exception as ex: print ex self.fail('Failed to create volume') return try: #check vol2 = self.cl.getVolumeByName(VOLUME_NAME2) self.assertIsNotNone(vol2) volName = vol2['name'] self.assertEqual(VOLUME_NAME2, volName) except Exception as ex: print ex self.fail("Failed to get volume") self.printFooter('create_volume') def test_1_create_volume_duplicate_name(self): self.printHeader('create_volume_duplicate_name') #add one and check try: optional = {'description': 'test volume', 'isThinProvisioned': True} self.cl.createVolume(VOLUME_NAME1, self.cluster_id, 2 * self.GB_TO_BYTES, optional) except Exception as ex: print ex self.fail("Failed to create volume") self.assertRaises(exceptions.HTTPServerError, self.cl.createVolume, VOLUME_NAME1, self.cluster_id, 2 * self.GB_TO_BYTES, optional) self.printFooter('create_volume_duplicate_name') def test_1_create_volume_tooLarge(self): self.printHeader('create_volume_tooLarge') optional = {'description': 'test volume', 'isThinProvisioned': False} self.assertRaises(exceptions.HTTPServerError, self.cl.createVolume, VOLUME_NAME1, self.cluster_id, 16777218 * self.GB_TO_BYTES, optional) self.printFooter('create_volume_tooLarge') def test_2_get_volume_bad(self): self.printHeader('get_volume_bad') self.assertRaises(exceptions.HTTPNotFound, self.cl.getVolumeByName, 'NoSuchVolume') self.printFooter('get_volume_bad') def test_2_get_volumes(self): self.printHeader('get_volumes') self.cl.createVolume(VOLUME_NAME1, self.cluster_id, 3 * self.GB_TO_BYTES) self.cl.createVolume(VOLUME_NAME2, self.cluster_id, 3 * self.GB_TO_BYTES) vol1 = self.cl.getVolumeByName(VOLUME_NAME1) vol2 = self.cl.getVolumeByName(VOLUME_NAME2) vols = self.cl.getVolumes() self.assertTrue(self.findInDict(vols['members'], 'name', vol1['name'])) self.assertTrue(self.findInDict(vols['members'], 'name', vol2['name'])) self.printFooter('get_volumes') def test_3_delete_volume_nonExist(self): self.printHeader('delete_volume_nonExist') volume_id = -1 self.assertRaises(exceptions.HTTPServerError, self.cl.deleteVolume, volume_id) self.printFooter('delete_volume_nonExist') def test_3_delete_volumes(self): self.printHeader('delete_volumes') try: optional = {'description': 'Made by flask.'} self.cl.createVolume(VOLUME_NAME1, self.cluster_id, 1 * self.GB_TO_BYTES, optional) vol1 = self.cl.getVolumeByName(VOLUME_NAME1) self.printHeader('vol1 id %s' % vol1['id']) self.printHeader('members %s' % vol1) except Exception as ex: print ex self.fail('Failed to create volume %s' % VOLUME_NAME1) try: optional = {'description': 'Made by flask.'} self.cl.createVolume(VOLUME_NAME2, self.cluster_id, 1 * self.GB_TO_BYTES, optional) vol2 = self.cl.getVolumeByName(VOLUME_NAME2) self.printHeader('vol2 id %s' % vol2['id']) except Exception as ex: print ex self.fail('Failed to create volume %s' % VOLUME_NAME2) try: self.cl.deleteVolume(vol1['id']) except Exception as ex: print ex self.fail('Failed to delete %s' % vol1['id']) self.assertRaises(exceptions.HTTPNotFound, self.cl.getVolumeByName, VOLUME_NAME1) try: self.cl.deleteVolume(vol2['id']) except Exception as ex: print ex self.fail('Failed to delete %s' % vol2['id']) self.assertRaises(exceptions.HTTPNotFound, self.cl.getVolumeByName, VOLUME_NAME2) self.printFooter('delete_volumes') def test_4_create_snapshot(self): self.printHeader('create_snapshot') try: self.cl.createVolume(VOLUME_NAME1, self.cluster_id, 1 * self.GB_TO_BYTES) volume_info = self.cl.getVolumeByName(VOLUME_NAME1) option = {'inheritAccess': True} self.cl.createSnapshot(SNAP_NAME1, volume_info['id'], option) except Exception as ex: print ex self.fail("Failed with unexpected exception") snap_info = self.cl.getSnapshotByName(SNAP_NAME1) self.cl.deleteSnapshot(snap_info['id']) self.printFooter('create_snapshot') def test_4_create_snapshot_nonExistVolume(self): self.printHeader('create_snapshot_nonExistVolume') optional = {'description': 'test snapshot'} self.assertRaises(exceptions.HTTPServerError, self.cl.createSnapshot, 'UnitTestSnapshot', -1, optional) self.printFooter('create_snapshot_nonExistVolume') #testing #suite = unittest.TestLoader().loadTestsFromTestCase(HPLeftHandClientVolumeTestCase) #unittest.TextTestRunner(verbosity=2).run(suite) hplefthandclient-1.0.1/test/test_HPLeftHandMockServer_flask.py0000775000175000017500000003165012263053020024752 0ustar stackstack00000000000000import pprint import json import random import string import argparse from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException parser = argparse.ArgumentParser() parser.add_argument("-debug", help="Turn on http debugging", default=False, action="store_true") parser.add_argument("-user", help="User name", default='administrator') parser.add_argument("-password", help="User password", default='hpinvent') parser.add_argument("-port", help="Port to listen on", type=int, default=5001) args = parser.parse_args() user_name = args.user user_pass = args.password debugRequests = False if "debug" in args and args.debug is True: debugRequests = True #__all__ = ['make_json_app'] def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) def make_json_app(import_name, **kwargs): """ Creates a JSON-oriented Flask app. All error responses that you don't specifically manage yourself will have application/json content type, and will contain JSON like this (just an example): { "message": "405: Method Not Allowed" } """ def make_json_error(ex): pprint.pprint(ex) pprint.pprint(ex.code) #response = jsonify(message=str(ex)) response = jsonify(ex) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response app = Flask(import_name, **kwargs) #app.debug = True app.secret_key = id_generator(24) for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error return app app = make_json_app(__name__) session_key = id_generator(24) def debugRequest(request): if debugRequests: print "\n" pprint.pprint(request) pprint.pprint(request.headers) pprint.pprint(request.data) def throw_error(http_code, error_code=None, desc=None, debug1=None, debug2=None): if error_code: info = {'code': error_code, 'desc': desc} if debug1: info['debug1'] = debug1 if debug2: info['debug2'] = debug2 abort(Response(json.dumps(info), status=http_code)) else: abort(http_code) @app.route('/') def index(): debugRequest(request) if 'username' in session: return 'Logged in as %s' % escape(session['username']) abort(401) @app.route('/lhos/throwerror') def errtest(): debugRequest(request) throw_error(405, 'ERR_TEST', 'testing throwing an error', 'debug1 message', 'debug2 message') @app.errorhandler(404) def not_found(error): debugRequest(request) return Response("%s has not been implemented" % request.path, status=501) @app.route('/lhos/credentials', methods=['GET', 'POST']) def credentials(): debugRequest(request) if request.method == 'GET': return 'GET credentials called' elif request.method == 'POST': data = json.loads(request.data) if data['user'] == user_name and data['password'] == user_pass: #do something good here try: resp = make_response(json.dumps({'key': session_key}), 201) resp.headers['Location'] = '/lhos/credentials/%s' % session_key session['username'] = data['user'] session['password'] = data['password'] session['session_key'] = session_key return resp except Exception as ex: pprint.pprint(ex) else: #authentication failed! throw_error(401, "HTTP_AUTH_FAIL", "Username and or Password was incorrect") @app.route('/lhos/credentials/', methods=['DELETE']) def logout_credentials(session_key): debugRequest(request) session.clear() return 'DELETE credentials called' #### CLUSTER INFO #### @app.route('/lhos/clusters', methods=['GET']) def get_cluster_by_name(): debugRequest(request) cluster_name = request.args.get('name') for cluster in clusters['members']: if cluster['name'] == cluster_name: resp = make_response(json.dumps(cluster), 200) return resp throw_error(404, 'NON_EXISTENT_CLUSTER', "cluster doesn't exist") ### VOLUMES & SNAPSHOTS #### @app.route('/lhos/volumes', methods=['GET']) def get_volume(): debugRequest(request) volume_name = None volume_name = request.args.get('name') if volume_name is not None: for volume in volumes['members']: if volume['name'] == volume_name: resp = make_response(json.dumps(volume), 200) return resp throw_error(404, 'NON_EXISTENT_VOLUME', "volume doesn't exist") else: resp = make_response(json.dumps(volumes), 200) return resp @app.route('/lhos/snapshots', methods=['GET']) def get_snapshot(): debugRequest(request) snapshot_name = None snapshot_name = request.args.get('name') if snapshot_name is not None: pprint.pprint('snapshot name %s' % snapshot_name) for snapshot in snapshots['members']: if snapshot['name'] == snapshot_name: pprint.pprint('snapshot namei inside %s' % snapshot['name']) resp = make_response(json.dumps(snapshot), 200) return resp throw_error(404, 'NON_EXISTENT_SNAPSHOT', "snapshot doesn't exist") else: resp = make_response(json.dumps(snapshots), 200) return resp @app.route('/lhos/volumes/', methods=['POST']) def create_snapshot(volume_id): debugRequest(request) data = json.loads(request.data) valid_keys = {'action': None, 'parameters': None} ## do some fake errors here depending on data for key in data.keys(): if key not in valid_keys.keys(): throw_error(400, 'INV_INPUT', "Invalid Parameter '%s'" % key) for volume in volumes['members']: if volume['id'] == int(volume_id): snapshots['members'].append({'name': data['parameters'].get('name'), 'id': random.randint(1, 2000)}) pprint.pprint(snapshots) return make_response("", 200) throw_error(500, 'SERVER_ERROR', "volume doesn't exist") @app.route('/lhos/volumes', methods=['POST']) def create_volumes(): debugRequest(request) data = json.loads(request.data) valid_keys = {'name': None, 'isThinProvisioned': None, 'size': None, 'description': None, 'clusterID': None} for key in data.keys(): if key not in valid_keys.keys(): throw_error(500, 'SERVER_ERROR', "Invalid Parameter '%s'" % key) if 'name' in data.keys(): for vol in volumes['members']: if vol['name'] == data['name']: throw_error(500, 'SERVER_ERROR', 'The volume already exists.') else: throw_error(500, 'SERVER_ERROR', 'No volume name provided.') if 'size' in data.keys(): if data['size'] > 17592188141567: throw_error(500, 'SERVER_ERROR', 'Volume to larger') data['id'] = random.randint(1, 2000) volumes['members'].append(data) return make_response("", 200) @app.route('/lhos/volumes/', methods=['DELETE']) def delete_volumes(volume_id): debugRequest(request) for volume in volumes['members']: if volume['id'] == int(volume_id): volumes['members'].remove(volume) return make_response("", 200) throw_error(500, 'SERVER_ERROR', "The volume id '%s' does not exists." % volume_id) @app.route('/lhos/snapshots/', methods=['DELETE']) def delete_snapshots(snapshot_id): debugRequest(request) for snapshot in snapshots['members']: if snapshot['id'] == int(snapshot_id): snapshots['members'].remove(snapshot) return make_response("", 200) throw_error(404, 'NON_EXISTENT_SNAPSHOT', "The snapshot id '%s' does not exists." % snapshot_id) if __name__ == "__main__": #fake volumes global volumes volumes = {'members': [{ 'autogrowSeconds': 2, 'bytesWritten': 0, 'clusterId': 21, 'clusterName': 'ClusterVSA309', 'created': '2013-10-23T16:58:58Z', 'dataProtectionLevel': 0, 'dataWritten': 0, 'description': 'test volume', 'fcTransportStatus': 0, 'fibreChannelPaths': None, 'friendlyName': '', 'hasUnrecoverableIOErrors': False, 'id': 24, 'isAdaptiveOptimizationEnabled': True, 'isAvailable': True, 'isDeleting': False, 'isLicensed': True, 'isMigrating': False, 'isPrimary': True, 'isThinProvisioned': False, 'isVIPRebalancing': False, 'iscsiIqn': 'iqn.2003-10.com.lefthandnetworks:mgvsa309:24:vol1', 'iscsiSessions': None, 'migrationStatus': 'none', 'modified': '', 'name': 'VOLUME0_UNIT_TEST', 'numberOfReplicas': 1, 'provisionedSpace': 4194304, 'replicationStatus': 'normal', 'restripePendingStatus': 'none', 'resynchronizationStatus': 'none', 'scsiLUNStatus': 'available', 'serialNumber': '27d18c785f81e91f36a5073fff9233720000000000000018', 'size': 1048576, 'snapshots': {'name': 'snapshots', 'resource': None, 'type': 'snapshot', 'uri': '/snapshots?volumeName=VOLUME1_UNIT_TEST'}, 'transport': 0, 'transportServerId': 0, 'type': 'volume', 'uri': '/lhos/volumes/24', 'volumeACL': None}], 'total': 4} #fake snapshots global snapshots snapshots = {'members': [{ 'autogrowSeconds': 2, 'bytesWritten': 0, 'clusterId': 21, 'clusterName': 'ClusterVSA309', 'created': '2013-10-23T16:59:19Z', 'dataWritten': 0, 'description': '', 'fcTransportStatus': 0, 'fibreChannelPaths': None, 'hasUnrecoverableIOErrors': False, 'id': 26, 'isAutomatic': False, 'isAvailable': True, 'isDeleting': False, 'isLicensed': True, 'isMigrating': False, 'isPrimary': True, 'isThinProvisioned': True, 'iscsiIqn': 'iqn.2003-10.com.lefthandnetworks:mgvsa309:26:vol1-ss-1', 'managedBy': 0, 'migrationStatus': 'none', 'modified': '', 'name': 'vol1_SS_1', 'provisionedSpace': 528384, 'replicationStatus': 'normal', 'restripePendingStatus': 'none', 'resynchronizationStatus': 'none', 'scsiLUNStatus': 'available', 'serialNumber': '27d18c785f81e91f36a5073fff923372000000000000001a', 'sessions': None, 'size': 4194304, 'snapshotACL': None, 'transport': 0, 'transportServerId': 0, 'type': 'snapshot', 'uri': '/lhos/snapshots/26', 'writableSpaceUsed': 0}], 'total': 4} #fake clusters global clusters clusters = {'members': [{'adaptiveOptimizationCapable': False, 'created': 'N/A', 'description': '', 'id': 21, 'modified': 'N/A', 'moduleCount': 1, 'name': 'ClusterVSA309', 'spaceAvailable': 13457408, 'spaceTotal': 40728576, 'storageModuleIPAddresses': ['10.10.30.165'], 'supportedFeatures': [''], 'type': 'cluster', 'uri': '/lhos/clusters/21', 'virtualIPAddresses': [{'ipV4Address': '10.10.22.7', 'ipV4NetMask': '255.255.224.0'}], 'virtualIPEnabled': True, 'volumeCreationSpace': [{'availableSpace': 13457408, 'replicationLevel': 1}], 'volumes': {'name': 'volumes', 'resource': None, 'type': 'volume', 'uri': '/volumes?clusterName=ClusterVSA309'}}], 'name': 'Clusters Collection', 'total': 1, 'type': 'cluster', 'uri': '/lhos/clusters'} app.run(port=args.port, debug=debugRequests) hplefthandclient-1.0.1/test/test_HPLeftHandClient_base.py0000664000175000017500000000677312263053020023727 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2009-2012 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test base class of LeftHand Client""" import sys import os sys.path.insert(0, os.path.realpath(os.path.abspath('../'))) from hplefthandclient import client import unittest import subprocess import time import inspect from testconfig import config from urlparse import urlparse # pip install nose-testconfig # e.g. # nosetests test_HPLeftHandClient_volume.py -v --tc-file config.ini class HPLeftHandClientBaseTestCase(unittest.TestCase): user = config['TEST']['user'] password = config['TEST']['pass'] cluster = config['TEST']['cluster'] flask_url = config['TEST']['flask_url'] url_lhos = config['TEST']['lhos_url'] debug = config['TEST']['debug'].lower() == 'true' unitTest = config['TEST']['unit'].lower() == 'true' startFlask = config['TEST']['start_flask_server'].lower() == 'true' def setUp(self): cwd = os.path.dirname(os.path.abspath( inspect.getfile(inspect.currentframe()))) if self.unitTest: self.printHeader('Using flask ' + self.flask_url) self.cl = client.HPLeftHandClient(self.flask_url) parsed_url = urlparse(self.flask_url) userArg = '-user=%s' % self.user passwordArg = '-password=%s' % self.password portArg = '-port=%s' % parsed_url.port script = 'test_HPLeftHandMockServer_flask.py' path = "%s/%s" % (cwd, script) try: if self.startFlask: self.mockServer = subprocess.Popen([sys.executable, path, userArg, passwordArg, portArg], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) else: pass except Exception: pass time.sleep(1) else: self.printHeader('Using LeftHand ' + self.url_lhos) self.cl = client.HPLeftHandClient(self.url_lhos) if self.debug: self.cl.debug_rest(True) self.cl.login(self.user, self.password) def tearDown(self): self.cl.logout() if self.unitTest and self.startFlask: #TODO: it seems to kill all the process except the last one... #don't know why self.mockServer.kill() def printHeader(self, name): print "\n##Start testing '%s'" % name def printFooter(self, name): print "##Compeleted testing '%s\n" % name def findInDict(self, dic, key, value): for i in dic: if key in i and i[key] == value: return True hplefthandclient-1.0.1/setup.py0000664000175000017500000000220012263054236016772 0ustar stackstack00000000000000import hplefthandclient try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages import sys setup( name='hplefthandclient', version=hplefthandclient.version, description="HP LeftHand/StoreVirtual HTTP REST Client", author="Kurt Martin", author_email="kurt.f.martin@hp.com", maintainer="Kurt Martin", keywords=["hp", "lefthand", "storevirtual", "rest"], requires=['httplib2(>=0.6.0)'], install_requires=['httplib2 >= 0.6.0'], tests_require=["nose", "werkzeug", "nose-testconfig"], license="Apache License, Version 2.0", packages=find_packages(), provides=['hplefthandclient'], url="http://packages.python.org/hplefthandclient", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Topic :: Internet :: WWW/HTTP', ] ) hplefthandclient-1.0.1/LICENSE.txt0000664000175000017500000002613612263053020017107 0ustar stackstack00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. hplefthandclient-1.0.1/hplefthandclient/0000775000175000017500000000000012263071672020605 5ustar stackstack00000000000000hplefthandclient-1.0.1/hplefthandclient/__init__.py0000664000175000017500000000222212263054604022710 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 Hewlett Packard Development Company, L.P. # 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. """ HP LeftHand REST Client :Author: Kurt Martin :Author: Walter A. Boring IV :Copyright: Copyright 2013, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (1, 0, 1) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HPLeftHandClient.""" hplefthandclient-1.0.1/hplefthandclient/client.py0000664000175000017500000003440112263053020022422 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Hewlett Packard Development Company, L.P. # 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. """ HPLeftHand REST Client .. module: HPLeftHandClient .. moduleauthor: Kurt Martin :Author: Kurt Martin :Description: This is the LeftHand/StoreVirtual Client that talks to the LeftHand OS REST Service. This client requires and works with version 11.5 of the LeftHand firmware """ from hplefthandclient import http class HPLeftHandClient: def __init__(self, api_url): self.api_url = api_url self.http = http.HTTPJSONRESTClient(self.api_url) def debug_rest(self, flag): """ This is useful for debugging requests to LeftHand :param flag: set to True to enable debugging :type flag: bool """ self.http.set_debug_flag(flag) def login(self, username, password): """ This authenticates against the LH OS REST server and creates a session. :param username: The username :type username: str :param password: The password :type password: str :returns: None """ self.http.authenticate(username, password) def logout(self): """ This destroys the session and logs out from the LH OS server :returns: None """ self.http.unauthenticate() def getClusters(self): """ Get the list of Clusters :returns: list of Clusters """ response, body = self.http.get('/clusters') return body def getCluster(self, cluster_id): """ Get information about a Cluster :param cluster_id: The id of the cluster to find :type cluster_id: str :returns: cluster """ response, body = self.http.get('/clusters/%s' % cluster_id) return body def getClusterByName(self, name): """ Get information about a cluster by name :param name: The name of the cluster to find :type name: str :returns: cluster :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_CLUSTER - cluster doesn't exist """ response, body = self.http.get('/clusters?name=%s' % name) return body def getServers(self): """ Get the list of Servers :returns: list of Servers """ response, body = self.http.get('/servers') return body def getServer(self, server_id): """ Get information about a server :param server_id: The id of the server to find :type server_id: str :returns: server :raises: :class:`~hplefthandclient.exceptions.HTTPServerError` """ response, body = self.http.get('/servers/%s' % server_id) return body def getServerByName(self, name): """ Get information about a server by name :param name: The name of the server to find :type name: str :returns: server :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_SERVER - server doesn't exist """ response, body = self.http.get('/servers?name=%s' % name) return body def createServer(self, name, iqn, optional=None): """ Create a server by name :param name: The name of the server to create :type name: str :param iqn: The iSCSI qualified name :type name: str :param optional: Dictionary of optional params :type optional: dict .. code-block:: python optional = { 'description' : "some comment", 'iscsiEnabled' : True, 'chapName': "some chap name", 'chapAuthenticationRequired': False, 'chapInitiatorSecret': "initiator secret", 'chapTargetSecret': "target secret", 'iscsiLoadBalancingEnabled': True, 'controllingServerName': "server name", 'fibreChannelEnabled': False, 'inServerCluster": True } :returns: server :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_SERVER - server doesn't exist """ info = {'name': name, 'iscsiIQN': iqn} if optional: info = self._mergeDict(info, optional) response, body = self.http.post('/servers', body=info) return body def deleteServer(self, server_id): """ Delete a Server :param server_id: the server ID to delete :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_SERVER - The server does not exist """ response, body = self.http.delete('/servers/%s' % server_id) return body def getSnapshots(self): """ Get the list of Snapshots :returns: list of Snapshots """ response, body = self.http.get('/snapshots') return body def getSnapshot(self, snapshot_id): """ Get information about a Snapshot :returns: snapshot :raises: :class:`~hplefthandclient.exceptions.HTTPServerError` """ response, body = self.http.get('/snapshots/%s' % snapshot_id) return body def getSnapshotByName(self, name): """ Get information about a snapshot by name :param name: The name of the snapshot to find :returns: volume :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_SNAP - shapshot doesn't exist """ response, body = self.http.get('/snapshots?name=%s' % name) return body def createSnapshot(self, name, source_volume_id, optional=None): """ Create a snapshot of an existing Volume :param name: Name of the Snapshot :type name: str :param source_volume_id: The volume you want to snapshot :type source_volume_id: int :param optional: Dictionary of optional params :type optional: dict .. code-block:: python optional = { 'description' : "some comment", 'inheritAccess' : false } """ parameters = {'name': name} if optional: parameters = self._mergeDict(parameters, optional) info = {'action': 'createSnapshot', 'parameters': parameters} response, body = self.http.post('/volumes/%s' % source_volume_id, body=info) return body def deleteSnapshot(self, snapshot_id): """ Delete a Snapshot :param snapshot_id: the snapshot ID to delete :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_SNAPSHOT - The snapshot does not exist """ response, body = self.http.delete('/snapshots/%s' % snapshot_id) return body def cloneSnapshot(self, name, source_snapshot_id, optional=None): """ Create a clone of an existing Shapshot :param name: Name of the Snapshot clone :type name: str :param source_snapshot_id: The snapshot you want to clone :type source_snapshot_id: int :param optional: Dictionary of optional params :type optional: dict .. code-block:: python optional = { 'description' : "some comment" } """ parameters = {'name': name} if optional: parameters = self._mergeDict(parameters, optional) info = {'action': 'createSmartClone', 'parameters': parameters} response, body = self.http.post('/snapshots/%s' % source_snapshot_id, body=info) return body def getVolumes(self): """ Get the list of Volumes :returns: list of Volumes """ response, body = self.http.get('/volumes') return body def getVolume(self, volume_id): """ Get information about a volume :param volume_id: The id of the volume to find :type volume_id: str :returns: volume :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_VOL - volume doesn't exist """ response, body = self.http.get('/volumes/%s' % volume_id) return body def getVolumeByName(self, name): """ Get information about a volume by name :param name: The name of the volume to find :type volume_id: str :returns: volume :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_VOL - volume doesn't exist """ response, body = self.http.get('/volumes?name=%s' % name) return body def createVolume(self, name, cluster_id, size, optional=None): """ Create a new volume :param name: the name of the volume :type name: str :param cluster_id: the cluster Id :type cluster_id: int :param sizeKB: size in KB for the volume :type sizeKB: int :param optional: dict of other optional items :type optional: dict .. code-block:: python optional = { 'description': 'some comment', 'isThinProvisioned': 'true', 'autogrowSeconds': 200, 'clusterName': 'somename', 'isAdaptiveOptimizationEnabled': 'true', 'dataProtectionLevel': 2, } :returns: List of Volumes :raises: :class:`~hplefthandclient.exceptions.HTTPConflict` - EXISTENT_SV - Volume Exists already """ info = {'name': name, 'clusterID': cluster_id, 'size': size} if optional: info = self._mergeDict(info, optional) response, body = self.http.post('/volumes', body=info) return body def deleteVolume(self, volume_id): """ Delete a volume :param name: the name of the volume :type name: str :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_VOL - The volume does not exist """ response, body = self.http.delete('/volumes/%s' % volume_id) return body def modifyVolume(self, volume_id, optional): """Modify an existing volume. :param volume_id: The id of the volume to find :type volume_id: str :returns: volume :raises: :class:`~hplefthandclient.exceptions.HTTPNotFound` - NON_EXISTENT_VOL - volume doesn't exist """ info = {'volume_id': volume_id} info = self._mergeDict(info, optional) response, body = self.http.put('/volumes/%s' % volume_id, body=info) return body def cloneVolume(self, name, source_volume_id, optional=None): """ Create a clone of an existing Volume :param name: Name of the Volume clone :type name: str :param source_volume_id: The Volume you want to clone :type source_volume_id: int :param optional: Dictionary of optional params :type optional: dict .. code-block:: python optional = { 'description' : "some comment" } """ parameters = {'name': name} if optional: parameters = self._mergeDict(parameters, optional) info = {'action': 'createSmartClone', 'parameters': parameters} response, body = self.http.post('/volumes/%s' % source_volume_id, body=info) return body def addServerAccess(self, volume_id, server_id, optional=None): """ Assign a Volume to a Server :param volume_id: Volume ID of the volume :type name: int :param server_id: Server ID of the server to add the volume to :type source_volume_id: int :param optional: Dictionary of optional params :type optional: dict .. code-block:: python optional = { 'Transport' : 0, 'Lun' : 1, } """ parameters = {'serverID': server_id, 'exclusiveAccess': True, 'readAccess': True, 'writeAccess': True} if optional: parameters = self._mergeDict(parameters, optional) info = {'action': 'addServerAccess', 'parameters': parameters} response, body = self.http.post('/volumes/%s' % volume_id, body=info) return body def removeServerAccess(self, volume_id, server_id): """ Unassign a Volume from a Server :param volume_id: Volume ID of the volume :type name: int :param server_id: Server ID of the server to remove the volume fom :type source_volume_id: int """ parameters = {'serverID': server_id} info = {'action': 'removeServerAccess', 'parameters': parameters} response, body = self.http.post('/volumes/%s' % volume_id, body=info) return body def _mergeDict(self, dict1, dict2): """ Safely merge 2 dictionaries together :param dict1: The first dictionary :type dict1: dict :param dict2: The second dictionary :type dict2: dict :returns: dict :raises Exception: dict1, dict2 is not a dictionary """ if type(dict1) is not dict: raise Exception("dict1 is not a dictionary") if type(dict2) is not dict: raise Exception("dict2 is not a dictionary") dict3 = dict1.copy() dict3.update(dict2) return dict3 hplefthandclient-1.0.1/hplefthandclient/http.py0000664000175000017500000002457112263054407022144 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 Hewlett Packard Development Company, L.P. # 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. """ HPLeftHand HTTP Client :Author: Walter A. Boring IV :Description: This is the HTTP Client that is used to make the actual calls. It includes the authentication that knows the cookie name for LH. """ import logging import httplib2 import time import pprint try: import json except ImportError: import simplejson as json from hplefthandclient import exceptions class HTTPJSONRESTClient(httplib2.Http): """ An HTTP REST Client that sends and recieves JSON data as the body of the HTTP request. :param api_url: The url to the LH OS REST service ie. https://:/lhos :type api_url: str :param insecure: Use https? requires a local certificate :type insecure: bool """ USER_AGENT = 'python-hplefthandclient' SESSION_COOKIE_NAME = 'Authorization' #API_VERSION = 'X-API-Version' #CHRP_VERSION = 'X_HP-CHRP-Client-Version' def __init__(self, api_url, insecure=False, http_log_debug=False): super(HTTPJSONRESTClient, self).__init__(disable_ssl_certificate_validation=True) self.session_key = None #should be http:///lhos self.set_url(api_url) self.set_debug_flag(http_log_debug) self.times = [] # [("item", starttime, endtime), ...] # httplib2 overrides self.force_exception_to_status_code = True #self.disable_ssl_certificate_validation = insecure self._logger = logging.getLogger(__name__) def set_url(self, api_url): #should be http:///lhos self.api_url = api_url.rstrip('/') def set_debug_flag(self, flag): """ This turns on/off http request/response debugging output to console :param flag: Set to True to enable debugging output :type flag: bool """ self.http_log_debug = flag if self.http_log_debug: ch = logging.StreamHandler() self._logger.setLevel(logging.DEBUG) self._logger.addHandler(ch) def authenticate(self, user, password, optional=None): """ This tries to create an authenticated session with the LH OS server :param user: The username :type user: str :param password: The password :type password: str """ #this prevens re-auth attempt if auth fails self.auth_try = 1 self.session_key = None info = {'user': user, 'password': password} self._auth_optional = None if optional: self._auth_optional = optional info.update(optional) resp, body = self.post('/credentials', body=info) if body and 'authToken' in body: self.session_key = body['authToken'] self.auth_try = 0 self.user = user self.password = password def _reauth(self): self.authenticate(self.user, self.password, self._auth_optional) def unauthenticate(self): """ This clears the authenticated session with the LH server. It logs out. """ #delete the session on the LH self.delete('/credentials/%s' % self.session_key) self.session_key = None def get_timings(self): """ Ths gives an array of the request timings since last reset_timings call """ return self.times def reset_timings(self): """ This resets the request/response timings array """ self.times = [] def _http_log_req(self, args, kwargs): if not self.http_log_debug: return string_parts = ['curl -i'] for element in args: if element in ('GET', 'POST'): string_parts.append(' -X %s' % element) else: string_parts.append(' %s' % element) for element in kwargs['headers']: header = ' -H "%s: %s"' % (element, kwargs['headers'][element]) string_parts.append(header) self._logger.debug("\nREQ: %s\n" % "".join(string_parts)) if 'body' in kwargs: self._logger.debug("REQ BODY: %s\n" % (kwargs['body'])) def _http_log_resp(self, resp, body): if not self.http_log_debug: return self._logger.debug("RESP:%s\n", pprint.pformat(resp)) self._logger.debug("RESP BODY:%s\n", body) def request(self, *args, **kwargs): """ This makes an HTTP Request to the LH server. You should use get, post, delete instead. """ if self.session_key and self.auth_try != 1: kwargs.setdefault('headers', {})[self.SESSION_COOKIE_NAME] = self.session_key kwargs.setdefault('headers', kwargs.get('headers', {})) kwargs['headers']['User-Agent'] = self.USER_AGENT kwargs['headers']['Accept'] = 'application/json' if 'body' in kwargs: kwargs['headers']['Content-Type'] = 'application/json' kwargs['body'] = json.dumps(kwargs['body']) self._http_log_req(args, kwargs) resp, body = super(HTTPJSONRESTClient, self).request(*args, **kwargs) self._http_log_resp(resp, body) # Try and conver the body response to an object # This assumes the body of the reply is JSON if body: try: body = json.loads(body) except ValueError: #pprint.pprint("failed to decode json\n") pass else: body = None if resp.status >= 400: raise exceptions.from_response(resp, body) return resp, body def _time_request(self, url, method, **kwargs): start_time = time.time() resp, body = self.request(url, method, **kwargs) self.times.append(("%s %s" % (method, url), start_time, time.time())) return resp, body def _do_reauth(self, url, method, ex, **kwargs): print("_do_reauth called") try: if self.auth_try != 1: self._reauth() resp, body = self._time_request(self.api_url + url, method, **kwargs) return resp, body else: raise ex except exceptions.HTTPUnauthorized: raise ex def _cs_request(self, url, method, **kwargs): # Perform the request once. If we get a 401 back then it # might be because the auth token expired, so try to # re-authenticate and try again. If it still fails, bail. try: resp, body = self._time_request(self.api_url + url, method, **kwargs) return resp, body except exceptions.HTTPUnauthorized as ex: print("_CS_REQUEST HTTPUnauthorized") resp, body = self._do_reauth(url, method, ex, **kwargs) return resp, body except exceptions.HTTPForbidden as ex: print("_CS_REQUEST HTTPForbidden") resp, body = self._do_reauth(url, method, ex, **kwargs) return resp, body def get(self, url, **kwargs): """ Make an HTTP GET request to the server. .. code-block:: python #example call try { headers, body = http.get('/volumes') } except exceptions.HTTPUnauthorized as ex: print "Not logged in" } :param url: The relative url from the LH api_url :type url: str :returns: headers - dict of HTTP Response headers :returns: body - the body of the response. If the body was JSON, it will be an object """ return self._cs_request(url, 'GET', **kwargs) def post(self, url, **kwargs): """ Make an HTTP POST request to the server. .. code-block:: python #example call try { info = {'name': 'new volume name', 'sizeMiB': 300} headers, body = http.post('/volumes', body=info) } except exceptions.HTTPUnauthorized as ex: print "Not logged in" } :param url: The relative url from the LH api_url :type url: str :returns: headers - dict of HTTP Response headers :returns: body - the body of the response. If the body was JSON, it will be an object """ return self._cs_request(url, 'POST', **kwargs) def put(self, url, **kwargs): """ Make an HTTP PUT request to the server. .. code-block:: python #example call try { info = {'name': 'something'} headers, body = http.put('/volumes', body=info) } except exceptions.HTTPUnauthorized as ex: print "Not logged in" } :param url: The relative url from the LH api_url :type url: str :returns: headers - dict of HTTP Response headers :returns: body - the body of the response. If the body was JSON, it will be an object """ return self._cs_request(url, 'PUT', **kwargs) def delete(self, url, **kwargs): """ Make an HTTP DELETE request to the server. .. code-block:: python #example call try { headers, body = http.delete('/volumes/%s' % name) } except exceptions.HTTPUnauthorized as ex: print "Not logged in" } :param url: The relative url from the LH api_url :type url: str :returns: headers - dict of HTTP Response headers :returns: body - the body of the response. If the body was JSON, it will be an object """ return self._cs_request(url, 'DELETE', **kwargs) hplefthandclient-1.0.1/hplefthandclient/exceptions.py0000664000175000017500000002026412263053020023327 0ustar stackstack00000000000000# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Hewlett Packard Development Company, L.P. # 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. """ Exceptions for the client .. module: Exceptions :Author: Walter A. Boring IV :Description: This contains the HTTP exceptions that can come back from the REST calls """ class UnsupportedVersion(Exception): """ Indicates that the user is trying to use an unsupported version of the API """ pass class CommandError(Exception): pass class AuthorizationFailure(Exception): pass class NoUniqueMatch(Exception): pass class ClientException(Exception): """ The base exception class for all exceptions this library raises. :param error: The error array :type error: array """ _error_code = None _error_desc = None _debug1 = None _debug2 = None def __init__(self, error=None): if error: if 'messageID' in error: self._error_code = error['messageID'] if 'message' in error: self._error_desc = error['message'] if 'debug1' in error: self._debug1 = error['debug1'] if 'debug2' in error: self._debug2 = error['debug2'] def get_code(self): return self._error_code def get_description(self): return self._error_desc def __str__(self): formatted_string = "%s (HTTP %s)" % (self.message, self.http_status) if self._error_code: formatted_string += " %s" % self._error_code if self._error_desc: formatted_string += " - %s" % self._error_desc if self._debug1: formatted_string += " (1: '%s')" % self._debug1 if self._debug2: formatted_string += " (2: '%s')" % self._debug2 return formatted_string ## ## 400 Errors ## class HTTPBadRequest(ClientException): """ HTTP 400 - Bad request: you sent some malformed data. """ http_status = 400 message = "Bad request" class HTTPUnauthorized(ClientException): """ HTTP 401 - Unauthorized: bad credentials. """ http_status = 401 message = "Unauthorized" class HTTPForbidden(ClientException): """ HTTP 403 - Forbidden: your credentials don't give you access to this resource. """ http_status = 403 message = "Forbidden" class HTTPNotFound(ClientException): """ HTTP 404 - Not found """ http_status = 404 message = "Not found" class HTTPMethodNotAllowed(ClientException): """ HTTP 405 - Method not Allowed """ http_status = 405 message = "Method Not Allowed" class HTTPNotAcceptable(ClientException): """ HTTP 406 - Method not Acceptable """ http_status = 406 message = "Method Not Acceptable" class HTTPProxyAuthRequired(ClientException): """ HTTP 407 - The client must first authenticate itself with the proxy. """ http_status = 407 message = "Proxy Authentication Required" class HTTPRequestTimeout(ClientException): """ HTTP 408 - The server timed out waiting for the request. """ http_status = 408 message = "Request Timeout" class HTTPConflict(ClientException): """ HTTP 409 - Conflict: A Conflict happened on the server """ http_status = 409 message = "Conflict" class HTTPGone(ClientException): """ HTTP 410 - Indicates that the resource requested is no longer available and will not be available again. """ http_status = 410 message = "Gone" class HTTPLengthRequired(ClientException): """ HTTP 411 - The request did not specify the length of its content, which is required by the requested resource. """ http_status = 411 message = "Length Required" class HTTPPreconditionFailed(ClientException): """ HTTP 412 - The server does not meet one of the preconditions that the requester put on the request. """ http_status = 412 message = "Over limit" class HTTPRequestEntityTooLarge(ClientException): """ HTTP 413 - The request is larger than the server is willing or able to process """ http_status = 413 message = "Request Entity Too Large" class HTTPRequestURITooLong(ClientException): """ HTTP 414 - The URI provided was too long for the server to process. """ http_status = 414 message = "Request URI Too Large" class HTTPUnsupportedMediaType(ClientException): """ HTTP 415 - The request entity has a media type which the server or resource does not support. """ http_status = 415 message = "Unsupported Media Type" class HTTPRequestedRangeNotSatisfiable(ClientException): """ HTTP 416 - The client has asked for a portion of the file, but the server cannot supply that portion. """ http_status = 416 message = "Requested Range Not Satisfiable" class HTTPExpectationFailed(ClientException): """ HTTP 417 - The server cannot meet the requirements of the Expect request-header field. """ http_status = 417 message = "Expectation Failed" class HTTPTeaPot(ClientException): """ HTTP 418 - I'm a Tea Pot """ http_status = 418 message = "I'm A Teapot. (RFC 2324)" ## ## 500 Errors ## class HTTPServerError(ClientException): """ HTTP 500 - """ http_status = 500 message = "Error" # NotImplemented is a python keyword. class HTTPNotImplemented(ClientException): """ HTTP 501 - Not Implemented: the server does not support this operation. """ http_status = 501 message = "Not Implemented" class HTTPBadGateway(ClientException): """ HTTP 502 - The server was acting as a gateway or proxy and received an invalid response from the upstream server. """ http_status = 502 message = "Bad Gateway" class HTTPServiceUnavailable(ClientException): """ HTTP 503 - The server is currently unavailable """ http_status = 503 message = "Service Unavailable" class HTTPGatewayTimeout(ClientException): """ HTTP 504 - The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. """ http_status = 504 message = "Gateway Timeout" class HTTPVersionNotSupported(ClientException): """ HTTP 505 - The server does not support the HTTP protocol version used in the request. """ http_status = 505 message = "Version Not Supported" # In Python 2.4 Exception is old-style and thus doesn't have a __subclasses__() # so we can do this: # _code_map = dict((c.http_status, c) # for c in ClientException.__subclasses__()) # # Instead, we have to hardcode it: _code_map = dict((c.http_status, c) for c in [HTTPBadRequest, HTTPUnauthorized, HTTPForbidden, HTTPNotFound, HTTPMethodNotAllowed, HTTPNotAcceptable, HTTPProxyAuthRequired, HTTPRequestTimeout, HTTPConflict, HTTPGone, HTTPLengthRequired, HTTPPreconditionFailed, HTTPRequestEntityTooLarge, HTTPRequestURITooLong, HTTPUnsupportedMediaType, HTTPRequestedRangeNotSatisfiable, HTTPExpectationFailed, HTTPTeaPot, HTTPServerError, HTTPNotImplemented, HTTPBadGateway, HTTPServiceUnavailable, HTTPGatewayTimeout, HTTPVersionNotSupported]) def from_response(response, body): """ Return an instance of an ClientException or subclass based on an httplib2 response. Usage:: resp, body = http.request(...) if resp.status != 200: raise exception_from_response(resp, body) """ cls = _code_map.get(response.status, ClientException) return cls(body) hplefthandclient-1.0.1/PKG-INFO0000664000175000017500000000146512263071672016374 0ustar stackstack00000000000000Metadata-Version: 1.1 Name: hplefthandclient Version: 1.0.1 Summary: HP LeftHand/StoreVirtual HTTP REST Client Home-page: http://packages.python.org/hplefthandclient Author: Kurt Martin Author-email: kurt.f.martin@hp.com License: Apache License, Version 2.0 Description: UNKNOWN Keywords: hp,lefthand,storevirtual,rest Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Environment :: Web Environment Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.0 Classifier: Topic :: Internet :: WWW/HTTP Requires: httplib2(>=0.6.0) Provides: hplefthandclient hplefthandclient-1.0.1/docs/0000775000175000017500000000000012263071672016221 5ustar stackstack00000000000000hplefthandclient-1.0.1/docs/conf.py0000664000175000017500000002211412263053020017503 0ustar stackstack00000000000000# -*- coding: utf-8 -*- # # hplefthandclient documentation build configuration file, created by # sphinx-quickstart on Mon Nov 25 13:33:35 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os sys.path.insert(0,os.path.realpath(os.path.abspath('../'))) import hplefthandclient # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'HP LeftHand REST Client' copyright = u'2013 Hewlett Packard Development Company, L.P.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = hplefthandclient.version # The full version, including alpha/beta/rc tags. release = hplefthandclient.version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'HPLeftHandClient' + release.replace('.','_') # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'hplefthandclient.tex', u'hplefthandclient Documentation', u'Author', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'hplefthandclient', u'hplefthandclient Documentation', [u'Author'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'hplefthandclient', u'hplefthandclient Documentation', u'Author', 'hplefthandclient', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'hplefthandclient' epub_author = u'Author' epub_publisher = u'Author' epub_copyright = u'2013, Author' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True hplefthandclient-1.0.1/docs/changelog.rst0000664000175000017500000000017012263053020020663 0ustar stackstack00000000000000Changelog ========= Changes in Version 1.0.0 ------------------------ - First implementation of the REST API Client hplefthandclient-1.0.1/docs/index.rst0000664000175000017500000000316412263053020020051 0ustar stackstack00000000000000HPLeftHandClient |release| Documentation ======================================== Overview -------- **HPLeftHandClient** is a Python package containing a class that uses HTTP REST calls to talk with an HP LeftHand/StoreVirtual drive array. The distribution containing tools for working with `LeftHand/StoreVirtual Storage Arrays `_. This documentation attempts to explain everything you need to know to use **HPLeftHandClient**. :doc:`installation` Instructions on how to get the distribution. :doc:`tutorial` Start here for a quick overview. :doc:`api/index` The complete API documentation, organized by module. Issues ------ .. todo:: create the open source website .. todo:: create the bug tracker All issues should be reported (and can be tracked / voted for / commented on) at the main `github issues `_, in the "LeftHand Python Driver" project. Changes ------- See the :doc:`changelog` for a full list of changes to HPLeftHandClient. About This Documentation ------------------------ This documentation is generated using the `Sphinx `_ documentation generator. The source files for the documentation are located in the *doc/* directory of the **HPLeftHandClient** distribution. To generate the docs locally run the following command from the root directory of the **HPLeftHandClient** .. code-block:: bash $ python setup.py doc .. toctree:: :hidden: installation tutorial changelog api/index Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` hplefthandclient-1.0.1/docs/Makefile0000664000175000017500000001274412263053020017654 0ustar stackstack00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/hplefthandclient.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/hplefthandclient.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/hplefthandclient" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/hplefthandclient" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." hplefthandclient-1.0.1/docs/installation.rst0000664000175000017500000000205612263053020021442 0ustar stackstack00000000000000Installing / Upgrading ====================== .. highlight:: bash **HPLeftHandClient** is in the `Python Package Index `_. Installing with pip ------------------- We prefer `pip `_ to install hplefthandclient on platforms other than Windows:: $ pip install hplefthandclient To upgrade using pip:: $ pip install --upgrade hplefthandclient Installing with easy_install ---------------------------- If you must install hplefthandclient using `setuptools `_ do:: $ easy_install hplefthandclient To upgrade do:: $ easy_install -U hplefthandclient Installing from source ---------------------- If you'd rather install directly from the source (i.e. to stay on the bleeding edge), install the C extension dependencies then check out the latest source from github and install the driver from the resulting tree:: $ git clone git://github.com/WaltHP/python-lefthandlient.git $ cd python-lefthandclient/ $ python setup.py install hplefthandclient-1.0.1/docs/hplefthandclient.rst0000664000175000017500000000120712263053020022252 0ustar stackstack00000000000000hplefthandclient Package ======================== :mod:`hplefthandclient` Package ------------------------------- .. automodule:: hplefthandclient.__init__ :members: :undoc-members: :show-inheritance: :mod:`client` Module -------------------- .. automodule:: hplefthandclient.client :members: :undoc-members: :show-inheritance: :mod:`exceptions` Module ------------------------ .. automodule:: hplefthandclient.exceptions :members: :undoc-members: :show-inheritance: :mod:`http` Module ------------------ .. automodule:: hplefthandclient.http :members: :undoc-members: :show-inheritance: hplefthandclient-1.0.1/docs/tutorial.rst0000664000175000017500000000402212263053020020577 0ustar stackstack00000000000000Tutorial ======== This tutorial is intended as an introduction to working with **HPLeftHandClient**. Prerequisites ------------- Before we start, make sure that you have the **HPLeftHandClient** distribution :doc:`installed `. In the Python shell, the following should run without raising an exception: .. code-block:: bash >>> import hplefthandclient This tutorial also assumes that a LeftHand array is up and running and the LeftHand OS is running. Create the Client and login --------------------------- The first step when working with **HPLeftHandClient** is to create a :class:`~hplefthandclient.client.HPLeftHandClient` to the LeftHand drive array and logging in to create the session. You must :meth:`~hplefthandclient.client.HPLeftHandClient.login` prior to calling the other APIs to do work on the LeftHand. Doing so is easy: .. code-block:: python from hplefthandclient import client, exceptions #this creates the client object and sets the url to the #LeftHand server with IP 10.10.10.10 on port 8008. cl = client.HPLeftHandClient("https://10.10.10.10:8008/api/v1") try: cl.login(username, password) print "Login worked!" except exceptions.HTTPUnauthorized as ex: print "Login failed." When you are done with the the client, it's a good idea to logout from the LeftHand so there isn't a stale session sitting around. .. code-block:: python cl.logout() print "logout worked" Getting a list of Volumes ------------------------- After you have logged in, you can start making calls to the LeftHand APIs. A simple example is getting a list of existing volumes on the array with a call to :meth:`~hplefthandclient.client.HPLeftHandClient.getVolumes`. .. code-block:: python import pprint try: volumes = cl.getVolumes() pprint.pprint(volumes) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: #something unexpected happened print ex .. note:: volumes is an array of volumes in the above call hplefthandclient-1.0.1/docs/_static/0000775000175000017500000000000012263071672017647 5ustar stackstack00000000000000hplefthandclient-1.0.1/docs/_static/empty_dir0000664000175000017500000000000012263053020021537 0ustar stackstack00000000000000hplefthandclient-1.0.1/docs/make.bat0000664000175000017500000001177412263053020017623 0ustar stackstack00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\hplefthandclient.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\hplefthandclient.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end hplefthandclient-1.0.1/docs/api/0000775000175000017500000000000012263071672016772 5ustar stackstack00000000000000hplefthandclient-1.0.1/docs/api/hplefthandclient/0000775000175000017500000000000012263071672022306 5ustar stackstack00000000000000hplefthandclient-1.0.1/docs/api/hplefthandclient/http.rst0000664000175000017500000000137612263053020024011 0ustar stackstack00000000000000:mod:`http` -- HTTP REST Base Class ==================================================== .. automodule:: hplefthandclient.http :synopsis: HTTP REST Base Class .. autoclass::hplefthandclient.http(api_url, [insecure=False[,http_log_debug=False]]) .. automethod:: authenticate .. automethod:: unauthenticate .. describe:: c[db_name] || c.db_name Get the `db_name` :class:`~pymongo.database.Database` on :class:`Connection` `c`. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. .. autoattribute:: api_url .. autoattribute:: http_log_debug .. automethod:: request .. automethod:: get .. automethod:: post .. automethod:: put .. automethod:: delete hplefthandclient-1.0.1/docs/api/hplefthandclient/client.rst0000664000175000017500000000215212263053020024301 0ustar stackstack00000000000000:mod:`client` -- HPLeftHandClient ================================= .. automodule:: hplefthandclient.client :synopsis: HP LeftHand REST Web client .. autoclass:: hplefthandclient.client.HPLeftHandClient(api_url) .. automethod:: debug_rest .. automethod:: login .. automethod:: logout .. automethod:: getClusters .. automethod:: getCluster .. automethod:: getClusterByName .. automethod:: getServers .. automethod:: getServer .. automethod:: getServerByName .. automethod:: createServer .. automethod:: deleteServer .. automethod:: getSnapshots .. automethod:: getSnapshot .. automethod:: getSnapshotByName .. automethod:: createSnapshot .. automethod:: deleteSnapshot .. automethod:: cloneSnapshot .. automethod:: getVolumes .. automethod:: getVolume .. automethod:: getVolumeByName .. automethod:: createVolume .. automethod:: deleteVolume .. automethod:: modifyVolume .. automethod:: cloneVolume .. automethod:: addServerAccess .. automethod:: removeServerAccess hplefthandclient-1.0.1/docs/api/hplefthandclient/index.rst0000664000175000017500000000037112263053020024133 0ustar stackstack00000000000000:mod:`client` -- HPLeftHandClient ================================= .. automodule:: hplefthandclient :synopsis: HP LeftHand REST Web client .. autodata:: version Sub-modules: .. toctree:: :maxdepth: 2 client exceptions http hplefthandclient-1.0.1/docs/api/hplefthandclient/exceptions.rst0000664000175000017500000000043612263053020025207 0ustar stackstack00000000000000:mod:`exceptions` -- HTTP Exceptions ==================================================== .. automodule:: hplefthandclient.exceptions :synopsis: HTTP Exceptions .. autoclass:: hplefthandclient.exceptions.HTTPNotFound .. autoclass:: hplefthandclient.exceptions.HTTPBadRequest hplefthandclient-1.0.1/docs/api/index.rst0000664000175000017500000000035312263053020020617 0ustar stackstack00000000000000API Documentation ================= The HP LeftHand Client package contains a :mod:`hplefthandclient` class which extends a more generic :mod:`http` class for doing REST calls .. toctree:: :maxdepth: 2 hplefthandclient/index hplefthandclient-1.0.1/samples/0000775000175000017500000000000012263071672016735 5ustar stackstack00000000000000hplefthandclient-1.0.1/samples/README.rst0000664000175000017500000000075012263053020020411 0ustar stackstack00000000000000This directory is going away..... The unit tests are in 'test' This directory contains unit tests flask_server.py -- is a sample server that acts like a LeftHand OS API server. This requires python-flask How to run the tests * First run the api server python flask_server.py * Now run the test client. python test_client.py for overriding error content in flask http://flask.pocoo.org/snippets/83/ http://flask.pocoo.org/docs/api/?highlight=abort#flask.Flask.errorhandler hplefthandclient-1.0.1/samples/test_client.py0000664000175000017500000001375012263053020021615 0ustar stackstack00000000000000import argparse from os import sys import os import pprint # this is a hack to get the hp driver module # and it's utils module on the search path. cmd_folder = os.path.realpath(os.path.abspath("..")) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) from hplefthandclient import client, exceptions parser = argparse.ArgumentParser() parser.add_argument("-debug", help="Turn on http debugging", default=False, action="store_true") args = parser.parse_args() cl = client.HPLeftHandClient("http://10.10.22.7:8080/lhos") # This is the local flask server url #cl = client.HPLeftHandClient("http://127.0.0.1:5000/lhos") if "debug" in args and args.debug == True: cl.debug_rest(True) def test_login(): print "Test Login" try: cl.login("administrator", "hpinvent") pprint.pprint("Login worked") except exceptions.HTTPUnauthorized: pprint.pprint("Login Failed") def test_logout(): print "Test Logout" try: cl.login("administrator", "hpinvent") pprint.pprint("Login worked") except exceptions.HTTPUnauthorized: pprint.pprint("Login Failed") try: cl.logout() pprint.pprint("Logout worked") except exceptions.HTTPUnauthorized: pprint.pprint("Logout Failed") def test_get_snapshot(snap_id): print "Get Snapshot" try: cl.login("administrator", "hpinvent") snap = cl.getSnapshot(snap_id) pprint.pprint(snap) except exceptions.HTTPUnauthorized as ex: pprint.pprint("You must login first") except Exception as ex: pprint.pprint(ex) def test_get_snapshot_by_name(name): print "Get Snapshot By Name" try: cl.login("administrator", "hpinvent") snap = cl.getSnapshotByName(name) pprint.pprint(snap) except exceptions.HTTPUnauthorized as ex: pprint.pprint("You must login first") except Exception as ex: pprint.pprint(ex) def test_create_snapshot(): print "Create Snapshot" try: cl.login("administrator", "hpinvent") vol = cl.createVolume("VolumeSource", 20, 1048576) snapshot = cl.createSnapshot('VolumeSnapshot', vol['id']) pprint.pprint(snapshot) cl.deleteSnapshot(snapshot['id']) cl.deleteVolume(vol['id']) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_snapshots(): print "Get Snapshots" try: cl.login("administrator", "hpinvent") snapshots = cl.getSnapshots() pprint.pprint(snapshots) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_servers(): print "Get Servers" try: cl.login("administrator", "hpinvent") servers = cl.getServers() pprint.pprint(servers) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_server(server_id): print "Get Server" try: cl.login("administrator", "hpinvent") server = cl.getServer(server_id) pprint.pprint(server) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_server_by_name(name): print "Get Server By Name" try: cl.login("administrator", "hpinvent") server = cl.getServerByName(name) pprint.pprint(server) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_volume(volume_id): print "Get Volumes" try: cl.login("administrator", "hpinvent") volume = cl.getVolume(volume_id) return volume except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_volume_by_name(name): print "Get Volume By Name" try: cl.login("administrator", "hpinvent") volume = cl.getVolumeByName(name) return volume except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_volumes(): print "Get Volumes" try: cl.login("administrator", "hpinvent") volumes = cl.getVolumes() pprint.pprint(volumes) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_clusters(): print "Get Clusters" try: cl.login("administrator", "hpinvent") volumes = cl.getClusters() pprint.pprint(volumes) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_get_cluster_by_name(name): print "Get Cluster By Name" try: cl.login("administrator", "hpinvent") volumes = cl.getClusterByName(name) pprint.pprint(volumes) except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_create_volume(): print "Create Volumes" try: cl.login("administrator", "hpinvent") vol = cl.createVolume("Volume1", 20, 1048576) return vol except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_delete_volume(volume_id): print "Delete a Volume" try: cl.login("administrator", "hpinvent") vol = cl.deleteVolume(volume_id) return vol except exceptions.HTTPUnauthorized: pprint.pprint("You must login first") def test_error(): print "test Error" try: cl.login("administrator", "hpinvent") resp, body = cl.http.get('/throwerror') pprint.pprint(resp) pprint.pprint(body) except Exception as ex: print ex #test_login() #test_logout() #vols = test_get_volumes() #vol = test_get_volume_by_name("vol1_test") #vols = test_get_clusters() #snap = test_get_snapshot("25") #snap = test_get_snapshot_by_name("vol1_test_SS_1") snaps = test_get_snapshots() #clusters = test_get_clusters() #cluster = test_get_cluster_by_name("ClusterVSA309") #servers = test_get_servers() #server = test_get_server_by_name("jim-devstack") #vol = test_get_volume(23) #pprint.pprint(vol) #test_delete_volume(400) #test_create_snapshot() #test_error() hplefthandclient-1.0.1/samples/utils.py0000664000175000017500000000742112263053020020436 0ustar stackstack00000000000000import argparse from os import sys import random from sys import path from os import getcwd import os, sys, inspect, pprint # this is a hack to get the hp driver module # and it's utils module on the search path. cmd_folder = os.path.realpath(os.path.abspath("..") ) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) from hplefthandclient import client, exceptions def get_volumes(cl): print "Get Volumes" try: volumes = cl.getVolumes() if volumes: for volume in volumes['members']: print "Found '%s'" % volume['name'] except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex print "Complete\n" def get_volume(cl, name): print "Get Volume %s" % name try: vol = cl.getVolume(name) pprint.pprint(vol) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex print "Complete\n" def get_hosts(cl): print "Get Hosts" try: hosts = cl.getHosts() if hosts: for host in hosts['members']: pprint.pprint(host) # print "Found '%s'" % host['name'] except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_host(cl,hostname): try: host = cl.getHost(hostname) pprint.pprint(host) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def delete_host(cl,hostname): try: host = cl.deleteHost(hostname) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_host_vluns(cl,hostname): try: host = cl.getHostVLUNs(hostname) pprint.pprint(host) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def delete_host_vluns(cl, hostName): try: vluns = cl.getHostVLUNs(hostName) if vluns: for vlun in vluns: print "Deleting VLUN %s " % vlun['volumeName'] cl.deleteVLUN(vlun['volumeName'], vlun['lun'], vlun['hostname'], vlun['portPos']) except exceptions.HTTPUnauthorized as ex: print "You must login" except Exception as ex: print ex def get_ports(cl): try: ports = cl.getPorts() pprint.pprint(ports) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_vluns(cl): print "Get VLUNs" try: vluns = cl.getVLUNs() if vluns: pprint.pprint(vluns) for vlun in vluns['members']: pprint.pprint(vlun) print "Found VLUN '%s'" % vlun['volumeName'] except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_vlun(cl,vlunname): try: vlun = cl.getVLUN(vlunname) pprint.pprint(vlun) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_cpgs(cl): print "Get CPGs" try: cpgs = cl.getCPGs() if cpgs: for cpg in cpgs['members']: print "Found CPG '%s'" % cpg['name'] except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex def get_cpg(cl, name): try: cpg = cl.getCPG(name) pprint.pprint(cpg) except exceptions.HTTPUnauthorized as ex: print "You must login first" except Exception as ex: print ex hplefthandclient-1.0.1/setup.cfg0000664000175000017500000000007312263071672017112 0ustar stackstack00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0