def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add a HeltcheckExpect only expect_string field.

        URL: healthcheckexpect/add/expectstring/
        """

        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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data

            expect_string = healthcheck_map.get('expect_string')
            if not is_valid_string_maxsize(expect_string, 50):
                self.log.error(
                    u'Parameter expect_string is invalid. Value: %s.',
                    expect_string)
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            healthcheck.insert_expect_string(user, expect_string)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(
                dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add a HeltcheckExpect only expect_string field.

        URL: healthcheckexpect/add/expectstring/
        """

        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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data

            expect_string = healthcheck_map.get('expect_string')
            if not is_valid_string_maxsize(expect_string, 50):
                self.log.error(
                    u'Parameter expect_string is invalid. Value: %s.', expect_string)
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            healthcheck.insert_expect_string(user, expect_string)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para consulta de HealthCheckExpects por id.

        Lista as informações de um HealthCheckExpect por id.

        URL:  /healthcheckexpect/get/<id_healthcheck_expect>/
        """
        try:
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_healthcheck = kwargs.get('id_healthcheck')

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

            heal = HealthcheckExpect.get_by_pk(id_healthcheck)

            healthcheckexpect_map = model_to_dict(heal)

            return self.response(
                dumps_networkapi({'healthcheck_expect':
                                  healthcheckexpect_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 GET para consulta de HealthCheckExpects por id.

        Lista as informações de um HealthCheckExpect por id.

        URL:  /healthcheckexpect/get/<id_healthcheck_expect>/
        """
        try:
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            id_healthcheck = kwargs.get('id_healthcheck')

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

            heal = HealthcheckExpect.get_by_pk(id_healthcheck)

            healthcheckexpect_map = model_to_dict(heal)

            return self.response(dumps_networkapi({'healthcheck_expect': healthcheckexpect_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 GET para buscar expect_strings do Healthchecks_expects com distinct.

        URL:  /healthcheckexpect/distinct/
        """
        try:
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            expect_strings = HealthcheckExpect.get_expect_strings()

            return self.response(dumps_networkapi({"healthcheck_expect": expect_strings}))

        except (HealthcheckExpectError, GrupoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para buscar expect_strings do Healthchecks_expects com distinct.

        URL:  /healthcheckexpect/distinct/
        """
        try:
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            expect_strings = HealthcheckExpect.get_expect_strings()

            return self.response(
                dumps_networkapi({'healthcheck_expect': expect_strings})
            )

        except (HealthcheckExpectError, GrupoError):
            return self.response_error(1)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para consulta de HealthCheckExpects.

        Lista as informações dos HealthCheckExpect's de um determinado ambiente.

        URL:  /healthcheckexpect/ambiente/<id_amb>/
        """
        try:
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            map_list = []

            environment_id = kwargs.get('id_amb')
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'The environment_id parameter is not a valid value: %s.',
                    environment_id)
                raise InvalidValueError(None, 'environment_id', environment_id)

            environment = Ambiente().get_by_pk(environment_id)

            healthcheckexpects = HealthcheckExpect().search(environment_id)

            for healthcheckexpect in healthcheckexpects:
                healthcheckexpect_map = dict()
                healthcheckexpect_map['id'] = healthcheckexpect.id
                healthcheckexpect_map[
                    'expect_string'] = healthcheckexpect.expect_string
                healthcheckexpect_map[
                    'match_list'] = healthcheckexpect.match_list
                healthcheckexpect_map[
                    'id_ambiente'] = healthcheckexpect.ambiente_id

                map_list.append(healthcheckexpect_map)

            return self.response(
                dumps_networkapi({'healthcheck_expect': map_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Ejemplo n.º 8
0
            except IpCantBeRemovedFromVip, e:
                raise AmbienteUsedByEquipmentVlanError(e.cause, e.message)

        # Remove every association between equipment and this environment
        for equip_env in environment.equipamentoambiente_set.all():
            try:
                EquipamentoAmbiente.remove(
                    authenticated_user, equip_env.equipamento_id, equip_env.ambiente_id)
            except EquipamentoAmbienteNotFoundError, e:
                raise AmbienteUsedByEquipmentVlanError(e, e.message)
            except EquipamentoError, e:
                raise AmbienteUsedByEquipmentVlanError(e, e.message)

        # Dissociate or remove healthcheck expects
        try:
            HealthcheckExpect.dissociate_environment_and_delete(
                authenticated_user, pk)
        except HealthcheckExpectError, e:
            cls.log.error(u'Falha ao desassociar algum HealthCheckExpect.')
            raise AmbienteError(
                e, u'Falha ao desassociar algum HealthCheckExpect.')

        # Remove ConfigEnvironments associated with environment
        try:
            ConfigEnvironment.remove_by_environment(authenticated_user, pk)
        except (ConfigEnvironmentError, OperationalError, ConfigEnvironmentNotFoundError), e:
            cls.log.error(u'Falha ao remover algum Ambiente Config.')
            raise AmbienteError(e, u'Falha ao remover algum Ambiente Config.')

        # Remove the environment
        try:
            environment.delete()
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add a HeltcheckExpect.

        URL: healthcheckexpect/add/
        """

        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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            match_list = healthcheck_map.get('match_list')
            expect_string = healthcheck_map.get('expect_string')
            environment_id = healthcheck_map.get('id_ambiente')

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

            if expect_string is not None:
                if not is_valid_string_maxsize(expect_string, 50) or not is_valid_string_minsize(expect_string, 2):
                    self.log.error(
                        u'Parameter expect_string is invalid. Value: %s.', expect_string)
                    raise InvalidValueError(
                        None, 'expect_string', expect_string)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            if match_list is not None:
                if not is_valid_string_maxsize(match_list, 50) or not is_valid_string_minsize(match_list, 2):
                    self.log.error(
                        u'Parameter match_list is invalid. Value: %s.', match_list)
                    raise InvalidValueError(None, 'match_list', match_list)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            ambiente = Ambiente.get_by_pk(environment_id)

            healthcheck.insert(user, match_list, expect_string, ambiente)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except AmbienteNotFoundError, e:
            return self.response_error(112)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add a HeltcheckExpect.

        URL: healthcheckexpect/add/
        """

        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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            match_list = healthcheck_map.get('match_list')
            expect_string = healthcheck_map.get('expect_string')
            environment_id = healthcheck_map.get('id_ambiente')

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

            if expect_string is not None:
                if not is_valid_string_maxsize(
                        expect_string, 50) or not is_valid_string_minsize(
                            expect_string, 2):
                    self.log.error(
                        u'Parameter expect_string is invalid. Value: %s.',
                        expect_string)
                    raise InvalidValueError(None, 'expect_string',
                                            expect_string)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            if match_list is not None:
                if not is_valid_string_maxsize(
                        match_list, 50) or not is_valid_string_minsize(
                            match_list, 2):
                    self.log.error(
                        u'Parameter match_list is invalid. Value: %s.',
                        match_list)
                    raise InvalidValueError(None, 'match_list', match_list)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            ambiente = Ambiente.get_by_pk(environment_id)

            healthcheck.insert(user, match_list, expect_string, ambiente)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(
                dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except AmbienteNotFoundError, e:
            return self.response_error(112)
    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)
Ejemplo n.º 12
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)