def networkIPv4_deploy(request, network_id): '''Deploy network L3 configuration in the environment routers for network ipv4 Receives optional parameter equipments to specify what equipment should receive network configuration ''' networkipv4 = NetworkIPv4.get_by_pk(int(network_id)) environment = networkipv4.vlan.ambiente equipments_id_list = None if request.DATA is not None: equipments_id_list = request.DATA.get("equipments", None) equipment_list = [] if equipments_id_list is not None: if type(equipments_id_list) is not list: raise api_exceptions.ValidationException("equipments") for equip in equipments_id_list: try: int(equip) except ValueError, e: raise api_exceptions.ValidationException("equipments") #Check that equipments received as parameters are in correct vlan environment equipment_list = Equipamento.objects.filter( equipamentoambiente__ambiente = environment, id__in=equipments_id_list) log.info ("list = %s" % equipment_list) if len(equipment_list) != len(equipments_id_list): log.error("Error: equipments %s are not part of network environment." % equipments_id_list) raise exceptions.EquipmentIDNotInCorrectEnvException()
def test_alter_valid(self): mock = self.mock_network_alter_valid() response = self.client_autenticado().postXML( self.URL_ALTER, {self.XML_KEY_ALTER: mock}) valid_response(response) net = NetworkIPv4.get_by_pk(self.ID_NETWORK_IPV4_ALTER_VALID) self.valid_network_attr(mock, model_to_dict(net))
def create(self, ipv4_id, networkipv4_id): ipv4 = Ip.get_by_pk(ipv4_id) networkipv4 = NetworkIPv4.get_by_pk(networkipv4_id) if len(DHCPRelayIPv4.objects.filter(ipv4=ipv4, networkipv4=networkipv4)) > 0: raise exceptions.DHCPRelayAlreadyExistsError(ipv4_id, networkipv4_id) self.ipv4 = ipv4 self.networkipv4 = networkipv4
def deactivate_network(self, user, id): id_network, network_type = self.get_id_and_net_type(id) if not is_valid_int_greater_zero_param(id_network): self.log.error( u'The id network parameter is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_network', id_network) if not is_valid_version_ip(network_type, IP_VERSION): self.log.error( u'The type network parameter is invalid value: %s.', network_type) raise InvalidValueError(None, 'network_type', network_type) if network_type == self.NETWORK_TYPE_V4: net = NetworkIPv4.get_by_pk(id_network) if not self.is_active_netwok(net): raise NetworkInactiveError( message=error_messages.get(self.CODE_MESSAGE_INACTIVE_NETWORK)) command = NETWORKIPV4_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net = NetworkIPv4.get_by_pk(id_network) net.deactivate(user) else: net = NetworkIPv6.get_by_pk(id_network) if not self.is_active_netwok(net): raise NetworkInactiveError( message=error_messages.get(self.CODE_MESSAGE_INACTIVE_NETWORK)) command = NETWORKIPV6_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net.deactivate(user) return code, stdout, stderr
def networksIPv4_by_pk(request, network_id): """ Lists network ipv4. """ try: networkipv4_obj = NetworkIPv4.get_by_pk(network_id) serializer_options = NetworkIPv4Serializer(networkipv4_obj, many=False) return Response(serializer_options.data) except NetworkIPv4NotFoundError, exception: raise exceptions.InvalidNetworkIDException()
def deactivate_network(self, user, id): id_network, network_type = self.get_id_and_net_type(id) if not is_valid_int_greater_zero_param(id_network): self.log.error(u'The id network parameter is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_network', id_network) if not is_valid_version_ip(network_type, IP_VERSION): self.log.error(u'The type network parameter is invalid value: %s.', network_type) raise InvalidValueError(None, 'network_type', network_type) if not self.is_active_netwok(net): code = 0 stdout = 'Nothing to do. Network is not active.' stderr = '' else: if network_type == self.NETWORK_TYPE_V4: net = NetworkIPv4.get_by_pk(id_network) command = NETWORKIPV4_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net = NetworkIPv4.get_by_pk(id_network) net.deactivate(user) else: net = NetworkIPv6.get_by_pk(id_network) command = NETWORKIPV6_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net.deactivate(user) return code, stdout, stderr
def deactivate_network(self, user, id): id_network, network_type = self.get_id_and_net_type(id) if not is_valid_int_greater_zero_param(id_network): self.log.error( u'The id network parameter is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_network', id_network) if not is_valid_version_ip(network_type, IP_VERSION): self.log.error( u'The type network parameter is invalid value: %s.', network_type) raise InvalidValueError(None, 'network_type', network_type) if not self.is_active_netwok(net): code = 0 stdout = 'Nothing to do. Network is not active.' stderr = '' else: if network_type == self.NETWORK_TYPE_V4: net = NetworkIPv4.get_by_pk(id_network) command = NETWORKIPV4_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net = NetworkIPv4.get_by_pk(id_network) net.deactivate(user) else: net = NetworkIPv6.get_by_pk(id_network) command = NETWORKIPV6_REMOVE % int(id_network) code, stdout, stderr = exec_script(command) if code == 0: net.deactivate(user) return code, stdout, stderr
def networksIPv4_by_pk(request, network_id): '''Lists network ipv4 ''' try: networkIPv4_obj = NetworkIPv4.get_by_pk(network_id) serializer_options = NetworkIPv4Serializer( networkIPv4_obj, many=False ) return Response(serializer_options.data) except NetworkIPv4NotFoundError, exception: raise exceptions.InvalidNetworkIDException()
def activate_network(self, user, id): # id => ex: '55-v4' or '55-v6' value = id.split('-') if len(value) != 2: self.log.error( u'The id network parameter is invalid format: %s.', value) raise InvalidValueError(None, 'id_network', value) id_net = value[0] network_type = value[1] if not is_valid_int_greater_zero_param(id_net): self.log.error( u'The id network parameter is invalid. Value: %s.', id_net) raise InvalidValueError(None, 'id_network', id_net) if not is_valid_version_ip(network_type, IP_VERSION): self.log.error( u'The type network parameter is invalid value: %s.', network_type) raise InvalidValueError(None, 'network_type', network_type) if network_type == 'v4': # network_type = 'v4' # Make command command = NETWORKIPV4_CREATE % int(id_net) code, stdout, stderr = exec_script(command) if code == 0: # Change column 'active = 1' net = NetworkIPv4.get_by_pk(id_net) net.activate(user) else: # network_type = 'v6' # Make command command = NETWORKIPV6_CREATE % int(id_net) code, stdout, stderr = exec_script(command) if code == 0: # Change column 'active = 1' net = NetworkIPv6.get_by_pk(id_net) net.activate(user) return code, stdout, stderr
def inserir_equip(user, variablestochangecore, rede_id): ip = Ip() ip.descricao = None ip.oct1, ip.oct2, ip.oct3, ip.oct4 = str(variablestochangecore["IPCORE"]).split('.') equip = Equipamento.get_by_name(variablestochangecore["EQUIP_NAME"]) rede = NetworkIPv4.get_by_pk(rede_id) ip.save_ipv4(equip.id, user, rede) if ip.id is None: raise RackAplError (None, None, "Erro ao inserir os equipamentos") # Delete vlan's cache destroy_cache_function([rede.vlan_id]) list_id_equip = [] list_id_equip.append(equip.id) destroy_cache_function(list_id_equip, True) return 0
def inserir_equip(user, variablestochangecore, rede_id): ip = Ip() ip.descricao = None ip.oct1, ip.oct2, ip.oct3, ip.oct4 = str( variablestochangecore['IPCORE']).split('.') equip = Equipamento.get_by_name(variablestochangecore['EQUIP_NAME']) rede = NetworkIPv4.get_by_pk(rede_id) ip.save_ipv4(equip.id, user, rede) if ip.id is None: raise RackAplError(None, None, 'Erro ao inserir os equipamentos') # Delete vlan's cache destroy_cache_function([rede.vlan_id]) list_id_equip = [] list_id_equip.append(equip.id) destroy_cache_function(list_id_equip, True) return 0
def handle_get(self, request, user, *args, **kwargs): """Handles GET requests to list all network IPv4 by network ipv4 id. URLs: network/ipv4/id/id_rede4 """ 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 # Valid id access id_network = kwargs.get('id_rede4') if not is_valid_int_greater_zero_param(id_network): self.log.error(u'Parameter id_rede is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_rede4', id_network) # Business Rules network = NetworkIPv4.get_by_pk(id_network) network_map = dict() network_map['network'] = model_to_dict(network) # Return XML return self.response(dumps_networkapi(network_map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_get(self, request, user, *args, **kwargs): """Handles GET requests to list all network IPv4 by network ipv4 id. URLs: network/ipv4/id/id_rede4 """ 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 # Valid id access id_network = kwargs.get('id_rede4') if not is_valid_int_greater_zero_param(id_network): self.log.error( u'Parameter id_rede is invalid. Value: %s.', id_network) raise InvalidValueError(None, 'id_rede4', id_network) # Business Rules network = NetworkIPv4.get_by_pk(id_network) network_map = dict() network_map['network'] = model_to_dict(network) # Return XML return self.response(dumps_networkapi(network_map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def networkIPv4_deploy(request, network_id): """Deploy network L3 configuration in the environment routers for network ipv4 Receives optional parameter equipments to specify what equipment should receive network configuration """ log.debug("networkIPv4_deploy") networkipv4 = NetworkIPv4.get_by_pk(int(network_id)) environment = networkipv4.vlan.ambiente equipments_id_list = None if request.DATA is not None: equipments_id_list = request.DATA.get('equipments', None) if equipments_id_list is not None: if type(equipments_id_list) is not list: raise api_exceptions.ValidationException('equipments') for equip in equipments_id_list: try: int(equip) except ValueError: raise api_exceptions.ValidationException('equipments') # Check that equipments received as parameters are in correct vlan # environment equipment_list = Equipamento.objects.filter( equipamentoambiente__ambiente=environment, id__in=equipments_id_list) log.info('list = %s' % equipment_list) if len(equipment_list) != len(equipments_id_list): log.error( 'Error: equipments %s are not part of network environment.' % equipments_id_list) raise exceptions.EquipmentIDNotInCorrectEnvException() else: # TODO GET network routers equipment_list = Equipamento.objects.filter( ipequipamento__ip__networkipv4=networkipv4, equipamentoambiente__ambiente=networkipv4.vlan.ambiente, equipamentoambiente__is_router=1).distinct() if len(equipment_list) == 0: raise exceptions.NoEnvironmentRoutersFoundException() # Check permission to configure equipments for equip in equipment_list: # User permission if not has_perm(request.user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip.id, AdminPermission.EQUIP_WRITE_OPERATION): log.error( u'User does not have permission to perform the operation.') raise PermissionDenied( 'No permission to configure equipment %s-%s' % (equip.id, equip.nome)) if all_equipments_are_in_maintenance(equipment_list): raise AllEquipmentsAreInMaintenanceException() try: # deploy network configuration if request.method == 'POST': returned_data = facade.deploy_networkIPv4_configuration( request.user, networkipv4, equipment_list) elif request.method == 'DELETE': returned_data = facade.remove_deploy_networkIPv4_configuration( request.user, networkipv4, equipment_list) return Response(returned_data) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
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_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)
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_get(self, request, user, *args, **kwargs): """Handles GET requests to list all network IPv4 by network ipv4 id. URLs: ip/id_network_ipv4/id_rede """ try: # Commons Validations # User permission if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Valid id access id_network = kwargs.get('id_rede') if not is_valid_int_greater_zero_param(id_network): raise InvalidValueError(None, 'id_rede', id_network) # Business Rules NetworkIPv4.get_by_pk(id_network) ips = Ip.list_by_network(id_network) try: len(ips) except Exception, e: raise InvalidValueError(None, 'id_rede', id_network) if ips is None or len(ips) <= 0: raise IpNotFoundError(305, id_network) EquipIps = [] mapa = dict() # lista = [] try: for ip in ips: EquipIps = [] equipsIp = IpEquipamento.list_by_ip(ip.id) for eIp in equipsIp: EquipIps.append(eIp) mapa[ip.id] = EquipIps # lista.append(mapa) except IpEquipmentNotFoundError: EquipIps.append(None) except IpError: EquipIps.append(None) network_map = dict() list_ips = [] for ip in ips: lequips = [] ip_maps = dict() ip_maps = model_to_dict(ip) for equip in mapa.get(ip.id): equip = Equipamento.get_by_pk(equip.equipamento.id) lequips.append(model_to_dict(equip)) ip_maps['equipamento'] = lequips list_ips.append(ip_maps) network_map['ips'] = list_ips # Return XML return self.response(dumps_networkapi(network_map))
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 networkIPv4_deploy(request, network_id): """Deploy network L3 configuration in the environment routers for network ipv4 Receives optional parameter equipments to specify what equipment should receive network configuration """ networkipv4 = NetworkIPv4.get_by_pk(int(network_id)) environment = networkipv4.vlan.ambiente equipments_id_list = None if request.DATA is not None: equipments_id_list = request.DATA.get('equipments', None) equipment_list = [] if equipments_id_list is not None: if type(equipments_id_list) is not list: raise api_exceptions.ValidationException('equipments') for equip in equipments_id_list: try: int(equip) except ValueError: raise api_exceptions.ValidationException('equipments') # Check that equipments received as parameters are in correct vlan # environment equipment_list = Equipamento.objects.filter( equipamentoambiente__ambiente=environment, id__in=equipments_id_list) log.info('list = %s' % equipment_list) if len(equipment_list) != len(equipments_id_list): log.error( 'Error: equipments %s are not part of network environment.' % equipments_id_list) raise exceptions.EquipmentIDNotInCorrectEnvException() else: # TODO GET network routers equipment_list = Equipamento.objects.filter( ipequipamento__ip__networkipv4=networkipv4, equipamentoambiente__ambiente=networkipv4.vlan.ambiente, equipamentoambiente__is_router=1).distinct() if len(equipment_list) == 0: raise exceptions.NoEnvironmentRoutersFoundException() # Check permission to configure equipments for equip in equipment_list: # User permission if not has_perm(request.user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip.id, AdminPermission.EQUIP_WRITE_OPERATION): log.error(u'User does not have permission to perform the operation.') raise PermissionDenied( 'No permission to configure equipment %s-%s' % (equip.id, equip.nome)) if all_equipments_are_in_maintenance(equipment_list): raise AllEquipmentsAreInMaintenanceException() try: # deploy network configuration if request.method == 'POST': returned_data = facade.deploy_networkIPv4_configuration( request.user, networkipv4, equipment_list) elif request.method == 'DELETE': returned_data = facade.remove_deploy_networkIPv4_configuration( request.user, networkipv4, equipment_list) return Response(returned_data) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
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') # 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.select_related().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) # 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.select_related().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)