def dic_fe_prod(rack): CIDRFEipv4 = {} CIDRFEipv4[rack] = [] CIDRFEipv6 = {} CIDRFEipv6[rack] = [] subnetsRackFEipv4 = {} subnetsRackFEipv4[rack] = [] subnetsRackFEipv6 = {} subnetsRackFEipv6[rack] = [] podsFEipv4 = {} podsFEipv4[rack] = [] podsFEipv6 = {} podsFEipv6[rack] = [] redes = dict() ranges = dict() ipv6 = dict() try: # CIDR sala 01 => 172.20.0.0/14 # Sumário do rack => 172.20.0.0/21 CIDRFEipv4[0] = IPNetwork(get_variable('cidr_fe_v4')) # CIDRFE[1] = IPNetwork('172.20.1.0/14') CIDRFEipv6[0] = IPNetwork(get_variable('cidr_fe_v6')) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável VLAN_MNGT<BE,FE,BO,CA,FILER> ou CIDR<FEv4,FEv6>.' )
def generate_delete_file(user, equip_id, interface_list, channel): try: INTERFACE_CONFIG_FILES_PATH = get_variable("interface_config_files_path") TEMPLATE_REMOVE_CHANNEL = get_variable("template_remove_channel") TEMPLATE_REMOVE_INTERFACE = get_variable("template_remove_interface") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável INTERFACE_CONFIG_TEMPLATE_PATH, TEMPLATE_REMOVE_CHANNEL ou TEMPLATE_REMOVE_INTERFACE.") key_dict = dict() config_to_be_saved = "" request_id = getattr(local, 'request_id', NO_REQUEST_ID) filename_out = "equip_"+str(equip_id) +"_channel_"+str(channel.id)+"_remove_"+str(request_id) filename_to_save = INTERFACE_CONFIG_FILES_PATH+filename_out rel_file_to_deploy = INTERFACE_CONFIG_FILES_PATH+filename_out key_dict['PORTCHANNEL_NAME'] = channel.nome for i in interface_list: key_dict['INTERFACE_NAME'] = i.interface try: interface_template_file = _load_template_file(int(equip_id),TEMPLATE_REMOVE_INTERFACE) config_to_be_saved += interface_template_file.render(Context(key_dict)) except exceptions.InterfaceTemplateException, e: log.error(e) raise exceptions.InterfaceTemplateException() except KeyError, exception: log.error("Erro: %s " % exception) raise exceptions.InvalidKeyException(exception)
def dic_fe_prod(rack): CIDRFEipv4 = {} CIDRFEipv4[rack] = [] CIDRFEipv6 = {} CIDRFEipv6[rack] = [] subnetsRackFEipv4 = {} subnetsRackFEipv4[rack] = [] subnetsRackFEipv6 = {} subnetsRackFEipv6[rack] = [] redes=dict() ranges=dict() ipv6=dict() try: #CIDR sala 01 => 172.20.0.0/14 #Sumário do rack => 172.20.0.0/21 CIDRFEipv4[0] = IPNetwork(get_variable("cidr_fe_v4")) #CIDRFE[1] = IPNetwork('172.20.1.0/14') CIDRFEipv6[0] = IPNetwork(get_variable("cidr_fe_v6")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável VLAN_MNGT<BE,FE,BO,CA,FILER> ou CIDR<FEv4,FEv6>.")
def _generate_config_file(interfaces_list): log.info("_generate_config_file") try: INTERFACE_CONFIG_TOAPPLY_REL_PATH = get_variable( 'interface_config_toapply_rel_path') INTERFACE_CONFIG_FILES_PATH = get_variable( 'interface_config_files_path') TEMPLATE_TYPE_INT = get_variable('template_type_int') TEMPLATE_TYPE_CHANNEL = get_variable('template_type_channel') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável INTERFACE_CONFIG' '<TOAPPLY,TEMPLATE,FILES>_PATH.') # check if all interfaces are configuring same equipment # raises error if not equipment_interfaces = dict() equipment_interfaces[interfaces_list[0].equipamento.nome] = 1 for interface in interfaces_list: if interface.equipamento.nome not in equipment_interfaces: log.error('Error trying to configure multiple interfaces in ' 'different equipments in same call.') raise exceptions.InvalidIdInterfaceException config_to_be_saved = '' equipment_id = interfaces_list[0].equipamento.id request_id = getattr(local, 'request_id', NO_REQUEST_ID) extension = '.py' if interfaces_list[ 0].equipamento.modelo.marca.nome == "HP" else '' filename_out = 'int-d_' + str( interfaces_list[0].id) + '_config_' + str(request_id) + extension log.debug(filename_out) filename_to_save = INTERFACE_CONFIG_FILES_PATH + filename_out rel_file_to_deploy = INTERFACE_CONFIG_TOAPPLY_REL_PATH + filename_out int_template_file = _load_template_file(equipment_id, TEMPLATE_TYPE_INT) channels_configured = {} for interface in interfaces_list: key_dict = _generate_dict(interface) # If Interface is in channel, render the template for channel, # only once for each channel try: if interface.channel is not None: if interface.channel.id is not None and \ interface.channel.id not in channels_configured.keys(): channel_template_file = _load_template_file( equipment_id, TEMPLATE_TYPE_CHANNEL) config_to_be_saved += channel_template_file.render( Context(key_dict)) channels_configured[interface.channel.id] = 1 # Render the template for interface config_to_be_saved += int_template_file.render(Context(key_dict)) except KeyError, exception: log.error('Erro: %s ' % exception) raise exceptions.InvalidKeyException(exception)
def _generate_config_file(interfaces_list): log.info("_generate_config_file") try: INTERFACE_CONFIG_TOAPPLY_REL_PATH = get_variable( 'interface_config_toapply_rel_path') INTERFACE_CONFIG_FILES_PATH = get_variable( 'interface_config_files_path') TEMPLATE_TYPE_INT = get_variable('template_type_int') TEMPLATE_TYPE_CHANNEL = get_variable('template_type_channel') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável INTERFACE_CONFIG' '<TOAPPLY,TEMPLATE,FILES>_PATH.') # check if all interfaces are configuring same equipment # raises error if not equipment_interfaces = dict() equipment_interfaces[interfaces_list[0].equipamento.nome] = 1 for interface in interfaces_list: if interface.equipamento.nome not in equipment_interfaces: log.error( 'Error trying to configure multiple interfaces in ' 'different equipments in same call.') raise exceptions.InvalidIdInterfaceException config_to_be_saved = '' equipment_id = interfaces_list[0].equipamento.id request_id = getattr(local, 'request_id', NO_REQUEST_ID) extension = '.py' if interfaces_list[0].equipamento.modelo.marca.nome == "HP" else '' filename_out = 'int-d_' + str(interfaces_list[0].id) + '_config_' + str(request_id) + extension log.debug(filename_out) filename_to_save = INTERFACE_CONFIG_FILES_PATH + filename_out rel_file_to_deploy = INTERFACE_CONFIG_TOAPPLY_REL_PATH + filename_out int_template_file = _load_template_file(equipment_id, TEMPLATE_TYPE_INT) channels_configured = {} for interface in interfaces_list: key_dict = _generate_dict(interface) # If Interface is in channel, render the template for channel, # only once for each channel try: if interface.channel is not None: if interface.channel.id is not None and \ interface.channel.id not in channels_configured.keys(): channel_template_file = _load_template_file( equipment_id, TEMPLATE_TYPE_CHANNEL) config_to_be_saved += channel_template_file.render( Context(key_dict)) channels_configured[interface.channel.id] = 1 # Render the template for interface config_to_be_saved += int_template_file.render(Context(key_dict)) except KeyError, exception: log.error('Erro: %s ' % exception) raise exceptions.InvalidKeyException(exception)
def post(self, *args, **kwargs): try: log.info('RACK deploy.') rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) try: PATH_TO_ADD_CONFIG = get_variable('path_to_add_config') REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou " "REL_PATH_TO_ADD_CONFIG.") path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*' arquivos = glob.glob(path_config) # Get all files and search for equipments of the rack for var in arquivos: filename_equipments = var.split('/')[-1] rel_filename = REL_PATH_TO_ADD_CONFIG + filename_equipments log.debug("rel_filename: %s" % rel_filename) # Check if file is config relative to this rack if rack.nome in filename_equipments: # Apply config only in spines. Leaves already have all necessary config in startup if "ADD" in filename_equipments: # Check if equipment in under maintenance. If so, does not aplly on it equipment_name = filename_equipments.split('-ADD-')[0] log.debug("equipment_name: %s" % equipment_name) try: equip = Equipamento.get_by_name(equipment_name) if not equip.maintenance: lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_USERSCRIPT % (equip.id) output = deploy_facade.deploy_config_in_equipment_synchronous(rel_filename, equip, lockvar) log.debug("equipment output: %s" % (output)) except Exception as e: log.exception(e) raise exceptions.RackAplError(e) # SEPARAR AQUI! datas = dict() success_map = dict() success_map['rack_conf'] = True datas['sucesso'] = success_map return Response(datas, status=status.HTTP_201_CREATED) except exceptions.RackNumberNotFoundError as e: log.exception(e) raise exceptions.NetworkAPIException(e) except var_exceptions.VariableDoesNotExistException as e: log.error(e) raise api_exceptions.NetworkAPIException( 'Erro buscando a variável PATH_TO_ADD_CONFIG ou REL_PATH_TO_ADD_CONFIG. Erro: %s' % e) except Exception as e: log.exception(e) raise api_exceptions.NetworkAPIException(e)
def dic_pods(rack): subnetsRackBEipv4 = {} subnetsRackBEipv4[rack] = [] PODSBEipv4 = {} redesPODSBEipv4 = {} PODSBEFEipv4 = {} redesPODSBEFEipv4 = {} PODSBEBOipv4 = {} redesPODSBEBOipv4 = {} PODSBECAipv4 = {} redesPODSBECAipv4 = {} PODSBEipv4[rack] = [] redesPODSBEipv4[rack] = [] PODSBEFEipv4[rack] = [] redesPODSBEFEipv4[rack] = [] PODSBEBOipv4[rack] = [] redesPODSBEBOipv4[rack] = [] PODSBECAipv4[rack] = [] redesPODSBECAipv4[rack] = [] PODSBEipv6 = {} redesPODSBEipv6 = {} PODSBEFEipv6 = {} redesPODSBEFEipv6 = {} PODSBEBOipv6 = {} redesPODSBEBOipv6 = {} PODSBECAipv6 = {} redesPODSBECAipv6 = {} subnetsRackBEipv6 = {} PODSBEipv6[rack] = [] redesPODSBEipv6[rack] = [] PODSBEFEipv6[rack] = [] redesPODSBEFEipv6[rack] = [] PODSBEBOipv6[rack] = [] redesPODSBEBOipv6[rack] = [] PODSBECAipv6[rack] = [] redesPODSBECAipv6[rack] = [] subnetsRackBEipv6[rack] = [] try: # CIDR sala 01 => 10.128.0.0/12 CIDRBEipv4 = IPNetwork(get_variable('cidr_be_v4')) CIDRBEipv6 = IPNetwork(get_variable('cidr_be_v6')) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável CIDR<BEv4,BEv6>.')
def dic_pods(rack): subnetsRackBEipv4 = {} subnetsRackBEipv4[rack] = [] PODSBEipv4 = {} redesPODSBEipv4 = {} PODSBEFEipv4 = {} redesPODSBEFEipv4 = {} PODSBEBOipv4 = {} redesPODSBEBOipv4 = {} PODSBECAipv4 = {} redesPODSBECAipv4 = {} PODSBEipv4[rack]=[] redesPODSBEipv4[rack]=[] PODSBEFEipv4[rack]=[] redesPODSBEFEipv4[rack]=[] PODSBEBOipv4[rack]=[] redesPODSBEBOipv4[rack]=[] PODSBECAipv4[rack]=[] redesPODSBECAipv4[rack]=[] PODSBEipv6 = {} redesPODSBEipv6 = {} PODSBEFEipv6 = {} redesPODSBEFEipv6 = {} PODSBEBOipv6 = {} redesPODSBEBOipv6 = {} PODSBECAipv6 = {} redesPODSBECAipv6 = {} subnetsRackBEipv6 = {} PODSBEipv6[rack]=[] redesPODSBEipv6[rack]=[] PODSBEFEipv6[rack]=[] redesPODSBEFEipv6[rack]=[] PODSBEBOipv6[rack]=[] redesPODSBEBOipv6[rack]=[] PODSBECAipv6[rack]=[] redesPODSBECAipv6[rack]=[] subnetsRackBEipv6[rack]=[] try: #CIDR sala 01 => 10.128.0.0/12 CIDRBEipv4 = IPNetwork(get_variable("cidr_be_v4")) CIDRBEipv6 = IPNetwork(get_variable("cidr_be_v6")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável CIDR<BEv4,BEv6>.")
def _generate_config_file(interfaces_list): try: INTERFACE_CONFIG_TOAPPLY_REL_PATH = get_variable("interface_config_toapply_rel_path") INTERFACE_CONFIG_FILES_PATH = get_variable("interface_config_files_path") TEMPLATE_TYPE_INT = get_variable("template_type_int") TEMPLATE_TYPE_CHANNEL = get_variable("template_type_channel") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável INTERFACE_CONFIG<TOAPPLY,TEMPLATE,FILES>_PATH." ) # check if all interfaces are configuring same equipment # raises error if not equipment_interfaces = dict() equipment_interfaces[interfaces_list[0].equipamento.nome] = 1 for interface in interfaces_list: if interface.equipamento.nome not in equipment_interfaces: log.error("Error trying to configure multiple interfaces in different equipments in same call.") raise exceptions.InvalidIdInterfaceException config_to_be_saved = "" equipment_id = interfaces_list[0].equipamento.id request_id = getattr(local, "request_id", NO_REQUEST_ID) filename_out = "int-d_" + str(interfaces_list[0].id) + "_config_" + str(request_id) filename_to_save = INTERFACE_CONFIG_FILES_PATH + filename_out rel_file_to_deploy = INTERFACE_CONFIG_TOAPPLY_REL_PATH + filename_out int_template_file = _load_template_file(equipment_id, TEMPLATE_TYPE_INT) channels_configured = {} for interface in interfaces_list: key_dict = _generate_dict(interface) # If Interface is in channel, render the template for channel, only once # for each channel try: if interface.channel is not None: if interface.channel.id is not None and interface.channel.id not in channels_configured.keys(): channel_template_file = _load_template_file(equipment_id, TEMPLATE_TYPE_CHANNEL) config_to_be_saved += channel_template_file.render(Context(key_dict)) channels_configured[interface.channel.id] = 1 # Render the template for interface config_to_be_saved += int_template_file.render(Context(key_dict)) except KeyError, exception: log.error("Erro: %s " % exception) raise exceptions.InvalidKeyException(exception)
def ambiente_prod_fe(user, rack, environment_list): redes, ranges, ipv6 = dic_fe_prod(rack.numero) ambientes= dict() ambientes['LOG']="PRODUCAO" ambientes['L3']= rack.nome ambientes['DC']="FE" redes['TIPO']= "Rede invalida equipamentos" ipv6['TIPO']= "Rede invalida equipamentos" acl_path = 'FECLOUD' #criar ambiente env = criar_ambiente(user, ambientes, ranges, acl_path, "Servidores", "FEVrf") environment_list.append(env) #configuracao dos ambientes redes['VERSION']="ipv4" config_ambiente(user, redes, ambientes) ipv6['VERSION']="ipv6" config_ambiente(user, ipv6, ambientes) vlans=dict() try: vlans['VLAN_NUM'] = int(get_variable("num_vlan_acl_fe")) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável NUM_VLAN_ACL_FE") vlans['VLAN_NAME'] = "ACL_"+ambientes.get('DC')+"_"+ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def aplicar(rack): try: PATH_TO_CONFIG = get_variable("path_to_config") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_CONFIG.") path_config = PATH_TO_CONFIG +'*'+rack.nome+'*' arquivos = glob.glob(path_config) for var in arquivos: name_equipaments = var.split('/')[-1][:-4] #Check if file is config relative to this rack for nome in name_equipaments: #Check if file is config relative to this rack if rack.nome in nome: #Apply config only in spines. Leaves already have all necessary config in startup if "DEL" in nome: #Check if equipment in under maintenance. If so, does not aplly on it try: equip = Equipamento.get_by_name(nome) if not equip.maintenance: (erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w 300" % (var, nome)) if erro: raise RackAplError(None, None, "Falha ao aplicar as configuracoes: %s" %(result)) except RackAplError, e: raise e except: #Error equipment not found, do nothing pass
def aplicar(rack): try: PATH_TO_CONFIG = get_variable("path_to_config") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável PATH_TO_CONFIG.") path_config = PATH_TO_CONFIG + '*' + rack.nome + '*' arquivos = glob.glob(path_config) for var in arquivos: name_equipaments = var.split('/')[-1][:-4] #Check if file is config relative to this rack for nome in name_equipaments: #Check if file is config relative to this rack if rack.nome in nome: #Apply config only in spines. Leaves already have all necessary config in startup if "DEL" in nome: #Check if equipment in under maintenance. If so, does not aplly on it try: equip = Equipamento.get_by_name(nome) if not equip.maintenance: (erro, result) = commands.getstatusoutput( "/usr/bin/backuper -T acl -b %s -e -i %s -w 300" % (var, nome)) if erro: raise RackAplError( None, None, "Falha ao aplicar as configuracoes: %s" % (result)) except RackAplError, e: raise e except: #Error equipment not found, do nothing pass
def _load_template_file(equipment_id, template_type): try: INTERFACE_CONFIG_TEMPLATE_PATH = get_variable("interface_config_template_path") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável INTERFACE_CONFIG<TOAPPLY,TEMPLATE,FILES>_PATH." ) try: equipment_template = (EquipamentoRoteiro.search(None, equipment_id, template_type)).uniqueResult() except: log.error("Template type %s not found. Equip: %s" % (template_type, equipment_id)) raise exceptions.InterfaceTemplateException() filename_in = INTERFACE_CONFIG_TEMPLATE_PATH + equipment_template.roteiro.roteiro # Read contents from file try: file_handle = open(filename_in, "r") template_file = Template(file_handle.read()) file_handle.close() except IOError, e: log.error("Error opening template file for read: %s. Equip: %s" % (filename_in, equipment_id)) raise e
def _load_template_file(equipment_id, template_type): log.info("_load_template_file") try: INTERFACE_CONFIG_TEMPLATE_PATH = get_variable( 'interface_config_template_path') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável INTERFACE_CONFIG' '<TOAPPLY,TEMPLATE,FILES>_PATH.') try: equipment_template = (EquipamentoRoteiro.search( None, equipment_id, template_type)).uniqueResult() except: log.error('Template type %s not found. Equip: %s' % (template_type, equipment_id)) raise exceptions.InterfaceTemplateException() filename_in = INTERFACE_CONFIG_TEMPLATE_PATH + \ equipment_template.roteiro.roteiro # Read contents from file try: file_handle = open(filename_in, 'r') template_file = Template(file_handle.read()) file_handle.close() except IOError, e: log.error('Error opening template file for read: %s. Equip: %s' % (filename_in, equipment_id)) raise e
def ambiente_prod(user, rack, environment_list): redes, ipv6 = dic_pods(rack.numero) divisao_aclpaths = [['BE','BECLOUD'],['BEFE','BEFE'],['BEBORDA','BEBORDA'],['BECACHOS','BECACHOS']] grupol3 = rack.nome ambiente_logico = "PRODUCAO" ambientes= dict() ambientes['LOG']=ambiente_logico ambientes['L3']= grupol3 ranges=dict() hosts=dict() vlans=dict() try: base_vlan = int(get_variable("num_vlan_acl_be")) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável NUM_VLAN_ACL_BE") hosts['TIPO']= "Rede invalida equipamentos" ipv6['TIPO']= "Rede invalida equipamentos" for item in divisao_aclpaths: divisaodc = item[0] acl_path = item[1] ambientes['DC']=divisaodc #criar ambiente vlan_min = divisaodc+"_VLAN_MIN" vlan_max = divisaodc+"_VLAN_MAX" ranges['MAX']= redes.get(vlan_max) ranges['MIN']= redes.get(vlan_min) env = criar_ambiente(user, ambientes, ranges, acl_path, "Servidores", "BEVrf") environment_list.append(env) #configuracao dos ambientes prefix = divisaodc+"_PREFIX" rede = divisaodc+"_REDE" hosts['PREFIX']= redes.get(prefix) hosts['REDE']= redes.get(rede) hosts['VERSION']="ipv4" config_ambiente(user, hosts, ambientes) ipv6['PREFIX']=ipv6.get(prefix) ipv6['REDE']=ipv6.get(rede) ipv6['VERSION']="ipv6" config_ambiente(user, ipv6, ambientes) vlans['VLAN_NUM'] = base_vlan base_vlan += 1 vlans['VLAN_NAME'] = "ACL_"+divisaodc+"_"+ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def inner(*args, **kwargs): if get_variable('mock_return', '0') == '0': return func(*args, **kwargs) def mock(): return mock_value return mock()
def post(self, *args, **kwargs): try: log.info('RACK deploy.') rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) try: PATH_TO_ADD_CONFIG = get_variable('path_to_add_config') REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável PATH_TO_ADD_CONFIG ou " "REL_PATH_TO_ADD_CONFIG.") path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*' arquivos = glob.glob(path_config) # Get all files and search for equipments of the rack for var in arquivos: filename_equipments = var.split('/')[-1] rel_filename = "../../" + REL_PATH_TO_ADD_CONFIG + filename_equipments log.debug("rel_filename: %s" % rel_filename) # Check if file is config relative to this rack if rack.nome in filename_equipments: # Apply config only in spines. Leaves already have all necessary config in startup if "ADD" in filename_equipments: # Check if equipment in under maintenance. If so, does not aplly on it equipment_name = filename_equipments.split('-ADD-')[0] log.debug("equipment_name: %s" % equipment_name) try: equip = Equipamento.get_by_name(equipment_name) if not equip.maintenance: (erro, result) = commands.getstatusoutput( "/usr/bin/backuper -T acl -b %s -e -i %s -w " "300" % (rel_filename, equipment_name)) log.debug("erro: %s, result: %s" % (str(erro), str(result))) if erro: raise exceptions.RackAplError() except exceptions.RackAplError, e: raise e except: # Error equipment not found, do nothing pass
def dic_hosts_cloud(rack): subnetsRackBEipv4 = {} subnetsRackBEipv4[rack] = [] redesHostsipv4 = {} redesHostsipv4[rack] = [] redeHostsBEipv4 = {} redeHostsBEipv4[rack] = [] redeHostsFEipv4 = {} redeHostsFEipv4[rack] = [] redeHostsBOipv4 = {} redeHostsBOipv4[rack] = [] redeHostsCAipv4 = {} redeHostsCAipv4[rack] = [] redeHostsFILERipv4 = {} redeHostsFILERipv4[rack] = [] subnetsRackBEipv6 = {} subnetsRackBEipv6[rack] = [] redesHostsipv6 = {} redesHostsipv6[rack] = [] redeHostsBEipv6 = {} redeHostsBEipv6[rack] = [] redeHostsFEipv6 = {} redeHostsFEipv6[rack] = [] redeHostsBOipv6 = {} redeHostsBOipv6[rack] = [] redeHostsCAipv6 = {} redeHostsCAipv6[rack] = [] redeHostsFILERipv6 = {} redeHostsFILERipv6[rack] = [] hosts = dict() BE = dict() FE = dict() BO = dict() CA = dict() FILER = dict() ipv6 = dict() BE_ipv6 = dict() FE_ipv6 = dict() BO_ipv6 = dict() CA_ipv6 = dict() FILER_ipv6 = dict() try: # CIDR sala 01 => 10.128.0.0/12 CIDRBEipv4 = IPNetwork(get_variable('cidr_be_v4')) CIDRBEipv6 = IPNetwork(get_variable('cidr_be_v6')) hosts['VLAN_MNGT_BE'] = int(get_variable('vlan_mngt_be')) hosts['VLAN_MNGT_FE'] = int(get_variable('vlan_mngt_fe')) hosts['VLAN_MNGT_BO'] = int(get_variable('vlan_mngt_bo')) hosts['VLAN_MNGT_CA'] = int(get_variable('vlan_mngt_ca')) hosts['VLAN_MNGT_FILER'] = int(get_variable('vlan_mngt_filer')) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável VLAN_MNGT<BE,FE,BO,CA,FILER> ou CIDR<BEv4,BEv6>.' )
def ambiente_borda(user, rack, environment_list): ranges = dict() ranges['MAX'] = None ranges['MIN'] = None ranges_vlans = dict() try: ranges_vlans['BORDA_DSR_VLAN_MIN'] = int( get_variable('borda_dsr_vlan_min')) ranges_vlans['BORDA_DSR_VLAN_MAX'] = int( get_variable('borda_dsr_vlan_max')) ranges_vlans['BORDA_DMZ_VLAN_MIN'] = int( get_variable('borda_dmz_vlan_min')) ranges_vlans['BORDA_DMZ_VLAN_MAX'] = int( get_variable('borda_dmz_vlan_max')) ranges_vlans['BORDACACHOS_VLAN_MIN'] = int( get_variable('bordacachos_vlan_min')) ranges_vlans['BORDACACHOS_VLAN_MAX'] = int( get_variable('bordacachos_vlan_max')) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando as variáveis BORDA<DSR,DMZ,CACHOS>_VLAN_<MAX,MIN>.') try: base_vlan = int(get_variable('num_vlan_acl_bordadsr')) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável NUM_VLAN_ACL_BORDADSR') ambientes = dict() vlans = dict() ambientes['LOG'] = 'PRODUCAO' ambientes['L3'] = rack.nome divisao_aclpaths = [['BORDA_DSR', 'BORDA-DSR', 'BordaVrf'], ['BORDA_DMZ', 'BORDA-DMZ', 'BordaVrf'], ['BORDACACHOS', 'BORDACACHOS', 'BordaCachosVrf']] for item in divisao_aclpaths: divisaodc = item[0] acl_path = item[1] vrf = item[2] vlan_min = divisaodc + '_VLAN_MIN' vlan_max = divisaodc + '_VLAN_MAX' ranges['MAX'] = ranges_vlans.get(vlan_max) ranges['MIN'] = ranges_vlans.get(vlan_min) ambientes['DC'] = divisaodc env = criar_ambiente(user, ambientes, ranges, acl_path, 'Servidores', vrf) environment_list.append(env) vlans['VLAN_NUM'] = base_vlan base_vlan += 1 vlans['VLAN_NAME'] = 'ACL_' + divisaodc + '_' + ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def dic_hosts_cloud(rack): subnetsRackBEipv4 = {} subnetsRackBEipv4[rack] = [] redesHostsipv4={} redesHostsipv4[rack]=[] redeHostsBEipv4={} redeHostsBEipv4[rack]=[] redeHostsFEipv4={} redeHostsFEipv4[rack]=[] redeHostsBOipv4={} redeHostsBOipv4[rack]=[] redeHostsCAipv4={} redeHostsCAipv4[rack]=[] redeHostsFILERipv4={} redeHostsFILERipv4[rack]=[] subnetsRackBEipv6 = {} subnetsRackBEipv6[rack] = [] redesHostsipv6={} redesHostsipv6[rack]=[] redeHostsBEipv6={} redeHostsBEipv6[rack]=[] redeHostsFEipv6={} redeHostsFEipv6[rack]=[] redeHostsBOipv6={} redeHostsBOipv6[rack]=[] redeHostsCAipv6={} redeHostsCAipv6[rack]=[] redeHostsFILERipv6={} redeHostsFILERipv6[rack]=[] hosts=dict() BE=dict() FE=dict() BO=dict() CA= dict() FILER=dict() ipv6=dict() BE_ipv6=dict() FE_ipv6=dict() BO_ipv6=dict() CA_ipv6= dict() FILER_ipv6=dict() try: #CIDR sala 01 => 10.128.0.0/12 CIDRBEipv4 = IPNetwork(get_variable("cidr_be_v4")) CIDRBEipv6 = IPNetwork(get_variable("cidr_be_v6")) hosts['VLAN_MNGT_BE']=int(get_variable("vlan_mngt_be")) hosts['VLAN_MNGT_FE']=int(get_variable("vlan_mngt_fe")) hosts['VLAN_MNGT_BO']=int(get_variable("vlan_mngt_bo")) hosts['VLAN_MNGT_CA']=int(get_variable("vlan_mngt_ca")) hosts['VLAN_MNGT_FILER']=int(get_variable("vlan_mngt_filer")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável VLAN_MNGT<BE,FE,BO,CA,FILER> ou CIDR<BEv4,BEv6>.")
def post(self, *args, **kwargs): try: log.info('RACK deploy.') rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) try: PATH_TO_ADD_CONFIG = get_variable('path_to_add_config') REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou " "REL_PATH_TO_ADD_CONFIG.") path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*' arquivos = glob.glob(path_config) # Get all files and search for equipments of the rack for var in arquivos: filename_equipments = var.split('/')[-1] rel_filename = "../../" + REL_PATH_TO_ADD_CONFIG + filename_equipments log.debug("rel_filename: %s" % rel_filename) # Check if file is config relative to this rack if rack.nome in filename_equipments: # Apply config only in spines. Leaves already have all necessary config in startup if "ADD" in filename_equipments: # Check if equipment in under maintenance. If so, does not aplly on it equipment_name = filename_equipments.split('-ADD-')[0] log.debug("equipment_name: %s" % equipment_name) try: equip = Equipamento.get_by_name(equipment_name) if not equip.maintenance: (erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w " "300" % (rel_filename, equipment_name)) log.debug("erro: %s, result: %s" % (str(erro), str(result))) if erro: raise exceptions.RackAplError() except exceptions.RackAplError, e: raise e except: # Error equipment not found, do nothing pass
def dic_vlan_core(variablestochangecore, rack, name_core, name_rack): """ variablestochangecore: list rack: Numero do Rack name_core: Nome do Core name_rack: Nome do rack """ core = int(name_core.split("-")[2]) try: #valor base para as vlans e portchannels BASE_SO = int(get_variable("base_so")) #rede para conectar cores aos racks SO_OOB_NETipv4= IPNetwork(get_variable("net_core")) #Vlan para cadastrar vlan_so_name = get_variable("vlan_so_name") except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável BASE_SO ou SO_OOB_NETipv4.")
def _generate_dict(interface): log.info("_generate_dict") try: supported_string = get_variable('supported_equipment_brands') SUPPORTED_EQUIPMENT_BRANDS = ast.literal_eval(supported_string) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável supported_equipment_brands.') except ValueError: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável supported_equipment_brands. ' 'Formato invalido. Deve ser uma string no formato de lista.') # Check if it is a supported equipment interface if interface.equipamento.modelo.marca.nome not in \ SUPPORTED_EQUIPMENT_BRANDS: raise exceptions.UnsupportedEquipmentException() key_dict = {} # TODO Separate differet vendor support # Cisco Nexus 6001 dict key_dict['NATIVE_VLAN'] = interface.vlan_nativa key_dict['USE_MCLAG'] = 1 key_dict['INTERFACE_NAME'] = interface.interface key_dict['INTERFACE_DESCRIPTION'] = str( interface.ligacao_front.equipamento.nome) + ' ' + str( interface.ligacao_front.interface) key_dict['INTERFACE_TYPE'] = interface.tipo.tipo if key_dict['INTERFACE_TYPE'] in 'trunk': vlan_range_results = get_vlan_range(interface) key_dict['VLAN_RANGE'] = vlan_range_results[0] key_dict['VLAN_RANGE_LIST'] = vlan_range_results[1] if interface.channel is not None: key_dict['BOOL_INTERFACE_IN_CHANNEL'] = 1 key_dict['PORTCHANNEL_NAME'] = interface.channel.nome try: key_dict['MCLAG_IDENTIFIER'] = int( re.sub(r'[a-zA\-]', '', interface.channel.nome)) except ValueError, e: log.error('Error: invalid channel name') raise e if interface.channel.lacp: key_dict['CHANNEL_LACP_MODE'] = 'active' else: key_dict['CHANNEL_LACP_MODE'] = 'on' # Normally used in junos plugin: key_dict['LACP_SYSTEM_ID_MAC'] = __generate_lacp_system_id_mac( interface.channel.nome)
def generate_delete_file(user, equip_id, interface_list, channel): try: INTERFACE_CONFIG_TOAPPLY_REL_PATH = get_variable( 'interface_config_toapply_rel_path') INTERFACE_CONFIG_FILES_PATH = get_variable( 'interface_config_files_path') TEMPLATE_REMOVE_CHANNEL = get_variable('template_remove_channel') TEMPLATE_REMOVE_INTERFACE = get_variable('template_remove_interface') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável INTERFACE_CONFIG_TEMPLATE_PATH,' 'TEMPLATE_REMOVE_CHANNEL ou TEMPLATE_REMOVE_INTERFACE.') key_dict = dict() config_to_be_saved = '' request_id = getattr(local, 'request_id', NO_REQUEST_ID) extension = '.py' if interface_list[ 0].equipamento.modelo.marca.nome == "HP" else '' filename_out = 'equip_' + str(equip_id) + '_channel_' + str( channel.id) + '_remove_' + str(request_id) + extension log.debug(filename_out) filename_to_save = INTERFACE_CONFIG_FILES_PATH + filename_out rel_file_to_deploy = INTERFACE_CONFIG_TOAPPLY_REL_PATH + filename_out key_dict['PORTCHANNEL_NAME'] = channel.nome for i in interface_list: key_dict['INTERFACE_NAME'] = i.interface try: interface_template_file = _load_template_file( int(equip_id), TEMPLATE_REMOVE_INTERFACE) config_to_be_saved += interface_template_file.render( Context(key_dict)) except exceptions.InterfaceTemplateException, e: log.error(e) raise exceptions.InterfaceTemplateException() except KeyError, exception: log.error('Erro: %s ' % exception) raise exceptions.InvalidKeyException(exception)
def generate_delete_file(user, equip_id, interface_list, channel): try: INTERFACE_CONFIG_TOAPPLY_REL_PATH = get_variable( 'interface_config_toapply_rel_path') INTERFACE_CONFIG_FILES_PATH = get_variable( 'interface_config_files_path') TEMPLATE_REMOVE_CHANNEL = get_variable('template_remove_channel') TEMPLATE_REMOVE_INTERFACE = get_variable('template_remove_interface') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável INTERFACE_CONFIG_TEMPLATE_PATH,' 'TEMPLATE_REMOVE_CHANNEL ou TEMPLATE_REMOVE_INTERFACE.') key_dict = dict() config_to_be_saved = '' request_id = getattr(local, 'request_id', NO_REQUEST_ID) extension = '.py' if interface_list[0].equipamento.modelo.marca.nome == "HP" else '' filename_out = 'equip_' + str(equip_id) + '_channel_' + str(channel.id) + '_remove_' + str(request_id) + extension log.debug(filename_out) filename_to_save = INTERFACE_CONFIG_FILES_PATH + filename_out rel_file_to_deploy = INTERFACE_CONFIG_TOAPPLY_REL_PATH + filename_out key_dict['PORTCHANNEL_NAME'] = channel.nome for i in interface_list: key_dict['INTERFACE_NAME'] = i.interface try: interface_template_file = _load_template_file( int(equip_id), TEMPLATE_REMOVE_INTERFACE) config_to_be_saved += interface_template_file.render( Context(key_dict)) except exceptions.InterfaceTemplateException, e: log.error(e) raise exceptions.InterfaceTemplateException() except KeyError, exception: log.error('Erro: %s ' % exception) raise exceptions.InvalidKeyException(exception)
def get_local_tunnel_ip(equipment): try: networkv4_tunnel_id = get_variable("networkv4_tunnel_ip") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando o id da rede com o local_tunnel_ip") unique_ip = IpEquipamento.objects.filter(equipamento=equipment, ip__networkipv4=networkv4_tunnel_id)\ .select_related('ip').uniqueResult() log.debug('equip %s' % equipment) log.debug('unique_ip: %s' % unique_ip.ip.ip_formated) return unique_ip.ip.ip_formated
def _generate_dict(interface): log.info("_generate_dict") try: supported_string = get_variable('supported_equipment_brands') SUPPORTED_EQUIPMENT_BRANDS = ast.literal_eval(supported_string) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável supported_equipment_brands.') except ValueError: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável supported_equipment_brands. ' 'Formato invalido. Deve ser uma string no formato de lista.') # Check if it is a supported equipment interface if interface.equipamento.modelo.marca.nome not in \ SUPPORTED_EQUIPMENT_BRANDS: raise exceptions.UnsupportedEquipmentException() key_dict = {} # TODO Separate differet vendor support # Cisco Nexus 6001 dict key_dict['NATIVE_VLAN'] = interface.vlan_nativa key_dict['USE_MCLAG'] = 1 key_dict['INTERFACE_NAME'] = interface.interface key_dict['INTERFACE_DESCRIPTION'] = str( interface.ligacao_front.equipamento.nome ) + ' ' + str(interface.ligacao_front.interface) key_dict['INTERFACE_TYPE'] = interface.tipo.tipo if key_dict['INTERFACE_TYPE'] in 'trunk': vlan_range_results = get_vlan_range(interface) key_dict['VLAN_RANGE'] = vlan_range_results[0] key_dict['VLAN_RANGE_LIST'] = vlan_range_results[1] if interface.channel is not None: key_dict['BOOL_INTERFACE_IN_CHANNEL'] = 1 key_dict['PORTCHANNEL_NAME'] = interface.channel.nome try: key_dict['MCLAG_IDENTIFIER'] = int( re.sub(r'[a-zA\-]', '', interface.channel.nome)) except ValueError, e: log.error('Error: invalid channel name') raise e if interface.channel.lacp: key_dict['CHANNEL_LACP_MODE'] = 'active' else: key_dict['CHANNEL_LACP_MODE'] = 'on'
def ambiente_borda(user,rack, environment_list): ranges=dict() ranges['MAX']=None ranges['MIN']=None ranges_vlans = dict() try: ranges_vlans['BORDA_DSR_VLAN_MIN'] = int(get_variable("borda_dsr_vlan_min")) ranges_vlans['BORDA_DSR_VLAN_MAX'] = int(get_variable("borda_dsr_vlan_max")) ranges_vlans['BORDA_DMZ_VLAN_MIN'] = int(get_variable("borda_dmz_vlan_min")) ranges_vlans['BORDA_DMZ_VLAN_MAX'] = int(get_variable("borda_dmz_vlan_max")) ranges_vlans['BORDACACHOS_VLAN_MIN'] = int(get_variable("bordacachos_vlan_min")) ranges_vlans['BORDACACHOS_VLAN_MAX'] = int(get_variable("bordacachos_vlan_max")) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis BORDA<DSR,DMZ,CACHOS>_VLAN_<MAX,MIN>.") try: base_vlan = int(get_variable("num_vlan_acl_bordadsr")) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável NUM_VLAN_ACL_BORDADSR") ambientes=dict() vlans = dict() ambientes['LOG'] = "PRODUCAO" ambientes['L3']= rack.nome divisao_aclpaths = [['BORDA_DSR','BORDA-DSR', 'BordaVrf'],['BORDA_DMZ','BORDA-DMZ', 'BordaVrf'],['BORDACACHOS','BORDACACHOS', 'BordaCachosVrf']] for item in divisao_aclpaths: divisaodc = item[0] acl_path = item[1] vrf = item[2] vlan_min = divisaodc+"_VLAN_MIN" vlan_max = divisaodc+"_VLAN_MAX" ranges['MAX']= ranges_vlans.get(vlan_max) ranges['MIN']= ranges_vlans.get(vlan_min) ambientes['DC']= divisaodc env = criar_ambiente(user, ambientes,ranges, acl_path, "Servidores", vrf) environment_list.append(env) vlans['VLAN_NUM'] = base_vlan base_vlan += 1 vlans['VLAN_NAME'] = "ACL_"+divisaodc+"_"+ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def autoprovision_coreoob(rack, FILEINCR1, FILEINCR2, FILEINOOB, name_core1, name_core2, name_oob, name_lf1, name_lf2, ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob): # gerando dicionarios para substituir paravras chaves do roteiro variablestochangecore1 = {} variablestochangecore2 = {} variablestochangeoob = {} # nome dos cores, do console de gerencia dos lf do rack, e do rack HOSTNAME_CORE1 = name_core1 HOSTNAME_CORE2 = name_core2 HOSTNAME_OOB = name_oob HOSTNAME_RACK = HOSTNAME_OOB.split('-') HOSTNAME_LF1 = name_lf1 HOSTNAME_LF2 = name_lf2 # interfaces de conexão entre os cores e o console INT_OOBC1_UPLINK = int_oob_core1 INT_OOBC2_UPLINK = int_oob_core2 INTERFACE_CORE1 = int_core1_oob INTERFACE_CORE2 = int_core2_oob # ip de gerencia do oob IP_GERENCIA_OOB = ip_mgmtoob try: # roteiro para configuracao de core fileincore1 = get_variable('path_to_guide') + FILEINCR1 fileincore2 = get_variable('path_to_guide') + FILEINCR2 fileinoob = get_variable('path_to_guide') + FILEINOOB # valor base para as vlans e portchannels BASE_SO = int(get_variable('base_so')) # arquivos de saida, OOB-CM-01.cfg e OOB-CM-02.cfg fileoutcore1 = get_variable( 'path_to_add_config' ) + HOSTNAME_CORE1 + '-ADD-' + HOSTNAME_RACK[2] + '.cfg' fileoutcore2 = get_variable( 'path_to_add_config' ) + HOSTNAME_CORE2 + '-ADD-' + HOSTNAME_RACK[2] + '.cfg' fileoutoob = get_variable('path_to_config') + HOSTNAME_OOB + '.cfg' except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável PATH_TO_<GUIDE, CONFIG> ou BASE_SO.')
def _generate_dict(interface): try: supported_string = get_variable("supported_equipment_brands") SUPPORTED_EQUIPMENT_BRANDS = ast.literal_eval(supported_string) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável supported_equipment_brands.") except ValueError: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável supported_equipment_brands. Formato invalido. Deve ser uma string no formato de lista." ) # Check if it is a supported equipment interface if interface.equipamento.modelo.marca.nome not in SUPPORTED_EQUIPMENT_BRANDS: raise exceptions.UnsupportedEquipmentException() key_dict = {} # TODO Separate differet vendor support # Cisco Nexus 6001 dict key_dict["NATIVE_VLAN"] = interface.vlan_nativa key_dict["USE_MCLAG"] = 1 key_dict["INTERFACE_NAME"] = interface.interface key_dict["INTERFACE_DESCRIPTION"] = ( str(interface.ligacao_front.equipamento.nome) + " " + str(interface.ligacao_front.interface) ) key_dict["INTERFACE_TYPE"] = interface.tipo.tipo if key_dict["INTERFACE_TYPE"] in "trunk": key_dict["VLAN_RANGE"] = get_vlan_range(interface) if interface.channel is not None: key_dict["BOOL_INTERFACE_IN_CHANNEL"] = 1 key_dict["PORTCHANNEL_NAME"] = interface.channel.nome try: key_dict["MCLAG_IDENTIFIER"] = int(re.sub(r"[a-zA\-]", "", interface.channel.nome)) except ValueError, e: log.error("Error: invalid channel name") raise e if interface.channel.lacp: key_dict["CHANNEL_LACP_MODE"] = "active" else: key_dict["CHANNEL_LACP_MODE"] = "on"
def dic_lf_spn(user, rack): CIDREBGP = {} CIDRBE = {} ######## VLANBELEAF = {} VLANFELEAF = {} VLANBORDALEAF = {} VLANBORDACACHOSLEAF = {} ######## VLANBELEAF[rack] = [] VLANFELEAF[rack] = [] VLANBORDALEAF[rack] = [] VLANBORDACACHOSLEAF[rack] = [] ipv4_spn1 = dict() ipv4_spn2 = dict() ipv4_spn3 = dict() ipv4_spn4 = dict() redev6_spn1 = dict() redev6_spn2 = dict() redev6_spn3 = dict() redev6_spn4 = dict() try: BASE_RACK = int(get_variable('base_rack')) VLANBE = int(get_variable('vlanbe')) VLANFE = int(get_variable('vlanfe')) VLANBORDA = int(get_variable('vlanborda')) VLANBORDACACHOS = int(get_variable('vlanbordacachos')) VLANBETORxTOR = int(get_variable('vlanbetorxtor')) # CIDR sala 01 => 10.128.0.0/12 CIDRBE[0] = IPNetwork(get_variable('cidr_sl01')) CIDREBGP[0] = IPNetwork(get_variable('cidr_bgp')) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável BASE_RACK ou VLAN<BE,FE,BORDA,CACHOS,TORxTOR> ou CIDR<BE,EBGP>.' )
def dic_lf_spn(user, rack): CIDREBGP = {} CIDRBE = {} ######## VLANBELEAF = {} VLANFELEAF = {} VLANBORDALEAF = {} VLANBORDACACHOSLEAF = {} ######## VLANBELEAF[rack]=[] VLANFELEAF[rack]=[] VLANBORDALEAF[rack]=[] VLANBORDACACHOSLEAF[rack]=[] ipv4_spn1 = dict() ipv4_spn2 = dict() ipv4_spn3 = dict() ipv4_spn4 = dict() redev6_spn1 = dict() redev6_spn2 = dict() redev6_spn3 = dict() redev6_spn4 = dict() try: BASE_RACK = int(get_variable("base_rack")) VLANBE = int(get_variable("vlanbe")) VLANFE = int(get_variable("vlanfe")) VLANBORDA = int(get_variable("vlanborda")) VLANBORDACACHOS = int(get_variable("vlanbordacachos")) VLANBETORxTOR = int(get_variable("vlanbetorxtor")) #CIDR sala 01 => 10.128.0.0/12 CIDRBE[0] = IPNetwork(get_variable("cidr_sl01")) CIDREBGP[0] = IPNetwork(get_variable("cidr_bgp")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável BASE_RACK ou VLAN<BE,FE,BORDA,CACHOS,TORxTOR> ou CIDR<BE,EBGP>.")
def ambiente_prod_fe(user, rack, environment_list): redes, ranges, ipv6 = dic_fe_prod(rack.numero) ambientes = dict() ambientes['LOG'] = 'PRODUCAO' ambientes['L3'] = rack.nome ambientes['DC'] = 'FE' redes['TIPO'] = 'Rede invalida equipamentos' ipv6['TIPO'] = 'Rede invalida equipamentos' acl_path = 'FECLOUD' # criar ambiente env = criar_ambiente(user, ambientes, ranges, acl_path, 'Servidores', 'FEVrf') environment_list.append(env) # configuracao dos ambientes redes['VERSION'] = 'ipv4' config_ambiente(user, redes, ambientes) ipv6['VERSION'] = 'ipv6' config_ambiente(user, ipv6, ambientes) vlans = dict() try: vlans['VLAN_NUM'] = int(get_variable('num_vlan_acl_fe')) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável NUM_VLAN_ACL_FE') vlans['VLAN_NAME'] = 'ACL_' + \ ambientes.get('DC') + '_' + ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def ambiente_prod_fe(user, rack, environment_list): redes, ranges, ipv6 = dic_fe_prod(rack.numero) ambientes = dict() ambientes['LOG'] = "PRODUCAO" ambientes['L3'] = rack.nome ambientes['DC'] = "FE" redes['TIPO'] = "Rede invalida equipamentos" ipv6['TIPO'] = "Rede invalida equipamentos" acl_path = 'FECLOUD' #criar ambiente env = criar_ambiente(user, ambientes, ranges, acl_path, "Servidores", "FEVrf") environment_list.append(env) #configuracao dos ambientes redes['VERSION'] = "ipv4" config_ambiente(user, redes, ambientes) ipv6['VERSION'] = "ipv6" config_ambiente(user, ipv6, ambientes) vlans = dict() try: vlans['VLAN_NUM'] = int(get_variable("num_vlan_acl_fe")) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável NUM_VLAN_ACL_FE") vlans['VLAN_NAME'] = "ACL_" + ambientes.get('DC') + "_" + ambientes.get( 'L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
def autoprovision_coreoob(rack, FILEINCR1, FILEINCR2, FILEINOOB, name_core1, name_core2, name_oob, name_lf1, name_lf2, ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob ): #gerando dicionarios para substituir paravras chaves do roteiro variablestochangecore1={} variablestochangecore2={} variablestochangeoob={} #nome dos cores, do console de gerencia dos lf do rack, e do rack HOSTNAME_CORE1=name_core1 HOSTNAME_CORE2=name_core2 HOSTNAME_OOB=name_oob HOSTNAME_RACK = HOSTNAME_OOB.split("-") HOSTNAME_LF1 = name_lf1 HOSTNAME_LF2 = name_lf2 #interfaces de conexão entre os cores e o console INT_OOBC1_UPLINK = int_oob_core1 INT_OOBC2_UPLINK = int_oob_core2 INTERFACE_CORE1 = int_core1_oob INTERFACE_CORE2 = int_core2_oob #ip de gerencia do oob IP_GERENCIA_OOB = ip_mgmtoob try: #roteiro para configuracao de core fileincore1=get_variable("path_to_guide")+FILEINCR1 fileincore2=get_variable("path_to_guide")+FILEINCR2 fileinoob=get_variable("path_to_guide")+FILEINOOB #valor base para as vlans e portchannels BASE_SO = int(get_variable("base_so")) #arquivos de saida, OOB-CM-01.cfg e OOB-CM-02.cfg fileoutcore1=get_variable("path_to_add_config")+HOSTNAME_CORE1+"-ADD-"+HOSTNAME_RACK[2]+".cfg" fileoutcore2=get_variable("path_to_add_config")+HOSTNAME_CORE2+"-ADD-"+HOSTNAME_RACK[2]+".cfg" fileoutoob=get_variable("path_to_config")+HOSTNAME_OOB+".cfg" except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_<GUIDE, CONFIG> ou BASE_SO.")
def api_foreman(rack): try: NETWORKAPI_FOREMAN_URL = get_variable("foreman_url") NETWORKAPI_FOREMAN_USERNAME = get_variable("foreman_username") NETWORKAPI_FOREMAN_PASSWORD = get_variable("foreman_password") FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable( "foreman_hosts_environment_id") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando as variáveis relativas ao Foreman.") foreman = Foreman( NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2) # for each switch, check the switch ip against foreman know networks, finds foreman hostgroup # based on model and brand and inserts the host in foreman # if host already exists, delete and recreate with new information for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]: # Get all foremand subnets and compare with the IP address of the switches until find it if mac == None: raise RackConfigError( None, rack.nome, ("Could not create entry for %s. There is no mac address." % switch.nome)) ip = _buscar_ip(switch.id) if ip == None: raise RackConfigError( None, rack.nome, ("Could not create entry for %s. There is no management IP." % switch.nome)) switch_cadastrado = 0 for subnet in foreman.subnets.index()['results']: network = IPNetwork(ip + '/' + subnet['mask']).network # check if switches ip network is the same as subnet['subnet']['network'] e subnet['subnet']['mask'] if network.__str__() == subnet['network']: subnet_id = subnet['id'] hosts = foreman.hosts.index(search=switch.nome)['results'] if len(hosts) == 1: foreman.hosts.destroy(id=hosts[0]['id']) elif len(hosts) > 1: raise RackConfigError(None, rack.nome, ( "Could not create entry for %s. There are multiple entries " "with the sam name." % switch.nome)) # Lookup foreman hostgroup # By definition, hostgroup should be Marca+"_"+Modelo hostgroup_name = switch.modelo.marca.nome + "_" + switch.modelo.nome hostgroups = foreman.hostgroups.index(search=hostgroup_name) if len(hostgroups['results']) == 0: raise RackConfigError( None, rack.nome, "Could not create entry for %s. Could not find hostgroup %s " "in foreman." % (switch.nome, hostgroup_name)) elif len(hostgroups['results']) > 1: raise RackConfigError( None, rack.nome, "Could not create entry for %s. Multiple hostgroups %s found" " in Foreman." % (switch.nome, hostgroup_name)) else: hostgroup_id = hostgroups['results'][0]['id'] host = foreman.hosts.create( host={ 'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true' }) switch_cadastrado = 1 if not switch_cadastrado: raise RackConfigError( None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % switch.nome)
def autoprovision_splf(rack, equips): log.info("AutoprovisionSPN-LF") numero_rack = rack.numero prefixspn = "SPN" prefixlf = "LF-" prefixoob = "OOB" # STRUCTURE: IPSPINE[rack][spine]: ip a configurar no spine 'spine' relativo à leaf do rack 'rack' # STRUCTURE: IPLEAF[rack][spine]: ip a configurar no leaf do rack 'rack' relativo ao spine 'spine' CIDREBGP = dict() IPSPINEipv4 = dict() IPSPINEipv6 = dict() IPLEAFipv4 = dict() IPLEAFipv6 = dict() IPSIBGPipv4 = dict() IPSIBGPipv6 = dict() ASLEAF = dict() # VLANBELEAF = dict() VLANFELEAF = dict() VLANBORDALEAF = dict() VLANBORDACACHOSLEAF = dict() VLANBORDACACHOSBLEAF = dict() # PODSBEipv4 = dict() redesPODSBEipv4 = dict() # subnetsRackBEipv4 = dict() # PODSBEipv6 = dict() redesPODSBEipv6 = dict() PODSBEFEipv6 = dict() redesPODSBEFEipv6 = dict() PODSBEBOipv6 = dict() redesPODSBEBOipv6 = dict() PODSBECAipv6 = dict() redesPODSBECAipv6 = dict() redesHostsipv6 = dict() redeHostsBEipv6 = dict() redeHostsFEipv6 = dict() redeHostsBOipv6 = dict() redeHostsCAipv6 = dict() redeHostsFILERipv6 = dict() subnetsRackBEipv6 = dict() subnetsRackFEipv4 = dict() subnetsRackBO_DSRipv4 = dict() subnetsRackBOCAAipv4 = dict() subnetsRackBOCABipv4 = dict() redesPODSFEipv4 = dict() subnetsRackFEipv6 = dict() subnetsRackBO_DSRipv6 = dict() subnetsRackBOCAAipv6 = dict() subnetsRackBOCABipv6 = dict() redesPODSFEipv6 = dict() # IPSPINEipv4[numero_rack] = list() IPSPINEipv6[numero_rack] = list() IPLEAFipv4[numero_rack] = list() IPLEAFipv6[numero_rack] = list() IPSIBGPipv4[numero_rack] = list() IPSIBGPipv6[numero_rack] = list() VLANBELEAF[numero_rack] = list() VLANFELEAF[numero_rack] = list() VLANBORDALEAF[numero_rack] = list() VLANBORDACACHOSLEAF[numero_rack] = list() VLANBORDACACHOSBLEAF[numero_rack] = list() ASLEAF[numero_rack] = list() # PODSBEipv4[numero_rack] = list() redesPODSBEipv4[numero_rack] = list() # subnetsRackBEipv4[numero_rack] = list() # PODSBEipv6[numero_rack] = list() redesPODSBEipv6[numero_rack] = list() PODSBEFEipv6[numero_rack] = list() redesPODSBEFEipv6[numero_rack] = list() PODSBEBOipv6[numero_rack] = list() redesPODSBEBOipv6[numero_rack] = list() PODSBECAipv6[numero_rack] = list() redesPODSBECAipv6[numero_rack] = list() redesHostsipv6[numero_rack] = list() redeHostsBEipv6[numero_rack] = list() redeHostsFEipv6[numero_rack] = list() redeHostsBOipv6[numero_rack] = list() redeHostsCAipv6[numero_rack] = list() redeHostsFILERipv6[numero_rack] = list() subnetsRackBEipv6[numero_rack] = list() subnetsRackFEipv4[numero_rack] = list() subnetsRackBO_DSRipv4[numero_rack] = list() subnetsRackBOCAAipv4[numero_rack] = list() subnetsRackBOCABipv4[numero_rack] = list() redesPODSFEipv4[numero_rack] = list() subnetsRackFEipv6[numero_rack] = list() subnetsRackBO_DSRipv6[numero_rack] = list() subnetsRackBOCAAipv6[numero_rack] = list() subnetsRackBOCABipv6[numero_rack] = list() redesPODSFEipv6[numero_rack] = list() CIDRFEipv4 = dict() CIDRFEipv6 = dict() variablestochangespine1 = dict() variablestochangeleaf1 = dict() VLANBE = None VLANFE = None VLANBORDA = None VLANBORDACACHOS = None CIDRBEipv4 = None CIDRBEipv6 = None CIDRBO_DSRipv4interno = "" prefixInternoBO_DSRV4 = "" CIDRBO_DSRipv6interno = "" prefixInternoBO_DSRV6 = "" CIDRBOCAAipv4interno = "" prefixInternoBOCAAV4 = "" CIDRBOCAAipv6interno = "" prefixInternoBOCAAV6 = "" CIDRBOCABipv4interno = "" prefixInternoBOCABV4 = "" CIDRBOCABipv6interno = "" prefixInternoBOCABV6 = "" try: path_to_guide = get_variable("path_to_guide") path_to_add_config = get_variable("path_to_add_config") path_to_config = get_variable("path_to_config") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável PATH_TO_GUIDE") try: variablestochangeleaf1["KICKSTART_SO_LF"] = get_variable( "kickstart_so_lf") variablestochangeleaf1["IMAGE_SO_LF"] = get_variable("image_so_lf") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável KICKSTART_SO_LF ou IMAGE_SO_LF.") equips_sorted = sorted(equips, key=operator.itemgetter('sw')) dcroom = model_to_dict(rack.dcroom) log.debug("type: %s" % str(type(dcroom.get("config")))) fabricconfig = dcroom.get("config") try: fabricconfig = json.loads(fabricconfig) log.debug("type -ast: %s" % str(type(fabricconfig))) except: pass try: fabricconfig = ast.literal_eval(fabricconfig) log.debug("config -ast: %s" % str(fabricconfig)) except: pass envconfig = fabricconfig BASE_RACK = dcroom.get("racks") BGP = envconfig.get("BGP") BASE_AS_SPN = int(BGP.get("spines")) BASE_AS_LFS = int(BGP.get("leafs")) # get fathers environments spn_envs = models_env.Ambiente.objects.filter( dcroom=dcroom.get("id"), father_environment__isnull=True, ambiente_logico__nome="SPINES") prod_envs = models_env.Ambiente.objects.filter( dcroom=dcroom.get("id"), father_environment__isnull=True, ambiente_logico__nome="PRODUCAO", divisao_dc__nome__in=[ "BE", "FE", "BO_DSR", "BOCACHOS-A", "BOCACHOS-B" ]) lf_env = models_env.Ambiente.objects.filter( dcroom=dcroom.get("id"), divisao_dc__nome="BE", grupo_l3__nome=str(rack.dcroom.name), ambiente_logico__nome="LEAF-LEAF").uniqueResult() for spn in spn_envs: if spn.divisao_dc.nome[:2] == "BE": VLANBE = spn.min_num_vlan_1 for net in spn.configs: if net.ip_config.type == "v4": CIDRBEipv4 = IPNetwork(str(net.ip_config.subnet)) prefixBEV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRBEipv6 = IPNetwork(str(net.ip_config.subnet)) prefixBEV6 = int(net.ip_config.new_prefix) elif spn.divisao_dc.nome[:2] == "FE": VLANFE = spn.min_num_vlan_1 for net in spn.configs: if net.ip_config.type == "v4": CIDRFEipv4 = IPNetwork(str(net.ip_config.subnet)) prefixFEV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRFEipv6 = IPNetwork(str(net.ip_config.subnet)) prefixFEV6 = int(net.ip_config.new_prefix) elif spn.divisao_dc.nome == "BO": VLANBORDA = spn.min_num_vlan_1 elif spn.divisao_dc.nome == "BOCACHOS-A": VLANBORDACACHOS = spn.min_num_vlan_1 elif spn.divisao_dc.nome == "BOCACHOS-B": VLANBORDACACHOSB = spn.min_num_vlan_1 for prod in prod_envs: if prod.divisao_dc.nome[:2] == "BE": for net in prod.configs: if net.ip_config.type == "v4": CIDRBEipv4interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRBEipv6interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoV6 = int(net.ip_config.new_prefix) elif prod.divisao_dc.nome[:2] == "FE": for net in prod.configs: if net.ip_config.type == "v4": CIDRFEipv4interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoFEV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRFEipv6interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoFEV6 = int(net.ip_config.new_prefix) elif prod.divisao_dc.nome == "BO_DSR": for net in prod.configs: if net.ip_config.type == "v4": CIDRBO_DSRipv4interno = IPNetwork(str( net.ip_config.subnet)) prefixInternoBO_DSRV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRBO_DSRipv6interno = IPNetwork(str( net.ip_config.subnet)) prefixInternoBO_DSRV6 = int(net.ip_config.new_prefix) elif prod.divisao_dc.nome == "BOCACHOS-A": for net in prod.configs: if net.ip_config.type == "v4": CIDRBOCAAipv4interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoBOCAAV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRBOCAAipv6interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoBOCAAV6 = int(net.ip_config.new_prefix) elif prod.divisao_dc.nome == "BOCACHOS-B": for net in prod.configs: if net.ip_config.type == "v4": CIDRBOCABipv4interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoBOCABV4 = int(net.ip_config.new_prefix) else: log.debug(str(net.ip_config.subnet)) CIDRBOCABipv6interno = IPNetwork(str(net.ip_config.subnet)) prefixInternoBOCABV6 = int(net.ip_config.new_prefix) log.debug(str(lf_env)) for netlf in lf_env.configs: if netlf.ip_config.type == "v4": IBGPToRLxLipv4 = IPNetwork(str(netlf.ip_config.subnet)) elif netlf.ip_config.type == "v6": IBGPToRLxLipv6 = IPNetwork(str(netlf.ip_config.subnet)) SPINE1ipv4 = splitnetworkbyrack(CIDRBEipv4, prefixBEV4, 0) SPINE2ipv4 = splitnetworkbyrack(CIDRBEipv4, prefixBEV4, 1) SPINE3ipv4 = splitnetworkbyrack(CIDRBEipv4, prefixBEV4, 2) SPINE4ipv4 = splitnetworkbyrack(CIDRBEipv4, prefixBEV4, 3) SPINE1ipv6 = splitnetworkbyrack(CIDRBEipv6, prefixBEV6, 0) SPINE2ipv6 = splitnetworkbyrack(CIDRBEipv6, prefixBEV6, 1) SPINE3ipv6 = splitnetworkbyrack(CIDRBEipv6, prefixBEV6, 2) SPINE4ipv6 = splitnetworkbyrack(CIDRBEipv6, prefixBEV6, 3) id_vlt = [ envconfig.get("VLT").get("id_vlt_lf1"), envconfig.get("VLT").get("id_vlt_lf2") ] priority_vlt = [ envconfig.get("VLT").get("priority_vlt_lf1"), envconfig.get("VLT").get("priority_vlt_lf2") ] subSPINE1ipv4 = list(SPINE1ipv4.subnet(31)) subSPINE2ipv4 = list(SPINE2ipv4.subnet(31)) subSPINE3ipv4 = list(SPINE3ipv4.subnet(31)) subSPINE4ipv4 = list(SPINE4ipv4.subnet(31)) subSPINE1ipv6 = list(SPINE1ipv6.subnet(127)) subSPINE2ipv6 = list(SPINE2ipv6.subnet(127)) subSPINE3ipv6 = list(SPINE3ipv6.subnet(127)) subSPINE4ipv6 = list(SPINE4ipv6.subnet(127)) subIBGPToRLxLipv4 = list(IBGPToRLxLipv4.subnet(31)) subIBGPToRLxLipv6 = list(IBGPToRLxLipv6.subnet(127)) IPSPINEipv4[numero_rack].append(subSPINE1ipv4[numero_rack][0]) IPSPINEipv4[numero_rack].append(subSPINE2ipv4[numero_rack][0]) IPSPINEipv4[numero_rack].append(subSPINE3ipv4[numero_rack][0]) IPSPINEipv4[numero_rack].append(subSPINE4ipv4[numero_rack][0]) # IPLEAFipv4[numero_rack].append(subSPINE1ipv4[numero_rack][1]) IPLEAFipv4[numero_rack].append(subSPINE2ipv4[numero_rack][1]) IPLEAFipv4[numero_rack].append(subSPINE3ipv4[numero_rack][1]) IPLEAFipv4[numero_rack].append(subSPINE4ipv4[numero_rack][1]) # IPSIBGPipv4[numero_rack].append(subIBGPToRLxLipv4[numero_rack][0]) IPSIBGPipv4[numero_rack].append(subIBGPToRLxLipv4[numero_rack][1]) # IPSPINEipv6[numero_rack].append(subSPINE1ipv6[numero_rack][0]) IPSPINEipv6[numero_rack].append(subSPINE2ipv6[numero_rack][0]) IPSPINEipv6[numero_rack].append(subSPINE3ipv6[numero_rack][0]) IPSPINEipv6[numero_rack].append(subSPINE4ipv6[numero_rack][0]) # IPLEAFipv6[numero_rack].append(subSPINE1ipv6[numero_rack][1]) IPLEAFipv6[numero_rack].append(subSPINE2ipv6[numero_rack][1]) IPLEAFipv6[numero_rack].append(subSPINE3ipv6[numero_rack][1]) IPLEAFipv6[numero_rack].append(subSPINE4ipv6[numero_rack][1]) # IPSIBGPipv6[numero_rack].append(subIBGPToRLxLipv6[numero_rack][0]) IPSIBGPipv6[numero_rack].append(subIBGPToRLxLipv6[numero_rack][1]) # VLANBELEAF[numero_rack].append(VLANBE + numero_rack) VLANBELEAF[numero_rack].append(VLANBE + numero_rack + BASE_RACK) VLANBELEAF[numero_rack].append(VLANBE + numero_rack + 2 * BASE_RACK) VLANBELEAF[numero_rack].append(VLANBE + numero_rack + 3 * BASE_RACK) # VLANFELEAF[numero_rack].append(VLANFE + numero_rack) VLANFELEAF[numero_rack].append(VLANFE + numero_rack + BASE_RACK) VLANFELEAF[numero_rack].append(VLANFE + numero_rack + 2 * BASE_RACK) VLANFELEAF[numero_rack].append(VLANFE + numero_rack + 3 * BASE_RACK) # VLANBORDALEAF[numero_rack].append(VLANBORDA + numero_rack) VLANBORDALEAF[numero_rack].append(VLANBORDA + numero_rack + BASE_RACK) VLANBORDALEAF[numero_rack].append(VLANBORDA + numero_rack + 2 * BASE_RACK) VLANBORDALEAF[numero_rack].append(VLANBORDA + numero_rack + 3 * BASE_RACK) # VLANBORDACACHOSLEAF[numero_rack].append(VLANBORDACACHOS + numero_rack) VLANBORDACACHOSLEAF[numero_rack].append(VLANBORDACACHOS + numero_rack + BASE_RACK) VLANBORDACACHOSLEAF[numero_rack].append(VLANBORDACACHOS + numero_rack + 2 * BASE_RACK) VLANBORDACACHOSLEAF[numero_rack].append(VLANBORDACACHOS + numero_rack + 3 * BASE_RACK) # VLANBORDACACHOSBLEAF[numero_rack].append(VLANBORDACACHOSB + numero_rack) VLANBORDACACHOSBLEAF[numero_rack].append(VLANBORDACACHOSB + numero_rack + BASE_RACK) VLANBORDACACHOSBLEAF[numero_rack].append(VLANBORDACACHOSB + numero_rack + 2 * BASE_RACK) VLANBORDACACHOSBLEAF[numero_rack].append(VLANBORDACACHOSB + numero_rack + 3 * BASE_RACK) # ASLEAF[numero_rack].append(BASE_AS_LFS + numero_rack) # ::::::: SUBNETING FOR RACK NETWORKS - /19 ::::::: # Redes p/ rack => 10.128.0.0/19, 10.128.32.0/19 , ... ,10.143.224.0/19 subnetsRackBEipv4[numero_rack] = splitnetworkbyrack( CIDRBEipv4interno, prefixInternoV4, numero_rack) subnetsRackBEipv6[numero_rack] = splitnetworkbyrack( CIDRBEipv6interno, prefixInternoV6, numero_rack) # PODS BE => /20 # ::::::::::::::::::::::::::::::::::: FRONTEND # ::::::: SUBNETING FOR RACK NETWORKS - /19 ::::::: # Sumário do rack => 172.20.0.0/21 subnetsRackFEipv4[numero_rack] = splitnetworkbyrack( CIDRFEipv4interno, prefixInternoFEV4, numero_rack) subnetsRackFEipv6[numero_rack] = splitnetworkbyrack( CIDRFEipv6interno, prefixInternoFEV6, numero_rack) # if CIDRBO_DSRipv4interno: subnetsRackBO_DSRipv4[numero_rack] = splitnetworkbyrack( CIDRBO_DSRipv4interno, prefixInternoBO_DSRV4, numero_rack) subnetsRackBO_DSRipv6[numero_rack] = splitnetworkbyrack( CIDRBO_DSRipv6interno, prefixInternoBO_DSRV6, numero_rack) # if CIDRBOCAAipv4interno: subnetsRackBOCAAipv4[numero_rack] = splitnetworkbyrack( CIDRBOCAAipv4interno, prefixInternoBOCAAV4, numero_rack) subnetsRackBOCAAipv6[numero_rack] = splitnetworkbyrack( CIDRBOCAAipv6interno, prefixInternoBOCAAV6, numero_rack) # if CIDRBOCABipv4interno: subnetsRackBOCABipv4[numero_rack] = splitnetworkbyrack( CIDRBOCABipv4interno, prefixInternoBOCABV4, numero_rack) subnetsRackBOCABipv6[numero_rack] = splitnetworkbyrack( CIDRBOCABipv6interno, prefixInternoBOCABV6, numero_rack) # ::::::: SUBNETING EACH RACK NETWORK::::::: # PODS FE => 128 redes /28 ; 128 redes /64 # redesPODSBEipv4[numero_rack] = list(subnetsRackFEipv4[numero_rack].subnet(28)) # redesPODSBEipv6[numero_rack] = list(subnetsRackFEipv6[numero_rack].subnet(64)) for equip, spn, j in zip(equips_sorted[:2], [0, 2], [0, 1]): # lf 1/2 log.info("for equip spn j") variablestochangeleaf1["IPLEAFSP1IPV4"] = str( IPLEAFipv4[numero_rack][spn]) variablestochangeleaf1["IPLEAFSP2IPV4"] = str( IPLEAFipv4[numero_rack][spn + 1]) variablestochangeleaf1["IPIBGPIPV4"] = str(IPSIBGPipv4[numero_rack][j]) variablestochangeleaf1["IPLEAFSP1IPV6"] = str( IPLEAFipv6[numero_rack][spn]) variablestochangeleaf1["IPLEAFSP2IPV6"] = str( IPLEAFipv6[numero_rack][spn + 1]) variablestochangeleaf1["IPIBGPIPV6"] = str(IPSIBGPipv6[numero_rack][j]) variablestochangeleaf1["VLANBELEAFSP1"] = str( VLANBELEAF[numero_rack][spn]) variablestochangeleaf1["VLANBELEAFSP2"] = str( VLANBELEAF[numero_rack][spn + 1]) variablestochangeleaf1["VLANFELEAFSP1"] = str( VLANFELEAF[numero_rack][spn]) variablestochangeleaf1["VLANFELEAFSP2"] = str( VLANFELEAF[numero_rack][spn + 1]) variablestochangeleaf1["VLANBORDALEAFSP1"] = str( VLANBORDALEAF[numero_rack][spn]) variablestochangeleaf1["VLANBORDALEAFSP2"] = str( VLANBORDALEAF[numero_rack][spn + 1]) variablestochangeleaf1["VLANBORDACACHOSLEAFSP1"] = str( VLANBORDACACHOSLEAF[numero_rack][spn]) variablestochangeleaf1["VLANBORDACACHOSLEAFSP2"] = str( VLANBORDACACHOSLEAF[numero_rack][spn + 1]) variablestochangeleaf1["VLANBORDACACHOSBLEAFSP1"] = str( VLANBORDACACHOSBLEAF[numero_rack][spn]) variablestochangeleaf1["VLANBORDACACHOSBLEAFSP2"] = str( VLANBORDACACHOSBLEAF[numero_rack][spn + 1]) variablestochangeleaf1["ASLEAF"] = str(ASLEAF[numero_rack][0]) variablestochangeleaf1["IPNEIGHSPINE1IPV4"] = str( IPSPINEipv4[numero_rack][spn]) variablestochangeleaf1["IPNEIGHSPINE2IPV4"] = str( IPSPINEipv4[numero_rack][spn + 1]) variablestochangeleaf1["IPNEIGHSPINE1IPV6"] = str( IPSPINEipv6[numero_rack][spn]) variablestochangeleaf1["IPNEIGHSPINE2IPV6"] = str( IPSPINEipv6[numero_rack][spn + 1]) if equip.get("nome")[-1] == "1": log.debug("lf-name: %s. Ip: %s" % (equip.get("nome"), IPSIBGPipv4[numero_rack][1])) variablestochangeleaf1["IPNEIGHIBGPIPV4"] = str( IPSIBGPipv4[numero_rack][1]) variablestochangeleaf1["IPNEIGHIBGPIPV6"] = str( IPSIBGPipv6[numero_rack][1]) else: log.debug("lf-name: %s. Ip: %s" % (equip.get("nome"), IPSIBGPipv4[numero_rack][0])) variablestochangeleaf1["IPNEIGHIBGPIPV4"] = str( IPSIBGPipv4[numero_rack][0]) variablestochangeleaf1["IPNEIGHIBGPIPV6"] = str( IPSIBGPipv6[numero_rack][0]) variablestochangeleaf1["NET_HOST_BE_IPV4"] = str( subnetsRackBEipv4[numero_rack]) variablestochangeleaf1["NET_HOST_FE_IPV4"] = str( subnetsRackFEipv4[numero_rack]) if CIDRBO_DSRipv4interno: variablestochangeleaf1["NET_HOST_BO_DSR_IPV4"] = str( subnetsRackBO_DSRipv4[numero_rack]) if CIDRBOCAAipv4interno: variablestochangeleaf1["NET_HOST_BOCAA_IPV4"] = str( subnetsRackBOCAAipv4[numero_rack]) if CIDRBOCABipv4interno: variablestochangeleaf1["NET_HOST_BOCAB_IPV4"] = str( subnetsRackBOCABipv4[numero_rack]) variablestochangeleaf1["NET_SPINE1_LF_IPV4"] = str( subSPINE1ipv4[numero_rack]) variablestochangeleaf1["NET_SPINE2_LF_IPV4"] = str( subSPINE2ipv4[numero_rack]) variablestochangeleaf1["NET_LF_LF_IPV4"] = str( subIBGPToRLxLipv4[numero_rack]) variablestochangeleaf1["NET_HOST_BE_IPV6"] = str( subnetsRackBEipv6[numero_rack]) variablestochangeleaf1["NET_HOST_FE_IPV6"] = str( subnetsRackFEipv6[numero_rack]) if CIDRBO_DSRipv6interno: variablestochangeleaf1["NET_HOST_BO_DSR_IPV6"] = str( subnetsRackBO_DSRipv6[numero_rack]) if CIDRBOCAAipv6interno: variablestochangeleaf1["NET_HOST_BOCAA_IPV6"] = str( subnetsRackBOCAAipv6[numero_rack]) if CIDRBOCABipv6interno: variablestochangeleaf1["NET_HOST_BOCAB_IPV6"] = str( subnetsRackBOCABipv6[numero_rack]) variablestochangeleaf1["NET_SPINE1_LF_IPV6"] = str( subSPINE1ipv6[numero_rack]) variablestochangeleaf1["NET_SPINE2_LF_IPV6"] = str( subSPINE2ipv6[numero_rack]) variablestochangeleaf1["NET_LF_LF_IPV6"] = str( subIBGPToRLxLipv6[numero_rack]) variablestochangeleaf1["ID_LEAF"] = str(equip.get("sw")) # lf1 ou lf2 variablestochangeleaf1["OWN_IP_MGMT"] = equip.get("ip_mngt") variablestochangeleaf1["LF_HOSTNAME"] = equip.get("nome") for i in equip.get("interfaces"): log.info("for i in equip") log.info(str(type(i.get("nome")[:3]))) if i.get("nome")[:3] == prefixlf: variablestochangeleaf1["LFNEIGH_HOSTNAME"] = i.get("nome") variablestochangeleaf1["LFNEIGH_IP_MGMT"] = i.get("ip_mngt") elif i.get("nome")[:3] == prefixspn: spine_num = int(i.get("nome")[-1]) variablestochangespine1["ASSPINE"] = str(BASE_AS_SPN + spine_num - 1) variablestochangespine1["INTERFACE"] = i.get("interface") variablestochangespine1["LEAFNAME"] = equip.get("nome") variablestochangespine1["INT_LF_UPLINK"] = i.get( "eq_interface") variablestochangespine1["IPSPINEIPV4"] = str( IPSPINEipv4[numero_rack][spine_num - 1]) variablestochangespine1["IPSPINEIPV6"] = str( IPSPINEipv6[numero_rack][spine_num - 1]) variablestochangespine1["VLANBELEAF"] = str( VLANBELEAF[numero_rack][spine_num - 1]) variablestochangespine1["VLANFELEAF"] = str( VLANFELEAF[numero_rack][spine_num - 1]) variablestochangespine1["VLANBORDALEAF"] = str( VLANBORDALEAF[numero_rack][spine_num - 1]) variablestochangespine1["VLANBORDACACHOSLEAF"] = str( VLANBORDACACHOSLEAF[numero_rack][spine_num - 1]) variablestochangespine1["VLANBORDACACHOSBLEAF"] = str( VLANBORDACACHOSBLEAF[numero_rack][spine_num - 1]) variablestochangespine1["ASLEAF"] = str(ASLEAF[numero_rack][0]) variablestochangespine1["IPNEIGHLEAFIPV4"] = str( IPLEAFipv4[numero_rack][spine_num - 1]) variablestochangespine1["IPNEIGHLEAFIPV6"] = str( IPLEAFipv6[numero_rack][spine_num - 1]) if spine_num in [1, 3]: variablestochangeleaf1["SP1_HOSTNAME"] = i.get("nome") variablestochangeleaf1["INTERFACE_SP1"] = i.get( "interface") variablestochangeleaf1["ASSPINE1"] = str(BASE_AS_SPN + spine_num - 1) else: variablestochangeleaf1["SP2_HOSTNAME"] = i.get("nome") variablestochangeleaf1["INTERFACE_SP2"] = i.get( "interface") variablestochangeleaf1["ASSPINE2"] = str(BASE_AS_SPN + spine_num - 1) fileinspine1 = path_to_guide + i.get("roteiro") fileoutspine1 = path_to_add_config + i.get( "nome") + "-ADD-" + rack.nome + ".cfg" replace(fileinspine1, fileoutspine1, variablestochangespine1) variablestochangespine1 = dict() elif i.get("nome")[:3] == prefixoob: variablestochangeleaf1["HOSTNAME_OOB"] = i.get("nome") variablestochangeleaf1["INTERFACE_OOB"] = i.get("interface") variablestochangeleaf1["ID_VLT"] = str(id_vlt[j]) variablestochangeleaf1["PRIORITY_VLT"] = str(priority_vlt[j]) fileinleaf1 = path_to_guide + equip.get("roteiro") fileoutleaf1 = path_to_config + equip.get("nome") + ".cfg" replace(fileinleaf1, fileoutleaf1, variablestochangeleaf1) variablestochangeleaf1 = dict() return True
logging.critical('Unable to connect to BIG-IP. Details: %s' % (e)) raise base_exceptions.CommandErrorException(e) else: log.info('Connected in hostname:%s' % hostname) try: self._version = self._channel.System.SystemInfo.get_version() if self._version[8:len(self._version)].split('.')[0] <= 10: raise base_exceptions.UnsupportedVersion( 'This plugin only supports BIG-IP v11 or above') else: if session: log.info('Try get new session') session_cur = self._channel.System.Session.get_session_timeout() log.info('Session Timeout Current: %s' % session_cur) session_timeout = get_variable( 'set_session_timeout_plugin_f5', '60') if int(session_cur) > int(session_timeout): self._channel.System.Session.set_session_timeout( session_timeout) self._channel = self.get_session() except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e) def get_session(self): try: channel = self._channel.with_session_id() log.info('Session %s', channel) except Exception, e: if 'There are too many existing user sessions.'.lower() in str(e).lower():
from networkapi.api_environment import facade as facade_env from networkapi.infrastructure.xml_utils import dumps_networkapi from networkapi.vlan import models as models_vlan from networkapi.api_vlan.facade import v3 as facade_vlan_v3 from networkapi.equipamento.models import Equipamento, EquipamentoRoteiro from networkapi.interface.models import Interface, InterfaceNotFoundError from networkapi.ip.models import IpEquipamento, Ip from networkapi.rack.models import Rack, Datacenter, DatacenterRooms, RackConfigError, RackError, RackNumberNotFoundError from networkapi.rest import RestResource, UserNotAuthorizedError from networkapi.api_rack import serializers as rack_serializers from networkapi.api_rack import exceptions, autoprovision from networkapi.system import exceptions as var_exceptions from networkapi.system.facade import get_value as get_variable from networkapi.api_rest.exceptions import ValidationAPIException, ObjectDoesNotExistException, NetworkAPIException if int(get_variable('use_foreman')): from foreman.client import Foreman, ForemanException log = logging.getLogger(__name__) def save_dc(dc_dict): dc = Datacenter() dc.dcname = dc_dict.get('dcname') dc.address = dc_dict.get('address') dc.save_dc() return dc
def handle_post(self, request, user, *args, **kwargs): """Treat requests POST to create the configuration file. URL: rack/alocar-config/id_rack """ try: # User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) rack_id = kwargs.get('id_rack') rack = Rack() rack = rack.get_by_pk(rack_id) # Validar configuracao if not rack.config: raise RackAplError( None, rack.nome, 'Os arquivos de configuracao devem ser gerados antes.') if rack.create_vlan_amb: raise RackAplError( None, rack.nome, 'As vlans, redes e ambientes ja foram criados.') # variaveis name_core1, name_core2 = get_core_name(rack) environment_list = [] variablestochangecore1 = {} variablestochangecore2 = {} variablestochangecore1 = dic_vlan_core(variablestochangecore1, rack.numero, name_core1, rack.nome) variablestochangecore2 = dic_vlan_core(variablestochangecore2, rack.numero, name_core2, rack.nome) # VLAN Gerencia SO ambientes = dict() try: DIVISAODC_MGMT = get_variable('divisaodc_mngt') AMBLOG_MGMT = get_variable('amblog_mngt') GRPL3_MGMT = get_variable('grpl3_mngt') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando as variáveis <DIVISAODC,AMBLOG,GRPL3>_MGMT.' ) ambientes['DC'] = DIVISAODC_MGMT ambientes['LOG'] = AMBLOG_MGMT ambientes['L3'] = GRPL3_MGMT try: # criar vlan vlan = criar_vlan(user, variablestochangecore1, ambientes) except: raise RackAplError(None, rack.nome, 'Erro ao criar a VLAN_SO.') try: # criar rede network = criar_rede(user, 'Rede invalida equipamentos', variablestochangecore1, vlan) except: raise RackAplError(None, rack.nome, 'Erro ao criar a rede da VLAN_SO') try: # inserir os Core inserir_equip(user, variablestochangecore1, network.id) inserir_equip(user, variablestochangecore2, network.id) except: raise RackAplError(None, rack.nome, 'Erro ao inserir o core 1 e 2') # Ambientes # BE - SPINE - LEAF try: environment_list = ambiente_spn_lf(user, rack, environment_list) except: raise RackAplError( None, rack.nome, 'Erro ao criar os ambientes e alocar as vlans do Spine-leaf.' ) # BE - PRODUCAO try: environment_list = ambiente_prod(user, rack, environment_list) except ObjectDoesNotExist, e: raise var_exceptions.VariableDoesNotExistException(e) except: raise RackAplError(None, rack.nome, 'Erro ao criar os ambientes de produção.') # BE - Hosts - CLOUD try: environment_list = ambiente_cloud(user, rack, environment_list) except: raise RackAplError( None, rack.nome, 'Erro ao criar os ambientes e alocar as vlans da Cloud.') # FE try: environment_list = ambiente_prod_fe(user, rack, environment_list) except ObjectDoesNotExist, e: raise var_exceptions.VariableDoesNotExistException(e)
from networkapi.ip.models import Ip from networkapi.ip.models import IpEquipamento from networkapi.rack.models import Rack from networkapi.rack.models import RackConfigError from networkapi.rack.models import RackError from networkapi.rack.models import RackNumberNotFoundError from networkapi.rack.resource.GeraConfig import autoprovision_coreoob from networkapi.rack.resource.GeraConfig import autoprovision_splf from networkapi.rest import RestResource from networkapi.rest import UserNotAuthorizedError from networkapi.system import exceptions as var_exceptions from networkapi.system.facade import get_value as get_variable log = logging.getLogger(__name__) if int(get_variable('use_foreman')): from foreman.client import Foreman, ForemanException def buscar_roteiro(id_sw, tipo): roteiros = EquipamentoRoteiro.search(None, id_sw) for rot in roteiros: if (rot.roteiro.tipo_roteiro.tipo == tipo): roteiro_eq = rot.roteiro.roteiro roteiro_eq = roteiro_eq.lower() if '.txt' not in roteiro_eq: roteiro_eq = roteiro_eq + '.txt' return roteiro_eq
def handle_post(self, request, user, *args, **kwargs): """Treat requests POST to create the configuration file. URL: rack/alocar-config/id_rack """ try: # User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) rack_id = kwargs.get('id_rack') rack = Rack() rack = rack.get_by_pk(rack_id) #Validar configuracao if not rack.config: raise RackAplError(None, rack.nome, "Os arquivos de configuracao devem ser gerados antes.") if rack.create_vlan_amb: raise RackAplError(None, rack.nome, "As vlans, redes e ambientes ja foram criados.") #variaveis name_core1, name_core2 = get_core_name(rack) environment_list = [] variablestochangecore1 = {} variablestochangecore2 = {} variablestochangecore1 = dic_vlan_core(variablestochangecore1, rack.numero, name_core1, rack.nome) variablestochangecore2 = dic_vlan_core(variablestochangecore2, rack.numero, name_core2, rack.nome) ####################################################################### VLAN Gerencia SO ambientes=dict() try: DIVISAODC_MGMT = get_variable("divisaodc_mngt") AMBLOG_MGMT = get_variable("amblog_mngt") GRPL3_MGMT = get_variable("grpl3_mngt") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis <DIVISAODC,AMBLOG,GRPL3>_MGMT.") ambientes['DC']=DIVISAODC_MGMT ambientes['LOG']=AMBLOG_MGMT ambientes['L3']=GRPL3_MGMT try: #criar vlan vlan = criar_vlan(user, variablestochangecore1, ambientes) except: raise RackAplError(None, rack.nome, "Erro ao criar a VLAN_SO.") try: #criar rede network = criar_rede(user, "Rede invalida equipamentos", variablestochangecore1, vlan) except: raise RackAplError(None, rack.nome, "Erro ao criar a rede da VLAN_SO") try: #inserir os Core inserir_equip(user, variablestochangecore1, network.id) inserir_equip(user, variablestochangecore2, network.id) except: raise RackAplError(None, rack.nome, "Erro ao inserir o core 1 e 2") ####################################################################### Ambientes #BE - SPINE - LEAF try: environment_list = ambiente_spn_lf(user, rack, environment_list) except: raise RackAplError(None, rack.nome, "Erro ao criar os ambientes e alocar as vlans do Spine-leaf.") #BE - PRODUCAO try: environment_list = ambiente_prod(user, rack, environment_list) except ObjectDoesNotExist, e: raise var_exceptions.VariableDoesNotExistException(e) except: raise RackAplError(None, rack.nome, "Erro ao criar os ambientes de produção.") #BE - Hosts - CLOUD try: environment_list = ambiente_cloud(user, rack, environment_list) except: raise RackAplError(None, rack.nome, "Erro ao criar os ambientes e alocar as vlans da Cloud.") #FE try: environment_list = ambiente_prod_fe(user, rack, environment_list) except ObjectDoesNotExist, e: raise var_exceptions.VariableDoesNotExistException(e)
def gera_config(rack): id_core1=None id_core2=None name_sp1=None name_sp2=None name_sp3=None name_sp4=None name_core1=None name_core2=None int_sp1=None int_sp2=None int_sp3=None int_sp4=None int_lf1_sp1=None int_lf1_sp2=None int_lf2_sp3=None int_lf2_sp4=None int_oob_mgmtlf1=None int_oob_mgmtlf2=None int_oob_core1=None int_oob_core2=None int_core1_oob=None int_core2_oob=None #Equipamentos num_rack = rack.numero try: id_lf1 = rack.id_sw1.id name_lf1 = rack.id_sw1.nome id_lf2 = rack.id_sw2.id name_lf2 = rack.id_sw2.nome id_oob = rack.id_ilo.id name_oob = rack.id_ilo.nome except: raise RackConfigError(None,rack.nome,"Erro: Rack incompleto.") #Interface leaf01 try: interfaces = Interface.search(id_lf1) for interface in interfaces: try: sw = interface.get_switch_and_router_interface_from_host_interface(None) if sw.equipamento.nome.split('-')[2]=='01' or sw.equipamento.nome.split('-')[2]=='1': int_lf1_sp1 = interface.interface name_sp1 = sw.equipamento.nome id_sp1 = sw.equipamento.id int_sp1 = sw.interface elif sw.equipamento.nome.split('-')[2]=='02' or sw.equipamento.nome.split('-')[2]=='2': int_lf1_sp2 = interface.interface name_sp2 = sw.equipamento.nome id_sp2 = sw.equipamento.id int_sp2 = sw.interface elif sw.equipamento.nome.split('-')[0]=='OOB': int_oob_mgmtlf1 = sw.interface except: pass except InterfaceNotFoundError: raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Leaf 01.") if int_sp1==None or int_sp2==None or int_oob_mgmtlf1==None: raise RackConfigError(None,rack.nome,"Erro: As interfaces do Leaf01 nao foram cadastradas.") #Interface leaf02 try: interfaces1 = Interface.search(id_lf2) for interface1 in interfaces1: try: sw = interface1.get_switch_and_router_interface_from_host_interface(None) if sw.equipamento.nome.split('-')[2]=='03' or sw.equipamento.nome.split('-')[2]=='3': int_lf2_sp3 = interface1.interface name_sp3 = sw.equipamento.nome id_sp3 = sw.equipamento.id int_sp3 = sw.interface elif sw.equipamento.nome.split('-')[2]=='04' or sw.equipamento.nome.split('-')[2]=='4': int_lf2_sp4 = interface1.interface name_sp4 = sw.equipamento.nome id_sp4 = sw.equipamento.id int_sp4 = sw.interface elif sw.equipamento.nome.split('-')[0]=='OOB': int_oob_mgmtlf2 = sw.interface except: pass except InterfaceNotFoundError: raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Leaf 02.") if int_sp3==None or int_sp4==None or int_oob_mgmtlf2==None: raise RackConfigError(None,rack.nome,"Erro: As interfaces do Leaf02 nao foram cadastradas.") #Interface OOB try: interfaces2 = Interface.search(id_oob) for interface2 in interfaces2: try: sw = interface2.get_switch_and_router_interface_from_host_interface(None) if sw.equipamento.nome.split('-')[0]=='OOB': if sw.equipamento.nome.split('-')[2]=='01' or sw.equipamento.nome.split('-')[2]=='1': int_oob_core1 = interface2.interface name_core1 = sw.equipamento.nome int_core1_oob = sw.interface id_core1 = sw.equipamento.id elif sw.equipamento.nome.split('-')[2]=='02' or sw.equipamento.nome.split('-')[2]=='2': int_oob_core2 = interface2.interface name_core2 = sw.equipamento.nome int_core2_oob = sw.interface id_core2 = sw.equipamento.id except: pass except InterfaceNotFoundError: raise RackConfigError(None,rack.nome,"Erro ao buscar as interfaces associadas ao Switch de gerencia.") if int_oob_core1==None or int_core1_oob==None or int_oob_core2==None or int_core2_oob==None: raise RackConfigError(None,rack.nome,"Erro: As interfaces do Switch de gerencia nao foram cadastradas.") #Roteiro LF01 try: FILEINLF1 = buscar_roteiro(id_lf1, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Leaf 01.") #Roteiro LF02 try: FILEINLF2 = buscar_roteiro(id_lf2, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Leaf 02.") #Roteiro SPN01 try: FILEINSP1 = buscar_roteiro(id_sp1, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 01.") #Roteiro SPN02 try: FILEINSP2 = buscar_roteiro(id_sp2, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 02.") #Roteiro SPN03 try: FILEINSP3 = buscar_roteiro(id_sp3, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 03.") #Roteiro SPN04 try: FILEINSP4 = buscar_roteiro(id_sp4, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Spine 04.") #Roteiro Core 01 try: FILEINCR1 = buscar_roteiro(id_core1, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Core 01.") #Roteiro Core 02 try: FILEINCR2 = buscar_roteiro(id_core2, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do Core 02.") #Roteiro OOB try: FILEINOOB = buscar_roteiro(id_oob, "CONFIGURACAO") except: raise RackConfigError(None,rack.nome,"Erro ao buscar o roteiro do switch de gerencia.") #Ip LF01 try: ip_mgmtlf1 = buscar_ip(id_lf1) except: raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do leaf 01.") #Ip LF02 try: ip_mgmtlf2 = buscar_ip(id_lf2) except: raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do leaf 02.") #Ip OOB try: ip_mgmtoob = buscar_ip(id_oob) except: raise RackConfigError(None,rack.nome,"Erro ao buscar o ip de gerencia do oob.") try: NETWORKAPI_USE_FOREMAN = int(get_variable("use_foreman")) NETWORKAPI_FOREMAN_URL = get_variable("foreman_url") NETWORKAPI_FOREMAN_USERNAME = get_variable("foreman_username") NETWORKAPI_FOREMAN_PASSWORD = get_variable("foreman_password") FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable("foreman_hosts_environment_id") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis relativas ao Foreman.") #begin - Create Foreman entries for rack switches if NETWORKAPI_USE_FOREMAN: foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2) #for each switch, check the switch ip against foreman know networks, finds foreman hostgroup # based on model and brand and inserts the host in foreman # if host already exists, delete and recreate with new information for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]: #Get all foremand subnets and compare with the IP address of the switches until find it if mac == None: raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no mac address." % (switch.nome))) ip = buscar_ip(switch.id) switch_cadastrado=0 for subnet in foreman.subnets.index()['results']: network = IPNetwork(ip+'/'+subnet['mask']).network #check if switches ip network is the same as subnet['subnet']['network'] e subnet['subnet']['mask'] if network.__str__() == subnet['network']: subnet_id = subnet['id'] hosts = foreman.hosts.index(search=switch.nome)['results'] if len(hosts) == 1: foreman.hosts.destroy(id=hosts[0]['id']) elif len(hosts) > 1: raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There are multiple entries with the sam name." % (switch.nome))) #Lookup foreman hostgroup #By definition, hostgroup should be Marca+"_"+Modelo hostgroup_name = switch.modelo.marca.nome+"_"+switch.modelo.nome hostgroups = foreman.hostgroups.index(search=hostgroup_name) if len(hostgroups['results']) == 0: raise RackConfigError(None, rack.nome, "Could not create entry for %s. Could not find hostgroup %s in foreman." % (switch.nome, hostgroup_name)) elif len(hostgroups['results'])>1: raise RackConfigError(None, rack.nome, "Could not create entry for %s. Multiple hostgroups %s found in Foreman." % (switch.nome, hostgroup_name)) else: hostgroup_id = hostgroups['results'][0]['id'] host = foreman.hosts.create(host={'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true'}) switch_cadastrado=1 if not switch_cadastrado: raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % (switch.nome)) #end - Create Foreman entries for rack switches var1 = autoprovision_splf(num_rack, FILEINLF1, FILEINLF2, FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4, name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4, ip_mgmtlf1, ip_mgmtlf2, int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1, int_lf1_sp2, int_lf2_sp3, int_lf2_sp4) var2 = autoprovision_coreoob(num_rack, FILEINCR1, FILEINCR2, FILEINOOB, name_core1, name_core2, name_oob, name_lf1, name_lf2, ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob ) if var1 and var2: return True return False
def autoprovision_splf(rack,FILEINLF1, FILEINLF2,FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4,name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4, ip_mgmtlf1, ip_mgmtlf2, int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1,int_lf1_sp2,int_lf2_sp3,int_lf2_sp4): # STRUCTURE: IPSPINE[rack][spine]: ip a configurar no spine 'spine' relativo à leaf do rack 'rack' # STRUCTURE: IPLEAF[rack][spine]: ip a configurar na leaf do rack 'rack' relativo ao spine 'spine' CIDREBGP = {} CIDRBE = {} IPSPINEipv4 = {} IPSPINEipv6 = {} IPLEAFipv4 = {} IPLEAFipv6 = {} IPSIBGPipv4 = {} IPSIBGPipv6 = {} ASLEAF = {} # VLANBELEAF = {} VLANFELEAF = {} VLANBORDALEAF = {} VLANBORDACACHOSLEAF = {} # PODSBEipv4 = {} redesPODSBEipv4 = {} # subnetsRackBEipv4 = {} # PODSBEipv6 = {} redesPODSBEipv6 = {} PODSBEFEipv6 = {} redesPODSBEFEipv6 = {} PODSBEBOipv6 = {} redesPODSBEBOipv6 = {} PODSBECAipv6 = {} redesPODSBECAipv6 = {} redesHostsipv6 = {} redeHostsBEipv6 = {} redeHostsFEipv6 = {} redeHostsBOipv6 = {} redeHostsCAipv6 = {} redeHostsFILERipv6 = {} subnetsRackBEipv6 = {} subnetsRackFEipv4 = {} redesPODSFEipv4 = {} subnetsRackFEipv6 = {} redesPODSFEipv6 = {} # IPSPINEipv4[rack]=[] IPSPINEipv6[rack]=[] IPLEAFipv4[rack]=[] IPLEAFipv6[rack]=[] IPSIBGPipv4[rack]=[] IPSIBGPipv6[rack]=[] VLANBELEAF[rack]=[] VLANFELEAF[rack]=[] VLANBORDALEAF[rack]=[] VLANBORDACACHOSLEAF[rack]=[] ASLEAF[rack]=[] # PODSBEipv4[rack]=[] redesPODSBEipv4[rack]=[] # subnetsRackBEipv4[rack] = [] # PODSBEipv6[rack]=[] redesPODSBEipv6[rack]=[] PODSBEFEipv6[rack]=[] redesPODSBEFEipv6[rack]=[] PODSBEBOipv6[rack]=[] redesPODSBEBOipv6[rack]=[] PODSBECAipv6[rack]=[] redesPODSBECAipv6[rack]=[] redesHostsipv6[rack]=[] redeHostsBEipv6[rack]=[] redeHostsFEipv6[rack]=[] redeHostsBOipv6[rack]=[] redeHostsCAipv6[rack]=[] redeHostsFILERipv6[rack]=[] subnetsRackBEipv6[rack] = [] subnetsRackFEipv4[rack] = [] redesPODSFEipv4[rack] = [] subnetsRackFEipv6[rack] = [] redesPODSFEipv6[rack] = [] CIDRFEipv4 = {} CIDRFEipv6 = {} variablestochangespine1={} variablestochangespine2={} variablestochangespine3={} variablestochangespine4={} variablestochangeleaf1={} variablestochangeleaf2={} try: fileinleaf1=get_variable("path_to_guide")+FILEINLF1 fileinleaf2=get_variable("path_to_guide")+FILEINLF2 fileinspine1=get_variable("path_to_guide")+FILEINSP1 fileinspine2=get_variable("path_to_guide")+FILEINSP2 fileinspine3=get_variable("path_to_guide")+FILEINSP3 fileinspine4=get_variable("path_to_guide")+FILEINSP4 BASE_RACK = int(get_variable("base_rack")) BASE_AS = int(get_variable("base_as")) VLANBE = int(get_variable("vlanbe")) VLANFE = int(get_variable("vlanfe")) VLANBORDA = int(get_variable("vlanborda")) VLANBORDACACHOS = int(get_variable("vlanbordacachos")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_GUIDE ou BASE_<RACK,AS> ou VLAN<BE,FE,BORDA,CACHOS>.")
import logging from networkapi.rest import RestResource, UserNotAuthorizedError from networkapi.equipamento.models import EquipamentoRoteiro from networkapi.interface.models import Interface, InterfaceNotFoundError from networkapi.rack.resource.GeraConfig import autoprovision_splf, autoprovision_coreoob from networkapi.ip.models import Ip, IpEquipamento from netaddr import IPNetwork from requests.exceptions import RequestException from networkapi.system.facade import get_value as get_variable from networkapi.system import exceptions as var_exceptions from django.core.exceptions import ObjectDoesNotExist import re log = logging.getLogger(__name__) if int(get_variable("use_foreman")): from foreman.client import Foreman, ForemanException def buscar_roteiro(id_sw, tipo): roteiros = EquipamentoRoteiro.search(None, id_sw) for rot in roteiros: if (rot.roteiro.tipo_roteiro.tipo == tipo): roteiro_eq = rot.roteiro.roteiro roteiro_eq = roteiro_eq.lower() if not '.txt' in roteiro_eq: roteiro_eq = roteiro_eq + ".txt" return roteiro_eq
def gera_config(rack): id_core1 = None id_core2 = None name_sp1 = None name_sp2 = None name_sp3 = None name_sp4 = None name_core1 = None name_core2 = None int_sp1 = None int_sp2 = None int_sp3 = None int_sp4 = None int_lf1_sp1 = None int_lf1_sp2 = None int_lf2_sp3 = None int_lf2_sp4 = None int_oob_mgmtlf1 = None int_oob_mgmtlf2 = None int_oob_core1 = None int_oob_core2 = None int_core1_oob = None int_core2_oob = None prefix_spine = 'SPN' prefix_oob = 'OOB' # Equipamentos num_rack = rack.numero try: id_lf1 = rack.id_sw1.id name_lf1 = rack.id_sw1.nome id_lf2 = rack.id_sw2.id name_lf2 = rack.id_sw2.nome id_oob = rack.id_ilo.id name_oob = rack.id_ilo.nome except: raise RackConfigError(None, rack.nome, 'Erro: Rack incompleto.') # Interface leaf01 try: interfaces = Interface.search(id_lf1) for interface in interfaces: try: sw = interface.get_switch_and_router_interface_from_host_interface( None) if sw.equipamento.nome.split('-')[0] == prefix_spine: if sw.equipamento.nome.split('-')[2] == '01' or sw.equipamento.nome.split('-')[2] == '1': int_lf1_sp1 = interface.interface name_sp1 = sw.equipamento.nome id_sp1 = sw.equipamento.id int_sp1 = sw.interface elif sw.equipamento.nome.split('-')[2] == '02' or sw.equipamento.nome.split('-')[2] == '2': int_lf1_sp2 = interface.interface name_sp2 = sw.equipamento.nome id_sp2 = sw.equipamento.id int_sp2 = sw.interface elif sw.equipamento.nome.split('-')[0] == prefix_oob: int_oob_mgmtlf1 = sw.interface except: pass except InterfaceNotFoundError: raise RackConfigError( None, rack.nome, 'Erro ao buscar as interfaces associadas ao Leaf 01.') if int_sp1 is None or int_sp2 is None or int_oob_mgmtlf1 is None: raise RackConfigError( None, rack.nome, 'Erro: As interfaces do Leaf01 nao foram cadastradas.') # Interface leaf02 try: interfaces1 = Interface.search(id_lf2) for interface1 in interfaces1: try: sw = interface1.get_switch_and_router_interface_from_host_interface( None) if sw.equipamento.nome.split('-')[0] == prefix_spine: if sw.equipamento.nome.split('-')[2] == '03' or sw.equipamento.nome.split('-')[2] == '3': int_lf2_sp3 = interface1.interface name_sp3 = sw.equipamento.nome id_sp3 = sw.equipamento.id int_sp3 = sw.interface elif sw.equipamento.nome.split('-')[2] == '04' or sw.equipamento.nome.split('-')[2] == '4': int_lf2_sp4 = interface1.interface name_sp4 = sw.equipamento.nome id_sp4 = sw.equipamento.id int_sp4 = sw.interface elif sw.equipamento.nome.split('-')[0] == prefix_oob: int_oob_mgmtlf2 = sw.interface except: pass except InterfaceNotFoundError: raise RackConfigError( None, rack.nome, 'Erro ao buscar as interfaces associadas ao Leaf 02.') if int_sp3 is None or int_sp4 is None or int_oob_mgmtlf2 is None: raise RackConfigError( None, rack.nome, 'Erro: As interfaces do Leaf02 nao foram cadastradas.') # Interface OOB try: interfaces2 = Interface.search(id_oob) for interface2 in interfaces2: try: sw = interface2.get_switch_and_router_interface_from_host_interface( None) if sw.equipamento.nome.split('-')[0] == prefix_oob: if sw.equipamento.nome.split('-')[2] == '01' or sw.equipamento.nome.split('-')[2] == '1': int_oob_core1 = interface2.interface name_core1 = sw.equipamento.nome int_core1_oob = sw.interface id_core1 = sw.equipamento.id elif sw.equipamento.nome.split('-')[2] == '02' or sw.equipamento.nome.split('-')[2] == '2': int_oob_core2 = interface2.interface name_core2 = sw.equipamento.nome int_core2_oob = sw.interface id_core2 = sw.equipamento.id except: pass except InterfaceNotFoundError: raise RackConfigError( None, rack.nome, 'Erro ao buscar as interfaces associadas ao Switch de gerencia.') if int_oob_core1 is None or int_core1_oob is None or int_oob_core2 is None or int_core2_oob is None: raise RackConfigError( None, rack.nome, 'Erro: As interfaces do Switch de gerencia nao foram cadastradas.') # Roteiro LF01 try: FILEINLF1 = buscar_roteiro(id_lf1, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Leaf 01.') # Roteiro LF02 try: FILEINLF2 = buscar_roteiro(id_lf2, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Leaf 02.') # Roteiro SPN01 try: FILEINSP1 = buscar_roteiro(id_sp1, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Spine 01.') # Roteiro SPN02 try: FILEINSP2 = buscar_roteiro(id_sp2, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Spine 02.') # Roteiro SPN03 try: FILEINSP3 = buscar_roteiro(id_sp3, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Spine 03.') # Roteiro SPN04 try: FILEINSP4 = buscar_roteiro(id_sp4, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Spine 04.') # Roteiro Core 01 try: FILEINCR1 = buscar_roteiro(id_core1, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Core 01.') # Roteiro Core 02 try: FILEINCR2 = buscar_roteiro(id_core2, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do Core 02.') # Roteiro OOB try: FILEINOOB = buscar_roteiro(id_oob, 'CONFIGURACAO') except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o roteiro do switch de gerencia.') # Ip LF01 try: ip_mgmtlf1 = buscar_ip(id_lf1) except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o ip de gerencia do leaf 01.') # Ip LF02 try: ip_mgmtlf2 = buscar_ip(id_lf2) except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o ip de gerencia do leaf 02.') # Ip OOB try: ip_mgmtoob = buscar_ip(id_oob) except: raise RackConfigError( None, rack.nome, 'Erro ao buscar o ip de gerencia do oob.') try: NETWORKAPI_USE_FOREMAN = int(get_variable('use_foreman')) NETWORKAPI_FOREMAN_URL = get_variable('foreman_url') NETWORKAPI_FOREMAN_USERNAME = get_variable('foreman_username') NETWORKAPI_FOREMAN_PASSWORD = get_variable('foreman_password') FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable( 'foreman_hosts_environment_id') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando as variáveis relativas ao Foreman.') # begin - Create Foreman entries for rack switches if NETWORKAPI_USE_FOREMAN: foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2) # for each switch, check the switch ip against foreman know networks, finds foreman hostgroup # based on model and brand and inserts the host in foreman # if host already exists, delete and recreate with new information for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]: # Get all foremand subnets and compare with the IP address of the # switches until find it if mac is None: raise RackConfigError( None, rack.nome, ('Could not create entry for %s. There is no mac address.' % (switch.nome))) ip = buscar_ip(switch.id) if ip is None: raise RackConfigError( None, rack.nome, ('Could not create entry for %s. There is no management IP.' % (switch.nome))) switch_cadastrado = 0 for subnet in foreman.subnets.index()['results']: network = IPNetwork(ip + '/' + subnet['mask']).network # check if switches ip network is the same as # subnet['subnet']['network'] e subnet['subnet']['mask'] if network.__str__() == subnet['network']: subnet_id = subnet['id'] hosts = foreman.hosts.index(search=switch.nome)['results'] if len(hosts) == 1: foreman.hosts.destroy(id=hosts[0]['id']) elif len(hosts) > 1: raise RackConfigError( None, rack.nome, ('Could not create entry for %s. There are multiple entries with the sam name.' % (switch.nome))) # Lookup foreman hostgroup # By definition, hostgroup should be Marca+"_"+Modelo hostgroup_name = switch.modelo.marca.nome + '_' + switch.modelo.nome hostgroups = foreman.hostgroups.index( search=hostgroup_name) if len(hostgroups['results']) == 0: raise RackConfigError(None, rack.nome, 'Could not create entry for %s. Could not find hostgroup %s in foreman.' % ( switch.nome, hostgroup_name)) elif len(hostgroups['results']) > 1: raise RackConfigError(None, rack.nome, 'Could not create entry for %s. Multiple hostgroups %s found in Foreman.' % ( switch.nome, hostgroup_name)) else: hostgroup_id = hostgroups['results'][0]['id'] host = foreman.hosts.create(host={'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true'}) switch_cadastrado = 1 if not switch_cadastrado: raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % (switch.nome)) #end - Create Foreman entries for rack switches var1 = autoprovision_splf(num_rack, FILEINLF1, FILEINLF2, FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4, name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4, ip_mgmtlf1, ip_mgmtlf2, int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1, int_lf1_sp2, int_lf2_sp3, int_lf2_sp4) var2 = autoprovision_coreoob(num_rack, FILEINCR1, FILEINCR2, FILEINOOB, name_core1, name_core2, name_oob, name_lf1, name_lf2, ip_mgmtoob, int_oob_core1, int_oob_core2, int_core1_oob, int_core2_oob ) if var1 and var2: return True return False
def ambiente_prod(user, rack, environment_list): redes, ipv6 = dic_pods(rack.numero) divisao_aclpaths = [['BE', 'BECLOUD'], ['BEFE', 'BEFE'], ['BEBORDA', 'BEBORDA'], ['BECACHOS', 'BECACHOS']] grupol3 = rack.nome ambiente_logico = 'PRODUCAO' ambientes = dict() ambientes['LOG'] = ambiente_logico ambientes['L3'] = grupol3 ranges = dict() hosts = dict() vlans = dict() try: base_vlan = int(get_variable('num_vlan_acl_be')) except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável NUM_VLAN_ACL_BE') hosts['TIPO'] = 'Rede invalida equipamentos' ipv6['TIPO'] = 'Rede invalida equipamentos' for item in divisao_aclpaths: divisaodc = item[0] acl_path = item[1] ambientes['DC'] = divisaodc # criar ambiente vlan_min = divisaodc + '_VLAN_MIN' vlan_max = divisaodc + '_VLAN_MAX' ranges['MAX'] = redes.get(vlan_max) ranges['MIN'] = redes.get(vlan_min) env = criar_ambiente(user, ambientes, ranges, acl_path, 'Servidores', 'BEVrf') environment_list.append(env) # configuracao dos ambientes prefix = divisaodc + '_PREFIX' rede = divisaodc + '_REDE' hosts['PREFIX'] = redes.get(prefix) hosts['REDE'] = redes.get(rede) hosts['VERSION'] = 'ipv4' config_ambiente(user, hosts, ambientes) ipv6['PREFIX'] = ipv6.get(prefix) ipv6['REDE'] = ipv6.get(rede) ipv6['VERSION'] = 'ipv6' config_ambiente(user, ipv6, ambientes) vlans['VLAN_NUM'] = base_vlan base_vlan += 1 vlans['VLAN_NAME'] = 'ACL_' + divisaodc + '_' + ambientes.get('L3') criar_vlan(user, vlans, ambientes, 1) return environment_list
BASE_RACK = int(get_variable('base_rack')) VLANBE = int(get_variable('vlanbe')) VLANFE = int(get_variable('vlanfe')) VLANBORDA = int(get_variable('vlanborda')) VLANBORDACACHOS = int(get_variable('vlanbordacachos')) VLANBETORxTOR = int(get_variable('vlanbetorxtor')) # CIDR sala 01 => 10.128.0.0/12 CIDRBE[0] = IPNetwork(get_variable('cidr_sl01')) CIDREBGP[0] = IPNetwork(get_variable('cidr_bgp')) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável BASE_RACK ou VLAN<BE,FE,BORDA,CACHOS,TORxTOR> ou CIDR<BE,EBGP>.' ) SPINE1ipv4 = IPNetwork(get_variable('net_spn01')) SPINE2ipv4 = IPNetwork(get_variable('net_spn02')) SPINE3ipv4 = IPNetwork(get_variable('net_spn03')) SPINE4ipv4 = IPNetwork(get_variable('net_spn04')) # REDE subSPINE1ipv4[rack] subSPINE1ipv4 = list(SPINE1ipv4.subnet(31)) subSPINE2ipv4 = list(SPINE2ipv4.subnet(31)) subSPINE3ipv4 = list(SPINE3ipv4.subnet(31)) subSPINE4ipv4 = list(SPINE4ipv4.subnet(31)) SPINE1ipv6 = IPNetwork(get_variable('net_spn01_v6')) SPINE2ipv6 = IPNetwork(get_variable('net_spn02_v6')) SPINE3ipv6 = IPNetwork(get_variable('net_spn03_v6')) SPINE4ipv6 = IPNetwork(get_variable('net_spn04_v6')) subSPINE1ipv6 = list(SPINE1ipv6.subnet(127)) subSPINE2ipv6 = list(SPINE2ipv6.subnet(127))
def autoprovision_coreoob(rack, equips): log.info("AutoprovisionOOB") variablestochangecore1 = dict() variablestochangecore2 = dict() variablestochangeoob = dict() prefixlf = "LF-" prefixoob = "OOB" vlan_base = None dcroom = model_to_dict(rack.dcroom) log.debug("type: %s" % str(type(dcroom.get("config")))) fabricconfig = dcroom.get("config") try: fabricconfig = json.loads(fabricconfig) log.debug("type -ast: %s" % str(type(fabricconfig))) except: pass try: fabricconfig = ast.literal_eval(fabricconfig) log.debug("config -ast: %s" % str(fabricconfig)) except: pass envconfig = fabricconfig BASE_CHANNEL = int(envconfig.get("Channel").get( "channel")) if envconfig.get("Channel") else 10 try: path_to_guide = get_variable("path_to_guide") path_to_add_config = get_variable("path_to_add_config") path_to_config = get_variable("path_to_config") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( "Erro buscando a variável PATH_TO_GUIDE") environment = models_env.Ambiente.objects.filter( dcroom=rack.dcroom.id, father_environment__isnull=True, ambiente_logico__nome="GERENCIA", divisao_dc__nome="OOB").uniqueResult() log.debug("environment: %s " % str(environment)) log.debug("equips: %s" % str(equips)) vlan_base = environment.min_num_vlan_1 for net in environment.configs: if net.ip_config.type == "v4": redev4 = IPNetwork(str(net.ip_config.subnet)) prefixv4 = int(net.ip_config.new_prefix) subredev4 = list(redev4.subnet(prefixv4)) if not vlan_base: raise Exception( "Range de Vlans do ambiente de gerencia do fabric não encontrado.") if not subredev4: raise Exception("Rede ipv4 do ambiente OOB do fabric não encontrado.") vlan_so = str(int(vlan_base) + int(rack.numero)) variablestochangeoob["VLAN_SO"] = vlan_so equips_sorted = sorted(equips, key=operator.itemgetter('sw')) oob = equips_sorted[-1] variablestochangeoob["OWN_IP_MGMT"] = oob.get("ip_mngt") variablestochangeoob["HOSTNAME_OOB"] = oob.get("nome") variablestochangeoob["HOSTNAME_RACK"] = rack.nome fileinoob = path_to_guide + oob.get("roteiro") fileoutoob = path_to_config + oob.get("nome") + ".cfg" for equip in oob.get("interfaces"): nome = equip.get("nome") log.debug(str(nome)) roteiro = equip.get("roteiro") if nome[:3] == prefixlf: if nome[-1] == "1": variablestochangeoob["HOSTNAME_LF1"] = nome else: variablestochangeoob["HOSTNAME_LF2"] = nome elif nome[:3] == prefixoob: intoob = equip.get("eq_interface") intcore = equip.get("interface") if nome[-1] == "1": log.info("oob01") log.info(str(nome)) hostname_core1 = nome core = int(hostname_core1.split('-')[-1]) ip = 124 + core variablestochangeoob["INT_OOBC1_UPLINK"] = intoob variablestochangeoob["INTERFACE_CORE1"] = intcore variablestochangeoob["HOSTNAME_CORE1"] = nome variablestochangecore1["INT_OOB_UPLINK"] = intoob variablestochangecore1["INTERFACE_CORE"] = intcore variablestochangecore1["HOSTNAME_RACK"] = rack.nome variablestochangecore1["SO_HOSTNAME_OOB"] = "SO_" + str( rack.nome) variablestochangecore1["VLAN_SO"] = vlan_so variablestochangecore1['IPCORE'] = str( subredev4[rack.numero][ip]) variablestochangecore1['IPHSRP'] = str( subredev4[rack.numero][1]) variablestochangecore1['NUM_CHANNEL'] = str(BASE_CHANNEL + int(rack.numero)) if (1 + int(rack.numero)) % 2 == 0: variablestochangecore1["HSRP_PRIORITY"] = "100" else: variablestochangecore1["HSRP_PRIORITY"] = "101" fileincore1 = path_to_guide + roteiro fileoutcore1 = path_to_add_config + nome + "-ADD-" + str( rack.nome) + ".cfg" elif nome[-1] == "2": log.info("oob02") log.info(str(nome)) hostname_core2 = nome core = int(hostname_core2.split('-')[-1]) ip = 124 + core variablestochangeoob["INT_OOBC2_UPLINK"] = intoob variablestochangeoob["INTERFACE_CORE2"] = intcore variablestochangeoob["HOSTNAME_CORE2"] = nome variablestochangecore2["INT_OOB_UPLINK"] = intoob variablestochangecore2["INTERFACE_CORE"] = intcore variablestochangecore2["HOSTNAME_RACK"] = rack.nome variablestochangecore2["SO_HOSTNAME_OOB"] = "SO_" + str( rack.nome) variablestochangecore2["VLAN_SO"] = vlan_so variablestochangecore2['IPCORE'] = str( subredev4[rack.numero][ip]) variablestochangecore2['IPHSRP'] = str( subredev4[rack.numero][1]) variablestochangecore2['NUM_CHANNEL'] = str(BASE_CHANNEL + int(rack.numero)) if (2 + int(rack.numero)) % 2 == 0: variablestochangecore2["HSRP_PRIORITY"] = "100" else: variablestochangecore2["HSRP_PRIORITY"] = "101" fileincore2 = path_to_guide + roteiro fileoutcore2 = path_to_add_config + nome + "-ADD-" + str( rack.nome) + ".cfg" replace(fileincore1, fileoutcore1, variablestochangecore1) replace(fileincore2, fileoutcore2, variablestochangecore2) replace(fileinoob, fileoutoob, variablestochangeoob) return True
try: BASE_RACK = int(get_variable("base_rack")) VLANBE = int(get_variable("vlanbe")) VLANFE = int(get_variable("vlanfe")) VLANBORDA = int(get_variable("vlanborda")) VLANBORDACACHOS = int(get_variable("vlanbordacachos")) VLANBETORxTOR = int(get_variable("vlanbetorxtor")) #CIDR sala 01 => 10.128.0.0/12 CIDRBE[0] = IPNetwork(get_variable("cidr_sl01")) CIDREBGP[0] = IPNetwork(get_variable("cidr_bgp")) except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável BASE_RACK ou VLAN<BE,FE,BORDA,CACHOS,TORxTOR> ou CIDR<BE,EBGP>.") SPINE1ipv4 = IPNetwork(get_variable("net_spn01")) SPINE2ipv4 = IPNetwork(get_variable("net_spn02")) SPINE3ipv4 = IPNetwork(get_variable("net_spn03")) SPINE4ipv4 = IPNetwork(get_variable("net_spn04")) #REDE subSPINE1ipv4[rack] subSPINE1ipv4=list(SPINE1ipv4.subnet(31)) subSPINE2ipv4=list(SPINE2ipv4.subnet(31)) subSPINE3ipv4=list(SPINE3ipv4.subnet(31)) subSPINE4ipv4=list(SPINE4ipv4.subnet(31)) SPINE1ipv6 = IPNetwork(get_variable("net_spn01_v6")) SPINE2ipv6 = IPNetwork(get_variable("net_spn02_v6")) SPINE3ipv6 = IPNetwork(get_variable("net_spn03_v6")) SPINE4ipv6 = IPNetwork(get_variable("net_spn04_v6")) subSPINE1ipv6=list(SPINE1ipv6.subnet(127)) subSPINE2ipv6=list(SPINE2ipv6.subnet(127))
from networkapi.infrastructure.xml_utils import dumps_networkapi import logging from networkapi.rest import RestResource, UserNotAuthorizedError from networkapi.equipamento.models import EquipamentoRoteiro from networkapi.interface.models import Interface, InterfaceNotFoundError from networkapi.rack.resource.GeraConfig import autoprovision_splf, autoprovision_coreoob from networkapi.ip.models import Ip, IpEquipamento from netaddr import IPNetwork from requests.exceptions import RequestException from networkapi.system.facade import get_value as get_variable from networkapi.system import exceptions as var_exceptions from django.core.exceptions import ObjectDoesNotExist log = logging.getLogger(__name__) if int(get_variable("use_foreman")): from foreman.client import Foreman, ForemanException def buscar_roteiro(id_sw, tipo): roteiros = EquipamentoRoteiro.search(None, id_sw) for rot in roteiros: if (rot.roteiro.tipo_roteiro.tipo==tipo): roteiro_eq = rot.roteiro.roteiro roteiro_eq = roteiro_eq.lower() if not '.txt' in roteiro_eq: roteiro_eq=roteiro_eq+".txt" return roteiro_eq def buscar_ip(id_sw):
raise base_exceptions.CommandErrorException(e) else: log.info('Connected in hostname:%s' % hostname) try: self._version = self._channel.System.SystemInfo.get_version() if self._version[8:len(self._version)].split('.')[0] <= 10: raise base_exceptions.UnsupportedVersion( 'This plugin only supports BIG-IP v11 or above') else: if session: log.info('Try get new session') session_cur = self._channel.System.Session.get_session_timeout( ) log.info('Session Timeout Current: %s' % session_cur) session_timeout = get_variable( 'set_session_timeout_plugin_f5', '60') if int(session_cur) > int(session_timeout): self._channel.System.Session.set_session_timeout( session_timeout) self._channel = self.get_session() except Exception, e: log.error(e) raise base_exceptions.CommandErrorException(e) def get_session(self): try: channel = self._channel.with_session_id() log.info('Session %s', channel) except Exception, e: if 'There are too many existing user sessions.'.lower() in str(
def handle_delete(self, request, user, *args, **kwargs): """Treat requests POST to delete Rack. URL: rack/id_rack/ """ try: self.log.info("Delete Rack") ######################################################## User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) rack_id = kwargs.get('id_rack') rack = Rack() rack = rack.get_by_pk(rack_id) ######################################################## Mover os arquivos de configuracao que foram gerados try: LEAF = get_variable("leaf") OOB = get_variable("oob") SPN = get_variable("spn") FORMATO = get_variable("formato") PATH_TO_CONFIG = get_variable("path_to_config") PATH_TO_MV = get_variable("path_to_mv") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis <LEAF,OOB,SPN> ou FORMATO ou PATH_TO_<MV,CONFIG>.") try: for i in range(1,3): nome_lf = LEAF+"-"+rack.nome+"-0"+str(i)+FORMATO nome_lf_b = PATH_TO_CONFIG+nome_lf nome_lf_a = PATH_TO_MV+nome_lf shutil.move(nome_lf_b, nome_lf_a) nome_oob = OOB+"-0"+str(i)+"-ADD-"+rack.nome+FORMATO nome_oob_b = PATH_TO_CONFIG+nome_oob nome_oob_a = PATH_TO_MV+nome_oob shutil.move(nome_oob_b, nome_oob_a) for i in range(1,5): nome_spn = SPN+"-0"+str(i)+"-ADD-"+rack.nome+FORMATO nome_spn_b = PATH_TO_CONFIG+nome_spn nome_spn_a = PATH_TO_MV+nome_spn shutil.move(nome_spn_b, nome_spn_a) nome_oob = OOB+"-"+rack.nome+"-01"+FORMATO nome_oob_b = PATH_TO_CONFIG+nome_oob nome_oob_a = PATH_TO_MV+nome_oob shutil.move(nome_oob_b, nome_oob_a) except: pass ######################################################## Remover as Vlans, redes e ambientes try: desativar_vlan_rede(user, rack) lista_amb = remover_ambiente_rack(user, rack) remover_ambiente(user, lista_amb, rack) remover_vlan_so(user, rack) except: raise RackError(None, u'Failed to remove the Vlans and Environments.') ######################################################## Remove rack config from spines and core oob #aplicar(rack) ######################################################## Remove Rack with distributedlock(LOCK_RACK % rack_id): try: rack.delete() except RackNumberNotFoundError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Rack.') raise RackError(e, u'Failed to remove the Rack.')
def handle_delete(self, request, user, *args, **kwargs): """Treat requests POST to delete Rack. URL: rack/id_rack/ """ try: self.log.info('Delete Rack') # User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) rack_id = kwargs.get('id_rack') rack = Rack() rack = rack.get_by_pk(rack_id) # Mover os arquivos de configuracao que foram gerados try: LEAF = get_variable('leaf') OOB = get_variable('oob') SPN = get_variable('spn') FORMATO = get_variable('formato') PATH_TO_CONFIG = get_variable('path_to_config') PATH_TO_MV = get_variable('path_to_mv') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException( 'Erro buscando as variáveis <LEAF,OOB,SPN> ou FORMATO ou PATH_TO_<MV,CONFIG>.' ) try: for i in range(1, 3): nome_lf = LEAF + '-' + rack.nome + '-0' + str(i) + FORMATO nome_lf_b = PATH_TO_CONFIG + nome_lf nome_lf_a = PATH_TO_MV + nome_lf shutil.move(nome_lf_b, nome_lf_a) nome_oob = OOB + '-0' + \ str(i) + '-ADD-' + rack.nome + FORMATO nome_oob_b = PATH_TO_CONFIG + nome_oob nome_oob_a = PATH_TO_MV + nome_oob shutil.move(nome_oob_b, nome_oob_a) for i in range(1, 5): nome_spn = SPN + '-0' + \ str(i) + '-ADD-' + rack.nome + FORMATO nome_spn_b = PATH_TO_CONFIG + nome_spn nome_spn_a = PATH_TO_MV + nome_spn shutil.move(nome_spn_b, nome_spn_a) nome_oob = OOB + '-' + rack.nome + '-01' + FORMATO nome_oob_b = PATH_TO_CONFIG + nome_oob nome_oob_a = PATH_TO_MV + nome_oob shutil.move(nome_oob_b, nome_oob_a) except: pass # Remover as Vlans, redes e ambientes try: desativar_vlan_rede(user, rack) lista_amb = remover_ambiente_rack(user, rack) remover_ambiente(user, lista_amb, rack) remover_vlan_so(user, rack) except: raise RackError( None, u'Failed to remove the Vlans and Environments.') # Remove rack config from spines and core oob # aplicar(rack) # Remove Rack with distributedlock(LOCK_RACK % rack_id): try: rack.delete() except RackNumberNotFoundError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Rack.') raise RackError(e, u'Failed to remove the Rack.')
def autoprovision_splf(rack, FILEINLF1, FILEINLF2, FILEINSP1, FILEINSP2, FILEINSP3, FILEINSP4, name_lf1, name_lf2, name_oob, name_sp1, name_sp2, name_sp3, name_sp4, ip_mgmtlf1, ip_mgmtlf2, int_oob_mgmtlf1, int_oob_mgmtlf2, int_sp1, int_sp2, int_sp3, int_sp4, int_lf1_sp1, int_lf1_sp2, int_lf2_sp3, int_lf2_sp4): # STRUCTURE: IPSPINE[rack][spine]: ip a configurar no spine 'spine' relativo à leaf do rack 'rack' # STRUCTURE: IPLEAF[rack][spine]: ip a configurar no leaf do rack 'rack' relativo ao spine 'spine' CIDREBGP = {} CIDRBE = {} IPSPINEipv4 = {} IPSPINEipv6 = {} IPLEAFipv4 = {} IPLEAFipv6 = {} IPSIBGPipv4 = {} IPSIBGPipv6 = {} ASLEAF = {} # VLANBELEAF = {} VLANFELEAF = {} VLANBORDALEAF = {} VLANBORDACACHOSLEAF = {} # PODSBEipv4 = {} redesPODSBEipv4 = {} # subnetsRackBEipv4 = {} # PODSBEipv6 = {} redesPODSBEipv6 = {} PODSBEFEipv6 = {} redesPODSBEFEipv6 = {} PODSBEBOipv6 = {} redesPODSBEBOipv6 = {} PODSBECAipv6 = {} redesPODSBECAipv6 = {} redesHostsipv6 = {} redeHostsBEipv6 = {} redeHostsFEipv6 = {} redeHostsBOipv6 = {} redeHostsCAipv6 = {} redeHostsFILERipv6 = {} subnetsRackBEipv6 = {} subnetsRackFEipv4 = {} redesPODSFEipv4 = {} subnetsRackFEipv6 = {} redesPODSFEipv6 = {} # IPSPINEipv4[rack] = [] IPSPINEipv6[rack] = [] IPLEAFipv4[rack] = [] IPLEAFipv6[rack] = [] IPSIBGPipv4[rack] = [] IPSIBGPipv6[rack] = [] VLANBELEAF[rack] = [] VLANFELEAF[rack] = [] VLANBORDALEAF[rack] = [] VLANBORDACACHOSLEAF[rack] = [] ASLEAF[rack] = [] # PODSBEipv4[rack] = [] redesPODSBEipv4[rack] = [] # subnetsRackBEipv4[rack] = [] # PODSBEipv6[rack] = [] redesPODSBEipv6[rack] = [] PODSBEFEipv6[rack] = [] redesPODSBEFEipv6[rack] = [] PODSBEBOipv6[rack] = [] redesPODSBEBOipv6[rack] = [] PODSBECAipv6[rack] = [] redesPODSBECAipv6[rack] = [] redesHostsipv6[rack] = [] redeHostsBEipv6[rack] = [] redeHostsFEipv6[rack] = [] redeHostsBOipv6[rack] = [] redeHostsCAipv6[rack] = [] redeHostsFILERipv6[rack] = [] subnetsRackBEipv6[rack] = [] subnetsRackFEipv4[rack] = [] redesPODSFEipv4[rack] = [] subnetsRackFEipv6[rack] = [] redesPODSFEipv6[rack] = [] CIDRFEipv4 = {} CIDRFEipv6 = {} variablestochangespine1 = {} variablestochangespine2 = {} variablestochangespine3 = {} variablestochangespine4 = {} variablestochangeleaf1 = {} variablestochangeleaf2 = {} try: fileinleaf1 = get_variable("path_to_guide") + FILEINLF1 fileinleaf2 = get_variable("path_to_guide") + FILEINLF2 fileinspine1 = get_variable("path_to_guide") + FILEINSP1 fileinspine2 = get_variable("path_to_guide") + FILEINSP2 fileinspine3 = get_variable("path_to_guide") + FILEINSP3 fileinspine4 = get_variable("path_to_guide") + FILEINSP4 ### BASE_RACK = int(get_variable("base_rack")) BASE_AS = int(get_variable("base_as")) VLANBE = int(get_variable("vlanbe")) VLANFE = int(get_variable("vlanfe")) VLANBORDA = int(get_variable("vlanborda")) VLANBORDACACHOS = int(get_variable("vlanbordacachos")) ### except ObjectDoesNotExist, exception: log.error(exception) raise var_exceptions.VariableDoesNotExistException( 'Erro buscando a variável PATH_TO_GUIDE ou BASE_<RACK,AS> ou VLAN<BE,FE,BORDA,CACHOS>.' )
def api_foreman(rack): try: NETWORKAPI_FOREMAN_URL = get_variable("foreman_url") NETWORKAPI_FOREMAN_USERNAME = get_variable("foreman_username") NETWORKAPI_FOREMAN_PASSWORD = get_variable("foreman_password") FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable("foreman_hosts_environment_id") except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis relativas ao Foreman.") foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2) # for each switch, check the switch ip against foreman know networks, finds foreman hostgroup # based on model and brand and inserts the host in foreman # if host already exists, delete and recreate with new information for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]: # Get all foremand subnets and compare with the IP address of the switches until find it if mac == None: raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no mac address." % switch.nome)) ip = _buscar_ip(switch.id) if ip == None: raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no management IP." % switch.nome)) switch_cadastrado = 0 for subnet in foreman.subnets.index()['results']: network = IPNetwork(ip + '/' + subnet['mask']).network # check if switches ip network is the same as subnet['subnet']['network'] e subnet['subnet']['mask'] if network.__str__() == subnet['network']: subnet_id = subnet['id'] hosts = foreman.hosts.index(search = switch.nome)['results'] if len(hosts) == 1: foreman.hosts.destroy(id = hosts[0]['id']) elif len(hosts) > 1: raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There are multiple entries " "with the sam name." % switch.nome)) # Lookup foreman hostgroup # By definition, hostgroup should be Marca+"_"+Modelo hostgroup_name = switch.modelo.marca.nome + "_" + switch.modelo.nome hostgroups = foreman.hostgroups.index(search = hostgroup_name) if len(hostgroups['results']) == 0: raise RackConfigError(None, rack.nome, "Could not create entry for %s. Could not find hostgroup %s " "in foreman." % (switch.nome, hostgroup_name)) elif len(hostgroups['results'])>1: raise RackConfigError(None, rack.nome, "Could not create entry for %s. Multiple hostgroups %s found" " in Foreman." % (switch.nome, hostgroup_name)) else: hostgroup_id = hostgroups['results'][0]['id'] foreman.hosts.create(host = {'name': switch.nome, 'ip': ip, 'mac': mac, 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, 'build': 'true', 'overwrite': 'true'}) switch_cadastrado = 1 if not switch_cadastrado: raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % switch.nome)