def get_fexports(moDir, fexProfile): ''' :param moDir: login session :param fexProfile: FEX Profile name :return: list of all configured ports ''' configured = [] uri = 'uni/infra/fexprof-{0}' dnq = DnQuery(uri.format(fexProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraHPortS' ports = moDir.query(dnq) names = [each.name for each in ports if each] for name in names: uri2 = 'uni/infra/fexprof-{0}/hports-{1}-typ-range' dnq2 = DnQuery(uri2.format(fexProfile, name)) dnq2.queryTarget = 'children' dnq2.classFilter = 'infraPortBlk' blocks = moDir.query(dnq2) for block in blocks: ints = [] startingPort = block.fromPort card = block.fromCard ints.append(card + '/' + startingPort) s = int(startingPort) while s != int(block.toPort): s += 1 ints.append(card + '/' + str(s)) configured.append({'name': name, 'ports': ints}) return configured
def get_nodeid(moDir, leafProfile): """ :param moDir: login session :param leafProfile: leaf Profile name :return node ids a switch. assumes one LeafS in leaf Profile, maximum of 2 nodes in a block. '0' if not configured """ uri = 'uni/infra/nprof-{0}' dnq = DnQuery(uri.format(leafProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraLeafS' leafs = moDir.query(dnq) dnq2 = DnQuery(leafs[0].dn) dnq2.queryTarget = 'children' nodeBlk = moDir.query(dnq2) dnq2.classFilter = 'infraNodeBlk' nodeBlk = moDir.query(dnq2) if len(nodeBlk) == 2: if int(nodeBlk[0].from_) < int(nodeBlk[1].from_): return nodeBlk[0].from_ + '-' + nodeBlk[1].from_ else: return nodeBlk[1].from_ + '-' + nodeBlk[0].from_ elif len(nodeBlk) == 1: return nodeBlk[0].from_ else: return "0"
def get_vpcnodeid(moDir, leafProfile): """ :param moDir: login session :param leafProfile: leaf Profile name :return node ids for a vpc protection group. '0' if not configured """ uri = 'uni/infra/nprof-{0}' dnq = DnQuery(uri.format(leafProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraLeafS' leafs = moDir.query(dnq) dnq2 = DnQuery(leafs[0].dn) dnq2.queryTarget = 'children' nodeBlk = moDir.query(dnq2) dnq2.classFilter = 'infraNodeBlk' nodeBlk = moDir.query(dnq2) if len(nodeBlk) == 2: if int(nodeBlk[0].from_) < int(nodeBlk[1].from_): nodes = nodeBlk[0].from_ + '-' + nodeBlk[1].from_ else: nodes = nodeBlk[1].from_ + '-' + nodeBlk[0].from_ elif nodeBlk[0].from_ != nodeBlk[0].to_: nodes = nodeBlk[0].from_ + '-' + nodeBlk[0].to_ else: return '0' # verify leafProfile has associated protection profile uri2 = 'uni/fabric/protpol/expgep-{0}' vpcs = moDir.lookupByClass('fabric.ExplicitGEp') vpcnodes = [] for vpc in vpcs: dnq2 = DnQuery(uri2.format(vpc.name)) dnq2.queryTarget = 'children' dnq2.classFilter = 'fabricNodePEp' nodePEp = moDir.query(dnq2) ids = [each.id for each in nodePEp if each] if len(ids) == 2: if int(ids[0]) < int(ids[1]): vpcnodes.append(ids[0] + '-' + ids[1]) else: vpcnodes.append(ids[1] + '-' + ids[0]) for vpcnode in vpcnodes: if nodes == vpcnode: return nodes return '0'
def lookupByClass(self, classNames, parentDn=None, propFilter=None): """Lookup MO's by class A short-form managed object (MO) query by class. Args: classNames (str or list): The class name list of class names. If parentDn is set, the classNames are used as a filter in a subtree query for the parentDn parentDn (cobra.mit.naming.Dn or str): The distinguished name of the parent object as a :class:`cobra.mit.naming.Dn` or string. propFilter (str): A property filter expression Returns: list: A list of the managed objects found in the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' if propFilter: dnQuery.propFilter = propFilter mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) if propFilter: classQuery.propFilter = propFilter mos = self.query(classQuery) return mos
def lookupByClass(self, classNames, parentDn=None, **kwargs): """Lookup MO's by class. A short-form managed object (MO) query by class. Args: classNames (str or list): The class name list of class names. If parentDn is set, the classNames are used as a filter in a subtree query for the parentDn parentDn (cobra.mit.naming.Dn or str, optional): The distinguished name of the parent object as a :class:`cobra.mit.naming.Dn` or string. **kwargs: Arbitrary parameters to be passed to the query generated internally, to further filter the result Returns: list: A list of the managed objects found in the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' self.__setQueryParams(dnQuery, kwargs) mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) self.__setQueryParams(classQuery, kwargs) mos = self.query(classQuery) return mos
def add_servicegraph(): apicURL = os.getenv("CliqrCloud_AciApicEndpoint") apicUser = os.getenv("CliqrCloud_AciUsername") apicPwd = os.getenv("CliqrCloud_AciPassword") apicTenant = os.getenv("CliqrCloud_AciTenantName") apicServiceGraphTemplate = os.getenv("Cloud_Setting_serviceGraphTemplate") # Handle cases where APIC URL is configured without ssl (typically, in a lab). if apicURL.startswith("https"): loginSession = LoginSession(apicURL, apicUser, apicPwd) else: loginSession = LoginSession(apicURL, apicUser, apicPwd,secure=False) # CliqrTier_CentOS_1_Cloud_Setting_AciPortGroup_2 tmpString = "CliqrTier_" + os.getenv("CliqrDependencies") + "_Cloud_Setting_AciPortGroup_2" appProfileName = os.getenv(tmpString).split("|")[1] qTenant = "tn-" + apicTenant qString = "uni/" + qTenant + "/ap-" + appProfileName dnQuery = DnQuery(qString) dnQuery.queryTarget = 'subtree' dnQuery.classFilter = 'fvRsProv' dnQuery.subtree = 'children' #dnQuery.subtreePropFilter='eq(fvRsCons.tCl,"vzBrCP")' # Obtain Session from APIC. moDir = MoDirectory(loginSession) moDir.login() # Query to obtain data from Managed Object Directory. dmo = moDir.query(dnQuery) print str(dmo[0].tDn) # Debug String. Remove from running env. logging.debug(" Contract String Obtained :" + dmo[0].tDn) # Service Graph - Query String qStringAbsG = "uni/" + qTenant + "/AbsGraph-" + apicServiceGraphTemplate graphMO = moDir.lookupByDn(qStringAbsG) # Subject Query String qStringSubj = dmo[0].tDn + "/subj-cliqr-subject" subjMO = moDir.lookupByDn(qStringSubj) # Attach Graph to Contract. RsSubjGraphAtt(subjMO, tnVnsAbsGraphName=graphMO.name) # Create Commit Object. nsCfg = ConfigRequest() nsCfg.addMo(subjMO) moDir.commit(nsCfg) contractString = dmo[0].tDn tmpArr = contractString.split("/") apicContractName = tmpArr[len(tmpArr)-1].replace("brc-","") aviApicContractArg = apicContractName + ":" + apicServiceGraphTemplate aviApicEpgName = appProfileName + ":" + os.getenv(tmpString).split("|")[2] params = {} with open('params.json', 'r') as p: params = json.loads(p.read()) params['apic_contract_graph'] = aviApicContractArg params['apic_epg_name'] = aviApicEpgName logging.debug(" Dump Params :: " + json.dumps(params)) with open('params.json', 'w') as f: json.dump(params, f)
def check_if_switchport_configured(moDir, switchProfile, range): ''' :param moDir: login session :param switchProfile: switch Profile name :param range: switch port range to check :return: True if configured ''' configured = [] proposed = [] card, fromPort, toPort = input_ports(range) proposed.append(card + '/' + fromPort) fromP = int(fromPort) toP = int(toPort) while (fromP != toP): fromP += 1 proposed.append(card + '/' + str(fromP)) uri = 'uni/infra/accportprof-{0}_ifselector' dnq = DnQuery(uri.format(switchProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraHPortS' ports = moDir.query(dnq) names = [each.name for each in ports if each] for name in names: uri2 = 'uni/infra/accportprof-{0}_ifselector/hports-{1}-typ-range' dnq2 = DnQuery(uri2.format(switchProfile, name)) dnq2.queryTarget = 'children' dnq2.classFilter = 'infraPortBlk' blocks = moDir.query(dnq2) for block in blocks: startingPort = block.fromPort card = block.fromCard configured.append(card + '/' + startingPort) s = int(startingPort) while s != int(block.toPort): s += 1 configured.append(card + '/' + str(s)) for p in proposed: if p in configured: return True return False
def get_ports_in_group(moDir, uri): ''' :param moDir: login session :param uri: dn of the policy group :return: list of ports configured for a policy group ''' ports = [] dnq = DnQuery(uri) dnq.queryTarget = 'children' dnq.classFilter = 'infraRtAccBaseGrp' ports = moDir.query(dnq) return ports
def get_domain_aep(moDir, Aep): ''' :param moDir: login session :param Aep: attachable entity profile name :return: list of domains in the AEP ''' uri = 'uni/infra/attentp-{0}/dompcont' dnq = DnQuery(uri.format(Aep)) dnq.queryTarget = 'children' dnq.classFilter = 'infraAssocDomP' assocDomP = moDir.query(dnq) dompDns = [each.dompDn for each in assocDomP if each] return dompDns
def get_vlan_pool(moDir, domain_dn): ''' :param moDir: login session :param domain_dn: dn of the domain :return: dn of a vlan pool ''' dnq = DnQuery(domain_dn) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsVlanNs' vlanNs = moDir.query(dnq) #there will only be one pool in the domain pool = vlanNs[0].tDn return pool
def get_epg_dom(moDir, uri, Aepg): """ :param moDir: login session :param uri: dn of EPG :param Aepg: name of EPG :return list of domains for an EPG """ domains = [] dnq = DnQuery(uri + Aepg) dnq.queryTarget = 'children' dnq.classFilter = 'fvRsDomAtt' rsDomAtt = moDir.query(dnq) # "uni/phys-LEGACY", "uni/vmmp-VMware/dom-AVS-01" domains = [each.tDn for each in rsDomAtt if each] return domains
def get_policy_group_aep(moDir, policyGroup, type): """ :param moDir: login session :param policyGroup: name of policy group :param type: type of policy. accbundle or accportgrp :return AEP for a policy group """ uri = 'uni/infra/funcprof/{0}{1}' dnq = DnQuery(uri.format(type, policyGroup)) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsAttEntP' rsAttEntP = moDir.query(dnq) try: aep = str(rsAttEntP[0].tDn).split('attentp-')[1] except IndexError: aep = '0' return aep
def get_vlans(moDir, pool_dn): ''' :param moDir: login session :param pool_dn: dn of a vlan pool :return: list of vlans ''' vlans = [] dnq = DnQuery(pool_dn) dnq.queryTarget = 'children' dnq.classFilter = 'fvnsEncapBlk' encapBlk = moDir.query(dnq) for ranges in encapBlk: # cannot access from keyword, so access as dictionary startingVlan = ranges.__dict__['from'].split('-')[1] vlans.append('vlan-' + startingVlan) s = int(startingVlan) while s != int(ranges.to.split('-')[1]): s += 1 vlans.append('vlan-' + str(s)) return vlans
def get_fexport_policy_group(moDir, fexProfile, port_name): ''' :param moDir: login session :param fexProfile: profile name of the FEX :param port_name: name of the port :return: policy group for the configured port. '0' if not configured ''' uri = 'uni/infra/fexprof-{0}/hports-{1}-typ-range' dnq = DnQuery(uri.format(fexProfile, port_name)) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsAccBaseGrp' rsAccBaseGrp = moDir.query(dnq) try: if rsAccBaseGrp[0].tCl == 'infraAccBndlGrp': policy_group = str(rsAccBaseGrp[0].tDn).split('accbundle-')[1] elif rsAccBaseGrp[0].tCl == 'infraAccPortGrp': policy_group = str(rsAccBaseGrp[0].tDn).split('accportgrp-')[1] except IndexError: policy_group = '0' return policy_group
def lookupByClass(self, classNames, parentDn=None, **queryParams): """ A short-form managed object (MO) query by class. Args: classNames: Name of the class to lookup parentDn: dn of the root object were to start search from (optional) queryParams: a dictionary including the properties to the added to the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' self.__setQueryParams(dnQuery, queryParams) mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) self.__setQueryParams(classQuery, queryParams) mos = self.query(classQuery) return mos
from cobra.mit.request import DnQuery urllib3.disable_warnings() #Disable HTTPS warnings apic_url = '' apic_user = '' apic_password = '' loginSession = LoginSession(apic_url, apic_user, apic_password) #Setup Login credentials md = MoDirectory(loginSession) md.login() #Login dq1 = DnQuery('uni/infra') dq1.queryTarget = 'subtree' dq1.classFilter = 'infraAccPortP' InterfaceProfiles = md.query(dq1) for IF in InterfaceProfiles: dq2 = DnQuery('uni/infra/accportprof-' + IF.name + '/hports-' + IF.name + '-IF-typ-range/portblk-block2') dq2.queryTarget = 'subtree' dq2.classFilter = 'infraPortBlk' AccPorts = md.query(dq2) if len(AccPorts) != 0: print IF.name + ' = ' + AccPorts[0].fromCard + '/' + AccPorts[ 0].fromPort raw_input('Press Enter to continue...')