Search in sources :

Example 1 with VisorIllegalStateException

use of org.apache.ignite.internal.visor.util.VisorIllegalStateException in project gridgain by gridgain.

the class CommandHandler method execute.

/**
 * Parse and execute command.
 *
 * @param rawArgs Arguments to parse and execute.
 * @return Exit code.
 */
public int execute(List<String> rawArgs) {
    LocalDateTime startTime = LocalDateTime.now();
    Thread.currentThread().setName("session=" + ses);
    logger.info("Control utility [ver. " + ACK_VER_STR + "]");
    logger.info(COPYRIGHT);
    logger.info("User: " + System.getProperty("user.name"));
    logger.info("Time: " + startTime.format(formatter));
    String commandName = "";
    Throwable err = null;
    boolean verbose = false;
    try {
        if (F.isEmpty(rawArgs) || (rawArgs.size() == 1 && CMD_HELP.equalsIgnoreCase(rawArgs.get(0)))) {
            printHelp();
            return EXIT_CODE_OK;
        }
        verbose = F.exist(rawArgs, CMD_VERBOSE::equalsIgnoreCase);
        ConnectionAndSslParameters args = parseAndValidate(rawArgs);
        Command command = args.command();
        commandName = command.name();
        GridClientConfiguration clientCfg = getClientConfiguration(args);
        int tryConnectMaxCount = 3;
        boolean suppliedAuth = !F.isEmpty(args.userName()) && !F.isEmpty(args.password());
        boolean credentialsRequested = false;
        while (true) {
            try {
                if (!args.autoConfirmation()) {
                    command.prepareConfirmation(clientCfg);
                    if (!confirm(command.confirmationPrompt())) {
                        logger.info("Operation cancelled.");
                        return EXIT_CODE_OK;
                    }
                }
                logger.info("Command [" + commandName + "] started");
                logger.info("Arguments: " + argumentsToString(rawArgs));
                logger.info(DELIM);
                lastOperationRes = command.execute(clientCfg, logger, args.verbose());
                break;
            } catch (Throwable e) {
                if (!isAuthError(e))
                    throw e;
                if (suppliedAuth)
                    throw new GridClientAuthenticationException("Wrong credentials.");
                if (tryConnectMaxCount == 0) {
                    throw new GridClientAuthenticationException("Maximum number of " + "retries exceeded");
                }
                logger.info(credentialsRequested ? "Authentication error, please try again." : "This cluster requires authentication.");
                if (credentialsRequested)
                    tryConnectMaxCount--;
                String user = retrieveUserName(args, clientCfg);
                String pwd = new String(requestPasswordFromConsole("password: "));
                clientCfg = getClientConfiguration(user, pwd, args);
                credentialsRequested = true;
            }
        }
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_OK);
        return EXIT_CODE_OK;
    } catch (IllegalArgumentException e) {
        logger.severe("Check arguments. " + errorMessage(e));
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_INVALID_ARGUMENTS);
        if (verbose)
            err = e;
        return EXIT_CODE_INVALID_ARGUMENTS;
    } catch (Throwable e) {
        if (isAuthError(e)) {
            logger.severe("Authentication error. " + errorMessage(e));
            logger.info("Command [" + commandName + "] finished with code: " + ERR_AUTHENTICATION_FAILED);
            if (verbose)
                err = e;
            return ERR_AUTHENTICATION_FAILED;
        }
        if (isConnectionError(e)) {
            IgniteCheckedException cause = X.cause(e, IgniteCheckedException.class);
            if (isConnectionClosedSilentlyException(e))
                logger.severe("Connection to cluster failed. Please check firewall settings and " + "client and server are using the same SSL configuration.");
            else {
                if (isSSLMisconfigurationError(cause))
                    e = cause;
                logger.severe("Connection to cluster failed. " + errorMessage(e));
            }
            logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_CONNECTION_FAILED);
            if (verbose)
                err = e;
            return EXIT_CODE_CONNECTION_FAILED;
        }
        if (X.hasCause(e, VisorIllegalStateException.class)) {
            VisorIllegalStateException vise = X.cause(e, VisorIllegalStateException.class);
            logger.severe(errorMessage(vise));
            logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_ILLEGAL_STATE_ERROR);
            if (verbose)
                err = e;
            return EXIT_CODE_ILLEGAL_STATE_ERROR;
        }
        logger.severe(errorMessage(e));
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_UNEXPECTED_ERROR);
        err = e;
        return EXIT_CODE_UNEXPECTED_ERROR;
    } finally {
        LocalDateTime endTime = LocalDateTime.now();
        Duration diff = Duration.between(startTime, endTime);
        if (nonNull(err))
            logger.info("Error stack trace:" + System.lineSeparator() + X.getFullStackTrace(err));
        logger.info("Control utility has completed execution at: " + endTime.format(formatter));
        logger.info("Execution time: " + diff.toMillis() + " ms");
        Arrays.stream(logger.getHandlers()).filter(handler -> handler instanceof FileHandler).forEach(Handler::close);
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) Arrays(java.util.Arrays) COPYRIGHT(org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) INDENT(org.apache.ignite.internal.commandline.CommandLogger.INDENT) Scanner(java.util.Scanner) CMD_VERBOSE(org.apache.ignite.internal.commandline.CommonArgParser.CMD_VERBOSE) Formatter(java.util.logging.Formatter) DFLT_CONNECT_TIMEOUT(org.apache.ignite.internal.client.GridClientConfiguration.DFLT_CONNECT_TIMEOUT) GridClientHandshakeException(org.apache.ignite.internal.client.GridClientHandshakeException) FileHandler(java.util.logging.FileHandler) SecurityCredentialsProvider(org.apache.ignite.plugin.security.SecurityCredentialsProvider) SB(org.apache.ignite.internal.util.typedef.internal.SB) SecurityCredentials(org.apache.ignite.plugin.security.SecurityCredentials) Duration(java.time.Duration) X(org.apache.ignite.internal.util.typedef.X) SslContextFactory(org.apache.ignite.ssl.SslContextFactory) DFLT_HOST(org.apache.ignite.internal.commandline.TaskExecutor.DFLT_HOST) DFLT_PORT(org.apache.ignite.internal.commandline.TaskExecutor.DFLT_PORT) CommandLogger.optional(org.apache.ignite.internal.commandline.CommandLogger.optional) CMD_AUTO_CONFIRMATION(org.apache.ignite.internal.commandline.CommonArgParser.CMD_AUTO_CONFIRMATION) ACK_VER_STR(org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) JavaLoggerFormatter(org.apache.ignite.logger.java.JavaLoggerFormatter) GridClientConnectionResetException(org.apache.ignite.internal.client.impl.connection.GridClientConnectionResetException) UUID(java.util.UUID) LogRecord(java.util.logging.LogRecord) Logger(java.util.logging.Logger) GridSslBasicContextFactory(org.apache.ignite.internal.client.ssl.GridSslBasicContextFactory) Collectors(java.util.stream.Collectors) CommonArgParser.getCommonOptions(org.apache.ignite.internal.commandline.CommonArgParser.getCommonOptions) GridClientDisconnectedException(org.apache.ignite.internal.client.GridClientDisconnectedException) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Handler(java.util.logging.Handler) NotNull(org.jetbrains.annotations.NotNull) Objects.nonNull(java.util.Objects.nonNull) SecurityCredentialsBasicProvider(org.apache.ignite.plugin.security.SecurityCredentialsBasicProvider) System.lineSeparator(java.lang.System.lineSeparator) LocalDateTime(java.time.LocalDateTime) U(org.apache.ignite.internal.util.typedef.internal.U) DOUBLE_INDENT(org.apache.ignite.internal.commandline.CommandLogger.DOUBLE_INDENT) GridServerUnreachableException(org.apache.ignite.internal.client.GridServerUnreachableException) Level(java.util.logging.Level) DFLT_SSL_PROTOCOL(org.apache.ignite.ssl.SslContextFactory.DFLT_SSL_PROTOCOL) GridClientAuthenticationException(org.apache.ignite.internal.client.GridClientAuthenticationException) StreamHandler(java.util.logging.StreamHandler) GridClientClosedException(org.apache.ignite.internal.client.GridClientClosedException) F(org.apache.ignite.internal.util.typedef.F) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) GridClientConfiguration(org.apache.ignite.internal.client.GridClientConfiguration) File(java.io.File) CommandLogger.errorMessage(org.apache.ignite.internal.commandline.CommandLogger.errorMessage) DateTimeFormatter(java.time.format.DateTimeFormatter) Collections(java.util.Collections) FileHandler(java.util.logging.FileHandler) Handler(java.util.logging.Handler) StreamHandler(java.util.logging.StreamHandler) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) Duration(java.time.Duration) FileHandler(java.util.logging.FileHandler) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) GridClientAuthenticationException(org.apache.ignite.internal.client.GridClientAuthenticationException) GridClientConfiguration(org.apache.ignite.internal.client.GridClientConfiguration)

Example 2 with VisorIllegalStateException

use of org.apache.ignite.internal.visor.util.VisorIllegalStateException in project gridgain by gridgain.

the class GridClientNioTcpConnection method handleClientResponse.

/**
 * Handler responses addressed to this client.
 *
 * @param fut Response future.
 * @param resp Response.
 */
@SuppressWarnings("unchecked")
private void handleClientResponse(TcpClientFuture fut, GridClientResponse resp) {
    if (resp.sessionToken() != null)
        sesTok = resp.sessionToken();
    GridClientMessage src = fut.pendingMessage();
    switch(fut.retryState()) {
        case TcpClientFuture.STATE_INITIAL:
            {
                if (resp.successStatus() == GridClientResponse.STATUS_AUTH_FAILURE) {
                    if (credentials() == null) {
                        fut.onDone(new GridClientAuthenticationException("Authentication failed on server " + "(client has no credentials) [clientId=" + clientId + ", srvAddr=" + serverAddress() + ", errMsg=" + resp.errorMessage() + ']'));
                        removePending(resp.requestId());
                        return;
                    }
                    fut.retryState(TcpClientFuture.STATE_AUTH_RETRY);
                    GridClientAuthenticationRequest req = buildAuthRequest();
                    req.requestId(resp.requestId());
                    ses.send(req);
                    return;
                }
                break;
            }
        case TcpClientFuture.STATE_AUTH_RETRY:
            {
                if (resp.successStatus() == GridClientResponse.STATUS_SUCCESS) {
                    fut.retryState(TcpClientFuture.STATE_REQUEST_RETRY);
                    src.sessionToken(sesTok);
                    ses.send(src);
                    return;
                }
                break;
            }
    }
    removePending(resp.requestId());
    if (resp.successStatus() == GridClientResponse.STATUS_AUTH_FAILURE)
        fut.onDone(new GridClientAuthenticationException("Client authentication failed [clientId=" + clientId + ", srvAddr=" + serverAddress() + ", errMsg=" + resp.errorMessage() + ']'));
    else if (resp.successStatus() == GridClientResponse.STATUS_ILLEGAL_STATE)
        fut.onDone(new VisorIllegalStateException(resp.errorMessage()));
    else if (resp.errorMessage() != null)
        fut.onDone(new GridClientException(resp.errorMessage()));
    else
        fut.onDone(resp.result());
}
Also used : GridClientException(org.apache.ignite.internal.client.GridClientException) GridClientAuthenticationRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientAuthenticationRequest) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) GridClientAuthenticationException(org.apache.ignite.internal.client.GridClientAuthenticationException) GridClientMessage(org.apache.ignite.internal.processors.rest.client.message.GridClientMessage)

Example 3 with VisorIllegalStateException

use of org.apache.ignite.internal.visor.util.VisorIllegalStateException in project gridgain by gridgain.

the class PartitionReconciliation method partitionReconciliationCheck.

/**
 * Prepares arguments, executes partition reconciliation task, prints logs and optionally fix inconsistency.
 *
 * @param client Client node to run initial task.
 * @param clientCfg Client configuration.
 * @param log Logger.
 * @return Result of operation.
 * @throws GridClientException If failed.
 */
private ReconciliationResult partitionReconciliationCheck(GridClient client, GridClientConfiguration clientCfg, Logger log) throws GridClientException {
    VisorPartitionReconciliationTaskArg taskArg = new VisorPartitionReconciliationTaskArg(args.caches, args.fastCheck, args.repair, args.includeSensitive, args.locOutput, args.parallelism, args.batchSize, args.recheckAttempts, args.repairAlg, args.recheckDelay);
    List<GridClientNode> unsupportedSrvNodes = client.compute().nodes().stream().filter(node -> !node.isClient()).filter(node -> !node.supports(IgniteFeatures.PARTITION_RECONCILIATION)).collect(Collectors.toList());
    if (!unsupportedSrvNodes.isEmpty()) {
        final String strErrReason = "Partition reconciliation was rejected. The node [id=%s, consistentId=%s] doesn't support this feature.";
        List<String> errs = unsupportedSrvNodes.stream().map(n -> String.format(strErrReason, n.nodeId(), n.consistentId())).collect(toList());
        print(new ReconciliationResult(new ReconciliationAffectedEntries(), new HashMap<>(), errs), log::info);
        throw new VisorIllegalStateException("There are server nodes not supported partition reconciliation.");
    } else {
        ReconciliationResult res = executeTask(client, VisorPartitionReconciliationTask.class, taskArg, clientCfg);
        print(res, log::info);
        return res;
    }
}
Also used : GridClientNode(org.apache.ignite.internal.client.GridClientNode) VisorPartitionReconciliationTaskArg(org.apache.ignite.internal.visor.checker.VisorPartitionReconciliationTaskArg) Arrays(java.util.Arrays) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) PartitionReconciliationCommandArg(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg) CommandLogger(org.apache.ignite.internal.commandline.CommandLogger) HashMap(java.util.HashMap) CommandArgIterator(org.apache.ignite.internal.commandline.CommandArgIterator) IgniteFeatures(org.apache.ignite.internal.IgniteFeatures) CommandArgUtils(org.apache.ignite.internal.commandline.argument.CommandArgUtils) RECHECK_ATTEMPTS(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.RECHECK_ATTEMPTS) ReconciliationResult(org.apache.ignite.internal.processors.cache.checker.objects.ReconciliationResult) SB(org.apache.ignite.internal.util.typedef.internal.SB) LOCAL_OUTPUT(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.LOCAL_OUTPUT) Map(java.util.Map) RepairAlgorithm(org.apache.ignite.internal.processors.cache.verify.RepairAlgorithm) INCLUDE_SENSITIVE(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.INCLUDE_SENSITIVE) GridClientNode(org.apache.ignite.internal.client.GridClientNode) CommandLogger.optional(org.apache.ignite.internal.commandline.CommandLogger.optional) FAST_CHECK(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.FAST_CHECK) PatternSyntaxException(java.util.regex.PatternSyntaxException) GridClient(org.apache.ignite.internal.client.GridClient) GridClientConfiguration(org.apache.ignite.internal.client.GridClientConfiguration) VisorPartitionReconciliationTask(org.apache.ignite.internal.visor.checker.VisorPartitionReconciliationTask) IgniteException(org.apache.ignite.IgniteException) PARTITION_RECONCILIATION(org.apache.ignite.internal.commandline.cache.CacheSubcommands.PARTITION_RECONCILIATION) Set(java.util.Set) RECHECK_DELAY(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.RECHECK_DELAY) UUID(java.util.UUID) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Consumer(java.util.function.Consumer) List(java.util.List) Command(org.apache.ignite.internal.commandline.Command) Collectors.toList(java.util.stream.Collectors.toList) CacheCommands.usageCache(org.apache.ignite.internal.commandline.cache.CacheCommands.usageCache) PARALLELISM(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.PARALLELISM) TaskExecutor.executeTask(org.apache.ignite.internal.commandline.TaskExecutor.executeTask) GridClientException(org.apache.ignite.internal.client.GridClientException) ReconciliationAffectedEntries(org.apache.ignite.internal.processors.cache.checker.objects.ReconciliationAffectedEntries) AbstractCommand(org.apache.ignite.internal.commandline.AbstractCommand) Pattern(java.util.regex.Pattern) REPAIR(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.REPAIR) BATCH_SIZE(org.apache.ignite.internal.commandline.cache.argument.PartitionReconciliationCommandArg.BATCH_SIZE) HashMap(java.util.HashMap) ReconciliationResult(org.apache.ignite.internal.processors.cache.checker.objects.ReconciliationResult) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) VisorPartitionReconciliationTaskArg(org.apache.ignite.internal.visor.checker.VisorPartitionReconciliationTaskArg) ReconciliationAffectedEntries(org.apache.ignite.internal.processors.cache.checker.objects.ReconciliationAffectedEntries)

Example 4 with VisorIllegalStateException

use of org.apache.ignite.internal.visor.util.VisorIllegalStateException in project gridgain by gridgain.

the class GridRestProcessor method handle.

/**
 * Executes particular command from a {@link GridRestRequest}
 */
public IgniteInternalFuture<GridRestResponse> handle(final GridRestRequest req, boolean securityIsActive) {
    interceptRequest(req);
    GridRestCommandHandler hnd = handlers.get(req.command());
    IgniteInternalFuture<GridRestResponse> res = hnd == null ? null : hnd.handleAsync(req);
    if (res == null)
        return new GridFinishedFuture<>(new IgniteCheckedException("Failed to find registered handler for command: " + req.command()));
    return res.chain(new C1<IgniteInternalFuture<GridRestResponse>, GridRestResponse>() {

        @Override
        public GridRestResponse apply(IgniteInternalFuture<GridRestResponse> f) {
            GridRestResponse res;
            boolean failed = false;
            try {
                res = f.get();
            } catch (Exception e) {
                failed = true;
                if (X.hasCause(e, VisorIllegalStateException.class)) {
                    VisorIllegalStateException iae = X.cause(e, VisorIllegalStateException.class);
                    res = new GridRestResponse(STATUS_ILLEGAL_STATE, iae.getMessage());
                } else {
                    if (!X.hasCause(e, VisorClusterGroupEmptyException.class))
                        LT.error(log, e, "Failed to handle request: " + req.command());
                    if (log.isDebugEnabled())
                        log.debug("Failed to handle request [req=" + req + ", e=" + e + "]");
                    // Prepare error message:
                    SB sb = new SB(256);
                    sb.a("Failed to handle request: [req=").a(req.command());
                    if (req instanceof GridRestTaskRequest) {
                        GridRestTaskRequest tskReq = (GridRestTaskRequest) req;
                        sb.a(", taskName=").a(tskReq.taskName()).a(", params=").a(tskReq.params());
                    }
                    sb.a(", err=").a(e.getMessage() != null ? e.getMessage() : e.getClass().getName()).a(", trace=").a(getErrorMessage(e)).a(']');
                    res = new GridRestResponse(STATUS_FAILED, sb.toString());
                }
            }
            assert res != null;
            if (securityIsActive && !failed)
                res.sessionTokenBytes(req.sessionToken());
            interceptResponse(res, req);
            return res;
        }
    });
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException) IgniteAuthenticationException(org.apache.ignite.IgniteAuthenticationException) SecurityException(org.apache.ignite.plugin.security.SecurityException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) VisorClusterGroupEmptyException(org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException) SB(org.apache.ignite.internal.util.typedef.internal.SB) GridRestCommandHandler(org.apache.ignite.internal.processors.rest.handlers.GridRestCommandHandler) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) VisorClusterGroupEmptyException(org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException) VisorIllegalStateException(org.apache.ignite.internal.visor.util.VisorIllegalStateException)

Aggregations

VisorIllegalStateException (org.apache.ignite.internal.visor.util.VisorIllegalStateException)4 Arrays (java.util.Arrays)2 List (java.util.List)2 UUID (java.util.UUID)2 Logger (java.util.logging.Logger)2 Collectors (java.util.stream.Collectors)2 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 GridClientAuthenticationException (org.apache.ignite.internal.client.GridClientAuthenticationException)2 GridClientConfiguration (org.apache.ignite.internal.client.GridClientConfiguration)2 GridClientException (org.apache.ignite.internal.client.GridClientException)2 CommandLogger.optional (org.apache.ignite.internal.commandline.CommandLogger.optional)2 SB (org.apache.ignite.internal.util.typedef.internal.SB)2 File (java.io.File)1 String.format (java.lang.String.format)1 System.lineSeparator (java.lang.System.lineSeparator)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Duration (java.time.Duration)1 LocalDateTime (java.time.LocalDateTime)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 Collections (java.util.Collections)1