def prepares_network_simple(vlan): vlan_dict = dict() netv4_itens = [] for netv4 in vlan.networkipv4_set.all(): net_dict = dict() net = str(netv4.oct1) + '.' + str(netv4.oct2) + '.' + \ str(netv4.oct3) + '.' + str(netv4.oct4) + '/' + str(netv4.block) net_dict['network'] = IPNetwork(net).exploded net_dict['id'] = netv4.id netv4_itens.append(net_dict) netv6_itens = [] for netv6 in vlan.networkipv6_set.all(): net_dict = dict() net = str(netv6.block1) + ':' + str(netv6.block2) + ':' + str(netv6.block3) + ':' + str(netv6.block4) + ':' + \ str(netv6.block5) + ':' + str(netv6.block6) + ':' + \ str(netv6.block7) + ':' + \ str(netv6.block8) + '/' + str(netv6.block) net_dict['network'] = IPNetwork(net).compressed net_dict['id'] = netv6.id netv6_itens.append(net_dict) vlan_dict['id'] = vlan.id vlan_dict['redeipv4'] = netv4_itens vlan_dict['redeipv6'] = netv6_itens return vlan_dict
def validate_network(envs, net_ip, version): """Verify if network make conflict in environment or environment related. """ models = get_app('ambiente', 'models') cidr = models.EnvCIDR() # Filter network_ipv4 where environment has config permiting to insert # current network. nets_envs = list() for env in envs: # get configs v4 of environment nts = [IPNetwork(config.network) for config in cidr.get(env_id=env.id).filter(ip_version=version)] # get networks that can be intersect with current network if verify_intersect(nts, net_ip)[0]: log.info('Environment %s has config(%s) permiting to insert ' 'in this network %s' % (env.name, nts, net_ip)) if version == models.IP_VERSION.IPv4[0]: for vlan in env.vlans: for network_ipv4 in vlan.networks_ipv4: nets_envs.append(IPNetwork(network_ipv4.networkv4)) else: for vlan in env.vlans: for network_ipv6 in vlan.networks_ipv6: nets_envs.append(IPNetwork(network_ipv6.networkv6)) if nets_envs: verify_networks(net_ip, nets_envs)
def verify_subnet(vlan, network_ip, version): if version == IP_VERSION.IPv4[0]: vlan_net = vlan.networkipv4_set.all() else: vlan_net = vlan.networkipv6_set.all() # One vlan may have many networks, iterate over it for net in vlan_net: if version == IP_VERSION.IPv4[0]: ip = '%s.%s.%s.%s/%s' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block) else: ip = '%s:%s:%s:%s:%s:%s:%s:%s/%d' % ( net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block) ip_net = IPNetwork(ip) # If some network, inside this vlan, is subnet of network search param if ip_net in network_ip: # This vlan must be in vlans founded, dont need to continue # checking return True # If some network, inside this vlan, is supernet of network search # param if network_ip in ip_net: # This vlan must be in vlans founded, dont need to continue # checking return True # If dont found any subnet return None return False
def verify_subnet_and_equip(vlan_net, network_ip, version, net_obj, env_obj): # Check if an equipment is shared in a subnet equip_list = get_equips(net_obj, env_obj) # One vlan may have many networks, iterate over it for net_env in vlan_net: net = net_env.get('net') env = net_env.get('vlan_env') if version == 'v4': ip = '%s.%s.%s.%s/%s' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block) else: ip = '%s:%s:%s:%s:%s:%s:%s:%s/%d' % ( net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block) ip_net = IPNetwork(ip) # If some network, inside this vlan, is subnet of network search param if ip_net in network_ip: equip_list_aux = get_equips(net, env) if len(set(equip_list) & set(equip_list_aux)) > 0: # This vlan must be in vlans founded, dont need to continue # checking return True # If some network, inside this vlan, is supernet of network search # param if network_ip in ip_net: equip_list_aux = get_equips(net, env) if len(set(equip_list) & set(equip_list_aux)) > 0: # This vlan must be in vlans founded, dont need to continue # checking return True # If dont found any subnet return None return False
def verify_subnet(vlan, network_ip, version): if version == IP_VERSION.IPv4[0]: key = 'redeipv4' else: key = 'redeipv6' # One vlan may have many networks, iterate over it for net in vlan[key]: ip_net = IPNetwork(net['network']) # If some network, inside this vlan, is subnet of network search param if ip_net in network_ip: # This vlan must be in vlans founded, dont need to continue # checking return True # If some network, inside this vlan, is supernet of network search # param if network_ip in ip_net: # This vlan must be in vlans founded, dont need to continue # checking return True # If dont found any subnet return None return False
def _validate_network(self, network, prefix): try: net = IPNetwork(network) except ValueError: self.log.error( u'The network parameter is invalid value: %s.', network) raise InvalidValueError(None, 'network', network) blocks, network, version = break_network(network) expl = split( net.network.exploded, "." if version == IP_VERSION.IPv4[0] else ":") expl.append(str(net.prefixlen)) block = int(blocks[-1]) if blocks != expl: raise InvalidValueError(None, 'network', network) if block > int(prefix): self.log.error(u'The block parameter is invalid value: %s.', block) raise InvalidValueError(None, 'block', block)
def handle_post(self, request, user, *args, **kwargs): """Handles POST requests to find all VLANs by search parameters. URLs: /vlan/find/ """ self.log.info('Find all VLANs') try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data, ['searchable_columns', 'asorting_cols']) # 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) vlan_map = networkapi_map.get('vlan') if vlan_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data start_record = vlan_map.get('start_record') end_record = vlan_map.get('end_record') asorting_cols = vlan_map.get('asorting_cols') searchable_columns = vlan_map.get('searchable_columns') custom_search = vlan_map.get('custom_search') number = vlan_map.get('numero') name = vlan_map.get('nome') iexact = vlan_map.get('exato') environment = vlan_map.get('ambiente') net_type = vlan_map.get('tipo_rede') network = vlan_map.get('rede') ip_version = vlan_map.get('versao') subnet = vlan_map.get('subrede') acl = vlan_map.get('acl') # Business Rules # Start with alls vlans = Vlan.objects.all().prefetch_related( 'networkipv4_set', 'networkipv6_set') if number is not None: # If number is valid, add to filter if not is_valid_int_greater_zero_param(number, False): raise InvalidValueError(None, 'numero', number) else: vlans = vlans.filter(num_vlan=number) if name is not None: # If name is valid, add to filter if not is_valid_string_minsize(name, 3, False): raise InvalidValueError(None, 'nome', name) else: # Iexact must be valid to add name to filter if not is_valid_boolean_param(iexact, False): raise InvalidValueError(None, 'exato', iexact) else: if (iexact is None) or (iexact == 'False') or (iexact == '0'): iexact = False if iexact: vlans = vlans.filter(nome=name) else: vlans = vlans.filter(nome__icontains=name) # If environment is valid, add to filter if environment is not None: if not is_valid_int_greater_zero_param(environment, False): raise InvalidValueError(None, 'ambiente', environment) else: vlans = vlans.filter(ambiente__pk=environment) if net_type is not None: # If net_type is valid, add to filter if not is_valid_int_greater_zero_param(net_type, False): raise InvalidValueError(None, 'tipo_rede', net_type) else: q1 = Q(networkipv4__network_type__id=net_type) q2 = Q(networkipv6__network_type__id=net_type) vlans = vlans.filter(q1 | q2) if acl is not None: # If acl is valid, add to filter if not is_valid_boolean_param(acl, False): raise InvalidValueError(None, 'acl', acl) else: if (acl is None) or (acl == 'False') or (acl == '0'): acl = False # If acl is true, only show vlans with false acl_valida if acl: vlans = vlans.filter(acl_valida=False) # If ip_version is valid if not is_valid_int_greater_equal_zero_param(ip_version): raise InvalidValueError(None, 'versao', ip_version) else: if ip_version == '0': vlans = vlans.filter( Q(networkipv6__isnull=True) | Q(networkipv4__isnull=False)) elif ip_version == '1': vlans = vlans.filter( Q(networkipv4__isnull=True) | Q(networkipv6__isnull=False)) if network is not None: # If network is valid if not is_valid_string_minsize(network, 1, False): raise InvalidValueError(None, 'rede', network) else: blocks, network, version = break_network(network) try: network_ip = IPNetwork(network) except ValueError, e: raise InvalidValueError(None, 'rede', network) # If subnet is valid, add to filter if not (subnet == '0' or subnet == '1'): raise InvalidValueError(None, 'subrede', subnet) else: # If subnet is 0, only filter network octs if subnet == '0': # Filter octs if version == IP_VERSION.IPv4[0]: # Network IP v4 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv4__oct1=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv4__oct2=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv4__oct3=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv4__oct4=blocks[3]) if len(blocks[4]) != 0: blk = Q(networkipv4__block=blocks[4]) vlans = vlans.filter(oct1 & oct2 & oct3 & oct4 & blk) else: # Network IP v6 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() oct5 = Q() oct6 = Q() oct7 = Q() oct8 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv6__block1__iexact=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv6__block2__iexact=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv6__block3__iexact=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv6__block4__iexact=blocks[3]) if len(blocks[4]) != 0: oct5 = Q(networkipv6__block5__iexact=blocks[4]) if len(blocks[5]) != 0: oct6 = Q(networkipv6__block6__iexact=blocks[5]) if len(blocks[6]) != 0: oct7 = Q(networkipv6__block7__iexact=blocks[6]) if len(blocks[7]) != 0: oct8 = Q(networkipv6__block8__iexact=blocks[7]) if len(blocks[8]) != 0: blk = Q(networkipv6__block=blocks[8]) vlans = vlans.filter(oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8 & blk) # If subnet is 1 else: if version == IP_VERSION.IPv4[0]: expl = split(network_ip.network.exploded, '.') else: expl = split(network_ip.network.exploded, ':') expl.append(str(network_ip.prefixlen)) if blocks != expl: raise InvalidValueError(None, 'rede', network) # First, get all vlans filtered until now itens = get_networks_simple(vlans) ids_exclude = [] # Then iterate over it to verify each vlan for vlan in itens: is_subnet = verify_subnet(vlan, network_ip, version) if not is_subnet: ids_exclude.append(vlan['id']) vlans = vlans.exclude(id__in=ids_exclude) # Custom order if asorting_cols: if 'ambiente' in asorting_cols: vlans = vlans.order_by('ambiente__divisao_dc__nome', 'ambiente__ambiente_logico__nome', 'ambiente__grupo_l3__nome') asorting_cols.remove('ambiente') if '-ambiente' in asorting_cols: vlans = vlans.order_by('-ambiente__divisao_dc__nome', '-ambiente__ambiente_logico__nome', '-ambiente__grupo_l3__nome') asorting_cols.remove('-ambiente') if 'tipo_rede' in asorting_cols: vlans = vlans.order_by( 'networkipv4__network_type__tipo_rede', 'networkipv6__network_type__tipo_rede') asorting_cols.remove('tipo_rede') if '-tipo_rede' in asorting_cols: vlans = vlans.order_by( '-networkipv4__network_type__tipo_rede', '-networkipv6__network_type__tipo_rede') asorting_cols.remove('-tipo_rede') if 'network' in asorting_cols: vlans = vlans.order_by( 'networkipv4__oct1', 'networkipv4__oct2', 'networkipv4__oct3', 'networkipv4__oct4', 'networkipv4__block', 'networkipv6__block1', 'networkipv6__block2', 'networkipv6__block3', 'networkipv6__block4', 'networkipv6__block5', 'networkipv6__block6', 'networkipv6__block7', 'networkipv6__block8', 'networkipv6__block') asorting_cols.remove('network') if '-network' in asorting_cols: vlans = vlans.order_by( '-networkipv4__oct1', '-networkipv4__oct2', '-networkipv4__oct3', '-networkipv4__oct4', '-networkipv4__block', '-networkipv6__block1', '-networkipv6__block2', '-networkipv6__block3', '-networkipv6__block4', '-networkipv6__block5', '-networkipv6__block6', '-networkipv6__block7', '-networkipv6__block8', '-networkipv6__block') asorting_cols.remove('-network') vlans = vlans.distinct() # Datatable paginator vlans, total = build_query_to_datatable(vlans, asorting_cols, custom_search, searchable_columns, start_record, end_record) vlans = vlans.prefetch_related( 'ambiente', 'networkipv4_set__network_type', 'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente', 'networkipv6_set__network_type', 'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente' ) itens = get_networks(vlans, False) vlan_map = dict() vlan_map['vlan'] = itens vlan_map['total'] = total return self.response(dumps_networkapi(vlan_map))
def prepares_network(vlan, half): vlan_dict = dict() if not half: vlan_dict = model_to_dict(vlan) vlan_dict['ambiente_name'] = vlan.ambiente.divisao_dc.nome + ' - ' + \ vlan.ambiente.ambiente_logico.nome + \ ' - ' + vlan.ambiente.grupo_l3.nome vlan_dict['is_more'] = False netv4_itens = [] for netv4 in vlan.networkipv4_set.all(): net_dict = dict() net = str(netv4.oct1) + '.' + str(netv4.oct2) + '.' + \ str(netv4.oct3) + '.' + str(netv4.oct4) + '/' + str(netv4.block) net_dict['network'] = IPNetwork(net).exploded net_dict['id'] = netv4.id if not half: net_dict['tipo_rede_name'] = netv4.network_type.tipo_rede equip_itens = [] for ip in netv4.ip_set.all(): for ip_equip in ip.ipequipamento_set.all(): if not ip_equip.equipamento.nome in equip_itens: for equip_amb in ip_equip.equipamento.equipamentoambiente_set.all( ): if equip_amb.ambiente == vlan.ambiente and equip_amb.is_router: equip_itens.append(ip_equip.equipamento.nome) if len(equip_itens) == 0: equip_itens.append(' ') elif len(equip_itens) > 3: vlan_dict['is_more'] = True net_dict['equipamentos'] = equip_itens netv4_itens.append(net_dict) netv6_itens = [] for netv6 in vlan.networkipv6_set.all(): net_dict = dict() net = str(netv6.block1) + ':' + str(netv6.block2) + ':' + str(netv6.block3) + ':' + str(netv6.block4) + ':' + \ str(netv6.block5) + ':' + str(netv6.block6) + ':' + \ str(netv6.block7) + ':' + \ str(netv6.block8) + '/' + str(netv6.block) net_dict['network'] = IPNetwork(net).compressed net_dict['id'] = netv6.id if not half: net_dict['tipo_rede_name'] = netv6.network_type.tipo_rede equip_itens = [] for ip in netv6.ipv6_set.all(): for ip_equip in ip.ipv6equipament_set.all(): if not ip_equip.equipamento.nome in equip_itens: for equip_amb in ip_equip.equipamento.equipamentoambiente_set.all( ): if equip_amb.ambiente == vlan.ambiente and equip_amb.is_router: equip_itens.append(ip_equip.equipamento.nome) if len(equip_itens) == 0: equip_itens.append(' ') elif len(equip_itens) > 3: vlan_dict['is_more'] = True net_dict['equipamentos'] = equip_itens netv6_itens.append(net_dict) vlan_dict['id'] = vlan.id vlan_dict['redeipv4'] = netv4_itens vlan_dict['redeipv6'] = netv6_itens if (len(netv4_itens) > 1): if (vlan_dict['is_more'] is True) or (len(netv4_itens) > 3): vlan_dict['more_than_three'] = True if (len(netv6_itens) > 1): if (vlan_dict['is_more'] is True) or (len(netv6_itens) > 3): vlan_dict['more_than_three'] = True if len(netv4_itens) > 3: vlan_dict['is_more'] = True if len(netv6_itens) > 3: vlan_dict['is_more'] = True return vlan_dict
def handle_post(self, request, user, *args, **kwargs): """Treat POST requests to add new Network URL: network/add/ """ try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # 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) network_map = networkapi_map.get('network') if network_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data network = network_map.get('network') id_vlan = network_map.get('id_vlan') network_type = network_map.get('id_network_type') environment_vip = network_map.get('id_environment_vip') cluster_unit = network_map.get('cluster_unit') # Valid Network try: net = IPNetwork(network) except ValueError, e: raise InvalidValueError(None, 'network', network) # VLAN # Valid vlan ID if not is_valid_int_greater_zero_param(id_vlan): raise InvalidValueError(None, 'id_vlan', id_vlan) # Find vlan by ID to check if it exist vlan = Vlan().get_by_pk(id_vlan) # Network Type # Valid network_type ID if not is_valid_int_greater_zero_param(network_type): raise InvalidValueError(None, 'id_network_type', network_type) # Find network_type by ID to check if it exist net_type = 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): raise InvalidValueError(None, 'id_environment_vip', environment_vip) evips = EnvironmentVip.objects.all() evip_list = EnvironmentVip.available_evips( EnvironmentVip(), evips, int(id_vlan)) # Check if the chose environment is in the same environment if any( int(environment_vip) == item['id'] for item in evip_list): # Find Environment VIP by ID to check if it exist env_vip = EnvironmentVip.get_by_pk(environment_vip) else: raise InvalidValueError(None, 'id_environment_vip', environment_vip) else: env_vip = None # Check unchecked exception blocks, network, version = break_network(network) expl = split(net.network.exploded, '.' if version == IP_VERSION.IPv4[0] else ':') expl.append(str(net.prefixlen)) if blocks != expl: raise InvalidValueError(None, 'rede', network) # Business Rules if version == IP_VERSION.IPv4[0]: # Find all networks related to environment nets = NetworkIPv4.objects.filter( vlan__ambiente__id=vlan.ambiente.id) # Cast to API class networks = set([ IPv4Network('%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets ]) # If network selected not in use for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use in this environment.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use in this environment.' % network_aux) if env_vip is not None: # Find all networks related to environment vip nets = NetworkIPv4.objects.filter( ambient_vip__id=env_vip.id) # Cast to API class networks = set([ IPv4Network('%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets ]) # If there is already a network with the same range ip as # related the environment vip for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use in this environment VIP.' % network_aux) # # Filter case 1 - Adding new network with same ip range to another network on other environment ## # Get environments with networks with the same ip range nets = NetworkIPv4.objects.filter(oct1=expl[0], oct2=expl[1], oct3=expl[2], oct4=expl[3], block=expl[4]) env_ids = list() for net_ip in nets: env_ids.append(net_ip.vlan.ambiente.id) # If other network with same ip range exists if len(env_ids) > 0: # Get equipments related to this network's environment env_equips = EquipamentoAmbiente.objects.filter( ambiente=vlan.ambiente.id) # Verify equipments related with all other environments # that contains networks with same ip range for env_id in env_ids: # Equipments related to other environments other_env_equips = EquipamentoAmbiente.objects.filter( ambiente=env_id) # Adjust to equipments equip_list = list() for equip_env in other_env_equips: equip_list.append(equip_env.equipamento.id) for env_equip in env_equips: if env_equip.equipamento.id in equip_list: # Filter testing if other_env_equips[ 0].ambiente.filter is None or vlan.ambiente.filter is None: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.' ) else: # Test both environment's filters tp_equip_list_one = list() for fet in FilterEquipType.objects.filter( filter=vlan.ambiente.filter.id): tp_equip_list_one.append(fet.equiptype) tp_equip_list_two = list() for fet in FilterEquipType.objects.filter( filter=other_env_equips[0]. ambiente.filter.id): tp_equip_list_two.append(fet.equiptype) if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.' ) # # Filter case 1 - end ## # New NetworkIPv4 network_ip = NetworkIPv4() # Set octs by network generated network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str( net.network).split('.') # Set block by network generated network_ip.block = net.prefixlen # Set mask by network generated network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str( net.netmask).split('.') # Set broadcast by network generated network_ip.broadcast = net.broadcast.compressed else: # Find all networks ralated to environment nets = NetworkIPv6.objects.filter( vlan__ambiente__id=vlan.ambiente.id) # Cast to API class networks = set([ IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3, net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets ]) # If network selected not in use for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use in this environment.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use in this environment.' % network_aux) if env_vip is not None: # Find all networks related to environment vip nets = NetworkIPv6.objects.filter( ambient_vip__id=env_vip.id) # Cast to API class networks = set([ IPv6Network( '%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3, net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets ]) # If there is already a network with the same range ip as # related the environment vip for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use in this environment VIP.' % network_aux) # # Filter case 1 - Adding new network with same ip range to another network on other environment ## # Get environments with networks with the same ip range nets = NetworkIPv6.objects.filter(block1=expl[0], block2=expl[1], block3=expl[2], block4=expl[3], block5=expl[4], block6=expl[5], block7=expl[6], block8=expl[7], block=expl[8]) env_ids = list() for net_ip in nets: env_ids.append(net_ip.vlan.ambiente.id) # If other network with same ip range exists if len(env_ids) > 0: # Get equipments related to this network's environment env_equips = EquipamentoAmbiente.objects.filter( ambiente=vlan.ambiente.id) # Verify equipments related with all other environments # that contains networks with same ip range for env_id in env_ids: # Equipments related to other environments other_env_equips = EquipamentoAmbiente.objects.filter( ambiente=env_id) # Adjust to equipments equip_list = list() for equip_env in other_env_equips: equip_list.append(equip_env.equipamento.id) for env_equip in env_equips: if env_equip.equipamento.id in equip_list: # Filter testing if other_env_equips[ 0].ambiente.filter is None or vlan.ambiente.filter is None: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.' ) else: # Test both environment's filters tp_equip_list_one = list() for fet in FilterEquipType.objects.filter( filter=vlan.ambiente.filter.id): tp_equip_list_one.append(fet.equiptype) tp_equip_list_two = list() for fet in FilterEquipType.objects.filter( filter=other_env_equips[0]. ambiente.filter.id): tp_equip_list_two.append(fet.equiptype) if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.' ) # # Filter case 1 - end ## # New NetworkIPv6 network_ip = NetworkIPv6() # Set block by network generated network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str( net.network.exploded).split(':') # Set block by network generated network_ip.block = net.prefixlen # Set mask by network generated network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str( net.netmask.exploded).split(':') # Get all vlans environments from equipments of the current # environment ambiente = vlan.ambiente equips = list() envs = list() # equips = all equipments from the environment which this network # is about to be allocated on for env in ambiente.equipamentoambiente_set.all(): equips.append(env.equipamento) # envs = all environments from all equips above # This will be used to test all networks from the environments. for equip in equips: for env in equip.equipamentoambiente_set.all(): if env.ambiente not in envs: envs.append(env.ambiente) network_ip_verify = IPNetwork(network) # For all vlans in all common environments, # check if any network is a subnetwork or supernetwork # of the desired network network_ip_verify for env in envs: for vlan_obj in env.vlan_set.all(): is_subnet = verify_subnet(vlan_obj, network_ip_verify, version) if is_subnet: if vlan_obj.ambiente == ambiente: raise NetworkIPRangeEnvError(None) if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or int( vlan_obj.ambiente.filter_id) != int( ambiente.filter_id): raise NetworkIPRangeEnvError(None) # Set Vlan network_ip.vlan = vlan # Set Network Type network_ip.network_type = net_type # Set Environment VIP network_ip.ambient_vip = env_vip # Set Cluster Unit network_ip.cluster_unit = cluster_unit # Persist try: # Delete vlan's cache destroy_cache_function([id_vlan]) network_ip.save() list_equip_routers_ambient = EquipamentoAmbiente.objects.filter( ambiente=network_ip.vlan.ambiente.id, is_router=True) if list_equip_routers_ambient: if version == IP_VERSION.IPv4[0]: if network_ip.block < 31: # 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(network_ip.id) 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_ip.id ip_model.save() if len(list_equip_routers_ambient ) > 1 and network_ip.block < 30: 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( network_ip.id, 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 = network_ip.id ip_model2.save(user) IpEquipamento().create( user, ip_model2.id, equip.equipamento.id) else: if network_ip.block < 127: # 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(network_ip.id) 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 = network_ip.id ipv6_model.save() if len(list_equip_routers_ambient ) > 1 and network_ip.block < 126: 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( network_ip.id, 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 = network_ip.id ipv6_model2.save(user) Ipv6Equipament().create( user, ipv6_model2.id, equip.equipamento.id) except Exception, e: raise IpError(e, u'Error persisting Network.')
def handle_get(self, request, user, *args, **kwargs): '''Treat GET requests to check if a vlan need confimation to insert URL: vlan/confirm/ ''' try: # Get XML data ip_version = kwargs.get('ip_version') if ip_version == 'None': is_number = True number = kwargs.get('number') id_environment = kwargs.get('id_environment') else: network = kwargs.get('number') network = network.replace('net_replace', '/') id_vlan = kwargs.get('id_environment') if ip_version == '1': version = 'v6' else: version = 'v4' is_number = False # Commons Validations # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() if is_number: # Valid number 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) ambiente = Ambiente.get_by_pk(id_environment) equips = list() envs = list() envs_aux = list() for env in ambiente.equipamentoambiente_set.all(): equips.append(env.equipamento) for equip in equips: for env in equip.equipamentoambiente_set.all(): if env.ambiente_id not in envs_aux: envs.append(env.ambiente) envs_aux.append(env.ambiente_id) # Valid number map = dict() map['needs_confirmation'] = True for env in envs: for vlan in env.vlan_set.all(): if int(vlan.num_vlan) == int(number): if ambiente.filter_id is None or vlan.ambiente.filter_id is None or int( vlan.ambiente.filter_id) != int( ambiente.filter_id): map['needs_confirmation'] = False else: map['needs_confirmation'] = True break else: # Valid subnet if not is_valid_int_greater_zero_param(id_vlan): self.log.error(u'Parameter id_vlan is invalid. Value: %s.', id_vlan) raise InvalidValueError(None, 'id_vlan', id_vlan) # Get all vlans environments from equipments of the current # environment vlan = Vlan() vlan = vlan.get_by_pk(id_vlan) ambiente = vlan.ambiente equips = list() envs = list() envs_aux = list() for env in ambiente.equipamentoambiente_set.all(): equips.append(env.equipamento) for equip in equips: for env in equip.equipamentoambiente_set.all(): if env.ambiente_id not in envs_aux: envs.append(env.ambiente) envs_aux.append(env.ambiente_id) # Check subnet's network = str(network) prefix = split(network, "/") net_explode = prefix[0] if version == IP_VERSION.IPv4[0]: expl = split(net_explode, ".") else: expl = split(net_explode, ":") expl.append(str(prefix[1])) ids_exclude = [] ids_all = [] network_ip_verify = IPNetwork(network) for env in envs: for vlan_obj in env.vlan_set.all(): ids_all.append(vlan_obj.id) is_subnet = verify_subnet(vlan_obj, network_ip_verify, version) if not is_subnet: ids_exclude.append(vlan_obj.id) else: if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or int( vlan_obj.ambiente.filter_id) != int( ambiente.filter_id): pass else: ids_exclude.append(vlan_obj.id) # Valid number map = dict() map['needs_confirmation'] = True # Ignore actual vlan if envs != [] and long(id_vlan) not in ids_exclude: ids_exclude.append(id_vlan) # Check if have duplicated vlan's with same net range in an # environment with shared equipment if len(ids_all) != len(ids_exclude): map['needs_confirmation'] = False else: map['needs_confirmation'] = True # Return XML return self.response(dumps_networkapi(map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_post(self, request, user, *args, **kwargs): """Treat POST requests to add new Network URL: network/add/ """ try: if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() xml_map, attrs_map = loads(request.raw_post_data) 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) network_map = networkapi_map.get('network') if network_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data network = network_map.get('network') id_vlan = network_map.get('id_vlan') network_type = network_map.get('id_network_type') environment_vip = network_map.get('id_environment_vip') cluster_unit = network_map.get('cluster_unit') try: net = IPNetwork(network) except ValueError: raise InvalidValueError(None, 'network', network) # Valid vlan ID if not is_valid_int_greater_zero_param(id_vlan): raise InvalidValueError(None, 'id_vlan', id_vlan) if not is_valid_int_greater_zero_param(network_type): raise InvalidValueError(None, 'id_network_type', network_type) vlan = Vlan().get_by_pk(id_vlan) net_type = TipoRede.get_by_pk(network_type) if environment_vip is not None: if not is_valid_int_greater_zero_param(environment_vip): raise InvalidValueError(None, 'id_environment_vip', environment_vip) evips = EnvironmentVip.objects.all() evip_list = EnvironmentVip.available_evips( EnvironmentVip(), evips, int(id_vlan)) # Check if the chose environment is in the same environment if any( int(environment_vip) == item['id'] for item in evip_list): # Find Environment VIP by ID to check if it exist env_vip = EnvironmentVip.get_by_pk(environment_vip) else: raise InvalidValueError(None, 'id_environment_vip', environment_vip) else: env_vip = None # Check unchecked exception blocks, network, version = break_network(network) expl = split(net.network.exploded, '.' if version == IP_VERSION.IPv4[0] else ':') expl.append(str(net.prefixlen)) if blocks != expl: raise InvalidValueError(None, 'rede', network) if version == IP_VERSION.IPv4[0]: # Find all networks related to environment nets = NetworkIPv4.objects.filter( vlan__ambiente__id=vlan.ambiente.id) # Cast to API class networks = set([ IPv4Network('%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets ]) # If network selected not in use for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already ' 'in use in this environment.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use in this environment.' % network_aux) if env_vip is not None: # Find all networks related to environment vip nets = NetworkIPv4.objects.filter( ambient_vip__id=env_vip.id) # Cast to API class networks = set([ IPv4Network('%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets ]) # If there is already a network with the same range ip as # related the environment vip for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use ' 'in this environment VIP.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in use ' u'in this environment VIP.' % network_aux) # Check if the new network is in the range of the Environment Network try: vlan = Vlan().get_by_pk(id_vlan) vlan_env_id = vlan.ambiente try: config_env = ConfigEnvironment() environment_conf = config_env.get_by_environment( vlan_env_id) if environment_conf: for env_config in environment_conf: ipconfig = env_config.ip_config subnet = ipconfig.subnet env_net = IPNetwork(subnet) try: if net in env_net: self.log.debug( 'Network "%s" can be allocated because is in the ' 'environment network(%s) subnets.' % (net, subnet)) else: raise NetworkSubnetRange( None, 'A rede a ser cadastrada (%s) não pertence às ' 'subredes do ambiente (rede ambiente: %s). ' 'Cadastre o range desejado no ' 'ambiente.' % (net, subnet)) except NetworkSubnetRange: self.log.error( 'Network "%s" can not be allocated because is not in the ' 'environment network(%s) subnets.' % (net, subnet)) return self.response_error(414) else: raise NetworkEnvironmentError( None, 'O ambiente não está configurado. ' 'É necessário efetuar a configuração.') except NetworkEnvironmentError: self.log.error( 'The environment does not have a registered network' ) return self.response_error(415) except Exception as ERROR: self.log.error(ERROR) # # Filter case 1 - Adding new network with same ip range to another network on other environment ## # Get environments with networks with the same ip range nets = NetworkIPv4.objects.filter(oct1=expl[0], oct2=expl[1], oct3=expl[2], oct4=expl[3], block=expl[4]) env_ids = list() for net_ip in nets: env_ids.append(net_ip.vlan.ambiente.id) # If other network with same ip range exists if len(env_ids) > 0: # Get equipments related to this network's environment env_equips = EquipamentoAmbiente.objects.filter( ambiente=vlan.ambiente.id) # Verify equipments related with all other environments # that contains networks with same ip range for env_id in env_ids: # Equipments related to other environments other_env_equips = EquipamentoAmbiente.objects.filter( ambiente=env_id) # Adjust to equipments equip_list = list() for equip_env in other_env_equips: equip_list.append(equip_env.equipamento.id) for env_equip in env_equips: if env_equip.equipamento.id in equip_list: # Filter testing if other_env_equips[ 0].ambiente.filter is None or vlan.ambiente.filter is None: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ambiente ' u'desta rede também está associado com outro ambiente ' u'que tem uma rede com essa mesma faixa, adicione ' u'filtros nos ambientes se necessário.' ) else: # Test both environment's filters tp_equip_list_one = list() for fet in FilterEquipType.objects.filter( filter=vlan.ambiente.filter.id): tp_equip_list_one.append(fet.equiptype) tp_equip_list_two = list() for fet in FilterEquipType.objects.filter( filter=other_env_equips[0]. ambiente.filter.id): tp_equip_list_two.append(fet.equiptype) if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \ env_equip.equipamento.tipo_equipamento not in tp_equip_list_two: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ' u'ambiente desta rede também está associado ' u'com outro ambiente que tem uma rede com ' u'essa mesma faixa, adicione filtros nos ' u'ambientes se necessário.') # # Filter case 1 - end ## # New NetworkIPv4 network_ip = NetworkIPv4() network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str( net.network).split('.') network_ip.block = net.prefixlen network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = \ str(net.netmask).split('.') network_ip.broadcast = net.broadcast.compressed else: # Find all networks ralated to environment nets = NetworkIPv6.objects.filter( vlan__ambiente__id=vlan.ambiente.id) networks = set([ IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3, net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets ]) # If network selected not in use for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in use ' 'in this environment.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s already in ' u'use in this environment.' % network_aux) if env_vip is not None: # Find all networks related to environment vip nets = NetworkIPv6.objects.filter( ambient_vip__id=env_vip.id) networks = set([ IPv6Network( '%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3, net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets ]) # If there is already a network with the same range ip as # related the environment vip for network_aux in networks: if net in network_aux or network_aux in net: self.log.debug( 'Network %s cannot be allocated. It conflicts with %s already in ' 'use in this environment VIP.' % (net, network)) raise NetworkIPv4AddressNotAvailableError( None, u'Network cannot be allocated. %s ' u'already in use in this environment ' u'VIP.' % network_aux) # # Filter case 1 - Adding new network with same ip range to another network on other environment ## # Get environments with networks with the same ip range nets = NetworkIPv6.objects.filter(block1=expl[0], block2=expl[1], block3=expl[2], block4=expl[3], block5=expl[4], block6=expl[5], block7=expl[6], block8=expl[7], block=expl[8]) env_ids = list() for net_ip in nets: env_ids.append(net_ip.vlan.ambiente.id) # If other network with same ip range exists if len(env_ids) > 0: # Get equipments related to this network's environment env_equips = EquipamentoAmbiente.objects.filter( ambiente=vlan.ambiente.id) # Verify equipments related with all other environments # that contains networks with same ip range for env_id in env_ids: # Equipments related to other environments other_env_equips = EquipamentoAmbiente.objects.filter( ambiente=env_id) # Adjust to equipments equip_list = list() for equip_env in other_env_equips: equip_list.append(equip_env.equipamento.id) for env_equip in env_equips: if env_equip.equipamento.id in equip_list: # Filter testing if other_env_equips[ 0].ambiente.filter is None or vlan.ambiente.filter is None: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ' u'ambiente desta rede também está associado ' u'com outro ambiente que tem uma rede com ' u'essa mesma faixa, adicione filtros nos ' u'ambientes se necessário.') else: # Test both environment's filters tp_equip_list_one = list() for fet in FilterEquipType.objects.filter( filter=vlan.ambiente.filter.id): tp_equip_list_one.append(fet.equiptype) tp_equip_list_two = list() for fet in FilterEquipType.objects.filter( filter=other_env_equips[0]. ambiente.filter.id): tp_equip_list_two.append(fet.equiptype) if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \ env_equip.equipamento.tipo_equipamento not in tp_equip_list_two: raise NetworkIPRangeEnvError( None, u'Um dos equipamentos associados com o ' u'ambiente desta rede também está ' u'associado com outro ambiente que tem ' u'uma rede com essa mesma faixa, adicione ' u'filtros nos ambientes se necessário.' ) # # Filter case 1 - end ## # New NetworkIPv6 network_ip = NetworkIPv6() network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, \ network_ip.block6, network_ip.block7, network_ip.block8 = str(net.network.exploded).split(':') network_ip.block = net.prefixlen network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, \ network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(net.netmask.exploded).split(':') # Get all vlans environments from equipments of the current # environment ambiente = vlan.ambiente equips = list() envs = list() # equips = all equipments from the environment which this network # is about to be allocated on for env in ambiente.equipamentoambiente_set.all(): equips.append(env.equipamento) # envs = all environments from all equips above # This will be used to test all networks from the environments. for equip in equips: for env in equip.equipamentoambiente_set.all(): if env.ambiente not in envs: envs.append(env.ambiente) network_ip_verify = IPNetwork(network) # For all vlans in all common environments, # check if any network is a subnetwork or supernetwork # of the desired network network_ip_verify for env in envs: for vlan_obj in env.vlan_set.all(): is_subnet = verify_subnet(vlan_obj, network_ip_verify, version) if is_subnet: if vlan_obj.ambiente == ambiente: raise NetworkIPRangeEnvError(None) if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or \ int(vlan_obj.ambiente.filter_id) != int(ambiente.filter_id): raise NetworkIPRangeEnvError(None) network_ip.vlan = vlan network_ip.network_type = net_type network_ip.ambient_vip = env_vip network_ip.cluster_unit = cluster_unit try: destroy_cache_function([id_vlan]) network_ip.save() list_equip_routers_ambient = EquipamentoAmbiente.objects.filter( ambiente=network_ip.vlan.ambiente.id, is_router=True) if list_equip_routers_ambient: if version == IP_VERSION.IPv4[0]: if network_ip.block < 31: # Add 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(network_ip.id) 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_ip.id ip_model.save() if len(list_equip_routers_ambient ) > 1 and network_ip.block < 30: multiple_ips = True else: multiple_ips = False logging.debug('vxlan: %s' % vlan.vxlan) if vlan.vxlan: logging.debug('vxlan ok') for equip in list_equip_routers_ambient: IpEquipamento().create( user, ip_model.id, equip.equipamento.id) if multiple_ips: debug_ip = Ip.get_first_available_ip( network_ip.id, True) ips = Ip() ips.oct1, ips.oct2, ips.oct3, ips.oct4 = str( debug_ip).split('.') ips.networkipv4_id = network_ip.id ips.descricao = "IP alocado para debug" ips.save(user) IpEquipamento().create( user, ips.id, list_equip_routers_ambient[0]. equipamento.id) else: 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( network_ip.id, 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 = network_ip.id ip_model2.save(user) IpEquipamento().create( user, ip_model2.id, equip.equipamento.id) else: if network_ip.block < 127: # Add 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(network_ip.id) 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 = network_ip.id ipv6_model.save() if len(list_equip_routers_ambient ) > 1 and network_ip.block < 126: multiple_ips = True else: multiple_ips = False if vlan.vxlan: 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( network_ip.id, True) ipv6s = Ipv6() ipv6s.block1, ipv6s.block2, ipv6s.block3, ipv6s.block4, ipv6s.block5, \ ipv6s.block6, ipv6s.block7, ipv6s.block8 = str(router_ip).split(':') ipv6s.networkipv6_id = network_ip.id ipv6s.descricao = "IPv6 alocado para debug" ipv6s.save(user) Ipv6Equipament().create( user, ipv6s.id, list_equip_routers_ambient[0]. equipamento.id) else: 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( network_ip.id, 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 = network_ip.id ipv6_model2.save(user) Ipv6Equipament().create( user, ipv6_model2.id, equip.equipamento.id) except Exception as e: raise IpError(e, u'Error persisting Network.') network_map = dict() network_map['id'] = network_ip.id network_map['rede'] = str(net) network_map[ 'broadcast'] = net.broadcast if net.version == 4 else '' network_map['mask'] = net.netmask.exploded network_map['id_vlan'] = vlan.id network_map['id_tipo_rede'] = net_type.id network_map[ 'id_ambiente_vip'] = env_vip.id if env_vip is not None else '' network_map['active'] = network_ip return self.response(dumps_networkapi({'network': network_map})) except NetworkIPRangeEnvError: return self.response_error(346) except InvalidValueError as e: self.log.error(u'Parameter %s is invalid. Value: %s.' % (e.param, e.value)) return self.response_error(269, e.param, e.value) except NetworkTypeNotFoundError: self.log.error(u'The network_type parameter does not exist.') return self.response_error(111) except VlanNotFoundError: self.log.error(u'Vlan not found') return self.response_error(116) except EnvironmentVipNotFoundError: return self.response_error(283) except NetworkIPv4AddressNotAvailableError: return self.response_error(295) except NetworkIPv6AddressNotAvailableError: return self.response_error(296) except ConfigEnvironmentInvalidError: return self.response_error(294) except NetworkIpAddressNotAvailableError: return self.response_error(335) except (IpError, NetworkIPv6Error, NetworkIPv4Error, GrupoError, VlanError): return self.response_error(1) except XMLError as e: self.log.error(u'Error reading the XML request.') return self.response_error(3, e)
def validate_conflict_join_envs(env_ip, equipments): models_env = get_app('ambiente', 'models') models_vrf = get_app('api_vrf', 'models') nums_vlan_rel_ip = [vlan.num_vlan for vlan in env_ip.vlans] for equipment in equipments: # Equipment without environment related, do not need validate # Validate if equipment is not in related in environment if equipment.id not in list(env_ip.eqpts): # Validate if equipment has environments related for env_rel in equipment.environments: env_rel_eqpt = env_rel.ambiente use_filter = True if env_rel_eqpt.filter != env_ip.filter: use_filter = False # Exists differents filters, so is need to validate # all equipments eqpts = env_rel_eqpt.filtered_eqpts \ if use_filter else env_rel_eqpt.eqpts eqpts_env_ip = env_ip.filtered_eqpts \ if use_filter else env_ip.eqpts # Verify if vlans of environment of IP make conflict in # new relationship nums_vlan_rel_eqpt = [vlan.num_vlan for vlan in env_rel_eqpt.vlans] vlans_conflict = list( set(nums_vlan_rel_eqpt) & set(nums_vlan_rel_ip)) if vlans_conflict: msg = 'VLANs {} already registred with same ' \ 'number in equipments of environment: {}' msg = msg.format(vlans_conflict, env_rel_eqpt.name) log.error(msg) raise models_env.IpErrorV3(msg) # Verify if networks of environment of IP make conflict in new # relationship for vlan_rel_ip in env_ip.vlans: # Get vrfs of 1 vlan of environment of IP vrfs_vlan_rel_ip = models_vrf.Vrf.objects.filter(Q( Q(vrfvlanequipment__equipment__in=eqpts) & Q(vrfvlanequipment__vlan__id=vlan_rel_ip.id)) | Q(id=vlan_rel_ip.ambiente.default_vrf_id) ) # Get vrfs of 1 vlan of environment related with # equipment for vlan_rel_eqpt in env_rel_eqpt.vlans: vrfs_vlan_rel_eqpt = models_vrf.Vrf.objects.filter(Q( Q(vrfvlanequipment__equipment__in=eqpts_env_ip) & Q(vrfvlanequipment__vlan__id=vlan_rel_eqpt.id)) | Q(id=vlan_rel_eqpt.ambiente.default_vrf_id) ) # Validate conflict of network if has intersect # of vrfs vrfs_intersect = list( set(vrfs_vlan_rel_ip) & set(vrfs_vlan_rel_eqpt)) if vrfs_intersect: netv4 = vrfs_vlan_rel_eqpt\ .networkipv4_set.filter() netv6 = vrfs_vlan_rel_eqpt\ .networkipv6_set.filter() netv4_eqpt = [IPNetwork(net.networkv4) for net in netv4] netv6_eqpt = [IPNetwork(net.networkv6) for net in netv6] netv4 = vrfs_vlan_rel_ip.networkipv4_set.filter() netv6 = vrfs_vlan_rel_ip.networkipv6_set.filter() netv4_ip = [IPNetwork(net.networkv4) for net in netv4] netv6_ip = [IPNetwork(net.networkv6) for net in netv6] verify_networks(netv4_ip, netv4_eqpt) verify_networks(netv6_ip, netv6_eqpt)
def check_filter_use(new_filter_id, env): from networkapi.equipamento.models import EquipamentoAmbiente from networkapi.ip.models import NetworkIPv4, NetworkIPv6 from networkapi.vlan.models import Vlan try: # Check existence of new filter new_fil = Filter.objects.get(pk=new_filter_id) except ObjectDoesNotExist: new_fil = None pass # Filters old_fil = env.filter if old_fil is not None: # Envs using old filter envs_old_filter = old_fil.ambiente_set.all() # Vlans in listed envs vlans = list() for env_old_filter in envs_old_filter: for vlan in env_old_filter.vlan_set.all(): vlans.append(vlan) # Nets in vlan nets_ipv4 = list() nets_ipv6 = list() for vlan in vlans: for net in vlan.networkipv4_set.all(): nets_ipv4.append({'net': net, 'vlan_env': vlan.ambiente}) for net in vlan.networkipv6_set.all(): nets_ipv6.append({'net': net, 'vlan_env': vlan.ambiente}) # Verify subnet ipv4 for i in range(0, len(nets_ipv4)): net = nets_ipv4[i].get('net') ip = '%s.%s.%s.%s/%s' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block) network_ip_verify = IPNetwork(ip) nets_ipv4_aux = clone(nets_ipv4) nets_ipv4_aux.remove(nets_ipv4[i]) if verify_subnet_and_equip(nets_ipv4_aux, network_ip_verify, 'v4', net, nets_ipv4[i].get('vlan_env')): env_aux_id = nets_ipv4[i].get('vlan_env').id if env.id == env_aux_id: raise CannotDissociateFilterError( old_fil.name, u'Filter %s cannot be dissociated, its in use.' % old_fil.name) # Verify subnet ipv6 for i in range(0, len(nets_ipv6)): net = nets_ipv6[i].get('net') ip = '%s:%s:%s:%s:%s:%s:%s:%s/%d' % ( net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block) network_ip_verify = IPNetwork(ip) nets_ipv6_aux = clone(nets_ipv6) nets_ipv6_aux.remove(nets_ipv6[i]) if verify_subnet_and_equip(nets_ipv6_aux, network_ip_verify, 'v6', net, nets_ipv6[i].get('vlan_env')): env_aux_id = nets_ipv6[i].get('vlan_env').id if env.id == env_aux_id: raise CannotDissociateFilterError( old_fil.name, u'Filter %s cannot be dissociated, its in use.' % old_fil.name) old_tp_equips = [ fet.equiptype.id for fet in old_fil.filterequiptype_set.all() ] if new_fil is not None: new_tp_equips = [ fet.equiptype.id for fet in new_fil.filterequiptype_set.all() ] else: new_tp_equips = [] # EquipTypes being excluded, check for these in environments diff_tp_equips = list(set(old_tp_equips) - set(new_tp_equips)) # Check equipments with type in diff, associated to this environment if len(diff_tp_equips) > 0: # Filter case 1 and 2 # Check for networks with same ip range nets_same_range = NetworkIPv4.objects.values( 'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(count=Count('id')).filter(count__gt=1) if len(nets_same_range) > 0: for net_gp in nets_same_range: nets_current_range = NetworkIPv4.objects.filter( oct1=net_gp['oct1'], oct2=net_gp['oct2'], oct3=net_gp['oct3'], oct4=net_gp['oct4'], block=net_gp['block']) envs_of_nets = [ net_crt.vlan.ambiente.id for net_crt in nets_current_range ] if env.id in envs_of_nets: eqas = EquipamentoAmbiente.objects.filter( equipamento__tipo_equipamento__in=diff_tp_equips, ambiente=env.id) equips_in_env = [eqa.equipamento.id for eqa in eqas] # Get other environments with these equips other_envs = [ eqa.ambiente.id for eqa in EquipamentoAmbiente.objects.filter( equipamento__in=equips_in_env, ambiente__in=envs_of_nets).exclude( ambiente=env.id) ] if len(other_envs) > 0: raise CannotDissociateFilterError( old_fil.name, u'Filter %s cannot be dissociated, its in use.' % old_fil.name) # Check for networks v6 with same ip range nets_same_range_v6 = NetworkIPv6.objects.values( 'block1', 'block2', 'block3', 'block4', 'block5', 'block6', 'block7', 'block8', 'block').annotate(count=Count('id')).filter(count__gt=1) if len(nets_same_range_v6) > 0: for net_gp in nets_same_range_v6: nets_current_range = NetworkIPv6.objects.filter( block1=net_gp['block1'], block2=net_gp['block2'], block3=net_gp['block3'], block4=net_gp['block4'], block5=net_gp['block5'], block6=net_gp['block6'], block7=net_gp['block7'], block8=net_gp['block8'], block=net_gp['block']) envs_of_nets = [ net_crt.vlan.ambiente.id for net_crt in nets_current_range ] if env.id in envs_of_nets: eqas = EquipamentoAmbiente.objects.filter( equipamento__tipo_equipamento__in=diff_tp_equips, ambiente=env.id) equips_in_env = [eqa.equipamento.id for eqa in eqas] # Get other environments with these equips other_envs = [ eqa.ambiente.id for eqa in EquipamentoAmbiente.objects.filter( equipamento__in=equips_in_env, ambiente__in=envs_of_nets).exclude( ambiente=env.id) ] if len(other_envs) > 0: raise CannotDissociateFilterError( old_fil.name, u'Filter %s cannot be dissociated, its in use.' % old_fil.name) # End of filter case 1 and 2 # Filter case 3 # Get vlans with same number vlans_same_number = Vlan.objects.values('num_vlan').annotate( count=Count('id')).filter(count__gt=1) if len(vlans_same_number) > 0: for vlan_gp in vlans_same_number: vlans_current_number = Vlan.objects.filter( num_vlan=vlan_gp['num_vlan']) envs_of_vlans = [ vlan.ambiente.id for vlan in vlans_current_number ] if env.id in envs_of_vlans: eqas = EquipamentoAmbiente.objects.filter( ambiente=env.id) equips_in_env = [eqa.equipamento.id for eqa in eqas] # Get other environments with these equips other_envs = [ eqa.ambiente.id for eqa in EquipamentoAmbiente.objects.filter( equipamento__in=equips_in_env, ambiente__in=envs_of_vlans).exclude( ambiente=env.id) ] if len(other_envs) > 0: raise CannotDissociateFilterError( old_fil.name, u'Filter %s cannot be dissociated, its in use.' % old_fil.name) env.filter = new_fil return env
def handle_post(self, request, user, *args, **kwargs): """Handles POST requests to edit an Network. URL: network/edit/ """ self.log.info('Edit an Network') 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) net_map = networkapi_map.get('net') if net_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 id_network = net_map.get('id_network') ip_type = net_map.get('ip_type') id_net_type = net_map.get('id_net_type') id_env_vip = net_map.get('id_env_vip') cluster_unit = net_map.get('cluster_unit') # Valid id_network if not is_valid_int_greater_zero_param(id_network): self.log.error( u'Parameter id_network is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_network', id_network) # Valid ip_type if not is_valid_int_param(ip_type): self.log.error( u'Parameter ip_type is invalid. Value: %s.', ip_type) raise InvalidValueError(None, 'ip_type', ip_type) list_choice = [0, 1] # Valid ip_type choice if int(ip_type) not in list_choice: self.log.error( u'Parameter ip_type is invalid. Value: %s.', ip_type) raise InvalidValueError(None, 'ip_type', ip_type) # Valid id_net_type if not is_valid_int_greater_zero_param(id_net_type): self.log.error( u'Parameter id_net_type is invalid. Value: %s.', id_net_type) raise InvalidValueError(None, 'id_net_type', id_net_type) # Valid id_env_vip if id_env_vip is not None: if not is_valid_int_greater_zero_param(id_env_vip): self.log.error( u'Parameter id_env_vip is invalid. Value: %s.', id_env_vip) raise InvalidValueError(None, 'id_env_vip', id_env_vip) # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION): raise UserNotAuthorizedError( None, u'User does not have permission to perform the operation.') # Business Rules if (id_env_vip is not None): id_env_vip = EnvironmentVip.get_by_pk(id_env_vip) id_net_type = TipoRede.get_by_pk(id_net_type) # New network_tyoe # EDIT NETWORK IP4 if int(ip_type) == 0: net = NetworkIPv4.get_by_pk(id_network) with distributedlock(LOCK_NETWORK_IPV4 % id_network): if id_env_vip is not None: if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id: network = IPNetwork( '%d.%d.%d.%d/%d' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block)) # Find all networks related to environment vip nets = NetworkIPv4.objects.filter( ambient_vip__id=id_env_vip.id) # Cast to API class networks = set([IPv4Network( '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets]) # If there is already a network with the same ip # range as related the environment vip if network in networks: raise NetworkIpAddressNotAvailableError( None, u'Unavailable address to create a NetworkIPv4.') net.edit_network_ipv4( user, id_net_type, id_env_vip, cluster_unit) # EDIT NETWORK IP6 else: net = NetworkIPv6.get_by_pk(id_network) with distributedlock(LOCK_NETWORK_IPV6 % id_network): if id_env_vip is not None: if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id: network = IPNetwork('%s:%s:%s:%s:%s:%s:%s:%s/%d' % ( net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block)) # Find all networks related to environment vip nets = NetworkIPv6.objects.filter( ambient_vip__id=id_env_vip.id) # Cast to API class networks = set([IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3, net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets]) # If there is already a network with the same # range ip as related the environment vip if net in networks: raise NetworkIpAddressNotAvailableError( None, u'Unavailable address to create a NetworkIPv6.') net.edit_network_ipv6(user, id_net_type, id_env_vip) # Delete vlan's cache # destroy_cache_function() return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)