def get_dict_v4_to_use_in_configuration_deploy(user, networkipv4, equipment_list): """Generate dictionary with vlan an IP information to be used to generate template dict for equipment configuration Args: networkipv4 NetworkIPv4 object equipment_list: Equipamento objects list Returns: 2-dimension dictionary with equipments information for template rendering """ try: gateway_ip = Ip.get_by_octs_and_net(networkipv4.oct1, networkipv4.oct2, networkipv4.oct3, networkipv4.oct4 + 1, networkipv4) except IpNotFoundError: log.error('Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.') raise exceptions.IncorrectRedundantGatewayRegistryException() ips = IpEquipamento.objects.filter( ip=gateway_ip, equipamento__in=equipment_list) if len(ips) != len(equipment_list): log.error('Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.') raise exceptions.IncorrectRedundantGatewayRegistryException() dict_ips = dict() if networkipv4.vlan.vrf is not None and networkipv4.vlan.vrf is not '': dict_ips['vrf'] = networkipv4.vlan.vrf elif networkipv4.vlan.ambiente.vrf is not None and networkipv4.vlan.ambiente.vrf is not '': dict_ips['vrf'] = networkipv4.vlan.ambiente.vrf # DHCPRelay list dhcprelay_list = DHCPRelayIPv4.objects.filter(networkipv4=networkipv4) if len(dhcprelay_list) > 0: dict_ips['dhcprelay_list'] = [] for dhcprelay in dhcprelay_list: ipv4 = '%s.%s.%s.%s' % ( dhcprelay.ipv4.oct1, dhcprelay.ipv4.oct2, dhcprelay.ipv4.oct3, dhcprelay.ipv4.oct4) dict_ips['dhcprelay_list'].append(ipv4) dict_ips['gateway'] = '%d.%d.%d.%d' % ( gateway_ip.oct1, gateway_ip.oct2, gateway_ip.oct3, gateway_ip.oct4) dict_ips['ip_version'] = 'IPV4' dict_ips['equipments'] = dict() dict_ips['vlan_num'] = networkipv4.vlan.num_vlan dict_ips['vlan_name'] = networkipv4.vlan.nome dict_ips['cidr_block'] = networkipv4.block dict_ips['mask'] = '%d.%d.%d.%d' % ( networkipv4.mask_oct1, networkipv4.mask_oct2, networkipv4.mask_oct3, networkipv4.mask_oct4) dict_ips['wildmask'] = '%d.%d.%d.%d' % ( 255 - networkipv4.mask_oct1, 255 - networkipv4.mask_oct2, 255 - networkipv4.mask_oct3, 255 - networkipv4.mask_oct4) if _has_active_network_in_vlan(networkipv4.vlan): dict_ips['first_network'] = False else: dict_ips['first_network'] = True # Check IPs for routers when there are multiple gateways if len(equipment_list) > 1: dict_ips['gateway_redundancy'] = True equip_number = 0 for equipment in equipment_list: ip_equip = IpEquipamento.objects.filter(equipamento=equipment, ip__networkipv4=networkipv4).exclude(ip=gateway_ip)\ .select_related('ip') if ip_equip == []: log.error('Error: Equipment IPs not correctly registered. \ In case of multiple gateways, they should have an IP other than the gateway registered.') raise exceptions.IncorrectNetworkRouterRegistryException() ip = ip_equip[0].ip dict_ips[equipment] = dict() dict_ips[equipment]['ip'] = '%s.%s.%s.%s' % ( ip.oct1, ip.oct2, ip.oct3, ip.oct4) dict_ips[equipment]['prio'] = 100 + equip_number equip_number += 1 else: dict_ips['gateway_redundancy'] = False dict_ips[equipment_list[0]] = dict() dict_ips[equipment_list[0]]['ip'] = dict_ips['gateway'] dict_ips[equipment_list[0]]['prio'] = 100 return dict_ips
def get_dict_v4_to_use_in_configuration_deploy(user, networkipv4, equipment_list): """Generate dictionary with vlan an IP information to be used to generate template dict for equipment configuration Args: networkipv4 NetworkIPv4 object equipment_list: Equipamento objects list Returns: 2-dimension dictionary with equipments information for template rendering """ try: gateway_ip = Ip.get_by_octs_and_net(networkipv4.oct1, networkipv4.oct2, networkipv4.oct3, networkipv4.oct4 + 1, networkipv4) except IpNotFoundError: log.error('Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.' ) raise exceptions.IncorrectRedundantGatewayRegistryException() ips = IpEquipamento.objects.filter(ip=gateway_ip, equipamento__in=equipment_list) if len(ips) != len(equipment_list): log.error('Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.' ) raise exceptions.IncorrectRedundantGatewayRegistryException() dict_ips = dict() if networkipv4.vlan.vrf is not None and networkipv4.vlan.vrf is not '': dict_ips['vrf'] = networkipv4.vlan.vrf elif networkipv4.vlan.ambiente.vrf is not None and networkipv4.vlan.ambiente.vrf is not '': dict_ips['vrf'] = networkipv4.vlan.ambiente.vrf # DHCPRelay list dhcprelay_list = DHCPRelayIPv4.objects.filter(networkipv4=networkipv4) if len(dhcprelay_list) > 0: dict_ips['dhcprelay_list'] = [] for dhcprelay in dhcprelay_list: ipv4 = '%s.%s.%s.%s' % (dhcprelay.ipv4.oct1, dhcprelay.ipv4.oct2, dhcprelay.ipv4.oct3, dhcprelay.ipv4.oct4) dict_ips['dhcprelay_list'].append(ipv4) dict_ips['gateway'] = '%d.%d.%d.%d' % (gateway_ip.oct1, gateway_ip.oct2, gateway_ip.oct3, gateway_ip.oct4) dict_ips['ip_version'] = 'IPV4' dict_ips['equipments'] = dict() dict_ips['vlan_num'] = networkipv4.vlan.num_vlan dict_ips['vlan_name'] = networkipv4.vlan.nome dict_ips['cidr_block'] = networkipv4.block dict_ips['mask'] = '%d.%d.%d.%d' % ( networkipv4.mask_oct1, networkipv4.mask_oct2, networkipv4.mask_oct3, networkipv4.mask_oct4) dict_ips['wildmask'] = '%d.%d.%d.%d' % ( 255 - networkipv4.mask_oct1, 255 - networkipv4.mask_oct2, 255 - networkipv4.mask_oct3, 255 - networkipv4.mask_oct4) if _has_active_network_in_vlan(networkipv4.vlan): dict_ips['first_network'] = False else: dict_ips['first_network'] = True # Check IPs for routers when there are multiple gateways if len(equipment_list) > 1: dict_ips['gateway_redundancy'] = True equip_number = 0 for equipment in equipment_list: ip_equip = IpEquipamento.objects.filter(equipamento=equipment, ip__networkipv4=networkipv4).exclude(ip=gateway_ip)\ .select_related('ip') if ip_equip == []: log.error('Error: Equipment IPs not correctly registered. \ In case of multiple gateways, they should have an IP other than the gateway registered.' ) raise exceptions.IncorrectNetworkRouterRegistryException() ip = ip_equip[0].ip dict_ips[equipment] = dict() dict_ips[equipment]['ip'] = '%s.%s.%s.%s' % (ip.oct1, ip.oct2, ip.oct3, ip.oct4) dict_ips[equipment]['prio'] = 100 + equip_number equip_number += 1 else: dict_ips['gateway_redundancy'] = False dict_ips[equipment_list[0]] = dict() dict_ips[equipment_list[0]]['ip'] = dict_ips['gateway'] dict_ips[equipment_list[0]]['prio'] = 100 return dict_ips
def handle_post(self, request, user, *args, **kwargs): '''Handles POST requests to add an IP and associate it to an equipment. URL: ipv4/save/ ''' self.log.info('Add an IP and associate it 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 equip_id = ip_map.get('id_equip') network_ipv4_id = ip_map.get('id_net') description = ip_map.get('descricao') ip4 = ip_map.get('ip4') # 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) # Valid ip size if not is_valid_string_maxsize(ip4, 15): self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4) raise InvalidValueError(None, 'ip4', ip4) # Description can NOT be greater than 100 if description is not None: if not is_valid_string_maxsize(description, 100) or not is_valid_string_minsize(description, 3): self.log.error( u'Parameter description is invalid. Value: %s.', description) raise InvalidValueError(None, 'description', description) # 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 # New IP ip = Ip() net = NetworkIPv4.get_by_pk(network_ipv4_id) with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id): # se Houver erro no ip informado para retorna-lo na mensagem ip_error = ip4 # verificação se foi passado algo errado no ip ip4 = ip4.split(".") for oct in ip4: if not is_valid_int_param(oct): raise InvalidValueError(None, 'ip4', ip_error) #raise IndexError # Ip passado de forma invalida if len(ip4) is not 4: raise IndexError ip.descricao = description ip.oct1 = ip4[0] ip.oct2 = ip4[1] ip.oct3 = ip4[2] ip.oct4 = ip4[3] 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) if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two: flag_vlan_error = True ## 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 ip.save_ipv4(equip_id, user, net) list_ip = [] lequips = [] if ip.id is None: ip = Ip.get_by_octs_and_net( ip.oct1, ip.oct2, ip.oct3, ip.oct4, net.id) equips = IpEquipamento.list_by_ip(ip.id) ip_maps = dict() ip_maps['id'] = ip.id ip_maps['oct1'] = ip.oct1 ip_maps['oct2'] = ip.oct2 ip_maps['oct3'] = ip.oct3 ip_maps['oct4'] = ip.oct4 ip_maps['descricao'] = ip.descricao list_id_equip = [] for equip in equips: list_id_equip.append(equip.equipamento.id) equip = Equipamento.get_by_pk(equip.equipamento.id) lequips.append(model_to_dict(equip)) ip_maps['equipamento'] = lequips list_ip.append(ip_maps) network_map = dict() network_map['ip'] = list_ip # Delete vlan's cache destroy_cache_function([net.vlan_id]) # Delete equipment's cache destroy_cache_function(list_id_equip, True) return self.response(dumps_networkapi(network_map)) except IpRangeAlreadyAssociation, e: return self.response_error(347)
def handle_post(self, request, user, *args, **kwargs): '''Handles POST requests to add an IP and associate it to an equipment. URL: ipv4/save/ ''' self.log.info('Add an IP and associate it 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 equip_id = ip_map.get('id_equip') network_ipv4_id = ip_map.get('id_net') description = ip_map.get('descricao') ip4 = ip_map.get('ip4') # 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) # Valid ip size if not is_valid_string_maxsize(ip4, 15): self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4) raise InvalidValueError(None, 'ip4', ip4) # Description can NOT be greater than 100 if description is not None: if not is_valid_string_maxsize( description, 100) or not is_valid_string_minsize( description, 3): self.log.error( u'Parameter description is invalid. Value: %s.', description) raise InvalidValueError(None, 'description', description) # 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 # New IP ip = Ip() net = NetworkIPv4.get_by_pk(network_ipv4_id) with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id): # se Houver erro no ip informado para retorna-lo na mensagem ip_error = ip4 # verificação se foi passado algo errado no ip ip4 = ip4.split(".") for oct in ip4: if not is_valid_int_param(oct): raise InvalidValueError(None, 'ip4', ip_error) #raise IndexError # Ip passado de forma invalida if len(ip4) is not 4: raise IndexError ip.descricao = description ip.oct1 = ip4[0] ip.oct2 = ip4[1] ip.oct3 = ip4[2] ip.oct4 = ip4[3] 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) if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two: flag_vlan_error = True ## 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 ip.save_ipv4(equip_id, user, net) list_ip = [] lequips = [] if ip.id is None: ip = Ip.get_by_octs_and_net(ip.oct1, ip.oct2, ip.oct3, ip.oct4, net.id) equips = IpEquipamento.list_by_ip(ip.id) ip_maps = dict() ip_maps['id'] = ip.id ip_maps['oct1'] = ip.oct1 ip_maps['oct2'] = ip.oct2 ip_maps['oct3'] = ip.oct3 ip_maps['oct4'] = ip.oct4 ip_maps['descricao'] = ip.descricao list_id_equip = [] for equip in equips: list_id_equip.append(equip.equipamento.id) equip = Equipamento.get_by_pk(equip.equipamento.id) lequips.append(model_to_dict(equip)) ip_maps['equipamento'] = lequips list_ip.append(ip_maps) network_map = dict() network_map['ip'] = list_ip # Delete vlan's cache destroy_cache_function([net.vlan_id]) # Delete equipment's cache destroy_cache_function(list_id_equip, True) return self.response(dumps_networkapi(network_map)) except IpRangeAlreadyAssociation, e: return self.response_error(347)
def get_dict_v4_to_use_in_configuration_deploy(user, networkipv4, equipment_list): '''Generate dictionary with vlan an IP information to be used to generate template dict for equipment configuration Args: networkipv4 NetworkIPv4 object equipment_list: Equipamento objects list Returns: 2-dimension dictionary with equipments information for template rendering ''' try: gateway_ip = Ip.get_by_octs_and_net(networkipv4.oct1, networkipv4.oct2, networkipv4.oct3, networkipv4.oct4+1, networkipv4) except IpNotFoundError: log.error("Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.") raise exceptions.IncorrectRedundantGatewayRegistryException() ips = IpEquipamento.objects.filter(ip=gateway_ip, equipamento__in=equipment_list) if len(ips) != len(equipment_list): log.error("Equipment IPs not correctly registered. \ Router equipments should have first IP of network allocated for them.") raise exceptions.IncorrectRedundantGatewayRegistryException() dict_ips = dict() if networkipv4.vlan.vrf is not None and networkipv4.vlan.vrf is not '': dict_ips["vrf"] = networkipv4.vlan.vrf elif networkipv4.vlan.ambiente.vrf is not None and networkipv4.vlan.ambiente.vrf is not '': dict_ips["vrf"] = networkipv4.vlan.ambiente.vrf dict_ips["gateway"] = "%d.%d.%d.%d" % (gateway_ip.oct1, gateway_ip.oct2, gateway_ip.oct3, gateway_ip.oct4) dict_ips["ip_version"] = "IPV4" dict_ips["equipments"] = dict() dict_ips["vlan_num"] = networkipv4.vlan.num_vlan dict_ips["vlan_name"] = networkipv4.vlan.nome dict_ips["cidr_block"] = networkipv4.block dict_ips["mask"] = "%d.%d.%d.%d" % (networkipv4.mask_oct1, networkipv4.mask_oct2, networkipv4.mask_oct3, networkipv4.mask_oct4) dict_ips["wildmask"] = "%d.%d.%d.%d" % (255-networkipv4.mask_oct1, 255-networkipv4.mask_oct2, 255-networkipv4.mask_oct3, 255-networkipv4.mask_oct4) if _has_active_network_in_vlan(networkipv4.vlan): dict_ips["first_network"] = False else: dict_ips["first_network"] = True #Check IPs for routers when there are multiple gateways if len(equipment_list) > 1: dict_ips["gateway_redundancy"] = True equip_number = 0 for equipment in equipment_list: ip_equip = IpEquipamento.objects.filter(equipamento=equipment, ip__networkipv4=networkipv4).exclude(ip=gateway_ip)\ .select_related('ip') if ip_equip == []: log.error("Error: Equipment IPs not correctly registered. \ In case of multiple gateways, they should have an IP other than the gateway registered.") raise exceptions.IncorrectNetworkRouterRegistryException ip = ip_equip[0].ip dict_ips[equipment] = dict() dict_ips[equipment]["ip"] = "%s.%s.%s.%s" % (ip.oct1, ip.oct2, ip.oct3, ip.oct4) dict_ips[equipment]["prio"] = 100+equip_number equip_number += 1 else: dict_ips["gateway_redundancy"] = False dict_ips[equipment_list[0]] = dict() dict_ips[equipment_list[0]]["ip"] = dict_ips["gateway"] dict_ips[equipment_list[0]]["prio"] = 100 return dict_ips