def deploy_networkIPv6_configuration(user, networkipv6, equipment_list): '''Loads template for creating Network IPv6 equipment configuration, creates file and apply config. Args: NetworkIPv6 object Equipamento objects list Returns: List with status of equipments output ''' data = dict() #lock network id to prevent multiple requests to same id with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id): with distributedlock(LOCK_VLAN % networkipv6.vlan.id): if networkipv6.active == 1: data["output"] = "Network already active. Nothing to do." return data #load dict with all equipment attributes dict_ips = get_dict_v6_to_use_in_configuration_deploy(user, networkipv6, equipment_list) status_deploy = dict() #TODO implement threads for equipment in equipment_list: #generate config file file_to_deploy = _generate_config_file(dict_ips, equipment, TEMPLATE_NETWORKv6_ACTIVATE) #deploy config file in equipments lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % (equipment.id) status_deploy[equipment.id] = deploy_config_in_equipment_synchronous(file_to_deploy, equipment, lockvar) networkipv6.activate(user) transaction.commit() if networkipv6.vlan.ativada == 0: networkipv6.vlan.activate(user) return status_deploy
def create_lock(objects, lock_name): """Create locks for list of objects""" locks_list = list() for obj in objects: if isinstance(obj, dict): lock = distributedlock(lock_name % obj['id']) else: lock = distributedlock(lock_name % obj) lock.__enter__() locks_list.append(lock) return locks_list
def remove_deploy_networkIPv6_configuration(user, networkipv6, equipment_list): """Loads template for removing Network IPv6 equipment configuration, creates file and apply config. Args: NetworkIPv6 object Equipamento objects list Returns: List with status of equipments output """ data = dict() # lock network id to prevent multiple requests to same id with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id): with distributedlock(LOCK_VLAN % networkipv6.vlan.id): if networkipv6.active == 0: data['output'] = 'Network already not active. Nothing to do.' return data # load dict with all equipment attributes dict_ips = get_dict_v6_to_use_in_configuration_deploy( user, networkipv6, equipment_list) status_deploy = dict() # TODO implement threads for equipment in equipment_list: # generate config file file_to_deploy = _generate_config_file( dict_ips, equipment, TEMPLATE_NETWORKv6_DEACTIVATE) # deploy config file in equipments lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % ( equipment.id) status_deploy[ equipment.id] = deploy_config_in_equipment_synchronous( file_to_deploy, equipment, lockvar) networkipv6.deactivate(user) transaction.commit() if networkipv6.vlan.ativada == 1: # if there are no other networks active in vlan, remove int # vlan if not _has_active_network_in_vlan(networkipv6.vlan): # remove int vlan for equipment in equipment_list: if equipment.maintenance is not True: status_deploy[equipment.id] += _remove_svi( equipment, networkipv6.vlan.num_vlan) networkipv6.vlan.remove(user) return status_deploy
def remove_deploy_networkIPv6_configuration(user, networkipv6, equipment_list): """Loads template for removing Network IPv6 equipment configuration, creates file and apply config. Args: NetworkIPv6 object Equipamento objects list Returns: List with status of equipments output """ data = dict() # lock network id to prevent multiple requests to same id with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id): with distributedlock(LOCK_VLAN % networkipv6.vlan.id): if networkipv6.active == 0: data['output'] = 'Network already not active. Nothing to do.' return data # load dict with all equipment attributes dict_ips = get_dict_v6_to_use_in_configuration_deploy( user, networkipv6, equipment_list) status_deploy = dict() # TODO implement threads for equipment in equipment_list: # generate config file file_to_deploy = _generate_config_file( dict_ips, equipment, TEMPLATE_NETWORKv6_DEACTIVATE) # deploy config file in equipments lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % ( equipment.id) status_deploy[equipment.id] = deploy_config_in_equipment_synchronous( file_to_deploy, equipment, lockvar) networkipv6.deactivate(user) transaction.commit() if networkipv6.vlan.ativada == 1: # if there are no other networks active in vlan, remove int # vlan if not _has_active_network_in_vlan(networkipv6.vlan): # remove int vlan for equipment in equipment_list: if equipment.maintenance is not True: status_deploy[ equipment.id] += _remove_svi(equipment, networkipv6.vlan.num_vlan) networkipv6.vlan.remove(user) return status_deploy
def handle_put(self, request, user, *args, **kwargs): '''Trata as requisições de PUT para inserir o relacionamento entre IP e Equipamento. URL: ip/<id_ip>/equipamento/<id_equipamento>/$ ''' try: ip_id = kwargs.get('id_ip') equip_id = kwargs.get('id_equipamento') if not is_valid_int_greater_zero_param(ip_id): self.log.error( u'The ip_id parameter is not a valid value: %s.', ip_id) raise InvalidValueError(None, 'ip_id', ip_id) if not is_valid_int_greater_zero_param(equip_id): self.log.error( u'The equip_id parameter is not a valid value: %s.', equip_id) raise InvalidValueError(None, 'equip_id', equip_id) Ip.get_by_pk(ip_id) with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)): ip_equipment = insert_ip_equipment(ip_id, equip_id, user) ipequipamento_map = dict() ipequipamento_map['id'] = ip_equipment.id map = dict() map['ip_equipamento'] = ipequipamento_map return self.response(dumps_networkapi(map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def deploy_config_in_equipment_synchronous(rel_filename, equipment, lockvar, tftpserver=None, equipment_access=None): '''Apply configuration file on equipment Args: rel_filename: relative file path from TFTPBOOT_FILES_PATH to apply in equipment equipment: networkapi.equipamento.Equipamento() or Equipamento().id lockvar: distributed lock variable to use when applying config to equipment equipment_access: networkapi.equipamento.EquipamentoAcesso() to use tftpserver: source TFTP server address Returns: equipment output Raises: ''' #validate filename path = os.path.abspath(TFTPBOOT_FILES_PATH+rel_filename) if not path.startswith(TFTPBOOT_FILES_PATH): raise exceptions.InvalidFilenameException(rel_filename) if type(equipment) is int: equipment = Equipamento.get_by_pk(equipment) elif type(equipment) is Equipamento: pass else: log.error("Invalid data for equipment") raise api_exceptions.NetworkAPIException() with distributedlock(lockvar): return __applyConfig(equipment, rel_filename, equipment_access, tftpserver)
def set_cache_search_with_list(prefix, search, data, timeout=DEFAULT_CACHE_TIMEOUT): if cache_enabled(): with distributedlock(prefix): try: search_md5 = hashlib.md5(str(search)).hexdigest() key = prefix + search_md5 djangocache.set(key, data, timeout) cached_search_md5_list = get_cache(prefix) if not cached_search_md5_list: cached_search_md5_list = [] if search_md5 not in cached_search_md5_list: cached_search_md5_list.append(search_md5) log.debug("Caching key %s in list %s with timeout %s..." % (key, prefix, timeout)) key = prefix djangocache.set(key, cached_search_md5_list, timeout) except Exception as e: log.error(e)
def handle_delete(self, request, user, *args, **kwargs): """Treat DELETE requests to remove Group User. URL: ugroup/<id_ugroup>/ """ try: self.log.info('Remove Group User') # User permission if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_ugroup = kwargs.get('id_ugroup') # Valid Group User ID if not is_valid_int_greater_zero_param(id_ugroup): self.log.error( u'The id_ugroup parameter is not a valid value: %s.', id_ugroup) raise InvalidValueError(None, 'id_ugroup', id_ugroup) # Find Group User by ID to check if it exist ugroup = UGrupo.get_by_pk(id_ugroup) with distributedlock(LOCK_GROUP_USER % id_ugroup): ugroup.delete() return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Trata as requisições de DELETE para remover uma associação entre um Equipamento e um Grupo. URL: /equipamentogrupo/equipamento/<id_equip>/egrupo/<id_egrupo>/ """ try: equip_id = kwargs.get('id_equip') if not is_valid_int_greater_zero_param(equip_id): self.log.error( u'The equip_id parameter is not a valid value: %s.', equip_id) raise InvalidValueError(None, 'equip_id', equip_id) egroup_id = kwargs.get('id_egrupo') if not is_valid_int_greater_zero_param(egroup_id): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup_id) raise InvalidValueError(None, 'egroup_id', egroup_id) Equipamento.get_by_pk(equip_id) EGrupo.get_by_pk(egroup_id) if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, equip_id, AdminPermission.EQUIP_WRITE_OPERATION): return self.not_authorized() with distributedlock(LOCK_EQUIPMENT_GROUP % egroup_id): EquipamentoGrupo.remove(user, equip_id, egroup_id) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Trata as requisições de DELETE para remover direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/<id_direito>/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id, False): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) DireitosGrupoEquipamento.get_by_pk(right_id) with distributedlock(LOCK_GROUP_RIGHTS % right_id): DireitosGrupoEquipamento.remove(user, right_id) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def create_dhcprelayIPv6_object(user, ipv6_id, networkipv6_id): with distributedlock(LOCK_DCHCPv6_NET % networkipv6_id): dhcprelay_obj = DHCPRelayIPv6() dhcprelay_obj.create(ipv6_id, networkipv6_id) dhcprelay_obj.save() return dhcprelay_obj
def handle_put(self, request, user, *args, **kwargs): """Treat PUT requests to edit Access Type. URL: /tipoacesso/<id_tipo_acesso>/ """ try: if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error(u"User does not have permission to perform the operation.") raise UserNotAuthorizedError(None) # Valid Access Type ID tipo_acesso_id = kwargs.get("id_tipo_acesso") if not is_valid_int_greater_zero_param(tipo_acesso_id): self.log.error(u"The tipo_acesso_id parameter is not a valid value: %s.", tipo_acesso_id) raise InvalidValueError(None, "tipo_acesso_id", tipo_acesso_id) xml_map, attrs_map = loads(request.raw_post_data) networkapi_map = xml_map.get("networkapi") if networkapi_map is None: return self.response_error(3, u"There is no networkapi tag in request XML.") tipo_acesso_map = networkapi_map.get("tipo_acesso") if tipo_acesso_map is None: return self.response_error(3, u"There is no tipo_acesso tag in request XML.") # Valid protocol protocol = tipo_acesso_map.get("protocolo") if ( not is_valid_string_minsize(protocol, 3) or not is_valid_string_maxsize(protocol, 45) or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$") ): self.log.error(u"Parameter protocol is invalid. Value: %s", protocol) raise InvalidValueError(None, "protocol", protocol) # Verify existence tpa = TipoAcesso.get_by_pk(tipo_acesso_id) tpa.protocolo = protocol try: if len(TipoAcesso.objects.filter(protocolo__iexact=protocol).exclude(id=tpa.id)) > 0: raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol) except TipoAcesso.DoesNotExist: pass with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id): try: # save access type tpa.save(user) except Exception, e: self.log.error(u"Failed to update TipoAcesso.") raise TipoAcessoError(e, u"Failed to update TipoAcesso.") return self.response(dumps_networkapi({}))
def handle_delete(self, request, user, *args, **kwargs): """Treat DELETE requests to remove IP and Equipment relationship. URL: ip/<id_ip>/equipamento/<id_equipamento>/$ """ try: ip_id = kwargs.get('id_ip') equip_id = kwargs.get('id_equipamento') if not is_valid_int_greater_zero_param(ip_id): self.log.error( u'The ip_id parameter is not a valid value: %s.', ip_id) raise InvalidValueError(None, 'ip_id', ip_id) if not is_valid_int_greater_zero_param(equip_id): self.log.error( u'The equip_id parameter is not a valid value: %s.', equip_id) raise InvalidValueError(None, 'equip_id', equip_id) Ip.get_by_pk(ip_id) Equipamento.get_by_pk(equip_id) with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)): ipv4 = Ip.get_by_pk(ip_id) equipament = Equipamento.get_by_pk(equip_id) # Delete vlan's cache destroy_cache_function([ipv4]) # delete equipment's cache destroy_cache_function([equip_id], True) server_pool_member_list = ServerPoolMember.objects.filter( ip=ipv4) if server_pool_member_list.count() != 0: # IP associated with Server Pool server_pool_name_list = set() for member in server_pool_member_list: item = '{}: {}'.format( member.server_pool.id, member.server_pool.identifier) server_pool_name_list.add(item) server_pool_name_list = list(server_pool_name_list) server_pool_identifiers = ', '.join(server_pool_name_list) raise IpCantRemoveFromServerPool({'ip': mount_ipv4_string(ipv4), 'equip_name': equipament.nome, 'server_pool_identifiers': server_pool_identifiers}, 'Ipv4 não pode ser disassociado do equipamento %s porque ele está sendo utilizando nos Server Pools (id:identifier) %s' % (equipament.nome, server_pool_identifiers)) remove_ip_equipment(ip_id, equip_id, user) return self.response(dumps_networkapi({})) except IpCantRemoveFromServerPool, e: return self.response_error(385, e.cause.get('ip'), e.cause.get('equip_name'), e.cause.get('server_pool_identifiers'))
def handle_delete(self, request, user, *args, **kwargs): """Treat DELETE requests to dissociate User and Group. URL: usergroup/user/<id_user>/ugroup/<id_group>/dissociate/ """ try: self.log.info('Dissociate User and Group.') # User permission if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_user = kwargs.get('id_user') id_group = kwargs.get('id_group') # Valid ID User if not is_valid_int_greater_zero_param(id_user): self.log.error( u'The id_user parameter is not a valid value: %s.', id_user) raise InvalidValueError(None, 'id_user', id_user) # Valid ID Group if not is_valid_int_greater_zero_param(id_group): self.log.error( u'The id_group parameter is not a valid value: %s.', id_group) raise InvalidValueError(None, 'id_group', id_group) # Find User by ID to check if it exist Usuario.get_by_pk(id_user) # Find Group by ID to check if it exist UGrupo.get_by_pk(id_group) # Find UserGroup by ID to check if it exist user_group = UsuarioGrupo.get_by_user_group(id_user, id_group) with distributedlock(LOCK_USER_GROUP % (id_user, id_group)): try: # remove UserGroup user_group.delete() except Exception, e: self.log.error(u'Failed to remove the UserGroup.') raise GrupoError(e, u'Failed to remove the UserGroup.') return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests PUT to delete Environment VIP. URL: environmentvip/<id_environment_vip>/ """ try: self.log.info('Delete Environment VIP') id_environment_vip = kwargs.get('id_environment_vip') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_VIP, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Environment VIP ID if not is_valid_int_greater_zero_param(id_environment_vip): self.log.error( u'The id_environment_vip parameter is not a valid value: %s.', id_environment_vip) raise InvalidValueError(None, 'id_environment_vip', id_environment_vip) # Find Environment VIP by ID to check if it exist environment_vip = EnvironmentVip.get_by_pk(id_environment_vip) with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip): # Find networkIPv4 by Environment VIP to check if is greater # than zero if len( NetworkIPv4.objects.filter( ambient_vip=environment_vip.id)) > 0: return self.response_error(284) # Find networkIPv6 by Environment VIP to check if is greater # than zero if len( NetworkIPv6.objects.filter( ambient_vip=environment_vip.id)) > 0: return self.response_error(285) try: # Delete Environment Vip environment_vip.delete() except Exception, e: self.log.error(u'Failed to delete the environment vip.') raise EnvironmentVipError( e, u'Failed to delete the environment vip') 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): """Trata as requisições de POST para alterar a senha de um Usuario. URL: user-change-pass/ """ try: xml_map, attrs_map = loads(request.raw_post_data) self.log.info('Change user password') # User permission if not has_perm(user, AdminPermission.AUTHENTICATE, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') user_map = networkapi_map.get('user') if user_map is None: return self.response_error(3, u'Não existe valor para a tag usuario do XML de requisição.') # Get XML data id_user = user_map.get('user_id') password = user_map.get('password') # Valid ID User if not is_valid_int_greater_zero_param(id_user): self.log.error( u'The id_user parameter is not a valid value: %s.', id_user) raise InvalidValueError(None, 'id_user', id_user) # Valid pwd if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45): self.log.error(u'Parameter password is invalid. Value: ****') raise InvalidValueError(None, 'password', '****') # Find User by ID to check if it exist usr = Usuario.get_by_pk(id_user) with distributedlock(LOCK_USER % id_user): # set variable usr.pwd = hashlib.md5(password).hexdigest() try: # update User usr.save(user) except Exception, e: self.log.error(u'Failed to update the user.') raise UsuarioError(e, u'Failed to update the user.') return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT to change Environment VIP. URL: environmentvip/<id_environment_vip>/ """ try: self.log.info('Change Environment VIP') id_environment_vip = kwargs.get('id_environment_vip') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_VIP, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # 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: return self.response_error(3, u'There is no value to the networkapi tag of XML request.') environmentvip_map = networkapi_map.get('environment_vip') if environmentvip_map is None: return self.response_error(3, u'There is no value to the environment_vip tag of XML request.') # Valid Environment VIP ID if not is_valid_int_greater_zero_param(id_environment_vip): self.log.error( u'The id_environment_vip parameter is not a valid value: %s.', id_environment_vip) raise InvalidValueError( None, 'id_environment_vip', id_environment_vip) # Find Environment VIP by ID to check if it exist environment_vip = EnvironmentVip.get_by_pk(id_environment_vip) with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip): # Valid Environment Vip environment_vip.valid_environment_vip(environmentvip_map) try: # Update Environment Vip environment_vip.save() except Exception, e: self.log.error(u'Failed to update the environment vip.') raise EnvironmentVipError( e, u'Failed to update the environment vip') return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT to change Environment VIP. URL: environmentvip/<id_environment_vip>/ """ try: self.log.info("Change Environment VIP") id_environment_vip = kwargs.get('id_environment_vip') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_VIP, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # 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: return self.response_error(3, u'There is no value to the networkapi tag of XML request.') environmentvip_map = networkapi_map.get('environment_vip') if environmentvip_map is None: return self.response_error(3, u'There is no value to the environment_vip tag of XML request.') # Valid Environment VIP ID if not is_valid_int_greater_zero_param(id_environment_vip): self.log.error( u'The id_environment_vip parameter is not a valid value: %s.', id_environment_vip) raise InvalidValueError( None, 'id_environment_vip', id_environment_vip) # Find Environment VIP by ID to check if it exist environment_vip = EnvironmentVip.get_by_pk(id_environment_vip) with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip): # Valid Environment Vip environment_vip.valid_environment_vip(environmentvip_map) try: # Update Environment Vip environment_vip.save() except Exception, e: self.log.error(u'Failed to update the environment vip.') raise EnvironmentVipError( e, u'Failed to update the environment vip') return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/ """ # Verifica acesso e obtém dados do request try: # Obtém argumentos passados na URL id_equipamento = kwargs.get('id_equipamento') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_equipamento): self.log.error( u'The id_equipamento parameter is not a valid value: %s.', id_equipamento) raise InvalidValueError(None, 'id_equipamento', id_equipamento) id_tipo_acesso = kwargs.get('id_tipo_acesso') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_tipo_acesso): self.log.error( u'The id_tipo_acesso parameter is not a valid value: %s.', id_tipo_acesso) raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso) Equipamento.get_by_pk(id_equipamento) TipoAcesso.get_by_pk(id_tipo_acesso) # Após obtenção do id_equipamento podemos verificar a permissão if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION): return self.not_authorized() with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso): # Remove a informação de acesso a equipamento EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso) # Retorna response vazio em caso de sucesso return self.response(dumps_networkapi({})) except InvalidValueError as e: return self.response_error(269, e.param, e.value) except EquipamentoNotFoundError: return self.response_error(117, id_equipamento) except AccessTypeNotFoundError: return self.response_error(171, id_tipo_acesso) except EquipamentoAcesso.DoesNotExist: return self.response_error(209, id_equipamento, id_tipo_acesso) except (EquipamentoError, GrupoError): return self.response_error(1)
def delete_dhcprelayipv6(user, dhcprelayipv6_id): dhcprelayipv6_obj = DHCPRelayIPv6.get_by_pk(id=dhcprelayipv6_id) with distributedlock(LOCK_NETWORK_IPV6 % dhcprelayipv6_obj.networkipv6.id): if not dhcprelayipv6_obj.networkipv6.active: dhcprelayipv6_obj.delete() return True else: raise exceptions.CannotRemoveDHCPRelayFromActiveNetwork()
def deploy_networkIPv4_configuration(user, networkipv4, equipment_list): """Loads template for creating Network IPv4 equipment configuration, creates file and apply config. Args: equipment_list: NetworkIPv4 object equipment_list: Equipamento objects list Returns: List with status of equipments output """ log.info("deploy_networkIPv4_configuration") data = dict() # lock network id to prevent multiple requests to same id with distributedlock(LOCK_NETWORK_IPV4 % networkipv4.id): with distributedlock(LOCK_VLAN % networkipv4.vlan.id): if networkipv4.active == 1: data['output'] = 'Network already active. Nothing to do.' return data # load dict with all equipment attributes dict_ips = get_dict_v4_to_use_in_configuration_deploy( user, networkipv4, equipment_list) status_deploy = dict() # TODO implement threads for equipment in equipment_list: # generate config file file_to_deploy = _generate_config_file( dict_ips, equipment, TEMPLATE_NETWORKv4_ACTIVATE) # deploy config file in equipments lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % ( equipment.id) status_deploy[equipment.id] = \ deploy_config_in_equipment_synchronous( file_to_deploy, equipment, lockvar) networkipv4.activate(user) transaction.commit() if networkipv4.vlan.ativada == 0: networkipv4.vlan.activate(user) return status_deploy
def create_lock(pools): """ Create locks to pools list """ locks_list = list() for pool in pools: lock = distributedlock(LOCK_POOL % pool['server_pool']['id']) lock.__enter__() locks_list.append(lock) return locks_list
def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar um grupo de equipamento. URL: egrupo/<id_grupo>/ """ try: egroup_id = kwargs.get('id_grupo') if not is_valid_int_greater_zero_param(egroup_id): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup_id) raise InvalidValueError(None, 'egroup_id', egroup_id) egrp = EGrupo.get_by_pk(egroup_id) if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error( 3, u'Não existe valor para a tag networkapi do XML de requisição.' ) egroup_map = networkapi_map.get('grupo') if egroup_map is None: return self.response_error( 3, u'Não existe valor para a tag grupo do XML de requisição.') name = egroup_map.get('nome') if not is_valid_string_maxsize(name, 100): self.log.error(u'Parameter name is invalid. Value: %s', name) raise InvalidValueError(None, 'name', name) with distributedlock(LOCK_GROUP_EQUIPMENT % egroup_id): # Destroy equipment's cache equip_id_list = [] for equipament in egrp.equipamento_set.all(): equip_id_list.append(equipament.id) destroy_cache_function(equip_id_list, True) EGrupo.update(user, egroup_id, nome=name) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/<id_direito>/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) try: xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error( 3, u'Não existe valor para a tag networkapi do XML de requisição.' ) direito_map = networkapi_map.get('direito_grupo_equipamento') if direito_map is None: return self.response_error( 3, u'Não existe valor para a tag direito_grupo_equipamento do XML de requisição.' ) response = self.__valida_request(direito_map, False) if response is not None: return response with distributedlock(LOCK_GROUP_RIGHTS % right_id): DireitosGrupoEquipamento.update( user, right_id, leitura=direito_map.get('leitura'), escrita=direito_map.get('escrita'), alterar_config=direito_map.get('alterar_config'), exclusao=direito_map.get('exclusao')) return self.response(dumps_networkapi({}))
def handle_put(self, request, user, *args, **kwargs): '''Treat PUT requests to Invalidate a vlan URL: vlan/<id_vlan>/invalidate/<network> ''' try: id_vlan = kwargs.get('id_vlan') network = kwargs.get('network') # User permission if not has_perm(user, AdminPermission.ACL_VLAN_VALIDATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vlan ID if not is_valid_int_greater_zero_param(id_vlan): self.log.error( u'The id_vlan parameter is not a valid value: %s.', id_vlan) raise InvalidValueError(None, 'vlan_id', id_vlan) # Valid Network if not is_valid_version_ip(network, IP_VERSION): self.log.error( u'The network parameter is not a valid value: %s.', network) raise InvalidValueError(None, 'network', network) # Find Vlan by ID to check if it exist vlan = Vlan().get_by_pk(id_vlan) with distributedlock(LOCK_VLAN % id_vlan): # Set Values if network == IP_VERSION.IPv4[0]: vlan.acl_valida = 0 vlan.acl_file_name = None else: vlan.acl_valida_v6 = 0 vlan.acl_file_name_v6 = None vlan.save() return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """ Treat DELETE requests to remove a vip request. Also remove reals related and balancer ips (if this ips isn't used for another vip). URL: vip/delete/<id_vip>/ """ try: vip_id = kwargs.get('id_vip') keep_ip = bool(request.REQUEST.get('keep_ip', False)) # User permission if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Valid vip ID if not is_valid_int_greater_zero_param(vip_id): self.log.error(u'Parameter id_vip is invalid. Value: %s.', vip_id) raise InvalidValueError(None, 'id_vip', vip_id) vip = RequisicaoVips.get_by_pk(vip_id) if vip.vip_criado: return self.response_error(370, vip_id) ipv4 = vip.ip ipv6 = vip.ipv6 with distributedlock(LOCK_VIP % vip_id): try: vip.delete_vips_and_reals(user) vip.remove(user, vip_id) # SYNC_VIP delete_new(vip_id) if ipv4 and not keep_ip: if not self.is_ipv4_in_use(ipv4, vip_id): ipv4.delete() if ipv6 and not keep_ip: if not self.is_ipv6_in_use(ipv6, vip_id): ipv6.delete() except IpCantRemoveFromServerPool, e: raise e except IpCantBeRemovedFromVip, e: raise e
def handle_delete(self, request, user, *args, **kwargs): """Treat requests PUT to delete Environment VIP. URL: environmentvip/<id_environment_vip>/ """ try: self.log.info('Delete Environment VIP') id_environment_vip = kwargs.get('id_environment_vip') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_VIP, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Environment VIP ID if not is_valid_int_greater_zero_param(id_environment_vip): self.log.error( u'The id_environment_vip parameter is not a valid value: %s.', id_environment_vip) raise InvalidValueError( None, 'id_environment_vip', id_environment_vip) # Find Environment VIP by ID to check if it exist environment_vip = EnvironmentVip.get_by_pk(id_environment_vip) with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip): # Find networkIPv4 by Environment VIP to check if is greater # than zero if len(NetworkIPv4.objects.filter(ambient_vip=environment_vip.id)) > 0: return self.response_error(284) # Find networkIPv6 by Environment VIP to check if is greater # than zero if len(NetworkIPv6.objects.filter(ambient_vip=environment_vip.id)) > 0: return self.response_error(285) try: # Delete Environment Vip environment_vip.delete() except Exception, e: self.log.error(u'Failed to delete the environment vip.') raise EnvironmentVipError( e, u'Failed to delete the environment vip') return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """ Treat DELETE requests to remove a vip request. Also remove reals related and balancer ips (if this ips isn't used for another vip). URL: vip/delete/<id_vip>/ """ try: vip_id = kwargs.get('id_vip') keep_ip = bool(request.REQUEST.get('keep_ip', False)) # User permission if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Valid vip ID if not is_valid_int_greater_zero_param(vip_id): self.log.error( u'Parameter id_vip is invalid. Value: %s.', vip_id) raise InvalidValueError(None, 'id_vip', vip_id) vip = RequisicaoVips.get_by_pk(vip_id) if vip.vip_criado: return self.response_error(370, vip_id) ipv4 = vip.ip ipv6 = vip.ipv6 with distributedlock(LOCK_VIP % vip_id): try: vip.delete_vips_and_reals(user) vip.remove(user, vip_id) # SYNC_VIP delete_new(vip_id) if ipv4 and not keep_ip: if not self.is_ipv4_in_use(ipv4, vip_id): ipv4.delete() if ipv6 and not keep_ip: if not self.is_ipv6_in_use(ipv6, vip_id): ipv6.delete() except IpCantRemoveFromServerPool, e: raise e except IpCantBeRemovedFromVip, e: raise e
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Logical Environment. URL: logicalenvironment/<id_logicalenvironment>/ """ try: self.log.info("Remove Logical Environment") # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_logicalenvironment = kwargs.get('id_logicalenvironment') # Valid ID Logical Environment if not is_valid_int_greater_zero_param(id_logicalenvironment): self.log.error( u'The id_logicalenvironment parameter is not a valid value: %s.', id_logicalenvironment) raise InvalidValueError(None, 'id_logicalenvironment', id_logicalenvironment) # Find Logical Environment by ID to check if it exist loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment) with distributedlock(LOCK_LOGICAL_ENVIRONMENT % id_logicalenvironment): try: if loc_env.ambiente_set.count() > 0: raise AmbienteLogicoUsedByEnvironmentError( None, u"O Ambiente Lógico %s tem ambiente associado." % loc_env.id) # remove Logical Environment loc_env.delete() except AmbienteLogicoUsedByEnvironmentError, e: raise e except Exception, e: self.log.error( u'Failed to remove the Logical Environment.') raise AmbienteError( e, u'Failed to remove the Logical Environment.')
def handle_put(self, request, user, *args, **kwargs): '''Treat PUT requests to Invalidate a vlan URL: vlan/<id_vlan>/invalidate/<network> ''' try: id_vlan = kwargs.get('id_vlan') network = kwargs.get('network') # User permission if not has_perm(user, AdminPermission.ACL_VLAN_VALIDATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vlan ID if not is_valid_int_greater_zero_param(id_vlan): self.log.error( u'The id_vlan parameter is not a valid value: %s.', id_vlan) raise InvalidValueError(None, 'vlan_id', id_vlan) # Valid Network if not is_valid_version_ip(network, IP_VERSION): self.log.error( u'The network parameter is not a valid value: %s.', network) raise InvalidValueError(None, 'network', network) # Find Vlan by ID to check if it exist vlan = Vlan().get_by_pk(id_vlan) with distributedlock(LOCK_VLAN % id_vlan): # Set Values if network == IP_VERSION.IPv4[0]: vlan.acl_valida = 0 vlan.acl_file_name = None else: vlan.acl_valida_v6 = 0 vlan.acl_file_name_v6 = None vlan.save(user) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove user. URL: user/<id_user>/ """ try: self.log.info('Remove User') # User permission if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_user = kwargs.get('id_user') # Valid ID User if not is_valid_int_greater_zero_param(id_user): self.log.error( u'The id_user parameter is not a valid value: %s.', id_user) raise InvalidValueError(None, 'id_user', id_user) # Find Permission by ID to check if it exist usr = Usuario.get_by_pk(id_user) with distributedlock(LOCK_USER % id_user): try: if usr.eventlog_set.count() != 0: raise UsuarioHasEventOrGrupoError( None, u'Existe event_log associado ao usuario %s' % user.id) if usr.usuariogrupo_set.count() != 0: raise UsuarioHasEventOrGrupoError( None, u'Existe grupo associado ao usuario %s' % user.id) # remove User usr.delete() except UsuarioHasEventOrGrupoError, e: raise e except Exception, e: self.log.error(u'Failed to remove the user.') raise GrupoError(e, u'Failed to remove the user.')
def handle_delete(self, request, user, *args, **kwargs): """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/ """ # Verifica acesso e obtém dados do request try: # Obtém argumentos passados na URL id_equipamento = kwargs.get('id_equipamento') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_equipamento): self.log.error( u'The id_equipamento parameter is not a valid value: %s.', id_equipamento) raise InvalidValueError(None, 'id_equipamento', id_equipamento) id_tipo_acesso = kwargs.get('id_tipo_acesso') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_tipo_acesso): self.log.error( u'The id_tipo_acesso parameter is not a valid value: %s.', id_tipo_acesso) raise InvalidValueError(None, 'id_tipo_acesso', id_tipo_acesso) Equipamento.get_by_pk(id_equipamento) TipoAcesso.get_by_pk(id_tipo_acesso) # Após obtenção do id_equipamento podemos verificar a permissão if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION): return self.not_authorized() with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso): # Remove a informação de acesso a equipamento EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso) # Retorna response vazio em caso de sucesso return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/<id_direito>/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) try: xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') direito_map = networkapi_map.get('direito_grupo_equipamento') if direito_map is None: return self.response_error(3, u'Não existe valor para a tag direito_grupo_equipamento do XML de requisição.') response = self.__valida_request(direito_map, False) if response is not None: return response with distributedlock(LOCK_GROUP_RIGHTS % right_id): DireitosGrupoEquipamento.update(user, right_id, leitura=direito_map.get( 'leitura'), escrita=direito_map.get( 'escrita'), alterar_config=direito_map.get( 'alterar_config'), exclusao=direito_map.get('exclusao')) return self.response(dumps_networkapi({}))
def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar um grupo de equipamento. URL: egrupo/<id_grupo>/ """ try: egroup_id = kwargs.get('id_grupo') if not is_valid_int_greater_zero_param(egroup_id): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup_id) raise InvalidValueError(None, 'egroup_id', egroup_id) egrp = EGrupo.get_by_pk(egroup_id) if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') egroup_map = networkapi_map.get('grupo') if egroup_map is None: return self.response_error(3, u'Não existe valor para a tag grupo do XML de requisição.') name = egroup_map.get('nome') if not is_valid_string_maxsize(name, 100): self.log.error(u'Parameter name is invalid. Value: %s', name) raise InvalidValueError(None, 'name', name) with distributedlock(LOCK_GROUP_EQUIPMENT % egroup_id): # Destroy equipment's cache equip_id_list = [] for equipament in egrp.equipamento_set.all(): equip_id_list.append(equipament.id) destroy_cache_function(equip_id_list, True) EGrupo.update(user, egroup_id, nome=name) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Equipment Script. URL: equipmentscript/<id_equipment>/<id_script>/ """ try: self.log.info("Remove Equipment Script") id_equipment = kwargs.get('id_equipment') id_script = kwargs.get('id_script') # Valid ID Equipment if not is_valid_int_greater_zero_param(id_equipment): self.log.error( u'The id_equipment parameter is not a valid value: %s.', id_equipment) raise InvalidValueError(None, 'id_equipment', id_equipment) # Valid ID Script if not is_valid_int_greater_zero_param(id_script): self.log.error( u'The id_script parameter is not a valid value: %s.', id_script) raise InvalidValueError(None, 'id_script', id_script) # Find Equipment by ID to check if it exist Equipamento.get_by_pk(id_equipment) # Find Script by ID to check if it exist Roteiro.get_by_pk(id_script) # User permission if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, id_equipment, AdminPermission.EQUIP_WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) with distributedlock(LOCK_EQUIPMENT_SCRIPT % id_script): EquipamentoRoteiro.remove(user, id_equipment, id_script) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Division Dc. URL: divisiondc/<id_divisiondc>/ """ try: self.log.info('Remove Division Dc') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_divisiondc = kwargs.get('id_divisiondc') # Valid ID Division Dc if not is_valid_int_greater_zero_param(id_divisiondc): self.log.error( u'The id_divisiondc parameter is not a valid value: %s.', id_divisiondc) raise InvalidValueError(None, 'id_divisiondc', id_divisiondc) # Find Division Dc by ID to check if it exist division_dc = DivisaoDc.get_by_pk(id_divisiondc) with distributedlock(LOCK_DC_DIVISION % id_divisiondc): try: if division_dc.ambiente_set.count() > 0: raise DivisaoDcUsedByEnvironmentError( None, u'A Divisão DC %s tem ambiente associado.' % division_dc.id) # remove Division Dc division_dc.delete() except DivisaoDcUsedByEnvironmentError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Division Dc.') raise AmbienteError(e, u'Failed to remove the Division Dc.')
def delete_cached_searches_list(prefix): with distributedlock(prefix): try: cached_search_md5_list = memcache.get(prefix) if cached_search_md5_list: for cached_search_md5 in cached_search_md5_list: key = str(prefix) + str(cached_search_md5) log.debug("Deleting cache entry %s ... " % key) memcache.delete(key) log.debug("Deleting cache list entry %s ..." % prefix) memcache.delete(prefix) except Exception as e: log.error(e) raise e return True
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Script Type. URL: scripttype/<id_script_type>/ """ try: self.log.info("Remove Script Type") # User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_script_type = kwargs.get('id_script_type') # Valid ID Script Type if not is_valid_int_greater_zero_param(id_script_type): self.log.error( u'The id_script_type parameter is not a valid value: %s.', id_script_type) raise InvalidValueError(None, 'id_script_type', id_script_type) # Find Script Type by ID to check if it exist script_type = TipoRoteiro.get_by_pk(id_script_type) with distributedlock(LOCK_SCRIPT_TYPE % id_script_type): try: if script_type.roteiro_set.count() != 0: raise TipoRoteiroHasRoteiroError( None, u'Existe roteiros associado ao tipo de roteiro %d' % script_type.id) # remove Script Type script_type.delete() except TipoRoteiroHasRoteiroError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Script Type.') raise RoteiroError(e, u'Failed to remove the Script Type.')
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Equipment Script. URL: equipmentscript/<id_equipment>/<id_script>/ """ try: self.log.info("Remove Equipment Script") id_equipment = kwargs.get("id_equipment") id_script = kwargs.get("id_script") # Valid ID Equipment if not is_valid_int_greater_zero_param(id_equipment): self.log.error(u"The id_equipment parameter is not a valid value: %s.", id_equipment) raise InvalidValueError(None, "id_equipment", id_equipment) # Valid ID Script if not is_valid_int_greater_zero_param(id_script): self.log.error(u"The id_script parameter is not a valid value: %s.", id_script) raise InvalidValueError(None, "id_script", id_script) # Find Equipment by ID to check if it exist Equipamento.get_by_pk(id_equipment) # Find Script by ID to check if it exist Roteiro.get_by_pk(id_script) # User permission if not has_perm( user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None, id_equipment, AdminPermission.EQUIP_WRITE_OPERATION, ): self.log.error(u"User does not have permission to perform the operation.") raise UserNotAuthorizedError(None) with distributedlock(LOCK_EQUIPMENT_SCRIPT % id_script): EquipamentoRoteiro.remove(user, id_equipment, id_script) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Logical Environment. URL: logicalenvironment/<id_logicalenvironment>/ """ try: self.log.info("Remove Logical Environment") # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_logicalenvironment = kwargs.get('id_logicalenvironment') # Valid ID Logical Environment if not is_valid_int_greater_zero_param(id_logicalenvironment): self.log.error( u'The id_logicalenvironment parameter is not a valid value: %s.', id_logicalenvironment) raise InvalidValueError( None, 'id_logicalenvironment', id_logicalenvironment) # Find Logical Environment by ID to check if it exist loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment) with distributedlock(LOCK_LOGICAL_ENVIRONMENT % id_logicalenvironment): try: if loc_env.ambiente_set.count() > 0: raise AmbienteLogicoUsedByEnvironmentError( None, u"O Ambiente Lógico %s tem ambiente associado." % loc_env.id) # remove Logical Environment loc_env.delete(user) except AmbienteLogicoUsedByEnvironmentError, e: raise e except Exception, e: self.log.error( u'Failed to remove the Logical Environment.') raise AmbienteError( e, u'Failed to remove the Logical Environment.')
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Brand. URL: brand/<id_brand>/ """ try: self.log.info("Remove Brand") # User permission if not has_perm(user, AdminPermission.BRAND_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_brand = kwargs.get('id_brand') # Valid ID Brand if not is_valid_int_greater_zero_param(id_brand): self.log.error( u'The id_brand parameter is not a valid value: %s.', id_brand) raise InvalidValueError(None, 'id_brand', id_brand) # Find Brand by ID to check if it exist brand = Marca.get_by_pk(id_brand) with distributedlock(LOCK_BRAND % id_brand): try: if brand.modelo_set.count() > 0: raise MarcaUsedByModeloError( None, u"A marca %d tem modelo associado." % brand.id) # remove Brand brand.delete() except MarcaUsedByModeloError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Brand.') raise EquipamentoError(e, u'Failed to remove the Brand.')
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Model. URL: model/<id_model>/ """ try: self.log.info('Remove Model') # User permission if not has_perm(user, AdminPermission.BRAND_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_model = kwargs.get('id_model') # Valid ID Model if not is_valid_int_greater_zero_param(id_model): self.log.error( u'The id_model parameter is not a valid value: %s.', id_model) raise InvalidValueError(None, 'id_model', id_model) # Find Model by ID to check if it exist model = Modelo.get_by_pk(id_model) with distributedlock(LOCK_MODEL % id_model): try: if model.equipamento_set.count() > 0: raise ModeloUsedByEquipamentoError( None, u'O modelo %s tem equipamento associado.' % model.id) # remove Model model.delete() except ModeloUsedByEquipamentoError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Model.') raise EquipamentoError(e, u'Failed to remove the Model.')
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Group l3. URL: groupl3/<id_groupl3>/ """ try: self.log.info('Remove Group l3') # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_groupl3 = kwargs.get('id_groupl3') # Valid ID Group L3 if not is_valid_int_greater_zero_param(id_groupl3): self.log.error( u'The id_groupl3 parameter is not a valid value: %s.', id_groupl3) raise InvalidValueError(None, 'id_groupl3', id_groupl3) # Find GroupL3 by ID to check if it exist groupl3 = GrupoL3.get_by_pk(id_groupl3) with distributedlock(LOCK_GROUP_L3 % id_groupl3): try: if groupl3.ambiente_set.count() > 0: raise GrupoL3UsedByEnvironmentError( None, u'O GrupoL3 %s tem ambiente associado.' % groupl3.id) # remove Group l3 groupl3.delete() except GrupoL3UsedByEnvironmentError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Group l3.') raise GrupoError(e, u'Failed to remove the Group l3.')
def handle_delete(self, request, user, *args, **kwargs): """Treat DELETE requests to remove Access Type. URL: /tipoacesso/<id_tipo_acesso>/ """ try: if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Access Type ID tipo_acesso_id = kwargs.get('id_tipo_acesso') if not is_valid_int_greater_zero_param(tipo_acesso_id): self.log.error( u'The tipo_acesso_id parameter is not a valid value: %s.', tipo_acesso_id) raise InvalidValueError(None, 'tipo_acesso_id', tipo_acesso_id) # Verify existence tpa = TipoAcesso.get_by_pk(tipo_acesso_id) with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id): # Verifica se o tipo de acesso não é utilizado por algum # equipamento if tpa.equipamentoacesso_set.count() > 0: self.log.error(u'Access Type in use by equipment.') raise AccessTypeUsedByEquipmentError( None, u'Access Type in use by equipment.') tpa.delete() return self.response(dumps_networkapi({})) except UserNotAuthorizedError: return self.not_authorized() except AccessTypeNotFoundError: return self.response_error(171, tipo_acesso_id) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_get(self, request, user, *args, **kwargs): """Handles get requests to validate Vip Requests by id. URLs: /vip/validate/<id_vip>/ """ self.log.info('Validate Vip Request by id') try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations id_vip = kwargs.get('id_vip') # Valid vip id if not is_valid_int_greater_zero_param(id_vip): self.log.error(u'Parameter id_vip is invalid. Value: %s.', id_vip) raise InvalidValueError(None, 'id_vip', id_vip) vip = RequisicaoVips.get_by_pk(id_vip) with distributedlock(LOCK_VIP % id_vip): vip.validado = True vip.save() return self.response(dumps_networkapi({})) except RequisicaoVipsNotFoundError: return self.response_error(152) except RequisicaoVipsError: return self.response_error(150, 'Failed to validate vip request.') except InvalidValueError, e: self.log.error(u'Parameter %s is invalid. Value: %s.', e.param, e.value) return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Trata requisições DELETE para remover um Ambiente. URL: ambiente/<id_ambiente>/ """ try: environment_id = kwargs.get('id_ambiente') # Valid ID Environment if not is_valid_int_greater_zero_param(environment_id): self.log.error( u'The environment_id parameter is not a valid value: %s.', environment_id) raise InvalidValueError(None, 'environment_id', environment_id) if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() with distributedlock(LOCK_ENVIRONMENT % environment_id): # Delete vlan's cache key_list_db = Vlan.objects.filter(ambiente__pk=environment_id) key_list = [] for key in key_list_db: key_list.append(key.id) destroy_cache_function(key_list) # Destroy equipment's cache equip_id_list = [] envr = Ambiente.get_by_pk(environment_id) for equipment in envr.equipamentoambiente_set.all(): equip_id_list.append(equipment.equipamento_id) destroy_cache_function(equip_id_list, True) Ambiente.remove(user, environment_id) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def delete(self, request, *args, **kwargs): """URL: api/interface/disconnect/(?P<id_interface_1>\d+)/(?P<id_interface_2>\d+)/""" try: log.info('API_Disconnect') data = dict() id_interface_1 = kwargs.get('id_interface_1') id_interface_2 = kwargs.get('id_interface_2') interface_1 = Interface.get_by_pk(int(id_interface_1)) interface_2 = Interface.get_by_pk(int(id_interface_2)) with distributedlock(LOCK_INTERFACE % id_interface_1): if interface_1.channel or interface_2.channel: raise exceptions.InterfaceException( 'Interface está em um Port Channel') if interface_1.ligacao_front_id == interface_2.id: interface_1.ligacao_front = None if interface_2.ligacao_front_id == interface_1.id: interface_2.ligacao_front = None else: interface_2.ligacao_back = None elif interface_1.ligacao_back_id == interface_2.id: interface_1.ligacao_back = None if interface_2.ligacao_back_id == interface_1.id: interface_2.ligacao_back = None else: interface_2.ligacao_front = None elif not interface_1.ligacao_front_id and not interface_1.ligacao_back_id: raise exceptions.InterfaceException( 'Interface id %s não connectada' % interface_1) interface_1.save() interface_2.save() return Response(data, status=status.HTTP_200_OK) except exceptions.InterfaceException, exception: raise exception
def handle_get(self, request, user, *args, **kwargs): """Handles get requests to validate Vip Requests by id. URLs: /vip/validate/<id_vip>/ """ self.log.info('Validate Vip Request by id') try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations id_vip = kwargs.get('id_vip') # Valid vip id if not is_valid_int_greater_zero_param(id_vip): self.log.error( u'Parameter id_vip is invalid. Value: %s.', id_vip) raise InvalidValueError(None, 'id_vip', id_vip) vip = RequisicaoVips.get_by_pk(id_vip) with distributedlock(LOCK_VIP % id_vip): vip.validado = True vip.save() return self.response(dumps_networkapi({})) except RequisicaoVipsNotFoundError: return self.response_error(152) except RequisicaoVipsError: return self.response_error(150, 'Failed to validate vip request.') except InvalidValueError, e: self.log.error( u'Parameter %s is invalid. Value: %s.', e.param, e.value) return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Division Dc. URL: divisiondc/<id_divisiondc>/ """ try: self.log.info("Remove Division Dc") # User permission if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_divisiondc = kwargs.get('id_divisiondc') # Valid ID Division Dc if not is_valid_int_greater_zero_param(id_divisiondc): self.log.error( u'The id_divisiondc parameter is not a valid value: %s.', id_divisiondc) raise InvalidValueError(None, 'id_divisiondc', id_divisiondc) # Find Division Dc by ID to check if it exist division_dc = DivisaoDc.get_by_pk(id_divisiondc) with distributedlock(LOCK_DC_DIVISION % id_divisiondc): try: if division_dc.ambiente_set.count() > 0: raise DivisaoDcUsedByEnvironmentError( None, u"A Divisão DC %s tem ambiente associado." % division_dc.id) # remove Division Dc division_dc.delete(user) except DivisaoDcUsedByEnvironmentError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Division Dc.') raise AmbienteError( e, u'Failed to remove the Division Dc.')
def handle_delete(self, request, user, *args, **kwargs): '''Trata requisições de DELETE para remover um equipamento. URL: /equipamento/id/ ''' try: equipment_id = kwargs.get('id_equip') if not is_valid_int_greater_zero_param(equipment_id): self.log.error( u'The equipment_id parameter is not a valid value: %s.', equipment_id) raise InvalidValueError(None, 'equipment_id', equipment_id) equip = Equipamento.get_by_pk(equipment_id) with distributedlock(LOCK_EQUIPMENT % equipment_id): ip_equipamento_list = IpEquipamento.objects.filter( equipamento=equipment_id) ip6_equipamento_list = Ipv6Equipament.objects.filter( equipamento=equipment_id) # Delete vlan's cache key_list = [] for eq in ip_equipamento_list: vlan = eq.ip.networkipv4.vlan vlan_id = vlan.id key_list.append(vlan_id) for eq in ip6_equipamento_list: vlan = eq.ip.networkipv6.vlan vlan_id = vlan.id key_list.append(vlan_id) destroy_cache_function(key_list) remove_equipment(equipment_id, user) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_delete(self, request, user, *args, **kwargs): """Treat requests DELETE to remove Script. URL: script/<id_script>/ """ try: self.log.info("Remove Script") # User permission if not has_perm(user, AdminPermission.SCRIPT_MANAGEMENT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) id_script = kwargs.get('id_script') # Valid ID Script if not is_valid_int_greater_zero_param(id_script): self.log.error( u'The id_script parameter is not a valid value: %s.', id_script) raise InvalidValueError(None, 'id_script', id_script) # Find Script by ID to check if it exist script = Roteiro.get_by_pk(id_script) with distributedlock(LOCK_SCRIPT % id_script): try: if script.equipamentoroteiro_set.count() != 0: raise RoteiroHasEquipamentoError( None, u'Existe equipamento associado ao roteiro %s' % script.id) # remove Script script.delete(user) except RoteiroHasEquipamentoError, e: raise e except Exception, e: self.log.error(u'Failed to remove the Script.') raise RoteiroError(e, u'Failed to remove the Script.')
def handle_get(self, request, user, *args, **kwargs): """Validate L7 filter URLs: /vip/l7/<id_vip>/validate/ """ try: if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() self.log.info('Validate L7 filter to VIP') id_vip = kwargs.get('id_vip') # Valid Vip ID if not is_valid_int_greater_zero_param(id_vip): self.log.error( u'The vip_id parameter is not a valid value: %s.', id_vip) raise InvalidValueError(None) vip = RequisicaoVips.get_by_pk(id_vip) with distributedlock(LOCK_VIP % id_vip): # Vip must be created if not vip.vip_criado: self.log.error( u'L7 filter can not be changed because VIP has not yet been created.') raise RequestVipsNotBeenCreatedError(None) vip.filter_valid = True vip.save() map = dict() map['sucesso'] = 'sucesso' return self.response(dumps_networkapi(map)) except UserNotAuthorizedError: return self.not_authorized()