Search in sources :

Example 1 with InfoResultData

use of org.apache.geode.management.internal.cli.result.InfoResultData in project geode by apache.

the class IndexCommands method destroyIndex.

@CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
@CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA })
public Result destroyIndex(@CliOption(key = CliStrings.DESTROY_INDEX__NAME, mandatory = false, unspecifiedDefaultValue = "", help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName, @CliOption(key = CliStrings.DESTROY_INDEX__REGION, mandatory = false, optionContext = ConverterHint.REGION_PATH, help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath, @CliOption(key = CliStrings.DESTROY_INDEX__MEMBER, mandatory = false, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID, @CliOption(key = CliStrings.DESTROY_INDEX__GROUP, mandatory = false, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
    Result result = null;
    if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath) && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
        return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
    }
    String regionName = null;
    final Cache cache = CacheFactory.getAnyInstance();
    // requires data manage permission on all regions
    if (StringUtils.isNotBlank(regionPath)) {
        regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
        this.securityService.authorizeRegionManage(regionName);
    } else {
        this.securityService.authorizeDataManage();
    }
    IndexInfo indexInfo = new IndexInfo(indexName, regionName);
    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
    if (targetMembers.isEmpty()) {
        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
    }
    ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
    List<Object> funcResults = (List<Object>) rc.getResult();
    Set<String> successfulMembers = new TreeSet<String>();
    Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
    for (Object funcResult : funcResults) {
        if (!(funcResult instanceof CliFunctionResult)) {
            continue;
        }
        CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
        if (cliFunctionResult.isSuccessful()) {
            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
            if (xmlEntity.get() == null) {
                xmlEntity.set(cliFunctionResult.getXmlEntity());
            }
        } else {
            String exceptionMessage = cliFunctionResult.getMessage();
            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
            if (failedMembers == null) {
                failedMembers = new TreeSet<String>();
            }
            failedMembers.add(cliFunctionResult.getMemberIdOrName());
            indexOpFailMap.put(exceptionMessage, failedMembers);
        }
    }
    if (!successfulMembers.isEmpty()) {
        InfoResultData infoResult = ResultBuilder.createInfoResultData();
        if (StringUtils.isNotBlank(indexName)) {
            if (StringUtils.isNotBlank(regionPath)) {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG, indexName, regionPath));
            } else {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
            }
        } else {
            if (StringUtils.isNotBlank(regionPath)) {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath));
            } else {
                infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
            }
        }
        int num = 0;
        for (String memberId : successfulMembers) {
            infoResult.addLine(CliStrings.format(CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
            ;
        }
        result = ResultBuilder.buildResult(infoResult);
    } else {
        ErrorResultData erd = ResultBuilder.createErrorResultData();
        if (StringUtils.isNotBlank(indexName)) {
            erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
        } else {
            erd.addLine("Indexes could not be destroyed for following reasons");
        }
        Set<String> exceptionMessages = indexOpFailMap.keySet();
        for (String exceptionMessage : exceptionMessages) {
            erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
            erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);
            Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
            int num = 0;
            for (String memberId : memberIds) {
                erd.addLine(CliStrings.format(CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
            }
            erd.addLine("");
        }
        result = ResultBuilder.buildResult(erd);
    }
    if (xmlEntity.get() != null) {
        persistClusterConfiguration(result, () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
    }
    return result;
}
Also used : TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Set(java.util.Set) InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) IndexInfo(org.apache.geode.management.internal.cli.domain.IndexInfo) ConverterHint(org.apache.geode.management.cli.ConverterHint) Result(org.apache.geode.management.cli.Result) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) XmlEntity(org.apache.geode.management.internal.configuration.domain.XmlEntity) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) TreeSet(java.util.TreeSet) DistributedMember(org.apache.geode.distributed.DistributedMember) ArrayList(java.util.ArrayList) List(java.util.List) ErrorResultData(org.apache.geode.management.internal.cli.result.ErrorResultData) ResultCollector(org.apache.geode.cache.execute.ResultCollector) InternalCache(org.apache.geode.internal.cache.InternalCache) Cache(org.apache.geode.cache.Cache) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Example 2 with InfoResultData

use of org.apache.geode.management.internal.cli.result.InfoResultData in project geode by apache.

the class LauncherLifecycleCommands method startLocator.

@CliCommand(value = CliStrings.START_LOCATOR, help = CliStrings.START_LOCATOR__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEODE_LOCATOR, CliStrings.TOPIC_GEODE_LIFECYCLE })
public Result startLocator(@CliOption(key = CliStrings.START_LOCATOR__MEMBER_NAME, help = CliStrings.START_LOCATOR__MEMBER_NAME__HELP) String memberName, @CliOption(key = CliStrings.START_LOCATOR__BIND_ADDRESS, help = CliStrings.START_LOCATOR__BIND_ADDRESS__HELP) final String bindAddress, @CliOption(key = CliStrings.START_LOCATOR__CLASSPATH, help = CliStrings.START_LOCATOR__CLASSPATH__HELP) final String classpath, @CliOption(key = CliStrings.START_LOCATOR__FORCE, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__FORCE__HELP) final Boolean force, @CliOption(key = CliStrings.START_LOCATOR__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.START_LOCATOR__GROUP__HELP) final String group, @CliOption(key = CliStrings.START_LOCATOR__HOSTNAME_FOR_CLIENTS, help = CliStrings.START_LOCATOR__HOSTNAME_FOR_CLIENTS__HELP) final String hostnameForClients, @CliOption(key = CliStrings.START_LOCATOR__INCLUDE_SYSTEM_CLASSPATH, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = CliStrings.START_LOCATOR__INCLUDE_SYSTEM_CLASSPATH__HELP) final Boolean includeSystemClasspath, @CliOption(key = CliStrings.START_LOCATOR__LOCATORS, optionContext = ConverterHint.LOCATOR_DISCOVERY_CONFIG, help = CliStrings.START_LOCATOR__LOCATORS__HELP) final String locators, @CliOption(key = CliStrings.START_LOCATOR__LOG_LEVEL, optionContext = ConverterHint.LOG_LEVEL, help = CliStrings.START_LOCATOR__LOG_LEVEL__HELP) final String logLevel, @CliOption(key = CliStrings.START_LOCATOR__MCAST_ADDRESS, help = CliStrings.START_LOCATOR__MCAST_ADDRESS__HELP) final String mcastBindAddress, @CliOption(key = CliStrings.START_LOCATOR__MCAST_PORT, help = CliStrings.START_LOCATOR__MCAST_PORT__HELP) final Integer mcastPort, @CliOption(key = CliStrings.START_LOCATOR__PORT, help = CliStrings.START_LOCATOR__PORT__HELP) final Integer port, @CliOption(key = CliStrings.START_LOCATOR__DIR, help = CliStrings.START_LOCATOR__DIR__HELP) String workingDirectory, @CliOption(key = CliStrings.START_LOCATOR__PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_LOCATOR__PROPERTIES__HELP) String gemfirePropertiesPathname, @CliOption(key = CliStrings.START_LOCATOR__SECURITY_PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_LOCATOR__SECURITY_PROPERTIES__HELP) String gemfireSecurityPropertiesPathname, @CliOption(key = CliStrings.START_LOCATOR__INITIALHEAP, help = CliStrings.START_LOCATOR__INITIALHEAP__HELP) final String initialHeap, @CliOption(key = CliStrings.START_LOCATOR__MAXHEAP, help = CliStrings.START_LOCATOR__MAXHEAP__HELP) final String maxHeap, @CliOption(key = CliStrings.START_LOCATOR__J, optionContext = GfshParser.J_OPTION_CONTEXT, help = CliStrings.START_LOCATOR__J__HELP) final String[] jvmArgsOpts, @CliOption(key = CliStrings.START_LOCATOR__CONNECT, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__CONNECT__HELP) final boolean connect, @CliOption(key = CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION__HELP) final boolean enableSharedConfiguration, @CliOption(key = CliStrings.START_LOCATOR__LOAD__SHARED_CONFIGURATION__FROM__FILESYSTEM, unspecifiedDefaultValue = "false", help = CliStrings.START_LOCATOR__LOAD__SHARED_CONFIGURATION__FROM__FILESYSTEM__HELP) final boolean loadSharedConfigurationFromDirectory, @CliOption(key = CliStrings.START_LOCATOR__CLUSTER__CONFIG__DIR, unspecifiedDefaultValue = "", help = CliStrings.START_LOCATOR__CLUSTER__CONFIG__DIR__HELP) final String clusterConfigDir, @CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT, help = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT__HELP) final Integer httpServicePort, @CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS, help = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS__HELP) final String httpServiceBindAddress) {
    try {
        if (StringUtils.isBlank(memberName)) {
            // when the user doesn't give us a name, we make one up!
            memberName = nameGenerator.generate('-');
        }
        workingDirectory = resolveWorkingDir(workingDirectory, memberName);
        gemfirePropertiesPathname = CliUtil.resolvePathname(gemfirePropertiesPathname);
        if (StringUtils.isNotBlank(gemfirePropertiesPathname) && !IOUtils.isExistingPathname(gemfirePropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY, gemfirePropertiesPathname));
        }
        gemfireSecurityPropertiesPathname = CliUtil.resolvePathname(gemfireSecurityPropertiesPathname);
        if (StringUtils.isNotBlank(gemfireSecurityPropertiesPathname) && !IOUtils.isExistingPathname(gemfireSecurityPropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gemfireSecurityPropertiesPathname));
        }
        File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
        final int oldPid = readPid(locatorPidFile);
        Properties gemfireProperties = new Properties();
        gemfireProperties.setProperty(GROUPS, StringUtils.defaultString(group));
        gemfireProperties.setProperty(LOCATORS, StringUtils.defaultString(locators));
        gemfireProperties.setProperty(LOG_LEVEL, StringUtils.defaultString(logLevel));
        gemfireProperties.setProperty(MCAST_ADDRESS, StringUtils.defaultString(mcastBindAddress));
        gemfireProperties.setProperty(MCAST_PORT, StringUtils.defaultString(mcastPort));
        gemfireProperties.setProperty(ENABLE_CLUSTER_CONFIGURATION, StringUtils.defaultString(enableSharedConfiguration));
        gemfireProperties.setProperty(LOAD_CLUSTER_CONFIGURATION_FROM_DIR, StringUtils.defaultString(loadSharedConfigurationFromDirectory));
        gemfireProperties.setProperty(CLUSTER_CONFIGURATION_DIR, StringUtils.defaultString(clusterConfigDir));
        gemfireProperties.setProperty(HTTP_SERVICE_PORT, StringUtils.defaultString(httpServicePort));
        gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, StringUtils.defaultString(httpServiceBindAddress));
        // read the OSProcess enable redirect system property here -- TODO: replace with new GFSH
        // argument
        final boolean redirectOutput = Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
        LocatorLauncher.Builder locatorLauncherBuilder = new LocatorLauncher.Builder().setBindAddress(bindAddress).setForce(force).setPort(port).setRedirectOutput(redirectOutput).setWorkingDirectory(workingDirectory);
        if (hostnameForClients != null) {
            locatorLauncherBuilder.setHostnameForClients(hostnameForClients);
        }
        if (memberName != null) {
            locatorLauncherBuilder.setMemberName(memberName);
        }
        LocatorLauncher locatorLauncher = locatorLauncherBuilder.build();
        String[] locatorCommandLine = createStartLocatorCommandLine(locatorLauncher, gemfirePropertiesPathname, gemfireSecurityPropertiesPathname, gemfireProperties, classpath, includeSystemClasspath, jvmArgsOpts, initialHeap, maxHeap);
        final Process locatorProcess = new ProcessBuilder(locatorCommandLine).directory(new File(locatorLauncher.getWorkingDirectory())).start();
        locatorProcess.getInputStream().close();
        locatorProcess.getOutputStream().close();
        // fix TRAC bug #51967 by using NON_BLOCKING on Windows
        final ReadingMode readingMode = SystemUtils.isWindows() ? ReadingMode.NON_BLOCKING : ReadingMode.BLOCKING;
        // need thread-safe StringBuffer
        final StringBuffer message = new StringBuffer();
        InputListener inputListener = new InputListener() {

            @Override
            public void notifyInputLine(String line) {
                message.append(line);
                if (readingMode == ReadingMode.BLOCKING) {
                    message.append(StringUtils.LINE_SEPARATOR);
                }
            }
        };
        ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(locatorProcess).inputStream(locatorProcess.getErrorStream()).inputListener(inputListener).readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
        LocatorState locatorState;
        String previousLocatorStatusMessage = null;
        LauncherSignalListener locatorSignalListener = new LauncherSignalListener();
        final boolean registeredLocatorSignalListener = getGfsh().getSignalHandler().registerListener(locatorSignalListener);
        try {
            getGfsh().logInfo(String.format(CliStrings.START_LOCATOR__RUN_MESSAGE, IOUtils.tryGetCanonicalPathElseGetAbsolutePath(new File(locatorLauncher.getWorkingDirectory()))), null);
            locatorState = LocatorState.fromDirectory(workingDirectory, memberName);
            do {
                if (locatorProcess.isAlive()) {
                    Gfsh.print(".");
                    synchronized (this) {
                        TimeUnit.MILLISECONDS.timedWait(this, 500);
                    }
                    locatorState = LocatorState.fromDirectory(workingDirectory, memberName);
                    String currentLocatorStatusMessage = locatorState.getStatusMessage();
                    if (locatorState.isStartingOrNotResponding() && !(StringUtils.isBlank(currentLocatorStatusMessage) || currentLocatorStatusMessage.equalsIgnoreCase(previousLocatorStatusMessage) || currentLocatorStatusMessage.trim().toLowerCase().equals("null"))) {
                        Gfsh.println();
                        Gfsh.println(currentLocatorStatusMessage);
                        previousLocatorStatusMessage = currentLocatorStatusMessage;
                    }
                } else {
                    final int exitValue = locatorProcess.exitValue();
                    return ResultBuilder.createShellClientErrorResult(String.format(CliStrings.START_LOCATOR__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE, exitValue, locatorLauncher.getWorkingDirectory(), message.toString()));
                }
            } while (!(registeredLocatorSignalListener && locatorSignalListener.isSignaled()) && locatorState.isStartingOrNotResponding());
        } finally {
            // stop will close
            stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
            // ErrorStream
            getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
        }
        Gfsh.println();
        final boolean asyncStart = (registeredLocatorSignalListener && locatorSignalListener.isSignaled() && ServerState.isStartingNotRespondingOrNull(locatorState));
        InfoResultData infoResultData = ResultBuilder.createInfoResultData();
        if (asyncStart) {
            infoResultData.addLine(String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, LOCATOR_TERM_NAME));
        } else {
            infoResultData.addLine(locatorState.toString());
            String locatorHostName;
            InetAddress bindAddr = locatorLauncher.getBindAddress();
            if (bindAddr != null) {
                locatorHostName = bindAddr.getCanonicalHostName();
            } else {
                locatorHostName = StringUtils.defaultIfBlank(locatorLauncher.getHostnameForClients(), HostUtils.getLocalHost());
            }
            int locatorPort = Integer.parseInt(locatorState.getPort());
            // Else, ask the user to use the "connect" command to connect to the Locator.
            if (shouldAutoConnect(connect)) {
                doAutoConnect(locatorHostName, locatorPort, gemfirePropertiesPathname, gemfireSecurityPropertiesPathname, infoResultData);
            }
            // Report on the state of the Shared Configuration service if enabled...
            if (enableSharedConfiguration) {
                infoResultData.addLine(ClusterConfigurationStatusRetriever.fromLocator(locatorHostName, locatorPort));
            }
        }
        return ResultBuilder.buildResult(infoResultData);
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        if (message != null && message.matches(LocalizedStrings.Launcher_Builder_UNKNOWN_HOST_ERROR_MESSAGE.toLocalizedString(".+"))) {
            message = CliStrings.format(CliStrings.LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1, LOCATOR_TERM_NAME, message);
        }
        return ResultBuilder.createUserErrorResult(message);
    } catch (IllegalStateException e) {
        return ResultBuilder.createUserErrorResult(e.getMessage());
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable t) {
        SystemFailure.checkFailure();
        String errorMessage = String.format(CliStrings.START_LOCATOR__GENERAL_ERROR_MESSAGE, StringUtils.defaultIfBlank(workingDirectory, memberName), getLocatorId(bindAddress, port), toString(t, getGfsh().getDebug()));
        getGfsh().logToFile(errorMessage, t);
        return ResultBuilder.createShellClientErrorResult(errorMessage);
    } finally {
        Gfsh.redirectInternalJavaLoggers();
    }
}
Also used : LocatorLauncher(org.apache.geode.distributed.LocatorLauncher) InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) CommandStringBuilder(org.apache.geode.management.internal.cli.util.CommandStringBuilder) ResultBuilder(org.apache.geode.management.internal.cli.result.ResultBuilder) OSProcess(org.apache.geode.internal.OSProcess) Properties(java.util.Properties) ConnectionEndpoint(org.apache.geode.management.internal.cli.util.ConnectionEndpoint) ConverterHint(org.apache.geode.management.cli.ConverterHint) InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) ProcessStreamReader(org.apache.geode.internal.process.ProcessStreamReader) LocatorState(org.apache.geode.distributed.LocatorLauncher.LocatorState) File(java.io.File) InetAddress(java.net.InetAddress) ReadingMode(org.apache.geode.internal.process.ProcessStreamReader.ReadingMode) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Example 3 with InfoResultData

use of org.apache.geode.management.internal.cli.result.InfoResultData 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 4 with InfoResultData

use of org.apache.geode.management.internal.cli.result.InfoResultData 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 5 with InfoResultData

use of org.apache.geode.management.internal.cli.result.InfoResultData in project geode by apache.

the class IndexCommands method defineIndex.

@CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
@CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA })
public // TODO : Add optionContext for indexName
Result defineIndex(@CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true, help = CliStrings.DEFINE_INDEX__HELP) final String indexName, @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true, help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression, @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true, optionContext = ConverterHint.REGION_PATH, help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath, @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, mandatory = false, unspecifiedDefaultValue = "range", optionContext = ConverterHint.INDEX_TYPE, help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
    Result result = null;
    XmlEntity xmlEntity = null;
    this.securityService.authorizeRegionManage(regionPath);
    int idxType = IndexInfo.RANGE_INDEX;
    // Index type check
    if ("range".equalsIgnoreCase(indexType)) {
        idxType = IndexInfo.RANGE_INDEX;
    } else if ("hash".equalsIgnoreCase(indexType)) {
        idxType = IndexInfo.HASH_INDEX;
    } else if ("key".equalsIgnoreCase(indexType)) {
        idxType = IndexInfo.KEY_INDEX;
    } else {
        return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
    }
    if (indexName == null || indexName.isEmpty()) {
        return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
    }
    if (indexedExpression == null || indexedExpression.isEmpty()) {
        return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
    }
    if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
        return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
    }
    if (!regionPath.startsWith(Region.SEPARATOR)) {
        regionPath = Region.SEPARATOR + regionPath;
    }
    IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
    indexDefinitions.add(indexInfo);
    final InfoResultData infoResult = ResultBuilder.createInfoResultData();
    infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
    infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
    result = ResultBuilder.buildResult(infoResult);
    return result;
}
Also used : XmlEntity(org.apache.geode.management.internal.configuration.domain.XmlEntity) InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) IndexInfo(org.apache.geode.management.internal.cli.domain.IndexInfo) ConverterHint(org.apache.geode.management.cli.ConverterHint) Result(org.apache.geode.management.cli.Result) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Aggregations

InfoResultData (org.apache.geode.management.internal.cli.result.InfoResultData)21 CliMetaData (org.apache.geode.management.cli.CliMetaData)17 CliCommand (org.springframework.shell.core.annotation.CliCommand)17 Result (org.apache.geode.management.cli.Result)12 ResourceOperation (org.apache.geode.management.internal.security.ResourceOperation)10 DistributedMember (org.apache.geode.distributed.DistributedMember)9 IOException (java.io.IOException)7 InternalCache (org.apache.geode.internal.cache.InternalCache)7 ConverterHint (org.apache.geode.management.cli.ConverterHint)7 CliFunctionResult (org.apache.geode.management.internal.cli.functions.CliFunctionResult)7 GfshParseResult (org.apache.geode.management.internal.cli.GfshParseResult)6 ErrorResultData (org.apache.geode.management.internal.cli.result.ErrorResultData)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 XmlEntity (org.apache.geode.management.internal.configuration.domain.XmlEntity)5 File (java.io.File)4 List (java.util.List)4 Set (java.util.Set)4 NetstatFunctionResult (org.apache.geode.management.internal.cli.functions.NetstatFunction.NetstatFunctionResult)4