Search in sources :

Example 21 with ResourceOperation

use of org.apache.geode.management.internal.security.ResourceOperation in project geode by apache.

the class ExportImportClusterConfigurationCommands method importSharedConfig.

@CliCommand(value = { CliStrings.IMPORT_SHARED_CONFIG }, help = CliStrings.IMPORT_SHARED_CONFIG__HELP)
@CliMetaData(interceptor = "org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands$ImportInterceptor", relatedTopic = { CliStrings.TOPIC_GEODE_CONFIG })
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
@SuppressWarnings("unchecked")
public Result importSharedConfig(@CliOption(key = { CliStrings.IMPORT_SHARED_CONFIG__ZIP }, mandatory = true, help = CliStrings.IMPORT_SHARED_CONFIG__ZIP__HELP) String zip) {
    InternalLocator locator = InternalLocator.getLocator();
    if (!locator.isSharedConfigurationRunning()) {
        ErrorResultData errorData = ResultBuilder.createErrorResultData();
        errorData.addLine(CliStrings.SHARED_CONFIGURATION_NOT_STARTED);
        return ResultBuilder.buildResult(errorData);
    }
    InternalCache cache = getCache();
    Set<DistributedMember> servers = CliUtil.getAllNormalMembers(cache);
    Set<String> regionsWithData = servers.stream().map(this::getRegionNamesOnServer).flatMap(Collection::stream).collect(toSet());
    if (!regionsWithData.isEmpty()) {
        return ResultBuilder.createGemFireErrorResult("Cannot import cluster configuration with existing regions: " + regionsWithData.stream().collect(joining(",")));
    }
    byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
    String zipFileName = CliUtil.bytesToNames(shellBytesData)[0];
    byte[] zipBytes = CliUtil.bytesToData(shellBytesData)[0];
    Result result;
    InfoResultData infoData = ResultBuilder.createInfoResultData();
    File zipFile = new File(zipFileName);
    try {
        ClusterConfigurationService sc = locator.getSharedConfiguration();
        // backup the old config
        for (Configuration config : sc.getEntireConfiguration().values()) {
            sc.writeConfigToFile(config);
        }
        sc.renameExistingSharedConfigDirectory();
        FileUtils.writeByteArrayToFile(zipFile, zipBytes);
        ZipUtils.unzip(zipFileName, sc.getSharedConfigurationDirPath());
        // load it from the disk
        sc.loadSharedConfigurationFromDisk();
        infoData.addLine(CliStrings.IMPORT_SHARED_CONFIG__SUCCESS__MSG);
    } catch (Exception e) {
        ErrorResultData errorData = ResultBuilder.createErrorResultData();
        errorData.addLine("Import failed");
        logSevere(e);
        result = ResultBuilder.buildResult(errorData);
        // if import is unsuccessful, don't need to bounce the server.
        return result;
    } finally {
        FileUtils.deleteQuietly(zipFile);
    }
    // Bounce the cache of each member
    Set<CliFunctionResult> functionResults = servers.stream().map(this::reCreateCache).collect(toSet());
    for (CliFunctionResult functionResult : functionResults) {
        if (functionResult.isSuccessful()) {
            infoData.addLine("Successfully applied the imported cluster configuration on " + functionResult.getMemberIdOrName());
        } else {
            infoData.addLine("Failed to apply the imported cluster configuration on " + functionResult.getMemberIdOrName() + " due to " + functionResult.getMessage());
        }
    }
    result = ResultBuilder.buildResult(infoData);
    return result;
}
Also used : InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) Configuration(org.apache.geode.management.internal.configuration.domain.Configuration) InternalCache(org.apache.geode.internal.cache.InternalCache) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) InternalLocator(org.apache.geode.distributed.internal.InternalLocator) ClusterConfigurationService(org.apache.geode.distributed.internal.ClusterConfigurationService) DistributedMember(org.apache.geode.distributed.DistributedMember) ErrorResultData(org.apache.geode.management.internal.cli.result.ErrorResultData) File(java.io.File) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 22 with ResourceOperation

use of org.apache.geode.management.internal.security.ResourceOperation in project geode by apache.

the class ExportImportClusterConfigurationCommands method exportSharedConfig.

@CliCommand(value = { CliStrings.EXPORT_SHARED_CONFIG }, help = CliStrings.EXPORT_SHARED_CONFIG__HELP)
@CliMetaData(interceptor = "org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands$ExportInterceptor", relatedTopic = { CliStrings.TOPIC_GEODE_CONFIG })
@ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
public Result exportSharedConfig(@CliOption(key = { CliStrings.EXPORT_SHARED_CONFIG__FILE }, mandatory = true, help = CliStrings.EXPORT_SHARED_CONFIG__FILE__HELP) String zipFileName) {
    InternalLocator locator = InternalLocator.getLocator();
    if (!locator.isSharedConfigurationRunning()) {
        return ResultBuilder.createGemFireErrorResult(CliStrings.SHARED_CONFIGURATION_NOT_STARTED);
    }
    Path tempDir;
    try {
        tempDir = Files.createTempDirectory("clusterConfig");
    } catch (IOException e) {
        logSevere(e);
        ErrorResultData errorData = ResultBuilder.createErrorResultData().addLine("Unable to create temp directory");
        return ResultBuilder.buildResult(errorData);
    }
    File zipFile = tempDir.resolve("exportedCC.zip").toFile();
    ClusterConfigurationService sc = locator.getSharedConfiguration();
    Result result;
    try {
        for (Configuration config : sc.getEntireConfiguration().values()) {
            sc.writeConfigToFile(config);
        }
        ZipUtils.zipDirectory(sc.getSharedConfigurationDirPath(), zipFile.getCanonicalPath());
        InfoResultData infoData = ResultBuilder.createInfoResultData();
        byte[] byteData = FileUtils.readFileToByteArray(zipFile);
        infoData.addAsFile(zipFileName, byteData, InfoResultData.FILE_TYPE_BINARY, CliStrings.EXPORT_SHARED_CONFIG__DOWNLOAD__MSG, false);
        result = ResultBuilder.buildResult(infoData);
    } catch (Exception e) {
        ErrorResultData errorData = ResultBuilder.createErrorResultData();
        errorData.addLine("Export failed");
        logSevere(e);
        result = ResultBuilder.buildResult(errorData);
    } finally {
        zipFile.delete();
    }
    return result;
}
Also used : Path(java.nio.file.Path) InternalLocator(org.apache.geode.distributed.internal.InternalLocator) ClusterConfigurationService(org.apache.geode.distributed.internal.ClusterConfigurationService) Configuration(org.apache.geode.management.internal.configuration.domain.Configuration) InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) IOException(java.io.IOException) ErrorResultData(org.apache.geode.management.internal.cli.result.ErrorResultData) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 23 with ResourceOperation

use of org.apache.geode.management.internal.security.ResourceOperation in project geode by apache.

the class ExportLogsCommand method exportLogs.

@CliCommand(value = CliStrings.EXPORT_LOGS, help = CliStrings.EXPORT_LOGS__HELP)
@CliMetaData(shellOnly = false, isFileDownloadOverHttp = true, interceptor = "org.apache.geode.management.internal.cli.commands.ExportLogsInterceptor", relatedTopic = { CliStrings.TOPIC_GEODE_SERVER, CliStrings.TOPIC_GEODE_DEBUG_UTIL })
@ResourceOperation(resource = ResourcePermission.Resource.CLUSTER, operation = ResourcePermission.Operation.READ)
public Result exportLogs(@CliOption(key = CliStrings.EXPORT_LOGS__DIR, help = CliStrings.EXPORT_LOGS__DIR__HELP, mandatory = false) String dirName, @CliOption(key = CliStrings.EXPORT_LOGS__GROUP, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.EXPORT_LOGS__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.EXPORT_LOGS__MEMBER, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.EXPORT_LOGS__MEMBER__HELP) String[] memberIds, @CliOption(key = CliStrings.EXPORT_LOGS__LOGLEVEL, unspecifiedDefaultValue = DEFAULT_EXPORT_LOG_LEVEL, optionContext = ConverterHint.LOG_LEVEL, help = CliStrings.EXPORT_LOGS__LOGLEVEL__HELP) String logLevel, @CliOption(key = CliStrings.EXPORT_LOGS__UPTO_LOGLEVEL, unspecifiedDefaultValue = "false", help = CliStrings.EXPORT_LOGS__UPTO_LOGLEVEL__HELP) boolean onlyLogLevel, @CliOption(key = CliStrings.EXPORT_LOGS__MERGELOG, unspecifiedDefaultValue = "false", help = CliStrings.EXPORT_LOGS__MERGELOG__HELP) boolean mergeLog, @CliOption(key = CliStrings.EXPORT_LOGS__STARTTIME, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXPORT_LOGS__STARTTIME__HELP) String start, @CliOption(key = CliStrings.EXPORT_LOGS__ENDTIME, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXPORT_LOGS__ENDTIME__HELP) String end, @CliOption(key = CliStrings.EXPORT_LOGS__LOGSONLY, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.EXPORT_LOGS__LOGSONLY__HELP) boolean logsOnly, @CliOption(key = CliStrings.EXPORT_LOGS__STATSONLY, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.EXPORT_LOGS__STATSONLY__HELP) boolean statsOnly, @CliOption(key = CliStrings.EXPORT_LOGS__FILESIZELIMIT, unspecifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__UNSPECIFIED_DEFAULT, specifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__SPECIFIED_DEFAULT, help = CliStrings.EXPORT_LOGS__FILESIZELIMIT__HELP) String fileSizeLimit) {
    long totalEstimatedExportSize = 0;
    Result result;
    InternalCache cache = getCache();
    try {
        Set<DistributedMember> targetMembers = getMembers(groups, memberIds);
        if (targetMembers.isEmpty()) {
            return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
        }
        if (parseFileSizeLimit(fileSizeLimit) > 0) {
            // Get estimated size of exported logs from all servers before exporting anything
            for (DistributedMember server : targetMembers) {
                SizeExportLogsFunction.Args args = new SizeExportLogsFunction.Args(start, end, logLevel, onlyLogLevel, logsOnly, statsOnly);
                List<Object> results = (List<Object>) estimateLogSize(args, server).getResult();
                long estimatedSize = 0;
                if (!results.isEmpty()) {
                    List<?> res = (List<?>) results.get(0);
                    if (res.get(0) instanceof Long) {
                        estimatedSize = (Long) res.get(0);
                    }
                }
                logger.info("Received estimated export size from member {}: {}", server.getId(), estimatedSize);
                totalEstimatedExportSize += estimatedSize;
            }
            // disk available on the locator
            try {
                checkIfExportLogsOverflowsDisk("locator", parseFileSizeLimit(fileSizeLimit), totalEstimatedExportSize, getLocalDiskAvailable());
            } catch (ManagementException e) {
                return ResultBuilder.createUserErrorResult(e.getMessage());
            }
        }
        // get zipped files from all servers next
        Map<String, Path> zipFilesFromMembers = new HashMap<>();
        for (DistributedMember server : targetMembers) {
            Region region = ExportLogsFunction.createOrGetExistingExportLogsRegion(true, cache);
            ExportLogsCacheWriter cacheWriter = (ExportLogsCacheWriter) region.getAttributes().getCacheWriter();
            cacheWriter.startFile(server.getName());
            CliUtil.executeFunction(new ExportLogsFunction(), new ExportLogsFunction.Args(start, end, logLevel, onlyLogLevel, logsOnly, statsOnly), server).getResult();
            Path zipFile = cacheWriter.endFile();
            ExportLogsFunction.destroyExportLogsRegion(cache);
            // only put the zipfile in the map if it is not null
            if (zipFile != null) {
                logger.info("Received zip file from member {}: {}", server.getId(), zipFile);
                zipFilesFromMembers.put(server.getId(), zipFile);
            }
        }
        if (zipFilesFromMembers.isEmpty()) {
            return ResultBuilder.createUserErrorResult("No files to be exported.");
        }
        Path tempDir = Files.createTempDirectory("exportedLogs");
        // make sure the directory is created, so that even if there is no files unzipped to this
        // dir, we can still zip it and send an empty zip file back to the client
        Path exportedLogsDir = tempDir.resolve("exportedLogs");
        FileUtils.forceMkdir(exportedLogsDir.toFile());
        for (Path zipFile : zipFilesFromMembers.values()) {
            Path unzippedMemberDir = exportedLogsDir.resolve(zipFile.getFileName().toString().replace(".zip", ""));
            ZipUtils.unzip(zipFile.toAbsolutePath().toString(), unzippedMemberDir.toString());
            FileUtils.deleteQuietly(zipFile.toFile());
        }
        Path dirPath;
        if (StringUtils.isBlank(dirName)) {
            dirPath = Paths.get(System.getProperty("user.dir"));
        } else {
            dirPath = Paths.get(dirName);
        }
        Path exportedLogsZipFile = dirPath.resolve("exportedLogs_" + System.currentTimeMillis() + ".zip").toAbsolutePath();
        logger.info("Zipping into: " + exportedLogsZipFile.toString());
        ZipUtils.zipDirectory(exportedLogsDir, exportedLogsZipFile);
        try {
            checkFileSizeWithinLimit(parseFileSizeLimit(fileSizeLimit), exportedLogsZipFile.toFile());
        } catch (ManagementException e) {
            FileUtils.deleteQuietly(exportedLogsZipFile.toFile());
            return ResultBuilder.createUserErrorResult(e.getMessage());
        } finally {
            FileUtils.deleteDirectory(tempDir.toFile());
        }
        result = ResultBuilder.createInfoResult(exportedLogsZipFile.toString());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        result = ResultBuilder.createGemFireErrorResult(ex.getMessage());
    } finally {
        ExportLogsFunction.destroyExportLogsRegion(cache);
    }
    logger.debug("Exporting logs returning = {}", result);
    return result;
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) ExportLogsCacheWriter(org.apache.geode.management.internal.cli.util.ExportLogsCacheWriter) SizeExportLogsFunction(org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction) InternalCache(org.apache.geode.internal.cache.InternalCache) BytesToString(org.apache.geode.management.internal.cli.util.BytesToString) ManagementException(org.apache.geode.management.ManagementException) Result(org.apache.geode.management.cli.Result) ManagementException(org.apache.geode.management.ManagementException) DistributedMember(org.apache.geode.distributed.DistributedMember) SizeExportLogsFunction(org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction) ExportLogsFunction(org.apache.geode.management.internal.cli.functions.ExportLogsFunction) Region(org.apache.geode.cache.Region) List(java.util.List) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 24 with ResourceOperation

use of org.apache.geode.management.internal.security.ResourceOperation in project geode by apache.

the class FunctionCommands method executeFunction.

@CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
@CliMetaData(relatedTopic = { CliStrings.TOPIC_GEODE_FUNCTION })
@ResourceOperation(resource = Resource.DATA, operation = Operation.WRITE)
public Result executeFunction(// TODO: Add optioncontext for functionID
@CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true, help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId, @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONGROUPS, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups, @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONMEMBER, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember, @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.REGION_PATH, help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion, @CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments, @CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector, @CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
    Result result = null;
    CompositeResultData executeFunctionResultTable = ResultBuilder.createCompositeResultData();
    TabularResultData resultTable = executeFunctionResultTable.addSection().addTable("Table1");
    String headerText = "Execution summary";
    resultTable.setHeader(headerText);
    ResultCollector resultCollectorInstance = null;
    Function function;
    Set<String> filters = new HashSet<String>();
    Execution execution = null;
    if (functionId != null) {
        functionId = functionId.trim();
    }
    if (onRegion != null) {
        onRegion = onRegion.trim();
    }
    if (onMember != null) {
        onMember = onMember.trim();
    }
    if (filterString != null) {
        filterString = filterString.trim();
    }
    try {
        // validate otherwise return right away. no need to process anything
        if (functionId == null || functionId.length() == 0) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        }
        if (onRegion != null && onMember != null && onGroups != null) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        } else if (onRegion != null && onMember != null) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        } else if (onMember != null && onGroups != null) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        } else if (onRegion != null && onGroups != null) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        } else if (onRegion != null && onMember != null && onGroups != null) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        } else if ((onRegion == null || onRegion.length() == 0) && (filterString != null)) {
            ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION);
            result = ResultBuilder.buildResult(errorResultData);
            return result;
        }
        InternalCache cache = getCache();
        if (resultCollector != null) {
            resultCollectorInstance = (ResultCollector) ClassPathLoader.getLatest().forName(resultCollector).newInstance();
        }
        if (filterString != null && filterString.length() > 0) {
            filters.add(filterString);
        }
        if (onRegion == null && onMember == null && onGroups == null) {
            // run function on all the members excluding locators bug#46113
            // if user wish to execute on locator then he can choose --member or --group option
            Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
            if (dsMembers.size() > 0) {
                function = new UserFunctionExecution();
                LogWrapper.getInstance().info(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
                for (DistributedMember member : dsMembers) {
                    executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member, resultTable, onRegion);
                }
                return ResultBuilder.buildResult(resultTable);
            } else {
                return ResultBuilder.createUserErrorResult(CliStrings.EXECUTE_FUNCTION__MSG__DS_HAS_NO_MEMBERS);
            }
        } else if (onRegion != null && onRegion.length() > 0) {
            if (cache.getRegion(onRegion) == null) {
                // find a member where region is present
                DistributedRegionMXBean bean = ManagementService.getManagementService(getCache()).getDistributedRegionMXBean(onRegion);
                if (bean == null) {
                    bean = ManagementService.getManagementService(getCache()).getDistributedRegionMXBean(Region.SEPARATOR + onRegion);
                    if (bean == null) {
                        return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__MXBEAN_0_FOR_NOT_FOUND, onRegion));
                    }
                }
                DistributedMember member = null;
                String[] membersName = bean.getMembers();
                Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
                Iterator it = dsMembers.iterator();
                boolean matchFound = false;
                if (membersName.length > 0) {
                    while (it.hasNext() && matchFound == false) {
                        DistributedMember dsmember = (DistributedMember) it.next();
                        for (String memberName : membersName) {
                            if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
                                member = dsmember;
                                matchFound = true;
                                break;
                            }
                        }
                    }
                }
                if (matchFound == true) {
                    executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member, resultTable, onRegion);
                    return ResultBuilder.buildResult(resultTable);
                } else {
                    return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER_REGION, " " + onRegion));
                }
            } else {
                execution = FunctionService.onRegion(cache.getRegion(onRegion));
                if (execution != null) {
                    if (resultCollectorInstance != null) {
                        execution = execution.withCollector(resultCollectorInstance);
                    }
                    if (filters != null && filters.size() > 0) {
                        execution = execution.withFilter(filters);
                    }
                    if (arguments != null && arguments.length > 0) {
                        execution = execution.setArguments(arguments);
                    }
                    try {
                        List<Object> results = (List<Object>) execution.execute(functionId).getResult();
                        if (results.size() > 0) {
                            StringBuilder strResult = new StringBuilder();
                            for (Object obj : results) {
                                strResult.append(obj);
                            }
                            toTabularResultData(resultTable, cache.getDistributedSystem().getDistributedMember().getId(), strResult.toString());
                        }
                        return ResultBuilder.buildResult(resultTable);
                    } catch (FunctionException e) {
                        return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2, functionId, onRegion, e.getMessage()));
                    }
                } else {
                    return ResultBuilder.createGemFireErrorResult(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2, functionId, onRegion, CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR));
                }
            }
        } else if (onGroups != null) {
            // execute on group members
            Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
            for (String grp : onGroups) {
                dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
            }
            StringBuilder successMessage = new StringBuilder();
            if (dsMembers.size() > 0) {
                for (DistributedMember member : dsMembers) {
                    executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member, resultTable, onRegion);
                }
                return ResultBuilder.buildResult(resultTable);
            } else {
                StringBuilder grps = new StringBuilder();
                for (String grp : onGroups) {
                    grps.append(grp);
                    grps.append(", ");
                }
                return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__GROUPS_0_HAS_NO_MEMBERS, grps.toString().substring(0, grps.toString().length() - 1)));
            }
        } else if (onMember != null && onMember.length() > 0) {
            // fix for bug
            DistributedMember member = CliUtil.getDistributedMemberByNameOrId(onMember);
            // 45658
            if (member != null) {
                executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member, resultTable, onRegion);
            } else {
                toTabularResultData(resultTable, onMember, CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER + " " + onMember));
            }
            return ResultBuilder.buildResult(resultTable);
        }
    } catch (InstantiationException e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    } catch (IllegalAccessException e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    } catch (IllegalArgumentException e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    } catch (SecurityException e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    } catch (Exception e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    }
    return result;
}
Also used : UserFunctionExecution(org.apache.geode.management.internal.cli.functions.UserFunctionExecution) CompositeResultData(org.apache.geode.management.internal.cli.result.CompositeResultData) HashSet(java.util.HashSet) Set(java.util.Set) TabularResultData(org.apache.geode.management.internal.cli.result.TabularResultData) InternalCache(org.apache.geode.internal.cache.InternalCache) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) Function(org.apache.geode.cache.execute.Function) ListFunctionFunction(org.apache.geode.management.internal.cli.functions.ListFunctionFunction) UnregisterFunction(org.apache.geode.management.internal.cli.functions.UnregisterFunction) UserFunctionExecution(org.apache.geode.management.internal.cli.functions.UserFunctionExecution) Execution(org.apache.geode.cache.execute.Execution) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashSet(java.util.HashSet) FunctionException(org.apache.geode.cache.execute.FunctionException) DistributedRegionMXBean(org.apache.geode.management.DistributedRegionMXBean) FunctionException(org.apache.geode.cache.execute.FunctionException) CommandResultException(org.apache.geode.management.internal.cli.result.CommandResultException) DistributedMember(org.apache.geode.distributed.DistributedMember) ErrorResultData(org.apache.geode.management.internal.cli.result.ErrorResultData) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 25 with ResourceOperation

use of org.apache.geode.management.internal.security.ResourceOperation in project geode by apache.

the class FunctionCommands method destroyFunction.

@CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
@CliMetaData(relatedTopic = { CliStrings.TOPIC_GEODE_FUNCTION }, interceptor = "org.apache.geode.management.internal.cli.commands.FunctionCommands$Interceptor")
@ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
public // TODO: Add optioncontext for functionId
Result destroyFunction(@CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true, help = CliStrings.DESTROY_FUNCTION__HELP) String functionId, @CliOption(key = CliStrings.DESTROY_FUNCTION__ONGROUPS, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups, @CliOption(key = CliStrings.DESTROY_FUNCTION__ONMEMBER, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
    Result result = null;
    try {
        InternalCache cache = getCache();
        Set<DistributedMember> dsMembers = new HashSet<DistributedMember>();
        if (groups != null && memberId != null) {
            return ResultBuilder.createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
        } else if (groups != null && groups.length > 0) {
            // execute on group members
            for (String grp : groups) {
                dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
            }
            @SuppressWarnings("unchecked") Result results = executeFunction(cache, dsMembers, functionId);
            return results;
        } else if (memberId != null) {
            // execute on member
            dsMembers.add(getMember(cache, memberId));
            @SuppressWarnings("unchecked") Result results = executeFunction(cache, dsMembers, functionId);
            return results;
        } else {
            // no option provided.
            @SuppressWarnings("unchecked") Result results = executeFunction(cache, cache.getMembers(), functionId);
            return results;
        }
    } catch (Exception e) {
        ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
        result = ResultBuilder.buildResult(errorResultData);
        return result;
    }
}
Also used : DistributedMember(org.apache.geode.distributed.DistributedMember) InternalCache(org.apache.geode.internal.cache.InternalCache) ErrorResultData(org.apache.geode.management.internal.cli.result.ErrorResultData) FunctionException(org.apache.geode.cache.execute.FunctionException) CommandResultException(org.apache.geode.management.internal.cli.result.CommandResultException) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) HashSet(java.util.HashSet) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Aggregations

ResourceOperation (org.apache.geode.management.internal.security.ResourceOperation)58 CliCommand (org.springframework.shell.core.annotation.CliCommand)57 CliMetaData (org.apache.geode.management.cli.CliMetaData)55 DistributedMember (org.apache.geode.distributed.DistributedMember)49 Result (org.apache.geode.management.cli.Result)49 CliFunctionResult (org.apache.geode.management.internal.cli.functions.CliFunctionResult)32 InternalCache (org.apache.geode.internal.cache.InternalCache)30 TabularResultData (org.apache.geode.management.internal.cli.result.TabularResultData)30 CommandResultException (org.apache.geode.management.internal.cli.result.CommandResultException)27 ArrayList (java.util.ArrayList)18 List (java.util.List)18 ExecutionException (java.util.concurrent.ExecutionException)15 GfshParseResult (org.apache.geode.management.internal.cli.GfshParseResult)14 ObjectName (javax.management.ObjectName)13 CompositeResultData (org.apache.geode.management.internal.cli.result.CompositeResultData)13 IOException (java.io.IOException)11 HashSet (java.util.HashSet)11 SystemManagementService (org.apache.geode.management.internal.SystemManagementService)11 HashMap (java.util.HashMap)10 ConverterHint (org.apache.geode.management.cli.ConverterHint)10