Skip to content

Commit

Permalink
Minor code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Smith committed Sep 27, 2018
1 parent 698e0f5 commit f504ff1
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 43 deletions.
30 changes: 23 additions & 7 deletions acitoolkit/acibaseobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,12 @@ def get_event(cls, session):
if not session.has_events(url):
continue
event = session.get_event(url)
class_name = None
for class_name in cls._get_apic_classes():
if class_name in event['imdata'][0]:
break
if class_name is None:
return None
attributes = event['imdata'][0][class_name]['attributes']
status = str(attributes['status'])
dn = str(attributes['dn'])
Expand Down Expand Up @@ -911,7 +914,8 @@ def get_interfaces(self, status='attached'):
resp.append(relation.item)
return resp

def _get_all_relations_by_class(self, relations, attached_class,
@staticmethod
def _get_all_relations_by_class(relations, attached_class,
status='attached', relation_type=None):
"""
Internal function to get relations or attachments for a given class.
Expand Down Expand Up @@ -968,8 +972,7 @@ def _get_url_extension(self):

def __str__(self):
return self.name

@staticmethod

def get_from_json(self, data, parent=None):
"""
returns a Tenant object from a json
Expand All @@ -989,8 +992,8 @@ def get_from_json(self, data, parent=None):
class_object._populate_from_attributes(children[child_key]['attributes'])
object_exist = True
if not object_exist:
child_obj = class_name(child_name,parent=self)
class_name._populate_from_attributes(child_obj,children[child_key]['attributes'])
child_obj = class_name(child_name, parent=self)
class_name._populate_from_attributes(child_obj, children[child_key]['attributes'])
class_name.get_from_json(child_obj, children, parent=self)

def get_json(self, obj_class, attributes=None,
Expand Down Expand Up @@ -1102,7 +1105,7 @@ def get(cls, session, toolkit_class, apic_class, parent=None, tenant=None, query
:param tenant: Tenant object to assign the created objects.
:param query_target_type: type of the query either self,children,subtree
"""
if query_target_type not in ['self','children','subtree']:
if query_target_type not in ['self', 'children', 'subtree']:
raise ValueError
if isinstance(tenant, str):
raise TypeError
Expand Down Expand Up @@ -1356,9 +1359,12 @@ def _instance_get_subtree_faults(self, session, fault_objs, extension='', deep=F
class BaseACIPhysObject(BaseACIObject):
"""Base class for physical objects
"""

def __init__(self, name='', parent=None, pod=None):
self._session = None
if not hasattr(self, 'type'):
self.type = None
if not hasattr(self, 'module'):
self.module = None
self.pod = None
if pod:
self.pod = pod
Expand Down Expand Up @@ -1593,6 +1599,7 @@ def _get_name_from_dn(cls, dn):
name = dn.split('/tag-')[1].split('/')[0]
return name


class BaseACIPhysModule(BaseACIPhysObject):
"""BaseACIPhysModule: base class for modules """

Expand Down Expand Up @@ -1748,6 +1755,15 @@ class BaseInterface(BaseACIObject):
"""Abstract class used to provide base functionality to other Interface
classes.
"""
def __init__(self, name, parent=None):
if not hasattr(self, 'module'):
self.module = None
if not hasattr(self, 'port'):
self.port = None
if not hasattr(self, 'node'):
self.node = None
super(BaseInterface, self).__init__(name, parent)

@staticmethod
def is_dn_vpc(dn):
"""
Expand Down
26 changes: 16 additions & 10 deletions acitoolkit/acisession.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@


class CredentialsError(Exception):
"""
Exception class for errors with Credentials class
"""
def __init___(self, message):
Exception.__init__(self, "Session Credentials Error:{0}".format(message))
self.message = message
Expand Down Expand Up @@ -209,7 +212,8 @@ def _send_subscription(self, url, only_new=False):
return resp
resp_data = json.loads(resp.text)
if 'subscriptionId' not in resp_data:
logging.error('Did not receive proper subscription response from APIC for url %s response: %s', url, resp_data)
logging.error('Did not receive proper subscription response from APIC for url %s response: %s',
url, resp_data)
resp = requests.Response()
resp.status_code = 404
resp._content = '{"error": "Could not send subscription to APIC"}'
Expand Down Expand Up @@ -489,7 +493,7 @@ def __init__(self, url, uid, pwd=None, cert_name=None, key=None, verify_ssl=Fals
if not isinstance(key, str):
raise CredentialsError("The key path must be a string")
if (cert_name and not key) or (not cert_name and key):
raise CredentialsError("Both a certificate name and private key must be provided")
raise CredentialsError("Both a certificate name and private key must be provided")
if not isinstance(relogin_forever, bool):
raise CredentialsError("relogin_forever must be a boolean")

Expand Down Expand Up @@ -595,8 +599,7 @@ def _prep_x509_header(self, method, url, data=None):
self.key,
method,
url,
data)
)
data))

payload = '{}{}'.format(method, url)
if data:
Expand All @@ -608,7 +611,7 @@ def _prep_x509_header(self, method, url, data=None):
'APIC-Certificate-Fingerprint': 'fingerprint',
'APIC-Certificate-DN': cert_dn}

logging.debug('Authentication cookie %s' % cookie)
logging.debug('Authentication cookie %s', cookie)
return cookie

def _send_login(self, timeout=None):
Expand All @@ -628,7 +631,8 @@ def _send_login(self, timeout=None):
login_url = '/api/requestAppToken.json'
data = {'aaaAppToken': {'attributes': {'appName': self.cert_name}}}
elif self.cert_auth:
logging.warning('Will not explicitly login because certificate based authentication is being used for this session.')
logging.warning('Will not explicitly login because certificate based authentication'
' is being used for this session.')
logging.warning('If permanently using cert auth, consider removing the call to login().')
CertAuthResponse = namedtuple('CertAuthResponse', ['ok'])
return CertAuthResponse(ok=True)
Expand Down Expand Up @@ -827,7 +831,8 @@ def get(self, url, timeout=None):
logging.debug(get_url)

cookies = self._prep_x509_header('GET', url)
resp = self.session.get(get_url, timeout=timeout, verify=self.verify_ssl, proxies=self._proxies, cookies=cookies)
resp = self.session.get(get_url, timeout=timeout, verify=self.verify_ssl,
proxies=self._proxies, cookies=cookies)
if resp.status_code == 403:
if self.cert_auth and not (self.appcenter_user and self._subscription_enabled):
logging.error('Certificate authentication failed. Please check all settings are correct.')
Expand Down Expand Up @@ -856,7 +861,7 @@ def get(self, url, timeout=None):
total_count = orig_total_count - 10000
while total_count > 0 and resp.ok:
page_number += 1
logging.debug('Getting page %s' % page_number)
logging.debug('Getting page %s', page_number)
# Get the next chunk
cookies = self._prep_x509_header('GET', url + '&page=%s&page-size=10000' % page_number)
resp = self.session.get(get_url + '&page=%s&page-size=10000' % page_number,
Expand All @@ -869,12 +874,13 @@ def get(self, url, timeout=None):
'totalCount': orig_total_count}
resp._content = json.dumps(resp_content)
elif 400 < resp.status_code < 600:
logging.debug('Received error: %s %s' % (str(resp.status_code), resp.text))
logging.debug('Received error: %s %s', str(resp.status_code), resp.text)
retries = 3
while retries > 0:
logging.debug('Retrying query')
cookies = self._prep_x509_header('GET', url)
resp = self.session.get(get_url, timeout=timeout, verify=self.verify_ssl, proxies=self._proxies, cookies=cookies)
resp = self.session.get(get_url, timeout=timeout, verify=self.verify_ssl,
proxies=self._proxies, cookies=cookies)
if resp.status_code != 200:
logging.debug('Retry was not successful.')
retries -= 1
Expand Down
22 changes: 12 additions & 10 deletions acitoolkit/acitoolkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,8 @@ def _extract_relationships(self, data, obj_dict):
encap_id,
encap_mode)
else:
l2int = L2Interface('l2_int_{}-{}_on_{}{}/{}/{}/{}'.format(encap_type, encap_id, int_type, pod, node, module, port),
l2int = L2Interface('l2_int_{}-{}_on_{}{}/{}/{}/{}'.format(encap_type, encap_id, int_type,
pod, node, module, port),
encap_type,
encap_id,
encap_mode)
Expand Down Expand Up @@ -4869,6 +4870,11 @@ def __init__(self, if_type, pod, node, fex, module, port):

@classmethod
def parse_dn(cls, dn):
"""
Parse the pod, node, interface name from the dn
:param dn: String containing the interface DN
:return: Tuple consisting of if_type, pod, node, fex, module, port
"""
if '/phys-' in dn:
pod = dn.split('/pod-')[1].split('/')[0]
node = dn.split('/node-')[1].split('/')[0]
Expand Down Expand Up @@ -5432,7 +5438,8 @@ def get_all_by_epg(cls, session, tenant_name, app_name, epg_name, with_interface
:param tenant_name: String containing the tenant name
:param app_name: String containing the app name
:param epg_name: String containing the epg name
:param with_interface_attachments: Boolean indicating whether interfaces should be attached or not. True is default.
:param with_interface_attachments: Boolean indicating whether interfaces should be attached or not.
True is default.
:return: List of Endpoint instances
"""
if with_interface_attachments:
Expand Down Expand Up @@ -6516,7 +6523,7 @@ def __init__(self, name, encap_type, mode, start_id=None, end_id=None):
self.encap_type = encap_type
self.start_id = start_id
self.end_id = end_id
valid_modes = ['static', 'dynamic','UOL_VXLAN']
valid_modes = ['static', 'dynamic', 'UOL_VXLAN']
if mode not in valid_modes:
raise ValueError('Mode specified is not a valid mode')
self.mode = mode
Expand Down Expand Up @@ -6561,7 +6568,7 @@ def _get_apic_classes(cls):
Get the APIC classes used by the acitoolkit class.
:returns: list of strings containing APIC class names
"""
return ['fvnsVlanInstP','fvnsVxlanInstP']
return ['fvnsVlanInstP', 'fvnsVxlanInstP']

@classmethod
def get(cls, session):
Expand All @@ -6576,23 +6583,18 @@ def get(cls, session):
resp = []
for ac in apic_classes:
query_url = (('/api/mo/uni.json?query-target=subtree&'
'target-subtree-class=') + str(ac))
'target-subtree-class=') + str(ac))
ret = session.get(query_url)
data = ret.json()['imdata']

#print(data)
for object_data in data:
# print (apic_classes[0])
#print (object_data)
if ac in object_data:
#print("vlan")
name = str(object_data[ac]['attributes']['name'])
dn = object_data[ac]['attributes']['dn']
encap_type = "vlan"
if ac == 'fvnsVxlanInstP':
encap_type = "vxlan"
mode = dn.split("-")[-1]
#print(mode)
try:
obj = toolkit_class(name,encap_type,mode)
except ValueError:
Expand Down

0 comments on commit f504ff1

Please sign in to comment.