Exemplo n.º 1
0
def get_tenant():
    with open("/Users/clakits/Documents/ACI/AppCenter/log/log.txt",
              "a") as log_file:
        log_file.write("==================================================" +
                       "\n")
        log_file.write("Received API Request from Client. Sending Response" +
                       "\n")
        log_file.write("==================================================" +
                       "\n")

    tableList = []

    row = ('Tenant')

    tableList.append(row)
    apicUrl = 'https://10.22.47.171/'
    #loginSession = createCertSession()
    loginSession = LoginSession(apicUrl, 'admin', 'ins3965!')
    moDir = MoDirectory(loginSession)
    moDir.login()
    #tenantMo = moDir.lookupByClass('fvTenant');
    q = ClassQuery('fvTenant')
    q.subtree = 'children'
    tenantMo = moDir.query(q)
    moDir.logout()
    print tenantMo.totalCount
    for item in tenantMo:
        row = str(item.dn)
        print row
        tableList.append(row)
    #return respFormatJsonMos(tenantMo, tenantMo.totalCount)

    return render_template('result1.html', table=tableList)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
def main(host, username, password, tenant):
    apic = "https://%s" % host
    print("Connecting to APIC : %s" % apic)
    moDir = MoDirectory(LoginSession(apic, username, password))
    moDir.login()
    dn_name = "uni/tn-" + tenant
    print(dn_name)
    dnq = DnQuery(dn_name)
    dnq.subtree = 'children'
    tenantMO = moDir.query(dnq)
    for bdMO in tenantMO.BD:
        print("BD NAME => {", bdMO.name, "}")
Exemplo n.º 4
0
def main(host, username, password, tenant):
    apic = "https://%s" % host
    print("Connecting to APIC : %s" % apic)
    moDir = MoDirectory(LoginSession(apic, username, password))
    moDir.login()
    dn_name = "uni/tn-" + tenant
    print(dn_name)
    dnq = DnQuery(dn_name)
    dnq.subtree = 'children'
    tenantMO = moDir.query(dnq)
    for bdMO in tenantMO.BD:
        print("BD NAME => {", bdMO.name, "}")
Exemplo n.º 5
0
 def test_get_tn(self, apics, certobject, userobject):
     apic = apics[0]
     secure = False if apics[1] == 'False' else True
     userobject.pkey = certobject.readFile(
         fileName=certobject.pkeyfile)
     session = CertSession(apic, userobject.certDn, userobject.pkey,
                           secure=secure, requestFormat='xml')
     moDir = MoDirectory(session)
     dnQuery = DnQuery('uni/tn-common')
     #dnQuery.subtree = "full"
     tq = moDir.query(dnQuery)
     assert len(tq) == 1
     tq = tq[0]
     assert str(tq.parentDn) == 'uni'
     assert str(tq.dn) == 'uni/tn-common'
Exemplo n.º 6
0
 def test_get_tn(self, apics, certobject, userobject):
     apic = apics[0]
     secure = False if apics[1] == 'False' else True
     userobject.pkey = certobject.readFile(
         fileName=certobject.pkeyfile)
     session = CertSession(apic, userobject.certDn, userobject.pkey,
                           secure=secure, requestFormat='xml')
     moDir = MoDirectory(session)
     dnQuery = DnQuery('uni/tn-common')
     #dnQuery.subtree = "full"
     tq = moDir.query(dnQuery)
     assert len(tq) == 1
     tq = tq[0]
     assert str(tq.parentDn) == 'uni'
     assert str(tq.dn) == 'uni/tn-common'
Exemplo n.º 7
0
def home():

    #apicUrl = 'https://10.29.198.36'
    # loginSession = LoginSession(apicUrl, 'admin', 'ins3965!')

    #loginSession = createCertSession()
    loginSession = cobra.mit.session.LoginSession('https://10.29.198.36',
                                                  'admin', 'ins3965!')
    moDir = MoDirectory(loginSession)
    moDir.login()

    tableList = []
    row = ('TN', 'AP/L2OUT', 'EPG/InstP', 'CEP', 'IP', 'Type', 'PATH', 'PORT',
           'POD', 'ENCAP', 'BD:CTX')
    tableList.append(row)

    q = ClassQuery('fvCEp')
    q.subtree = 'children'
    tenantMo = moDir.query(q)

    for mo in tenantMo:
        for child in mo.rscEpToPathEp:
            #print child.dn
            ip = mo.ip

            tn, ap, epg, cep, varPod, varStrPath, varStrPort = tDnToPath(
                child.dn)
            if 'protpaths' in child.tDn: portType = 'vPC'
            elif 'paths' in child.tDn and 'eth' in child.tDn: portType = '-'
            else: portType = 'PC'
            encap = (mo.encap).split('-')[1]

            #if args.macSearch: bd,ctx = getAncestorDnStrFromDnString(md, str(mo.dn), 1)
            #else: bd='-'; ctx='-'
            bd = '-'
            ctx = '-'

            row = (tn, ap, epg, cep, mo.ip, portType, varStrPath, varStrPort,
                   varPod, encap, '%s:%s' % (bd, ctx))
            tableList.append(row)

    moDir.logout()

    return render_template('home.html', table=tableList)
Exemplo n.º 8
0
#!/usr/bin/env python
"""Obtain serial numbers of ACI fabric nodes using the Cobra SDK"""

from cobra.mit.access import MoDirectory
from cobra.mit.request import ClassQuery
from cobra.mit.session import LoginSession

from requests.packages.urllib3 import disable_warnings

disable_warnings()

apic_url = 'https://apic1.dcloud.cisco.com'
apic_user = '******'
apic_password = '******'

login_session = LoginSession(apic_url, apic_user, apic_password)
md = MoDirectory(login_session)
md.login()

cq = ClassQuery('fabricNode')
nodes = md.query(cq)

sorted_nodes = sorted(nodes, key=lambda node: node.name)

print '\nNode name : Serial number\n'

for node in sorted_nodes:
    print '{0:9} : {1} '.format(node.name, node.serial)

md.logout()
Exemplo n.º 9
0
from requests.packages.urllib3 import disable_warnings
disable_warnings()

# Define the URL and credentials for the APIC
apic_url = 'https://apic1.dcloud.cisco.com'
apic_user = '******'
apic_password = '******'

# Login to the APIC
loginSession = LoginSession(apic_url, apic_user, apic_password)
md = MoDirectory(loginSession)
md.login()

# Obtain the list of tenants and print their names
cq = ClassQuery('fvTenant')
tenants = md.query(cq)

for tenant in tenants:
    print tenant.name

raw_input('Press Enter to continue...')

# Define a new tenant
polUni = md.lookupByDn('uni')
tenant = Tenant(polUni, 'Some-New-Tenant')
tenant.descr = 'This tenant was created by cobra'

# Push the new tenant configuration to the APIC
cr = ConfigRequest()
cr.addMo(polUni)
md.commit(cr)
Exemplo n.º 10
0
        print 'Usage: apic_show-mac-address.py <hostname> <username> <password> <mac-address>'
        sys.exit()
    else:
        hostname, username, password, macaddress = sys.argv[1:]
        url = 'https://' + hostname
        print "Logging on APIC..."

        try:
            #
            lls = LoginSession(url, username, password, secure=False)
            md = MoDirectory(lls)
            md.login()
            q = ClassQuery('fvCEp')
            q.subtree = 'children'
            q.subtreeClassFilter = 'fvRsCEpToPathEp'
            mos = md.query(q)

            #Other variables
            hasmacaddress = False
            epglists = {}
            i = -1

            ## Verifying all mac address:
            for mo in mos:
                for child in mo.rscEpToPathEp:
                    line = str(child.dn)
                    i = i + 1
                    if (macaddress in line):
                        hasmacaddress = True
                        epglists[i] = line
Exemplo n.º 11
0
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()

dq1 = DnQuery('uni/<INSERT TENANT NAME>/<<INSERT AP PROFILE NAME>') #Query the Tenant
dq1.queryTarget='children' #request all children from Tenant
Bridge_Domains = md.query(dq1) #Get list of Bridge Domains (VLANs)
IFPG_List=[]
temp='temp'
ifpg_check = re.compile("") #create regex for your own naming convention of IFPGs to filter children of AP profile

for bd in Bridge_Domains:
    dq2 = DnQuery('uni/<INSERT TENANT NAME>/<<INSERT AP PROFILE NAME>/epg-'+bd.name) #create query for each BD found with previous query
    dq2.queryTarget='children' #target children (static ports)
    dq2.subtreeClassFilter='fvRsPathAtt'
    StaticPorts = md.query(dq2) #Get Result
    for epg in StaticPorts:
        if re.findall(ifpg_check, str(epg.dn)): #Check if entry if InterFace Policy Group
            temp = re.findall(ifpg_check, str(epg.dn)) #Save IFPG if entry checks out
        if len(IFPG_List)==0:
            IFPG_List.append(temp)
        else:
Exemplo n.º 12
0
# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('uni/tn-' + args.tenantName + '/ap-' + args.apName +
                  '/epg-' + args.epgName)
dnQuery.queryTarget = 'children'
dnQuery.subtreeClassFilter = 'fvAEPg'
epgMo = moDir.query(dnQuery)
for epg in epgMo:
    #print epg.dn
    if isinstance(epg, CEp):
        if (args.macAddress):
            if (args.macAddress == epg.name):
                cepQuery = DnQuery(epg.dn)
                cepQuery.queryTarget = 'children'
                cepMo = moDir.query(cepQuery)
                for cep in cepMo:
                    print cep.dn
        else:
            #print epg.name
            cepQuery = DnQuery(epg.dn)
            cepQuery.queryTarget = 'children'
            cepMo = moDir.query(cepQuery)
Exemplo n.º 13
0
class CobraClient(object):
    def __init__(self, hosts, user, password, ssl, verify=False, request_timeout=90):
        protocol = 'https' if ssl else 'http'


        LOG.info(hosts)

        self.api_base = collections.deque(['%s://%s/api' % (protocol, host) for host in hosts])
        self.verify = verify
        self.timeout = 90
        self.user = user
        self.password = password
        self.login()

    def login(self):
        # TODO handle multiple hosts
        LOG.info("ACI Login")
        login_session = LoginSession(self.api_base[0], self.user, self.password)
        self.mo_dir = MoDirectory(login_session)
        self.mo_dir.login()

        LOG.info("Login session created, will expire at {} in {} seconds".format(login_session.refreshTime,login_session.refreshTimeoutSeconds))


    def logout(self):
        self.mo_dir.logout()

    def lookupByDn(self, dn):
        retries = 0
        while retries < RETRY_LIMIT:
            try:
                uni_mo = self.mo_dir.lookupByDn(dn)
                return uni_mo
            except SSLError as e:
                self._retry(retries, e)
            except QueryError  as e:
                LOG.info("Lookup to ACI failed due to {}:{} retrying {} of {}".format(e.error, e.reason,retries,RETRY_LIMIT))
                if e.error == 403:
                    self.mo_dir.login()
                    LOG.info("New login session created")
                    self._retry(retries, e)
                else:
                    raise e

    def commit(self, managed_objects):
        retries = 0
        while retries < RETRY_LIMIT:
            try:
                config_request = ConfigRequest()

                if isinstance(managed_objects, list):
                    for mos in managed_objects:
                        config_request.addMo(mos)
                else:
                    config_request.addMo(managed_objects)

                return self.mo_dir.commit(config_request)
            except SSLError as e:
                self._retry(retries, e)
            except CommitError  as e:
                LOG.info("Commit to ACI failed due to {}:{} retrying  {} of {}".format(e.error, e.reason, retries,RETRY_LIMIT))
                if e.error == 403:
                    self.mo_dir.login()
                    LOG.info("New login session created")
                    self._retry(retries, e)
                else:
                    raise e

    def _retry(self, retries, e):
        retries += 1
        if retries >= RETRY_LIMIT:
            raise e

    def mo_exists(self, dn):
        mo = self.lookupByDn(dn)
        return mo is not None

    def uni_mo(self):
        return self.lookupByDn('uni')

    def get_full_tenant(self,tenant_name):
        dnQ = DnQuery('uni/tn-{}'.format(tenant_name))
        dnQ.subtree = 'full'
        tenant = self.mo_dir.query(dnQ)

        if tenant:
            return tenant[0]

        return None

    def get_tenant(self,tenant_name):
        tenant_mo = Tenant(self.uni_mo(), tenant_name)
        if self.mo_exists(tenant_mo.dn):
            return tenant_mo

        return None

    def get_or_create_tenant(self, tenant_name):
        tenant_mo = Tenant(self.uni_mo(), tenant_name)

        if not self.mo_exists(tenant_mo.dn):
            LOG.info("Configured tenant {} is missing, creating it now".format(tenant_mo.dn))
            self.commit(tenant_mo)
        else:
            LOG.info("Using existing ACI tenant {}".format(tenant_mo.dn))

        return tenant_mo
Exemplo n.º 14
0
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

if args.domain:
    nodeAQuery = DnQuery('topology/pod-1/node-' + args.leafANumber + '/sys/vpc/inst')
    nodeAQuery.queryTarget = 'children'
    nodeAMo = moDir.query(nodeAQuery)
    for vpcDomain in nodeAMo:
        if isinstance(vpcDomain,Dom):
	    print "DomainId: " + str(vpcDomain.id)
	    print "PeerState: " + vpcDomain.peerSt
	    print "Role: " + vpcDomain.operRole + ' (operational), ' + vpcDomain.oldRole + ' (configured)'
	    vpcQuery = DnQuery(vpcDomain.dn)
	    vpcQuery.queryTarget = 'children'
	    vpcMo = moDir.query(vpcQuery)
	    #for vpcIf in vpcMo:
	#	print vpcIf.name

    nodeASysQuery = DnQuery('topology/pod-1/node-' + args.leafANumber + '/sys')
    nodeASysQuery.queryTarget = 'children'
    nodeASysMo = moDir.query(nodeASysQuery)
    #for nodeObj in nodeASysMo:
Exemplo n.º 15
0
parser = argparse.ArgumentParser(description="Lookup Static Path by EPG")
parser.add_argument('tenantName', help='tenant name')
parser.add_argument('apName', help='ap name')
parser.add_argument('epgName', help='EPG name')
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('uni/tn-' + args.tenantName + '/ap-' + args.apName +
                  '/epg-' + args.epgName)
dnQuery.queryTarget = 'children'
dnQuery.subtreeClassFilter = 'fvAEPg'
epgMo = moDir.query(dnQuery)
for epg in epgMo:
    #print epg.dn
    if isinstance(epg, AEPg):
        print 'AEPg'
    elif isinstance(epg, RsPathAtt):
        print str(epg.tDn) + ' ' + epg.encap + ' ' + epg.mode

moDir.logout()
Exemplo n.º 16
0
class cobra_apic_base:
    def __init__(self):
        self.session = None
        self.moDir = None
        self.configReq = None
        self.uniMo = None

    """ Authentication """
    def login(self, url, user, password):
        """
        Login to the APIC
        :param url:
        :param user:
        :param password:
        :return:
        """
        self.apic_url = url
        self.apic_user = user
        self.session = LoginSession(url, user, password)
        self.moDir = MoDirectory(self.session)
        self.moDir.login()
        self.configReq = ConfigRequest()
        self.uniMo = self.moDir.lookupByDn('uni')

    def logout(self):
        """
        Logout from the APIC
        :return:
        """
        self.moDir.logout()

    """ Commits """
    def commit(self, commit_object):
        """
        Commits object changes to controller
        :param commit_object:
        :return:
        """

        self.configReq = ConfigRequest()
        self.configReq.addMo(commit_object)
        self.moDir.commit(self.configReq)

    """ Queries """
    def query_child_objects(self, dn_query_name):
        """
        Retrieve the object using the dn and return all the children under it
        :param dn_query_name: dn of the management object
        :return:
        """
        dn_query = DnQuery(dn_query_name)
        dn_query.queryTarget = QUERY_TARGET_CHILDREN
        child_mos = self.moDir.query(dn_query)
        return child_mos

    """ Generic Deletes """
    def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive):
        """
        Travers a dn list and compare each member with a pattern. If there is a match that object will be removed.
        If recursive is true, the algorithm will also do a recursive look for the children of each object looking
        for the pattern: will stop only when there is no more children to look for.
        :param dn_object_list:
        :param dn_pattern:
        :param recursive:
        :return:
        """
        for dn_object in dn_object_list:
            if dn_pattern in str(dn_object.dn):
                try:
                    self.delete_by_dn(str(dn_object.dn))
                except CommitError as e:
                    print 'Could not delete ' + str(dn_object.dn) + ' -> ' + str(e)
            elif recursive:
                children = self.query_child_objects(dn_object.dn)
                if children is not None:
                    self.delete_dn_by_pattern(children, dn_pattern, recursive)

    def delete_by_dn(self, dn_name):
        """
        Retrieve a mo and it removes it from the APIC
        :param dn_name:
        :return:
        """
        dn_object = self.moDir.lookupByDn(dn_name)
        if dn_object is not None:
            dn_object.delete()
            self.commit(dn_object)

    """ Tenants """
    def create_tenant(self, tenant_name):
        """
        Creates a tenant and commit changes to controller
        :param tenant_name:
        :return:
        """
        fv_tenant_mo = Tenant(self.uniMo, tenant_name)
        self.commit(fv_tenant_mo)
        return fv_tenant_mo

    def delete_tenant(self, tenant_dn):
        """
        Deletes a tenant and commit changes to controller
        :param tenant_dn:
        :return:
        """
        self.delete_by_dn(tenant_dn)

    def get_all_tenants(self):
        """
        Searches all tenants within apic
        :return:
        """
        class_query = ClassQuery('fvTenant')
        tn_list = self.moDir.query(class_query)
        return tn_list

    """ Switch Profiles """
    def delete_switch_profile(self, switch_profile_name):
        """
        Deletes an access policy switch profile
        :param switch_profile_name:
        :return:
        """
        self.delete_by_dn('uni/infra/nprof-' + switch_profile_name)

    """ Bridge domains """
    def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props):
        """
        Creates a BD object. Creates a subnet for the default gateway if it is not None
        :param bd_name:
        :param tenant_dn:
        :param default_gw:
        :param creation_props:
        :return:
        """
        fv_bd_mo = BD(tenant_dn, bd_name, creation_props)
        self.commit(fv_bd_mo)
        if default_gw is not None and len(default_gw) > 0:
            fv_subnet_mo = Subnet(fv_bd_mo, default_gw)
            self.commit(fv_subnet_mo)
        return fv_bd_mo

    def delete_bd(self, bd_dn):
        """
        Removes a bridge domain
        :param bd_dn:
        :return:
        """
        self.delete_by_dn(bd_dn)

    def get_bds_by_tenant(self, tenant_dn):
        """
        Retrieve a list with all bridge domains under a tenant
        :param tenant_dn:
        :return:
        """
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class
        tn_children = self.query_child_objects(tenant_dn)
        return filter(lambda x: type(x).__name__ == 'BD', tn_children)

    def get_all_bds(self):
        """
        Returns a list of all bridge domains in the fabric
        :return:
        """
        class_query = ClassQuery('fvBD')
        bd_list = self.moDir.query(class_query)
        return bd_list

    """ Filters """
    def create_filter(self, tenant_dn, filter_name):
        """
        Creates a filter under a tenant
        :param tenant_dn:
        :param filter_name:
        :return:
        """
        vz_filter_mo = Filter(tenant_dn, filter_name)
        self.commit(vz_filter_mo)

    def delete_filter(self, filter_dn):
        """
        Removes a filter from the APIC
        :param filter_dn:
        :return:
        """
        self.delete_by_dn(filter_dn)

    def get_filters_by_tenant(self, tenant_dn):
        """
        Query the filters that are children of a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class
        return filter(lambda x: type(x).__name__ == 'Filter', tn_children)

    """ Contracts """
    def create_contract(self, tenant_dn, contract_name):
        """
        Creates a contract under a tenant
        :param tenant_dn:
        :param contract_name:
        :return:
        """
        vz_contract = BrCP(tenant_dn, contract_name)
        self.commit(vz_contract)

    def delete_contract(self, contract_dn):
        """
        Removes a contract from the APIC
        :param contract_dn:
        :return:
        """
        self.delete_by_dn(contract_dn)

    def get_contracts_by_tenant(self, tenant_dn):
        """
        Return a list with all the contracts under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class
        return filter(lambda x: type(x).__name__ == 'BrCP', tn_children)

    def assign_contract(self, epg_dn, provider_dn, consumer_dn):
        """
        Assign contracts to an end point group
        :param epg_dn:
        :param provider_dn: Provider contract
        :param consumer_dn: Consumer contract
        :return:
        """
        epg_mo = self.moDir.lookupByDn(epg_dn)
        if len(provider_dn) > 0:
            # Retrieve the provider contract
            provider_mo = self.moDir.lookupByDn(provider_dn)
            # Create the provider relationship with EPG
            rsprov_mo = RsProv(epg_mo, provider_mo.name)
            self.commit(rsprov_mo)
        if len(consumer_dn) > 0:
            # Retrieve the consumer contract
            consumer_mo = self.moDir.lookupByDn(consumer_dn)
            # Creates the consumer relationship with EPG
            rscons_mo = RsCons(epg_mo, consumer_mo.name)
            self.commit(rscons_mo)

    def delete_assign_contract(self, epg_dn):
        """
        Removes the EPG's assigned contracts
        :param epg_dn:
        :return:
        """
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsProv class
        epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn))
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsCons class
        epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn))
        # For each consumer and provider contract removes the relationship
        for provider in epg_providers:
            provider.delete()
            self.commit(provider)
        for consumer in epg_consumers:
            consumer.delete()
            self.commit(consumer)

    """ Subjects """
    def create_subject(self, filter_dn, contract_dn, subject_name):
        """
        Creates a subject between a contract and a filter
        :param filter_dn:
        :param contract_dn:
        :param subject_name:
        :return:
        """
        subject_dn = Subj(contract_dn, subject_name)
        self.commit(subject_dn)
        filter_mo = self.moDir.lookupByDn(filter_dn)
        rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name)
        self.commit(rs_filter_subject)

    def get_subjects_by_contract(self, contract_dn):
        """
        Returns all subject under a given contract
        :param contract_dn:
        :return:
        """
        contract_children = self.query_child_objects(contract_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class
        return filter(lambda x: type(x).__name__ == 'Subj', contract_children)

    def delete_subject(self, subject_dn):
        """
        Removes a subject from the APIC
        :param subject_dn:
        :return:
        """
        self.delete_by_dn(subject_dn)

    """ End Point Groups """
    def create_epg(self, ap_dn, bd_dn, epg_name):
        """
        Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG
        :param ap_dn: application profile to be used as parent
        :param bd_dn: bridge domain to be associated with the EPG
        :param epg_name:
        :return:
        """
        epg_mo = AEPg(ap_dn, epg_name)
        self.commit(epg_mo)
        if bd_dn is not None and len(bd_dn) > 0:
            # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd
            #  class. Choose the first one and assign it to the rsbd_mo variable
            rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0]
            # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG.
            # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object
            rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name
            self.commit(rsbd_mo)
        return epg_mo

    def delete_epg(self, epg_dn):
        """
        Removes an EPG from the APIC
        :param epg_dn:
        :return:
        """
        self.delete_by_dn(epg_dn)

    def get_epg_by_ap(self, ap_dn):
        """
        Returns a list of end point groups under an application profile
        :param ap_dn:
        :return:
        """
        ap_children = self.query_child_objects(ap_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class.
        return filter(lambda x: type(x).__name__ == 'AEPg', ap_children)

    """ Application Profiles """
    def create_ap(self, tenant_dn, ap_name):
        """
        Creates an application profile
        :param tenant_dn:
        :param ap_name:
        :return:
        """
        ap_mo = Ap(tenant_dn, ap_name)
        self.commit(ap_mo)
        return ap_mo

    def delete_ap(self, ap_dn):
        """
        Removes an application profile
        :param ap_dn:
        :return:
        """
        self.delete_by_dn(ap_dn)

    def get_ap_by_tenant(self, tenant_dn):
        """
        Returns a list of application profiles under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class.
        return filter(lambda x: type(x).__name__ == 'Ap', tn_children)

    def __repr__(self):
        return 'Connected to %s with userid: %s' % (self.apic_url, self.apic_user)
Exemplo n.º 17
0
from cobra.mit.session import CertSession
from cobra.mit.access import MoDirectory
from cobra.mit.request import ClassQuery

from requests.packages.urllib3 import disable_warnings
disable_warnings()


def readFile(fileName=None, mode="r"):
    if fileName is None:
        return ""
    fileData = ""
    with open(fileName, mode) as aFile:
        fileData = aFile.read()
    return fileData


pkey = readFile("cobra.key")
csession = CertSession("https://sandboxapicdc.cisco.com/",
                       "uni/userext/user-cobra/usercert-cobra", pkey)

modir = MoDirectory(csession)

cq = ClassQuery('fvTenant')
tenants = modir.query(cq)

for tenant in tenants:
    print tenant.name

modir.logout()
Exemplo n.º 18
0
import yaml
import argparse

parser = argparse.ArgumentParser(description="Display Physical Domain")
parser.add_argument('physName', help='physical domain name')
parser.add_argument('-e','--epg', help='wants epg', action="store_true")
parser.add_argument('-a','--aaep', help='wants AAeP', action="store_true")
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('uni/phys-' + args.physName)
dnQuery.queryTarget = 'children'
#dnQuery.subtreeClassFilter = 'fvAEPg'
physMo = moDir.query(dnQuery)
for obj in physMo:
    if args.epg and isinstance(obj,RtDomAtt):
	print obj.tDn
    if args.aaep and isinstance(obj,RtDomP):
	print obj.tDn

moDir.logout()
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...')
Exemplo n.º 20
0
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('topology/pod-1/paths-' + args.leafNumber)
dnQuery.queryTarget = 'children'
#dnQuery.subtreeClassFilter = 'fvAEPg'
leafMo = moDir.query(dnQuery)
for obj in leafMo:
    if obj.pathT == 'leaf':
        if obj.lagT != 'node':
            #print obj.dn
            intfL2Pol = 'default'
            intfPC = ''
            intQuery = DnQuery('topology/pod-1/node-' + args.leafNumber +
                               '/sys/phys-[' + obj.name + ']')
            intQuery.queryTarget = 'children'
            intMo = moDir.query(intQuery)
            for intAttr in intMo:
                if isinstance(intAttr, PhysIf):
                    #print obj.name, '\t',
                    if intAttr.operSt == "link-up":
                        operState = intAttr.operStQual
Exemplo n.º 21
0
    new_epg = AEPg(application_profile, "vmepg")

    # Committing the changes
    config_request = ConfigRequest()
    config_request.addMo(new_epg)

    moDir.commit(config_request)

    # Enter epg to use as template for vmepg
    epg_template = "default"

    dnQuery = DnQuery('uni/tn-{0}/ap-{1}/epg-{2}'.format(
        tenant, ap, epg_template))
    dnQuery.subtree = 'children'
    epgMO = moDir.query(dnQuery)

    # Traversing every property within epg_template and copying it to vmepg
    for epg in epgMO:
        for epgChild in epg.children:
            for name, obj in inspect.getmembers(sys.modules[__name__]):
                if inspect.isclass(obj):
                    copy_of_property = str(epgChild.rn)
                    if (copy_of_property.lower().startswith(
                            obj.__name__.lower())):
                        exec("object_made = " + obj.__name__ + "(epg, \"" +
                             copy_of_property + "\")")

                        config_request.addMo(object_made)
                        moDir.commit(config_request)
        print 'Usage: apic_show-mac-address.py <hostname> <username> <password> <mac-address>'
        sys.exit()
    else:
        hostname, username, password, macaddress = sys.argv[1:]
        url = 'https://' + hostname
        print "Logging on APIC..."

        try:
            #
            lls = LoginSession(url, username, password, secure=False)
            md = MoDirectory(lls)
            md.login()
            q = ClassQuery('fvCEp')
            q.subtree = 'children'
            q.subtreeClassFilter = 'fvRsCEpToPathEp'
            mos = md.query(q)

            #Other variables
            hasmacaddress = False
            epglists = {}
            i = -1
        
            ## Verifying all mac address:
            for mo in mos:
                for child in mo.rscEpToPathEp:
                       line = str(child.dn)
                       i = i + 1
                       if (macaddress in line):
                           hasmacaddress = True
                           epglists[i] = line
Exemplo n.º 23
0
from cobra.mit.access import MoDirectory
from cobra.mit.session import LoginSession
from cobra.mit.access import DnQuery
from cobra.model.fv import Tenant, Ctx, BD, RsCtx, Ap, AEPg, RsBd, RsDomAtt

apicUrl = 'https://172.16.31.36'
loginSession = LoginSession(apicUrl, 'admin', 'Tel1dus!')
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('uni/tn-LAN01')
dnQuery.subtree = 'children'
tenantMo = moDir.query(dnQuery)
for obj in tenantMo:
    print obj.dn
    for _BD in obj.BD:
        print _BD.dn
    for _app in obj.AP:
        print _app.dn
moDir.logout()
# APIC Credentials
APIC_IP = parser.get('ACI', 'IP')
APIC_Username = parser.get('ACI', 'username')
APIC_Password = parser.get('ACI', 'password')
APIC_Proto = parser.get('ACI', 'protocol')
EPGs = parser.get('ACI', 'EPG_list').split()
os.environ['no_proxy'] = APIC_IP

Login_Session = LoginSession(APIC_Proto + '://' + APIC_IP, APIC_Username,
                             APIC_Password)
moDir = MoDirectory(Login_Session)
moDir.login()

fabric_health = []
getInfo = ClassQuery('fabricHealthTotal')
FabricHealth = moDir.query(getInfo)
for obj in FabricHealth:
    if str(obj.dn) == "topology/health":
        fabric_health.append({"Global": int(obj.cur)})
    else:
        fabric_health.append({
            str(obj.dn).replace("topology/", "").replace("/health", ""):
            int(obj.cur)
        })

EPGs_health = []
for EPG_dn in EPGs:
    getInfo = DnQuery('uni/' + EPG_dn + '/health')
    EPGHealth = moDir.query(getInfo)
    for obj in EPGHealth:
        # I only keep EPG name, to avoid a long string in the dashboard...
Exemplo n.º 25
0
    # Making a new epg and calling it "vmepg"
    application_profile = moDir.lookupByDn("uni/tn-{0}/ap-{1}".format(tenant, ap))

    new_epg = AEPg(application_profile, "vmepg")

    # Committing the changes
    config_request = ConfigRequest()
    config_request.addMo(new_epg)

    moDir.commit(config_request)

    # Enter epg to use as template for vmepg
    epg_template= "default"

    dnQuery = DnQuery('uni/tn-{0}/ap-{1}/epg-{2}'.format(tenant, ap, epg_template))
    dnQuery.subtree = 'children'
    epgMO = moDir.query(dnQuery)

    # Traversing every property within epg_template and copying it to vmepg
    for epg in epgMO:
        for epgChild in epg.children:
            for name, obj in inspect.getmembers(sys.modules[__name__]):
                if inspect.isclass(obj):
                    copy_of_property = str(epgChild.rn)
                    if (copy_of_property.lower().startswith(obj.__name__.lower())):
                        exec("object_made = " + obj.__name__ + "(epg, \"" + copy_of_property + "\")")

                        config_request.addMo(object_made)
                        moDir.commit(config_request)
Exemplo n.º 26
0
parser = argparse.ArgumentParser(description="Display Interface Profile")
parser.add_argument('intProfName', help='interface profile name')
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('uni/infra/accportprof-' + args.intProfName)
dnQuery.queryTarget = 'children'
#dnQuery.subtreeClassFilter = 'fvAEPg'
physMo = moDir.query(dnQuery)
for obj in physMo:
    if isinstance(obj, HPortS):
        objQuery = DnQuery(obj.dn)
        objQuery.queryTarget = 'children'
        portsMo = moDir.query(objQuery)
        for ports in portsMo:
            if isinstance(ports, PortBlk):
                print ports.fromCard + '/' + ports.fromPort + '-' + ports.toPort
    if isinstance(obj, RtAccPortP):
        print obj.dn

moDir.logout()
        # Create EPGs
        for epg in app['epgs']:

            print("Creating EPG: %s..." % (epg['name']))
            fvAEPgMo = AEPg(fvApMo, epg['name'])

            # Associate EPG to Bridge Domain
            RsBd(fvAEPgMo, tnFvBDName=tenant['bd'])

    # Commit each tenant separately
    tenantCfg = ConfigRequest()
    tenantCfg.addMo(fvTenantMo)
    moDir.commit(tenantCfg)
print('All tenants created.\n**')

print("Get the tenants by class.\n**")
tnQuery = ClassQuery('fvTenant')
tnMos = moDir.query(tnQuery)
for tnMo in tnMos:
    print(tnMo.dn)

print("Get the tenants by DN and delete them.\n**")
for tenant in TENANT_INFO:
    tnMo = moDir.lookupByDn('uni/tn-{0}'.format(tenant['name']))
    print(tnMo.name)
    print("Deleting tenant %s.." % (tenant['name']))
    tnMo.delete()
    tenantCfg = ConfigRequest()
    tenantCfg.addMo(tnMo)
    moDir.commit(tenantCfg)
Exemplo n.º 28
0
def home():
    with open("/home/app/data/logs.txt", "a") as log_file:
        log_file.write("==================================================" + "\n")
        log_file.write("Received API Request from Client. Sending Response" + "\n")
        log_file.write("==================================================" + "\n")

    reply = None
    try:
        apicUrl = 'https://172.17.0.1/'
        loginSession = createCertSession()
    

        #loginSession = cobra.mit.session.LoginSession('https://10.22.47.171', 'admin', 'ins3965!')
        moDir = MoDirectory(loginSession)
        moDir.login()

        tableList = []
        #row =  ('TN', 'AP/L2OUT', 'EPG/InstP', 'CEP', 'IP', 'Type', 'PATH', 'PORT', 'POD', 'ENCAP', 'BD:CTX')
        #tableList.append(row)
        try:
            row ={}
            q = ClassQuery('fvCEp')
            q.subtree = 'children'
            tenantMo = moDir.query(q)
        except cobra.mit.request.QueryError as e:
            log('Reason: ' + e.reason)
            log('Error: ' + e.error)
            log('HTTP code: ' + e.httpCode)
            log(traceback.format_exc())

        data = {}

        for mo in tenantMo:
            for child in mo.rscEpToPathEp:
                #print child.dn
                ip = mo.ip

                tn, ap, epg, cep, varPod, varStrPath, varStrPort = tDnToPath(child.dn)
                if 'protpaths' in child.tDn: portType = 'vPC'
                elif 'paths' in child.tDn and 'eth' in child.tDn: portType = '-'
                else: portType = 'PC'
                encap = (mo.encap).split('-')[1]

                #if args.macSearch: bd,ctx = getAncestorDnStrFromDnString(md, str(mo.dn), 1)
                #else: bd='-'; ctx='-'
                bd='-'; ctx='-'

                #row = (tn,ap,epg,cep,mo.ip,portType,varStrPath,varStrPort,varPod,encap,'%s:%s' %(bd,ctx))
                row = {
                    "tn": tn,
                    "ap/l2out":ap,
                    "epg":epg,
                    "cep":cep,
                    "ip":mo.ip,
                    "type":portType,
                    "path":varStrPath,
                    "port":varStrPort,
                    "pod":varPod,
                    "encap":encap,
                    "bd":"-:-"
                }
                tableList.append(row)

                #data[child.tDn]= row
        moDir.logout()
        #print json.dumps(data)
        #return render_template('home.html', table=tableList)
        #return respFormatJsonMos(data, len(data))
        log(tableList)
        reply = jsonify({'results': tableList})

    except Exception as e:
        log(traceback.format_exc())

    return reply
Exemplo n.º 29
0
class apic_base:
    def __init__(self):
        self.session = None
        self.moDir = None
        self.configReq = None
        self.uniMo = None

    """ Authentication """
    def login(self, url, user, password):
        """
        Login to the APIC
        :param url:
        :param user:
        :param password:
        :return:
        """
        self.session = LoginSession(url, user, password)
        self.moDir = MoDirectory(self.session)
        self.moDir.login()
        self.configReq = ConfigRequest()
        self.uniMo = self.moDir.lookupByDn('uni')

    def logout(self):
        """
        Logout from the APIC
        :return:
        """
        self.moDir.logout()

    """ Commits """
    def commit(self, commit_object):
        """
        Commits object changes to controller
        :param commit_object:
        :return:
        """

        self.configReq = ConfigRequest()
        self.configReq.addMo(commit_object)
        self.moDir.commit(self.configReq)

    """ Queries """
    def query_child_objects(self, dn_query_name):
        """
        Retrieve the object using the dn and return all the children under it
        :param dn_query_name: dn of the management object
        :return:
        """
        dn_query = DnQuery(dn_query_name)
        dn_query.queryTarget = QUERY_TARGET_CHILDREN
        child_mos = self.moDir.query(dn_query)
        return child_mos

    """ Generic Deletes """
    def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive):
        """
        Travers a dn list and compare each member with a pattern. If there is a match that object will be removed.
        If recursive is true, the algorithm will also do a recursive look for the children of each object looking
        for the pattern: will stop only when there is no more children to look for.
        :param dn_object_list:
        :param dn_pattern:
        :param recursive:
        :return:
        """
        for dn_object in dn_object_list:
            if dn_pattern in str(dn_object.dn):
                try:
                    self.delete_by_dn(str(dn_object.dn))
                except CommitError as e:
                    print 'Could not delete ' + str(dn_object.dn) + ' -> ' + str(e)
            elif recursive:
                children = self.query_child_objects(dn_object.dn)
                if children is not None:
                    self.delete_dn_by_pattern(children, dn_pattern, recursive)

    def delete_by_dn(self, dn_name):
        """
        Retrieve a mo and it removes it from the APIC
        :param dn_name:
        :return:
        """
        dn_object = self.moDir.lookupByDn(dn_name)
        if dn_object is not None:
            dn_object.delete()
            self.commit(dn_object)

    """ Tenants """
    def create_tenant(self, tenant_name):
        """
        Creates a tenant and commit changes to controller
        :param tenant_name:
        :return:
        """
        fv_tenant_mo = Tenant(self.uniMo, tenant_name)
        self.commit(fv_tenant_mo)
        return fv_tenant_mo

    def delete_tenant(self, tenant_dn):
        """
        Deletes a tenant and commit changes to controller
        :param tenant_dn:
        :return:
        """
        self.delete_by_dn(tenant_dn)

    def get_all_tenants(self):
        """
        Searches all tenants within apic
        :return:
        """
        class_query = ClassQuery('fvTenant')
        tn_list = self.moDir.query(class_query)
        return tn_list

    """ Switch Profiles """
    def delete_switch_profile(self, switch_profile_name):
        """
        Deletes an access policy switch profile
        :param switch_profile_name:
        :return:
        """
        self.delete_by_dn('uni/infra/nprof-' + switch_profile_name)

    """ Bridge domains """
    def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props):
        """
        Creates a BD object. Creates a subnet for the default gateway if it is not None
        :param bd_name:
        :param tenant_dn:
        :param default_gw:
        :param creation_props:
        :return:
        """
        fv_bd_mo = BD(tenant_dn, bd_name, creation_props)
        self.commit(fv_bd_mo)
        if default_gw is not None and len(default_gw) > 0:
            fv_subnet_mo = Subnet(fv_bd_mo, default_gw)
            self.commit(fv_subnet_mo)
        return fv_bd_mo

    def delete_bd(self, bd_dn):
        """
        Removes a bridge domain
        :param bd_dn:
        :return:
        """
        self.delete_by_dn(bd_dn)

    def get_bds_by_tenant(self, tenant_dn):
        """
        Retrieve a list with all bridge domains under a tenant
        :param tenant_dn:
        :return:
        """
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class
        tn_children = self.query_child_objects(tenant_dn)
        return filter(lambda x: type(x).__name__ == 'BD', tn_children)

    def get_all_bds(self):
        """
        Returns a list of all bridge domains in the fabric
        :return:
        """
        class_query = ClassQuery('fvBD')
        bd_list = self.moDir.query(class_query)
        return bd_list

    """ Filters """
    def create_filter(self, tenant_dn, filter_name):
        """
        Creates a filter under a tenant
        :param tenant_dn:
        :param filter_name:
        :return:
        """
        vz_filter_mo = Filter(tenant_dn, filter_name)
        self.commit(vz_filter_mo)

    def delete_filter(self, filter_dn):
        """
        Removes a filter from the APIC
        :param filter_dn:
        :return:
        """
        self.delete_by_dn(filter_dn)

    def get_filters_by_tenant(self, tenant_dn):
        """
        Query the filters that are children of a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class
        return filter(lambda x: type(x).__name__ == 'Filter', tn_children)

    """ Contracts """
    def create_contract(self, tenant_dn, contract_name):
        """
        Creates a contract under a tenant
        :param tenant_dn:
        :param contract_name:
        :return:
        """
        vz_contract = BrCP(tenant_dn, contract_name)
        self.commit(vz_contract)

    def delete_contract(self, contract_dn):
        """
        Removes a contract from the APIC
        :param contract_dn:
        :return:
        """
        self.delete_by_dn(contract_dn)

    def get_contracts_by_tenant(self, tenant_dn):
        """
        Return a list with all the contracts under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class
        return filter(lambda x: type(x).__name__ == 'BrCP', tn_children)

    def assign_contract(self, epg_dn, provider_dn, consumer_dn):
        """
        Assign contracts to an end point group
        :param epg_dn:
        :param provider_dn: Provider contract
        :param consumer_dn: Consumer contract
        :return:
        """
        epg_mo = self.moDir.lookupByDn(epg_dn)
        if len(provider_dn) > 0:
            # Retrieve the provider contract
            provider_mo = self.moDir.lookupByDn(provider_dn)
            # Create the provider relationship with EPG
            rsprov_mo = RsProv(epg_mo, provider_mo.name)
            self.commit(rsprov_mo)
        if len(consumer_dn) > 0:
            # Retrieve the consumer contract
            consumer_mo = self.moDir.lookupByDn(consumer_dn)
            # Creates the consumer relationship with EPG
            rscons_mo = RsCons(epg_mo, consumer_mo.name)
            self.commit(rscons_mo)

    def delete_assign_contract(self, epg_dn):
        """
        Removes the EPG's assigned contracts
        :param epg_dn:
        :return:
        """
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsProv class
        epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn))
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsCons class
        epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn))
        # For each consumer and provider contract removes the relationship
        for provider in epg_providers:
            provider.delete()
            self.commit(provider)
        for consumer in epg_consumers:
            consumer.delete()
            self.commit(consumer)

    """ Subjects """
    def create_subject(self, filter_dn, contract_dn, subject_name):
        """
        Creates a subject between a contract and a filter
        :param filter_dn:
        :param contract_dn:
        :param subject_name:
        :return:
        """
        subject_dn = Subj(contract_dn, subject_name)
        self.commit(subject_dn)
        filter_mo = self.moDir.lookupByDn(filter_dn)
        rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name)
        self.commit(rs_filter_subject)

    def get_subjects_by_contract(self, contract_dn):
        """
        Returns all subject under a given contract
        :param contract_dn:
        :return:
        """
        contract_children = self.query_child_objects(contract_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class
        return filter(lambda x: type(x).__name__ == 'Subj', contract_children)

    def delete_subject(self, subject_dn):
        """
        Removes a subject from the APIC
        :param subject_dn:
        :return:
        """
        self.delete_by_dn(subject_dn)

    """ End Point Groups """
    def create_epg(self, ap_dn, bd_dn, epg_name):
        """
        Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG
        :param ap_dn: application profile to be used as parent
        :param bd_dn: bridge domain to be associated with the EPG
        :param epg_name:
        :return:
        """
        epg_mo = AEPg(ap_dn, epg_name)
        self.commit(epg_mo)
        if bd_dn is not None and len(bd_dn) > 0:
            # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd
            #  class. Choose the first one and assign it to the rsbd_mo variable
            rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0]
            # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG.
            # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object
            rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name
            self.commit(rsbd_mo)
        return epg_mo

    def delete_epg(self, epg_dn):
        """
        Removes an EPG from the APIC
        :param epg_dn:
        :return:
        """
        self.delete_by_dn(epg_dn)

    def get_epg_by_ap(self, ap_dn):
        """
        Returns a list of end point groups under an application profile
        :param ap_dn:
        :return:
        """
        ap_children = self.query_child_objects(ap_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class.
        return filter(lambda x: type(x).__name__ == 'AEPg', ap_children)

    """ Application Profiles """
    def create_ap(self, tenant_dn, ap_name):
        """
        Creates an application profile
        :param tenant_dn:
        :param ap_name:
        :return:
        """
        ap_mo = Ap(tenant_dn, ap_name)
        self.commit(ap_mo)
        return ap_mo

    def delete_ap(self, ap_dn):
        """
        Removes an application profile
        :param ap_dn:
        :return:
        """
        self.delete_by_dn(ap_dn)

    def get_ap_by_tenant(self, tenant_dn):
        """
        Returns a list of application profiles under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class.
        return filter(lambda x: type(x).__name__ == 'Ap', tn_children)
Exemplo n.º 30
0
from cobra.mit.access import DnQuery
from cobra.model.fv import Tenant, Ctx, BD, RsCtx, Ap, AEPg, RsBd, RsDomAtt, RsPathAtt
from cobra.model.top import System
import yaml
import argparse

parser = argparse.ArgumentParser(description="Display Leaf")
parser.add_argument('leafNumber', help='leaf number')
args = parser.parse_args()

# open yaml files
f = open('credentials.yaml', 'r')
credentials = yaml.load(f)
f.close()

apicUrl = credentials['host']
loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass'])
moDir = MoDirectory(loginSession)
moDir.login()

dnQuery = DnQuery('topology/pod-1/node-' + args.leafNumber)
dnQuery.queryTarget = 'children'
#dnQuery.subtreeClassFilter = 'fvAEPg'
leafMo = moDir.query(dnQuery)
for obj in leafMo:
    if isinstance(obj, System):
        print obj.name + ' ' + obj.serial + ' ' + obj.role + ' ' + obj.state + ' ' + str(
            obj.systemUpTime)

moDir.logout()