Search in sources :

Example 26 with InternalCache

use of org.apache.geode.internal.cache.InternalCache in project geode by apache.

the class GetPDXTypeById method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, ClassNotFoundException {
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received get pdx type by id request ({} parts) from {}", serverConnection.getName(), clientMessage.getNumberOfParts(), serverConnection.getSocketString());
    }
    int pdxId = clientMessage.getPart(0).getInt();
    PdxType type;
    try {
        InternalCache cache = serverConnection.getCache();
        TypeRegistry registry = cache.getPdxRegistry();
        type = registry.getType(pdxId);
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    Message responseMsg = serverConnection.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setNumberOfParts(1);
    responseMsg.setTransactionId(clientMessage.getTransactionId());
    responseMsg.addObjPart(type);
    responseMsg.send(serverConnection);
    serverConnection.setAsTrue(RESPONDED);
}
Also used : PdxType(org.apache.geode.pdx.internal.PdxType) Message(org.apache.geode.internal.cache.tier.sockets.Message) InternalCache(org.apache.geode.internal.cache.InternalCache) TypeRegistry(org.apache.geode.pdx.internal.TypeRegistry) IOException(java.io.IOException)

Example 27 with InternalCache

use of org.apache.geode.internal.cache.InternalCache in project geode by apache.

the class GetPdxEnums70 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, ClassNotFoundException {
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received get pdx enums from {}", serverConnection.getName(), serverConnection.getSocketString());
    }
    Map<Integer, EnumInfo> enums;
    try {
        InternalCache cache = serverConnection.getCache();
        enums = cache.getPdxRegistry().enumMap();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    Message responseMsg = serverConnection.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setNumberOfParts(1);
    responseMsg.setTransactionId(clientMessage.getTransactionId());
    responseMsg.addObjPart(enums);
    responseMsg.send(serverConnection);
    serverConnection.setAsTrue(RESPONDED);
}
Also used : Message(org.apache.geode.internal.cache.tier.sockets.Message) EnumInfo(org.apache.geode.pdx.internal.EnumInfo) InternalCache(org.apache.geode.internal.cache.InternalCache) IOException(java.io.IOException)

Example 28 with InternalCache

use of org.apache.geode.internal.cache.InternalCache in project geode by apache.

the class ClientCommands method describeClient.

@CliCommand(value = CliStrings.DESCRIBE_CLIENT, help = CliStrings.DESCRIBE_CLIENT__HELP)
@CliMetaData(relatedTopic = { CliStrings.TOPIC_CLIENT })
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result describeClient(@CliOption(key = CliStrings.DESCRIBE_CLIENT__ID, mandatory = true, help = CliStrings.DESCRIBE_CLIENT__ID__HELP) String clientId) {
    Result result = null;
    if (clientId.startsWith("\"")) {
        clientId = clientId.substring(1);
    }
    if (clientId.endsWith("\"")) {
        clientId = clientId.substring(0, clientId.length() - 2);
    }
    if (clientId.endsWith("\";")) {
        clientId = clientId.substring(0, clientId.length() - 2);
    }
    try {
        CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
        SectionResultData sectionResult = compositeResultData.addSection("InfoSection");
        InternalCache cache = getCache();
        ManagementService service = ManagementService.getExistingManagementService(cache);
        ObjectName[] cacheServers = service.getDistributedSystemMXBean().listCacheServerObjectNames();
        if (cacheServers.length == 0) {
            return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT_COULD_NOT_RETRIEVE_SERVER_LIST));
        }
        ClientHealthStatus clientHealthStatus = null;
        for (ObjectName objName : cacheServers) {
            CacheServerMXBean serverMbean = service.getMBeanInstance(objName, CacheServerMXBean.class);
            List<String> listOfClient = new ArrayList<String>(Arrays.asList((String[]) serverMbean.getClientIds()));
            if (listOfClient.contains(clientId)) {
                if (clientHealthStatus == null) {
                    try {
                        clientHealthStatus = serverMbean.showClientStats(clientId);
                        if (clientHealthStatus == null) {
                            return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT_COULD_NOT_RETRIEVE_STATS_FOR_CLIENT_0, clientId));
                        }
                    } catch (Exception eee) {
                        return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT_COULD_NOT_RETRIEVE_STATS_FOR_CLIENT_0_REASON_1, clientId, eee.getMessage()));
                    }
                }
            }
        }
        if (clientHealthStatus == null) {
            return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT__CLIENT__ID__NOT__FOUND__0, clientId));
        }
        Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
        String isDurable = null;
        List<String> primaryServers = new ArrayList<String>();
        List<String> secondaryServers = new ArrayList<String>();
        if (dsMembers.size() > 0) {
            ContunuousQueryFunction contunuousQueryFunction = new ContunuousQueryFunction();
            FunctionService.registerFunction(contunuousQueryFunction);
            List<?> resultList = (List<?>) CliUtil.executeFunction(contunuousQueryFunction, clientId, dsMembers).getResult();
            for (int i = 0; i < resultList.size(); i++) {
                try {
                    Object object = resultList.get(i);
                    if (object instanceof Throwable) {
                        LogWrapper.getInstance().warning("Exception in Describe Client " + ((Throwable) object).getMessage(), ((Throwable) object));
                        continue;
                    }
                    if (object != null) {
                        ClientInfo objectResult = (ClientInfo) object;
                        isDurable = objectResult.isDurable;
                        if (objectResult.primaryServer != null && objectResult.primaryServer.length() > 0) {
                            if (primaryServers.size() == 0) {
                                primaryServers.add(objectResult.primaryServer);
                            } else {
                                primaryServers.add(" ,");
                                primaryServers.add(objectResult.primaryServer);
                            }
                        }
                        if (objectResult.secondaryServer != null && objectResult.secondaryServer.length() > 0) {
                            if (secondaryServers.size() == 0) {
                                secondaryServers.add(objectResult.secondaryServer);
                            } else {
                                secondaryServers.add(" ,");
                                secondaryServers.add(objectResult.secondaryServer);
                            }
                        }
                    }
                } catch (Exception e) {
                    LogWrapper.getInstance().info(CliStrings.DESCRIBE_CLIENT_ERROR_FETCHING_STATS_0 + " :: " + CliUtil.stackTraceAsString(e));
                    return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT_ERROR_FETCHING_STATS_0, e.getMessage()));
                }
            }
            buildTableResult(sectionResult, clientHealthStatus, isDurable, primaryServers, secondaryServers);
            result = ResultBuilder.buildResult(compositeResultData);
        } else {
            return ResultBuilder.createGemFireErrorResult(CliStrings.DESCRIBE_CLIENT_NO_MEMBERS);
        }
    } catch (Exception e) {
        LogWrapper.getInstance().info("Error in decribe clients. stack trace" + CliUtil.stackTraceAsString(e));
        result = ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESCRIBE_CLIENT_COULD_NOT_RETRIEVE_CLIENT_0, e.getMessage()));
    }
    LogWrapper.getInstance().info("decribe client result " + result);
    return result;
}
Also used : CompositeResultData(org.apache.geode.management.internal.cli.result.CompositeResultData) ArrayList(java.util.ArrayList) ContunuousQueryFunction(org.apache.geode.management.internal.cli.functions.ContunuousQueryFunction) InternalCache(org.apache.geode.internal.cache.InternalCache) CacheServerMXBean(org.apache.geode.management.CacheServerMXBean) Result(org.apache.geode.management.cli.Result) ObjectName(javax.management.ObjectName) ManagementService(org.apache.geode.management.ManagementService) ClientHealthStatus(org.apache.geode.management.ClientHealthStatus) DistributedMember(org.apache.geode.distributed.DistributedMember) SectionResultData(org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData) ArrayList(java.util.ArrayList) List(java.util.List) ClientInfo(org.apache.geode.management.internal.cli.functions.ContunuousQueryFunction.ClientInfo) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 29 with InternalCache

use of org.apache.geode.internal.cache.InternalCache in project geode by apache.

the class CreateAlterDestroyRegionCommands method destroyRegion.

@CliCommand(value = { CliStrings.DESTROY_REGION }, help = CliStrings.DESTROY_REGION__HELP)
@CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
@ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
public Result destroyRegion(@CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH, mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) {
    if (regionPath == null) {
        return ResultBuilder.createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY);
    }
    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
        return ResultBuilder.createInfoResult(CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] { regionPath }));
    }
    Result result;
    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
    try {
        InternalCache cache = getCache();
        ManagementService managementService = ManagementService.getExistingManagementService(cache);
        String regionPathToUse = regionPath;
        if (!regionPathToUse.startsWith(Region.SEPARATOR)) {
            regionPathToUse = Region.SEPARATOR + regionPathToUse;
        }
        Set<DistributedMember> regionMembersList = findMembersForRegion(cache, managementService, regionPathToUse);
        if (regionMembersList.size() == 0) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULDNOT_FIND_REGIONPATH_0_IN_GEODE, new Object[] { regionPath, "jmx-manager-update-rate milliseconds" }));
        }
        CliFunctionResult destroyRegionResult;
        ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
        List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult();
        String message = CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, new Object[] { regionPath, "" });
        // Only if there is an error is this set to false
        boolean isRegionDestroyed = true;
        for (CliFunctionResult aResultsList : resultsList) {
            destroyRegionResult = aResultsList;
            if (destroyRegionResult.isSuccessful()) {
                xmlEntity.set(destroyRegionResult.getXmlEntity());
            } else if (destroyRegionResult.getThrowable() != null) {
                Throwable t = destroyRegionResult.getThrowable();
                LogWrapper.getInstance().info(t.getMessage(), t);
                message = CliStrings.format(CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1, new Object[] { regionPath, t.getMessage() });
                isRegionDestroyed = false;
            } else {
                message = CliStrings.format(CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] { regionPath, destroyRegionResult.getMessage() });
                isRegionDestroyed = false;
            }
        }
        if (isRegionDestroyed) {
            result = ResultBuilder.createInfoResult(message);
        } else {
            result = ResultBuilder.createUserErrorResult(message);
        }
    } catch (IllegalStateException e) {
        result = ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] { regionPath, e.getMessage() }));
    } catch (Exception e) {
        result = ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, new Object[] { regionPath, e.getMessage() }));
    }
    if (xmlEntity.get() != null) {
        persistClusterConfiguration(result, () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
    }
    return result;
}
Also used : InternalCache(org.apache.geode.internal.cache.InternalCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) CommandResultException(org.apache.geode.management.internal.cli.result.CommandResultException) MalformedObjectNameException(javax.management.MalformedObjectNameException) Result(org.apache.geode.management.cli.Result) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) FetchRegionAttributesFunctionResult(org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult) XmlEntity(org.apache.geode.management.internal.configuration.domain.XmlEntity) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) ManagementService(org.apache.geode.management.ManagementService) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) DistributedMember(org.apache.geode.distributed.DistributedMember) List(java.util.List) ArrayList(java.util.ArrayList) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 30 with InternalCache

use of org.apache.geode.internal.cache.InternalCache in project geode by apache.

the class QueryDataFunction method queryData.

public static Object queryData(final String query, final String members, final int limit, final boolean zipResult, final int queryResultSetLimit, final int queryCollectionsDepth) throws Exception {
    if (query == null || query.isEmpty()) {
        return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__QUERY_EMPTY.toLocalizedString()).toString();
    }
    Set<DistributedMember> inputMembers = null;
    if (StringUtils.isNotBlank(members)) {
        inputMembers = new HashSet<>();
        StringTokenizer st = new StringTokenizer(members, ",");
        while (st.hasMoreTokens()) {
            String member = st.nextToken();
            DistributedMember distributedMember = BeanUtilFuncs.getDistributedMemberByNameOrId(member);
            inputMembers.add(distributedMember);
            if (distributedMember == null) {
                return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__INVALID_MEMBER.toLocalizedString(member)).toString();
            }
        }
    }
    InternalCache cache = (InternalCache) CacheFactory.getAnyInstance();
    try {
        SystemManagementService service = (SystemManagementService) ManagementService.getExistingManagementService(cache);
        Set<String> regionsInQuery = compileQuery(cache, query);
        // Validate region existence
        if (regionsInQuery.size() > 0) {
            for (String regionPath : regionsInQuery) {
                DistributedRegionMXBean regionMBean = service.getDistributedRegionMXBean(regionPath);
                if (regionMBean == null) {
                    return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND.toLocalizedString(regionPath)).toString();
                } else {
                    Set<DistributedMember> associatedMembers = DataCommands.getRegionAssociatedMembers(regionPath, cache, true);
                    if (inputMembers != null && inputMembers.size() > 0) {
                        if (!associatedMembers.containsAll(inputMembers)) {
                            return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBERS.toLocalizedString(regionPath)).toString();
                        }
                    }
                }
            }
        } else {
            return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__INVALID_QUERY.toLocalizedString("Region mentioned in query probably missing /")).toString();
        }
        // Validate
        if (regionsInQuery.size() > 1 && inputMembers == null) {
            for (String regionPath : regionsInQuery) {
                DistributedRegionMXBean regionMBean = service.getDistributedRegionMXBean(regionPath);
                if (regionMBean.getRegionType().equals(DataPolicy.PARTITION.toString()) || regionMBean.getRegionType().equals(DataPolicy.PERSISTENT_PARTITION.toString())) {
                    return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__JOIN_OP_EX.toLocalizedString()).toString();
                }
            }
        }
        String randomRegion = regionsInQuery.iterator().next();
        Set<DistributedMember> associatedMembers = // First
        DataCommands.getQueryRegionsAssociatedMembers(regionsInQuery, cache, false);
        if (associatedMembers != null && associatedMembers.size() > 0) {
            Object[] functionArgs = new Object[6];
            if (inputMembers != null && inputMembers.size() > 0) {
                // on input
                // members
                functionArgs[DISPLAY_MEMBERWISE] = true;
                functionArgs[QUERY] = query;
                functionArgs[REGION] = randomRegion;
                functionArgs[LIMIT] = limit;
                functionArgs[QUERY_RESULTSET_LIMIT] = queryResultSetLimit;
                functionArgs[QUERY_COLLECTIONS_DEPTH] = queryCollectionsDepth;
                return callFunction(functionArgs, inputMembers, zipResult);
            } else {
                // Query on any random member
                functionArgs[DISPLAY_MEMBERWISE] = false;
                functionArgs[QUERY] = query;
                functionArgs[REGION] = randomRegion;
                functionArgs[LIMIT] = limit;
                functionArgs[QUERY_RESULTSET_LIMIT] = queryResultSetLimit;
                functionArgs[QUERY_COLLECTIONS_DEPTH] = queryCollectionsDepth;
                return callFunction(functionArgs, associatedMembers, zipResult);
            }
        } else {
            return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND.toLocalizedString(regionsInQuery.toString())).toString();
        }
    } catch (QueryInvalidException qe) {
        return new JsonisedErrorMessage(ManagementStrings.QUERY__MSG__INVALID_QUERY.toLocalizedString(qe.getMessage())).toString();
    }
}
Also used : QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) InternalCache(org.apache.geode.internal.cache.InternalCache) DistributedRegionMXBean(org.apache.geode.management.DistributedRegionMXBean) SystemManagementService(org.apache.geode.management.internal.SystemManagementService) StringTokenizer(java.util.StringTokenizer) DistributedMember(org.apache.geode.distributed.DistributedMember) GfJsonObject(org.apache.geode.management.internal.cli.json.GfJsonObject)

Aggregations

InternalCache (org.apache.geode.internal.cache.InternalCache)267 DistributedMember (org.apache.geode.distributed.DistributedMember)78 Test (org.junit.Test)64 UnitTest (org.apache.geode.test.junit.categories.UnitTest)52 IOException (java.io.IOException)48 ArrayList (java.util.ArrayList)35 HashSet (java.util.HashSet)35 CliMetaData (org.apache.geode.management.cli.CliMetaData)34 CliCommand (org.springframework.shell.core.annotation.CliCommand)34 TabularResultData (org.apache.geode.management.internal.cli.result.TabularResultData)32 Region (org.apache.geode.cache.Region)31 Result (org.apache.geode.management.cli.Result)30 ResourceOperation (org.apache.geode.management.internal.security.ResourceOperation)30 Expectations (org.jmock.Expectations)30 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)26 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)25 CliFunctionResult (org.apache.geode.management.internal.cli.functions.CliFunctionResult)24 Set (java.util.Set)23 ResultCollector (org.apache.geode.cache.execute.ResultCollector)22 CommandResultException (org.apache.geode.management.internal.cli.result.CommandResultException)20