Esempio n. 1
0
 def test_ConfigRequest_getUrl(self, sessionUrl, mo, requestType):
     session = LoginSession(sessionUrl, 'admin', 'password',
                            requestFormat=requestType)
     expected = sessionUrl + '/api/mo/' + str(mo.dn) + '.' + requestType
     cr = ConfigRequest()
     cr.addMo(mo)
     assert cr.getUrl(session) == expected
Esempio n. 2
0
 def test_ConfigRequest_getUrl(self, sessionUrl, mo, requestType):
     session = LoginSession(sessionUrl, 'admin', 'password',
                            requestFormat=requestType)
     expected = sessionUrl + '/api/mo/' + str(mo.dn) + '.' + requestType
     cr = ConfigRequest()
     cr.addMo(mo)
     assert cr.getUrl(session) == expected
Esempio n. 3
0
 def test_ConfigRequest_requestargs(self):
     expected1 = {
                    'data': '<?xml version="1.0" encoding="UTF-8"?>\n' +
                            '<fvTenant name=\'testing\' ' +
                            'status=\'created,modified\'></fvTenant>',
                    'headers': {
                        'Cookie': 'APIC-cookie=None'
                    },
                    'timeout': 90,
                    'verify': False
                }
     expected2 = {
                    'data': '<?xml version="1.0" encoding="UTF-8"?>\n' +
                            '<fvTenant status=\'created,modified\' ' +
                            'name=\'testing\'></fvTenant>',
                    'headers': {
                        'Cookie': 'APIC-cookie=None'
                    },
                    'timeout': 90,
                    'verify': False
                }
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'testing')
     session = LoginSession('http://1.1.1.1', 'admin', 'password')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert (cr.requestargs(session) == expected1 or
             cr.requestargs(session) == expected2)
 def test_post_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)
     uni = Uni('')
     fvTenant = Tenant(uni, name='t')
     fvBD = BD(fvTenant, 't-bd')
     fvAp = Ap(fvTenant, 't-app')
     cr = ConfigRequest()
     #cr.subtree = 'full'
     cr.addMo(fvTenant)
     if userobject.user == 'rouser':
         with pytest.raises(RestError) as excinfo:
             r = moDir.commit(cr)
         assert ((excinfo.value.reason == ('user rouser does not have ' +
                                           'domain access to config Mo, ' +
                                           'class fvTenant')) or
                 (excinfo.value.reason == ('user rouser does not have ' +
                                           'domain access to config Mo, ' +
                                           'class fvBD')))
     elif userobject.user == 'rwuser':
         r = moDir.commit(cr)
     else:
         raise NotImplementedError
Esempio n. 5
0
def create_tenant(logon_session,
                  tenant_name="Example_TN",
                  description="Description"):

    from cobra.internal.codec.jsoncodec import toJSONStr
    from cobra.model.fv import Tenant, RsTenantMonPol
    from cobra.mit.request import ConfigRequest
    import cobra.model.pol
    import cobra.model.vns
    c = ConfigRequest()
    #apic_logon(apic_url, user, password)
    polUni = cobra.model.pol.Uni('')

    fvTenant = Tenant(polUni,
                      ownerKey=u'',
                      name=tenant_name,
                      descr=description,
                      nameAlias=tenant_name,
                      ownerTag=u'',
                      annotation=u'')
    vnsSvcCont = cobra.model.vns.SvcCont(fvTenant, annotation=u'')
    fvRsTenantMonPol = RsTenantMonPol(fvTenant,
                                      annotation=u'',
                                      tnMonEPGPolName=u'')

    tenant_data = toJSONStr(polUni)

    c.addMo(polUni)
    logon_session.commit(c)
    return tenant_data
Esempio n. 6
0
 def test_ConfigRequest_addMo_raises_not_allowed_context(self):
     fvTenant = Tenant('uni', 'testing')
     fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     with pytest.raises(ValueError):
         cr.addMo(fvnsVlanInstP)
Esempio n. 7
0
def create_bridge_domains(delete=''):
    bd_df = pd.read_excel("input-data/ACI_DD_Workbook.xlsx",
                          sheet_name='Bridge_Domains')
    file = open("BD_Configuration.log", "w")
    logon = apic_logon()
    uniMo = logon.lookupByDn('uni')
    for index, row in bd_df.iterrows():
        fvTenant = Tenant(uniMo, row['Tenant'])
        if delete == 'yes':
            fvBD = BD(fvTenant, name=row['Name'], status='deleted')
        else:
            fvBD = BD(fvTenant,
                      name=row['Name'],
                      arpFlood=row['ARP Flood'],
                      ipLearning=row['EP_learn'],
                      description=row['Description'],
                      multiDstPktAct=row['MultiDest_Flood'],
                      mcastAllow=row['mcastAllow'],
                      unkMcastAct=row['L3Unk_Mcast'],
                      limitIpLearnToSubnets=row['Limit_IP_Learn'])
            fvRsCtx = RsCtx(fvBD, tnFvCtxName=row['VRF'])
            if pd.isnull(row['L3O']) == False:
                fvRsBDToOut = RsBDToOut(fvBD, tnL3extOutName=row['L3O'])
        cfgRequest = ConfigRequest()
        cfgRequest.addMo(fvBD)
        logon.commit(cfgRequest)
        json_data = toJSONStr(fvBD, prettyPrint=True)
        file.write(
            '\n-------------------------------------------------------------------\n'
        )
        file.write(json_data)
    file.close()
Esempio n. 8
0
 def test_ConfigRequest_options(self):
     cid = '1234567890'
     expectedOptions = ''
     cr =  ConfigRequest()
     cr.id = cid
     expectedOptions += '_dc=' + cid
     assert cr.options == expectedOptions
Esempio n. 9
0
def create_apn(logon_session,
               tenant_name="Example_TN",
               description="Description",
               ap_name=''):

    from cobra.internal.codec.jsoncodec import toJSONStr
    from cobra.model.fv import Tenant, RsTenantMonPol, Ap
    from cobra.mit.request import ConfigRequest
    import cobra.model.pol
    import cobra.model.vns
    c = ConfigRequest()
    #apic_logon(apic_url, user, password)
    polUni = cobra.model.pol.Uni('')

    fvTenant = Tenant(polUni, tenant_name)

    # build the request using cobra syntax
    fvAp = Ap(fvTenant,
              ownerKey=u'',
              name=ap_name,
              descr=description,
              nameAlias=u'',
              ownerTag=u'',
              prio=u'unspecified',
              annotation=u'')

    apn_data = toJSONStr(polUni)

    c.addMo(polUni)
    logon_session.commit(c)
    return apn_data
Esempio n. 10
0
def create_contracts(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')
    fv_tenant = Tenant(policy_universe, tenant_name)

    # create Contract for web
    vz_ct_web = BrCP(fv_tenant, CONTRACT_WEB_CT)
    vz_subj_web = Subj(vz_ct_web, 'Web')
    vz_rs_subj_filt_att_web = RsSubjFiltAtt(vz_subj_web, 'http')

    #create contract for App
    vz_ct_app = BrCP(fv_tenant, CONTRACT_APP_CT)
    vz_subj_rmi = Subj(vz_ct_app, 'RMI')
    vz_rs_subj_filt_att_rmi = RsSubjFiltAtt(vz_subj_rmi, 'rmi')

    # create filter for sql
    vz_ct_db = BrCP(fv_tenant, CONTRACT_DB_CT)
    vz_subj_db = Subj(vz_ct_db, 'DbCt')
    vz_rs_subj_filt_att_db = RsSubjFiltAtt(vz_subj_db, 'sql')

    # print the query in XML format
    print toXMLStr(policy_universe, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 11
0
 def test_ConfigRequest_options(self):
     cid = '1234567890'
     expectedOptions = ''
     cr =  ConfigRequest()
     cr.id = cid
     expectedOptions += '_dc=' + cid
     assert cr.options == expectedOptions
Esempio n. 12
0
def create_contracts(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')
    fv_tenant = Tenant(policy_universe, tenant_name)

    # create Contract for web
    vz_ct_web = BrCP(fv_tenant, CONTRACT_WEB_CT)
    vz_subj_web = Subj(vz_ct_web, 'Web')
    vz_rs_subj_filt_att_web = RsSubjFiltAtt(vz_subj_web, 'http')

    #create contract for App
    vz_ct_app = BrCP(fv_tenant, CONTRACT_APP_CT)
    vz_subj_rmi = Subj(vz_ct_app, 'RMI')
    vz_rs_subj_filt_att_rmi = RsSubjFiltAtt(vz_subj_rmi, 'rmi')

    # create filter for sql
    vz_ct_db = BrCP(fv_tenant, CONTRACT_DB_CT)
    vz_subj_db = Subj(vz_ct_db, 'DbCt')
    vz_rs_subj_filt_att_db = RsSubjFiltAtt(vz_subj_db, 'sql')

    # print the query in XML format
    print toXMLStr(policy_universe, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 13
0
def vpc_policy(host, user, password):
    print('[BEG] VPC Configuration')
    moDir = apic_login(host, user, password)

    polUni = Uni('')
    fabricInst = Inst(polUni)

    print('--- Creating VPC Domain')

    VPCdID = '20'
    SW1 = '103'
    SW2 = '104'

    fabricProtPol = ProtPol(fabricInst, pairT=u'explicit', name=u'default')
    fabricExplicitGEp = ExplicitGEp(fabricProtPol,
                                    id=VPCdID,
                                    name=u'VPC-Cobra-Policy')
    fabricRsVpcInstPol = RsVpcInstPol(fabricExplicitGEp,
                                      tnVpcInstPolName=u'default')
    print('--- Assigning LEAF Switches - Node' + SW1 + ' Node' + SW2 +
          ' to Domain ID:' + VPCdID)
    fabricNodePEp = NodePEp(fabricExplicitGEp, id=SW1)
    fabricNodePEp2 = NodePEp(fabricExplicitGEp, id=SW2)

    tenantCfg = ConfigRequest()
    tenantCfg.addMo(fabricInst)
    moDir.commit(tenantCfg)
    print('[END] VPC Configuration \n')
Esempio n. 14
0
def conf_NTP(modir , ntp_list):
    '''
    Function that iterates through ntp_list and creates JSON call to configure NTP providers.
    The first NTP server in ntp_list will be the prefered NTP provider.
    '''
    topDn = cobra.mit.naming.Dn.fromString('uni/fabric/time-Best_NTP_Policy')
    topParentDn = topDn.getParent()
    topMo = modir.lookupByDn(topParentDn)
    datetimePol = cobra.model.datetime.Pol(topMo, ownerKey=u'', name=u'Best_NTP_Policy', descr=u'Scripted NTP_Config', adminSt=u'enabled', ownerTag=u'')
    ntp_servers_dict={}
    ntp_prov_dict={}

    for x in range(len(ntp_list)):
        if x == 1:
            ntp_servers_dict['ntp_server_%02d' % x] = cobra.model.datetime.NtpProv(datetimePol, name=ntp_list[x], preferred=u'true')
            ntp_prov_dict['ntp_prov_%02d' % x] = cobra.model.datetime.RsNtpProvToEpg(ntp_servers_dict['ntp_server_%02d' % x], tDn=u'uni/tn-mgmt/mgmtp-default/oob-default')
        else:
            ntp_servers_dict['ntp_server_%02d' % x] = cobra.model.datetime.NtpProv(datetimePol, name=ntp_list[x])
            ntp_prov_dict['ntp_prov_%02d' % x] = cobra.model.datetime.RsNtpProvToEpg(ntp_servers_dict['ntp_server_%02d' % x], tDn=u'uni/tn-mgmt/mgmtp-default/oob-default')


    print toXMLStr(topMo)
    c = ConfigRequest()
    c.addMo(topMo)
    modir.commit(c)
Esempio n. 15
0
 def test_post_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)
     uni = Uni('')
     fvTenant = Tenant(uni, name='t')
     fvBD = BD(fvTenant, 't-bd')
     fvAp = Ap(fvTenant, 't-app')
     cr = ConfigRequest()
     #cr.subtree = 'full'
     cr.addMo(fvTenant)
     if userobject.user == 'rouser':
         with pytest.raises(RestError) as excinfo:
             r = moDir.commit(cr)
         assert excinfo.value.reason == ('user rouser does not have ' +
                                         'domain access to config Mo, ' +
                                         'class fvTenant')
     elif userobject.user == 'rwuser':
         r = moDir.commit(cr)
     else:
         raise NotImplementedError
Esempio n. 16
0
def createTenant(md, tn, desc):
    uniMo = md.lookupByDn('uni')
    fvTenantMo = Tenant(uniMo, name=tn, descr=desc)

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(fvTenantMo)
    md.commit(cfgRequest)
Esempio n. 17
0
def create_vrfs(delete=''):
    vrf_df = pd.read_excel("input-data/ACI_DD_Workbook.xlsx",
                           sheet_name='VRFs')
    file = open("VRF_Configuration.log", "w")
    logon = apic_logon()
    uniMo = logon.lookupByDn('uni')
    for index, row in vrf_df.iterrows():
        fvTenant = Tenant(uniMo, row['Tenant'])
        if delete == 'yes':
            fvCtx = Ctx(fvTenant, name=row['Name'], status='deleted')
        else:

            fvCtx = Ctx(fvTenant,
                        name=row['Name'],
                        pcEnfDir=row['Enforcement Direction'],
                        pcEndPref=row['Enforcement'],
                        description=row['Description'])
        cfgRequest = ConfigRequest()
        cfgRequest.addMo(fvCtx)
        logon.commit(cfgRequest)
        json_data = toJSONStr(fvCtx, prettyPrint=True)
        file.write(
            '\n-------------------------------------------------------------------\n'
        )
        file.write(json_data)
    file.close()
Esempio n. 18
0
 def test_ConfigRequest_requestargs(self):
     expected1 = {
                    'data': '<?xml version="1.0" encoding="UTF-8"?>\n' +
                            '<fvTenant name=\'testing\' ' +
                            'status=\'created,modified\'></fvTenant>',
                    'headers': {
                        'Cookie': 'APIC-cookie=None'
                    },
                    'timeout': 90,
                    'verify': False
                }
     expected2 = {
                    'data': '<?xml version="1.0" encoding="UTF-8"?>\n' +
                            '<fvTenant status=\'created,modified\' ' +
                            'name=\'testing\'></fvTenant>',
                    'headers': {
                        'Cookie': 'APIC-cookie=None'
                    },
                    'timeout': 90,
                    'verify': False
                }
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'testing')
     session = LoginSession('http://1.1.1.1', 'admin', 'password')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert (cr.requestargs(session) == expected1 or
             cr.requestargs(session) == expected2)
Esempio n. 19
0
def createVRF(md, tn, vrfname, desc):
    tenant = 'uni/tn-' + tn
    uniMo = md.lookupByDn(tenant)
    fvCtxMo = Ctx(uniMo, name=vrfname, descr=desc)

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(fvCtxMo)
    md.commit(cfgRequest)
Esempio n. 20
0
 def commit_change(self, changed_object=None, print_xml=True, pretty_print=True):
     """Commit the changes to APIC"""
     changed_object = self.mo if changed_object is None else changed_object
     if print_xml:
         print_query_xml(changed_object, pretty_print=pretty_print)
     config_req = ConfigRequest()
     config_req.addMo(changed_object)
     self.modir.commit(config_req)
Esempio n. 21
0
def config_obj(moDir, mo):

    # Create Config Request
    CfgRqst = ConfigRequest()
    CfgRqst.addMo(mo)

    # Commit Config Request
    moDir.commit(CfgRqst)
Esempio n. 22
0
def createL2OUT(md, tn, l2out, desc):
    tenant = 'uni/tn-' + tn
    uniMo = md.lookupByDn(tenant)
    L2OUTMo = Out(uniMo, name=l2out, descr=desc)

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(L2OUTMo)
    md.commit(cfgRequest)
Esempio n. 23
0
def createBD(md, tn, bdname, desc):
    tenant = 'uni/tn-' + tn
    uniMo = md.lookupByDn(tenant)
    fvBDMo = BD(uniMo, name=bdname, descr=desc, ipLearning='no')

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(fvBDMo)
    md.commit(cfgRequest)
Esempio n. 24
0
 def test_ConfigRequest_data(self):
     expected = ('{"fvTenant": {"attributes": {"name": "test", "status": ' +
                 '"created,modified"}}}')
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'test')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert cr.data == expected
Esempio n. 25
0
def createBGPPeer(md, tn, l3out, profile, address, desc):
    parentdn = 'uni/tn-' + tn + '/out-' + l3out + '/lnodep-' + profile
    uniMo = md.lookupByDn(parentdn)
    bgpp = PeerP(uniMo, name=profile, addr=address, descr=desc)

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(bgpp)
    md.commit(cfgRequest)
Esempio n. 26
0
def createLogicalNodeProfile(md, tn, l3out, profile, desc):
    parentdn = 'uni/tn-' + tn + '/out-' + l3out
    uniMo = md.lookupByDn(parentdn)
    lnp = LNodeP(uniMo, name=profile, descr=desc)

    cfgRequest = ConfigRequest()
    cfgRequest.addMo(lnp)
    md.commit(cfgRequest)
Esempio n. 27
0
 def test_ConfigRequest_data(self):
     expected = ('{"fvTenant": {"attributes": {"name": "test", "status": ' +
                 '"created,modified"}}}')
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'test')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert cr.data == expected
Esempio n. 28
0
 def commit_change(self, changed_object=None, print_xml=True, pretty_print=True):
     """Commit the changes to APIC"""
     changed_object = self.mo if changed_object is None else changed_object
     if print_xml:
         print_query_xml(changed_object, pretty_print=pretty_print)
     config_req = ConfigRequest()
     config_req.addMo(changed_object)
     self.modir.commit(config_req)
Esempio n. 29
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)
Esempio n. 30
0
 def test_post_cert_to_local_user(self, moDir, certobject, userobject):
     # Update the user object with the cert data
     userobject.aaaUserCert.data = certobject.readFile(
         fileName=certobject.certfile)
     # Commit the user to the APIC with the cert
     cr = ConfigRequest()
     cr.addMo(userobject.aaaUser)
     r = moDir.commit(cr)
     assert r == []
def create_tenant(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')

    fvTenant = Tenant(policy_universe, tenant_name)

    print toXMLStr(policy_universe,prettyPrint = True)
    configReq = ConfigRequest()
    configReq.addMo(fvTenant)
    modir.commit(configReq)
Esempio n. 32
0
 def test_post_cert_to_local_user(self, moDir, certobject, userobject):
     # Update the user object with the cert data
     userobject.aaaUserCert.data = certobject.readFile(
         fileName=certobject.certfile)
     # Commit the user to the APIC with the cert
     cr = ConfigRequest()
     cr.addMo(userobject.aaaUser)
     r = moDir.commit(cr)
     assert r.status_code == 200
Esempio n. 33
0
 def test_ConfigRequest_getRootMo(self, mos, expected):
     cr = ConfigRequest()
     mos.append(expected)
     for mo in mos:
         if mo is not None:
             try:
                 cr.addMo(mo)
             except ValueError:
                 pass
     assert cr.getRootMo() == expected
Esempio n. 34
0
    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)
Esempio n. 35
0
 def test_ConfigRequest_getRootMo(self, mos, expected):
     cr = ConfigRequest()
     mos.append(expected)
     for mo in mos:
         if mo is not None:
             try:
                 cr.addMo(mo)
             except ValueError:
                 pass
     assert cr.getRootMo() == expected
Esempio n. 36
0
def commit(md, mo):
    """
    Helper function to commit changes to a mo
    :param md: MoDirectory instance
    :param mo: Cobra object to be committed
    :return:
    """
    c = ConfigRequest()
    c.addMo(mo)
    return md.commit(c)
Esempio n. 37
0
def create_tenant(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')

    fvTenant = Tenant(policy_universe, tenant_name)

    print toXMLStr(policy_universe, prettyPrint=True)

    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 38
0
def create_bd(logon_session,
              tenant_name="Example_TN",
              description="Description",
              bd_name='',
              vrf_name=''):

    from cobra.internal.codec.jsoncodec import toJSONStr
    from cobra.model.fv import Tenant, RsTenantMonPol, BD, RsIgmpsn, RsCtx
    from cobra.model.fv import RsBdToEpRet, RsBDToNdP
    from cobra.mit.request import ConfigRequest
    import cobra.model.pol
    import cobra.model.vns
    c = ConfigRequest()
    #apic_logon(apic_url, user, password)
    polUni = cobra.model.pol.Uni('')

    fvTenant = Tenant(polUni, tenant_name)

    fvBD = BD(fvTenant,
              multiDstPktAct=u'bd-flood',
              mcastAllow=u'no',
              limitIpLearnToSubnets=u'yes',
              unicastRoute=u'no',
              unkMcastAct=u'flood',
              descr=u'',
              llAddr=u'::',
              nameAlias=u'',
              type=u'regular',
              ipLearning=u'no',
              vmac=u'not-applicable',
              mac=u'00:22:BD:F8:19:FF',
              epMoveDetectMode=u'',
              ownerTag=u'',
              intersiteBumTrafficAllow=u'no',
              annotation=u'',
              ownerKey=u'',
              name=bd_name,
              epClear=u'no',
              unkMacUcastAct=u'flood',
              arpFlood=u'yes',
              intersiteL2Stretch=u'no',
              OptimizeWanBandwidth=u'no')
    fvRsIgmpsn = RsIgmpsn(fvBD, tnIgmpSnoopPolName=u'', annotation=u'')
    fvRsCtx = RsCtx(fvBD, annotation=u'', tnFvCtxName=vrf_name)
    fvRsBdToEpRet = RsBdToEpRet(fvBD,
                                resolveAct=u'resolve',
                                annotation=u'',
                                tnFvEpRetPolName=u'')
    fvRsBDToNdP = RsBDToNdP(fvBD, annotation=u'', tnNdIfPolName=u'')

    bd_data = toJSONStr(polUni)

    c.addMo(polUni)
    logon_session.commit(c)
    return bd_data
Esempio n. 39
0
def delete_tenant(modir, tenant_name):
    fv_tenant = modir.lookupByDn('uni/tn-' + tenant_name)
    fv_tenant.delete()

    # print the query in XML format
    print toXMLStr(fv_tenant, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(fv_tenant)
    modir.commit(configReq)
Esempio n. 40
0
    def commit_change(self, changed_object=None, print_xml=True):
        """Commit the changes to APIC"""

        # config_req = ConfigRequest()
        # config_req.addMo(self.mo)
        # self.modir.commit(config_req)
        # modir.logout()
        configReq = ConfigRequest()
        configReq.addMo(self.mo)
        self.modir.commit(configReq)
        self.modir.logout()
Esempio n. 41
0
def delete_tenant(modir, tenant_name):
    fv_tenant = modir.lookupByDn('uni/tn-' + tenant_name)
    fv_tenant.delete()

    # print the query in XML format
    print toXMLStr(fv_tenant, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(fv_tenant)
    modir.commit(configReq)
Esempio n. 42
0
    def commit_change(self, changed_object=None, print_xml=True):
        """Commit the changes to APIC"""

        # config_req = ConfigRequest()
        # config_req.addMo(self.mo)
        # self.modir.commit(config_req)
        # modir.logout()
        configReq = ConfigRequest()
        configReq.addMo(self.mo)
        self.modir.commit(configReq)
        self.modir.logout()
Esempio n. 43
0
 def test_ConfigRequest_removeMo_and_hasMo_negative(self):
     fvTenant = Tenant('uni', 'testing')
     fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     cr.removeMo(fvTenant)
     cr.addMo(fvnsVlanInstP)
     assert not cr.hasMo(fvTenant.dn)
Esempio n. 44
0
    def test_ConfigRequest_getUriPathAndOptions(self, sessionUrl, mo, dc,
                                                requestType):
        session = LoginSession(sessionUrl, 'admin', 'password',
                               requestFormat=requestType)

        cr = ConfigRequest()
        cr.addMo(mo)
        expected = '/api/mo/' + str(mo.dn) + '.' + requestType
        if dc is not None:
            cr.id =  dc
            expected += '?_dc=' + dc
        assert cr.getUriPathAndOptions(session) == expected
Esempio n. 45
0
 def test_ConfigRequest_xmldata(self):
     expected1 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                 '<fvTenant name=\'test\' status=\'created,modified\'>' +
                 '</fvTenant>')
     expected2 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                 '<fvTenant status=\'created,modified\' name=\'test\'>' +
                 '</fvTenant>')
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'test')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert (cr.xmldata == expected1 or cr.xmldata == expected2)
Esempio n. 46
0
def delete_import_policy(md, name):
    answer = ''
    while not answer in ['y', 'n']:
        answer = raw_input('Delete temporary import policy y/n [n]: ') or 'n'
    if answer == 'y':
        fabricInst = md.lookupByDn('uni/fabric')
        importpolicy = ImportP(fabricInst, name)
        importpolicy.delete()
        cr = ConfigRequest()
        cr.addMo(importpolicy)
        md.commit(cr)
        print 'Deleted import policy'
Esempio n. 47
0
 def test_ConfigRequest_xmldata(self):
     expected1 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                 '<fvTenant name=\'test\' status=\'created,modified\'>' +
                 '</fvTenant>')
     expected2 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                 '<fvTenant status=\'created,modified\' name=\'test\'>' +
                 '</fvTenant>')
     polUni = Uni('')
     fvTenant = Tenant(polUni, 'test')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     assert (cr.xmldata == expected1 or cr.xmldata == expected2)
Esempio n. 48
0
 def test_cleanup_user(self, apics, certobject, userobject):
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     userobject.aaaUser.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(userobject.aaaUser)
     r = moDir.commit(cr)
     assert r == []
Esempio n. 49
0
def create_tenant(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')

    # 
    fvTenant = Tenant(policy_universe, tenant_name)

    # print the query in XML format
    print toXMLStr(policy_universe, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 50
0
 def test_ConfigRequest_removeMo_and_hasMo_negative(self):
     fvTenant = Tenant('uni', 'testing')
     fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic')
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     cr.removeMo(fvTenant)
     cr.addMo(fvnsVlanInstP)
     assert not cr.hasMo(fvTenant.dn)
Esempio n. 51
0
def main(host, username, password, pool_name, from_vlan, to_vlan):
    apic = "https://%s" % host
    print("Connecting to APIC : %s" % apic)
    moDir = MoDirectory(LoginSession(apic, username, password))
    moDir.login()
    topMO = moDir.lookupByDn('uni')
    moDir.lookupByDn
    infraInfra = cobra.model.infra.Infra(topMO)
    fvnsVlanInstP = VlanInstP(infraInfra,name=pool_name, allocMode="static")
    temp_from_vlan = "vlan-" + from_vlan
    temp_to_vlan = "vlan-" + to_vlan
    fvnsEncapBlk = EncapBlk(fvnsVlanInstP, temp_from_vlan, temp_to_vlan)

    print(toXMLStr(topMO))
    c = ConfigRequest()
    c.addMo(infraInfra)
    moDir.commit(c)
Esempio n. 52
0
def create_3tier_application(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')
    fv_tenant = Tenant(policy_universe, tenant_name)

    # create context
    fv_ctx = Ctx(fv_tenant, CTX_NAME)

    #
    fv_bd = BD(fv_tenant, 'BD1')

    #
    fv_rs_ctx = RsCtx(fv_bd)
    fv_rs_ctx.__setattr__('tnFvCtxName', 'Apple-Router')
    fv_subnet_10 = Subnet(fv_bd,'10.0.0.1/24', scope='public')
    fv_subnet_20 = Subnet(fv_bd, '20.0.0.1/24', scope='public')
    fv_subnet_30 = Subnet(fv_bd, '30.0.0.1/24', scope='public')
    fv_subnet_40 = Subnet(fv_bd, '40.0.0.1/24', scope='public')

    #
    fv_ap = Ap(fv_tenant, '3-TierApp')

    fv_aepg_client = AEPg(fv_ap, 'Client')
    fv_rs_bd_client = RsBd(fv_aepg_client, tnFvBDName='BD1')
#    fv_rs_bd_client.__setattr__('tnFvBDName', 'BD1')
    fv_rs_cons_webct_client = RsCons(fv_aepg_client, 'WebCt')

    fv_aepg_web = AEPg(fv_ap, 'Web')
    fv_rs_bd_web = RsBd(fv_aepg_web, tnFvBDName='BD1')
    fv_rs_cons_webct_web = RsProv(fv_aepg_web, 'WebCt')
    fv_rs_cons_appct_web = RsCons(fv_aepg_web, 'AppCt')

    fv_aepg_app = AEPg(fv_ap, 'App')
    fv_rs_bd_app = RsBd(fv_aepg_app, tnFvBDName='DB1')
    fv_rs_cons_webct_app = RsProv(fv_aepg_app, 'WebCt')
    fv_rs_cons_appct_app = RsCons(fv_aepg_app, 'AppCt')

    fv_aepg_db = AEPg(fv_ap, 'DB')
    fv_rs_bd_db = RsBd(fv_aepg_db, tnFvBDName='BD1')
    fv_rs_prov_db = RsProv(fv_aepg_db, 'DbCt')

    print toXMLStr(policy_universe, prettyPrint=True)
    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 53
0
    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)
Esempio n. 54
0
 def test_tn_cleanup(self, apics, certobject, userobject):
     if userobject.user == 'rouser':
         return
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     uni = Uni('')
     fvTenant = Tenant(uni, name='t')
     fvTenant.delete()
     fvBD = BD(fvTenant, 't-bd')
     fvBD.delete()
     fvAp = Ap(fvTenant, 't-app')
     fvAp.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     r = moDir.commit(cr)
     assert r == []
Esempio n. 55
0
 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')
Esempio n. 56
0
def create_filters(modir, tenant_name):

    policy_universe = modir.lookupByDn('uni')
    fv_tenant = Tenant(policy_universe, tenant_name)

    # create filter for http
    vz_filter_http = Filter(fv_tenant, FILTER_HTTP_NAME)
    vz_entry_http = Entry(vz_filter_http, 'DPort-80', dFromPort='80', dToPort='80', etherT='ip', prot='tcp')

    #create filter for rmi
    vz_filter_rmi = Filter(fv_tenant, FILTER_RMI_NAME)
    vz_entry_rmi = Entry(vz_filter_http, 'DPort-1514', dFromPort='1514', dToPort='1514', etherT='ip', prot='tcp')

    # create filter for sql
    vz_filter_sql = Filter(fv_tenant, FILTER_RMI_NAME)
    vz_entry_sql = Entry(vz_filter_http, 'DPort-1433', dFromPort='1433', dToPort='1433', etherT='ip', prot='tcp')

    # print the query in XML format
    print toXMLStr(policy_universe, prettyPrint=True)

    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
Esempio n. 57
0
def commit_change(modir, changed_object):
    """Commit the changes to APIC"""
    config_req = ConfigRequest()
    config_req.addMo(changed_object)
    modir.commit(config_req)
Esempio n. 58
0
def main(host, port, user, password):

    # CONNECT TO APIC
    print('Initializing connection to APIC...')
    apicUrl = 'http://%s:%d' % (host, port)
    moDir = MoDirectory(LoginSession(apicUrl, user, password))
    moDir.login()

    # Get the top level Policy Universe Directory
    uniMo = moDir.lookupByDn('uni')
    uniInfraMo = moDir.lookupByDn('uni/infra')

    # Create Vlan Namespace
    nsInfo = VMM_DOMAIN_INFO['namespace']
    print("Creating namespace %s.." % (nsInfo['name']))
    fvnsVlanInstPMo = VlanInstP(uniInfraMo, nsInfo['name'], 'dynamic')
    #fvnsArgs = {'from': nsInfo['from'], 'to': nsInfo['to']}
    EncapBlk(fvnsVlanInstPMo, nsInfo['from'], nsInfo['to'], name=nsInfo['name'])
    
    nsCfg = ConfigRequest()
    nsCfg.addMo(fvnsVlanInstPMo)
    moDir.commit(nsCfg)

    # Create VMM Domain
    print('Creating VMM domain...')

    vmmpVMwareProvPMo = moDir.lookupByDn('uni/vmmp-VMware')
    vmmDomPMo = DomP(vmmpVMwareProvPMo, VMM_DOMAIN_INFO['name'])
    
    vmmUsrMo = []
    for usrp in VMM_DOMAIN_INFO['usrs']:
        usrMo = UsrAccP(vmmDomPMo, usrp['name'], usr=usrp['usr'],
                        pwd=usrp['pwd'])
        vmmUsrMo.append(usrMo)

    # Create Controllers under domain
    for ctrlr in VMM_DOMAIN_INFO['ctrlrs']:
        vmmCtrlrMo = CtrlrP(vmmDomPMo, ctrlr['name'], scope=ctrlr['scope'],
                            hostOrIp=ctrlr['ip'])
        # Associate Ctrlr to UserP
        RsAcc(vmmCtrlrMo, tDn=vmmUsrMo[0].dn)
    
    # Associate Domain to Namespace
    RsVlanNs(vmmDomPMo, tDn=fvnsVlanInstPMo.dn)
   
    vmmCfg = ConfigRequest()
    vmmCfg.addMo(vmmDomPMo)
    moDir.commit(vmmCfg)
    print("VMM Domain Creation Completed.")

    print("Starting Tenant Creation..")
    for tenant in TENANT_INFO:
        print("Creating tenant %s.." % (tenant['name']))
        fvTenantMo = Tenant(uniMo, tenant['name'])
        
        # Create Private Network
        Ctx(fvTenantMo, tenant['pvn'])
        
        # Create Bridge Domain
        fvBDMo = BD(fvTenantMo, name=tenant['bd'])
        
        # Create association to private network
        RsCtx(fvBDMo, tnFvCtxName=tenant['pvn'])
        
        # Create Application Profile
        for app in tenant['ap']:
            print('Creating Application Profile: %s' % app['name'])
            fvApMo = Ap(fvTenantMo, app['name'])
            
            # 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'])
                # Associate EPG to VMM Domain
                RsDomAtt(fvAEPgMo, vmmDomPMo.dn)

        # Commit each tenant seperately
        tenantCfg = ConfigRequest()
        tenantCfg.addMo(fvTenantMo)
        moDir.commit(tenantCfg)
    print('All done!')
#!/usr/bin/env python
import cobra.model.fv
import cobra.mit.access
import cobra.mit.session
from cobra.mit.request import ConfigRequest
import creds

# Create a login session with APIC IP / credentials
ls = cobra.mit.session.LoginSession(creds.APIC_URL, creds.APIC_USER, creds.APIC_PASSWORD)
md = cobra.mit.access.MoDirectory(ls)
md.login()

# Create MO object for root of the object tree
root = md.lookupByDn('uni')

# Create a tenant
cobratenant = cobra.model.fv.Tenant(root, 'cobratenant')

# Create a
c = ConfigRequest()
c.addMo(root)

# Get the URL to POST to
print 'Posting {} to {}'.format(c.data, c.getUrl(ls))

md.commit(c)
Esempio n. 60
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)