def handle_post(self, request, user, *args, **kwargs): """Handle POST requests to set Environment template URLs: /environment/set_template/<environment_id>/ """ try: environment_id = kwargs.get('environment_id') if not is_valid_int_greater_equal_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.VLAN_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.') environment_map = networkapi_map.get('environment') if environment_map is None: return self.response_error(3, u'Não existe valor para a tag ambiente do XML de requisição.') name = environment_map.get('name') network = environment_map.get('network') if int(environment_id) != 0: Ambiente().get_by_pk(environment_id) if network == IP_VERSION.IPv4[1]: Ambiente.objects.filter( id=environment_id).update(ipv4_template=name) elif network == IP_VERSION.IPv6[1]: Ambiente.objects.filter( id=environment_id).update(ipv6_template=name) else: return self.response_error(269, 'network', network) else: if network == IP_VERSION.IPv4[1]: Ambiente.objects.filter( ipv4_template=name).update(ipv4_template='') elif network == IP_VERSION.IPv6[1]: Ambiente.objects.filter( ipv6_template=name).update(ipv6_template='') else: return self.response_error(269, 'network', network) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value)
environment_vip) if code is not None: return code, vip # get traffic return # traffic_return=OptionVip.objects.filter(nome_opcao_txt=traffic) traffic_id = vip_map.get('trafficreturn') if traffic_id is None: traffic = OptionVip.get_all_trafficreturn(environment_vip.id) traffic = traffic.filter(nome_opcao_txt='Normal') traffic_id = traffic.id vip.trafficreturn = OptionVip() vip.trafficreturn.id = traffic_id # 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')) 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: raise InvalidValueError(None, 'real_name', 'None')
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT change limit connections to VIP. URLs: /vip/<id_vip>/maxcon/<maxcon>/ """ self.log.info("Change limit connections to VIP") try: vip_id = kwargs.get('id_vip') maxcon = kwargs.get('maxcon') # 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) # Valid Maxcon if not is_valid_int_greater_equal_zero_param(maxcon): self.log.error( u'The maxcon parameter is not a valid value: %s.', maxcon) raise InvalidValueError(None) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): vip_old = clone(vip) server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip) server_pools_old = [] server_pools_members_old = [] for sp in server_pools: server_pools_old.append(sp) for spm in sp.serverpoolmember_set.all(): server_pools_members_old.append(spm) # Vip must be created if not vip.vip_criado: self.log.error( u'Maxcon 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) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) # Valid real names and real ips of real server if variables_map.get('reals') is not None: evip = EnvironmentVip.get_by_values(variables_map.get( 'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) for real in variables_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') equip = Equipamento.get_by_name(equip_aux_error) # Valid Real RequisicaoVips.valid_real_server( ip_aux_error, equip, evip) # Valid reals_prioritys variables_map, code = vip.valid_values_reals_priority( variables_map) if code is not None: return self.response_error(329) # Valid reals_weight variables_map, code = vip.valid_values_reals_weight( variables_map) if code is not None: return self.response_error(330) # Valid ports variables_map, code = vip.valid_values_ports(variables_map) if code is not None: return self.response_error(331) variables_map['maxcon'] = maxcon vip.set_variables(variables_map) vip.save(user, commit=True) #update server pool limits table #Fix #27 server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip) for sp in server_pools: #If exists pool member, change default maxconn of pool and members if(len(sp.serverpoolmember_set.all()) > 0): #if(old_maxconn != sp.default_limit and sp.pool_created): sp.default_limit = maxcon sp.save(user, commit=True) for serverpoolmember in sp.serverpoolmember_set.all(): serverpoolmember.limit = maxcon serverpoolmember.save(user, commit=True) # gerador_vips -i <ID_REQUISICAO> --maxconn command = 'gerador_vips -i %d --maxconn' % 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: #TODO Check if is needed to update pool members separately vip_old.save(user, commit=True) for sp in server_pools_old: sp.save(user, commit=True) for spm in server_pools_members_old: spm.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): """Handles POST requests to find all VLANs by search parameters. URLs: /vlan/find/ """ self.log.info('Find all VLANs') try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['searchable_columns', 'asorting_cols']) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: msg = u'There is no value to the networkapi tag of XML request.' self.log.error(msg) return self.response_error(3, msg) vlan_map = networkapi_map.get('vlan') if vlan_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data start_record = vlan_map.get('start_record') end_record = vlan_map.get('end_record') asorting_cols = vlan_map.get('asorting_cols') searchable_columns = vlan_map.get('searchable_columns') custom_search = vlan_map.get('custom_search') number = vlan_map.get('numero') name = vlan_map.get('nome') iexact = vlan_map.get('exato') environment = vlan_map.get('ambiente') net_type = vlan_map.get('tipo_rede') network = vlan_map.get('rede') ip_version = vlan_map.get('versao') subnet = vlan_map.get('subrede') acl = vlan_map.get('acl') # Business Rules # Start with alls vlans = Vlan.objects.all().prefetch_related( 'networkipv4_set', 'networkipv6_set') if number is not None: # If number is valid, add to filter if not is_valid_int_greater_zero_param(number, False): raise InvalidValueError(None, 'numero', number) else: vlans = vlans.filter(num_vlan=number) if name is not None: # If name is valid, add to filter if not is_valid_string_minsize(name, 3, False): raise InvalidValueError(None, 'nome', name) else: # Iexact must be valid to add name to filter if not is_valid_boolean_param(iexact, False): raise InvalidValueError(None, 'exato', iexact) else: if (iexact is None) or (iexact == 'False') or (iexact == '0'): iexact = False if iexact: vlans = vlans.filter(nome=name) else: vlans = vlans.filter(nome__icontains=name) # If environment is valid, add to filter if environment is not None: if not is_valid_int_greater_zero_param(environment, False): raise InvalidValueError(None, 'ambiente', environment) else: vlans = vlans.filter(ambiente__pk=environment) if net_type is not None: # If net_type is valid, add to filter if not is_valid_int_greater_zero_param(net_type, False): raise InvalidValueError(None, 'tipo_rede', net_type) else: q1 = Q(networkipv4__network_type__id=net_type) q2 = Q(networkipv6__network_type__id=net_type) vlans = vlans.filter(q1 | q2) if acl is not None: # If acl is valid, add to filter if not is_valid_boolean_param(acl, False): raise InvalidValueError(None, 'acl', acl) else: if (acl is None) or (acl == 'False') or (acl == '0'): acl = False # If acl is true, only show vlans with false acl_valida if acl: vlans = vlans.filter(acl_valida=False) # If ip_version is valid if not is_valid_int_greater_equal_zero_param(ip_version): raise InvalidValueError(None, 'versao', ip_version) else: if ip_version == '0': vlans = vlans.filter( Q(networkipv6__isnull=True) | Q(networkipv4__isnull=False)) elif ip_version == '1': vlans = vlans.filter( Q(networkipv4__isnull=True) | Q(networkipv6__isnull=False)) if network is not None: # If network is valid if not is_valid_string_minsize(network, 1, False): raise InvalidValueError(None, 'rede', network) else: blocks, network, version = break_network(network) try: network_ip = IPNetwork(network) except ValueError, e: raise InvalidValueError(None, 'rede', network) # If subnet is valid, add to filter if not (subnet == '0' or subnet == '1'): raise InvalidValueError(None, 'subrede', subnet) else: # If subnet is 0, only filter network octs if subnet == '0': # Filter octs if version == IP_VERSION.IPv4[0]: # Network IP v4 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv4__oct1=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv4__oct2=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv4__oct3=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv4__oct4=blocks[3]) if len(blocks[4]) != 0: blk = Q(networkipv4__block=blocks[4]) vlans = vlans.filter( oct1 & oct2 & oct3 & oct4 & blk) else: # Network IP v6 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() oct5 = Q() oct6 = Q() oct7 = Q() oct8 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv6__block1__iexact=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv6__block2__iexact=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv6__block3__iexact=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv6__block4__iexact=blocks[3]) if len(blocks[4]) != 0: oct5 = Q(networkipv6__block5__iexact=blocks[4]) if len(blocks[5]) != 0: oct6 = Q(networkipv6__block6__iexact=blocks[5]) if len(blocks[6]) != 0: oct7 = Q(networkipv6__block7__iexact=blocks[6]) if len(blocks[7]) != 0: oct8 = Q(networkipv6__block8__iexact=blocks[7]) if len(blocks[8]) != 0: blk = Q(networkipv6__block=blocks[8]) vlans = vlans.filter( oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8 & blk) # If subnet is 1 else: if version == IP_VERSION.IPv4[0]: expl = split(network_ip.network.exploded, '.') else: expl = split(network_ip.network.exploded, ':') expl.append(str(network_ip.prefixlen)) if blocks != expl: raise InvalidValueError(None, 'rede', network) # First, get all vlans filtered until now itens = get_networks_simple(vlans) ids_exclude = [] # Then iterate over it to verify each vlan for vlan in itens: is_subnet = verify_subnet( vlan, network_ip, version) if not is_subnet: ids_exclude.append(vlan['id']) vlans = vlans.exclude(id__in=ids_exclude) # Custom order if asorting_cols: if 'ambiente' in asorting_cols: vlans = vlans.order_by( 'ambiente__divisao_dc__nome', 'ambiente__ambiente_logico__nome', 'ambiente__grupo_l3__nome') asorting_cols.remove('ambiente') if '-ambiente' in asorting_cols: vlans = vlans.order_by( '-ambiente__divisao_dc__nome', '-ambiente__ambiente_logico__nome', '-ambiente__grupo_l3__nome') asorting_cols.remove('-ambiente') if 'tipo_rede' in asorting_cols: vlans = vlans.order_by( 'networkipv4__network_type__tipo_rede', 'networkipv6__network_type__tipo_rede') asorting_cols.remove('tipo_rede') if '-tipo_rede' in asorting_cols: vlans = vlans.order_by( '-networkipv4__network_type__tipo_rede', '-networkipv6__network_type__tipo_rede') asorting_cols.remove('-tipo_rede') if 'network' in asorting_cols: vlans = vlans.order_by('networkipv4__oct1', 'networkipv4__oct2', 'networkipv4__oct3', 'networkipv4__oct4', 'networkipv4__block', 'networkipv6__block1', 'networkipv6__block2', 'networkipv6__block3', 'networkipv6__block4', 'networkipv6__block5', 'networkipv6__block6', 'networkipv6__block7', 'networkipv6__block8', 'networkipv6__block') asorting_cols.remove('network') if '-network' in asorting_cols: vlans = vlans.order_by('-networkipv4__oct1', '-networkipv4__oct2', '-networkipv4__oct3', '-networkipv4__oct4', '-networkipv4__block', '-networkipv6__block1', '-networkipv6__block2', '-networkipv6__block3', '-networkipv6__block4', '-networkipv6__block5', '-networkipv6__block6', '-networkipv6__block7', '-networkipv6__block8', '-networkipv6__block') asorting_cols.remove('-network') vlans = vlans.distinct() # Datatable paginator vlans, total = build_query_to_datatable( vlans, asorting_cols, custom_search, searchable_columns, start_record, end_record) vlans = vlans.prefetch_related('ambiente', 'networkipv4_set__network_type', 'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente', 'networkipv6_set__network_type', 'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente') itens = get_networks(vlans, False) vlan_map = dict() vlan_map['vlan'] = itens vlan_map['total'] = total return self.response(dumps_networkapi(vlan_map))
def handle_put(self, request, user, *args, **kwargs): """ Handles PUT requests to change the VIP's real server. URL: vip/real/edit """ self.log.info("Change VIP's real server") try: # 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) # Commons Validations # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority']) # 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 XML data vip_id = vip_map.get('vip_id') alter_priority = vip_map.get('alter_priority') # 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 Alter Priority if not is_valid_int_greater_equal_zero_param(alter_priority): alter_priority = 0 # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) # Clone vip vip_old = clone(vip) server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip) server_pools_old = [] server_pools_members_old = [] for sp in server_pools: server_pools_old.append(sp) for spm in sp.serverpoolmember_set.all(): server_pools_members_old.append(spm) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) # Get balancing method vip_map['metodo_bal'] = str( variables_map.get('metodo_bal')).upper() with distributedlock(LOCK_VIP % vip_id): # Valid real names and real ips of real server if vip_map.get('reals') is not None: evip = EnvironmentVip.get_by_values(variables_map.get( 'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) 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(329) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(330) # Get variables variables_map = vip.variables_to_map() vip_port_list, reals_list, reals_priority, reals_weight = vip.get_vips_and_reals( vip.id) if reals_list: variables_map['reals'] = {'real': reals_list} variables_map['reals_prioritys'] = { 'reals_priority': reals_priority} variables_map['reals_weights'] = { 'reals_weight': reals_weight} variables_map['portas_servicos'] = {'porta': vip_port_list} # clone variables_map variables_map_old = clone(variables_map) # Valid ports variables_map, code = vip.valid_values_ports(variables_map) if code is not None: return self.response_error(331) """ OLD CALLS - Deprecated """ vip_ports_pool = VipPortToPool.objects.filter( requisicao_vip=vip) reals = vip_map.get('reals') new_call = True if reals and 'port_real' not in reals['real'][0]: new_call = False reals_prioritys = vip_map.get('reals_prioritys') reals_weights = dict() if 'reals_weights' in vip_map: reals_weights = vip_map.get('reals_weights') reals_aux = dict() reals_prioritys_aux = dict() reals_weight_aux = dict() reals_aux['real'] = list() reals_prioritys_aux['reals_priority'] = list() reals_weight_aux['reals_weight'] = list() repeat = ( len(vip_ports_pool) * len(reals['real'])) / len(reals['real']) execute_list = list() for x in range(repeat): execute_list.append((x + 1) * len(reals['real'])) for i in range(len(reals['real'])): for vippp in vip_ports_pool: reals_prioritys_aux['reals_priority'].append( reals_prioritys['reals_priority'][i]) if 'reals_weight' in reals_weights: reals_weight_aux['reals_weight'].append( reals_weights['reals_weight'][i]) server_pool = ServerPool.objects.get( vipporttopool__id=vippp.id, vipporttopool__requisicao_vip=vip) if 'id_ip' not in reals['real'][i]: id_ip = get_id_ip(reals['real'][i]) else: id_ip = reals['real'][i]['id_ip'] reals_aux['real'].append({'id_ip': id_ip, 'port_real': server_pool.default_port, 'real_name': reals[ 'real'][i]['real_name'], 'port_vip': vippp.port_vip, u'real_ip': reals['real'][i]['real_ip']}) vip_map['reals_prioritys'] = reals_prioritys_aux vip_map['reals_weights'] = reals_weight_aux vip_map['reals'] = reals_aux """ OLD CALLS - END """ # Check diff reals (reals_to_add, reals_to_rem, reals_to_stay) reals_to_add, reals_to_rem, reals_to_stay = diff_reals( variables_map, vip_map) reals_final = dict() reals_final['reals'] = list() reals_final['priorities'] = list() reals_final['weights'] = list() reals_error = list() removes = True error = False ############################################## # NOT MODIFIED - reals_to_stay # ############################################## for i in range(len(reals_to_stay['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_stay, i, new_call) # Check ip type if is_valid_ipv4(real.get('real_ip')) == True: ip_type = IP_VERSION.IPv4[1] ip = Ip().get_by_pk(id_ip) else: ip_type = IP_VERSION.IPv6[1] ip = Ipv6().get_by_pk(id_ip) reals_final['reals'].append(reals_to_stay['reals'][i]) reals_final['priorities'].append( reals_to_stay['priorities'][i]) if reals_to_stay['weighted']: reals_final['weights'].append( reals_to_stay['weights'][i]) server_pool = ServerPool.objects.get( vipporttopool__port_vip=port_vip, vipporttopool__requisicao_vip=vip) if ip_type == IP_VERSION.IPv4[1]: server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool, port_real=port_real, ip=id_ip) else: server_pool_member = ServerPoolMember.objects.get(server_pool=server_pool, port_real=port_real, ipv6=id_ip) server_pool_member.priority = priority server_pool_member.weight = weight server_pool_member.save(user, commit=True) ############################################# # ADD REALS - reals_to_add # ############################################# for i in range(len(reals_to_add['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_add, i, new_call) if len(real.get('real_ip').split('.')) <= 1: ip_type = IP_VERSION.IPv6[1] ip = Ipv6().get_by_pk(id_ip) if new_call: command = VIP_REALS_v6_CREATE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v6_CREATE % ( vip.id, real.get('real_name'), real.get('real_ip')) else: ip_type = IP_VERSION.IPv4[1] ip = Ip().get_by_pk(id_ip) if new_call: command = VIP_REALS_v4_CREATE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v4_CREATE % ( vip.id, real.get('real_name'), real.get('real_ip')) self.log.info( '------------------- ADD ----------------------') self.log.info( 'Insert ServerPoolMember before execute script') add_reals_before_script( port_vip, vip, ip, ip_type, priority, weight, port_real, user) self.log.info('The insert has completed successfully') # if new_call or (i + 1) in execute_list: self.log.info('Execute script: %s' % command) code, stdout, stderr = exec_script(command) self.log.info( 'Script was executed and returned code %s' % code) if code != 0: removes = False error = True reals_error.append(real) self.log.info( 'Remove ServerPoolMember after execute script if code != 0') remove_reals_after_script( port_vip, ip_type, vip, port_real, priority, weight, id_ip, user) self.log.info('The remove has completed successfully') else: reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_add['priorities'][i]) if reals_to_add['weighted']: reals_final['weights'].append( reals_to_add['weights'][i]) self.log.info( '----------------- ADD END --------------------') ########################################## # REMOVE REALS - reals_to_rem # ########################################## if removes: for i in range(len(reals_to_rem['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_rem, i, new_call) if len(real.get('real_ip').split('.')) <= 1: ip_type = IP_VERSION.IPv6[1] if new_call: command = VIP_REALS_v6_REMOVE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v6_REMOVE % ( vip.id, real.get('real_name'), real.get('real_ip')) else: ip_type = IP_VERSION.IPv4[1] if new_call: command = VIP_REALS_v4_REMOVE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v4_REMOVE % ( vip.id, real.get('real_name'), real.get('real_ip')) self.log.info( '------------------ REMOVE --------------------') self.log.info('Execute script: %s' % command) code, stdout, stderr = exec_script(command) self.log.info( 'script was executed and returned code %s' % code) if code != 0: error = True reals_error.append(real) reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_rem['priorities'][i]) if reals_to_rem['weighted']: reals_final['weights'].append( reals_to_rem['weights'][i]) else: self.log.info( 'Remove ServerPoolMember after execute script') remove_reals_after_script( port_vip, ip_type, vip, port_real, priority, weight, id_ip, user) self.log.info( 'The remove has completed successfully') self.log.info( '---------------- REMOVE END ------------------') else: for i in range(len(reals_to_rem['reals'])): real = reals_to_rem['reals'][i] reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_rem['priorities'][i]) if reals_to_add['weighted']: reals_final['weights'].append( reals_to_rem['weights'][i]) variables_map['reals'] = dict() variables_map['reals_prioritys'] = dict() variables_map['reals_weights'] = dict() if len(reals_final['reals']) > 0: variables_map['reals']['real'] = reals_final['reals'] variables_map['reals_prioritys'][ 'reals_priority'] = reals_final['priorities'] if reals_final['weights'] is not None: variables_map['reals_weights'][ 'reals_weight'] = reals_final['weights'] else: variables_map.pop('reals') variables_map.pop('reals_prioritys') variables_map.pop('reals_weights') # set variables vip.set_variables(variables_map) try: # If Priority changed if int(alter_priority) != 0: # gerador_vips -i <ID_REQUISICAO> --priority command = 'gerador_vips -i %d --priority' % vip.id # Logging self.log.info( '---------------- ALTER PRIORITY ------------------') self.log.info('Command: ' + command) # Execute script code, stdout, stderr = exec_script(command) self.log.info('Code returned: ' + str(code)) self.log.info('Stdout: ' + stdout) self.log.info( '-------------- ALTER PRIORITY END ----------------') # Script returned error while executing, rollback the # changes in database if code != 0: self.log.info('Code != 0, rollback changes') vip_old.save(user, commit=True) for sp in server_pools_old: sp.save(user, commit=True) for spm in server_pools_members_old: spm.save(user, commit=True) return self.response_error(2, stdout + stderr) 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') if error: # build return message vip_list = '' ip_list = '' for real in reals_error: vip_list = vip_list + real['real_name'] + ', ' ip_list = ip_list + real['real_ip'] + ', ' return self.response_error(333, vip_list[:-2], ip_list[:-2]) else: return self.response(dumps_networkapi({})) 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') != 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') != 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) 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') != 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') != 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) 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_put(self, request, user, *args, **kwargs): """Treat PUT requests to change reals_priority list of VIP. URLs: /vip/<id_vip>/priority/ """ self.log.info("Change list the reals_priority to VIP") try: vip_id = kwargs.get('id_vip') # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['reals_priority']) # 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 reals_prioritys reals_prioritys_map = vip_map.get('reals_prioritys') if (reals_prioritys_map is not None): reals_priority_map = reals_prioritys_map.get('reals_priority') if (reals_priority_map is not None): # Valid values of reals_priority for reals_priority in reals_priority_map: if not is_valid_int_greater_equal_zero_param(reals_priority): self.log.error( u'The reals_priority parameter is not a valid value: %s.', reals_priority) raise InvalidValueError( None, 'reals_priority', reals_priority) if len(reals_priority_map) > 0: vip_map = RequisicaoVips.is_valid_values_reals_priority( reals_priority_map) else: self.log.error( u'The reals_priority_map parameter is not a valid value: %s.', reals_priority_map) raise InvalidValueError( None, 'reals_priority_map', reals_priority_map) else: self.log.error( u'The reals_priority parameter is not a valid value: %s.', reals_priority_map) raise InvalidValueError( None, 'reals_priority', reals_priority_map) else: self.log.error( u'The reals_prioritys parameter is not a valid value: %s.', reals_prioritys_map) raise InvalidValueError( None, 'reals_prioritys', reals_prioritys_map) # 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'Priority can not be changed because VIP has not yet been created.') raise RequestVipsNotBeenCreatedError(None) # Vip equipments permission 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): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.') raise EquipmentGroupsNotAuthorizedError(None) variables_map = vip.variables_to_map() # Valid list reals_server """if len(variables_map.get('reals').get('real')) != len(vip_map.get('reals_prioritys').get('reals_priority')): self.log.error(u'List the Reals_priority is higher or lower than list the real_server.') return self.response_error(272)""" variables_map['reals_prioritys'] = vip_map.get( 'reals_prioritys') vip.set_variables(variables_map) vip.save(user, commit=True) # gerador_vips -i <ID_REQUISICAO> --priority command = 'gerador_vips -i %d --priority' % 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)
try: environment_vip = EnvironmentVip.get_by_values( finalidade, cliente, ambiente) except Exception, e: raise EnvironmentVipNotFoundError( e, 'The fields finality or client or ambiente is None') # Valid HealthcheckExpect vip_map, vip, code = vip.valid_values_healthcheck( vip_map, vip, environment_vip) if code is not None: return code, vip # 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')) 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: raise InvalidValueError(None, 'real_name', 'None')
def handle_put(self, request, user, *args, **kwargs): """ Handles PUT requests to change the VIP's real server. URL: vip/real/edit """ self.log.info("Change VIP's real server") try: # 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) # Commons Validations # Load XML data xml_map, attrs_map = loads( request.raw_post_data, ['real', 'reals_weight', 'reals_priority']) # 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 XML data vip_id = vip_map.get('vip_id') alter_priority = vip_map.get('alter_priority') # 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 Alter Priority if not is_valid_int_greater_equal_zero_param(alter_priority): alter_priority = 0 # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) # Clone vip vip_old = clone(vip) server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip) server_pools_old = [] server_pools_members_old = [] for sp in server_pools: server_pools_old.append(sp) for spm in sp.serverpoolmember_set.all(): server_pools_members_old.append(spm) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) # Get balancing method vip_map['metodo_bal'] = str( variables_map.get('metodo_bal')).upper() with distributedlock(LOCK_VIP % vip_id): # Valid real names and real ips of real server if vip_map.get('reals') is not None: evip = EnvironmentVip.get_by_values( variables_map.get('finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) 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(329) # Valid reals_weight vip_map, code = vip.valid_values_reals_weight(vip_map) if code is not None: return self.response_error(330) # Get variables variables_map = vip.variables_to_map() vip_port_list, reals_list, reals_priority, reals_weight = vip.get_vips_and_reals( vip.id) if reals_list: variables_map['reals'] = {'real': reals_list} variables_map['reals_prioritys'] = { 'reals_priority': reals_priority } variables_map['reals_weights'] = { 'reals_weight': reals_weight } variables_map['portas_servicos'] = {'porta': vip_port_list} # clone variables_map # variables_map_old = clone(variables_map) # Valid ports variables_map, code = vip.valid_values_ports(variables_map) if code is not None: return self.response_error(331) """ OLD CALLS - Deprecated """ vip_ports_pool = VipPortToPool.objects.filter( requisicao_vip=vip) reals = vip_map.get('reals') new_call = True if reals and 'port_real' not in reals['real'][0]: new_call = False reals_prioritys = vip_map.get('reals_prioritys') reals_weights = dict() if 'reals_weights' in vip_map: reals_weights = vip_map.get('reals_weights') reals_aux = dict() reals_prioritys_aux = dict() reals_weight_aux = dict() reals_aux['real'] = list() reals_prioritys_aux['reals_priority'] = list() reals_weight_aux['reals_weight'] = list() repeat = (len(vip_ports_pool) * len(reals['real'])) / len( reals['real']) execute_list = list() for x in range(repeat): execute_list.append((x + 1) * len(reals['real'])) for i in range(len(reals['real'])): for vippp in vip_ports_pool: reals_prioritys_aux['reals_priority'].append( reals_prioritys['reals_priority'][i]) if 'reals_weight' in reals_weights: reals_weight_aux['reals_weight'].append( reals_weights['reals_weight'][i]) server_pool = ServerPool.objects.get( vipporttopool__id=vippp.id, vipporttopool__requisicao_vip=vip) if 'id_ip' not in reals['real'][i]: id_ip = get_id_ip(reals['real'][i]) else: id_ip = reals['real'][i]['id_ip'] reals_aux['real'].append({ 'id_ip': id_ip, 'port_real': server_pool.default_port, 'real_name': reals['real'][i]['real_name'], 'port_vip': vippp.port_vip, u'real_ip': reals['real'][i]['real_ip'] }) vip_map['reals_prioritys'] = reals_prioritys_aux vip_map['reals_weights'] = reals_weight_aux vip_map['reals'] = reals_aux """ OLD CALLS - END """ # Check diff reals (reals_to_add, reals_to_rem, reals_to_stay) reals_to_add, reals_to_rem, reals_to_stay = diff_reals( variables_map, vip_map) reals_final = dict() reals_final['reals'] = list() reals_final['priorities'] = list() reals_final['weights'] = list() reals_error = list() removes = True error = False ############################################## # NOT MODIFIED - reals_to_stay # ############################################## for i in range(len(reals_to_stay['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_stay, i, new_call) # Check ip type if is_valid_ipv4(real.get('real_ip')) is True: ip_type = IP_VERSION.IPv4[1] ip = Ip().get_by_pk(id_ip) else: ip_type = IP_VERSION.IPv6[1] ip = Ipv6().get_by_pk(id_ip) reals_final['reals'].append(reals_to_stay['reals'][i]) reals_final['priorities'].append( reals_to_stay['priorities'][i]) if reals_to_stay['weighted']: reals_final['weights'].append( reals_to_stay['weights'][i]) server_pool = ServerPool.objects.get( vipporttopool__port_vip=port_vip, vipporttopool__requisicao_vip=vip) if ip_type == IP_VERSION.IPv4[1]: server_pool_member = ServerPoolMember.objects.get( server_pool=server_pool, port_real=port_real, ip=id_ip) else: server_pool_member = ServerPoolMember.objects.get( server_pool=server_pool, port_real=port_real, ipv6=id_ip) server_pool_member.priority = priority server_pool_member.weight = weight server_pool_member.save(user, commit=True) ############################################# # ADD REALS - reals_to_add # ############################################# for i in range(len(reals_to_add['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_add, i, new_call) if len(real.get('real_ip').split('.')) <= 1: ip_type = IP_VERSION.IPv6[1] ip = Ipv6().get_by_pk(id_ip) if new_call: command = VIP_REALS_v6_CREATE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v6_CREATE % ( vip.id, real.get('real_name'), real.get('real_ip')) else: ip_type = IP_VERSION.IPv4[1] ip = Ip().get_by_pk(id_ip) if new_call: command = VIP_REALS_v4_CREATE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v4_CREATE % ( vip.id, real.get('real_name'), real.get('real_ip')) self.log.info( '------------------- ADD ----------------------') self.log.info( 'Insert ServerPoolMember before execute script') add_reals_before_script(port_vip, vip, ip, ip_type, priority, weight, port_real, user) self.log.info('The insert has completed successfully') # if new_call or (i + 1) in execute_list: self.log.info('Execute script: %s' % command) code, stdout, stderr = exec_script(command) self.log.info('Script was executed and returned code %s' % code) if code != 0: removes = False error = True reals_error.append(real) self.log.info( 'Remove ServerPoolMember after execute script if code != 0' ) remove_reals_after_script(port_vip, ip_type, vip, port_real, priority, weight, id_ip, user) self.log.info('The remove has completed successfully') else: reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_add['priorities'][i]) if reals_to_add['weighted']: reals_final['weights'].append( reals_to_add['weights'][i]) self.log.info( '----------------- ADD END --------------------') ########################################## # REMOVE REALS - reals_to_rem # ########################################## if removes: for i in range(len(reals_to_rem['reals'])): real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables( reals_to_rem, i, new_call) if len(real.get('real_ip').split('.')) <= 1: ip_type = IP_VERSION.IPv6[1] if new_call: command = VIP_REALS_v6_REMOVE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v6_REMOVE % ( vip.id, real.get('real_name'), real.get('real_ip')) else: ip_type = IP_VERSION.IPv4[1] if new_call: command = VIP_REALS_v4_REMOVE % ( vip.id, id_ip, port_real, port_vip) else: command = VIP_REAL_v4_REMOVE % ( vip.id, real.get('real_name'), real.get('real_ip')) self.log.info( '------------------ REMOVE --------------------') self.log.info('Execute script: %s' % command) code, stdout, stderr = exec_script(command) self.log.info( 'script was executed and returned code %s' % code) if code != 0: error = True reals_error.append(real) reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_rem['priorities'][i]) if reals_to_rem['weighted']: reals_final['weights'].append( reals_to_rem['weights'][i]) else: self.log.info( 'Remove ServerPoolMember after execute script') remove_reals_after_script(port_vip, ip_type, vip, port_real, priority, weight, id_ip, user) self.log.info( 'The remove has completed successfully') self.log.info( '---------------- REMOVE END ------------------') else: for i in range(len(reals_to_rem['reals'])): real = reals_to_rem['reals'][i] reals_final['reals'].append(real) reals_final['priorities'].append( reals_to_rem['priorities'][i]) if reals_to_add['weighted']: reals_final['weights'].append( reals_to_rem['weights'][i]) variables_map['reals'] = dict() variables_map['reals_prioritys'] = dict() variables_map['reals_weights'] = dict() if len(reals_final['reals']) > 0: variables_map['reals']['real'] = reals_final['reals'] variables_map['reals_prioritys'][ 'reals_priority'] = reals_final['priorities'] if reals_final['weights'] is not None: variables_map['reals_weights'][ 'reals_weight'] = reals_final['weights'] else: variables_map.pop('reals') variables_map.pop('reals_prioritys') variables_map.pop('reals_weights') # set variables vip.set_variables(variables_map) try: # If Priority changed if int(alter_priority) != 0: # gerador_vips -i <ID_REQUISICAO> --priority command = 'gerador_vips -i %d --priority' % vip.id # Logging self.log.info( '---------------- ALTER PRIORITY ------------------' ) self.log.info('Command: ' + command) # Execute script code, stdout, stderr = exec_script(command) self.log.info('Code returned: ' + str(code)) self.log.info('Stdout: ' + stdout) self.log.info( '-------------- ALTER PRIORITY END ----------------' ) # Script returned error while executing, rollback the # changes in database if code != 0: self.log.info('Code != 0, rollback changes') vip_old.save(user, commit=True) for sp in server_pools_old: sp.save(user, commit=True) for spm in server_pools_members_old: spm.save(user, commit=True) return self.response_error(2, stdout + stderr) 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') if error: # build return message vip_list = '' ip_list = '' for real in reals_error: vip_list = vip_list + real['real_name'] + ', ' ip_list = ip_list + real['real_ip'] + ', ' return self.response_error(333, vip_list[:-2], ip_list[:-2]) else: return self.response(dumps_networkapi({})) 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): """Handle POST requests to set Environment template URLs: /environment/set_template/<environment_id>/ """ try: environment_id = kwargs.get('environment_id') if not is_valid_int_greater_equal_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.VLAN_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.' ) environment_map = networkapi_map.get('environment') if environment_map is None: return self.response_error( 3, u'Não existe valor para a tag ambiente do XML de requisição.' ) name = environment_map.get('name') network = environment_map.get('network') if int(environment_id) != 0: Ambiente().get_by_pk(environment_id) if network == IP_VERSION.IPv4[1]: Ambiente.objects.filter(id=environment_id).update( ipv4_template=name) elif network == IP_VERSION.IPv6[1]: Ambiente.objects.filter(id=environment_id).update( ipv6_template=name) else: return self.response_error(269, 'network', network) else: if network == IP_VERSION.IPv4[1]: Ambiente.objects.filter(ipv4_template=name).update( ipv4_template='') elif network == IP_VERSION.IPv6[1]: Ambiente.objects.filter(ipv6_template=name).update( ipv6_template='') else: return self.response_error(269, 'network', network) 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): """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')
def handle_put(self, request, user, *args, **kwargs): """Treat PUT requests to change reals_priority list of VIP. URLs: /vip/<id_vip>/priority/ """ self.log.info("Change list the reals_priority to VIP") try: vip_id = kwargs.get('id_vip') # Load XML data xml_map, attrs_map = loads(request.raw_post_data, ['reals_priority']) # 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 reals_prioritys reals_prioritys_map = vip_map.get('reals_prioritys') if (reals_prioritys_map is not None): reals_priority_map = reals_prioritys_map.get('reals_priority') if (reals_priority_map is not None): # Valid values of reals_priority for reals_priority in reals_priority_map: if not is_valid_int_greater_equal_zero_param( reals_priority): self.log.error( u'The reals_priority parameter is not a valid value: %s.', reals_priority) raise InvalidValueError(None, 'reals_priority', reals_priority) if len(reals_priority_map) > 0: vip_map = RequisicaoVips.is_valid_values_reals_priority( reals_priority_map) else: self.log.error( u'The reals_priority_map parameter is not a valid value: %s.', reals_priority_map) raise InvalidValueError(None, 'reals_priority_map', reals_priority_map) else: self.log.error( u'The reals_priority parameter is not a valid value: %s.', reals_priority_map) raise InvalidValueError(None, 'reals_priority', reals_priority_map) else: self.log.error( u'The reals_prioritys parameter is not a valid value: %s.', reals_prioritys_map) raise InvalidValueError(None, 'reals_prioritys', reals_prioritys_map) # 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'Priority can not be changed because VIP has not yet been created.' ) raise RequestVipsNotBeenCreatedError(None) # Vip equipments permission 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): self.log.error( u'Groups of equipment registered with the IP of the VIP request is not allowed of acess.' ) raise EquipmentGroupsNotAuthorizedError(None) variables_map = vip.variables_to_map() # Valid list reals_server """if len(variables_map.get('reals').get('real')) != len(vip_map.get('reals_prioritys').get('reals_priority')): self.log.error(u'List the Reals_priority is higher or lower than list the real_server.') return self.response_error(272)""" variables_map['reals_prioritys'] = vip_map.get( 'reals_prioritys') vip.set_variables(variables_map) vip.save(user, commit=True) # gerador_vips -i <ID_REQUISICAO> --priority command = 'gerador_vips -i %d --priority' % 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 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 update_vip_request(vip_id, vip_map, user): log = Log('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) 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) if code is not None: return code return 0
def handle_post(self, request, user, *args, **kwargs): """Handles POST requests to find all VLANs by search parameters. URLs: /vlan/find/ """ self.log.info('Find all VLANs') try: # Commons Validations # User permission if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_OPERATION): self.log.error( u'User does not have permission to perform the operation.') return self.not_authorized() # Business Validations # Load XML data xml_map, attrs_map = loads(request.raw_post_data, ['searchable_columns', 'asorting_cols']) # XML data format networkapi_map = xml_map.get('networkapi') if networkapi_map is None: msg = u'There is no value to the networkapi tag of XML request.' self.log.error(msg) return self.response_error(3, msg) vlan_map = networkapi_map.get('vlan') if vlan_map is None: msg = u'There is no value to the vlan tag of XML request.' self.log.error(msg) return self.response_error(3, msg) # Get XML data start_record = vlan_map.get('start_record') end_record = vlan_map.get('end_record') asorting_cols = vlan_map.get('asorting_cols') searchable_columns = vlan_map.get('searchable_columns') custom_search = vlan_map.get('custom_search') number = vlan_map.get('numero') name = vlan_map.get('nome') iexact = vlan_map.get('exato') environment = vlan_map.get('ambiente') net_type = vlan_map.get('tipo_rede') network = vlan_map.get('rede') ip_version = vlan_map.get('versao') subnet = vlan_map.get('subrede') acl = vlan_map.get('acl') # Business Rules # Start with alls vlans = Vlan.objects.all().prefetch_related( 'networkipv4_set', 'networkipv6_set') if number is not None: # If number is valid, add to filter if not is_valid_int_greater_zero_param(number, False): raise InvalidValueError(None, 'numero', number) else: vlans = vlans.filter(num_vlan=number) if name is not None: # If name is valid, add to filter if not is_valid_string_minsize(name, 3, False): raise InvalidValueError(None, 'nome', name) else: # Iexact must be valid to add name to filter if not is_valid_boolean_param(iexact, False): raise InvalidValueError(None, 'exato', iexact) else: if (iexact is None) or (iexact == 'False') or (iexact == '0'): iexact = False if iexact: vlans = vlans.filter(nome=name) else: vlans = vlans.filter(nome__icontains=name) # If environment is valid, add to filter if environment is not None: if not is_valid_int_greater_zero_param(environment, False): raise InvalidValueError(None, 'ambiente', environment) else: vlans = vlans.filter(ambiente__pk=environment) if net_type is not None: # If net_type is valid, add to filter if not is_valid_int_greater_zero_param(net_type, False): raise InvalidValueError(None, 'tipo_rede', net_type) else: q1 = Q(networkipv4__network_type__id=net_type) q2 = Q(networkipv6__network_type__id=net_type) vlans = vlans.filter(q1 | q2) if acl is not None: # If acl is valid, add to filter if not is_valid_boolean_param(acl, False): raise InvalidValueError(None, 'acl', acl) else: if (acl is None) or (acl == 'False') or (acl == '0'): acl = False # If acl is true, only show vlans with false acl_valida if acl: vlans = vlans.filter(acl_valida=False) # If ip_version is valid if not is_valid_int_greater_equal_zero_param(ip_version): raise InvalidValueError(None, 'versao', ip_version) else: if ip_version == '0': vlans = vlans.filter( Q(networkipv6__isnull=True) | Q(networkipv4__isnull=False)) elif ip_version == '1': vlans = vlans.filter( Q(networkipv4__isnull=True) | Q(networkipv6__isnull=False)) if network is not None: # If network is valid if not is_valid_string_minsize(network, 1, False): raise InvalidValueError(None, 'rede', network) else: blocks, network, version = break_network(network) try: network_ip = IPNetwork(network) except ValueError, e: raise InvalidValueError(None, 'rede', network) # If subnet is valid, add to filter if not (subnet == '0' or subnet == '1'): raise InvalidValueError(None, 'subrede', subnet) else: # If subnet is 0, only filter network octs if subnet == '0': # Filter octs if version == IP_VERSION.IPv4[0]: # Network IP v4 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv4__oct1=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv4__oct2=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv4__oct3=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv4__oct4=blocks[3]) if len(blocks[4]) != 0: blk = Q(networkipv4__block=blocks[4]) vlans = vlans.filter(oct1 & oct2 & oct3 & oct4 & blk) else: # Network IP v6 oct1 = Q() oct2 = Q() oct3 = Q() oct4 = Q() oct5 = Q() oct6 = Q() oct7 = Q() oct8 = Q() blk = Q() if len(blocks[0]) != 0: oct1 = Q(networkipv6__block1__iexact=blocks[0]) if len(blocks[1]) != 0: oct2 = Q(networkipv6__block2__iexact=blocks[1]) if len(blocks[2]) != 0: oct3 = Q(networkipv6__block3__iexact=blocks[2]) if len(blocks[3]) != 0: oct4 = Q(networkipv6__block4__iexact=blocks[3]) if len(blocks[4]) != 0: oct5 = Q(networkipv6__block5__iexact=blocks[4]) if len(blocks[5]) != 0: oct6 = Q(networkipv6__block6__iexact=blocks[5]) if len(blocks[6]) != 0: oct7 = Q(networkipv6__block7__iexact=blocks[6]) if len(blocks[7]) != 0: oct8 = Q(networkipv6__block8__iexact=blocks[7]) if len(blocks[8]) != 0: blk = Q(networkipv6__block=blocks[8]) vlans = vlans.filter(oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8 & blk) # If subnet is 1 else: if version == IP_VERSION.IPv4[0]: expl = split(network_ip.network.exploded, '.') else: expl = split(network_ip.network.exploded, ':') expl.append(str(network_ip.prefixlen)) if blocks != expl: raise InvalidValueError(None, 'rede', network) # First, get all vlans filtered until now itens = get_networks_simple(vlans) ids_exclude = [] # Then iterate over it to verify each vlan for vlan in itens: is_subnet = verify_subnet(vlan, network_ip, version) if not is_subnet: ids_exclude.append(vlan['id']) vlans = vlans.exclude(id__in=ids_exclude) # Custom order if asorting_cols: if 'ambiente' in asorting_cols: vlans = vlans.order_by('ambiente__divisao_dc__nome', 'ambiente__ambiente_logico__nome', 'ambiente__grupo_l3__nome') asorting_cols.remove('ambiente') if '-ambiente' in asorting_cols: vlans = vlans.order_by('-ambiente__divisao_dc__nome', '-ambiente__ambiente_logico__nome', '-ambiente__grupo_l3__nome') asorting_cols.remove('-ambiente') if 'tipo_rede' in asorting_cols: vlans = vlans.order_by( 'networkipv4__network_type__tipo_rede', 'networkipv6__network_type__tipo_rede') asorting_cols.remove('tipo_rede') if '-tipo_rede' in asorting_cols: vlans = vlans.order_by( '-networkipv4__network_type__tipo_rede', '-networkipv6__network_type__tipo_rede') asorting_cols.remove('-tipo_rede') if 'network' in asorting_cols: vlans = vlans.order_by( 'networkipv4__oct1', 'networkipv4__oct2', 'networkipv4__oct3', 'networkipv4__oct4', 'networkipv4__block', 'networkipv6__block1', 'networkipv6__block2', 'networkipv6__block3', 'networkipv6__block4', 'networkipv6__block5', 'networkipv6__block6', 'networkipv6__block7', 'networkipv6__block8', 'networkipv6__block') asorting_cols.remove('network') if '-network' in asorting_cols: vlans = vlans.order_by( '-networkipv4__oct1', '-networkipv4__oct2', '-networkipv4__oct3', '-networkipv4__oct4', '-networkipv4__block', '-networkipv6__block1', '-networkipv6__block2', '-networkipv6__block3', '-networkipv6__block4', '-networkipv6__block5', '-networkipv6__block6', '-networkipv6__block7', '-networkipv6__block8', '-networkipv6__block') asorting_cols.remove('-network') vlans = vlans.distinct() # Datatable paginator vlans, total = build_query_to_datatable(vlans, asorting_cols, custom_search, searchable_columns, start_record, end_record) vlans = vlans.prefetch_related( 'ambiente', 'networkipv4_set__network_type', 'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente', 'networkipv6_set__network_type', 'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente' ) itens = get_networks(vlans, False) vlan_map = dict() vlan_map['vlan'] = itens vlan_map['total'] = total return self.response(dumps_networkapi(vlan_map))
def handle_put(self, request, user, *args, **kwargs): """Treat requests PUT change limit connections to VIP. URLs: /vip/<id_vip>/maxcon/<maxcon>/ """ self.log.info('Change limit connections to VIP') try: vip_id = kwargs.get('id_vip') maxcon = kwargs.get('maxcon') # 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) # Valid Maxcon if not is_valid_int_greater_equal_zero_param(maxcon): self.log.error( u'The maxcon parameter is not a valid value: %s.', maxcon) raise InvalidValueError(None) # Existing Vip ID vip = RequisicaoVips.get_by_pk(vip_id) with distributedlock(LOCK_VIP % vip_id): vip_old = clone(vip) server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip) server_pools_old = [] server_pools_members_old = [] for sp in server_pools: server_pools_old.append(sp) for spm in sp.serverpoolmember_set.all(): server_pools_members_old.append(spm) # Vip must be created if not vip.vip_criado: self.log.error( u'Maxcon 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) # Get variables variables_map = vip.variables_to_map() # Valid variables vip.set_variables(variables_map) # Valid real names and real ips of real server if variables_map.get('reals') is not None: evip = EnvironmentVip.get_by_values(variables_map.get( 'finalidade'), variables_map.get('cliente'), variables_map.get('ambiente')) for real in variables_map.get('reals').get('real'): ip_aux_error = real.get('real_ip') equip_aux_error = real.get('real_name') equip = Equipamento.get_by_name(equip_aux_error) # Valid Real RequisicaoVips.valid_real_server( ip_aux_error, equip, evip) # Valid reals_prioritys variables_map, code = vip.valid_values_reals_priority( variables_map) if code is not None: return self.response_error(329) # Valid reals_weight variables_map, code = vip.valid_values_reals_weight( variables_map) if code is not None: return self.response_error(330) # Valid ports variables_map, code = vip.valid_values_ports(variables_map) if code is not None: return self.response_error(331) variables_map['maxcon'] = maxcon vip.set_variables(variables_map) vip.save(user, commit=True) # update server pool limits table # Fix #27 server_pools = ServerPool.objects.filter( vipporttopool__requisicao_vip=vip) for sp in server_pools: # If exists pool member, change default maxconn of pool and # members if(len(sp.serverpoolmember_set.all()) > 0): # if(old_maxconn != sp.default_limit and # sp.pool_created): sp.default_limit = maxcon sp.save(user, commit=True) for serverpoolmember in sp.serverpoolmember_set.all(): serverpoolmember.limit = maxcon serverpoolmember.save(user, commit=True) # gerador_vips -i <ID_REQUISICAO> --maxconn command = 'gerador_vips -i %d --maxconn' % 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: # TODO Check if is needed to update pool members separately vip_old.save(user, commit=True) for sp in server_pools_old: sp.save(user, commit=True) for spm in server_pools_members_old: spm.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)