def add_pools(request): """ Add Pools For Vip Request. """ try: pool_ids = request.DATA.get('pool_ids') vip_request_id = request.DATA.get('vip_request_id') vip_request_obj = RequisicaoVips.objects.get(id=vip_request_id) for pool_id in pool_ids: pool_obj = ServerPool.objects.get(id=pool_id) vip_port_pool_obj = VipPortToPool(requisicao_vip=vip_request_obj, server_pool=pool_obj, port_vip=pool_obj.default_port) vip_port_pool_obj.save(request.user) syncs.old_to_new(vip_request_obj) return Response(status=status.HTTP_201_CREATED) except RequisicaoVips.DoesNotExist, exception: log.error(exception) raise exceptions.VipRequestDoesNotExistException()
def add_pools(request): """ Add Pools For Vip Request. """ try: pool_ids = request.DATA.get('pool_ids') vip_request_id = request.DATA.get('vip_request_id') vip_request_obj = RequisicaoVips.objects.get(id=vip_request_id) for pool_id in pool_ids: pool_obj = ServerPool.objects.get(id=pool_id) vip_port_pool_obj = VipPortToPool( requisicao_vip=vip_request_obj, server_pool=pool_obj, port_vip=pool_obj.default_port ) vip_port_pool_obj.save(request.user) syncs.old_to_new(vip_request_obj) return Response(status=status.HTTP_201_CREATED) except RequisicaoVips.DoesNotExist, exception: log.error(exception) raise exceptions.VipRequestDoesNotExistException()
def save(request): """ Save Vip Request :param request: Request :return: Data Serialized Post Save """ data = request.DATA user = request.user req_vip_serializer = RequestVipSerializer( data=data ) if not req_vip_serializer.is_valid(): log.error(req_vip_serializer.errors) raise api_exceptions.ValidationException() obj_req_vip = req_vip_serializer.object # valid if pools member can linked by environment/environment vip # relationship rule server_pool_ips_can_associate_with_vip_request(obj_req_vip) obj_req_vip.filter_valid = True obj_req_vip.validado = False set_l7_filter_for_vip(obj_req_vip) obj_req_vip.set_new_variables(data) # obj_req_vip.trafficreturn=OptionVip.get_by_pk(int(data['trafficreturn'])) if obj_req_vip.trafficreturn is None: obj_req_vip.trafficreturn = OptionVip.get_by_pk(12) obj_req_vip.save(user) if obj_req_vip.trafficreturn.nome_opcao_txt == 'DSRL3': dsrl3_to_vip_obj = DsrL3_to_Vip() dsrl3_to_vip_obj.get_dsrl3(obj_req_vip, user) for v_port in obj_req_vip.vip_ports_to_pools: v_port.requisicao_vip = obj_req_vip v_port.save() # SYNC_VIP syncs.old_to_new(obj_req_vip) return req_vip_serializer.data
def handle_post(self, request, user, *args, **kwargs): '''Treat POST requests to run remove script for vip URL: vip/remove/ ''' try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_REMOVE_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: msg = u'There is no value to the networkapi tag of XML request.' self.log.error(msg) return self.response_error(3, msg) vip_map = networkapi_map.get('vip') if vip_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data vip_id = vip_map.get('id_vip') # 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) map = dict() # Vip must exists in database vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): # Equipment permissions if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm( user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm( user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() # Must be validated if not vip.validado: return self.response_error(191, vip_id) # Must be created if not vip.vip_criado: return self.response_error(322, vip_id) # Business Rules # Make command command = VIP_REMOVE % (vip.id) # Execute command code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = { 'stdout': stdout, 'stderr': stderr } vip.vip_criado = 0 vip.save() # SYNC_VIP old_to_new(vip) #Marks the server pool as not created if the # server pool is not used in another already created vip request server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip.id) for server_pool in server_pools: #Checks if server pool is still used in another created vip request server_pools_still_used = VipPortToPool.objects.filter( server_pool=server_pool).exclude( requisicao_vip=vip.id) vip_with_server_pool_is_created = 0 for server_pool_still_used in server_pools_still_used: if server_pool_still_used.requisicao_vip.vip_criado: vip_with_server_pool_is_created = 1 if not vip_with_server_pool_is_created and server_pool.pool_created: server_pool.pool_created = 0 server_pool.save() map['sucesso'] = success_map else: return self.response_error(2, stdout + stderr) # Return XML return self.response(dumps_networkapi(map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def update_vip_request(vip_id, vip_map, user): log = logging.getLogger('update_vip_request') if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): raise UserNotAuthorizedError( None, u'Usuário não tem permissão para executar a operação.') healthcheck_expect_id = vip_map.get('id_healthcheck_expect') if healthcheck_expect_id is not None: if not is_valid_int_greater_zero_param(healthcheck_expect_id): log.error( u'The healthcheck_expect_id parameter is not a valid value: %s.', healthcheck_expect_id) raise InvalidValueError( None, 'healthcheck_expect_id', healthcheck_expect_id) else: healthcheck_expect_id = int(healthcheck_expect_id) ip_id = vip_map.get('id_ip') if not is_valid_int_greater_zero_param(ip_id): log.error(u'The ip_id parameter is not a valid value: %s.', ip_id) raise InvalidValueError(None, 'ip_id', ip_id) else: ip_id = int(ip_id) traffic_id = vip_map.get('trafficreturn') if not is_valid_int_greater_zero_param(traffic_id): log.error(u'The traffic_id parameter is not a valid value: %s.', traffic_id) raise InvalidValueError(None, 'trafficreturn', traffic_id) else: traffic_id = int(traffic_id) validated = vip_map.get('validado') if validated is None: return 246 if validated == '0': validated = False elif validated == '1': validated = True else: return 244 vip_created = vip_map.get('vip_criado') if vip_created is None: return 247 if vip_created == '0': vip_created = False elif vip_created == '1': vip_created = True else: return 245 # Valid maxcon if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')): log.error( u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) code = RequisicaoVips.update(user, vip_id, vip_map, healthcheck_expect_id=healthcheck_expect_id, ip_id=ip_id, vip_criado=vip_created, validado=validated, traffic_return_id=traffic_id) if code is not None: return code # SYNC_VIP vip = RequisicaoVips.get_by_pk(vip_id) old_to_new(vip) return 0
for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: raise InvalidValueError(None, 'real_name', 'None') RequisicaoVips.valid_real_server( ip_aux_error, equip, environment_vip) vip.create(user, vip_map) # SYNC_VIP old_to_new(vip) return 0, vip def update_vip_request(vip_id, vip_map, user): log = logging.getLogger('update_vip_request') if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): raise UserNotAuthorizedError( None, u'Usuário não tem permissão para executar a operação.') healthcheck_expect_id = vip_map.get('id_healthcheck_expect')
def handle_put(self, request, user, *args, **kwargs): """ Handles PUT requests to change the VIP's persistence. URL: vip/<id_vip>/persistence """ self.log.info("Change VIP's persistence") try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vip ID vip_id = kwargs.get('id_vip') if not is_valid_int_greater_zero_param(vip_id): self.log.error( u'The vip_id parameter is not a valid value: %s.', vip_id) raise InvalidValueError(None) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): vip_old = clone(vip) # Vip must be created if not vip.vip_criado: self.log.error( u'Persistence can not be changed because VIP has not yet been created.' ) raise RequestVipsNotBeenCreatedError(None) # Vip equipments permission if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm( user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.' ) raise EquipmentGroupsNotAuthorizedError(None) if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm( user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.' ) raise EquipmentGroupsNotAuthorizedError(None) # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error( 3, u'There is no value to the networkapi tag of XML request.' ) vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error( 3, u'There is no value to the vip tag of XML request.') # Get variables variables_map = vip.variables_to_map() # validation of persistence type is doing by set_variables persistence = vip_map.get('persistencia', None) variables_map['persistencia'] = persistence # Set variables vip.set_variables(variables_map) # Save VIP vip.save(user, commit=True) # SYNC_VIP old_to_new(vip) # Executar script # gerador_vips -i <ID_REQUISICAO> --healthcheck command = 'gerador_vips -i %d --persistence' % vip.id code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = { 'stdout': stdout, 'stderr': stderr } map = dict() map['sucesso'] = success_map return self.response(dumps_networkapi(map)) else: vip_old.save(user, commit=True) return self.response_error(2, stdout + stderr) except XMLError, x: self.log.error(u'Error reading the XML request.') return self.response_error(3, x)
def handle_post(self, request, user, *args, **kwargs): """Treat requests POST to insert request VIP. URLs: /requestvip/ deprecated:: Use the new rest API """ self.log.info('Add request VIP') try: # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority', 'porta']) # 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.') vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error(3, u'There is no value to the vip tag of XML request.') # 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.') raise UserNotAuthorizedError(None) # Valid Ipv4 and Ipv6 ID if (vip_map.get('id_ipv4') is None and vip_map.get('id_ipv6') is None): self.log.error( u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError( None, 'id_ipv4 e id_vip6', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv4') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv4')): self.log.error( u'The id_ipv4 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError( None, 'id_ipv4', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv6') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv6')): self.log.error( u'The id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv6')) raise InvalidValueError( None, 'id_ipv6', vip_map.get('id_ipv6')) # Valid maxcon if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')): self.log.error( u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) vip = RequisicaoVips() finalidade = vip_map.get('finalidade') cliente = vip_map.get('cliente') ambiente = vip_map.get('ambiente') try: evip = EnvironmentVip.get_by_values( finalidade, cliente, ambiente) except Exception, e: raise EnvironmentVipNotFoundError( e, 'The fields finality or client or ambiente is None') # Valid real names and real ips of real server if vip_map.get('reals') is not None: for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: self.log.error( u'The real_name parameter is not a valid value: None.') raise InvalidValueError(None, 'real_name', 'None') # Valid Real RequisicaoVips.valid_real_server( ip_aux_error, equip, evip, False) # Valid reals_prioritys vip_map, code = vip.valid_values_reals_priority(vip_map) if code is not None: return self.response_error(code) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(code) # Existing IPv4 ID if vip_map.get('id_ipv4') is not None: vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4')) # Existing IPv6 ID if vip_map.get('id_ipv6') is not None: vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6')) # Valid ports vip_map, code = vip.valid_values_ports(vip_map) if code is not None: return self.response_error(code[0], code[1]) # Valid HealthcheckExpect vip_map, vip, code = vip.valid_values_healthcheck( vip_map, vip, evip) if code is not None: return self.response_error(code) # Host host_name = vip_map.get('host') if not is_valid_string_minsize(host_name, 3) or not is_valid_string_maxsize(host_name, 100): self.log.error(u'Host_name value is invalid: %s.', host_name) raise InvalidValueError(None, 'host_name', host_name) # Areanegocio areanegocio = vip_map.get('areanegocio') if not is_valid_string_minsize(areanegocio, 3) or not is_valid_string_maxsize(areanegocio, 100): self.log.error( u'Areanegocio value is invalid: %s.', areanegocio) raise InvalidValueError(None, 'areanegocio', areanegocio) # Nome_servico nome_servico = vip_map.get('nome_servico') if not is_valid_string_minsize(nome_servico, 3) or not is_valid_string_maxsize(nome_servico, 100): self.log.error( u'Nome_servico value is invalid: %s.', nome_servico) raise InvalidValueError(None, 'nome_servico', nome_servico) # Existing l7_filter if vip_map.get('l7_filter') is not None: vip.l7_filter = vip_map.get('l7_filter') # If the l7_filter is a rule if vip_map.get('rule_id') is not None: if not is_valid_int_greater_zero_param(vip_map.get('rule_id')): self.log.error( u'The rule_id parameter is not a valid value: %s.', vip_map.get('rule_id')) raise InvalidValueError( None, 'rule_id', vip_map.get('rule_id')) rule = Rule.objects.get(pk=vip_map.get('rule_id')) vip.l7_filter = '\n'.join( rule.rulecontent_set.all().values_list('content', flat=True)) vip.rule = rule # set variables vip.filter_valid = 1 vip.validado = 0 vip.vip_criado = 0 vip.set_variables(vip_map) try: # save Resquest Vip vip.save() # save VipPortToPool, ServerPool and ServerPoolMember vip.save_vips_and_ports(vip_map, user) # SYNC_VIP old_to_new(vip) except Exception, e: if isinstance(e, IntegrityError): # Duplicate value for Port Vip, Port Real and IP self.log.error(u'Failed to save the request vip.') return self.response_error(353) else: raise e
def __create_vip(self, vip_id, user): # 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) with distributedlock(LOCK_VIP % vip_id): # Vip must exists in database vip = RequisicaoVips.get_by_pk(vip_id) # Equipment permissions if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm( user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm( user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() # Must be validated if not vip.validado: return self.response_error(191, vip_id) # Must be created if vip.vip_criado: return self.response_error(192, vip_id) # Business Rules # Make command command = VIP_CREATE % (vip.id) # Execute command code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = {'stdout': stdout, 'stderr': stderr} vip.rule_applied = vip.rule vip.filter_applied = vip.l7_filter vip.l7_filter = None vip.rule = None vip.filter_valid = False vip.vip_criado = 1 vip.save() # SYNC_VIP old_to_new(vip) server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip.id) for server_pool in server_pools: if not server_pool.pool_created: server_pool.pool_created = 1 server_pool.save() map = dict() map['sucesso'] = success_map else: return self.response_error(2, stdout + stderr) # Return XML return self.response(dumps_networkapi(map))
class GroupVirtualResource(RestResource): log = logging.getLogger('GroupVirtualResource') def handle_delete(self, request, user, *args, **kwargs): """Trata as requisições de PUT para remover um grupo virtual. URL: /grupovirtual/ """ try: xml_map, attrs_map = loads( request.raw_post_data, ['vip', 'equipamento', 'id_equipamento']) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisição.') 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.' ) vips_map = networkapi_map.get('vips') try: equipments_map = networkapi_map['equipamentos'] except KeyError: return self.response_error(3, u'XML de requisição inválido.') try: with distributedlock(LOCK_GROUP_VIRTUAL): # Vips if vips_map is not None: try: vip_maps = vips_map['vip'] for vip_map in vip_maps: balanceadores_map = vip_map['balanceadores'] if balanceadores_map is None: return self.response_error( 3, u'Valor da tag balanceadores do XML de requisição inválido.' ) ip_id = vip_map['id_ip'] try: ip_id = int(ip_id) except (TypeError, ValueError), e: self.log.error(u'Valor do id_ip inválido: %s.', ip_id) raise IpNotFoundError( e, u'Valor do id_ip inválido: %s.' % ip_id) vip_s = RequisicaoVips.get_by_ipv4_id(ip_id) # Run scripts to remove vips for vip in vip_s: # Make command command = VIP_REMOVE % (vip.id) # Execute command code, stdout, stderr = exec_script(command) if code == 0: vip.vip_criado = 0 vip.save() # SYNC_VIP old_to_new(vip) else: return self.response_error( 2, stdout + stderr) equipment_ids = balanceadores_map['id_equipamento'] for equip_id in equipment_ids: try: equip_id = int(equip_id) except (TypeError, ValueError), e: self.log.error( u'Valor do id_equipamento inválido: %s.', equip_id) raise EquipamentoNotFoundError( e, u'Valor do id_equipamento inválido: %s.' % equip_id) remove_ip_equipment(ip_id, equip_id, user) except KeyError: return self.response_error( 3, u'Valor das tags vips/vip do XML de requisição inválido.' )
def sync_vip(): # migrate old vips vip_requests = RequisicaoVips.objects.all() for vip_request in vip_requests: old_to_new(vip_request)
def __create_vip(self, vip_id, user): # 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) with distributedlock(LOCK_VIP % vip_id): # Vip must exists in database vip = RequisicaoVips.get_by_pk(vip_id) # Equipment permissions if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm(user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm(user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() # Must be validated if not vip.validado: return self.response_error(191, vip_id) # Must be created if vip.vip_criado: return self.response_error(192, vip_id) # Business Rules # Make command command = VIP_CREATE % (vip.id) # Execute command code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = {'stdout': stdout, 'stderr': stderr} vip.rule_applied = vip.rule vip.filter_applied = vip.l7_filter vip.l7_filter = None vip.rule = None vip.filter_valid = False vip.vip_criado = 1 vip.save() # SYNC_VIP old_to_new(vip) server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip.id) for server_pool in server_pools: if not server_pool.pool_created: server_pool.pool_created = 1 server_pool.save() map = dict() map['sucesso'] = success_map else: return self.response_error(2, stdout + stderr) # Return XML return self.response(dumps_networkapi(map))
def update(request, pk): """ Update Vip Request :param request: :param pk: Identifier Vip Request :return: Data Serialized Post Update """ data = request.DATA user = request.user if not is_valid_int_greater_zero_param(pk): raise exceptions.InvalidIdVipRequestException() vip_ports = data.get('vip_ports_to_pools') req_vip_serializer = RequestVipSerializer( data=data ) if not req_vip_serializer.is_valid(): log.error(req_vip_serializer.errors) raise api_exceptions.ValidationException() # test if request exists RequisicaoVips.objects.get(pk=pk) with distributedlock(LOCK_VIP % pk): obj_req_vip = req_vip_serializer.object # compatibility issues if obj_req_vip.trafficreturn is None: obj_req_vip.trafficreturn = RequisicaoVips.objects.get( pk=pk).trafficreturn obj_req_vip.id = int(pk) obj_req_vip.filter_valid = True obj_req_vip.validado = False set_l7_filter_for_vip(obj_req_vip) obj_req_vip.set_new_variables(data) old_trafficreturn = RequisicaoVips.objects.get(pk=pk).trafficreturn if old_trafficreturn.id != obj_req_vip.trafficreturn.id: if obj_req_vip.trafficreturn.nome_opcao_txt == 'DSRL3': dsrl3_to_vip_obj = DsrL3_to_Vip() dsrl3_to_vip_obj.get_dsrl3(obj_req_vip, user) else: try: dsrl3_to_vip_obj = DsrL3_to_Vip.get_by_vip_id( obj_req_vip.id) dsrl3_to_vip_obj.delete(user) except ObjectDoesNotExist: pass obj_req_vip.save() vip_port_serializer = VipPortToPoolSerializer( data=vip_ports, many=True) if not vip_port_serializer.is_valid(): raise api_exceptions.ValidationException( 'Invalid Port Vip To Pool') vip_port_to_pool_pks = [port['id'] for port in vip_ports if port.get('id')] vip_port_to_pool_to_remove = VipPortToPool.objects.filter( requisicao_vip=obj_req_vip ).exclude( id__in=vip_port_to_pool_pks ) # valid if pools member can linked by environment/environment vip # relationship rule server_pool_ips_can_associate_with_vip_request( obj_req_vip, vip_port_to_pool_to_remove) for v_port_to_del in vip_port_to_pool_to_remove: v_port_to_del.delete() for vip_port in vip_ports: vip_port_obj = VipPortToPool() vip_port_obj.id = vip_port.get('id') vip_port_obj.server_pool = ServerPool( id=vip_port.get('server_pool')) vip_port_obj.port_vip = vip_port.get('port_vip') vip_port_obj.requisicao_vip = obj_req_vip vip_port_obj.save() # SYNC_VIP syncs.old_to_new(obj_req_vip) return req_vip_serializer.data
def handle_post(self, request, user, *args, **kwargs): """Treat POST requests to run remove script for vip URL: vip/remove/ """ try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_REMOVE_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: msg = u'There is no value to the networkapi tag of XML request.' self.log.error(msg) return self.response_error(3, msg) vip_map = networkapi_map.get('vip') if vip_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data vip_id = vip_map.get('id_vip') # 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) map = dict() # Vip must exists in database vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): # Equipment permissions if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm(user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm(user, AdminPermission.VIP_CREATE_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): return self.not_authorized() # Must be validated if not vip.validado: return self.response_error(191, vip_id) # Must be created if not vip.vip_criado: return self.response_error(322, vip_id) # Business Rules # Make command command = VIP_REMOVE % (vip.id) # Execute command code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = { 'stdout': stdout, 'stderr': stderr} vip.vip_criado = 0 vip.save() # SYNC_VIP old_to_new(vip) # Marks the server pool as not created if the # server pool is not used in another already created vip # request server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip.id) for server_pool in server_pools: # Checks if server pool is still used in another # created vip request server_pools_still_used = VipPortToPool.objects.filter( server_pool=server_pool).exclude(requisicao_vip=vip.id) vip_with_server_pool_is_created = 0 for server_pool_still_used in server_pools_still_used: if server_pool_still_used.requisicao_vip.vip_criado: vip_with_server_pool_is_created = 1 if not vip_with_server_pool_is_created and server_pool.pool_created: server_pool.pool_created = 0 server_pool.save() map['sucesso'] = success_map else: return self.response_error(2, stdout + stderr) # Return XML return self.response(dumps_networkapi(map)) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
def handle_put(self, request, user, *args, **kwargs): """ Handles PUT requests to change the VIP's persistence. URL: vip/<id_vip>/persistence """ self.log.info("Change VIP's persistence") try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vip ID vip_id = kwargs.get('id_vip') if not is_valid_int_greater_zero_param(vip_id): self.log.error( u'The vip_id parameter is not a valid value: %s.', vip_id) raise InvalidValueError(None) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): vip_old = clone(vip) # Vip must be created if not vip.vip_criado: self.log.error( u'Persistence can not be changed because VIP has not yet been created.') raise RequestVipsNotBeenCreatedError(None) # Vip equipments permission if vip.ip is not None: for ip_equipment in vip.ip.ipequipamento_set.all(): if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.') raise EquipmentGroupsNotAuthorizedError(None) if vip.ipv6 is not None: for ip_equipment in vip.ipv6.ipv6equipament_set.all(): if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, ip_equipment.equipamento_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.') raise EquipmentGroupsNotAuthorizedError(None) # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'There is no value to the networkapi tag of XML request.') vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error(3, u'There is no value to the vip tag of XML request.') # Get variables variables_map = vip.variables_to_map() # validation of persistence type is doing by set_variables persistence = vip_map.get('persistencia', None) variables_map['persistencia'] = persistence # Set variables vip.set_variables(variables_map) # Save VIP vip.save(user, commit=True) # SYNC_VIP old_to_new(vip) # Executar script # gerador_vips -i <ID_REQUISICAO> --healthcheck command = 'gerador_vips -i %d --persistence' % vip.id code, stdout, stderr = exec_script(command) if code == 0: success_map = dict() success_map['codigo'] = '%04d' % code success_map['descricao'] = { 'stdout': stdout, 'stderr': stderr} map = dict() map['sucesso'] = success_map return self.response(dumps_networkapi(map)) else: vip_old.save(user, commit=True) return self.response_error(2, stdout + stderr) except XMLError, x: self.log.error(u'Error reading the XML request.') return self.response_error(3, x)
for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: raise InvalidValueError(None, 'real_name', 'None') RequisicaoVips.valid_real_server(ip_aux_error, equip, environment_vip) vip.create(user, vip_map) # SYNC_VIP old_to_new(vip) return 0, vip def update_vip_request(vip_id, vip_map, user): log = logging.getLogger('update_vip_request') if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): raise UserNotAuthorizedError( None, u'Usuário não tem permissão para executar a operação.') healthcheck_expect_id = vip_map.get('id_healthcheck_expect') if healthcheck_expect_id is not None:
def update_vip_request(vip_id, vip_map, user): log = logging.getLogger('update_vip_request') if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION): raise UserNotAuthorizedError( None, u'Usuário não tem permissão para executar a operação.') healthcheck_expect_id = vip_map.get('id_healthcheck_expect') if healthcheck_expect_id is not None: if not is_valid_int_greater_zero_param(healthcheck_expect_id): log.error( u'The healthcheck_expect_id parameter is not a valid value: %s.', healthcheck_expect_id) raise InvalidValueError(None, 'healthcheck_expect_id', healthcheck_expect_id) else: healthcheck_expect_id = int(healthcheck_expect_id) ip_id = vip_map.get('id_ip') if not is_valid_int_greater_zero_param(ip_id): log.error(u'The ip_id parameter is not a valid value: %s.', ip_id) raise InvalidValueError(None, 'ip_id', ip_id) else: ip_id = int(ip_id) traffic_id = vip_map.get('trafficreturn') if not is_valid_int_greater_zero_param(traffic_id): log.error(u'The traffic_id parameter is not a valid value: %s.', traffic_id) raise InvalidValueError(None, 'trafficreturn', traffic_id) else: traffic_id = int(traffic_id) validated = vip_map.get('validado') if validated is None: return 246 if validated == '0': validated = False elif validated == '1': validated = True else: return 244 vip_created = vip_map.get('vip_criado') if vip_created is None: return 247 if vip_created == '0': vip_created = False elif vip_created == '1': vip_created = True else: return 245 # Valid maxcon if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')): log.error(u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) code = RequisicaoVips.update(user, vip_id, vip_map, healthcheck_expect_id=healthcheck_expect_id, ip_id=ip_id, vip_criado=vip_created, validado=validated, traffic_return_id=traffic_id) if code is not None: return code # SYNC_VIP vip = RequisicaoVips.get_by_pk(vip_id) old_to_new(vip) return 0
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT change request VIP. URLs: /requestvip/<id_vip>/ deprecated:: Use the new rest API """ self.log.info('Change request VIP') try: vip_id = kwargs.get('id_vip') # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority', 'porta']) # 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.' ) vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error( 3, u'There is no value to the vip tag of XML request.') # User permission if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vip ID if not is_valid_int_greater_zero_param(vip_id): self.log.error( u'The vip_id parameter is not a valid value: %s.', vip_id) raise InvalidValueError(None, 'vip_id', vip_id) # Valid Ipv4 and Ipv6 ID if (vip_map.get('id_ipv4') is None and vip_map.get('id_ipv6') is None): self.log.error( u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError(None, 'id_ipv4 e id_vip6', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv4') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv4')): self.log.error( u'The id_ipv4 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError(None, 'id_ipv4', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv6') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv6')): self.log.error( u'The id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv6')) raise InvalidValueError(None, 'id_ipv6', vip_map.get('id_ipv6')) # Valid Vip validated if not is_valid_boolean_param(vip_map.get('validado')): self.log.error( u'The validated parameter is not a valid value: %s.', vip_map.get('validado')) raise InvalidValueError(None, 'validated', vip_map.get('validado')) # Valid Vip vip_created if not is_valid_boolean_param(vip_map.get('vip_criado')): self.log.error( u'The vip_created parameter is not a valid value: %s.', vip_map.get('vip_criado')) raise InvalidValueError(None, 'vip_created', vip_map.get('vip_criado')) # Valid maxcon if not is_valid_int_greater_equal_zero_param( vip_map.get('maxcon')): self.log.error( u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): # Valid Vip created if vip.vip_criado: self.log.error( u'The IP of the request for VIP %d can not be changed because the VIP is already created.' % vip.id) raise RequisicaoVipsAlreadyCreatedError(None) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) evip = EnvironmentVip.get_by_values( variables_map.get('finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) # Valid real names and real ips of real server if vip_map.get('reals') is not None: for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: self.log.error( u'The real_name parameter is not a valid value: None.' ) raise InvalidValueError(None, 'real_name', 'None') # Valid Real RequisicaoVips.valid_real_server( ip_aux_error, equip, evip, False) # Valid reals_prioritys vip_map, code = vip.valid_values_reals_priority(vip_map) if code is not None: return self.response_error(code) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(code) # Existing IPv4 ID if vip_map.get('id_ipv4') is not None: vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4')) else: vip.ip = None # Existing IPv6 ID if vip_map.get('id_ipv6') is not None: vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6')) else: vip.ipv6 = None # Valid ports vip_map, code = vip.valid_values_ports(vip_map) if code is not None: return self.response_error(code) # Valid HealthcheckExpect vip_map, vip, code = vip.valid_values_healthcheck( vip_map, vip, evip) if code is not None: return self.response_error(code) # Existing l7_filter if vip_map.get('l7_filter') is not None: vip.l7_filter = vip_map.get('l7_filter') else: vip.l7_filter = None # If the l7_filter is a rule, set filter_valid to TRUE if vip_map.get('rule_id') is not None: # Valid rule if not is_valid_int_greater_zero_param( vip_map.get('rule_id')): self.log.error( u'The rule_id parameter is not a valid value: %s.', vip_map.get('rule_id')) raise InvalidValueError(None, 'rule_id', vip_map.get('rule_id')) rule = Rule.objects.get(pk=vip_map.get('rule_id')) vip.l7_filter = '\n'.join( rule.rulecontent_set.all().values_list('content', flat=True)) vip.rule = rule else: vip.rule = None # set variables vip.filter_valid = 1 vip.validado = 0 vip.set_variables(vip_map) try: # update Resquest Vip vip.save() # update ServerPool, VipPortToPool, ServerPoolMembers vip.save_vips_and_ports(vip_map, user) # SYNC_VIP old_to_new(vip) except RequestVipServerPoolConstraintError, e: self.log.error(e.message) return self.response_error(384, e.message) except Exception, e: if isinstance(e, IntegrityError): # Duplicate value for Port Vip, Port Real and IP self.log.error(u'Failed to update the request vip.') return self.response_error(353) else: self.log.error(u'Failed to update the request vip.') raise RequisicaoVipsError( e, u'Failed to update the request vip')
def handle_post(self, request, user, *args, **kwargs): """Treat requests POST to insert request VIP. URLs: /requestvip/ deprecated:: Use the new rest API """ self.log.info('Add request VIP') try: # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority', 'porta']) # 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.' ) vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error( 3, u'There is no value to the vip tag of XML request.') # 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.') raise UserNotAuthorizedError(None) # Valid Ipv4 and Ipv6 ID if (vip_map.get('id_ipv4') is None and vip_map.get('id_ipv6') is None): self.log.error( u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError(None, 'id_ipv4 e id_vip6', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv4') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv4')): self.log.error( u'The id_ipv4 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError(None, 'id_ipv4', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv6') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv6')): self.log.error( u'The id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv6')) raise InvalidValueError(None, 'id_ipv6', vip_map.get('id_ipv6')) # Valid maxcon if not is_valid_int_greater_equal_zero_param( vip_map.get('maxcon')): self.log.error( u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) vip = RequisicaoVips() finalidade = vip_map.get('finalidade') cliente = vip_map.get('cliente') ambiente = vip_map.get('ambiente') try: evip = EnvironmentVip.get_by_values(finalidade, cliente, ambiente) except Exception, e: raise EnvironmentVipNotFoundError( e, 'The fields finality or client or ambiente is None') # Valid real names and real ips of real server if vip_map.get('reals') is not None: for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: self.log.error( u'The real_name parameter is not a valid value: None.' ) raise InvalidValueError(None, 'real_name', 'None') # Valid Real RequisicaoVips.valid_real_server(ip_aux_error, equip, evip, False) # Valid reals_prioritys vip_map, code = vip.valid_values_reals_priority(vip_map) if code is not None: return self.response_error(code) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(code) # Existing IPv4 ID if vip_map.get('id_ipv4') is not None: vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4')) # Existing IPv6 ID if vip_map.get('id_ipv6') is not None: vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6')) # Valid ports vip_map, code = vip.valid_values_ports(vip_map) if code is not None: return self.response_error(code[0], code[1]) # Valid HealthcheckExpect vip_map, vip, code = vip.valid_values_healthcheck( vip_map, vip, evip) if code is not None: return self.response_error(code) # Host host_name = vip_map.get('host') if not is_valid_string_minsize(host_name, 3) or not is_valid_string_maxsize( host_name, 100): self.log.error(u'Host_name value is invalid: %s.', host_name) raise InvalidValueError(None, 'host_name', host_name) # Areanegocio areanegocio = vip_map.get('areanegocio') if not is_valid_string_minsize(areanegocio, 3) or not is_valid_string_maxsize( areanegocio, 100): self.log.error(u'Areanegocio value is invalid: %s.', areanegocio) raise InvalidValueError(None, 'areanegocio', areanegocio) # Nome_servico nome_servico = vip_map.get('nome_servico') if not is_valid_string_minsize(nome_servico, 3) or not is_valid_string_maxsize( nome_servico, 100): self.log.error(u'Nome_servico value is invalid: %s.', nome_servico) raise InvalidValueError(None, 'nome_servico', nome_servico) # Existing l7_filter if vip_map.get('l7_filter') is not None: vip.l7_filter = vip_map.get('l7_filter') # If the l7_filter is a rule if vip_map.get('rule_id') is not None: if not is_valid_int_greater_zero_param(vip_map.get('rule_id')): self.log.error( u'The rule_id parameter is not a valid value: %s.', vip_map.get('rule_id')) raise InvalidValueError(None, 'rule_id', vip_map.get('rule_id')) rule = Rule.objects.get(pk=vip_map.get('rule_id')) vip.l7_filter = '\n'.join( rule.rulecontent_set.all().values_list('content', flat=True)) vip.rule = rule # set variables vip.filter_valid = 1 vip.validado = 0 vip.vip_criado = 0 vip.set_variables(vip_map) try: # save Resquest Vip vip.save() # save VipPortToPool, ServerPool and ServerPoolMember vip.save_vips_and_ports(vip_map, user) # SYNC_VIP old_to_new(vip) except Exception, e: if isinstance(e, IntegrityError): # Duplicate value for Port Vip, Port Real and IP self.log.error(u'Failed to save the request vip.') return self.response_error(353) else: raise e
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT change request VIP. URLs: /requestvip/<id_vip>/ deprecated:: Use the new rest API """ self.log.info('Change request VIP') try: vip_id = kwargs.get('id_vip') # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority', 'porta']) # 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.') vip_map = networkapi_map.get('vip') if vip_map is None: return self.response_error(3, u'There is no value to the vip tag of XML request.') # User permission if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION): self.log.error( u'User does not have permission to perform the operation.') raise UserNotAuthorizedError(None) # Valid Vip ID if not is_valid_int_greater_zero_param(vip_id): self.log.error( u'The vip_id parameter is not a valid value: %s.', vip_id) raise InvalidValueError(None, 'vip_id', vip_id) # Valid Ipv4 and Ipv6 ID if (vip_map.get('id_ipv4') is None and vip_map.get('id_ipv6') is None): self.log.error( u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError( None, 'id_ipv4 e id_vip6', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv4') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv4')): self.log.error( u'The id_ipv4 parameter is not a valid value: %s.', vip_map.get('id_ipv4')) raise InvalidValueError( None, 'id_ipv4', vip_map.get('id_ipv4')) if (vip_map.get('id_ipv6') is not None): if not is_valid_int_greater_zero_param(vip_map.get('id_ipv6')): self.log.error( u'The id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv6')) raise InvalidValueError( None, 'id_ipv6', vip_map.get('id_ipv6')) # Valid Vip validated if not is_valid_boolean_param(vip_map.get('validado')): self.log.error( u'The validated parameter is not a valid value: %s.', vip_map.get('validado')) raise InvalidValueError( None, 'validated', vip_map.get('validado')) # Valid Vip vip_created if not is_valid_boolean_param(vip_map.get('vip_criado')): self.log.error( u'The vip_created parameter is not a valid value: %s.', vip_map.get('vip_criado')) raise InvalidValueError( None, 'vip_created', vip_map.get('vip_criado')) # Valid maxcon if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')): self.log.error( u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon')) raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon')) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): # Valid Vip created if vip.vip_criado: self.log.error( u'The IP of the request for VIP %d can not be changed because the VIP is already created.' % vip.id) raise RequisicaoVipsAlreadyCreatedError(None) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) evip = EnvironmentVip.get_by_values(variables_map.get( 'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) # Valid real names and real ips of real server if vip_map.get('reals') is not None: for real in vip_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') if equip_aux_error is not None: equip = Equipamento.get_by_name(equip_aux_error) else: self.log.error( u'The real_name parameter is not a valid value: None.') raise InvalidValueError(None, 'real_name', 'None') # Valid Real RequisicaoVips.valid_real_server( ip_aux_error, equip, evip, False) # Valid reals_prioritys vip_map, code = vip.valid_values_reals_priority(vip_map) if code is not None: return self.response_error(code) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(code) # Existing IPv4 ID if vip_map.get('id_ipv4') is not None: vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4')) else: vip.ip = None # Existing IPv6 ID if vip_map.get('id_ipv6') is not None: vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6')) else: vip.ipv6 = None # Valid ports vip_map, code = vip.valid_values_ports(vip_map) if code is not None: return self.response_error(code) # Valid HealthcheckExpect vip_map, vip, code = vip.valid_values_healthcheck( vip_map, vip, evip) if code is not None: return self.response_error(code) # Existing l7_filter if vip_map.get('l7_filter') is not None: vip.l7_filter = vip_map.get('l7_filter') else: vip.l7_filter = None # If the l7_filter is a rule, set filter_valid to TRUE if vip_map.get('rule_id') is not None: # Valid rule if not is_valid_int_greater_zero_param(vip_map.get('rule_id')): self.log.error( u'The rule_id parameter is not a valid value: %s.', vip_map.get('rule_id')) raise InvalidValueError( None, 'rule_id', vip_map.get('rule_id')) rule = Rule.objects.get(pk=vip_map.get('rule_id')) vip.l7_filter = '\n'.join( rule.rulecontent_set.all().values_list('content', flat=True)) vip.rule = rule else: vip.rule = None # set variables vip.filter_valid = 1 vip.validado = 0 vip.set_variables(vip_map) try: # update Resquest Vip vip.save() # update ServerPool, VipPortToPool, ServerPoolMembers vip.save_vips_and_ports(vip_map, user) # SYNC_VIP old_to_new(vip) except RequestVipServerPoolConstraintError, e: self.log.error(e.message) return self.response_error(384, e.message) except Exception, e: if isinstance(e, IntegrityError): # Duplicate value for Port Vip, Port Real and IP self.log.error(u'Failed to update the request vip.') return self.response_error(353) else: self.log.error(u'Failed to update the request vip.') raise RequisicaoVipsError( e, u'Failed to update the request vip')