def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Environments.

        URL: /ambiente/equip/id_equip
        """

        try:

            # Commons Validations

            # User permission

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            equip = Equipamento.get_by_pk(id_equip)
            environments_list = EquipamentoAmbiente.get_by_equipment(equip.id)

            # Get all environments in DB
            lists_aux = []
            for environment in environments_list:
                env = Ambiente.get_by_pk(environment.ambiente.id)
                env_map = model_to_dict(env)
                env_map['grupo_l3_name'] = env.grupo_l3.nome
                env_map['ambiente_logico_name'] = env.ambiente_logico.nome
                env_map['divisao_dc_name'] = env.divisao_dc.nome
                env_map['is_router'] = environment.is_router

                try:
                    env_map['range'] = str(
                        env.min_num_vlan_1) + ' - ' + str(env.max_num_vlan_1)
                    if env.min_num_vlan_1 != env.min_num_vlan_2:
                        env_map['range'] = env_map[
                            'range'] + '; ' + str(env.min_num_vlan_2) + ' - ' + str(env.max_num_vlan_2)
                except:
                    env_map['range'] = 'Nao definido'

                if env.filter is not None:
                    env_map['filter_name'] = env.filter.name

                lists_aux.append(env_map)
            # Return XML
            environment_list = dict()
            environment_list['ambiente'] = lists_aux
            return self.response(dumps_networkapi(environment_list))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
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
Esempio n. 3
0
        # Remove every vlan associated with this environment
        for vlan in environment.vlan_set.all():
            try:
                if vlan.ativada:
                    vlan.remove(authenticated_user)
                vlan.delete()
            except VlanCantDeallocate, e:
                raise AmbienteUsedByEquipmentVlanError(e.cause, e.message)
            except IpCantBeRemovedFromVip, e:
                raise AmbienteUsedByEquipmentVlanError(e.cause, e.message)

        # Remove every association between equipment and this environment
        for equip_env in environment.equipamentoambiente_set.all():
            try:
                EquipamentoAmbiente.remove(
                    authenticated_user, equip_env.equipamento_id, equip_env.ambiente_id)
            except EquipamentoAmbienteNotFoundError, e:
                raise AmbienteUsedByEquipmentVlanError(e, e.message)
            except EquipamentoError, e:
                raise AmbienteUsedByEquipmentVlanError(e, e.message)

        # Dissociate or remove healthcheck expects
        try:
            HealthcheckExpect.dissociate_environment_and_delete(
                authenticated_user, pk)
        except HealthcheckExpectError, e:
            cls.log.error(u'Falha ao desassociar algum HealthCheckExpect.')
            raise AmbienteError(
                e, u'Falha ao desassociar algum HealthCheckExpect.')

        # Remove ConfigEnvironments associated with environment
    def network_ipv4_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

        try:

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

            # Network Type

            # Valid network_type ID
            """
            if not is_valid_int_greater_zero_param(network_type):
                self.log.error(
                    u'Parameter id_tipo_rede is invalid. Value: %s.', network_type)
                raise InvalidValueError(None, 'id_tipo_rede', network_type)
            """
            # Find network_type by ID to check if it exist
            net = None
            if network_type:
                net = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

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

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv4
            network_ipv4 = NetworkIPv4()
            vlan_map = network_ipv4.add_network_ipv4(user, vlan_id, net, evip, prefix)

            list_equip_routers_ambient = EquipamentoAmbiente.get_routers_by_environment(vlan_map['vlan']['id_ambiente'])

            if list_equip_routers_ambient:

                # Add Adds the first available ipv4 on all equipment
                # that is configured as a router for the environment related to
                # network
                ip = Ip.get_first_available_ip(vlan_map['vlan']['id_network'])

                ip = str(ip).split('.')

                ip_model = Ip()
                ip_model.oct1 = ip[0]
                ip_model.oct2 = ip[1]
                ip_model.oct3 = ip[2]
                ip_model.oct4 = ip[3]
                ip_model.networkipv4_id = network_ipv4.id

                ip_model.save()

                if len(list_equip_routers_ambient) > 1:
                    multiple_ips = True
                else:
                    multiple_ips = False

                for equip in list_equip_routers_ambient:
                    IpEquipamento().create(user, ip_model.id, equip.equipamento.id)

                    if multiple_ips:
                        router_ip = Ip.get_first_available_ip(vlan_map['vlan']['id_network'], True)
                        router_ip = str(router_ip).split('.')
                        ip_model2 = Ip()
                        ip_model2.oct1 = router_ip[0]
                        ip_model2.oct2 = router_ip[1]
                        ip_model2.oct3 = router_ip[2]
                        ip_model2.oct4 = router_ip[3]
                        ip_model2.networkipv4_id = vlan_map['vlan']['id_network']
                        ip_model2.save()
                        IpEquipamento().create(user, ip_model2.id, equip.equipamento.id)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    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)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat Delete requests to remove related Equipment and  Environment

        URL: equipment/<id_equip>/environment/<id_amb>/
        """

        self.log.info('Remove EquipmentEnvironment by id')

        try:

            # Business Validations

            id_equipment = kwargs.get('id_equipment')
            id_environment = kwargs.get('id_environment')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

            # Find Environment by ID to check if it exist
            environment = Ambiente.get_by_pk(id_environment)

            with distributedlock(LOCK_EQUIPMENT_ENVIRONMENT % id_environment):
                '''
                equip_env = EquipamentoAmbiente().get_by_equipment_environment(
                    id_equipment, id_environment)

                is_error = False
                ipv4_error = ""
                ipv6_error = ""

                for ipequip in equip_env.equipamento.ipequipamento_set.all():

                    if ipequip.ip.networkipv4.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv4_error += " %s.%s.%s.%s - Vip %s ," % (
                                ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause)

                for ipequip in equip_env.equipamento.ipv6equipament_set.all():

                    if ipequip.ip.networkipv6.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv6_error += " %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ," % (
                                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause)

                if is_error:
                    return self.response_error(336, environment.show_environment(), ipv4_error, ipv6_error)

                # Remove Equipment - Environment
                '''
                EquipamentoAmbiente.remove(user, id_equipment, id_environment)

                return self.response(dumps_networkapi({}))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equipment)
    def network_ipv6_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

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

            # Network Type

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

            # Find network_type by ID to check if it exist
            net = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

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

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv6
            network_ipv6 = NetworkIPv6()
            vlan_map = network_ipv6.add_network_ipv6(
                user, vlan_id, net, evip, prefix)

            list_equip_routers_ambient = EquipamentoAmbiente.get_routers_by_environment(vlan_map['vlan']['id_ambiente'])

            if list_equip_routers_ambient:

                # Add Adds the first available ipv6 on all equipment
                # that is configured as a router for the environment related to
                # network
                ipv6 = Ipv6.get_first_available_ip6(vlan_map['vlan']['id_network'])

                ipv6 = str(ipv6).split(':')

                ipv6_model = Ipv6()
                ipv6_model.block1 = ipv6[0]
                ipv6_model.block2 = ipv6[1]
                ipv6_model.block3 = ipv6[2]
                ipv6_model.block4 = ipv6[3]
                ipv6_model.block5 = ipv6[4]
                ipv6_model.block6 = ipv6[5]
                ipv6_model.block7 = ipv6[6]
                ipv6_model.block8 = ipv6[7]
                ipv6_model.networkipv6_id = vlan_map['vlan']['id_network']

                ipv6_model.save()

                if len(list_equip_routers_ambient) > 1:
                    multiple_ips = True
                else:
                    multiple_ips = False

                for equip in list_equip_routers_ambient:

                    Ipv6Equipament().create(
                        user, ipv6_model.id, equip.equipamento.id)

                    if multiple_ips:
                        router_ip = Ipv6.get_first_available_ip6(vlan_map['vlan']['id_network'], True)
                        ipv6_model2 = Ipv6()
                        ipv6_model2.block1 = router_ip[0]
                        ipv6_model2.block2 = router_ip[1]
                        ipv6_model2.block3 = router_ip[2]
                        ipv6_model2.block4 = router_ip[3]
                        ipv6_model2.block5 = router_ip[4]
                        ipv6_model2.block6 = router_ip[5]
                        ipv6_model2.block7 = router_ip[6]
                        ipv6_model2.block8 = router_ip[7]
                        ipv6_model2.networkipv6_id = vlan_map['vlan']['id_network']
                        ipv6_model2.save()
                        Ipv6Equipament().create(user, ipv6_model2.id, equip.equipamento.id)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
Esempio n. 8
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
Esempio n. 9
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
Esempio n. 10
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
    def network_ipv6_add(self,
                         user,
                         vlan_id,
                         network_type,
                         environment_vip,
                         prefix=None):

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

            # Network Type

            # Valid network_type ID
            """
            if not is_valid_int_greater_zero_param(network_type):
                self.log.error(
                    u'Parameter id_tipo_rede is invalid. Value: %s.', network_type)
                raise InvalidValueError(None, 'id_tipo_rede', network_type)
            """
            # Find network_type by ID to check if it exist
            net = None
            if network_type:
                net = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

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

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv6
            network_ipv6 = NetworkIPv6()
            vlan_map = network_ipv6.add_network_ipv6(user, vlan_id, net, evip,
                                                     prefix)

            list_equip_routers_ambient = EquipamentoAmbiente.get_routers_by_environment(
                vlan_map['vlan']['id_ambiente'])

            if list_equip_routers_ambient:

                # Add Adds the first available ipv6 on all equipment
                # that is configured as a router for the environment related to
                # network
                ipv6 = Ipv6.get_first_available_ip6(
                    vlan_map['vlan']['id_network'])

                ipv6 = str(ipv6).split(':')

                ipv6_model = Ipv6()
                ipv6_model.block1 = ipv6[0]
                ipv6_model.block2 = ipv6[1]
                ipv6_model.block3 = ipv6[2]
                ipv6_model.block4 = ipv6[3]
                ipv6_model.block5 = ipv6[4]
                ipv6_model.block6 = ipv6[5]
                ipv6_model.block7 = ipv6[6]
                ipv6_model.block8 = ipv6[7]
                ipv6_model.networkipv6_id = vlan_map['vlan']['id_network']

                ipv6_model.save()

                if len(list_equip_routers_ambient) > 1:
                    multiple_ips = True
                else:
                    multiple_ips = False

                for equip in list_equip_routers_ambient:

                    Ipv6Equipament().create(user, ipv6_model.id,
                                            equip.equipamento.id)

                    if multiple_ips:
                        router_ip = Ipv6.get_first_available_ip6(
                            vlan_map['vlan']['id_network'], True)
                        router_ip = str(router_ip).split(':')
                        ipv6_model2 = Ipv6()
                        ipv6_model2.block1 = router_ip[0]
                        ipv6_model2.block2 = router_ip[1]
                        ipv6_model2.block3 = router_ip[2]
                        ipv6_model2.block4 = router_ip[3]
                        ipv6_model2.block5 = router_ip[4]
                        ipv6_model2.block6 = router_ip[5]
                        ipv6_model2.block7 = router_ip[6]
                        ipv6_model2.block8 = router_ip[7]
                        ipv6_model2.networkipv6_id = vlan_map['vlan'][
                            'id_network']
                        ipv6_model2.save()
                        Ipv6Equipament().create(user, ipv6_model2.id,
                                                equip.equipamento.id)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
Esempio n. 12
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
Esempio n. 13
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
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat Delete requests to remove related Equipment and  Environment

        URL: equipment/<id_equip>/environment/<id_amb>/
        """

        self.log.info('Remove EquipmentEnvironment by id')

        try:

            # Business Validations

            id_equipment = kwargs.get('id_equipment')
            id_environment = kwargs.get('id_environment')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

            # Find Environment by ID to check if it exist
            environment = Ambiente.get_by_pk(id_environment)

            with distributedlock(LOCK_EQUIPMENT_ENVIRONMENT % id_environment):
                '''
                equip_env = EquipamentoAmbiente().get_by_equipment_environment(
                    id_equipment, id_environment)

                is_error = False
                ipv4_error = ""
                ipv6_error = ""

                for ipequip in equip_env.equipamento.ipequipamento_set.all():

                    if ipequip.ip.networkipv4.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv4_error += " %s.%s.%s.%s - Vip %s ," % (
                                ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause)

                for ipequip in equip_env.equipamento.ipv6equipament_set.all():

                    if ipequip.ip.networkipv6.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv6_error += " %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ," % (
                                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause)

                if is_error:
                    return self.response_error(336, environment.show_environment(), ipv4_error, ipv6_error)

                # Remove Equipment - Environment
                '''
                EquipamentoAmbiente.remove(user, id_equipment, id_environment)

                return self.response(dumps_networkapi({}))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equipment)