Esempio n. 1
0
    def dissociate_environment_and_delete(self, authenticated_user, environment_id=None):
        from networkapi.requisicaovips.models import RequisicaoVips
        try:
            healthcheckexpects = HealthcheckExpect.objects.all()
            if (environment_id is not None):
                hces = healthcheckexpects.filter(ambiente__id=environment_id)
                for hce in hces:
                    vip_criado = False
                    for req_vip in RequisicaoVips.get_by_healthcheck_expect(hce.id):
                        if req_vip.vip_criado:
                            vip_criado = True

                    # If any RequsicaoVips associated, dissociate healthcheck
                    # expect from Ambiente
                    if vip_criado:
                        hce.ambiente = None
                        hce.save(authenticated_user)
                    # Else, delete HealthcheckExpect object
                    else:
                        hce.delete()

        except Exception, e:
            self.log.error(u'Falha ao desassociar os healthcheck_expects.')
            raise HealthcheckExpectError(
                e, u'Falha ao desassociar os healthcheck_expects.')
    def dissociate_environment_and_delete(self,
                                          authenticated_user,
                                          environment_id=None):
        from networkapi.requisicaovips.models import RequisicaoVips
        try:
            healthcheckexpects = HealthcheckExpect.objects.all()
            if (environment_id is not None):
                hces = healthcheckexpects.filter(ambiente__id=environment_id)
                for hce in hces:
                    vip_criado = False
                    for req_vip in RequisicaoVips.get_by_healthcheck_expect(
                            hce.id):
                        if req_vip.vip_criado:
                            vip_criado = True

                    # If any RequsicaoVips associated, dissociate healthcheck
                    # expect from Ambiente
                    if vip_criado:
                        hce.ambiente = None
                        hce.save(authenticated_user)
                    # Else, delete HealthcheckExpect object
                    else:
                        hce.delete()

        except Exception, e:
            self.log.error(u'Falha ao desassociar os healthcheck_expects.')
            raise HealthcheckExpectError(
                e, u'Falha ao desassociar os healthcheck_expects.')
    def handle_get(self, request, user, *args, **kwargs):
        """
        Handles GET requests to list all the VIPs.

        URL: vip/all/
        """

        try:
            if not has_perm(user,
                            AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            request_vips = RequisicaoVips.get_all()
            vips = {}

            for vip in request_vips:
                request_vip_map = vip.variables_to_map()
                request_vip_map['id'] = vip.id
                request_vip_map['validado'] = vip.validado
                request_vip_map['vip_criado'] = vip.vip_criado
                request_vip_map['id_ip'] = vip.ip_id
                request_vip_map['id_ipv6'] = vip.ipv6_id
                request_vip_map[
                    'id_healthcheck_expect'] = vip.healthcheck_expect_id
                vips['vip_%s' % (vip.id)] = request_vip_map

            return self.response(dumps_networkapi(vips))

        except (RequisicaoVipsNotFoundError):
            return self.response_error(152)
        except (RequisicaoVipsError, GrupoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """
        Handles GET requests to list all the VIPs.

        URL: vip/all/
        """

        try:
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            request_vips = RequisicaoVips.get_all()
            vips = {}

            for vip in request_vips:
                request_vip_map = vip.variables_to_map()
                request_vip_map['id'] = vip.id
                request_vip_map['validado'] = vip.validado
                request_vip_map['vip_criado'] = vip.vip_criado
                request_vip_map['id_ip'] = vip.ip_id
                request_vip_map['id_ipv6'] = vip.ipv6_id
                request_vip_map[
                    'id_healthcheck_expect'] = vip.healthcheck_expect_id
                vips['vip_%s' % (vip.id)] = request_vip_map

            return self.response(dumps_networkapi(vips))

        except (RequisicaoVipsNotFoundError):
            return self.response_error(152)
        except (RequisicaoVipsError, GrupoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para listar uma requisição de VIP.

        Filtra a requisição de VIP por chave primária.

        URL: vip/id_vip
        """

        try:
            if kwargs.get('id_vip') is None:
                return super(RequisicaoVipsResource,
                             self).handle_get(request, user, *args, **kwargs)

            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Valid Ip ID
            if not is_valid_int_greater_zero_param(kwargs.get('id_vip')):
                self.log.error(
                    u'The id_vip parameter is not a valid value: %s.',
                    kwargs.get('id_vip'))
                raise InvalidValueError(None, 'id_vip', kwargs.get('id_vip'))

            request_vip = RequisicaoVips.get_by_pk(kwargs.get('id_vip'))

            request_vip_map = request_vip.variables_to_map()
            """"""
            vip_port_list, reals_list, reals_priority, reals_weight = request_vip.get_vips_and_reals(
                request_vip.id)

            if reals_list:
                request_vip_map['reals'] = {'real': reals_list}
                request_vip_map['reals_prioritys'] = {
                    'reals_priority': reals_priority
                }
                request_vip_map['reals_weights'] = {
                    'reals_weight': reals_weight
                }

            request_vip_map['portas_servicos'] = {'porta': vip_port_list}
            """"""

            request_vip_map['id'] = request_vip.id
            request_vip_map['validado'] = convert_boolean_to_int(
                request_vip.validado)
            request_vip_map['vip_criado'] = convert_boolean_to_int(
                request_vip.vip_criado)
            request_vip_map['id_ip'] = request_vip.ip_id
            request_vip_map['id_ipv6'] = request_vip.ipv6_id
            request_vip_map[
                'id_healthcheck_expect'] = request_vip.healthcheck_expect_id
            request_vip_map['l7_filter'] = request_vip.l7_filter
            request_vip_map['rule_id'] = request_vip.rule_id

            return self.response(dumps_networkapi({'vip': request_vip_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para listar uma requisição de VIP.

        Filtra a requisição de VIP por chave primária.

        URL: vip/id_vip
        """

        try:
            if kwargs.get('id_vip') is None:
                return super(RequisicaoVipsResource, self).handle_get(request, user, *args, **kwargs)

            if not has_perm(user,
                            AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Valid Ip ID
            if not is_valid_int_greater_zero_param(kwargs.get('id_vip')):
                self.log.error(
                    u'The id_vip parameter is not a valid value: %s.', kwargs.get('id_vip'))
                raise InvalidValueError(None, 'id_vip', kwargs.get('id_vip'))

            request_vip = RequisicaoVips.get_by_pk(kwargs.get('id_vip'))

            request_vip_map = request_vip.variables_to_map()

            """"""
            vip_port_list, reals_list, reals_priority, reals_weight = request_vip.get_vips_and_reals(
                request_vip.id)

            if reals_list:
                request_vip_map['reals'] = {'real': reals_list}
                request_vip_map['reals_prioritys'] = {
                    'reals_priority': reals_priority}
                request_vip_map['reals_weights'] = {
                    'reals_weight': reals_weight}

            request_vip_map['portas_servicos'] = {'porta': vip_port_list}

            """"""

            request_vip_map['id'] = request_vip.id
            request_vip_map['validado'] = convert_boolean_to_int(
                request_vip.validado)
            request_vip_map['vip_criado'] = convert_boolean_to_int(
                request_vip.vip_criado)
            request_vip_map['id_ip'] = request_vip.ip_id
            request_vip_map['id_ipv6'] = request_vip.ipv6_id
            request_vip_map[
                'id_healthcheck_expect'] = request_vip.healthcheck_expect_id
            request_vip_map['l7_filter'] = request_vip.l7_filter
            request_vip_map['rule_id'] = request_vip.rule_id

            return self.response(dumps_networkapi({'vip': request_vip_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Esempio n. 7
0
    def setUp(self):
        self.client = Client()
        self.mock_distributed_lock()

        #workaround on model loading issue
        #http://stackoverflow.com/questions/14386536/instantiating-django-model-raises-typeerror-isinstance-arg-2-must-be-a-class
        if not model_cache.loaded: model_cache._populate()

        self.ip = Ip(oct1 = 192, oct2 = 168, oct3 = 0, oct4 = 15)
        self.vip = RequisicaoVips(id = 1, ip = self.ip)
Esempio n. 8
0
    def is_ipv6_in_use(self, ipv6, vip_id):

        is_in_use = True
        pool_member_count = ServerPoolMember.objects.filter(ipv6=ipv6).exclude(
            server_pool__vipporttopool__requisicao_vip__ipv6=vip_id).count()
        vip_count = RequisicaoVips.get_by_ipv6_id(
            ipv6.id).exclude(pk=vip_id).count()
        if vip_count == 0 and pool_member_count == 0:
            is_in_use = False

        return is_in_use
    def is_ipv6_in_use(self, ipv6, vip_id):

        is_in_use = True
        pool_member_count = ServerPoolMember.objects.filter(ipv6=ipv6).exclude(
            server_pool__vipporttopool__requisicao_vip__ipv6=vip_id).count()
        vip_count = RequisicaoVips.get_by_ipv6_id(
            ipv6.id).exclude(pk=vip_id).count()
        if vip_count == 0 and pool_member_count == 0:
            is_in_use = False

        return is_in_use
Esempio n. 10
0
    def handle_delete(self, request, user, *args, **kwargs):
        """
        Treat DELETE requests to remove a vip request.
        Also remove reals related and balancer ips (if this ips isn't used for another vip).

        URL: vip/delete/<id_vip>/
        """

        try:
            vip_id = kwargs.get('id_vip')
            keep_ip = bool(request.REQUEST.get('keep_ip', False))

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Valid vip ID
            if not is_valid_int_greater_zero_param(vip_id):
                self.log.error(u'Parameter id_vip is invalid. Value: %s.',
                               vip_id)
                raise InvalidValueError(None, 'id_vip', vip_id)

            vip = RequisicaoVips.get_by_pk(vip_id)

            if vip.vip_criado:
                return self.response_error(370, vip_id)

            ipv4 = vip.ip
            ipv6 = vip.ipv6

            with distributedlock(LOCK_VIP % vip_id):
                try:
                    vip.delete_vips_and_reals(user)

                    vip.remove(user, vip_id)

                    # SYNC_VIP
                    delete_new(vip_id)

                    if ipv4 and not keep_ip:
                        if not self.is_ipv4_in_use(ipv4, vip_id):
                            ipv4.delete()
                    if ipv6 and not keep_ip:
                        if not self.is_ipv6_in_use(ipv6, vip_id):
                            ipv6.delete()
                except IpCantRemoveFromServerPool, e:
                    raise e
                except IpCantBeRemovedFromVip, e:
                    raise e
    def handle_delete(self, request, user, *args, **kwargs):
        """
        Treat DELETE requests to remove a vip request.
        Also remove reals related and balancer ips (if this ips isn't used for another vip).

        URL: vip/delete/<id_vip>/
        """

        try:
            vip_id = kwargs.get('id_vip')
            keep_ip = bool(request.REQUEST.get('keep_ip', False))

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Valid vip ID
            if not is_valid_int_greater_zero_param(vip_id):
                self.log.error(
                    u'Parameter id_vip is invalid. Value: %s.', vip_id)
                raise InvalidValueError(None, 'id_vip', vip_id)

            vip = RequisicaoVips.get_by_pk(vip_id)

            if vip.vip_criado:
                return self.response_error(370, vip_id)

            ipv4 = vip.ip
            ipv6 = vip.ipv6

            with distributedlock(LOCK_VIP % vip_id):
                try:
                    vip.delete_vips_and_reals(user)

                    vip.remove(user, vip_id)

                    # SYNC_VIP
                    delete_new(vip_id)

                    if ipv4 and not keep_ip:
                        if not self.is_ipv4_in_use(ipv4, vip_id):
                            ipv4.delete()
                    if ipv6 and not keep_ip:
                        if not self.is_ipv6_in_use(ipv6, vip_id):
                            ipv6.delete()
                except IpCantRemoveFromServerPool, e:
                    raise e
                except IpCantBeRemovedFromVip, e:
                    raise e
Esempio n. 12
0
def create_vip_request(vip_request, user):
    """
    Create Vip Request
    """
    # Remove when RequisicaoVips is die
    req = RequisicaoVips()
    req.save()

    vip = models.VipRequest()
    vip.id = req.id
    vip.name = vip_request['name']
    vip.service = vip_request['service']
    vip.business = vip_request['business']
    vip.environmentvip_id = vip_request['environmentvip']
    vip.ipv4 = Ip.get_by_pk(
        vip_request['ipv4']) if vip_request['ipv4'] else None
    vip.ipv6 = Ipv6.get_by_pk(
        vip_request['ipv6']) if vip_request['ipv6'] else None

    option_create = [
        vip_request['options'][key] for key in vip_request['options']
    ]
    vip.save()

    _create_port(vip_request['ports'], vip)
    _create_option(option_create, vip.id)

    # perms
    groups_perm = vip_request.get('groups_permissions', [])
    groups_perm += facade_usr.get_groups(
        vip_request.get('users_permissions', []))
    groups = facade_usr.reduce_groups(groups_perm)
    create_groups_permissions(groups, vip.id, user)

    # sync with old tables
    syncs.new_to_old(vip)

    return vip
Esempio n. 13
0
    def handle_put(self, request, user, *args, **kwargs):
        """ Handles a PUT request to edit the L7 filter.

        URL: vip/<id_vip>/filter/
        """

        if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT,
                        AdminPermission.WRITE_OPERATION):
            return self.not_authorized()

        id_vip = kwargs.get('id_vip')

        # 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.')

        vip = RequisicaoVips.get_by_pk(id_vip)

        # Get XML data
        l7_filter = vip_map['l7_filter']

        vip.l7_filter = l7_filter
        vip.filter_valid = False

        # If the l7_filter is a rule, set filter_valid to TRUE
        if vip_map.get('rule_id') is not None:
            vip.filter_valid = 1
            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.filter_valid = 0
            vip.rule = None

        vip.save()

        map = dict()
        map['sucesso'] = 'sucesso'
        return self.response(dumps_networkapi(map))
    def handle_put(self, request, user, *args, **kwargs):
        """ Handles a PUT request to edit the L7 filter.

        URL: vip/<id_vip>/filter/
        """

        if not has_perm(user,
                        AdminPermission.VIP_ALTER_SCRIPT,
                        AdminPermission.WRITE_OPERATION):
            return self.not_authorized()

        id_vip = kwargs.get('id_vip')

        # 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.')

        vip = RequisicaoVips.get_by_pk(id_vip)

        # Get XML data
        l7_filter = vip_map['l7_filter']

        vip.l7_filter = l7_filter
        vip.filter_valid = False

        # If the l7_filter is a rule, set filter_valid to TRUE
        if vip_map.get('rule_id') is not None:
            vip.filter_valid = 1
            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.filter_valid = 0
            vip.rule = None

        vip.save(user)

        map = dict()
        map['sucesso'] = 'sucesso'
        return self.response(dumps_networkapi(map))
    def handle_get(self, request, user, *args, **kwargs):
        """Handles get requests to validate Vip Requests by id.

        URLs: /vip/validate/<id_vip>/
        """

        self.log.info('Validate Vip Request by id')

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            id_vip = kwargs.get('id_vip')

            # Valid vip id
            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(u'Parameter id_vip is invalid. Value: %s.',
                               id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):
                vip.validado = True
                vip.save()

            return self.response(dumps_networkapi({}))

        except RequisicaoVipsNotFoundError:
            return self.response_error(152)
        except RequisicaoVipsError:
            return self.response_error(150, 'Failed to validate vip request.')
        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles get requests to validate Vip Requests by id.

        URLs: /vip/validate/<id_vip>/
        """

        self.log.info('Validate Vip Request by id')

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            id_vip = kwargs.get('id_vip')

            # Valid vip id
            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'Parameter id_vip is invalid. Value: %s.', id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):
                vip.validado = True
                vip.save()

            return self.response(dumps_networkapi({}))

        except RequisicaoVipsNotFoundError:
            return self.response_error(152)
        except RequisicaoVipsError:
            return self.response_error(150, 'Failed to validate vip request.')
        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
Esempio n. 17
0
    def handle_get(self, request, user, *args, **kwargs):
        """Validate L7 filter

        URLs: /vip/l7/<id_vip>/validate/
        """
        try:

            if not has_perm(user, AdminPermission.VIP_VALIDATION,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            self.log.info("Validate L7 filter to VIP")

            id_vip = kwargs.get('id_vip')

            # Valid Vip ID
            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'The vip_id parameter is not a valid value: %s.', id_vip)
                raise InvalidValueError(None)

            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):

                # Vip must be created
                if not vip.vip_criado:
                    self.log.error(
                        u'L7 filter can not be changed because VIP has not yet been created.'
                    )
                    raise RequestVipsNotBeenCreatedError(None)

                vip.filter_valid = True

                vip.save()

                map = dict()
                map['sucesso'] = 'sucesso'
                return self.response(dumps_networkapi(map))

        except UserNotAuthorizedError:
            return self.not_authorized()
    def handle_get(self, request, user, *args, **kwargs):
        """Validate L7 filter

        URLs: /vip/l7/<id_vip>/validate/
        """
        try:

            if not has_perm(user,
                            AdminPermission.VIP_VALIDATION,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            self.log.info('Validate L7 filter to VIP')

            id_vip = kwargs.get('id_vip')

            # Valid Vip ID
            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'The vip_id parameter is not a valid value: %s.', id_vip)
                raise InvalidValueError(None)

            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):

                # Vip must be created
                if not vip.vip_criado:
                    self.log.error(
                        u'L7 filter can not be changed because VIP has not yet been created.')
                    raise RequestVipsNotBeenCreatedError(None)

                vip.filter_valid = True

                vip.save()

                map = dict()
                map['sucesso'] = 'sucesso'
                return self.response(dumps_networkapi(map))

        except UserNotAuthorizedError:
            return self.not_authorized()
Esempio n. 19
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles a GET request to return L7 data

        URL: vip/l7/<id_vip>/
        """

        try:
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Valid Ip ID
            if not is_valid_int_greater_zero_param(kwargs.get('id_vip')):
                self.log.error(
                    u'The id_vip parameter is not a valid value: %s.',
                    kwargs.get('id_vip'))
                raise InvalidValueError(None, 'id_vip', kwargs.get('id_vip'))

            request_vip = RequisicaoVips.get_by_pk(kwargs.get('id_vip'))

            date = request_vip.applied_l7_datetime

            if date:
                date = date.strftime('%d/%m/%Y %H:%M:%S')

            request_vip_map = dict()
            request_vip_map['l7_filter'] = request_vip.l7_filter
            request_vip_map['rule'] = request_vip.rule
            request_vip_map['filter_applied'] = request_vip.filter_applied
            request_vip_map['rule_applied'] = request_vip.rule_applied
            request_vip_map['filter_rollback'] = request_vip.filter_rollback
            request_vip_map['rule_rollback'] = request_vip.rule_rollback
            request_vip_map['applied_l7_datetime'] = date
            request_vip_map['filter_valid'] = convert_boolean_to_int(
                request_vip.filter_valid)

            return self.response(dumps_networkapi({'vip': request_vip_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles a GET request to return L7 data

        URL: vip/l7/<id_vip>/
        """

        try:
            if not has_perm(user,
                            AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Valid Ip ID
            if not is_valid_int_greater_zero_param(kwargs.get('id_vip')):
                self.log.error(
                    u'The id_vip parameter is not a valid value: %s.', kwargs.get('id_vip'))
                raise InvalidValueError(None, 'id_vip', kwargs.get('id_vip'))

            request_vip = RequisicaoVips.get_by_pk(kwargs.get('id_vip'))

            date = request_vip.applied_l7_datetime

            if date:
                date = date.strftime('%d/%m/%Y %H:%M:%S')

            request_vip_map = dict()
            request_vip_map['l7_filter'] = request_vip.l7_filter
            request_vip_map['rule'] = request_vip.rule
            request_vip_map['filter_applied'] = request_vip.filter_applied
            request_vip_map['rule_applied'] = request_vip.rule_applied
            request_vip_map['filter_rollback'] = request_vip.filter_rollback
            request_vip_map['rule_rollback'] = request_vip.rule_rollback
            request_vip_map['applied_l7_datetime'] = date
            request_vip_map['filter_valid'] = convert_boolean_to_int(
                request_vip.filter_valid)

            return self.response(dumps_networkapi({'vip': request_vip_map}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    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))
        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')

            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):
    def administrate_real(self, user, vip_id, equip_id, ip_id, operation, network_version, port_vip=None, port_real=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 Equipament ID
        if not is_valid_int_greater_zero_param(equip_id):
            self.log.error(
                u'The equip_id parameter is not a valid value: %s.', equip_id)
            raise InvalidValueError(None, 'equip_id', equip_id)

        # Valid IP ID
        if not is_valid_int_greater_zero_param(ip_id):
            self.log.error(
                u'The ip_id parameter is not a valid value: %s.', ip_id)
            raise InvalidValueError(None, 'ip_id', ip_id)

        # Valid operation
        if operation not in ['add', 'del', 'ena', 'dis', 'chk']:
            self.log.error(
                u'The operation parameter is not a valid value: %s.', operation)
            raise InvalidValueError(None, 'operation', operation)

        # Valid network version
        if network_version not in ['v4', 'v6']:
            self.log.error(
                u'The network_version parameter is not a valid value: %s.', network_version)
            raise InvalidValueError(None, 'network_version', network_version)

        # User permission
        if (operation == 'chk'):
            if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)
        else:
            if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, AdminPermission.WRITE_OPERATION, None, equip_id, AdminPermission.EQUIP_UPDATE_CONFIG_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

        # new_call = True - New calls for Add/Del/Enable/Disable/Check with new params (Port Vip and Port Real)
        # new_call = False = Old calls for compatibility
        new_call = False
        if port_vip != None and port_real != None:
            # Valid ports
            if not is_valid_int_greater_zero_param(port_vip):
                self.log.error(
                    u'The port_vip parameter is not a valid value: %s.', port_vip)
                raise InvalidValueError(None, 'port_vip', port_vip)

            if not is_valid_int_greater_zero_param(port_real):
                self.log.error(
                    u'The port_vip parameter is not a valid value: %s.', port_real)
                raise InvalidValueError(None, 'port_real', port_real)

            new_call = True

        # Find Request VIP by ID to check if it exist
        vip = RequisicaoVips.get_by_pk(vip_id)
        # 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 network_version - IPv4
        if network_version == IP_VERSION.IPv4[0]:

            # Find IpEquipamento to check if it exist
            IpEquip = IpEquipamento().get_by_ip_equipment(ip_id, equip_id)

            real_name = IpEquip.equipamento.nome
            end_ip = "%s.%s.%s.%s" % (
                IpEquip.ip.oct1, IpEquip.ip.oct2, IpEquip.ip.oct3, IpEquip.ip.oct4)

            # Valid Real
            RequisicaoVips.valid_real_server(end_ip, IpEquip.equipamento, evip, False)

        # Valid network_version - IPv6
        elif network_version == IP_VERSION.IPv6[0]:

            # Find Ipv6Equipament to check if it exist
            Ipv6Equip = Ipv6Equipament().get_by_ip_equipment(ip_id, equip_id)

            real_name = Ipv6Equip.equipamento.nome
            end_ip = "%s:%s:%s:%s:%s:%s:%s:%s" % (Ipv6Equip.ip.block1, Ipv6Equip.ip.block2, Ipv6Equip.ip.block3,
                                                  Ipv6Equip.ip.block4, Ipv6Equip.ip.block5, Ipv6Equip.ip.block6, Ipv6Equip.ip.block7, Ipv6Equip.ip.block8)

            # Valid Real
            RequisicaoVips.valid_real_server(end_ip, Ipv6Equip.equipamento, evip, False)

        if (operation == 'chk'):

            if IP_VERSION.IPv4[0] == network_version:
                if new_call:
                    command = VIP_REALS_v4_CHECK % (
                        vip_id, ip_id, port_real, port_vip)
                else:
                    command = VIP_REAL_v4_CHECK % (vip_id, real_name, end_ip)
            else:
                if new_call:
                    command = VIP_REALS_v6_CHECK % (
                        vip_id, ip_id, port_real, port_vip)
                else:
                    command = VIP_REAL_v6_CHECK % (vip_id, real_name, end_ip)
        else:

            with distributedlock(LOCK_VIP_IP_EQUIP % (vip_id, ip_id, equip_id)):

                if (operation == 'add'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_CREATE % (
                                vip_id, ip_id, port_real, port_vip)
                            ServerPoolMember().save_specified_port(
                                vip_id, port_vip, IpEquip.ip, IP_VERSION.IPv4[1], port_real, user)
                        else:
                            command = VIP_REAL_v4_CREATE % (
                                vip_id, real_name, end_ip)
                            ServerPoolMember().save_with_default_port(
                                vip_id, IpEquip.ip, IP_VERSION.IPv4[1], user)

                    else:
                        if new_call:
                            command = VIP_REALS_v6_CREATE % (
                                vip_id, ip_id, port_real, port_vip)
                            ServerPoolMember().save_specified_port(
                                vip_id, port_vip, Ipv6Equip.ip, IP_VERSION.IPv6[1], port_real, user)
                        else:
                            command = VIP_REAL_v6_CREATE % (
                                vip_id, real_name, end_ip)
                            ServerPoolMember().save_with_default_port(
                                vip_id, Ipv6Equip.ip, IP_VERSION.IPv6[1], user)

                elif (operation == 'del'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_REMOVE % (
                                vip_id, ip_id, port_real, port_vip)
                            pool_members = ServerPoolMember.objects.filter(
                                ip=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id, server_pool__vipporttopool__port_vip=port_vip, port_real=port_real)
                            [pool_member.delete()
                             for pool_member in pool_members]
                        else:
                            command = VIP_REAL_v4_REMOVE % (
                                vip_id, real_name, end_ip)
                            pool_members = ServerPoolMember.objects.filter(
                                ip=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id)
                            [pool_member.delete()
                             for pool_member in pool_members]
                    else:
                        if new_call:
                            command = VIP_REALS_v6_REMOVE % (
                                vip_id, ip_id, port_real, port_vip)
                            pool_members = ServerPoolMember.objects.filter(
                                ipv6=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id, server_pool__vipporttopool__port_vip=port_vip, port_real=port_real)
                            [pool_member.delete()
                             for pool_member in pool_members]
                        else:
                            command = VIP_REAL_v6_REMOVE % (
                                vip_id, real_name, end_ip)
                            pool_members = ServerPoolMember.objects.filter(
                                ipv6=ip_id, server_pool__vipporttopool__requisicao_vip__id=vip_id)
                            [pool_member.delete()
                             for pool_member in pool_members]

                elif (operation == 'ena'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_ENABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_ENABLE % (
                                vip_id, real_name, end_ip)
                    else:
                        if new_call:
                            command = VIP_REALS_v6_ENABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_ENABLE % (
                                vip_id, real_name, end_ip)

                elif (operation == 'dis'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_DISABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_DISABLE % (
                                vip_id, real_name, end_ip)
                    else:
                        if new_call:
                            command = VIP_REALS_v6_DISABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_DISABLE % (
                                vip_id, real_name, end_ip)

        self.log.info(command)
        # Execute script
        code, stdout, stderr = exec_script(command)
        self.log.info(stdout)

        map = dict()
        success_map = dict()

        # Return XML
        if code == 0:
            success_map['codigo'] = '%04d' % code
            success_map['descricao'] = {'stdout': stdout, 'stderr': stderr}

            map['sucesso'] = success_map
            return self.response(dumps_networkapi(map))

        elif code == 12:
            success_map['codigo'] = '0'
            success_map['descricao'] = {'stdout': '0', 'stderr': ''}

            map['sucesso'] = success_map
            self.rollback_changes(operation, new_call, network_version,
                                  vip_id, ip_id, port_real, port_vip, real_name, end_ip, user)
            return self.response(dumps_networkapi(map))

        else:
            self.rollback_changes(operation, new_call, network_version,
                                  vip_id, ip_id, port_real, port_vip, real_name, end_ip, user)
            return self.response_error(2, stdout + stderr)
    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)
Esempio n. 25
0
    def __post_virtual_group_vip(self, vip_maps, user, vip_equipment_ip_map,
                                 resp_vip_maps):
        try:
            for vip_map in vip_maps:
                resp_vip_map = dict()

                vip_id = vip_map.get('id')

                resp_vip_map['id'] = vip_id

                id_vip_request_map = vip_map.get('requisicao_vip')

                ip_map = vip_map.get('ip')

                # Somente insere o IP do VIP se a requisição de VIP ainda não foi criada
                # (id_vip_request_map is None).

                if (ip_map is not None) and (id_vip_request_map is None):

                    # Insere o IP do VIP e o associa aos balanceadores

                    balanceadores_map = vip_map.get('balanceadores')
                    if balanceadores_map is None:
                        return self.response_error(
                            3,
                            u'Não existe valor para a tag balanceadors do vip %s do XML de requisição.'
                            % vip_id)

                    equipments_ids = balanceadores_map.get('id_equipamento')
                    if len(equipments_ids) == 0:
                        return self.response_error(
                            3,
                            u'Não existe valor para a tag id_equipamento do vip %s do XML de requisição.'
                            % vip_id)

                    # Insere um IP e o relacionamento dele com o primeiro
                    # balanceador
                    equip_id = equipments_ids[0]
                    ip_map['id_equipamento'] = equip_id
                    response_ip = insert_ip(ip_map, user)
                    if response_ip[0] != 0:
                        return self.__treat_response_error(response_ip)

                    # Insere o relacionamento entre o IP e os demais
                    # balanceadores
                    for equip_id in equipments_ids[1:len(equipments_ids)]:
                        insert_ip_equipment(response_ip[1].get('id'), equip_id,
                                            user)

                    resp_vip_map['ip'] = response_ip[1]

                    vip_map['id_ip'] = response_ip[1].get('id')

                # Constroe o reals

                # Obtem os reals já criados e que foram enviados no XML de
                # requisição
                reals_map = vip_map.get('reals')
                if reals_map is not None:
                    real_maps = reals_map.get('real', [])
                else:
                    real_maps = []

                # Adiciona os novos reals para os equipamentos criados
                equipment_ip_maps = vip_equipment_ip_map.get(vip_id)
                if equipment_ip_maps is not None:
                    for equipment_ip_map in equipment_ip_maps:
                        real_name = equipment_ip_map.get(
                            'nome_equipamento')  # + sufix
                        real_ip = equipment_ip_map.get('ip')
                        real_maps.append({
                            'real_name': real_name,
                            'real_ip': real_ip
                        })

                vip_map['reals'] = {'real': real_maps}

                reals_priority_map = vip_map.get('reals_prioritys')
                if reals_priority_map is not None:
                    reals_priority_map = reals_priority_map.get(
                        'reals_priority')
                    if reals_priority_map is None:
                        reals_priority_map = ['0' for __real in real_maps]
                else:
                    reals_priority_map = ['0' for __real in real_maps]

                vip_map['reals_prioritys'] = {
                    'reals_priority': reals_priority_map
                }

                reals_weight_map = vip_map.get('reals_weights')
                if reals_weight_map is not None:
                    reals_weight_map = reals_weight_map.get('reals_weight')
                    if reals_weight_map is None:
                        reals_weight_map = ['0' for __real in real_maps]
                else:
                    reals_weight_map = ['0' for __real in real_maps]

                vip_map['reals_weights'] = {'reals_weight': reals_weight_map}

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(
                        vip_map.get('finalidade'), vip_map.get('cliente'),
                        vip_map.get('ambiente'))

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_id = real.get('real_name')
                        if equip_id is not None:
                            equip = Equipamento.get_by_name(equip_id)
                        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)

                        vip_map, code = RequisicaoVips(
                        ).valid_values_reals_priority(vip_map)
                        if code is not None:
                            return self.response_error(code)

                        vip_map, code = RequisicaoVips(
                        ).valid_values_reals_weight(vip_map)
                        if code is not None:
                            return self.response_error(code)

                # Insere ou atualiza a requisição de VIP
                if (id_vip_request_map is not None):

                    resp_vip_map['requisicao_vip'] = id_vip_request_map

                    if not is_valid_int_greater_zero_param(
                            id_vip_request_map.get('id')):
                        self.log.error(
                            u'The requisicao_vip.id parameter is not a valid value: %s.',
                            id_vip_request_map.get('id'))
                        raise InvalidValueError(None, 'requisicao_vip.id',
                                                id_vip_request_map.get('id'))

                    vip_request = RequisicaoVips.get_by_pk(
                        id_vip_request_map.get('id'))

                    vip_map['id_ip'] = vip_request.ip_id
                    if vip_request.validado:
                        vip_map['validado'] = '1'
                    else:
                        vip_map['validado'] = '0'
                    if vip_request.vip_criado:
                        vip_map['vip_criado'] = '1'
                    else:
                        vip_map['vip_criado'] = '0'

                    response_vip = update_vip_request(vip_request.id, vip_map,
                                                      user)
                    if (response_vip != 0):
                        return self.response_error(response_vip)

                else:
                    """This condition is used to attend a requisite from 'Orquestra',
                       because in some points the VIP doesn't have cache option and
                       the value can be 'None'"""
                    if vip_map['cache'] is None:
                        vip_map['cache'] = '(nenhum)'

                    response_vip = insert_vip_request(vip_map, user)
                    if (response_vip[0] != 0):
                        if response_vip[0] not in (275, 276, 277):
                            return self.__treat_response_error(response_vip)
                        else:
                            return self.__treat_response_error(
                                [response_vip[0]])

                    resp_vip_map['requisicao_vip'] = {'id': response_vip[1].id}

                resp_vip_maps.append(resp_vip_map)

        except EnvironmentVipNotFoundError:
            return self.response_error(316, vip_map['finalidade'],
                                       vip_map['cliente'], vip_map['ambiente'])
        except RequisicaoVipsNotFoundError:
            return self.response_error(152)
        except HealthcheckExpectNotFoundError:
            return self.response_error(124)
        except InvalidFinalidadeValueError:
            return self.response_error(125)
        except InvalidClienteValueError:
            return self.response_error(126)
        except InvalidAmbienteValueError:
            return self.response_error(127)
        except InvalidCacheValueError:
            return self.response_error(128)
        except InvalidMetodoBalValueError:
            return self.response_error(131)
        except InvalidPersistenciaValueError:
            return self.response_error(132)
        except InvalidHealthcheckTypeValueError:
            return self.response_error(133)
        except InvalidHealthcheckValueError:
            return self.response_error(134)
        except InvalidTimeoutValueError:
            return self.response_error(135)
        except InvalidHostNameError:
            return self.response_error(136)
        except InvalidMaxConValueError:
            return self.response_error(137)
        except InvalidBalAtivoValueError:
            return self.response_error(129)
        except InvalidTransbordoValueError, t:
            transbordo = 'nulo'
            if t.message is not None:
                transbordo = t.message
            return self.response_error(130, transbordo)
    def __post_virtual_group_vip(self, vip_maps, user, vip_equipment_ip_map, resp_vip_maps):
        try:
            for vip_map in vip_maps:
                resp_vip_map = dict()

                vip_id = vip_map.get('id')

                resp_vip_map['id'] = vip_id

                id_vip_request_map = vip_map.get('requisicao_vip')

                ip_map = vip_map.get('ip')

                # Somente insere o IP do VIP se a requisição de VIP ainda não foi criada
                # (id_vip_request_map is None).

                if (ip_map is not None) and (id_vip_request_map is None):

                    # Insere o IP do VIP e o associa aos balanceadores

                    balanceadores_map = vip_map.get('balanceadores')
                    if balanceadores_map is None:
                        return self.response_error(3, u'Não existe valor para a tag balanceadors do vip %s do XML de requisição.' % vip_id)

                    equipments_ids = balanceadores_map.get('id_equipamento')
                    if len(equipments_ids) == 0:
                        return self.response_error(3, u'Não existe valor para a tag id_equipamento do vip %s do XML de requisição.' % vip_id)

                    # Insere um IP e o relacionamento dele com o primeiro
                    # balanceador
                    equip_id = equipments_ids[0]
                    ip_map['id_equipamento'] = equip_id
                    response_ip = insert_ip(ip_map, user)
                    if response_ip[0] != 0:
                        return self.__treat_response_error(response_ip)

                    # Insere o relacionamento entre o IP e os demais
                    # balanceadores
                    for equip_id in equipments_ids[1:len(equipments_ids)]:
                        insert_ip_equipment(
                            response_ip[1].get('id'), equip_id, user)

                    resp_vip_map['ip'] = response_ip[1]

                    vip_map['id_ip'] = response_ip[1].get('id')

                # Constroe o reals

                # Obtem os reals já criados e que foram enviados no XML de
                # requisição
                reals_map = vip_map.get('reals')
                if reals_map is not None:
                    real_maps = reals_map.get('real', [])
                else:
                    real_maps = []

                # Adiciona os novos reals para os equipamentos criados
                equipment_ip_maps = vip_equipment_ip_map.get(vip_id)
                if equipment_ip_maps is not None:
                    for equipment_ip_map in equipment_ip_maps:
                        real_name = equipment_ip_map.get(
                            'nome_equipamento')  # + sufix
                        real_ip = equipment_ip_map.get('ip')
                        real_maps.append(
                            {'real_name': real_name, 'real_ip': real_ip})

                vip_map['reals'] = {'real': real_maps}

                reals_priority_map = vip_map.get('reals_prioritys')
                if reals_priority_map is not None:
                    reals_priority_map = reals_priority_map.get(
                        'reals_priority')
                    if reals_priority_map is None:
                        reals_priority_map = ['0' for __real in real_maps]
                else:
                    reals_priority_map = ['0' for __real in real_maps]

                vip_map['reals_prioritys'] = {
                    'reals_priority': reals_priority_map}

                reals_weight_map = vip_map.get('reals_weights')
                if reals_weight_map is not None:
                    reals_weight_map = reals_weight_map.get('reals_weight')
                    if reals_weight_map is None:
                        reals_weight_map = ['0' for __real in real_maps]
                else:
                    reals_weight_map = ['0' for __real in real_maps]

                vip_map['reals_weights'] = {'reals_weight': reals_weight_map}

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(
                        vip_map.get('finalidade'), vip_map.get('cliente'), vip_map.get('ambiente'))

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_id = real.get('real_name')
                        if equip_id is not None:
                            equip = Equipamento.get_by_name(equip_id)
                        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)

                        vip_map, code = RequisicaoVips().valid_values_reals_priority(
                            vip_map)
                        if code is not None:
                            return self.response_error(code)

                        vip_map, code = RequisicaoVips().valid_values_reals_weight(
                            vip_map)
                        if code is not None:
                            return self.response_error(code)

                # Insere ou atualiza a requisição de VIP
                if (id_vip_request_map is not None):

                    resp_vip_map['requisicao_vip'] = id_vip_request_map

                    if not is_valid_int_greater_zero_param(id_vip_request_map.get('id')):
                        self.log.error(
                            u'The requisicao_vip.id parameter is not a valid value: %s.', id_vip_request_map.get('id'))
                        raise InvalidValueError(
                            None, 'requisicao_vip.id', id_vip_request_map.get('id'))

                    vip_request = RequisicaoVips.get_by_pk(
                        id_vip_request_map.get('id'))

                    vip_map['id_ip'] = vip_request.ip_id
                    if vip_request.validado:
                        vip_map['validado'] = '1'
                    else:
                        vip_map['validado'] = '0'
                    if vip_request.vip_criado:
                        vip_map['vip_criado'] = '1'
                    else:
                        vip_map['vip_criado'] = '0'

                    response_vip = update_vip_request(
                        vip_request.id, vip_map, user)
                    if (response_vip != 0):
                        return self.response_error(response_vip)

                else:
                    """This condition is used to attend a requisite from 'Orquestra', 
                       because in some points the VIP doesn't have cache option and 
                       the value can be 'None'"""
                    if vip_map['cache'] is None:
                        vip_map['cache'] = "(nenhum)"

                    response_vip = insert_vip_request(vip_map, user)
                    if (response_vip[0] != 0):
                        if response_vip[0] not in (275, 276, 277):
                            return self.__treat_response_error(response_vip)
                        else:
                            return self.__treat_response_error([response_vip[0]])

                    resp_vip_map['requisicao_vip'] = {'id': response_vip[1].id}

                resp_vip_maps.append(resp_vip_map)

        except EnvironmentVipNotFoundError:
            return self.response_error(316, vip_map['finalidade'], vip_map['cliente'], vip_map['ambiente'])
        except RequisicaoVipsNotFoundError:
            return self.response_error(152)
        except HealthcheckExpectNotFoundError:
            return self.response_error(124)
        except InvalidFinalidadeValueError:
            return self.response_error(125)
        except InvalidClienteValueError:
            return self.response_error(126)
        except InvalidAmbienteValueError:
            return self.response_error(127)
        except InvalidCacheValueError:
            return self.response_error(128)
        except InvalidMetodoBalValueError:
            return self.response_error(131)
        except InvalidPersistenciaValueError:
            return self.response_error(132)
        except InvalidHealthcheckTypeValueError:
            return self.response_error(133)
        except InvalidHealthcheckValueError:
            return self.response_error(134)
        except InvalidTimeoutValueError:
            return self.response_error(135)
        except InvalidHostNameError:
            return self.response_error(136)
        except InvalidMaxConValueError:
            return self.response_error(137)
        except InvalidBalAtivoValueError:
            return self.response_error(129)
        except InvalidTransbordoValueError, t:
            transbordo = 'nulo'
            if t.message is not None:
                transbordo = t.message
            return self.response_error(130, transbordo)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all rules by Environment Vip.

        URL: environment-vip/get/rules/<id_evip>
        """

        try:

            self.log.info("GET to list all the Rules by Environment Vip.")

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            id_environment_vip = kwargs.get('id_evip')
            id_vip = kwargs.get('id_vip')

            # Valid Environment VIP ID
            if not is_valid_int_greater_zero_param(id_environment_vip):
                self.log.error(
                    u'The id_environment_vip parameter is not a valid value: %s.',
                    id_environment_vip)
                raise InvalidValueError(None, 'id_environment_vip',
                                        id_environment_vip)

            # Find Environment VIP by ID to check if it exist
            environment_vip = EnvironmentVip.get_by_pk(id_environment_vip)

            envs = list()

            for net4 in environment_vip.networkipv4_set.all():
                if net4.vlan.ambiente.id not in envs:
                    envs.append(net4.vlan.ambiente.id)

            for net6 in environment_vip.networkipv6_set.all():
                if net6.vlan.ambiente.id not in envs:
                    envs.append(net6.vlan.ambiente.id)

            if id_vip:
                if not is_valid_int_greater_zero_param(id_vip):
                    self.log.error(u'Parameter id_vip is invalid. Value: %s.',
                                   id_vip)
                    raise InvalidValueError(None, 'id_vip', id_vip)

                vip = RequisicaoVips.get_by_pk(id_vip)
                rules = Rule.objects.filter(
                    environment__id__in=envs).filter(Q(vip=vip) | Q(vip=None))
            else:
                rules = Rule.objects.filter(environment__id__in=envs, vip=None)

            rules_dict = dict()
            rules_list = []

            rules_list.append({'id': u'', 'name_rule_opt': u''})

            for rule in rules:
                rules_dict['name_rule_opt'] = rule.name
                rules_dict['id'] = rule.id
                rules_list.append(rules_dict)
                rules_dict = dict()

            return self.response(
                dumps_networkapi({'name_rule_opt': rules_list}))

        except UserNotAuthorizedError:
            return self.not_authorized()

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Esempio n. 28
0
    def handle_put(self, request, user, *args, **kwargs):
        """
        Handles PUT requests to change the VIP's healthcheck.

        URL: vip/<id_vip>/healthcheck
        """

        self.log.info("Change VIP's healthcheck")

        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'Healthcheck 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 XML data
                healthcheck_type = upper(str(vip_map['healthcheck_type']))
                healthcheck = vip_map['healthcheck']
                id_healthcheck_expect = vip_map['id_healthcheck_expect']

                vars = vip.variables_to_map()
                environment_vip = EnvironmentVip.get_by_values(
                    vars.get('finalidade'), vars.get('cliente'),
                    vars.get('ambiente'))

                healthcheck_is_valid = RequisicaoVips.heathcheck_exist(
                    healthcheck_type, environment_vip.id)

                # healthcheck_type exist'
                if not healthcheck_is_valid:
                    self.log.error(
                        u'The healthcheck_type parameter not exist.')
                    raise InvalidValueError(
                        u'The healthcheck_type parameter not exist.',
                        'healthcheck_type', healthcheck_type)

                # If healthcheck_type is not HTTP id_healthcheck_expect and
                # healthcheck must be None
                if healthcheck_type != 'HTTP':
                    if not (id_healthcheck_expect is None
                            and healthcheck is None):
                        msg = u'The healthcheck_type parameter is %s, then healthcheck and id_healthcheck_expect must be None.' % healthcheck_type
                        self.log.error(msg)
                        raise InvalidValueError(msg)
#                         return self.response_error(276)
# If healthcheck_type is 'HTTP' id_healthcheck_expect and
# healthcheck must NOT be None
                elif healthcheck_type == 'HTTP':
                    if id_healthcheck_expect is None or healthcheck is None:
                        msg = u'The healthcheck_type parameter is HTTP, then healthcheck and id_healthcheck_expect must NOT be None.'
                        self.log.error(msg)
                        raise InvalidValueError(msg)
                    else:
                        try:

                            # Valid healthcheck_expect ID
                            if not is_valid_int_greater_zero_param(
                                    id_healthcheck_expect):
                                self.log.error(
                                    u'The id_healthcheck_expect parameter is not a valid value: %s.',
                                    id_healthcheck_expect)
                                raise InvalidValueError(
                                    None, 'id_healthcheck_expect',
                                    id_healthcheck_expect)

                            # Find healthcheck_expect by ID to check if it
                            # exist
                            healthcheck_expect = HealthcheckExpect.get_by_pk(
                                id_healthcheck_expect)

                            # Check if healthcheck is a string
                            if not isinstance(healthcheck, basestring):
                                msg = u'The healthcheck must be a string.'
                                self.log.error(msg)
                                raise InvalidValueError(
                                    msg, 'healthcheck', healthcheck)

                        except HealthcheckExpectNotFoundError:
                            msg = u'The id_healthcheck_expect parameter does not exist.'
                            self.log.error(msg)
                            raise InvalidValueError(msg,
                                                    'id_healthcheck_expect',
                                                    id_healthcheck_expect)

                # Business Rules

                # Get variables
                variables_map = vip.variables_to_map()

                # Valid variables
                vip.set_variables(variables_map)

                # Set healthcheck_type
                variables_map['healthcheck_type'] = healthcheck_type

                # If healthcheck_type is HTTP
                if healthcheck_type == 'HTTP':
                    # Set healthcheck
                    variables_map['healthcheck'] = healthcheck

                    # Set id_healthcheck_expect
                    vip.healthcheck_expect = healthcheck_expect
                else:
                    # Set healthcheck to None
                    variables_map['healthcheck'] = None

                    # Set id_healthcheck_expect to None
                    vip.healthcheck_expect = None

                # Set variables
                vip.set_variables(variables_map)

                # Save VIP
                vip.save(user, commit=True)

                # Executar script

                # Put old call to work with new pool features
                # This call is deprecated
                server_pools = ServerPool.objects.filter(
                    vipporttopool__requisicao_vip=vip)
                if healthcheck is None:
                    healthcheck = ''
                if id_healthcheck_expect is None:
                    healthcheck_expect = ''
                else:
                    healthcheck_expect = healthcheck_expect.expect_string
                healthcheck_identifier = ''
                healthcheck_destination = '*:*'
                hc = get_or_create_healthcheck(user, healthcheck_expect,
                                               healthcheck_type, healthcheck,
                                               healthcheck_destination,
                                               healthcheck_identifier)
                # Applies new healthcheck in pool
                # Todo - new method
                old_healthchecks = []
                for sp in server_pools:
                    old_healthchecks.append(sp.healthcheck)
                    sp.healthcheck = hc
                    sp.save(user, commit=True)

                # gerador_vips -i <ID_REQUISICAO> --healthcheck
                command = 'gerador_vips -i %d --healthcheck' % 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:
                    old_healthchecks.reverse()
                    for sp in server_pools:
                        sp.healthcheck = old_healthchecks.pop()
                        sp.save(user, commit=True)
                    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)
Esempio n. 29
0
def new_to_old(vp):

    from networkapi.api_vip_request.models import VipRequestDSCP
    from networkapi.requisicaovips.models import DsrL3_to_Vip, \
        RequisicaoVips, VipPortToPool

    try:
        vip_map = dict()
        vip = RequisicaoVips()
        vip.id = vp.id
        vip.ip = vp.ipv4 if vp.ipv4 else None
        vip.ipv6 = vp.ipv6 if vp.ipv6 else None
        vip_map['ip'] = vp.ipv4 if vp.ipv4 else None
        vip_map['ipv6'] = vp.ipv6 if vp.ipv6 else None
        vip_map['finalidade'] = vp.environmentvip.finalidade_txt
        vip_map['cliente'] = vp.environmentvip.cliente_txt
        vip_map['ambiente'] = vp.environmentvip.ambiente_p44_txt
        for vp_optionvip in vp.viprequestoptionvip_set.all():
            if vp_optionvip.optionvip.tipo_opcao == u'Persistencia':
                vip_map['persistencia'] = vp_optionvip.optionvip.nome_opcao_txt
            if vp_optionvip.optionvip.tipo_opcao == u'timeout':
                vip_map['timeout'] = vp_optionvip.optionvip.nome_opcao_txt
            if vp_optionvip.optionvip.tipo_opcao == u'cache':
                vip_map['cache'] = vp_optionvip.optionvip.nome_opcao_txt
            if vp_optionvip.optionvip.tipo_opcao == u'Retorno de trafego':
                vip_map['trafficreturn'] = vp_optionvip.optionvip.id
                vip.trafficreturn = vp_optionvip.optionvip

        vip_map['host'] = vp.name
        vip_map['areanegocio'] = vp.business
        vip_map['nome_servico'] = vp.service
        vip_map['vip_ports_to_pools'] = list()

        ports = vp.viprequestport_set.all()

        # delete old ports
        pools_current = VipPortToPool.get_by_vip_id(vip.id)
        pools_ids = [pool.id for pool in pools_current]
        ports_ids = [pt.id for pt in ports]
        ids_to_del = list(set(pools_ids) - set(ports_ids))
        pools_current.filter(id__in=ids_to_del).delete()

        vip.vip_criado = vp.created
        vip.validado = True
        vip.save()

        for port in ports:
            pools = port.viprequestportpool_set.all()

            for pool in pools:
                if pool.optionvip.nome_opcao_txt in (u'default_vip'):
                    vip_port = {
                        'id': port.id,
                        'requisicao_vip': vip,
                        'server_pool': pool.server_pool,
                        'port_vip': port.port,
                        'identifier': port.identifier,
                    }
                    vip_map['vip_ports_to_pools'].append(vip_port)

                    vip_port_obj = VipPortToPool(**vip_port)
                    vip_port_obj.save()

        if int(vip_map['trafficreturn']) == 48:
            dsrl3 = VipRequestDSCP.objects.get(vip_request=vp)

            try:
                vp_dsrl3 = DsrL3_to_Vip.get_by_vip_id(vip.id)
            except:
                vp_dsrl3 = DsrL3_to_Vip()
                vp_dsrl3.requisicao_vip_id = vip.id

            vp_dsrl3.id_dsrl3 = dsrl3.dscp
            vp_dsrl3.save()
        else:
            try:
                vp_dsrl3 = DsrL3_to_Vip.get_by_vip_id(vip.id)
                vp_dsrl3.delete()
            except:
                pass

        vip.set_new_variables(vip_map)
        vip.save()

    except Exception, e:
        log.error(e)
        raise e
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all real related equipment.

        URLs: equipamento/get_real_related/<id_equip>
        """

        try:

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

            # Valid equipment ID
            if not is_valid_int_greater_zero_param(id_equip):
                self.log.error(
                    u'The id_equip parameter is not a valid value: %s.', id_equip)
                raise InvalidValueError(None, 'id_equip', id_equip)

            equipment = Equipamento.get_by_pk(id_equip)

            map_dicts = []

            # IPV4
            for ip_equip in equipment.ipequipamento_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv4_string(ip)})

            # IPV6
            for ip_equip in equipment.ipv6equipament_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv6_string(ip)})

            vip_map = dict()
            vip_map["vips"] = map_dicts
            vip_map["equip_name"] = equipment.nome

            # Return XML
            return self.response(dumps_networkapi(vip_map))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equip)
Esempio n. 31
0
    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_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all real related equipment.

        URLs: equipamento/get_real_related/<id_equip>
        """

        try:

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            id_equip = kwargs.get('id_equip')

            # Valid equipment ID
            if not is_valid_int_greater_zero_param(id_equip):
                self.log.error(
                    u'The id_equip parameter is not a valid value: %s.', id_equip)
                raise InvalidValueError(None, 'id_equip', id_equip)

            equipment = Equipamento.get_by_pk(id_equip)

            map_dicts = []

            # IPV4
            for ip_equip in equipment.ipequipamento_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv4_string(ip)})

            # IPV6
            for ip_equip in equipment.ipv6equipament_set.all():
                vip_dict = dict()

                ip = ip_equip.ip

                for server_pool_member in ip.serverpoolmember_set.all():
                    server_pool_id = server_pool_member.server_pool_id
                    vip_port_to_pool = VipPortToPool.objects.filter(
                        server_pool__id=server_pool_id)

                    for vptp in vip_port_to_pool:
                        vip = RequisicaoVips.get_by_pk(
                            vptp.requisicao_vip.id)

                        if vip.id not in vip_dict:
                            vip_dict = {str(vip.id): list()}

                        host_name = vip.variables_to_map()['host']

                        map_dicts.append({'server_pool_member_id': server_pool_member.id,
                                          'id_vip': vip.id,
                                          'host_name': host_name,
                                          'port_vip': vptp.port_vip,
                                          'port_real': server_pool_member.port_real,
                                          'ip': mount_ipv6_string(ip)})

            vip_map = dict()
            vip_map["vips"] = map_dicts
            vip_map["equip_name"] = equipment.nome

            # Return XML
            return self.response(dumps_networkapi(vip_map))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equip)
    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)

            # 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()

                    #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 = dict()
                        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_get(self, request, user, *args, **kwargs):
        """Rollback of the filter

        URLs: /vip/l7/<id_vip>/rollback/
        """

        self.log.info('Applies the last working filter to VIP')

        try:
            id_vip = kwargs.get('id_vip')

            # User is authorized
            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(id_vip):
                self.log.error(
                    u'The vip_id parameter is not a valid value: %s.', id_vip)
                raise InvalidValueError(None)

            # Get VIP data
            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):
                # backup do vip
                vip_old = clone(vip)

                # Vip must be created
                if not vip.vip_criado:
                    self.log.error(
                        u'Filter can not be applied because VIP has not been created yet.'
                    )
                    raise RequestVipsNotBeenCreatedError(None)

                # salva data do rollback, rollback para aplicado, passa o
                # aplicado para l7
                vip.applied_l7_datetime = datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S')

                # Set Applied With Rollback
                vip.filter_applied = vip_old.filter_rollback
                vip.rule_applied = vip_old.rule_rollback

                # Set Rollback With Applied
                vip.filter_rollback = vip_old.filter_applied
                vip.rule_rollback = vip_old.rule_applied

                vip.save(user, commit=True)

                # roda script
                command = 'gerador_vips -i %d --l7_filter_current' % vip.id
                code, stdout, stderr = exec_script(command)

                # code 0 = executou com sucesso
                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:
                    # pega os dados anteriores e os salva no banco
                    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)
Esempio n. 35
0
    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
Esempio n. 36
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Vip Requests by id.

        URLs: /requestvip/getbyid/id_vip
        """

        self.log.info('Find Vip Request by id')

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations
            # Valid id access
            id_vip = kwargs.get('id_vip')

            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'Parameter id_vip is invalid. Value: %s.', id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()

            """"""
            vip_port_list, reals_list, reals_priority, reals_weight = vip.get_vips_and_reals(
                vip.id)

            if reals_list:
                vip_map['reals'] = {'real': reals_list}
                vip_map['reals_prioritys'] = {'reals_priority': reals_priority}
                vip_map['reals_weights'] = {'reals_weight': reals_weight}

            if vip_port_list:
                vip_map['portas_servicos'] = {'porta': vip_port_list}

            """"""

            vip_map['id'] = id_vip
            vip_map['validado'] = vip.validado
            vip_map['vip_criado'] = vip.vip_criado
            vip_map['rule_id'] = vip.rule_id
            vip_map[
                'trafficreturn'] = vip.trafficreturn.nome_opcao_txt if vip.trafficreturn else ''
            try:
                dsrl3_to_vip_obj = DsrL3_to_Vip.get_by_vip_id(vip.id)
                vip_map['dsrl3'] = dsrl3_to_vip_obj.id_dsrl3
            except ObjectDoesNotExist, e:
                pass

            # Maxcon, lbmethod e hc
            vip_map['maxcon'] = 0
            vip_map['metodo_bal'] = ''
            vip_map['healthcheck'] = ''
            vip_map['healthcheck_type'] = ''

            pools = []
            pool_to_use = None

            id_pools = vip.vipporttopool_set.values_list(
                'server_pool_id', flat=True)
            if len(id_pools) > 0:
                pools = ServerPool.objects.filter(
                    id__in=id_pools).order_by('id')
                pool_to_use = pools[0]
                for pool in pools:
                    if pool.healthcheck:
                        hc = pool.healthcheck.healthcheck_type
                        if hc == 'HTTP':
                            pool_to_use = pool
                            break

            if pool_to_use:
                vip_map['maxcon'] = pool_to_use.default_limit
                vip_map['metodo_bal'] = pool_to_use.lb_method
                vip_map[
                    'servicedownaction'] = pool_to_use.servicedownaction.name if pool_to_use.servicedownaction else ''
                vip_map[
                    'healthcheck_type'] = pool.healthcheck.healthcheck_type if pool.healthcheck else ''
                if vip_map['healthcheck_type'] in ('HTTP', 'HTTPS'):
                    vip_map[
                        'healthcheck'] = pool.healthcheck.healthcheck_request if pool.healthcheck else ''

            if vip.healthcheck_expect is not None:
                vip_map['id_healthcheck_expect'] = vip.healthcheck_expect.id
                vip_map['expect_string'] = vip.healthcheck_expect.expect_string
                vip_map['match_list'] = vip.healthcheck_expect.match_list
            else:
                vip_map['expect_string'] = ''
                vip_map['match_list'] = ''

            list_equips = []
            list_ips = list()
            list_environment = []
            descricao_ipv4 = None
            descricao_ipv6 = None

            if vip.ip is not None:
                descricao_ipv4 = vip.ip.descricao
                list_ips.append(
                    '%s.%s.%s.%s' % (vip.ip.oct1, vip.ip.oct2, vip.ip.oct3, vip.ip.oct4))
                list_environment.append('%s - %s - %s' % (vip.ip.networkipv4.vlan.ambiente.divisao_dc.nome,
                                                          vip.ip.networkipv4.vlan.ambiente.ambiente_logico.nome, vip.ip.networkipv4.vlan.ambiente.grupo_l3.nome))
                equips = vip.ip.ipequipamento_set.all()

                for equip in equips:

                    if equip.equipamento.nome not in list_equips:

                        list_equips.append(equip.equipamento.nome)

            if vip.ipv6 is not None:
                descricao_ipv6 = vip.ipv6.description
                list_ips.append('%s:%s:%s:%s:%s:%s:%s:%s' % (vip.ipv6.block1, vip.ipv6.block2, vip.ipv6.block3,
                                                             vip.ipv6.block4, vip.ipv6.block5, vip.ipv6.block6, vip.ipv6.block7, vip.ipv6.block8))
                list_environment.append('%s - %s - %s' % (vip.ipv6.networkipv6.vlan.ambiente.divisao_dc.nome,
                                                          vip.ipv6.networkipv6.vlan.ambiente.ambiente_logico.nome, vip.ipv6.networkipv6.vlan.ambiente.grupo_l3.nome))
                equips = vip.ipv6.ipv6equipament_set.all()

                for equip in equips:

                    if equip.equipamento.nome not in list_equips:

                        list_equips.append(equip.equipamento.nome)

            vip_map['ipv4_description'] = descricao_ipv4
            vip_map['ipv6_description'] = descricao_ipv6
            vip_map['environments'] = list_environment
            vip_map['ips'] = list_ips
            vip_map['equipamento'] = list_equips
            # Business Rules

            # Start with alls
            returned_map = dict()
            returned_map['vip'] = [vip_map]

            return self.response(dumps_networkapi(returned_map))
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        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.')
                return self.not_authorized()

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(
                    u'Parameter id_vip is invalid. Value: %s.', id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            if not is_valid_int_greater_zero_param(id_block):
                self.log.error(
                    u'Parameter id_block is invalid. Value: %s.', id_block)
                raise InvalidValueError(None, 'id_block', id_block)

            if not is_valid_boolean_param(override, False):
                self.log.error(
                    u'Parameter override is invalid. Value: %s.', override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.')
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.')
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all rules by Environment Vip.

        URL: environment-vip/get/rules/<id_evip>
        """

        try:

            self.log.info('GET to list all the Rules by Environment Vip.')

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            id_environment_vip = kwargs.get('id_evip')
            id_vip = kwargs.get('id_vip')

            # Valid Environment VIP ID
            if not is_valid_int_greater_zero_param(id_environment_vip):
                self.log.error(
                    u'The id_environment_vip parameter is not a valid value: %s.', id_environment_vip)
                raise InvalidValueError(
                    None, 'id_environment_vip', id_environment_vip)

            # Find Environment VIP by ID to check if it exist
            environment_vip = EnvironmentVip.get_by_pk(id_environment_vip)

            envs = list()

            for net4 in environment_vip.networkipv4_set.all():
                if net4.vlan.ambiente.id not in envs:
                    envs.append(net4.vlan.ambiente.id)

            for net6 in environment_vip.networkipv6_set.all():
                if net6.vlan.ambiente.id not in envs:
                    envs.append(net6.vlan.ambiente.id)

            if id_vip:
                if not is_valid_int_greater_zero_param(id_vip):
                    self.log.error(
                        u'Parameter id_vip is invalid. Value: %s.', id_vip)
                    raise InvalidValueError(None, 'id_vip', id_vip)

                vip = RequisicaoVips.get_by_pk(id_vip)
                rules = Rule.objects.filter(environment__id__in=envs).filter(
                    Q(vip=vip) | Q(vip=None))
            else:
                rules = Rule.objects.filter(environment__id__in=envs, vip=None)

            rules_dict = dict()
            rules_list = []

            rules_list.append({'id': u'', 'name_rule_opt': u''})

            for rule in rules:
                rules_dict['name_rule_opt'] = rule.name
                rules_dict['id'] = rule.id
                rules_list.append(rules_dict)
                rules_dict = dict()

            return self.response(dumps_networkapi({'name_rule_opt': rules_list}))

        except UserNotAuthorizedError:
            return self.not_authorized()

        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 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)
Esempio n. 40
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_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        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.')
                return self.not_authorized()

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

            if not is_valid_int_greater_zero_param(id_vip):
                self.log.error(u'Parameter id_vip is invalid. Value: %s.',
                               id_vip)
                raise InvalidValueError(None, 'id_vip', id_vip)

            if not is_valid_int_greater_zero_param(id_block):
                self.log.error(u'Parameter id_block is invalid. Value: %s.',
                               id_block)
                raise InvalidValueError(None, 'id_block', id_block)

            if not is_valid_boolean_param(override, False):
                self.log.error(u'Parameter override is invalid. Value: %s.',
                               override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.'
                )
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.'
                )
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)
    def handle_get(self, request, user, *args, **kwargs):
        """Rollback of the filter

        URLs: /vip/l7/<id_vip>/rollback/
        """

        self.log.info("Applies the last working filter to VIP")

        try:
            id_vip = kwargs.get('id_vip')

            # User is authorized
            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(id_vip):
                self.log.error(
                    u'The vip_id parameter is not a valid value: %s.', id_vip)
                raise InvalidValueError(None)

            # Get VIP data
            vip = RequisicaoVips.get_by_pk(id_vip)

            with distributedlock(LOCK_VIP % id_vip):
                # backup do vip
                vip_old = clone(vip)

                # Vip must be created
                if not vip.vip_criado:
                    self.log.error(
                        u'Filter can not be applied because VIP has not been created yet.')
                    raise RequestVipsNotBeenCreatedError(None)

                # salva data do rollback, rollback para aplicado, passa o
                # aplicado para l7
                vip.applied_l7_datetime = datetime.now().strftime(
                    "%Y-%m-%d %H:%M:%S")

                # Set Applied With Rollback
                vip.filter_applied = vip_old.filter_rollback
                vip.rule_applied = vip_old.rule_rollback

                # Set Rollback With Applied
                vip.filter_rollback = vip_old.filter_applied
                vip.rule_rollback = vip_old.rule_applied

                vip.save(user, commit=True)

                # roda script
                command = 'gerador_vips -i %d --l7_filter_current' % vip.id
                code, stdout, stderr = exec_script(command)

                # code 0 = executou com sucesso
                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:
                    # pega os dados anteriores e os salva no banco
                    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_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)
Esempio n. 44
0
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 handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to valid Real server.

        URL: vip/real/valid/
        """
        self.log.info('Valid Real Server')

        try:

            # 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.')

            real_map = networkapi_map.get('real')
            if real_map is None:
                return self.response_error(3, u'There is no value to the vip tag  of XML request.')

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Valid IP
            if not is_valid_ip_ipaddr(ip):
                self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                raise InvalidValueError(None, 'ip', ip)

            # Valid Name Equipment
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 80) or not is_valid_regex(name, '^[A-Z0-9-_]+$'):
                self.log.error(
                    u'Parameter name_equipment is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name_equipment', name)

            # Valid Environment Vip
            if not is_valid_int_greater_zero_param(id_evip):
                self.log.error(
                    u'Parameter id_environment_vip is invalid. Value: %s.', id_evip)
                raise InvalidValueError(None, 'id_environment_vip', id_evip)

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ''
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict['version'] = version

            real_dict['ip'] = ip_dict
            real_dict['equipment'] = model_to_dict(equip)
            real_dict['environmentvip'] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
        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')

            RequisicaoVips.valid_real_server(
                ip_aux_error, equip, environment_vip)

    vip.create(user, vip_map)
    return 0, vip


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.')
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 insert_vip_request(vip_map, user):
    """Insere uma requisição de VIP.

    @param vip_map: Mapa com os dados da requisição.
    @param user: Usuário autenticado.

    @return: Em caso de sucesso: tupla (0, <requisição de VIP>).
             Em caso de erro: tupla (código da mensagem de erro, argumento01, argumento02, ...)

    @raise IpNotFoundError: IP não cadastrado.

    @raise IpError: Falha ao pesquisar o IP.

    @raise HealthcheckExpectNotFoundError: HealthcheckExpect não cadastrado.

    @raise HealthcheckExpectError: Falha ao pesquisar o HealthcheckExpect.

    @raise InvalidFinalidadeValueError: Finalidade com valor inválido.

    @raise InvalidClienteValueError: Cliente com valor inválido.

    @raise InvalidAmbienteValueError: Ambiente com valor inválido.

    @raise InvalidCacheValueError: Cache com valor inválido.

    @raise InvalidMetodoBalValueError: Valor do método de balanceamento inválido.

    @raise InvalidPersistenciaValueError: Persistencia com valor inválido.

    @raise InvalidHealthcheckTypeValueError: Healthcheck_Type com valor inválido ou inconsistente em relação ao valor do healthcheck_expect.

    @raise InvalidTimeoutValueError: Timeout com valor inválido.

    @raise InvalidHostNameError: Host não cadastrado.

    @raise EquipamentoError: Falha ao pesquisar o equipamento.

    @raise InvalidMaxConValueError: Número máximo de conexões com valor inválido.

    @raise InvalidBalAtivoValueError: Bal_Ativo com valor inválido.

    @raise InvalidTransbordoValueError: Transbordo com valor inválido.

    @raise InvalidServicePortValueError: Porta do Serviço com valor inválido.

    @raise InvalidRealValueError: Valor inválido de um real.

    @raise InvalidHealthcheckValueError: Valor do healthcheck inconsistente em relação ao valor do healthcheck_type.

    @raise RequisicaoVipsError: Falha ao inserir a requisição de VIP.

    @raise UserNotAuthorizedError:
    """

    log = logging.getLogger('insert_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.')

    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)

    vip = RequisicaoVips()
    vip.ip = Ip()
    vip.ip.id = ip_id

    # Valid ports
    vip_map, code = vip.valid_values_ports(vip_map)
    if code is not None:
        return code, vip

    # get environmentVip for validation dynamic heathcheck

    finalidade = vip_map.get('finalidade')
    cliente = vip_map.get('cliente')
    ambiente = vip_map.get('ambiente')

    if not is_valid_string_minsize(
            finalidade, 3) or not is_valid_string_maxsize(finalidade, 50):
        log.error(u'Finality value is invalid: %s.', finalidade)
        raise InvalidValueError(None, 'finalidade', finalidade)

    if not is_valid_string_minsize(cliente, 3) or not is_valid_string_maxsize(
            cliente, 50):
        log.error(u'Client value is invalid: %s.', cliente)
        raise InvalidValueError(None, 'cliente', cliente)

    if not is_valid_string_minsize(ambiente, 3) or not is_valid_string_maxsize(
            ambiente, 50):
        log.error(u'Environment value is invalid: %s.', ambiente)
        raise InvalidValueError(None, 'ambiente', ambiente)

    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')
def insert_vip_request(vip_map, user):
    '''Insere uma requisição de VIP.

    @param vip_map: Mapa com os dados da requisição.
    @param user: Usuário autenticado.

    @return: Em caso de sucesso: tupla (0, <requisição de VIP>).
             Em caso de erro: tupla (código da mensagem de erro, argumento01, argumento02, ...)

    @raise IpNotFoundError: IP não cadastrado.

    @raise IpError: Falha ao pesquisar o IP.

    @raise HealthcheckExpectNotFoundError: HealthcheckExpect não cadastrado.

    @raise HealthcheckExpectError: Falha ao pesquisar o HealthcheckExpect.

    @raise InvalidFinalidadeValueError: Finalidade com valor inválido.

    @raise InvalidClienteValueError: Cliente com valor inválido.

    @raise InvalidAmbienteValueError: Ambiente com valor inválido.

    @raise InvalidCacheValueError: Cache com valor inválido.

    @raise InvalidMetodoBalValueError: Valor do método de balanceamento inválido.

    @raise InvalidPersistenciaValueError: Persistencia com valor inválido.

    @raise InvalidHealthcheckTypeValueError: Healthcheck_Type com valor inválido ou inconsistente em relação ao valor do healthcheck_expect.

    @raise InvalidTimeoutValueError: Timeout com valor inválido.

    @raise InvalidHostNameError: Host não cadastrado.

    @raise EquipamentoError: Falha ao pesquisar o equipamento.

    @raise InvalidMaxConValueError: Número máximo de conexões com valor inválido.

    @raise InvalidBalAtivoValueError: Bal_Ativo com valor inválido.

    @raise InvalidTransbordoValueError: Transbordo com valor inválido.

    @raise InvalidServicePortValueError: Porta do Serviço com valor inválido.

    @raise InvalidRealValueError: Valor inválido de um real.

    @raise InvalidHealthcheckValueError: Valor do healthcheck inconsistente em relação ao valor do healthcheck_type.

    @raise RequisicaoVipsError: Falha ao inserir a requisição de VIP.

    @raise UserNotAuthorizedError:
    '''

    log = Log('insert_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.')

    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)

    vip = RequisicaoVips()
    vip.ip = Ip()
    vip.ip.id = ip_id

    # Valid ports
    vip_map, code = vip.valid_values_ports(vip_map)
    if code is not None:
        return code, vip

    # get environmentVip dor validation dynamic heathcheck

    finalidade = vip_map.get('finalidade')
    cliente = vip_map.get('cliente')
    ambiente = vip_map.get('ambiente')

    if not is_valid_string_minsize(finalidade, 3) or not is_valid_string_maxsize(finalidade, 50):
        log.error(u'Finality value is invalid: %s.', finalidade)
        raise InvalidValueError(None, 'finalidade', finalidade)

    if not is_valid_string_minsize(cliente, 3) or not is_valid_string_maxsize(cliente, 50):
        log.error(u'Client value is invalid: %s.', cliente)
        raise InvalidValueError(None, 'cliente', cliente)

    if not is_valid_string_minsize(ambiente, 3) or not is_valid_string_maxsize(ambiente, 50):
        log.error(u'Environment value is invalid: %s.', ambiente)
        raise InvalidValueError(None, 'ambiente', ambiente)

    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')
    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 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 __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 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_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to valid Real server.

        URL: vip/real/valid/
        '''
        self.log.info('Valid Real Server')

        try:

            # 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.'
                )

            real_map = networkapi_map.get('real')
            if real_map is None:
                return self.response_error(
                    3, u'There is no value to the vip tag  of XML request.')

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Valid IP
            if not is_valid_ip_ipaddr(ip):
                self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                raise InvalidValueError(None, 'ip', ip)

            # Valid Name Equipment
            if not is_valid_string_minsize(
                    name, 3) or not is_valid_string_maxsize(
                        name, 80) or not is_valid_regex(name, "^[A-Z0-9-_]+$"):
                self.log.error(
                    u'Parameter name_equipment is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name_equipment', name)

            # Valid Environment Vip
            if not is_valid_int_greater_zero_param(id_evip):
                self.log.error(
                    u'Parameter id_environment_vip is invalid. Value: %s.',
                    id_evip)
                raise InvalidValueError(None, 'id_environment_vip', id_evip)

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ""
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict["version"] = version

            real_dict["ip"] = ip_dict
            real_dict["equipment"] = model_to_dict(equip)
            real_dict["environmentvip"] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_put(self, request, user, *args, **kwargs):
        """
        Handles PUT requests to change the VIP's healthcheck.

        URL: vip/<id_vip>/healthcheck
        """

        self.log.info("Change VIP's healthcheck")

        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"Healthcheck 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 XML data
                healthcheck_type = upper(str(vip_map["healthcheck_type"]))
                healthcheck = vip_map["healthcheck"]
                id_healthcheck_expect = vip_map["id_healthcheck_expect"]

                vars = vip.variables_to_map()
                environment_vip = EnvironmentVip.get_by_values(
                    vars.get("finalidade"), vars.get("cliente"), vars.get("ambiente")
                )

                healthcheck_is_valid = RequisicaoVips.heathcheck_exist(healthcheck_type, environment_vip.id)

                # healthcheck_type exist'
                if not healthcheck_is_valid:
                    self.log.error(u"The healthcheck_type parameter not exist.")
                    raise InvalidValueError(
                        u"The healthcheck_type parameter not exist.", "healthcheck_type", healthcheck_type
                    )

                # If healthcheck_type is not HTTP id_healthcheck_expect and
                # healthcheck must be None
                if healthcheck_type != "HTTP":
                    if not (id_healthcheck_expect == None and healthcheck == None):
                        msg = (
                            u"The healthcheck_type parameter is %s, then healthcheck and id_healthcheck_expect must be None."
                            % healthcheck_type
                        )
                        self.log.error(msg)
                        raise InvalidValueError(msg)
                #                         return self.response_error(276)
                # If healthcheck_type is 'HTTP' id_healthcheck_expect and
                # healthcheck must NOT be None
                elif healthcheck_type == "HTTP":
                    if id_healthcheck_expect == None or healthcheck == None:
                        msg = u"The healthcheck_type parameter is HTTP, then healthcheck and id_healthcheck_expect must NOT be None."
                        self.log.error(msg)
                        raise InvalidValueError(msg)
                    else:
                        try:

                            # Valid healthcheck_expect ID
                            if not is_valid_int_greater_zero_param(id_healthcheck_expect):
                                self.log.error(
                                    u"The id_healthcheck_expect parameter is not a valid value: %s.",
                                    id_healthcheck_expect,
                                )
                                raise InvalidValueError(None, "id_healthcheck_expect", id_healthcheck_expect)

                            # Find healthcheck_expect by ID to check if it
                            # exist
                            healthcheck_expect = HealthcheckExpect.get_by_pk(id_healthcheck_expect)

                            # Check if healthcheck is a string
                            if not isinstance(healthcheck, basestring):
                                msg = u"The healthcheck must be a string."
                                self.log.error(msg)
                                raise InvalidValueError(msg, "healthcheck", healthcheck)

                        except HealthcheckExpectNotFoundError:
                            msg = u"The id_healthcheck_expect parameter does not exist."
                            self.log.error(msg)
                            raise InvalidValueError(msg, "id_healthcheck_expect", id_healthcheck_expect)

                # Business Rules

                # Get variables
                variables_map = vip.variables_to_map()

                # Valid variables
                vip.set_variables(variables_map)

                # Set healthcheck_type
                variables_map["healthcheck_type"] = healthcheck_type

                # If healthcheck_type is HTTP
                if healthcheck_type == "HTTP":
                    # Set healthcheck
                    variables_map["healthcheck"] = healthcheck

                    # Set id_healthcheck_expect
                    vip.healthcheck_expect = healthcheck_expect
                else:
                    # Set healthcheck to None
                    variables_map["healthcheck"] = None

                    # Set id_healthcheck_expect to None
                    vip.healthcheck_expect = None

                # Set variables
                vip.set_variables(variables_map)

                # Save VIP
                vip.save(user, commit=True)

                # Executar script

                # Put old call to work with new pool features
                # This call is deprecated
                server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip)
                if healthcheck == None:
                    healthcheck = ""
                if id_healthcheck_expect == None:
                    healthcheck_expect = ""
                else:
                    healthcheck_expect = healthcheck_expect.expect_string
                healthcheck_identifier = ""
                healthcheck_destination = "*:*"
                hc = get_or_create_healthcheck(
                    user,
                    healthcheck_expect,
                    healthcheck_type,
                    healthcheck,
                    healthcheck_destination,
                    healthcheck_identifier,
                )
                # Applies new healthcheck in pool
                # Todo - new method
                old_healthchecks = []
                for sp in server_pools:
                    old_healthchecks.append(sp.healthcheck)
                    sp.healthcheck = hc
                    sp.save(user, commit=True)

                # gerador_vips -i <ID_REQUISICAO> --healthcheck
                command = "gerador_vips -i %d --healthcheck" % 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:
                    old_healthchecks.reverse()
                    for sp in server_pools:
                        sp.healthcheck = old_healthchecks.pop()
                        sp.save(user, commit=True)
                    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)
Esempio n. 57
0
    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_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)