Пример #1
0
def environment_rack(user, environment_list, rack):

    # Insert all environments in environment rack table
    # Insert rack switches in rack environments
    for env in environment_list:
        try:
            ambienteRack = EnvironmentRack()
            ambienteRack.ambiente = env
            ambienteRack.rack = rack
            ambienteRack.create(user)
        except EnvironmentRackDuplicatedError:
            pass

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

    #Insert all environments in environment rack table
    #Insert rack switches in rack environments
    for env in environment_list:
        try:
            ambienteRack = EnvironmentRack()
            ambienteRack.ambiente = env
            ambienteRack.rack = rack
            ambienteRack.create(user)
        except EnvironmentRackDuplicatedError:
            pass

        for switch in [rack.id_sw1, rack.id_sw2]:
            try:
                equipamento_ambiente = EquipamentoAmbiente()
                equipamento_ambiente.ambiente = env
                equipamento_ambiente.equipamento = switch
                equipamento_ambiente.is_router = True
                equipamento_ambiente.create(user)
            except EquipamentoAmbienteDuplicatedError:
                pass
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IP to an equipment.

        URL: ipv4/assoc/
        '''

        self.log.info('Associate Ip to an Equipment')

        try:
            # 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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv4_id = ip_map.get('id_net')

            # Valid ip_id
            if not is_valid_int_greater_zero_param(ip_id):
                self.log.error(
                    u'Parameter ip_id is invalid. Value: %s.', ip_id)
                raise InvalidValueError(None, 'ip_id', ip_id)

            # Valid equip_id
            if not is_valid_int_greater_zero_param(equip_id):
                self.log.error(
                    u'Parameter equip_id is invalid. Value: %s.', equip_id)
                raise InvalidValueError(None, 'equip_id', equip_id)

            # Valid network_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.', network_ipv4_id)
                raise InvalidValueError(
                    None, 'network_ipv4_id', network_ipv4_id)

            # User permission
            if not has_perm(user,
                            AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            equip_id,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # Get net
            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # Get ip
                ip = Ip.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                #Equipment type should be in both filters
                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                                    #Out of band network is never trunked, it is only in mgmt interface
                                    # allow it - not a good thing to to, but is very specific
                                    if vlan.ambiente.divisao_dc.nome == 'OOB-CM' or vlan_atual.ambiente.divisao_dc.nome == 'OOB-CM':
                                        flag_vlan_error = False
                                        

                            ## Filter case 3 - end ##

                            if flag_vlan_error:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome, vlan.ambiente.ambiente_logico.nome, vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(None,
                                                                  '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente 
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' % (equip.nome, nome_ambiente, ambiente_aux.id, vlan_aux.id, vlan_atual.num_vlan))

                # Persist
                try:

                    try:
                        ipEquip = IpEquipamento()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        # Ip %s.%s.%s.%s already has association with
                        # Equipament %s.' % (self.oct1, self.oct2, self.oct3,
                        # self.oct4,equipment_id)
                        raise IpEquipmentAlreadyAssociation(None, u'Ip %s.%s.%s.%s already has association with Equipament %s.' % (
                            ip.oct1, ip.oct2, ip.oct3, ip.oct4, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = IpEquipamento()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all IpEquipamento related to this equipment
                    ip_equips = IpEquipamento.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv4.oct1 == ip.networkipv4.oct1 and \
                                ip_test.networkipv4.oct2 == ip.networkipv4.oct2 and \
                                ip_test.networkipv4.oct3 == ip.networkipv4.oct3 and \
                                ip_test.networkipv4.oct4 == ip.networkipv4.oct4 and \
                                ip_test.networkipv4.block == ip.networkipv4.block and \
                                ip_test.networkipv4 != ip.networkipv4:

                            # Filter testing
                            if ip_test.networkipv4.vlan.ambiente.filter is None or ip.networkipv4.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None, u'Equipment is already associated with another ip with the same ip range.')
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=ip.networkipv4.vlan.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=ip_test.networkipv4.vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None, u'Equipment is already associated with another ip with the same ip range.')

                    ## Filter case 2 - end ##

                    ip_equipment.save()

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                        # Delete vlan's cache
                        destroy_cache_function([net.vlan_id])
                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
Пример #4
0
def _create_prod_vlans(rack, user):
    log.debug("_create_prod_vlans")

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

    if rack.dcroom.config:
        fabricconfig = rack.dcroom.config
    else:
        log.debug("No frabric configurations %s" % str(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 = 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 0

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

    for idx, amb in enumerate(fabenv):
        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 = []
        for net in env.configs:
            for net_dict in amb.get("config"):

                if net_dict.get("type") == net.ip_version:
                    cidr = IPNetwork(net.network)

                    initial_prefix = 20 if net.ip_version == "v4" else 56
                    prefixo = net_dict.get("mask")
                    if not idx:
                        bloco = list(cidr.subnet(int(prefixo)))[0]
                        log.debug(str(bloco))
                    else:
                        bloco1 = list(cidr.subnet(initial_prefix))[1]
                        bloco = list(bloco1.subnet(int(prefixo)))[idx - 1]
                        log.debug(str(bloco))
                    network = {
                        'network': str(bloco),
                        'ip_version': str(net.ip_version),
                        'network_type': int(net.id_network_type.id),
                        'subnet_mask': int(net_dict.get("new_prefix"))
                    }
                    config_subnet.append(network)

        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': rack.dcroom.id
        }
        environment = facade_env.create_environment(obj)
        log.debug("Environment object: %s" % str(environment))

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

    return environment
Пример #5
0
def _create_prod_envs(rack, user):
    log.debug("_create_prod_envs")

    prod_envs = models_env.Ambiente.objects.filter(
        dcroom=int(rack.dcroom.id),
        grupo_l3__nome=str(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(rack.nome).id
    except:
        grupo_l3_dict = models_env.GrupoL3()
        grupo_l3_dict.nome = rack.nome
        grupo_l3_dict.save()
        id_grupo_l3 = grupo_l3_dict.id
        pass

    if rack.dcroom.config:
        fabricconfig = rack.dcroom.config
    else:
        log.debug("sem configuracoes do fabric %s" % str(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 = []
    for env in prod_envs:

        father_id = env.id

        details = None
        for fab in fabricconfig.get("Ambiente"):
            if int(fab.get("id")) == int(father_id):
                details = fab.get("details")

        config_subnet = []
        for net in env.configs:
            cidr = IPNetwork(str(net.network))
            prefix = int(net.subnet_mask)
            subnet_list = list(cidr.subnet(int(prefix)))
            try:
                bloco = subnet_list[int(rack.numero)]
            except IndexError:
                msg = "Rack number %d is greater than the maximum number of " \
                      "subnets available with prefix %d from %s subnet" % \
                      (rack.numero, prefix, cidr)
                raise Exception(msg)

            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 = 31 if net.ip_version == "v4" else 127
                network = {
                    'network': str(bloco),
                    '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': father_id,
            'default_vrf': env.default_vrf.id,
            'configs': config_subnet,
            'fabric_id': rack.dcroom.id
        }
        obj_env = facade_env.create_environment(obj)
        environment.append(obj_env)
        log.debug("Environment object: %s" % str(obj_env))

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

    return environment
Пример #6
0
def _create_prod_envs(rack, user):
    log.debug("_create_prod_envs")

    prod_envs = models_env.Ambiente.objects.filter(
        dcroom=int(rack.dcroom.id),
        father_environment__isnull=True,
        grupo_l3__nome=str(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(rack.nome).id
    except:
        grupo_l3_dict = models_env.GrupoL3()
        grupo_l3_dict.nome = rack.nome
        grupo_l3_dict.save()
        id_grupo_l3 = grupo_l3_dict.id
        pass

    if rack.dcroom.config:
        fabricconfig = rack.dcroom.config
    else:
        log.debug("sem configuracoes do fabric %s" % str(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:

        father_id = env.id

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

        config_subnet = list()
        for net in env.configs:
            cidr = IPNetwork(str(net.ip_config.subnet))
            prefix = int(net.ip_config.new_prefix)
            bloco = list(cidr.subnet(int(prefix)))[int(rack.numero)]
            if details[0].get(str(net.ip_config.type)):
                new_prefix = details[0].get(str(
                    net.ip_config.type)).get("new_prefix")
            else:
                new_prefix = 31 if net.ip_config.type == "v4" else 127
            network = {
                'subnet': str(bloco),
                'type': net.ip_config.type,
                'network_type': net.ip_config.network_type.id,
                'new_prefix': 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': father_id,
            'default_vrf': env.default_vrf.id,
            'configs': config_subnet,
            'fabric_id': rack.dcroom.id
        }
        obj_env = facade_env.create_environment(obj)
        environment.append(obj_env)
        log.debug("Environment object: %s" % str(obj_env))

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

    return environment
Пример #7
0
def _create_spnlfenv(user, rack):
    log.debug("_create_spnlfenv")

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

    environment_spn_lf = None
    environment_spn_lf_list = list()
    spines = int(rack.dcroom.spines)
    fabric = 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.ip_config.subnet)
            prefix = int(net.ip_config.new_prefix)
            network = {
                'cidr': list(cidr.subnet(prefix)),
                'type': net.ip_config.type,
                'network_type': net.ip_config.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': rack.dcroom.id
            }
            try:
                environment_spn_lf = facade_env.create_environment(obj)
                environment_spn_lf_list.append(environment_spn_lf)
                for switch in [rack.id_sw1, rack.id_sw2]:
                    try:
                        equipamento_ambiente = EquipamentoAmbiente()
                        equipamento_ambiente.ambiente = environment_spn_lf
                        equipamento_ambiente.equipamento = switch
                        equipamento_ambiente.is_router = True
                        equipamento_ambiente.create(user)
                    except EquipamentoAmbienteDuplicatedError:
                        pass
            except:
                log.debug("Environment object: %s" % str(environment_spn_lf))

    return environment_spn_lf_list
Пример #8
0
    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
Пример #9
0
    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
Пример #10
0
def _create_prod_vlans(rack, user):
    log.debug("_create_prod_vlans")

    env = models_env.Ambiente.objects.filter(dcroom=int(rack.dcroom.id),
                                             divisao_dc__nome="BE",
                                             grupo_l3__nome=str(rack.nome),
                                             ambiente_logico__nome="PRODUCAO"
                                             ).uniqueResult()

    log.debug("BE environments: "+str(env))

    if rack.dcroom.config:
        fabricconfig = rack.dcroom.config
    else:
        log.debug("No frabric configurations %s" % str(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 = 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 0

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

    for idx, amb in enumerate(fabenv):
        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 = []
        for net in env.configs:
            for net_dict in amb.get("config"):

                if net_dict.get("type") == net.ip_config.type:
                    cidr = IPNetwork(net.ip_config.subnet)

                    initial_prefix  = 20 if net.ip_config.type=="v4" else 56
                    prefixo = net_dict.get("mask")
                    if not idx:
                        bloco = list(cidr.subnet(int(prefixo)))[0]
                        log.debug(str(bloco))
                    else:
                        bloco1 = list(cidr.subnet(initial_prefix))[1]
                        bloco = list(bloco1.subnet(int(prefixo)))[idx-1]
                        log.debug(str(bloco))
                    network = {
                        'subnet': str(bloco),
                        'type': str(net.ip_config.type),
                        'network_type': int(net.ip_config.network_type.id),
                        'new_prefix': int(net_dict.get("new_prefix"))
                    }
                    config_subnet.append(network)

        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': rack.dcroom.id
        }
        environment = facade_env.create_environment(obj)
        log.debug("Environment object: %s" % str(environment))

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

    return environment
Пример #11
0
def _create_prod_envs(rack, user):
    log.debug("_create_prod_envs")

    prod_envs = models_env.Ambiente.objects.filter(dcroom=int(rack.dcroom.id),
                                                   father_environment__isnull=True,
                                                   grupo_l3__nome=str(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(rack.nome).id
    except:
        grupo_l3_dict = models_env.GrupoL3()
        grupo_l3_dict.nome = rack.nome
        grupo_l3_dict.save()
        id_grupo_l3 = grupo_l3_dict.id
        pass

    if rack.dcroom.config:
        fabricconfig = rack.dcroom.config
    else:
        log.debug("sem configuracoes do fabric %s" % str(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 = []
    for env in prod_envs:

        father_id = env.id

        details = None
        for fab in fabricconfig.get("Ambiente"):
            if int(fab.get("id"))==int(father_id):
                details = fab.get("details")

        config_subnet = []
        for net in env.configs:
            cidr = IPNetwork(str(net.ip_config.subnet))
            prefix = int(net.ip_config.new_prefix)
            subnet_list = list(cidr.subnet(int(prefix)))

            try:
                bloco = subnet_list[int(rack.numero)]
            except IndexError as err:
                msg = "Rack number %d is greater than the maximum number of " \
                      "subnets available with prefix %d from %s subnet" % (
                    rack.numero, prefix, cidr
                )
                raise Exception(msg)

            if isinstance(details, list) and len(details) > 0:

                if details[0].get(str(net.ip_config.type)):
                    new_prefix = details[0].get(str(net.ip_config.type)).get("new_prefix")
                else:
                    new_prefix = 31 if net.ip_config.type=="v4" else 127
                network = {
                    'subnet': str(bloco),
                    'type': net.ip_config.type,
                    'network_type': net.ip_config.network_type.id,
                    'new_prefix': 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': father_id,
            'default_vrf': env.default_vrf.id,
            'configs': config_subnet,
            'fabric_id': rack.dcroom.id
        }
        obj_env = facade_env.create_environment(obj)
        environment.append(obj_env)
        log.debug("Environment object: %s" % str(obj_env))

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

    return environment