Пример #1
0
def rack_environments_vlans(rack_id, user):
    log.info("Rack Environments")

    rack = Rack().get_rack(idt=rack_id)
    if rack.create_vlan_amb:
        raise Exception("Os ambientes e Vlans já foram alocados.")

    # spine x leaf
    _create_spnlfenv(rack)
    _create_spnlfvlans(rack, user)

    # leaf x leaf
    _create_lflf_vlans(rack, user)

    # producao/cloud
    _create_prod_envs(rack, user)
    _create_prod_vlans(rack, user)

    # redes de gerencia OOB
    _create_oobvlans(rack, user)

    rack.__dict__.update(id=rack.id, create_vlan_amb=True)
    rack.save()

    return rack
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to create the configuration file.

        URL: rack/gerar-arq-config/id_rack
        """
        try:
            self.log.info("CONFIG")

            # 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)
            var = False

            #Chama o script para gerar os arquivos de configuracao
            var = gera_config(rack)

            rack.__dict__.update(id=rack_id, config=var)
            rack.save()

            success_map = dict()
            success_map['rack_conf'] = var
            map = dict()
            map['sucesso'] = success_map
                        
            return self.response(dumps_networkapi(map))


        except RackConfigError, e:
            return self.response_error(382, e.param, e.value)
Пример #3
0
def rack_environments_vlans(rack_id, user):
    log.info("Rack Environments")

    rack = Rack().get_rack(idt=rack_id)
    if rack.create_vlan_amb:
        raise Exception("Os ambientes e Vlans já foram alocados.")

    # spine x leaf
    _create_spnlfenv(user, rack)
    _create_spnlfvlans(rack, user)

    # leaf x leaf
    _create_lflf_vlans(rack, user)

    # producao/cloud
    _create_prod_envs(rack, user)
    _create_prod_vlans(rack, user)

    # redes de gerencia OOB
    _create_oobvlans(rack, user)

    rack.__dict__.update(id=rack.id, create_vlan_amb=True)
    rack.save()

    return rack
Пример #4
0
def delete_rack(rack_id):

    rack_obj = Rack()
    rack = rack_obj.get_rack(idt=rack_id)

    error_vlans = list()
    error_envs = list()

    envs_ids = models_env.Ambiente.objects.filter(dcroom=rack.dcroom.id,
                                                  grupo_l3__nome=str(rack.nome)
                                                  ).values_list('id', flat=True)

    log.debug("rack envs. Qtd: %s - Envs: %s" % (str(len(envs_ids)), str(envs_ids)))

    vlans_ids = models_vlan.Vlan.objects.filter(nome__icontains=rack.nome
                                                ).values_list('id', flat=True)

    log.debug("rack vlan. Qtd: %s - VLans: %s" % (str(len(vlans_ids)), str(vlans_ids)))

    for idt in vlans_ids:
        try:
            facade_vlan_v3.delete_vlan(idt)
        except (models_vlan.VlanError,
                models_vlan.VlanErrorV3,
                ValidationAPIException,
                ObjectDoesNotExistException,
                Exception,
                NetworkAPIException), e:
            error_vlans.append({'vlan_id': idt, 'error': e})
Пример #5
0
def delete_rack(rack_id):

    rack_obj = Rack()
    rack = rack_obj.get_rack(idt=rack_id)

    error_vlans = list()
    error_envs = list()

    envs_ids = models_env.Ambiente.objects.filter(
        dcroom=rack.dcroom.id,
        grupo_l3__nome=str(rack.nome)).values_list('id', flat=True)

    log.debug("rack envs. Qtd: %s - Envs: %s" %
              (str(len(envs_ids)), str(envs_ids)))

    vlans_ids = models_vlan.Vlan.objects.filter(
        nome__icontains=rack.nome).values_list('id', flat=True)

    log.debug("rack vlan. Qtd: %s - VLans: %s" %
              (str(len(vlans_ids)), str(vlans_ids)))

    for idt in vlans_ids:
        try:
            facade_vlan_v3.delete_vlan(idt)
        except (models_vlan.VlanError, models_vlan.VlanErrorV3,
                ValidationAPIException, ObjectDoesNotExistException, Exception,
                NetworkAPIException), e:
            error_vlans.append({'vlan_id': idt, 'error': e})
Пример #6
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Racks

        URLs: /rack/find/
        """

        self.log.info('Find all Racks')

        try:

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            nome = kwargs.get('rack_name')
            rack = Rack()
            rack = rack.get_by_name(nome)
            rack = model_to_dict(rack)

            return self.response(dumps_networkapi({'rack': rack}))

        except UserNotAuthorizedError:
            return self.not_authorized()

        except RackError:
            return self.response_error(379)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Racks

        URLs: /rack/find/
        """

        self.log.info('Find all Racks')

        try:

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT , AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            nome = kwargs.get('rack_name')
            rack = Rack()
            rack = rack.get_by_name(nome)
            rack = model_to_dict(rack)

            return self.response(dumps_networkapi({'rack': rack}))

        except UserNotAuthorizedError:
            return self.not_authorized()

        except RackError:
            return self.response_error(379)
Пример #8
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to create the configuration file.

        URL: rack/gerar-arq-config/id_rack
        """
        try:
            self.log.info('CONFIG')

            # 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)
            var = False

            # Chama o script para gerar os arquivos de configuracao
            var = gera_config(rack)

            rack.__dict__.update(id=rack_id, config=var)
            rack.save()

            success_map = dict()
            success_map['rack_conf'] = var
            map = dict()
            map['sucesso'] = success_map

            return self.response(dumps_networkapi(map))

        except RackConfigError, e:
            return self.response_error(382, e.param, e.value)
Пример #9
0
def get_rack(fabric_id=None, rack_id=None):

    rack_obj = Rack()

    try:
        if fabric_id:
            rack = rack_obj.get_rack(dcroom_id=fabric_id)
            rack_list = rack_serializers.RackSerializer(rack, many=True).data if rack else list()
        elif rack_id:
            rack = rack_obj.get_rack(idt=rack_id)
            rack_list = [rack_serializers.RackSerializer(rack).data] if rack else list()
        else:
            rack = rack_obj.get_rack()
            rack_list = rack_serializers.RackSerializer(rack, many=True).data if rack else list()

        return rack_list

    except (ObjectDoesNotExist, Exception), e:
        raise Exception(e)
Пример #10
0
def get_rack(fabric_id=None, rack_id=None):

    rack_obj = Rack()

    try:
        if fabric_id:
            rack = rack_obj.get_rack(dcroom_id=fabric_id)
            rack_list = rack_serializers.RackSerializer(
                rack, many=True).data if rack else list()
        elif rack_id:
            rack = rack_obj.get_rack(idt=rack_id)
            rack_list = [rack_serializers.RackSerializer(rack).data
                         ] if rack else list()
        else:
            rack = rack_obj.get_rack()
            rack_list = rack_serializers.RackSerializer(
                rack, many=True).data if rack else list()

        return rack_list

    except (ObjectDoesNotExist, Exception), e:
        raise Exception(e)
    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:
                for i in range(1,3):
                    nome_lf = settings.LEAF+"-"+rack.nome+"-0"+str(i)+settings.FORMATO
                    nome_lf_b = settings.PATH_TO_CONFIG+nome_lf
                    nome_lf_a = settings.PATH_TO_MV+nome_lf
                    shutil.move(nome_lf_b, nome_lf_a)
                    nome_oob = settings.OOB+"-0"+str(i)+"-ADD-"+rack.nome+settings.FORMATO
                    nome_oob_b = settings.PATH_TO_CONFIG+nome_oob
                    nome_oob_a = settings.PATH_TO_MV+nome_oob
                    shutil.move(nome_oob_b, nome_oob_a)
                for i in range(1,5):
                    nome_spn = settings.SPN+"-0"+str(i)+"-ADD-"+rack.nome+settings.FORMATO
                    nome_spn_b = settings.PATH_TO_CONFIG+nome_spn
                    nome_spn_a = settings.PATH_TO_MV+nome_spn
                    shutil.move(nome_spn_b, nome_spn_a)

                nome_oob = settings.OOB+"-"+rack.nome+"-01"+settings.FORMATO
                nome_oob_b = settings.PATH_TO_CONFIG+nome_oob
                nome_oob_a = settings.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(user)
                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_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 handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to edit Rack.

        URL: rack/edit/
        """

        try:

            self.log.info("Edit Rack")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            rack_map = networkapi_map.get('rack')
            if rack_map is None:
                return self.response_error(3, u'There is no value to the rack tag  of XML request.')

            # Get XML data
            id_rack = rack_map.get('id_rack')
            number = rack_map.get('number')
            name = rack_map.get('name')
            mac_address_sw1 = rack_map.get('mac_address_sw1')
            mac_address_sw2 = rack_map.get('mac_address_sw2')
            mac_address_ilo = rack_map.get('mac_address_ilo')
            id_sw1 = rack_map.get('id_sw1')
            id_sw2 = rack_map.get('id_sw2')
            id_ilo = rack_map.get('id_ilo')

            racks = Rack()

            with distributedlock(LOCK_RACK % id_rack):
                racks.__dict__.update(id=id_rack, nome=name, numero=number, mac_sw1=mac_address_sw1, mac_sw2=mac_address_sw2, mac_ilo=mac_address_ilo)
                if not id_sw1==None:
                    id_sw1 = int(id_sw1)
                    racks.id_sw1 = Equipamento.get_by_pk(id_sw1)

                if not id_sw2==None:
                    id_sw2 = int(id_sw2)
                    racks.id_sw2 = Equipamento.get_by_pk(id_sw2)

                if not id_ilo==None:
                    id_ilo = int(id_ilo)
                    racks.id_ilo = Equipamento.get_by_pk(id_ilo)

                # save 
                racks.save()

                rack_map = dict()
                rack_map['rack'] = model_to_dict(racks)

            return self.response(dumps_networkapi(rack_map))

        except InvalidValueError, e:
            return self.response_error(369, e.param, e.value)
Пример #14
0
 def __init__(self, rack_id):
     self.rack = Rack().get_by_pk(rack_id)
     self.spine_prefix = "SPN"
     self.leaf_prefix = "LF-"
     self.oob_prefix = "OOB"
Пример #15
0
def gerar_arquivo_config(ids):
    log.debug("gerar_arquivo_config")

    for id in ids:
        rack = Rack().get_rack(idt=id)
        equips = list()
        lf1 = dict()
        lf2 = dict()
        oob = dict()

        # Equipamentos
        try:
            nome_rack = rack.nome.upper()
            lf1["sw"] = 1
            lf1["id"] = rack.id_sw1.id
            lf1["nome"] = rack.id_sw1.nome
            lf1["mac"] = rack.mac_sw1
            lf1["marca"] = rack.id_sw1.modelo.marca.nome
            lf1["modelo"] = rack.id_sw1.modelo.nome
            equips.append(lf1)
            lf2["sw"] = 2
            lf2["id"] = rack.id_sw2.id
            lf2["nome"] = rack.id_sw2.nome
            lf2["mac"] = rack.mac_sw2
            lf2["marca"] = rack.id_sw2.modelo.marca.nome
            lf2["modelo"] = rack.id_sw2.modelo.nome
            equips.append(lf2)
            oob["sw"] = 3
            oob["id"] = rack.id_ilo.id
            oob["nome"] = rack.id_ilo.nome
            oob["mac"] = rack.mac_ilo
            oob["marca"] = rack.id_ilo.modelo.marca.nome
            oob["modelo"] = rack.id_ilo.modelo.nome
            equips.append(oob)
            dcname = rack.dcroom.dc.dcname
        except:
            raise Exception(
                "Erro: Informações incompletas. Verifique o cadastro do Datacenter, do Fabric e do Rack"
            )

        dcsigla = "".join([c[0] for c in dcname.split(" ")
                           ]) if len(dcname.split(" ")) >= 2 else dcname[:3]
        prefixspn = "SPN"
        prefixlf = "LF-"
        prefixoob = "OOB"

        # Interface e Roteiro
        for equip in equips:
            try:
                interfaces = Interface.search(equip.get("id"))
                equip["interfaces"] = list()
                for interface in interfaces:
                    dic = dict()
                    try:
                        sw = interface.get_switch_and_router_interface_from_host_interface(
                            None)
                        if sw.equipamento.nome[:3] in [
                                prefixlf, prefixoob, prefixspn
                        ]:
                            dic["nome"] = sw.equipamento.nome
                            dic["id"] = sw.equipamento.id
                            dic["ip_mngt"] = _buscar_ip(sw.equipamento.id)
                            dic["interface"] = sw.interface
                            dic["eq_interface"] = interface.interface
                            dic["roteiro"] = _buscar_roteiro(
                                sw.equipamento.id, "CONFIGURACAO")
                            equip["interfaces"].append(dic)
                    except:
                        pass
            except:
                raise Exception(
                    "Erro ao buscar o roteiro de configuracao ou as interfaces associadas ao equipamento: "
                    "%s." % equip.get("nome"))
            try:
                equip["roteiro"] = _buscar_roteiro(equip.get("id"),
                                                   "CONFIGURACAO")
                equip["ip_mngt"] = _buscar_ip(equip.get("id"))
            except:
                raise Exception(
                    "Erro ao buscar os roteiros do equipamento: %s" %
                    equip.get("nome"))

        autoprovision.autoprovision_splf(rack, equips)
        autoprovision.autoprovision_coreoob(rack, equips)

    return True
Пример #16
0
class RackEnvironment:
    def __init__(self, user, rack_id):
        self.rack = Rack().get_by_pk(rack_id)
        self.user = user

    @staticmethod
    def save_environment(self, env):
        pass

    @staticmethod
    def save_vlan(self, vlan):
        pass

    def allocate(self):
        self.rack.__dict__.update(id=self.rack.id, create_vlan_amb=True)
        self.rack.save()

    def deallocate(self):
        self.rack.__dict__.update(id=self.rack.id, create_vlan_amb=False)
        self.rack.save()

    def spines_environment_save(self):
        log.debug("_create_spnlfenv")

        envfathers = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            father_environment__isnull=True,
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome="SPINES")
        log.debug("SPN environments" + str(envfathers))

        environment_spn_lf_list = list()
        spines = int(self.rack.dcroom.spines)
        fabric = self.rack.dcroom.name

        try:
            id_grupo_l3 = models_env.GrupoL3().get_by_name(fabric).id
        except:
            grupo_l3_dict = models_env.GrupoL3()
            grupo_l3_dict.nome = fabric
            grupo_l3_dict.save()
            id_grupo_l3 = grupo_l3_dict.id
            pass

        for env in envfathers:
            config_subnet = list()
            for net in env.configs:
                # verificar se o ambiente possui range associado.
                cidr = IPNetwork(net.network)
                prefix = int(net.subnet_mask)
                network = {
                    'cidr': list(cidr.subnet(prefix)),
                    'type': net.ip_version,
                    'network_type': net.id_network_type.id
                }
                config_subnet.append(network)
            for spn in range(spines):
                amb_log_name = "SPINE0" + str(spn + 1) + "LEAF"
                try:
                    id_amb_log = models_env.AmbienteLogico().get_by_name(
                        amb_log_name).id
                except:
                    amb_log_dict = models_env.AmbienteLogico()
                    amb_log_dict.nome = amb_log_name
                    amb_log_dict.save()
                    id_amb_log = amb_log_dict.id
                    pass
                config = list()
                for sub in config_subnet:
                    config_spn = {
                        'subnet':
                        str(sub.get("cidr")[spn]),
                        'new_prefix':
                        str(31)
                        if str(sub.get("type"))[-1] is "4" else str(127),
                        'type':
                        str(sub.get("type")),
                        'network_type':
                        sub.get("network_type")
                    }
                    config.append(config_spn)
                obj = {
                    'grupo_l3': id_grupo_l3,
                    'ambiente_logico': id_amb_log,
                    'divisao_dc': env.divisao_dc.id,
                    'acl_path': env.acl_path,
                    'ipv4_template': env.ipv4_template,
                    'ipv6_template': env.ipv6_template,
                    'link': env.link,
                    'min_num_vlan_2': env.min_num_vlan_2,
                    'max_num_vlan_2': env.max_num_vlan_2,
                    'min_num_vlan_1': env.min_num_vlan_1,
                    'max_num_vlan_1': env.max_num_vlan_1,
                    'vrf': env.vrf,
                    'father_environment': env.id,
                    'default_vrf': env.default_vrf.id,
                    'configs': config,
                    'fabric_id': self.rack.dcroom.id
                }

        return environment_spn_lf_list

    def spines_environment_read(self):
        pass

    def spine_leaf_vlans_save(self):
        log.debug("_create_spnlfvlans")

        spn_lf_envs = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome__in=[
                "SPINE01LEAF", "SPINE02LEAF", "SPINE03LEAF", "SPINE04LEAF"
            ])
        log.debug("SPN environments" + str(spn_lf_envs))

        tipo_rede = "Ponto a ponto"
        try:
            id_network_type = models_vlan.TipoRede().get_by_name(tipo_rede).id
        except:
            network_type = models_vlan.TipoRede()
            network_type.tipo_rede = tipo_rede
            network_type.save()
            id_network_type = network_type.id
            pass

        for env in spn_lf_envs:

            obj = {
                'name':
                "VLAN_" + env.divisao_dc.nome + "_" +
                env.ambiente_logico.nome + "_" + self.rack.nome,
                'environment':
                env.id,
                'default_vrf':
                env.default_vrf.id,
                'vrf':
                env.vrf,
                'create_networkv4':
                None,
                'create_networkv6':
                None,
                'description':
                "Vlan spinexleaf do rack " + self.rack.nome
            }
            vlan = facade_vlan_v3.create_vlan(obj, self.user)

            log.debug("Vlan allocated: " + str(vlan))

            for config in env.configs:
                log.debug("Configs: " + str(config))
                network = dict(prefix=config.subnet_mask,
                               cluster_unit=None,
                               vlan=vlan.id,
                               network_type=id_network_type,
                               environmentvip=None)
                log.debug("Network allocated: " + str(network))
                if str(config.ip_version)[-1] is "4":
                    facade_redev4_v3.create_networkipv4(network, self.user)
                elif str(config.ip_version)[-1] is "6":
                    facade_redev6_v3.create_networkipv6(network, self.user)

    def spine_leaf_vlans_read(self):
        pass

    def leaf_leaf_vlans_save(self):
        log.debug("_create_lflf_vlans")

        env_lf = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome="LEAF-LEAF")
        log.debug("Leaf-leaf environments: " + str(env_lf))

        tipo_rede = "Ponto a ponto"
        try:
            id_network_type = models_vlan.TipoRede().get_by_name(tipo_rede).id
        except:
            network_type = models_vlan.TipoRede()
            network_type.tipo_rede = tipo_rede
            network_type.save()
            id_network_type = network_type.id
            pass

        for env in env_lf:
            env_id = env.id
            vlan_number = int(env.min_num_vlan_1)
            vlan_name = "VLAN_LFxLF_" + env.divisao_dc.nome + "_" + env.grupo_l3.nome

            try:
                models_vlan.Vlan.objects.all().filter(
                    nome=vlan_name).uniqueResult()
            except:
                log.debug("debug lfxlf")
                for net in env.configs:
                    bloco = net.network
                    prefix = bloco.split('/')[-1]
                    network = {
                        'prefix': prefix,
                        'network_type': id_network_type
                    }
                    if str(net.ip_version)[-1] is "4":
                        create_networkv4 = network
                    elif str(net.ip_version)[-1] is "6":
                        create_networkv6 = network
                obj = {
                    'name':
                    vlan_name,
                    'num_vlan':
                    vlan_number,
                    'environment':
                    env_id,
                    'default_vrf':
                    env.default_vrf.id,
                    'vrf':
                    env.vrf,
                    'create_networkv4':
                    create_networkv4 if create_networkv4 else None,
                    'create_networkv6':
                    create_networkv6 if create_networkv6 else None
                }
                facade_vlan_v3.create_vlan(obj, self.user)

    def leaf_leaf_envs_save(self):
        log.debug("_create_lflf_envs")

        env_lf = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome="LEAF-LEAF")
        log.debug("Leaf-leaf environments: " + str(env_lf))

        try:
            id_l3 = models_env.GrupoL3().get_by_name(self.rack.nome).id
        except:
            l3_dict = models_env.GrupoL3()
            l3_dict.nome = self.rack.nome
            l3_dict.save()
            id_l3 = l3_dict.id
            pass

        for env in env_lf:
            config_subnet = []
            for net in env.configs:
                cidr = list(
                    IPNetwork(net.network).subnet(int(
                        net.subnet_mask)))[self.rack.numero]
                network = {
                    'network': str(cidr),
                    'ip_version': str(net.ip_version),
                    'network_type': int(net.id_network_type.id),
                    'subnet_mask': int(net.subnet_mask)
                }
                config_subnet.append(network)

            obj = {
                'grupo_l3': id_l3,
                'ambiente_logico': env.ambiente_logico.id,
                'divisao_dc': env.divisao_dc.id,
                'acl_path': env.acl_path,
                'ipv4_template': env.ipv4_template,
                'ipv6_template': env.ipv6_template,
                'link': env.link,
                'min_num_vlan_2': env.min_num_vlan_1,
                'max_num_vlan_2': env.max_num_vlan_1,
                'min_num_vlan_1': env.min_num_vlan_1,
                'max_num_vlan_1': env.max_num_vlan_1,
                'vrf': env.vrf,
                'father_environment': env.id,
                'default_vrf': env.default_vrf.id,
                'configs': config_subnet,
                'fabric_id': self.rack.dcroom.id
            }
            environment = facade_env.create_environment(obj)
            log.debug("Environment object: %s" % str(environment))

    def prod_environment_save(self):
        log.debug("_create_prod_envs")

        prod_envs = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome="PRODUCAO").exclude(
                divisao_dc__nome="BO_DMZ")

        log.debug("PROD environments: " + str(prod_envs))

        try:
            id_grupo_l3 = models_env.GrupoL3().get_by_name(self.rack.nome).id
        except:
            grupo_l3_dict = models_env.GrupoL3()
            grupo_l3_dict.nome = self.rack.nome
            grupo_l3_dict.save()
            id_grupo_l3 = grupo_l3_dict.id
            pass

        if self.rack.dcroom.config:
            fabricconfig = self.rack.dcroom.config
        else:
            log.debug("sem configuracoes do fabric %s" %
                      str(self.rack.dcroom.id))
            fabricconfig = list()

        try:
            fabricconfig = json.loads(fabricconfig)
        except:
            pass

        try:
            fabricconfig = ast.literal_eval(fabricconfig)
            log.debug("config -ast: %s" % str(fabricconfig))
        except:
            pass

        environment = list()
        for env in prod_envs:
            details = None
            for fab in fabricconfig.get("Ambiente"):
                if int(fab.get("id")) == env.id:
                    details = fab.get("details")

            config_subnet = list()
            for net in env.configs:

                if isinstance(details, list) and len(details) > 0:
                    if details[0].get(str(net.ip_version)):
                        new_prefix = details[0].get(str(
                            net.ip_version)).get("new_prefix")
                    else:
                        new_prefix = 27 if net.ip_version == "v4" else 64
                    network = {
                        'ip_version': net.ip_version,
                        'network_type': net.id_network_type.id,
                        'subnet_mask': new_prefix
                    }
                    config_subnet.append(network)

            obj = {
                'grupo_l3': id_grupo_l3,
                'ambiente_logico': env.ambiente_logico.id,
                'divisao_dc': env.divisao_dc.id,
                'acl_path': env.acl_path,
                'ipv4_template': env.ipv4_template,
                'ipv6_template': env.ipv6_template,
                'link': env.link,
                'min_num_vlan_2': env.min_num_vlan_1,
                'max_num_vlan_2': env.max_num_vlan_1,
                'min_num_vlan_1': env.min_num_vlan_1,
                'max_num_vlan_1': env.max_num_vlan_1,
                'vrf': env.vrf,
                'father_environment': env.id,
                'default_vrf': env.default_vrf.id,
                'configs': config_subnet,
                'fabric_id': self.rack.dcroom.id
            }
            obj_env = facade_env.create_environment(obj)
            environment.append(obj_env)
            log.debug("Environment Prod. object: %s" % str(obj_env))

            for switch in [self.rack.id_sw1, self.rack.id_sw2]:
                try:
                    equipamento_ambiente = EquipamentoAmbiente()
                    equipamento_ambiente.ambiente = obj_env
                    equipamento_ambiente.equipamento = switch
                    equipamento_ambiente.is_router = True
                    equipamento_ambiente.create(self.user)
                except EquipamentoAmbienteDuplicatedError:
                    pass

        return environment

    def children_prod_environment_save(self):
        log.debug("_create_prod_children")

        try:
            env = models_env.Ambiente.objects.filter(
                dcroom=int(self.rack.dcroom.id),
                divisao_dc__nome="BE",
                grupo_l3__nome=str(self.rack.nome),
                ambiente_logico__nome="PRODUCAO").uniqueResult()
            log.debug("BE environments: %s" % env)
        except Exception as e:
            raise Exception("Erro: %s" % e)

        if self.rack.dcroom.config:
            fabricconfig = self.rack.dcroom.config
        else:
            log.debug("No fabric configurations %s" % str(self.rack.dcroom.id))
            fabricconfig = list()

        try:
            fabricconfig = json.loads(fabricconfig)
            fabricconfig = ast.literal_eval(fabricconfig)
            log.debug("config -ast: %s" % str(fabricconfig))
        except:
            log.debug("Error loading fabric json.")

        environment = None
        father_id = env.id
        fabenv = None

        for fab in fabricconfig.get("Ambiente"):
            if int(fab.get("id")) == int(env.father_environment.id):
                fabenv = fab.get("details")

        if not fabenv:
            log.debug("No configurations for child environment of env id=%s" %
                      (str(env.id)))
            return False

        fabenv.sort(key=operator.itemgetter('min_num_vlan_1'))
        log.debug("Order by min_num_vlan: %s" % str(fabenv))

        for amb in fabenv:
            log.debug("amb: %s" % amb)
            try:
                id_div = models_env.DivisaoDc().get_by_name(amb.get("name")).id
            except:
                div_dict = models_env.DivisaoDc()
                div_dict.nome = amb.get("name")
                div_dict.save()
                id_div = div_dict.id
                pass

            config_subnet = list()
            for net_dict in amb.get("config"):
                network = {
                    'ip_version': net_dict.get("type"),
                    'network_type': int(net_dict.get("network_type")),
                    'subnet_mask': int(net_dict.get("new_prefix")),
                    'network_mask': int(net_dict.get("mask"))
                }
                config_subnet.append(network)
            log.debug("config: %s" % config_subnet)
            obj = {
                'grupo_l3': env.grupo_l3.id,
                'ambiente_logico': env.ambiente_logico.id,
                'divisao_dc': id_div,
                'acl_path': env.acl_path,
                'ipv4_template': env.ipv4_template,
                'ipv6_template': env.ipv6_template,
                'link': env.link,
                'min_num_vlan_2': amb.get("min_num_vlan_1"),
                'max_num_vlan_2': amb.get("max_num_vlan_1"),
                'min_num_vlan_1': amb.get("min_num_vlan_1"),
                'max_num_vlan_1': amb.get("max_num_vlan_1"),
                'vrf': env.vrf,
                'father_environment': father_id,
                'default_vrf': env.default_vrf.id,
                'configs': config_subnet,
                'fabric_id': self.rack.dcroom.id
            }
            environment = facade_env.create_environment(obj)
            log.debug("Environment object: %s" % str(environment))

            for switch in [self.rack.id_sw1, self.rack.id_sw2]:
                try:
                    equipamento_ambiente = EquipamentoAmbiente()
                    equipamento_ambiente.ambiente = environment
                    equipamento_ambiente.equipamento = switch
                    equipamento_ambiente.is_router = True
                    equipamento_ambiente.create(self.user)
                except EquipamentoAmbienteDuplicatedError:
                    pass
                except Exception as e:
                    log.debug("error %s" % e)

        return environment

    def manage_vlan_save(self):
        log.debug("_create_oobvlans")

        env_oob = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            divisao_dc__nome="OOB",
            grupo_l3__nome=str(self.rack.dcroom.name),
            ambiente_logico__nome="GERENCIA").uniqueResult()
        log.debug("OOB environments: " + str(env_oob))

        for env in [env_oob]:

            obj = {
                'name':
                "VLAN_" + env.ambiente_logico.nome + "_" + self.rack.nome,
                'environment': env.id,
                'default_vrf': env.default_vrf.id,
                'vrf': env.vrf,
                'create_networkv4': None,
                'create_networkv6': None,
                'description': "Vlan de gerência do rack " + self.rack.nome
            }
            vlan = facade_vlan_v3.create_vlan(obj, self.user)

            log.debug("Vlan allocated: " + str(vlan))

            network = dict()
            for config in env.configs:
                log.debug("Configs: " + str(config))
                network = dict(prefix=config.subnet_mask,
                               cluster_unit=None,
                               vlan=vlan.id,
                               network_type=config.id_network_type.id,
                               environmentvip=None)
                log.debug("Network allocated: " + str(network))
            facade_redev4_v3.create_networkipv4(network, self.user)

        return vlan

    def rack_environment_remove(self):
        log.info("_remove_envs")

        envs = models_env.Ambiente.objects.filter(
            dcroom=int(self.rack.dcroom.id),
            grupo_l3__nome=str(self.rack.nome))

        for env in envs:
            env.delete_v3()

        log.debug("PROD environments: %s. Total: %s" % (str(envs), len(envs)))

    def rack_vlans_remove(self):
        log.info("remove_vlans")

        vlans = models_vlan.Vlan.objects.filter(nome__icontains="_" +
                                                self.rack.nome)

        for vlan in vlans:
            vlan.delete_v3()

        log.debug("Vlans: %s. total: %s" % (vlans, len(vlans)))
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: rack/insert/
        """

        try:

            self.log.info("Add Rack")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            rack_map = networkapi_map.get('rack')
            if rack_map is None:
                return self.response_error(3, u'There is no value to the rack tag  of XML request.')

            # Get XML data
            number = rack_map.get('number')
            name = rack_map.get('name')
            mac_address_sw1 = rack_map.get('mac_address_sw1')
            mac_address_sw2 = rack_map.get('mac_address_sw2')
            mac_address_ilo = rack_map.get('mac_address_ilo')
            id_sw1 = rack_map.get('id_sw1')
            id_sw2 = rack_map.get('id_sw2')
            id_ilo = rack_map.get('id_ilo')

            rack = Rack()

            # set variables
            rack.numero = number
            rack.nome = name
            rack.mac_sw1 = mac_address_sw1
            rack.mac_sw2 = mac_address_sw2
            rack.mac_ilo = mac_address_ilo
            if not id_sw1==None:
                id_sw1 = int(id_sw1)
                rack.id_sw1 = Equipamento(id=id_sw1)
            else:
                rack.id_sw1 = id_sw1
            if not id_sw2==None:
                id_sw2 = int(id_sw2)
                rack.id_sw2 = Equipamento(id=id_sw2)
            else:
                rack.id_sw2 = id_sw2
            if not id_ilo==None:
                id_ilo = int(id_ilo)
                rack.id_ilo = Equipamento(id=id_ilo)
            else:
                rack.id_ilo = id_ilo

            # save 
            rack.insert_new(user)
            
            rack_map = dict()
            rack_map['rack'] = model_to_dict(
                rack, exclude=["numero", "nome","mac_sw1", "mac_sw2","mac_ilo", "id_sw1", "id_sw2", "id_ilo"])

            return self.response(dumps_networkapi(rack_map))

        except InvalidValueError, e:
            return self.response_error(369, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to edit Rack.

        URL: rack/edit/
        """

        try:

            self.log.info("Edit Rack")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'There is no value to the networkapi tag  of XML request.'
                )

            rack_map = networkapi_map.get('rack')
            if rack_map is None:
                return self.response_error(
                    3, u'There is no value to the rack tag  of XML request.')

            # Get XML data
            id_rack = rack_map.get('id_rack')
            number = rack_map.get('number')
            name = rack_map.get('name')
            mac_address_sw1 = rack_map.get('mac_address_sw1')
            mac_address_sw2 = rack_map.get('mac_address_sw2')
            mac_address_ilo = rack_map.get('mac_address_ilo')
            id_sw1 = rack_map.get('id_sw1')
            id_sw2 = rack_map.get('id_sw2')
            id_ilo = rack_map.get('id_ilo')

            racks = Rack()

            with distributedlock(LOCK_RACK % id_rack):
                racks.__dict__.update(id=id_rack,
                                      nome=name,
                                      numero=number,
                                      mac_sw1=mac_address_sw1,
                                      mac_sw2=mac_address_sw2,
                                      mac_ilo=mac_address_ilo)
                if not id_sw1 == None:
                    id_sw1 = int(id_sw1)
                    racks.id_sw1 = Equipamento.get_by_pk(id_sw1)

                if not id_sw2 == None:
                    id_sw2 = int(id_sw2)
                    racks.id_sw2 = Equipamento.get_by_pk(id_sw2)

                if not id_ilo == None:
                    id_ilo = int(id_ilo)
                    racks.id_ilo = Equipamento.get_by_pk(id_ilo)

                # save
                racks.save()

                rack_map = dict()
                rack_map['rack'] = model_to_dict(racks)

            return self.response(dumps_networkapi(rack_map))

        except InvalidValueError, e:
            return self.response_error(369, e.param, e.value)
Пример #19
0
    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)
Пример #20
0
 def __init__(self, user, rack_id):
     self.rack = Rack().get_by_pk(rack_id)
     self.user = user
     self.dcroom_config = self._get_config_file()
     self.rack_asn = self._get_rack_asn()
Пример #21
0
def save_rack_dc(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('mac_sw1')
    rack.mac_sw2 = rack_dict.get('mac_sw2')
    rack.mac_ilo = rack_dict.get('mac_ilo')
    rack.id_sw1 = Equipamento().get_by_pk(rack_dict.get('id_sw1'))
    rack.id_sw2 = Equipamento().get_by_pk(rack_dict.get('id_sw2'))
    rack.id_sw3 = Equipamento().get_by_pk(rack_dict.get('id_ilo'))
    rack.dcroom = DatacenterRooms().get_dcrooms(
        idt=rack_dict.get('fabric_id')) if rack_dict.get('fabric_id') else None

    if not rack.nome:
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")

    rack.save_rack()
    return rack
Пример #22
0
def update_rack(rack_id, rack):

    try:
        rack_obj = Rack()
        rack_obj = rack_obj.get_rack(idt=rack_id)

        rack_obj.nome = rack.get("name")
        rack_obj.numero = rack.get("number")
        rack_obj.mac_sw1 = rack.get("mac_sw1")
        rack_obj.mac_sw2 = rack.get("mac_sw2")
        rack_obj.mac_ilo = rack.get("mac_ilo")
        rack_obj.id_sw1 = Equipamento().get_by_pk(int(rack.get("id_sw1")))
        rack_obj.id_sw2 = Equipamento().get_by_pk(int(rack.get("id_sw2")))
        rack_obj.id_ilo = Equipamento().get_by_pk(int(rack.get("id_ilo")))
        rack_obj.dcroom = DatacenterRooms().get_dcrooms(idt=rack.get('fabric_id')) if rack.get('fabric_id') \
            else None

        rack_obj.save()

        return rack_obj

    except (exceptions.RackNumberDuplicatedValueError,
            exceptions.RackNameDuplicatedError,
            exceptions.InvalidInputException) as e:
        log.exception(e)
        raise Exception(e)
    except Exception, e:
        log.exception(e)
        raise Exception(e)
Пример #23
0
def save_rack_dc(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('mac_sw1')
    rack.mac_sw2 = rack_dict.get('mac_sw2')
    rack.mac_ilo = rack_dict.get('mac_ilo')
    rack.id_sw1 = Equipamento().get_by_pk(rack_dict.get('id_sw1'))
    rack.id_sw2 = Equipamento().get_by_pk(rack_dict.get('id_sw2'))
    rack.id_sw3 = Equipamento().get_by_pk(rack_dict.get('id_ilo'))
    rack.dcroom = DatacenterRooms().get_dcrooms(idt=rack_dict.get('fabric_id')) if rack_dict.get('fabric_id') else None

    if not rack.nome:
        raise exceptions.InvalidInputException("O nome do Rack não foi informado.")

    rack.save_rack()
    return rack
Пример #24
0
def save_rack(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack.nome:
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")
    if Rack.objects.filter(nome__iexact=rack.nome):
        raise exceptions.RackNameDuplicatedError()
    if Rack.objects.filter(numero__iexact=rack.numero):
        raise exceptions.RackNumberDuplicatedValueError()

    if not id_sw1:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." %
                                               id_sw1)
    if not id_sw2:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." %
                                               id_sw2)
    if not id_sw3:
        raise exceptions.InvalidInputException("O OOB de id %s não existe." %
                                               id_sw3)

    rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
    rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
    rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))

    rack.save()
    return rack
Пример #25
0
def save_rack(rack_dict):

    rack = Rack()

    rack.nome = rack_dict.get('name')
    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack.nome:
        raise exceptions.InvalidInputException("O nome do Rack não foi informado.")
    if Rack.objects.filter(nome__iexact=rack.nome):
        raise exceptions.RackNameDuplicatedError()
    if Rack.objects.filter(numero__iexact=rack.numero):
        raise exceptions.RackNumberDuplicatedValueError()

    if not id_sw1:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw1)
    if not id_sw2:
        raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw2)
    if not id_sw3:
        raise exceptions.InvalidInputException("O OOB de id %s não existe." % id_sw3)

    rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
    rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
    rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))

    rack.save()
    return rack
Пример #26
0
 def __init__(self, user, rack_id):
     self.rack = Rack().get_by_pk(rack_id)
     self.user = user
Пример #27
0
def update_rack(rack_id, rack):

    try:
        rack_obj = Rack()
        rack_obj = rack_obj.get_rack(idt=rack_id)

        rack_obj.nome = rack.get("name")
        rack_obj.numero = rack.get("number")
        rack_obj.mac_sw1 = rack.get("mac_sw1")
        rack_obj.mac_sw2 = rack.get("mac_sw2")
        rack_obj.mac_ilo = rack.get("mac_ilo")
        rack_obj.id_sw1 = Equipamento().get_by_pk(int(rack.get("id_sw1")))
        rack_obj.id_sw2 = Equipamento().get_by_pk(int(rack.get("id_sw2")))
        rack_obj.id_ilo = Equipamento().get_by_pk(int(rack.get("id_ilo")))
        rack_obj.dcroom = DatacenterRooms().get_dcrooms(idt=rack.get('fabric_id')) if rack.get('fabric_id') \
            else None

        rack_obj.save()

        return rack_obj

    except (exceptions.RackNumberDuplicatedValueError,
            exceptions.RackNameDuplicatedError,
            exceptions.InvalidInputException) as e:
        log.exception(e)
        raise Exception(e)
    except Exception, e:
        log.exception(e)
        raise Exception(e)
    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.')
Пример #29
0
def save_rack(user, rack_dict):

    rack = Rack()

    rack.numero = rack_dict.get('number')
    rack.mac_sw1 = rack_dict.get('sw1_mac')
    rack.mac_sw2 = rack_dict.get('sw2_mac')
    rack.mac_ilo = rack_dict.get('sw3_mac')
    id_sw1 = rack_dict.get('sw1_id')
    id_sw2 = rack_dict.get('sw2_id')
    id_sw3 = rack_dict.get('sw3_id')

    if not rack_dict.get('name'):
        raise exceptions.InvalidInputException(
            "O nome do Rack não foi informado.")
    elif rack_dict.get('name') is not 0:
        rack.nome = rack_dict.get('name')
    try:
        Rack.objects.get(numero__iexact=rack.numero)
        raise exceptions.RackNumberDuplicatedValueError()
    except ObjectDoesNotExist:
        pass
    try:
        Rack.objects.get(nome__iexact=rack.nome)
        raise exceptions.RackNameDuplicatedError()
    except ObjectDoesNotExist:
        pass

    if id_sw1 is not None:
        try:
            rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
        except:
            raise exceptions.InvalidInputException(
                "O Leaf de id %s não existe." % id_sw1)
    if id_sw2 is not None:
        try:
            rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
        except:
            raise exceptions.InvalidInputException(
                "O Leaf de id %s não existe." % id_sw2)
    if id_sw3 is not None:
        try:
            rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))
        except:
            raise exceptions.InvalidInputException(
                "O OOB de id %s não existe." % id_sw3)

    rack.save(user)
    return 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 handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to create the configuration file.

        URL: rack/aplicar-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()
            ambientes['DC']=settings.DIVISAODC_MGMT
            ambientes['LOG']=settings.AMBLOG_MGMT
            ambientes['L3']=settings.GRPL3_MGMT
    
            try:
                #criar e ativar a vlan
                vlan = criar_vlan(user, variablestochangecore1, ambientes)
            except:
                raise RackAplError(None, rack.nome, "Erro ao criar a VLAN_SO.")
            try:
                #criar e ativar a rede
                network = criar_rede(user, "Ponto a ponto", 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
            environment_list = ambiente_spn_lf(user, rack, environment_list)

            #BE - PRODUCAO
            environment_list = ambiente_prod(user, rack, environment_list)

            #BE - Hosts - CLOUD
            environment_list = ambiente_cloud(user, rack, environment_list)
            
            #FE 
            environment_list = ambiente_prod_fe(user, rack, environment_list)

            #Borda
            environment_list = ambiente_borda(user, rack, environment_list)

            #######################################################################                   Backuper

            aplicar(rack)
            environment_rack(user, environment_list, rack)

            rack.__dict__.update(id=rack.id, create_vlan_amb=True)
            rack.save(user)

            success_map = dict()
            success_map['rack_conf'] = True
            map = dict()
            map['sucesso'] = success_map

            return self.response(dumps_networkapi(map))

        except RackConfigError, e:
            return self.response_error(382, e.param, e.value)