Search in sources :

Example 1 with GfshParseResult

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

the class CLIMultiStepHelper method executeStep.

private static Result executeStep(final LogWrapper logWrapper, final Gfsh shell, final CLIStep nextStep, final ParseResult parseResult, final SectionResultData nextStepArgs) {
    try {
        if (nextStep instanceof CLIRemoteStep) {
            if (shell.isConnectedAndReady()) {
                if (GfshParseResult.class.isInstance(parseResult)) {
                    GfshParseResult gfshParseResult = (GfshParseResult) parseResult;
                    // stepArgs
                    if (nextStepArgs != null) {
                        GfJsonObject argsJSon = nextStepArgs.getSectionGfJsonObject();
                        shell.setEnvProperty(CLIMultiStepHelper.STEP_ARGS, argsJSon.toString());
                    }
                    CommandRequest commandRequest = new CommandRequest(gfshParseResult, shell.getEnv());
                    commandRequest.setCustomInput(changeStepName(gfshParseResult.getUserInput(), nextStep.getName()));
                    commandRequest.getCustomParameters().put(CliStrings.QUERY__STEPNAME, nextStep.getName());
                    String json = (String) shell.getOperationInvoker().processCommand(commandRequest);
                    return ResultBuilder.fromJson(json);
                } else {
                    throw new IllegalArgumentException("Command Configuration/Definition error.");
                }
            } else {
                try {
                    throw new Exception();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                throw new IllegalStateException("Can't execute a remote command without connection. Use 'connect' first to connect.");
            }
        } else {
            Map<String, String> args = CommandExecutionContext.getShellEnv();
            if (args == null) {
                args = new HashMap<String, String>();
                CommandExecutionContext.setShellEnv(args);
            }
            if (nextStepArgs != null) {
                GfJsonObject argsJSon = nextStepArgs.getSectionGfJsonObject();
                Gfsh.getCurrentInstance().setEnvProperty(CLIMultiStepHelper.STEP_ARGS, argsJSon.toString());
            }
            return nextStep.exec();
        }
    } catch (CLIStepExecption e) {
        logWrapper.severe("CLIStep " + nextStep.getName() + " failed aborting command");
        throw e;
    }
}
Also used : CommandRequest(org.apache.geode.management.internal.cli.CommandRequest) GfJsonObject(org.apache.geode.management.internal.cli.json.GfJsonObject) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) GfJsonException(org.apache.geode.management.internal.cli.json.GfJsonException)

Example 2 with GfshParseResult

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

the class RemoteExecutionStrategy method execute.

public Object execute(ParseResult parseResult) throws RuntimeException {
    Result result = null;
    try {
        Assert.notNull(parseResult, "Parse result required");
        if (!GfshParseResult.class.isInstance(parseResult)) {
            // TODO: should this message be more specific?
            throw new IllegalArgumentException("Command Configuration/Definition error.");
        }
        GfshParseResult gfshParseResult = (GfshParseResult) parseResult;
        Method method = gfshParseResult.getMethod();
        if (!isShellOnly(method)) {
            Boolean fromShell = CommandExecutionContext.isShellRequest();
            boolean sentFromShell = fromShell != null && fromShell.booleanValue();
            String interceptorClass = getInterceptor(gfshParseResult.getMethod());
            CliAroundInterceptor interceptor = null;
            // 1. Pre Execution
            if (!sentFromShell && !CliMetaData.ANNOTATION_NULL_VALUE.equals(interceptorClass)) {
                try {
                    interceptor = (CliAroundInterceptor) ClassPathLoader.getLatest().forName(interceptorClass).newInstance();
                } catch (InstantiationException e) {
                    logWrapper.info(e.getMessage());
                } catch (IllegalAccessException e) {
                    logWrapper.info(e.getMessage());
                } catch (ClassNotFoundException e) {
                    logWrapper.info(e.getMessage());
                }
                if (interceptor != null) {
                    Result preExecResult = interceptor.preExecution(gfshParseResult);
                    if (Status.ERROR.equals(preExecResult.getStatus())) {
                        return preExecResult;
                    } else if (preExecResult instanceof FileResult) {
                        FileResult fileResult = (FileResult) preExecResult;
                        byte[][] fileData = fileResult.toBytes();
                        CommandExecutionContext.setBytesFromShell(fileData);
                    }
                } else {
                    return ResultBuilder.createBadConfigurationErrorResult("Interceptor Configuration Error");
                }
            }
            logWrapper.info("Executing " + gfshParseResult.getUserInput());
            result = (Result) ReflectionUtils.invokeMethod(gfshParseResult.getMethod(), gfshParseResult.getInstance(), gfshParseResult.getArguments());
            if (result != null && Status.ERROR.equals(result.getStatus())) {
                logWrapper.info("Error occurred while executing \"" + gfshParseResult.getUserInput() + "\".");
            }
            if (interceptor != null) {
                Result postExecResult = interceptor.postExecution(gfshParseResult, result, null);
                if (postExecResult != null) {
                    if (Status.ERROR.equals(postExecResult.getStatus())) {
                        logWrapper.warning(postExecResult.toString(), null);
                    } else if (logWrapper.fineEnabled()) {
                        logWrapper.fine(String.valueOf(postExecResult));
                    }
                    result = postExecResult;
                }
                // for remote commands with bytes
                CommandExecutionContext.setBytesFromShell(null);
            }
        } else {
            throw new IllegalArgumentException("Only Remote command can be executed through " + ManagementService.class.getSimpleName() + ".processCommand() or ManagementMBean's processCommand " + "operation. Please refer documentation for the list of " + "commands.");
        }
    } catch (RuntimeException e) {
        throw e;
    }
    return result;
}
Also used : GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) CliAroundInterceptor(org.apache.geode.management.internal.cli.CliAroundInterceptor) Method(java.lang.reflect.Method) ParseResult(org.springframework.shell.event.ParseResult) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult) ManagementService(org.apache.geode.management.ManagementService) FileResult(org.apache.geode.management.internal.cli.result.FileResult)

Example 3 with GfshParseResult

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

the class GfshExecutionStrategy method execute.

//////////////// ExecutionStrategy interface Methods Start ///////////////////
///////////////////////// Implemented Methods ////////////////////////////////
/**
   * Executes the method indicated by the {@link ParseResult} which would always be
   * {@link GfshParseResult} for GemFire defined commands. If the command Method is decorated with
   * {@link CliMetaData#shellOnly()} set to <code>false</code>, {@link OperationInvoker} is used to
   * send the command for processing on a remote GemFire node.
   * 
   * @param parseResult that should be executed (never presented as null)
   * @return an object which will be rendered by the {@link Shell} implementation (may return null)
   * @throws RuntimeException which is handled by the {@link Shell} implementation
   */
@Override
public Object execute(ParseResult parseResult) {
    Result result = null;
    Method method = parseResult.getMethod();
    try {
        // Check if it's a multi-step command
        MultiStepCommand cmd = method.getAnnotation(MultiStepCommand.class);
        if (cmd != null) {
            return execCLISteps(logWrapper, shell, parseResult);
        }
        // check if it's a shell only command
        if (isShellOnly(method)) {
            Assert.notNull(parseResult, "Parse result required");
            synchronized (mutex) {
                Assert.isTrue(isReadyForCommands(), "ProcessManagerHostedExecutionStrategy not yet ready for commands");
                return ReflectionUtils.invokeMethod(parseResult.getMethod(), parseResult.getInstance(), parseResult.getArguments());
            }
        }
        // check if it's a GfshParseResult
        if (!GfshParseResult.class.isInstance(parseResult)) {
            throw new IllegalStateException("Configuration error!");
        }
        result = executeOnRemote((GfshParseResult) parseResult);
    } catch (NotAuthorizedException e) {
        result = ResultBuilder.createGemFireUnAuthorizedErrorResult("Unauthorized. Reason: " + e.getMessage());
    } catch (JMXInvocationException | IllegalStateException e) {
        Gfsh.getCurrentInstance().logWarning(e.getMessage(), e);
    } catch (CommandProcessingException e) {
        Gfsh.getCurrentInstance().logWarning(e.getMessage(), null);
        Object errorData = e.getErrorData();
        if (errorData != null && errorData instanceof Throwable) {
            logWrapper.warning(e.getMessage(), (Throwable) errorData);
        } else {
            logWrapper.warning(e.getMessage());
        }
    } catch (Exception e) {
        Gfsh.getCurrentInstance().logWarning("Unexpected exception occurred. " + e.getMessage(), e);
        // Log other exceptions in gfsh log
        logWrapper.warning("Unexpected error occurred while executing command : " + ((GfshParseResult) parseResult).getUserInput(), e);
    }
    return result;
}
Also used : MultiStepCommand(org.apache.geode.management.internal.cli.multistep.MultiStepCommand) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Method(java.lang.reflect.Method) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) CommandProcessingException(org.apache.geode.management.cli.CommandProcessingException) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) CommandProcessingException(org.apache.geode.management.cli.CommandProcessingException) ParseResult(org.springframework.shell.event.ParseResult) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult)

Example 4 with GfshParseResult

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

the class GfshExecutionStrategy method executeOnRemote.

//////////////// ExecutionStrategy interface Methods End /////////////////////
/**
   * Sends the user input (command string) via {@link OperationInvoker} to a remote GemFire node for
   * processing & execution.
   *
   * @param parseResult
   * 
   * @return result of execution/processing of the command
   * 
   * @throws IllegalStateException if gfsh doesn't have an active connection.
   */
private Result executeOnRemote(GfshParseResult parseResult) {
    Result commandResult = null;
    Object response = null;
    if (!shell.isConnectedAndReady()) {
        shell.logWarning("Can't execute a remote command without connection. Use 'connect' first to connect.", null);
        logWrapper.info("Can't execute a remote command \"" + parseResult.getUserInput() + "\" without connection. Use 'connect' first to connect to GemFire.");
        return null;
    }
    byte[][] fileData = null;
    CliAroundInterceptor interceptor = null;
    String interceptorClass = getInterceptor(parseResult.getMethod());
    // 1. Pre Remote Execution
    if (!CliMetaData.ANNOTATION_NULL_VALUE.equals(interceptorClass)) {
        try {
            interceptor = (CliAroundInterceptor) ClassPathLoader.getLatest().forName(interceptorClass).newInstance();
        } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
            shell.logWarning("Configuration error", e);
        }
        if (interceptor != null) {
            Result preExecResult = interceptor.preExecution(parseResult);
            if (Status.ERROR.equals(preExecResult.getStatus())) {
                return preExecResult;
            } else if (preExecResult instanceof FileResult) {
                FileResult fileResult = (FileResult) preExecResult;
                fileData = fileResult.toBytes();
            }
        } else {
            return ResultBuilder.createBadConfigurationErrorResult("Interceptor Configuration Error");
        }
    }
    // 2. Remote Execution
    final Map<String, String> env = shell.getEnv();
    try {
        response = shell.getOperationInvoker().processCommand(new CommandRequest(parseResult, env, fileData));
    } catch (NotAuthorizedException e) {
        return ResultBuilder.createGemFireUnAuthorizedErrorResult("Unauthorized. Reason : " + e.getMessage());
    } catch (Exception e) {
        shell.logSevere(e.getMessage(), e);
    } finally {
        env.clear();
    }
    if (response == null) {
        shell.logWarning("Response was null for: \"" + parseResult.getUserInput() + "\". (gfsh.isConnected=" + shell.isConnectedAndReady() + ")", null);
        return ResultBuilder.createBadResponseErrorResult(" Error occurred while " + "executing \"" + parseResult.getUserInput() + "\" on manager. " + "Please check manager logs for error.");
    }
    // it can also be a Path to a temp file downloaded from the rest http request
    if (response instanceof String) {
        CommandResponse commandResponse = CommandResponseBuilder.prepareCommandResponseFromJson((String) response);
        if (commandResponse.isFailedToPersist()) {
            shell.printAsSevere(CliStrings.SHARED_CONFIGURATION_FAILED_TO_PERSIST_COMMAND_CHANGES);
            logWrapper.severe(CliStrings.SHARED_CONFIGURATION_FAILED_TO_PERSIST_COMMAND_CHANGES);
        }
        String debugInfo = commandResponse.getDebugInfo();
        if (StringUtils.isNotBlank(debugInfo)) {
            // TODO - Abhishek When debug is ON, log response in gfsh logs
            // TODO - Abhishek handle \n better. Is it coming from GemFire formatter
            debugInfo = debugInfo.replaceAll("\n\n\n", "\n");
            debugInfo = debugInfo.replaceAll("\n\n", "\n");
            debugInfo = debugInfo.replaceAll("\n", "\n[From Manager : " + commandResponse.getSender() + "]");
            debugInfo = "[From Manager : " + commandResponse.getSender() + "]" + debugInfo;
            LogWrapper.getInstance().info(debugInfo);
        }
        commandResult = ResultBuilder.fromJson((String) response);
    }
    Path tempFile = null;
    if (response instanceof Path) {
        tempFile = (Path) response;
    }
    // 3. Post Remote Execution
    if (interceptor != null) {
        Result postExecResult = interceptor.postExecution(parseResult, commandResult, tempFile);
        if (postExecResult != null) {
            if (Status.ERROR.equals(postExecResult.getStatus())) {
                if (logWrapper.infoEnabled()) {
                    logWrapper.info("Post execution Result :: " + postExecResult);
                }
            } else if (logWrapper.fineEnabled()) {
                logWrapper.fine("Post execution Result :: " + postExecResult);
            }
            commandResult = postExecResult;
        }
    }
    return commandResult;
}
Also used : Path(java.nio.file.Path) CliAroundInterceptor(org.apache.geode.management.internal.cli.CliAroundInterceptor) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) CommandResponse(org.apache.geode.management.internal.cli.CommandResponse) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) CommandProcessingException(org.apache.geode.management.cli.CommandProcessingException) ParseResult(org.springframework.shell.event.ParseResult) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult) CommandRequest(org.apache.geode.management.internal.cli.CommandRequest) FileResult(org.apache.geode.management.internal.cli.result.FileResult)

Aggregations

GfshParseResult (org.apache.geode.management.internal.cli.GfshParseResult)4 Result (org.apache.geode.management.cli.Result)3 FileResult (org.apache.geode.management.internal.cli.result.FileResult)3 ParseResult (org.springframework.shell.event.ParseResult)3 Method (java.lang.reflect.Method)2 CommandProcessingException (org.apache.geode.management.cli.CommandProcessingException)2 CliAroundInterceptor (org.apache.geode.management.internal.cli.CliAroundInterceptor)2 CommandRequest (org.apache.geode.management.internal.cli.CommandRequest)2 NotAuthorizedException (org.apache.geode.security.NotAuthorizedException)2 Path (java.nio.file.Path)1 ManagementService (org.apache.geode.management.ManagementService)1 CommandResponse (org.apache.geode.management.internal.cli.CommandResponse)1 GfJsonException (org.apache.geode.management.internal.cli.json.GfJsonException)1 GfJsonObject (org.apache.geode.management.internal.cli.json.GfJsonObject)1 MultiStepCommand (org.apache.geode.management.internal.cli.multistep.MultiStepCommand)1