Exemplo n.º 1
0
def testConfiglet(server):
    ''' Tests all the functionalities pertaining to configlets in Cvp application'''

    # generate more than a page worth of configlets
    reference = [('configlet%d' % c, 'configlet%d' % c) for c in range(25)]

    # insert them into cvp
    print 'inserting %d configs into cvp' % len(reference)
    for name, config in reference:
        configlet = cvp.Configlet(name, config)
        server.addConfiglet(configlet)

    # try inserting again
    print 'Retry inserting %d configs into cvp' % len(reference)
    for name, config in reference:
        configlet = cvp.Configlet(name, config)
        try:
            server.addConfiglet(configlet)
        except cvpServices.CvpError as err:
            if err.errorCode == errorCodes.CONFIGLET_ALREADY_EXIST:
                pass
            else:
                raise

    # read them all back and verify
    print 'verifying %d configs from cvp' % len(reference)
    configs = server.getConfiglets()
    for name, config in reference:
        for configInfo in configs:
            if configInfo.name == name:
                assert configInfo.config == config

    # change a configet and update
    print 'Inserting a modified configlet'
    configlet = cvp.Configlet('configlet20', 'configlet25')
    server.updateConfiglet(configlet)

    # check whether config is modified
    print 'checking for updated config'
    configlet = server.getConfiglet('configlet20')
    assert configlet.config == 'configlet25'

    # remove them all
    print 'removing %d configs from cvp' % len(reference)
    for config in configs:
        server.deleteConfiglet(config)
    assert len(server.getConfiglets()) == 0
Exemplo n.º 2
0
def addConfiglets(server, db, configletNames=''):
    '''Adds all the configlets from the database ( db ) to the cvp instance
   This method catches allowable exceptions for smooth execution of the Cvp restore.
   But it raises all other exception denoting error situations. CvpError class object
   contains information about the occured exception
   Raises:
      CvpError -- If unknown error occur while configlet addition
   '''
    if 'configlets' in db:
        for configletInfo in db['configlets']:
            if configletNames and (str(configletInfo['name']).lower()
                                   not in configletNames):
                continue
            if configletInfo['configletType'] == 'Static':
                configlet = cvp.Configlet(configletInfo['name'],
                                          configletInfo['config'],
                                          configletInfo['configletType'])
            elif configletInfo['configletType'] == 'Builder':
                configlet = cvp.ConfigletBuilder(configletInfo['name'],
                                                 configletInfo['formList'],
                                                 configletInfo['mainScript'])
            elif configletInfo['configletType'] == 'Reconciled':
                continue
            elif configletInfo['configletType'] == 'Generated':
                continue
            else:
                raise cvpServices.CvpError(errorCodes.INVALID_CONFIGLET_TYPE)
            try:
                server.addConfiglet(configlet)
            except cvpServices.CvpError as err:
                if (err.errorCode == errorCodes.CONFIGLET_ALREADY_EXIST
                        or err.errorCode
                        == errorCodes.CONFIG_BUILDER_ALREADY_EXSIST):
                    print 'Configlet already exists:', configlet.name
                    currConfig = server.getConfiglet(configlet.name)
                    if configlet.jsonable() != currConfig.jsonable():
                        server.updateConfiglet(configlet)
                        print configlet.name, 'configlet updated'
                else:
                    raise
Exemplo n.º 3
0
from string import Template

#
# Info needed
#
ip = '192.168.0.5'
user = '******'
password = '******'
snmp_community = 'kalleolle'
ContainerName = 'Leaf'

cvpServer = cvp.Cvp(ip)
cvpServer.authenticate(user, password)

Replacements = {"snmp_community": snmp_community}

myConfig = Template("""
snmp-server community $snmp_community ro
""").safe_substitute(Replacements)

myConfigletName = 'Patriks SNMP community'
myConfiglet = cvp.Configlet(myConfigletName, myConfig)

cvpServer.addConfiglet(myConfiglet)

ConfigletList = []
ConfigletList.append(myConfiglet)

myContainer = cvpServer.getContainer(ContainerName)
cvpServer.mapConfigletToContainer(myContainer, ConfigletList)
Exemplo n.º 4
0
        final_vni_list,
        key=lambda x: list(
            map(int,
                re.findall('[0-9]+(?=\svni)', x)[0].split('/'))))
    # Compile config lists into strings and concatenate for unified configlet
    for vlan in final_vlan_list:
        final_vlan_config += vlan
        final_vlan_config += "!\n"
    for svi in final_svi_list:
        final_svi_config += svi
        final_svi_config += "!\n"
    for vni in final_vni_list:
        final_vni_config += vni
    final_config = final_vlan_config + final_svi_config + final_vni_config
    # Generate configlet class object
    final_configlet = cvp.Configlet("Data Center Vlans", final_config)
    # Update configlet and return task IDs
    tasks = server.updateConfiglet(final_configlet, waitForTaskIds=True)
    print "Configlet updated. The following task IDs have been created. Execute them to push changes.\n"
    for task in tasks:
        print task
# If no Vlan config exists, create configlet and apply to container named "Leafs"
except cvp.cvpServices.CvpError as e:
    if str(e).startswith("132801"):
        print "Data Center Vlans configlet does not exist. Creating...\n"
        base_config = new_vlan_config + "!\n" + new_svi_config + "!\ninterface Vxlan1\n" + new_vni_config
        base_configlet = cvp.Configlet("Data Center Vlans", base_config)
        server.addConfiglet(base_configlet)
        # Apply Configlet to Leafs Container
        print "\nApplying new configlet to Leafs Container...\n"
        base_configlet = [base_configlet]
Exemplo n.º 5
0
server = cvp.Cvp(host)
server.authenticate(user, password)

#
# Create needed configlets for the new DC
#

Replacements = {"dnsconfig": dnsconfig, "domainname": domainname}

dns_config = Template("""
	!
	ip name-server $dnsconfig
	ip domain-name $domainname
""").safe_substitute(Replacements)

dns_configlet_name = "DNS config for container " + container

dns_configlet = cvp.Configlet(dns_configlet_name, dns_config)
server.addConfiglet(dns_configlet)
configlet_list = []
configlet_list.append(dns_configlet)

#
# Find the device in CVP and add configlet to it
#

containers = server.getContainers()

for mycontainer in containers:
    if mycontainer.name == container:
        server.mapConfigletToContainer(mycontainer, configlet_list)
Exemplo n.º 6
0
#
# Create needed configlets for the new DC
#

for interface in interfaceList:
    Replacements = {"interface": interface, "description": description}

    description_config = Template("""
!
interface $interface
   description $description
""").safe_substitute(Replacements)

    description_configlet_name = "Interface description for interface " + interface

    description_configlet = cvp.Configlet(description_configlet_name,
                                          description_config)
    server.addConfiglet(description_configlet)
    configlet_list = []
    configlet_list.append(description_configlet)

    #
    # Find the device in CVP and add configlet to it
    #

    devices = server.getDevices()

    for mydevice in devices:
        if mydevice.fqdn == device:
            server.mapConfigletToDevice(mydevice, configlet_list)
Exemplo n.º 7
0
   vxlan vlan $vlan vni $vxlanid
   vxland vrf $vrfname vni $vrfid
!
interface Vlan$vlan
   vrf forwarding $vrfname
   ip address virtual $ipaddress/$netmask
!
router bgp $asnumber
   vlan $vlan
      rd $vxlanid:$loopbackip
      route-target both $asnumber:$vxlanid
      redistribute learned
   vrf $vrfname
      rd $vxlanid:$loopbackip
      route-target both $asnumber:$vrfid
      redistribute connected
""").safe_substitute(Replacements)

    evpn_configlet_name = "Customer " + vrfname + " EVPN instance for VXLAN/VLAN " + vlan
    evpn_configlet = cvp.Configlet(evpn_configlet_name, evpn_config)
    server.addConfiglet(evpn_configlet)
    configlet_list = []
    configlet_list.append(evpn_configlet)

    #
    # Find the device in CVP and add configlet to it
    #

    for mydevice in mydevices:
        if mydevice.fqdn == device:
            server.mapConfigletToDevice(mydevice, configlet_list)
	Replacements = { "dummy": "dummy"
					}
	vxlan_leaf_config = Template("""
interface Vxlan1
   vxlan source-interface Loopback1
   vxlan udp-port 4789
!
""").safe_substitute(Replacements)

# If debug is activated, only print config that should have gone into configlets,
# do not actually create configlets. If debug is not activated, create configlets
# and add them to CVP.
#

if debug == "no":
	dc_configlet = cvp.Configlet( dc_configlet_name , dc_base_config  )
	if configletExists( server , dc_configlet_name ):
		updateMyConfiglet( server , dc_configlet_name , dc_base_config )
		rebuild = 1
	else:
		server.addConfiglet( dc_configlet )
		configlet_list.append( dc_configlet )
		rebuild = 0

	vxlan_configlet_name = name + " Interface VXLAN1 base configuration"
	if rebuild == 1:
		updateMyConfiglet ( server , vxlan_configlet_name , vxlan_leaf_config )
	else:
		vxlan_configlet = cvp.Configlet( vxlan_configlet_name, vxlan_leaf_config )
		server.addConfiglet( vxlan_configlet )#
Exemplo n.º 9
0
interface {iface}
   description NNI {name}
   switchport trunk allowed vlan {vlan}
   switchport mode trunk
!
router bgp 11111
   !
   vlan {vlan}
      rd auto
      route-target both {vlan}:{vlan}
      redistribute learned
!
'''.format(vlan=vlan, name=name, iface=iface)
nni_configlet_name = "{name} Config".format(name=name)

# Create NNI Configlet for Uniform deployment
print "Creating configlet for {name}...\n".format(name=name)
new_nni_configlet = cvp.Configlet(nni_configlet_name, new_nni_config)
server.addConfiglet(new_nni_configlet)
new_nni_configlet = [new_nni_configlet]

# Apply Configlet to selected Devices
print "\nApplying configlet to selected devices...\n"
device_class_dict = server._getDevicesFromInventory(rtr_list)
for router in rtr_list:
    device_class = device_class_dict[router]
    task = server.mapConfigletToDevice(device_class, new_nni_configlet)
    print "\nConfiglet applied to {router}. The following task ID has been created.\n".format(
        router=router)
    print "Task \"" + task[0] + "\""
print ""
Exemplo n.º 10
0
tenant_config = tenant_template.render(tenant_info=tenant_info)
for leaf in border_leaves:
    switch_ip = str(int(switch_ip) + 1)
    tenant_info.update(switch_ip=switch_ip)
    fw_config = fw_template.render(tenant_info=tenant_info)
    border_config.update({leaf: fw_config})

# First apply Tenant VRF Config to all Leaves
# Retrieve Existing Tenant Config from configlet named "L3LS-v Tenants"
try:
    tenant_configlet = server.cvpService.getConfigletByName("L3LS-v Tenants")
    old_config = tenant_configlet["config"]
    # Add new Tenant config to existing configlet
    new_tenant_config = old_config + tenant_config
    # Generate configlet class object
    final_tenant_configlet = cvp.Configlet("L3LS-v Tenants", new_tenant_config)
    # Update configlet and return task IDs
    tasks = server.updateConfiglet(final_tenant_configlet, waitForTaskIds=True)
    print "L3LS-v Tenants Configlet updated. The following task IDs have been created. Execute them to push changes.\n"
    for task in tasks:
        print task
# If no Tenant config exists, create new configlet and apply to container named "L3LS-v Leaves"
except cvp.cvpServices.CvpError as e:
    if str(e).startswith("132801"):
        print "L3LS-v Tenants configlet does not exist. Creating...\n"
        base_tenant_configlet = cvp.Configlet("L3LS-v Tenants", tenant_config)
        server.addConfiglet(base_tenant_configlet)
        # Apply Configlet to Leafs Container
        print "\nApplying new configlet to L3LS-v Leaves Container...\n"
        base_tenant_configlet = [base_tenant_configlet]
        container_class = server.getContainer("L3LS-v Leaves")
Exemplo n.º 11
0
def testContainer(server):
    ''' Tests all the functionalities pertaining to containers in Cvp application'''

    #generate sample configlets
    reference = [('configlet%d' % c, 'configlet%d' % c) for c in range(25)]
    for name, config in reference:
        configlet = cvp.Configlet(name, config)
        server.addConfiglet(configlet)
    #generate random container hierarchy
    containerList = {}
    parentConfig = []
    parentConfig.append(reference[0][0])
    parentConfig.append(reference[2][0])
    parentConfig.append(reference[4][0])
    childConfig = []
    childConfig.append(reference[3][0])
    childConfig.append(reference[5][0])
    childConfig.append(reference[6][0])
    print 'inserting containers'
    currRootContainerInfo = server.getRootContainerInfo()
    for i in range(0, 5):
        container = cvp.Container('parentContainer-%d' % i,
                                  currRootContainerInfo.name, parentConfig)
        server.addContainer(container)
        server.mapConfigletToContainer(container, parentConfig)
        containerList[container.name] = container
        for j in range(0, 3):
            childContainer = cvp.Container(
                'parentContainer%dchildContainer-%d' % (i, j),
                'parentContainer-%d' % i, childConfig)
            server.addContainer(childContainer)
            server.mapConfigletToContainer(childContainer, childConfig)
            containerList[childContainer.name] = childContainer

    print 're-inserting same containers'
    for i in range(0, 5):
        container = cvp.Container('parentContainer-%d' % i,
                                  currRootContainerInfo.name)
        try:
            server.addContainer(container)
        except cvpServices.CvpError as err:
            if err.errorCode == errorCodes.DATA_ALREADY_EXISTS:
                pass
            else:
                raise

        for j in range(0, 3):
            childContainer = cvp.Container(
                'parentContainer%dchildContainer-%d' % (i, j),
                'parentContainer-%d' % i)
            try:
                server.addContainer(childContainer)
            except cvpServices.CvpError as err:
                if err.errorCode == errorCodes.DATA_ALREADY_EXISTS:
                    pass
                else:
                    raise

    # read them all back and verify
    print 'verifying all the containers'
    containers = server.getContainers()
    for container in containers:
        if container.name == currRootContainerInfo.name:
            continue
        if container.name in containerList:
            assert container.parentName == containerList[
                container.name].parentName
            assert container.configlets == containerList[
                container.name].configlets
        else:
            raise KeyError

    # remove all the containers
    print 'removing all the containers'
    for container in containers:
        if container.name != currRootContainerInfo.name:
            server.deleteContainer(container)

    configs = server.getConfiglets()
    for config in configs:
        server.deleteConfiglet(config)
    # Add new MAC-VRF to existing configs
    final_macvrf_list.append(new_macvrf_config)
    # Sort final config for visual pleasure
    final_macvrf_list = sorted(
        final_macvrf_list,
        key=lambda x: list(
            map(int,
                re.findall('[0-9]+(?=\n\s\s\s)', x)[0].split('/'))))
    # Compile config lists into strings and concatenate for unified configlet
    for macvrf_config in final_macvrf_list:
        final_macvrf_config += macvrf_config
        final_macvrf_config += "!\n"
    # Combine all configlet sections
    final_tenant_config = final_vlan_config + final_svi_config + final_vni_config + final_macvrf_config
    # Generate configlet class object
    final_tenant_configlet = cvp.Configlet("L3LS-v Tenant Vlans",
                                           final_tenant_config)
    # Update configlet and return task IDs
    tasks = server.updateConfiglet(final_tenant_configlet, waitForTaskIds=True)
    print "Configlet updated. The following task IDs have been created. Execute them to push changes.\n"
    for task in tasks:
        print task
# If no Vlan config exists, create configlet and apply to container named "L3LS-v Leaves"
except cvp.cvpServices.CvpError as e:
    if str(e).startswith("132801"):
        print "L3LS-v Tenant Vlans configlet does not exist. Creating...\n"
        if gateway != None:
            base_tenant_config = new_vlan_config + "!\n" + new_svi_config + "!\n"
            base_tenant_config += "interface Vxlan1\n" + new_vni_config + "\n!\n"
            base_tenant_config += "router bgp 65002\n   !\n" + new_macvrf_config
        else:
            base_tenant_config = new_vlan_config + "!\n"
Exemplo n.º 13
0
        if config_section.startswith("vlan"):
            final_vlan_list.append(config_section)
    # Add new vlan to existing configs
    final_vlan_list.append(new_vlan_config)
    # Sort final config for visual pleasure
    final_vlan_list = sorted(
        final_vlan_list,
        key=lambda x: list(
            map(int,
                re.findall('[0-9]+(?=\n\s\s\s)', x)[0].split('/'))))
    # Compile config lists into strings and concatenate for unified configlet
    for vlan_config in final_vlan_list:
        final_vlan_config += vlan_config
        final_vlan_config += "!\n"
    # Generate configlet class object
    final_vlan_configlet = cvp.Configlet("L2LS Vlans", final_vlan_config)
    # Update configlet and return task IDs
    tasks = server.updateConfiglet(final_vlan_configlet, waitForTaskIds=True)
    print "Configlet updated. The following task IDs have been created. Execute them to push changes.\n"
    for task in tasks:
        print task
# If no Vlan config exists, create configlet and apply to container named "Leafs"
except cvp.cvpServices.CvpError as e:
    if str(e).startswith("132801"):
        print "L2LS Vlans configlet does not exist. Creating...\n"
        base_vlan_config = new_vlan_config
        base_vlan_configlet = cvp.Configlet("L2LS Vlans", base_vlan_config)
        server.addConfiglet(base_vlan_configlet)
        # Apply Configlet to Leafs Container
        print "\nApplying new configlet to L2LS Container...\n"
        base_vlan_configlet = [base_vlan_configlet]
						"description": interface['neighbor'],
						"linknet": interface['linknet']
						}
		add_to_spine_config = Template("""
!
interface $local_interface
   description $description
   no switchport
   ip address $linknet/31
!""").safe_substitute(Replacements)

		spine_base_config = spine_base_config + add_to_spine_config

	if debug == "no":
		spine_configlet_name = spine_switch['name'] + " configuration"
		spine_configlet = cvp.Configlet( spine_configlet_name , spine_base_config )
		server.addConfiglet( spine_configlet )
	else:
		spine_configlet_name = spine_switch['name'] + " configuration"
		print "Contents of configlet %s:" % ( spine_configlet_name )
		print "%s" % ( spine_base_config )
		print "!"
		print "!"
		print "!"
#
# Create config unique for spine in cvx and her deployment types
#

	if deploymenttype == "her" or deploymenttype == "cvx":
		Replacements = {
						"routerid": spine_switch['loopback'],
Exemplo n.º 15
0
def main():
    sys.stderr.write('\n\n\n\n\n')

    timestamp = datetime.now().replace(microsecond=0)
    sys.stderr.write(
        '{} {}INFO{}: Getting CVP device inventory...\n\n\n\n\n'.format(
            timestamp, bcolors.BOLD, bcolors.NORMAL))
    deployedDevices = [
        device for device in cvpApis().getDevices()
        if device.containerName != 'Undefined'
    ]

    pendingTasks = []

    for device in deployedDevices:
        sys.stderr.write(
            '===========================================================\n')
        sys.stderr.write('Processing device {}.\n'.format(device.fqdn))
        sys.stderr.write(
            '===========================================================\n')

        timestamp = datetime.now().replace(microsecond=0)
        sys.stderr.write(
            '{} {}INFO{}: Obtaining configlets applied to device.\n'.format(
                timestamp, bcolors.BOLD, bcolors.NORMAL))
        existingConfiglets = device.configlets

        generatedConfigletsApplied = False
        newConfigletList = device.configlets

        for configlet in device.configlets:
            thisConfiglet = cvpApis().getConfiglet(configlet)

            if isinstance(thisConfiglet, cvp.GeneratedConfiglet):
                generatedConfigletsApplied = True

                newConfiglet = cvp.Configlet(thisConfiglet.name,
                                             thisConfiglet.config, 'Static',
                                             thisConfiglet.user,
                                             thisConfiglet.sslConfig)

                if debug:
                    sys.stderr.write('\n\n\nConfiglet: {}\n'.format(
                        newConfiglet.name))
                    sys.stderr.write('==============================\n')
                    sys.stderr.write('{}'.format(newConfiglet.config))

                else:
                    if trace:
                        timestamp = datetime.now().replace(microsecond=0)
                        sys.stderr.write(
                            '{} {}INFO{}: Removing Generated configlet {} from Device {}.\n'
                            .format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                                    configlet, device.fqdn))

                    try:
                        configletList = []
                        configletList.append(thisConfiglet)
                        taskIdList = cvpApis().removeConfigletAppliedToDevice(
                            device, configletList)

                    except cvpServices.CvpError as error:
                        timestamp = datetime.now().replace(microsecond=0)
                        sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                            timestamp, bcolors.WARNING, bcolors.NORMAL, error))

                    else:
                        taskList = []
                        for taskId in taskIdList:
                            cvpApis().cancelTask(taskId)

                        if trace:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write(
                                '{} {}INFO{}: Deleting Generated configlet {}.\n'
                                .format(timestamp, bcolors.BOLD,
                                        bcolors.NORMAL, configlet))

                        try:
                            cvpApis().deleteConfiglet(thisConfiglet)

                        except cvpServices.CvpError as error:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                                timestamp, bcolors.WARNING, bcolors.NORMAL,
                                error))

                        if trace:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write(
                                '{} {}INFO{}: Creating Static configlet {}.\n'.
                                format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                                       configlet))

                        try:
                            cvpApis().addConfiglet(newConfiglet)

                        except cvpServices.CvpError as error:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                                timestamp, bcolors.WARNING, bcolors.NORMAL,
                                error))

            # Match on Generated configlets prior to CVP 2016.1.1 which don't follow Class GeneratedConfiglet schema
            elif thisConfiglet is None:
                targetConfigletInfo = [
                    configletInfo
                    for configletInfo in cvpApis().getConfigletsInfo()
                    if configletInfo['name'] == configlet
                ]

                if targetConfigletInfo[0]['type'] == 'Generated':
                    generatedConfigletsApplied = True

                newConfiglet = cvp.Configlet(
                    configlet, targetConfigletInfo[0]['config'], 'Static',
                    targetConfigletInfo[0]['user'],
                    targetConfigletInfo[0]['sslConfig'])

                if debug:
                    sys.stderr.write('\n\n\nConfiglet: {}\n'.format(
                        newConfiglet.name))
                    sys.stderr.write('==============================\n')
                    sys.stderr.write('{}'.format(newConfiglet.config))

                else:
                    if trace:
                        timestamp = datetime.now().replace(microsecond=0)
                        sys.stderr.write(
                            '{} {}INFO{}: Removing Generated configlet {} from Device {}.\n'
                            .format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                                    configlet, device.fqdn))

                    try:
                        configletList = []
                        configletList.append(
                            cvp.Configlet(configlet,
                                          targetConfigletInfo[0]['config'],
                                          targetConfigletInfo[0]['type'],
                                          targetConfigletInfo[0]['user'],
                                          targetConfigletInfo[0]['sslConfig']))
                        taskIdList = cvpApis().removeConfigletAppliedToDevice(
                            device, configletList)

                    except cvpServices.CvpError as error:
                        timestamp = datetime.now().replace(microsecond=0)
                        sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                            timestamp, bcolors.WARNING, bcolors.NORMAL, error))

                    else:
                        taskList = []
                        for taskId in taskIdList:
                            cvpApis().cancelTask(taskId)

                        if trace:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write(
                                '{} {}INFO{}: Deleting Generated configlet {}.\n'
                                .format(timestamp, bcolors.BOLD,
                                        bcolors.NORMAL, configlet))

                        try:
                            cvpApis().deleteConfiglet(
                                cvp.Configlet(
                                    configlet,
                                    targetConfigletInfo[0]['config'],
                                    targetConfigletInfo[0]['type'],
                                    targetConfigletInfo[0]['user'],
                                    targetConfigletInfo[0]['sslConfig']))

                        except cvpServices.CvpError as error:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                                timestamp, bcolors.WARNING, bcolors.NORMAL,
                                error))

                        if trace:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write(
                                '{} {}INFO{}: Creating Static configlet {}.\n'.
                                format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                                       configlet))

                        try:
                            cvpApis().addConfiglet(newConfiglet)

                        except cvpServices.CvpError as error:
                            timestamp = datetime.now().replace(microsecond=0)
                            sys.stderr.write('{} {}WARNING{}: {}.\n'.format(
                                timestamp, bcolors.WARNING, bcolors.NORMAL,
                                error))

        if not debug and generatedConfigletsApplied:
            timestamp = datetime.now().replace(microsecond=0)
            sys.stderr.write(
                '{} {}INFO{}: Getting CVP configlet inventory info...\n'.
                format(timestamp, bcolors.BOLD, bcolors.NORMAL))
            allConfigletsInfo = cvpApis().getConfigletsInfo()

            ckl = []
            for configlet in newConfigletList:
                for configletInfo in allConfigletsInfo:
                    if re.match(configletInfo['name'], configlet) is not None:
                        ckl.append(configletInfo['key'])

            try:
                tasks = cvpApis().applyConfigletToDevice(
                    device.ipAddress, device.fqdn, device.macAddress,
                    device.configlets, ckl, [], [])

            except cvpServices.CvpError as err:
                timestamp = datetime.now().replace(microsecond=0)
                sys.stderr.write(
                    '{}{} {}ERROR{}: ({}) {}{}\nUnable to continue.\n'.format(
                        bcolors.NORMAL, timestamp, bcolors.ERROR,
                        bcolors.NORMAL, error.errorCode, error.errorMessage,
                        bcolors.NORMAL))
                sys.exit(0)

            else:
                timestamp = datetime.now().replace(microsecond=0)
                sys.stderr.write(
                    '{} {}INFO{}: Applying new static configlet(s) to device {}.\n'
                    .format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                            device.fqdn))

            for task in tasks:
                pendingTasks.append(int(task))

        sys.stderr.write('\n\n\n\n\n')

    if not debug and len(pendingTasks) > 0:
        timestamp = datetime.now().replace(microsecond=0)
        startTime = time()
        sys.stderr.write(
            '{} {}INFO{}: Creating convertGenerated2Static {} Change Control.\n'
            .format(timestamp, bcolors.BOLD, bcolors.NORMAL, timestamp))

        request = {}
        request['config'] = {}
        request['config']['id'] = str(uuid4())
        request['config']['name'] = 'convertGenerated2StaticV5 {}'.format(
            timestamp)
        request['config']['root_stage'] = {}
        request['config']['root_stage']['id'] = 'Root Stage'
        request['config']['root_stage']['stage_row'] = []

        stages = []
        i = 1
        for taskId in pendingTasks:
            stage = {}
            stage['id'] = str(uuid4())
            stage['name'] = 'stage1-{}'.format(i)
            stage['action'] = {}
            stage['action']['name'] = 'task'
            stage['action']['args'] = {}
            stage['action']['args']['TaskID'] = str(taskId)

            stages.append(stage)

            i += 1

        request['config']['root_stage']['stage_row'].append({'stage': stages})
        result = cvpApis().updateChangeControl(request)

        timestamp = datetime.now().replace(microsecond=0)
        sys.stderr.write(
            '{} {}INFO{}: Auto approved {} Change Control.\n'.format(
                timestamp, bcolors.BOLD, bcolors.NORMAL,
                request['config']['name']))
        cvpApis().addChangeControlApproval({
            'cc_id':
            result['id'],
            'cc_timestamp':
            result['update_timestamp']
        })

        timestamp = datetime.now().replace(microsecond=0)
        sys.stderr.write('{} {}INFO{}: Executing {} Change Control.\n'.format(
            timestamp, bcolors.BOLD, bcolors.NORMAL,
            request['config']['name']))
        cvpApis().startChangeControl({'cc_id': result['id']})

        if trace:
            timestamp = datetime.now().replace(microsecond=0)
            sys.stderr.write(
                '{} {}INFO{}: Checking status of {} Change Control.\n'.format(
                    timestamp, bcolors.BOLD, bcolors.NORMAL,
                    request['config']['name']))

        ccRunning = True
        ccFailed = False
        while ccRunning:
            timestamp = datetime.now().replace(microsecond=0)
            status = cvpApis().getChangeControlStatus({'cc_id': result['id']})

            if status['status']['state'] == 'Completed':
                ccRunning = False
                timestamp = datetime.now().replace(microsecond=0)
                sys.stderr.write(
                    '{} {}INFO{}: {} Change Control complete.  Exiting.\n'.
                    format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                           request['config']['name']))

            elif status['status']['state'] == 'Failed':
                ccRunning = False
                ccFailed = True
                timestamp = datetime.now().replace(microsecond=0)
                sys.stderr.write(
                    '{} {}ERROR{}: Configlet Fix {} Change Control unsuccessful.  Initiating Network Rollback.\n'
                    .format(timestamp, bcolors.ERROR, bcolors.NORMAL,
                            request['config']['name']))

            else:
                timestamp = datetime.now().replace(microsecond=0)
                sys.stderr.write(
                    '{} {}INFO{}: {} Change Control outstanding.  Sleeping 30 seconds...\n'
                    .format(timestamp, bcolors.BOLD, bcolors.NORMAL,
                            request['config']['name']))
                sleep(30)

    elif not debug and len(pendingTasks) > 0:
        timestamp = datetime.now().replace(microsecond=0)
        sys.stderr.write(
            '{} {}INFO{}: Created tasks {}.  Please execute from CVP GUI..\n'.
            format(timestamp, bcolors.BOLD, bcolors.NORMAL, pendingTasks))
        return

    else:
        timestamp = datetime.now().replace(microsecond=0)
        sys.stderr.write('{} {}INFO{}: No changes made. Exiting.\n'.format(
            timestamp, bcolors.BOLD, bcolors.NORMAL))
Exemplo n.º 16
0
        "gateway": gateway,
        "mask": mask
    }
else:
    vlan_info = {"vlan_id": vlan, "vlan_name": name}
vlan_config = vlan_template.render(vlan_info=vlan_info)

# Retrieve Existing Tenant Config from configlet named "L3LS-v Tenant Vlans"
try:
    tenant_vlan_configlet = server.cvpService.getConfigletByName(
        "L3LS-v Tenant Vlans")
    old_config = tenant_vlan_configlet["config"]
    # Add new vlan config to existing configlet
    new_vlan_config = old_config + vlan_config
    # Generate configlet class object
    final_vlan_configlet = cvp.Configlet("L3LS-v Tenant Vlans",
                                         new_vlan_config)
    # Update configlet and return task IDs
    tasks = server.updateConfiglet(final_vlan_configlet, waitForTaskIds=True)
    print "L3LS-v Tenant Vlans Configlet updated. The following task IDs have been created. Execute them to push changes.\n"
    for task in tasks:
        print task
# If no Vlan config exists, create new configlet and apply to container named "L3LS-v Leaves"
except cvp.cvpServices.CvpError as e:
    if str(e).startswith("132801"):
        print "L3LS-v Tenant Vlans configlet does not exist. Creating...\n"
        base_vlan_configlet = cvp.Configlet("L3LS-v Tenant Vlans", vlan_config)
        server.addConfiglet(base_vlan_configlet)
        # Apply Configlet to Leafs Container
        print "\nApplying new configlet to L3LS-v Leaves Container...\n"
        base_vlan_configlet = [base_vlan_configlet]
        container_class = server.getContainer("L3LS-v Leaves")
Exemplo n.º 17
0
if trunk == "no":
    Replacements = {
        "vlan": vlan,
        "vni": vni,
        "interface": interface,
    }

    vxlan_config = Template("""
	!
	interface vxlan1
	   vxlan vlan $vlan vni $vni
	!
	interface $interface
	   switchport access vlan $vlan
	""").safe_substitute(Replacements)

vxlan_configlet = cvp.Configlet(vxlan_configlet_name, vxlan_config)
server.addConfiglet(vxlan_configlet)
configlet_list = []
configlet_list.append(vxlan_configlet)

#
# Find the device in CVP and add configlet to it
#

devices = server.getDevices()

for mydevice in devices:
    if mydevice.fqdn == device:
        server.mapConfigletToDevice(mydevice, configlet_list)