def listretentionclasses(self): """ List the Retention Classes available for the actual namespace. :return: a dict holding a dict per Retention Class """ try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time r = con.GET('/proc/retentionClasses') if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 root = Et.fromstring(x) d = OrderedDict() for n in root: d[n.attrib.get('name')] = n.attrib for i in d[n.attrib.get('name')].keys(): d[n.attrib.get('name')][i] = \ self._castvar(d[n.attrib.get('name')][i]) for n1 in n: d[n.attrib.get('name')]['description'] = n1.text.strip() else: raise (hcpsdk.HcpsdkError('{} - {}'.format(r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def listpermissions(self): """ List the namespace and user permissions for the actual namespace. :return: a dict holding a dict per permission domain """ try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time r = con.GET('/proc/permissions') if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 root = Et.fromstring(x) d = OrderedDict() for n in root: d[n.tag] = n.attrib for i in d[n.tag].keys(): d[n.tag][i] = self._castvar(d[n.tag][i]) else: raise (hcpsdk.HcpsdkError('{} - {}'.format(r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def getlinklist(self): """ Query MAPI for a list of replication links. :return: a list with the names of replication links :raises: HcpsdkError """ d = [] try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time try: r = con.GET('/mapi/services/replication/links') except Exception as e: d.append('Error: {}'.format(str(e))) else: if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 root = Et.fromstring(x) for child in root: if child.tag == 'name': d.append(child.text) else: raise (hcpsdk.HcpsdkError('{} - {}'.format( r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def setUp(self): self.T_HCPFILE = '/rest/hcpsdk/fail_TestHCPsdk_20_access' self.hcptarget = hcpsdk.Target(it.P_NS_GOOD, it.P_AUTH, it.P_SSLPORT, dnscache=it.P_DNSCACHE) self.con = hcpsdk.Connection(self.hcptarget)
def getreplicationsettings(self): """ Query MAPI for the general settings of the replication service. :return: a dict containing the settings :raises: HcpsdkError """ d = {} try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time try: r = con.GET('/mapi/services/replication') except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 for child in Et.fromstring(x): d[child.tag] = child.text else: raise (hcpsdk.HcpsdkError('{} - {}'.format( r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def setreplicationlinkstate(self, linkname, action, linktype=None): """ Alter the state of a replication link. :param linkname: name of the link to change the state :param linktype: one of ``[R_ACTIVE_ACTIVE, R_OUTBOUND, R_INBOUND]``; not required for ``[R_SUSPEND, R_RESUME, R_RESTORE]`` :param action: one of ``[R_SUSPEND, R_RESUME, R_RESTORE, R_FAILOVER, R_FAILBACK, R_BEGINRECOVERY, R_COMPLETERECOVERY]`` :raises: HcpsdkError """ # make sure that only valid linktypes and actions are accepted if linktype not in [Replication.R_ACTIVE_ACTIVE, Replication.R_OUTBOUND, Replication.R_INBOUND, None] or \ action not in [Replication.R_SUSPEND, Replication.R_RESUME, Replication.R_RESTORE, Replication.R_BEGINRECOVERY, Replication.R_COMPLETERECOVERY, Replication.R_FAILBACK, Replication.R_FAILOVER]: raise ValueError # make sure that no invalid action is called if (action == Replication.R_FAILBACK and linktype in [Replication.R_OUTBOUND, Replication.R_INBOUND]) or \ (action in [Replication.R_BEGINRECOVERY, Replication.R_COMPLETERECOVERY] and linktype == Replication.R_ACTIVE_ACTIVE) or \ (action in [Replication.R_FAILOVER, Replication.R_FAILBACK, Replication.R_BEGINRECOVERY, Replication.R_COMPLETERECOVERY] and not linktype): raise ReplicationSettingsError('{} not allowed on {} link'.format( action, linktype)) # build params action = {action: ''} # let's do it! try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: try: r = con.POST( '/mapi/services/replication/links/{}'.format(linkname), params=action) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: if r.status != 200: err = r.getheader('X-HCP-ErrorMessage', 'no message') raise (hcpsdk.HcpsdkError('{} - {} ({})'.format( r.status, r.reason, err))) else: r.read() finally: # noinspection PyUnboundLocalVariable con.close()
def setUp(self): print('>>> TestHcpsdk_2_Access_https_systemCA:') self.T_HCPFILE = '/rest/hcpsdk/TestHCPsdk_20_access' self.ctxt = ssl.create_default_context() print('Certificate store status:') pprint(self.ctxt.cert_store_stats()) print('CA certificates:') pprint((self.ctxt.get_ca_certs())) self.hcptarget = hcpsdk.Target(it.P_NS_GOOD, it.P_AUTH, it.P_SSLPORT, dnscache=it.P_DNSCACHE, sslcontext=self.ctxt) self.con = hcpsdk.Connection(self.hcptarget)
def listaccessiblens(self, all=False): """ List the settings of the actual (or all accessible namespace(s). :param all: list all accessible namespaces if True, else list the actual one, only. :return: a dict holding a dict per namespace """ # setup Target URL and apply parameters url = '/proc' if not all: params = {'single': 'true'} else: params = None try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time try: r = con.GET(url, params=params) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 root = Et.fromstring(x) d = OrderedDict() for n in root: d[n.attrib.get('name')] = n.attrib for i in d[n.attrib.get('name')].keys(): d[n.attrib.get('name')][i] = \ self._castvar(d[n.attrib.get('name')][i]) for n1 in n: d[n.attrib['name']]['description'] = n1.text.strip().split('°') else: raise (hcpsdk.HcpsdkError('{} - {}'.format(r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def setUp(self): print('>>> TestHcpsdk_1_Access_https_certfile:') self.T_HCPFILE = '/rest/hcpsdk/TestHCPsdk_20_access' self.ctxt = ssl.create_default_context( purpose=ssl.Purpose.SERVER_AUTH, cafile='certs/rootCertificate.pem') print('Certificate store status:') pprint(self.ctxt.cert_store_stats()) print('CA certificates:') pprint((self.ctxt.get_ca_certs())) self.hcptarget = hcpsdk.Target(it.P_NS_GOOD, it.P_AUTH, it.P_SSLPORT, dnscache=it.P_DNSCACHE, sslcontext=self.ctxt) self.con = hcpsdk.Connection(self.hcptarget)
def getlinkdetails(self, link): """ Query MAPI for the details of a replication link. :param link: the name of the link as retrieved by **getlinklist()** :return: a dict holding the details :raises: HcpsdkError """ d = {} try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time try: r = con.GET('/mapi/services/replication/links/{}'.format(link), params={'verbose': 'true'}) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 for child in Et.fromstring(x): if child.text: d[child.tag] = child.text else: d[child.tag] = {} for i in child: if i.text: d[child.tag][i.tag] = i.text else: d[child.tag][i.tag] = {} for j in i: d[child.tag][i.tag][j.tag] = j.text else: raise (hcpsdk.HcpsdkError('{} - {}'.format( r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def listtenants(target, timeout=60, debuglevel=0): """ Get a list of available Tenants :param target: an hcpsdk.Target object :param timeout: the connection timeout in seconds :param debuglevel: 0..9 (used in *http.client*) :returns: a list() of *Tenant()* objects :raises: *hcpsdk.HcpsdkPortError* in case *target* is initialized with a port different that *P_MAPI* """ logger = logging.getLogger(__name__) logger.debug('getting a list of Tenants') hcpsdk.checkport(target, hcpsdk.P_MAPI) tenantslist = [] try: con = hcpsdk.Connection(target, timeout=timeout, debuglevel=debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) try: con.GET('/mapi/tenants', headers={'Accept': 'application/json'}, params={'verbose': 'true'}) except Exception as e: logger.debug('getting a list of Tenants failed: {}'.format(e)) raise TenantError('get Tenant list failed: {}'.format(e)) else: if con.response_status == 200: for t in loads(con.read().decode())['name']: tenantslist.append(Tenant(target, t, debuglevel=debuglevel)) logger.debug('got a list of {} Tenants'.format(len(tenantslist))) else: con.close() logger.debug('getting a list of Tenants failed: {}-{}'.format( con.response_status, con.response_reason)) raise TenantError('unable to list Tenants ({} - {})'.format( con.response_status, con.response_reason)) con.close() return tenantslist
def __init__(self, target, name, timeout=60, debuglevel=0): """ :param target: an hcpsdk.Target object :param name: the Tenants name :param timeout: the connection timeout in seconds :param debuglevel: 0..9 (used in *http.client*) """ self.logger = logging.getLogger(__name__ + '.Tenant') self.target = target try: self.con = hcpsdk.Connection(self.target, timeout=timeout, debuglevel=debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) self.name = name # the Tenants name self._settings = {} # the Tenants base settings self.logger.debug('initialized for "{}"'.format(self.name))
def nsstatistics(self): """ Query for namespace statistic information :return: a dict holding the stats :raises: hcpsdk.HcpsdkError() """ # noinspection PyUnusedLocal d = None try: con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: self.connect_time = con.connect_time try: r = con.GET('/proc/statistics') except Exception as e: raise hcpsdk.HcpsdkError(str(e)) else: if r.status == 200: # Good status, get and parse the Response x = r.read() self.service_time = con.service_time2 root = Et.fromstring(x) d = root.attrib tobedel = None for i in d.keys(): if i.startswith('{http'): tobedel = i else: d[i] = self._castvar(d[i]) if tobedel: del d[tobedel] else: raise (hcpsdk.HcpsdkError('{} - {}'.format(r.status, r.reason))) finally: # noinspection PyUnboundLocalVariable con.close() return d
def __init__(self, target, debuglevel=0): """ :param target: an hcpsdk.Target object :param debuglevel: 0..9 (used in *http.client*) :raises: *hcpsdk.HcpsdkPortError* in case *target* is initialized with an incorrect port for use by this class. """ self.logger = logging.getLogger(__name__ + '.Logs') hcpsdk.checkport(target, hcpsdk.P_MAPI) self.target = target self.debuglevel = debuglevel self.connect_time = 0.0 self.service_time = 0.0 self.prepare_xml = None self.suggestedfilename = '' # the filename suggested by HCP try: self.con = hcpsdk.Connection(self.target, debuglevel=self.debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e))
def __init__(self, target, timeout=600, debuglevel=0): ''' :param target: an hcpsdk.Target object pointing to an HCP FQDN starting with **admin.** for access from a system level account or **<tenant>.** for a tenant level account :param timeout: the connection timeout; relatively high per default, as generating the report can take longer than **hcpsdk**\ s default of 30 seconds on a busy system :param debuglevel: 0..9 (used in *http.client*) ''' self.logger = logging.getLogger(__name__ + '.Chargeback') hcpsdk.checkport(target, hcpsdk.P_MAPI) self.connect_time = 0.0 self.service_time = 0.0 try: self.con = hcpsdk.Connection(target, timeout=timeout, debuglevel=debuglevel) except Exception as e: raise hcpsdk.HcpsdkError(str(e))
else: sys.exit('source path is undefined') T_OBJPATH = join(T_INPATH, T_OBJ) print("--> Init <hcptarget> object") try: auth = hcpsdk.NativeAuthorization(T_DAAC, T_DAAC_PWD) hcptarget = hcpsdk.Target(T_NAMESPACE, auth, T_PORT) except hcpsdk.HcpsdkError as e: sys.exit("Fatal: {}".format(e.errText)) print("--> Init <connection> object") conntimes = 0.0 outer_contime = time.time() try: con = hcpsdk.Connection(hcptarget, debuglevel=0, idletime=600, retries=2) except Exception as e: sys.exit('Exception: {}'.format(str(e))) print('--> PUT object {}'.format(T_OBJPATH)) with open(join(T_INPATH,T_OBJ), 'rb') as inHdl: r = con.PUT(T_NAME, inHdl) print('PUT result: {}'.format(con.response_status)) print('--> GET object {}'.format(T_OBJPATH)) try: r = con.HEAD(T_NAME) except Exception as e: print(str(e))
else: sys.exit('source path is undefined') print("--> Init <hcptarget> object") try: auth = hcpsdk.NativeAuthorization(T_DAAC, T_DAAC_PWD) hcptarget = hcpsdk.Target(T_NAMESPACE, auth, T_PORT) except hcpsdk.HcpsdkError as e: sys.exit("Fatal: {}".format(e.errText)) print("--> Init {} <connection> object(s)".format(T_THREADS)) conns = None conntimes = 0.0 outer_contime = time.time() try: conns = hcpsdk.Connection(hcptarget, debuglevel=0, idletime=3) except Exception as e: sys.exit('Exception: {}'.format(str(e))) else: conntimes += conns.connect_time outer_contime = time.time() - outer_contime print('\tinner connection time: {:,.5f}'.format(conntimes)) print('\touter connection time: {:,.5f}'.format(outer_contime)) # load one of the files into memory print('--> Loading test object into memory...') with open(join(T_INPATH,T_OBJS[T_OBJ]), 'rb') as inHdl: buf = bytearray(inHdl.read()) size = len(buf) print('...object size = {}'.format(size))
import os import time import hcpsdk if __name__ == '__main__': a = hcpsdk.NativeAuthorization('n', 'n01') t = hcpsdk.Target('n1.m.hcp1.snomis.local', a, port=443) c = hcpsdk.Connection(t) r = c.GET('/rest/hcpsdk/testfile2.mp4') print(c.response_status, c.response_reason) print('len(c.read(1024)) = {}'.format(len(c.read(1024)))) for i in range(10): print('.', end='', flush=True) time.sleep(1) print() try: print('len(c.read()) = {}'.format(len(c.read()))) except Exception as e: print(str(e)) raise e finally: c.close()
auth = hcpsdk.NativeAuthorization('<monitoring user>', '<password>') tgt = hcpsdk.Target( adminportal, auth, port=hcpsdk.P_MAPI) alltenants = hcpsdk.mapi.listtenants(tgt) for atenant in alltenants: tenantshortnamelist.append(atenant.name) for btenant in alltenants: tgttnts = hcpsdk.Target(btenant.name+'.'+url, auth, port=443) tenantfullnamelist.append(tgttnts._Target__fqdn) for tenantfullname in tenantfullnamelist: tgttnt = hcpsdk.Target(tenantfullname, auth, port=hcpsdk.P_MAPI) c = hcpsdk.Connection(tgttnt) for tenantsn in tenantshortnamelist: c.GET('/mapi/tenants/'+tenantsn+'/namespaces') c.response_status source = c.read() if source == "b''": pass else: try: namespacelistpertenant = etree.fromstring(source) namespaceinfopertenant = namespacelistpertenant.findall('name') for q, value in enumerate(namespaceinfopertenant): namespacename = str(value.text) cona = hcpsdk.Connection(tgt)