Exemplo n.º 1
0
def main():
    """
    Main show EPGs routine
    :return: None
    """
    # Login to APIC
    description = ('Simple application that logs on to the APIC'
                   ' and add static-binding-leaves.')
    creds = aci.Credentials('apic', description)
    creds.add_argument('-t', '--tenant', help='Tenant name', default=DEFAULT_TENANT)
    creds.add_argument('-a', '--app', help='Application profile name', default=DEFAULT_APP)
    creds.add_argument('-e', '--epg', help='EPG name', default=DEFAULT_EPG)
    creds.add_argument('-n', '--node', help='Node ID (e.g. 101)', default=DEFAULT_NODE_ID)
    creds.add_argument('-y', '--type', help='Encapsulation type (vlan | vxlan | nvgre)', default=DEFAULT_ENCAP_TYPE)
    creds.add_argument('-i', '--id', help='Specific identifier representing the virtual L2 network (e.g. 100)', default=DEFAULT_ENCAP_ID)
    creds.add_argument('-m', '--mode', help='Encapsulation mode (regular | untagged | native)', default=DEFAULT_ENCAP_MODE)
    creds.add_argument('-d', '--deploy', help='Deployment immediacy (immediate | lazy)', default=DEFAULT_IMMEDIACY)
    creds.add_argument('-o', '--pod', help='Pod number (e.g. 1)', default=DEFAULT_POD)

    args = creds.get()
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
    
    tenant = aci.Tenant(args.tenant)
    app = aci.AppProfile(args.app, tenant)
    epg = aci.EPG(args.epg, app)
    epg.add_static_leaf_binding(args.node, args.type, args.id, args.mode, args.deploy, args.pod)
    
    # Push it all to the APIC
    resp = session.push_to_apic(tenant.get_url(), tenant.get_json())
Exemplo n.º 2
0
def main():
    """
    Main execution routine

    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = 'Simple application that logs on to the APIC and displays \
                   all of the filters.'

    creds = ACI.Credentials('apic', description)
    args = creds.get()

    # Login to APIC
    session = ACI.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    # Download all of the tenants
    template = '{0:20} {1:20}'
    print template.format("TENANT", "FILTER")
    print template.format("------", "------")
    tenants = ACI.Tenant.get(session)
    for tenant in tenants:
        filters = ACI.Filter.get(session, tenant)
        for filter in filters:
            print template.format(tenant.name, filter.name)
def main():
    """
    Main subscribe tenants routine
    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = ('Simple application using event subscription for the'
                   'Tenant class. When run, this application will log '
                   'into the APIC and subscribe to events on the Tenant '
                   'class.  If a new tenant is created, the event will be'
                   'printed on the screen. Likewise, if an existing tenant'
                   'is deleted.')
    creds = aci.Credentials('apic', description)
    args = creds.get()

    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    aci.Tenant.subscribe(session)

    while True:
        if aci.Tenant.has_events(session):
            tenant = aci.Tenant.get_event(session)
            if tenant.is_deleted():
                print('Tenant', tenant.name, 'has been deleted.')
            else:
                print('Tenant', tenant.name, 'has been created or modified.')
Exemplo n.º 4
0
def main():
    """
    Main show Process routine
    :return: None
    """
    description = 'Simple application that logs on to the APIC and displays process information for a switch'
    creds = Credentials('apic', description)

    creds.add_argument('-s',
                       '--switch',
                       type=str,
                       default=None,
                       help='Specify a particular switch id, e.g. "102"')
    args = creds.get()

    session = ACI.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print '%% Could not login to APIC'
        sys.exit(0)

    switches = ACI.Node.get(session, '1', args.switch)
    for switch in switches:
        if switch.role != 'controller':
            processes = ACI.Process.get(session, switch)
            tables = ACI.Process.get_table(
                processes, 'Process list for Switch ' + switch.name + '::')
            for table in tables:
                print table.get_text(tablefmt='fancy_grid') + '\n'
Exemplo n.º 5
0
def main():
    """
    Main create tenant routine
    :return: None
    """
    # Get all the arguments
    description = 'It logs in to the APIC and will create the vlan pool.'
    creds = aci.Credentials('apic', description)
    creds.add_argument('-v',
                       '--vlan',
                       help='The name of vlan pool',
                       default=DEFAULT_VLAN_NAME)
    args = creds.get()

    # Login to the APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')

    # Create the VLAN pool
    vlan_pool = aci.NetworkPool(args.vlan, 'vlan', '222', '223', 'dynamic')

    # Push the VLAN pool to the APIC
    resp = session.push_to_apic(vlan_pool.get_url(), vlan_pool.get_json())
    if not resp.ok:
        print('%% Error: Could not push configuration to APIC')
        print(resp.text)
Exemplo n.º 6
0
def main():
    """
    Main execution routine
    :return: None
    """

    # Login to APIC
    session = aci.Session("http://apic-amslab.cisco.com", "admin", "C1sco123")
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')

    if resp.ok:
        print("\nApic login successful")

    intDown = []
    intNames = []
    interfaces = aci.Interface.get(session)
    for interface in interfaces:
        if interface.attributes['operSt'] == 'down':
            intDown.append(interface.attributes['operSt'])
            intNames.append(interface.attributes['if_name'])

    l3outNames = []
    l3outs = aci.L3ExtDomain.get(robvand)

    print('\nThere are {} ports available'.format(intDown.count('down')))

    template = "{0:25}"
    print(template.format("\nAVAILABLE INTERFACES"))
    print(template.format("---------"))
    for intName in intNames:
        print(template.format(intName))
Exemplo n.º 7
0
def create_aci_session(aci_apic, aci_user, aci_pass):
    """
    Creates an ACI session from the given APIC address, username, and password.
    :param aci_apic: Address of the APIC.
    :param aci_user: Username for the APIC.
    :param aci_pass: Password for the APIC.
    :return: The ACI session object or raises PortalException on error.
    """
    try:
        aci_session = ACI.Session(aci_apic, aci_user, aci_pass)
    except CredentialsError as e:
        app.logger.error(str(e))
        raise PortalException('ACI credentials or APIC IP invalid.')

    try:
        resp = aci_session.login(timeout=30)
    except (requests.exceptions.MissingSchema, requests.exceptions.InvalidURL, TypeError) as e:
        app.logger.error(str(e))
        raise PortalException('Invalid APIC IP, please provide a correct one.')

    if resp.status_code != 200:
        app.logger.error(resp.content)
        raise PortalException('ACI credentials or APIC IP incorrect!')

    return aci_session
def main():
    """
    Main common routine for show interface description
    :return: None
    """
    # Set up the command line options
    description = ('Simple application that logs in to the APIC'
                   'and displays the Interface Optics and Neighbors')
    creds = ACI.Credentials('apic', description)
    args = creds.get()

    # Login to APIC
    apic = ACI.Session(args.url, args.login, args.password)
    resp = apic.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        return

    # Show interface Optic & LLDP Neighbor
    #print('starting node_ids')
    switch_attributes = get_switch_attributes(apic, args)
    #print('starting intf_ids')
    intf_ids = get_intf_ids(apic, args, switch_attributes)
    #print('starting Section for Optics and Neighbors')
    interface_detail(apic, args, switch_attributes, intf_ids)
Exemplo n.º 9
0
def main():
    """
    Main show Process routine
    :return: None
    """
    description = 'Simple application that logs on to the APIC and check cluster information for a fabric'
    creds = Credentials('apic', description)

    args = creds.get()

    session = ACI.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print '%% Could not login to APIC'
        sys.exit(0)

    
    cluster = ACI_PHYS.Cluster('Cluster')
    cluster_info = cluster.get(session)

    if (cluster.config_size != cluster.cluster_size):
        print("*******************************************************")
        print ("WARNING, configured cluster size "), cluster.config_size
        print (":   not equal to the actual size "), cluster.cluster_size
        print "WARNING, desired stats collection might be lost"
        print("*******************************************************")
        print("APICs in the cluster"), cluster.name, (":")
        for apic in cluster.apics:
            print json.dumps(apic,indent=4, sort_keys = True)
    else:
        print("PASS")
 def establish_ws_session(self, max_retries=None):
     try:
         with utils.get_rlock(lcon.ACI_WS_CONNECTION_LOCK, blocking=False):
             retries = 0
             self._reload_websocket_config()
             max_retries = max_retries or 2 * len(self.ws_urls)
             while retries < max_retries:
                 if self.session and self.session.session:
                     self.session.close()
                 LOG.info('Establishing WS connection with url: %s',
                          self.ws_urls[0])
                 self.session = acitoolkit.Session(
                     self.ws_urls[0],
                     self.apic_username,
                     self.apic_password,
                     verify_ssl=self.verify_ssl_certificate,
                     cert_name=self.cert_name,
                     key=self.private_key_file)
                 resp = self.session.login()
                 if not resp.ok:
                     LOG.warn('Websocket connection failed: %s' % resp.text)
                     self.ws_urls.rotate(-1)
                     LOG.info('Rotating websocket URL, '
                              'using: %s' % self.ws_urls[0])
                     retries += 1
                     continue
                 LOG.info('Websocket connection succeeded.')
                 self._spawn_monitors()
                 return self.session
             utils.perform_harakiri(
                 LOG, "Cannot establish WS connection "
                 "after %s retries." % retries)
     except utils.LockNotAcquired:
         # Some other thread is trying to reconnect
         return
Exemplo n.º 11
0
def toolkit_login(admin_info):
    session = ACI.Session(admin_info['ip_addr'], admin_info['user'],
                          admin_info['password'])
    response = session.login()

    if not response.ok:
        error_message(
            [1, 'There was an error with the connection to the APIC.', -1])
        return False

    decoded_response = json.loads(response.text)

    if (response.status_code != 200):
        if (response.status_code == 401):
            connection_status = 'Username/Password incorrect'
            return False
        else:
            error_message([
                decoded_response['imdata'][0]['error']['attributes']['code'],
                decoded_response['imdata'][0]['error']['attributes']['text'],
                -1
            ])
            return False

    elif (response.status_code == 200):
        refresh = decoded_response['imdata'][0]['aaaLogin']['attributes'][
            'refreshTimeoutSeconds']
        cookie = response.cookies['APIC-cookie']
        return session
    else:
        return False

    return False
Exemplo n.º 12
0
def main():
    time.sleep(70)
    description = ('Simple application that logs on to the APIC'
                   ' and displays all of the Endpoints.')
    creds = aci.Credentials('apic', description)
    args = creds.get()

    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    data = []
    endpoints = aci.IPEndpoint.get(session)
    for ep in endpoints:
        epg = ep.get_parent()
        app_profile = epg.get_parent()
        tenant = app_profile.get_parent()
        if (tenant.name == 'Devops' and ((epg.name == 'web'))):
            data.append((ep.mac, ep.ip, epg.name))
    #print "Test here\n"
    y = len(data)
    print "[WEB]"
    print data[y - 1][1]
Exemplo n.º 13
0
def main():
    """
    Main Show Endpoints Routine
    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = ('Simple application that logs on to the APIC'
                   ' and displays all of the Endpoints.')
    creds = aci.Credentials('apic', description)
    args = creds.get()

    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        return

    # Download all of the interfaces
    # and store the data as tuples in a list
    data = []
    endpoints = aci.Endpoint.get(session)
    for ep in endpoints:
        epg = ep.get_parent()
        app_profile = epg.get_parent()
        tenant = app_profile.get_parent()
        data.append((ep.if_name, tenant.name))

    # Display the data downloaded
    print(tabulate(data, headers=["INTERFACE", "TENANT"]))
def main():
    """
    Main Show Physical Domains Routine
    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = ('Simple application that logs on to the APIC'
                   ' and displays all of the Physical Domains.')
    creds = aci.Credentials('apic', description)
    args = creds.get()

    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    domains = aci.PhysDomain.get(session)

    if len(domains) > 0:
        print ('---------------')
        print ('Physical Domain')
        print ('---------------')

    for domain in domains:
        print domain.name

    if len(domains) > 0:
        print '\n'

    domains = aci.VmmDomain.get(session)
Exemplo n.º 15
0
def main():

    # Get the APIC login credentials
    description = 'testing tags'
    creds = aci.Credentials('apic', description)
    args = creds.get()

    # Login to APIC and push the config
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        return
    # get all physical domains
    phydms = aci.PhysDomain.get(session)
    template = "{0:30} {1:30} {2:25}"
    if len(phydms) > 0:
        print(template.format("Physical Domain", "Network", "encap_type"))
    for p in phydms:
        pool_name = ""
        encap_type = ""
        if p.has_network():
            net = p.get_network()
            pool_name = net.name
            encap_type = net.encap_type
        print(template.format(p.name, pool_name, encap_type))
Exemplo n.º 16
0
def getErrorsEgressDrops():

    # Login to APIC
    session = ACI.Session("https://172.31.216.24",
                          "admin",
                          "scotch123",
                          subscription_enabled=False)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    # Download all of the interfaces and get their stats
    # and display the stats

    interfaces = ACI.Interface.get(session)
    allStats = []
    avgErrorPerInt = []
    for interface in sorted(interfaces, key=attrgetter('if_name')):
        if "egrDropPkts" in interface.stats.get().keys():
            stats = interface.stats.get()['egrDropPkts']
        if stats:
            allStats.append([interface.name, stats["5min"]])
    for i in allStats:
        #avg packets dropped cause full buffer
        name = i[0]
        drops = i[1][12]['bufferAvg']
        if drops:
            avgErrorPerInt.append([name, drops])
    return avgErrorPerInt
Exemplo n.º 17
0
 def establish_ws_session(self, max_retries=None):
     retries = 0
     self._reload_websocket_config()
     max_retries = max_retries or 2 * len(self.ws_urls)
     while retries < max_retries:
         if self.session and self.session.session:
             self.session.close()
         LOG.info('Establishing WS connection with parameters: %s',
                  [self.ws_urls[0], self.apic_username, self.apic_password,
                   self.verify_ssl_certificate])
         self.session = acitoolkit.Session(
             self.ws_urls[0], self.apic_username, self.apic_password,
             verify_ssl=self.verify_ssl_certificate,
             cert_name=self.cert_name, key=self.private_key_file)
         resp = self.session.login()
         if not resp.ok:
             LOG.debug('Websocket connection failed: %s' % resp.text)
             self.ws_urls.rotate(-1)
             LOG.info('Rotating websocket URL, using: %s' % self.ws_urls[0])
             retries += 1
             continue
         LOG.info('Websocket connection succeeded.')
         self._spawn_monitors()
         return self.session
     utils.perform_harakiri(LOG, "Cannot establish WS connection after %s "
                                 "retries." % retries)
Exemplo n.º 18
0
def main(login, password, url):
    """
    Main execution routine

    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = 'Simple application that logs on to the APIC and displays all of the Tenants.'
    #creds = ACI.Credentials('apic', description)
    #args = creds.get()

    # Login to APIC
    #session = ACI.Session(args.url, args.login, args.password)
    session = ACI.Session(url, login, password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    # Download all of the tenants
    print("TENANT")
    print("------")
    tenants = ACI.Tenant.get(session)
    count = 0
    for tenant in tenants:
        count += 1
        if count > 23:
            os.system("read -p \"Press enter key\"")
            count = 0
        print(tenant.name)
Exemplo n.º 19
0
def main():
    description = (
        'Simple application that logs on to the APIC and displays the'
        ' response of a given query')
    creds = aci.Credentials('apic', description)
    creds.add_argument('-c',
                       '--class_name',
                       help='The class which is to be queried',
                       required=True)
    creds.add_argument(
        '-q',
        '--query_target',
        default='self',
        help=('This restricts the scope of the query,query_target takes self'
              '| children | subtree. ex: -q self.  The default is self.'))
    args = creds.get()

    if not args.class_name:
        args.class_name = raw_input("Class Name: ")

    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    class_url = '/api/node/class/' + args.class_name + '.json?query-target=' + args.query_target
    print("class_url is " + class_url)
    ret = session.get(class_url)
    response = ret.json()
    imdata = response['imdata']
    pprint(imdata)
Exemplo n.º 20
0
def main():
    """
    Main show EPGs routine
    :return: None
    """
    # Login to APIC
    description = ('Simple application that logs on to the APIC'
                   ' and displays all of the EPGs.')
    creds = aci.Credentials('apic', description)
    args = creds.get()
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')

    # Download all of the tenants, app profiles, and EPGs
    # and store the names as tuples in a list
    data = []
    tenants = aci.Tenant.get(session)
    for tenant in tenants:
        apps = aci.AppProfile.get(session, tenant)
        for app in apps:
            epgs = aci.EPG.get(session, app, tenant)
            for epg in epgs:
                data.append((tenant.name, app.name, epg.name))

    # Display the data downloaded
    template = "{0:19} {1:20} {2:15}"
    print(template.format("TENANT", "APP_PROFILE", "EPG"))
    print(template.format("------", "-----------", "---"))
    for rec in data:
        print(template.format(*rec))
Exemplo n.º 21
0
def main():
    """
    Main create tenant routine
    :return: None
    """
    # Get all the arguments
    description = 'It logs in to APIC and will create the physical domain.'
    creds = aci.Credentials('apic', description)
    creds.add_argument('-p', '--phy_domain', 
                       help='The name of physical domain',
                       default=DEFAULT_PHY_DOMAIN_NAME)
    args = creds.get()

    # Login to the APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')

    # Create the physical Domain
    phy_dmn = aci.PhysDomain(args.phy_domain)

    # Push the physical domain to the APIC
    resp = session.push_to_apic(phy_dmn.get_url(),
                                phy_dmn.get_json())
    if not resp.ok:
        print('%% Error: Could not push configuration to APIC')
        print(resp.text)
Exemplo n.º 22
0
def main():
    """
    Main create tenant routine
    :return: None
    """
    # Get all the arguments
    description = 'It logs in to the APIC and will create the tenant.'
    creds = aci.Credentials('apic', description)
    creds.add_argument('-t',
                       '--tenant',
                       help='The name of tenant',
                       default=DEFAULT_TENANT_NAME)
    args = creds.get()

    # Login to the APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')

    # Create the Tenant
    tenant = aci.Tenant(args.tenant)

    # Push the tenant to the APIC
    resp = session.push_to_apic(tenant.get_url(), tenant.get_json())
    if not resp.ok:
        print('%% Error: Could not push configuration to APIC')
        print(resp.text)
Exemplo n.º 23
0
def main():
    # Get the APIC login credentials
    description = 'testing tags'
    creds = aci.Credentials('apic', description)
    creds.add_argument('--tag',
                       help='Add tag to all objects in this configuration')
    creds.add_argument('--tenant', help='Tenant name to be created')
    args = creds.get()

    #Create the Tenant
    if args.tenant:
        tenant = aci.Tenant(args.tenant)
    else:
        tenant = aci.Tenant('tutorial-tag')

    # Create the Application Profile
    app = aci.AppProfile('myapp', tenant)

    # Create the EPG
    epg1 = aci.EPG('myepg1', app)
    epg2 = aci.EPG('myepg2', app)

    # Create a Context and BridgeDomain
    context = aci.Context('myvrf', tenant)
    bd = aci.BridgeDomain('mybd', tenant)
    bd.add_context(context)

    # Place the EPG in the BD
    epg1.add_bd(bd)
    epg2.add_bd(bd)

    # Add Tag to the EPGs
    epg1.add_tag("web server")
    epg2.add_tag("database")

    # test
    app2 = aci.AppProfile('myapp2', tenant)
    epg21 = aci.EPG('myepg21', app2)
    epg22 = aci.EPG('myepg22', app2)

    # Add Tag to all objects in this configuration
    if args.tag:
        tenant.add_tag(args.tag)
        context.add_tag(args.tag)
        bd.add_tag(args.tag)
        epg1.add_tag(args.tag)
        epg2.add_tag(args.tag)

    # Login to APIC and push the config
    session = aci.Session(args.url, args.login, args.password)
    session.login()
    resp = tenant.push_to_apic(session)
    if resp.ok:
        print('Success')

    # Print what was sent
    print('Pushed the following JSON to the APIC')
    print('URL:', tenant.get_url())
    print('JSON:', tenant.get_json())
Exemplo n.º 24
0
def apic_login_acitk(hostname,username,password):

    # Login to APIC
    url = "https://" + hostname
    session = ACI.Session(url, username, password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)
    return session
Exemplo n.º 25
0
def apic_login():
    url = credentials.ACI_login['ipaddr']
    login = credentials.ACI_login['username']
    password = credentials.ACI_login['password']
    # Login to APIC
    session = ACI.Session(url, login, password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)
    return (session)
    def _ws_session_login(self,
                          url,
                          url_max_retries,
                          purpose,
                          aim_context=None,
                          apic_assign=None,
                          apic_assign_obj=None):
        retries = 0
        LOG.info('Establishing %s WS connection with url: %s', purpose, url)
        valid_session = None
        while retries < url_max_retries:
            session = acitoolkit.Session(
                url,
                self.apic_username,
                self.apic_password,
                verify_ssl=self.verify_ssl_certificate,
                cert_name=self.cert_name,
                key=self.private_key_file)
            resp = session.login()
            if not resp.ok:
                LOG.warn('%s Websocket connection failed: %s', purpose,
                         resp.text)
                retries += 1
                if session.session:
                    session.close()
                continue
            LOG.info('%s Websocket connection succeeded with url: %s', purpose,
                     url)
            valid_session = session
            break

        if valid_session:
            # We don't need to claim the ownership if we are just
            # picking up a backup APIC.
            if purpose != BACKUP_PURPOSE:
                obj = self._update_apic_assign_db(aim_context, apic_assign,
                                                  apic_assign_obj)
                if obj is None:
                    valid_session.close()
                    return False
            if purpose == BACKUP_PURPOSE or obj:
                if self.session and self.session.session:
                    self.session.close()
                    self.is_session_reconnected = True
                self.session = valid_session
                self._spawn_monitors()
                if purpose == BACKUP_PURPOSE:
                    self.need_recovery = True
                else:
                    self.apic_assign_obj = obj
                    self.need_recovery = False
                return True

        return False
Exemplo n.º 27
0
    def __init__(self, args):
        # Login to the APIC
        self.session = ACI.Session(args.url, args.login, args.password)
        resp = self.session.login()
        if not resp.ok:
            print '%% Could not login to APIC'

        # Create the Git repository
        repo_parent_dir = os.getcwd()
        self.repo_dir = os.path.join(repo_parent_dir, 'apic-config-db')
        self.repo = git.Repo.init(self.repo_dir)
Exemplo n.º 28
0
def main():
    '''
    Main Routine
    '''
    # Take login credentials from the command line if provided
    description = ('Simple application to display details about faults in an ACI Fabric')
    creds = aci.Credentials('apic', description)
    creds.add_argument('--sort', choices=["asc", "desc"], default="desc", help='Specify the sort order within each severity based on time/date. Default is Descending order. i.e. Newest faults at the top of each category')

    args = creds.get()

    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        return

    # Available severity codes for ACI Fault Instances
    fault_severity = ["critical", "major", "minor", "warning", "info", "cleared"]

    fault_lookup = {} # Dictionary to be used to store the returned MO's, with the key being the severity
    fault_severity_count = {} # Dictionary to track total faults per severity

    # Loop through all fault severity types, perform a fault lookup in the system and return the list of MO's.
    # Assign to the fault_lookup dictionary, with severity as the key
    for fault_type in fault_severity:
        resp = query_fault(session, fault_type, args.sort)
        resp2 = resp['imdata']
        faultInst = []
        for entry in resp2:
            faultInst.append((entry["faultInst"]["attributes"]["code"],
                              entry["faultInst"]["attributes"]["descr"],
                              entry["faultInst"]["attributes"]["cause"],
                              entry["faultInst"]["attributes"]["occur"],
                              entry["faultInst"]["attributes"]["lastTransition"]))

        #print faultInst
        fault_lookup[fault_type] = faultInst
        # Find out the length of the inner list, based off the fault severity in the lookup
        # eg: fault_lookup["critical"] = [x,y,z]
        fault_severity_count[fault_type] = len(fault_lookup[fault_type])

    # Loop through each severity, sort by faultCode and then print it out
    for item in fault_severity:
        print_fault(item, fault_lookup[item])

    print "=" * 80
    print ("Summary of total faults")
    print "-" * 80
    for fault_summary in fault_severity:
        print (fault_summary + " = " + str(fault_severity_count[fault_summary]))
    print "=" * 80
Exemplo n.º 29
0
def tracker(args):
    """
    Main Endpoint tracker
    :param args: command line arguments
    :return: None
    """
    # Login to APIC
    session = aci.Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    c, cnx = connect_mysql(args)

    # Download all of the Endpoints and store in the database
    endpoints = aci.Endpoint.get(session)
    for ep in endpoints:
        try:
            epg = ep.get_parent()
        except AttributeError:
            continue
        app_profile = epg.get_parent()
        tenant = app_profile.get_parent()
        if ep.if_dn:
            for dn in ep.if_dn:
                match = re.match('protpaths-(\d+)-(\d+)', dn.split('/')[2])
                if match:
                    if match.group(1) and match.group(2):
                        int_name = "Nodes: " + match.group(
                            1) + "-" + match.group(2) + " " + ep.if_name
        else:
            int_name = ep.if_name

        try:
            data = (ep.mac, ep.ip, tenant.name, app_profile.name, epg.name,
                    ep.if_name, convert_timestamp_to_mysql(ep.timestamp))
        except ValueError, e:
            if args.daemon:
                logging.info(e)
            continue

        ep_exists = c.execute("""SELECT * FROM endpoints
                                 WHERE mac="%s"
                                 AND
                                 timestop is null;""" % ep.mac)
        c.fetchall()
        if not ep_exists:
            c.execute("""INSERT INTO endpoints (mac, ip, tenant,
                         app, epg, interface, timestart)
                         VALUES ('%s', '%s', '%s', '%s',
                         '%s', '%s', '%s')""" % data)
            cnx.commit()
Exemplo n.º 30
0
def main():
    description = 'Simple application that logs on to the APIC and displays stats for all of the Interfaces.'
    creds = ACI.Credentials('apic', description)
    # group = creds.add_mutually_exclusive_group()
    group1 = creds.add_argument_group('Export', 'Export a cable plan')
    group1.add_argument('-e', '--export_file', default=None, const='export text', dest='export_file', nargs='?',
                        help='Export cableplan from running fabric.  If EXPORT_FILE is specified, the '
                             'cableplan will be written to EXPORT_FILE')
    group2 = creds.add_argument_group('Compare', 'Compare cable plans')
    group2.add_argument('-c1', '--cableplan1',
                        type=str, nargs=1,
                        default=None,
                        help="Name of cableplan xml file.  If only CABLEPLAN1 is specified, "
                             "it will be compared to the running fabric.  If it is specified with "
                             "CABLEPLAN2 (the -c2 option), then it will compare CABLEPLAN1 with CABLEPLAN2")
    group2.add_argument('-c2', '--cableplan2',
                        type=str, nargs=1,
                        default=None,
                        help="Name of second cableplan xml file.  The second cableplan file.  This file will "
                             "be compared to CABLEPLAN1.  This option must only be used "
                             "in conjunction with the -c1 option.")

    args = creds.get()

    session = ACI.Session(args.url, args.login, args.password)

    if args.export_file and (args.cableplan1 or args.cableplan2):
        creds.print_help()
        print '\nError: export and compare operations are mutually exclusive'
        exit()

    if args.cableplan2 and not args.cableplan1:
        creds.print_help()
        print '\nError: -c2 option only valid with -c1 option'
        exit()

    if not args.export_file and not args.cableplan1:
        creds.print_help()
        print '\nError: Either export (-e) or compare (-c1) is required'
        exit()

    if args.export_file:
        if args.export_file == 'export text':
            export_to_file(session)
        else:
            export_to_file(session, args.export_file)

    if args.cableplan1:
        if args.cableplan2:
            compare_cable_plans(session, args.cableplan1[0], args.cableplan2[0])
        else:
            compare_cable_plans(session, args.cableplan1[0])