Exemplo n.º 1
0
class APICHandler():
    def __init__(self):
        self.host = 'https://192.168.1.100'
        self.user = '******'
        self.pwd = 'GDTlabs123'
        self.session = None

    def do_login(self):
        loginSession = LoginSession(self.host, self.user, self.pwd)
        self.session = MoDirectory(loginSession)
        self.session.login()
        # print loginSession.cookie
        return self.session

    def target_location_lookup(self, active_session, location):
        change_location = self.session.lookupByDn(location)
        return change_location

    def update_config(self, active_session, change_location):
        configReq = ConfigRequest()
        configReq.addMo(change_location)
        self.session.commit(configReq)

    def logout(self, active_session):
        self.session.logout()
Exemplo n.º 2
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.º 3
0
def main():
    params = get_parameters()
    loginSession = LoginSession(params['apic-url'], params['apic-user'],
                                params['apic-password'])
    md = MoDirectory(loginSession)
    md.login()
    create_remote_scp_location(md, params['backup-host'],
                               params['backup-user'],
                               params['backup-password'],
                               params['backup-path'])
    import_backup(md, params['backup-filename'])
    check_backup_status(md, 'tmp_import_policy')
    delete_import_policy(md, 'tmp_import_policy')
    delete_backup_location(md, 'tmp_location')
    md.logout()
Exemplo n.º 4
0
def get_tenant():
    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")

    apicUrl = 'https://172.17.0.1/'
    loginSession = createCertSession()
    #loginSession = LoginSession(apicUrl, 'admin', 'ins3965!')
    #loginSession = cobra.mit.session.LoginSession('https://10.22.47.171', 'admin', 'ins3965!')
    moDir = MoDirectory(loginSession)
    moDir.login()
    tenantMo = moDir.lookupByClass('fvTenant');
    moDir.logout()
    #print json.dumps(tenantMo)
    return respFormatJsonMos(tenantMo, tenantMo.totalCount)
Exemplo n.º 5
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.º 6
0
def main():
    ls = LoginSession(apicURL, apicUN, apicPW)
    md = MoDirectory(ls)
    md.login()

    # Print LLDP Adjacent Endpoints
    printClass(md, 'lldpAdjEp', 'mgmtIp')

    # Print all tenants
    printClass(md, 'fvTenant', 'name')

    # Print all L2OUT
    printClass(md, 'l2extOut', 'name')

    # Print all fabric Nodes
    printClass(md, 'fabricNode', 'name')
    printClass(md, 'fabricNode', 'model')
    printClass(md, 'fabricNode', 'id')
    printClass(md, 'aaaUser', 'name')

    # Print BGP Peer
    printClass(md, 'bgpPeerP', 'addr')

    # Create tenants
    createTenant(md, 'EvictMe', 'My First Eviction')

    # Create VRF in EvictMe
    createVRF(md, 'EvictMe', 'VRF-Eviction', 'My VRF for eviction')

    # Create BD in EvictMe
    createBD(md, 'EvictMe', 'BD-Eviction', 'My BD for eviction')

    # Create L2OUT in EvictMe
    createL2OUT(md, 'EvictMe', 'L2OUT-Eviction', 'My L2OUT for eviction')

    # Create L3OUT Logical Node Profile
    createLogicalNodeProfile(md, 'EvictMe', 'DC-L3OUT', 'MyProfile', 'My LNP')

    # Create L3OUT BGP Peer
    createBGPPeer(md, 'EvictMe', 'DC-L3OUT', 'MyProfile', '9.9.9.9',
                  'My BGP Peer')

    md.logout()
Exemplo n.º 7
0
def get_tenant():

    with open("/Users/clakits/aci/myapps/apic/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")

    apicUrl = 'https://'
    loginSession = LoginSession(apicUrl, 'admin', '')

    #loginSession = createCertSession()

    moDir = MoDirectory(loginSession)
    moDir.login()
    tenantMo = moDir.lookupByClass('fvTenant')
    moDir.logout()

    return respFormatJsonMos(tenantMo, tenantMo.totalCount)
Exemplo n.º 8
0
apicPassword = TacacsPassword
loginSession = LoginSession(apicUrl, apicUsername, apicPassword)

# Create a session with the APIC and login
moDir = MoDirectory(loginSession)
moDir.login()

#Prompt User for Tenant to create BD in.
#UserTenant = raw_input('Create BD in which tenant? ')

# Start at the Tenant of MIT tree
TenantMo = moDir.lookupByDn((r'uni/tn-ExampleSdkTenant'))

# Create a new BD MO and connect it as a Child object to the Tenant MO
fvBDMo = fvModels.BD(TenantMo, name='myBD')

# Associate the VRF under the new BD
fvRsCtxMo = fvModels.RsCtx(fvBDMo, tnFvCtxName='myVRF')

# Add Subnet to BD
fvSubnetMo = fvModels.Subnet(fvBDMo, ip='10.20.30.1/24')

# Create a new configuration request to the APIC and pass in the new Tenant MO (including its children MOs)
# Commit the changes to the APIC
cfgRequest = ConfigRequest()
cfgRequest.addMo(fvBDMo)
moDir.commit(cfgRequest)

# Log Out once the request is complete
moDir.logout()
Exemplo n.º 9
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.º 10
0
# 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)

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

# Delete the newly created tenant
tenant.delete()

cr = ConfigRequest()
cr.addMo(polUni)
md.commit(cr)

# Log out of the APIC
md.logout()
Exemplo n.º 11
0
import logging, json

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


# uncomment the below to get more verbose output
# for debugging
"""
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
"""

session = LoginSession('https://*****:*****@lw@y')
moDir = MoDirectory(session)
moDir.login()
tenant1Mo = moDir.lookupByClass("dhcpClient")

for c in tenant1Mo:
	print(c.dn, c.model, c.name, c.ip)

moDir.logout()


Exemplo n.º 12
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.º 13
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.º 14
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.º 15
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