Search in sources :

Example 81 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine in project wildfly-core by wildfly.

the class UnsetVariableHandler method recognizeArguments.

@Override
protected void recognizeArguments(CommandContext ctx) throws CommandFormatException {
    final ParsedCommandLine args = ctx.getParsedCommandLine();
    final Set<String> propertyNames = args.getPropertyNames();
    if (!propertyNames.isEmpty()) {
        final Collection<String> names;
        if (helpArg.isPresent(args)) {
            if (propertyNames.size() == 1) {
                return;
            }
            names = new ArrayList<String>(propertyNames);
            names.remove(helpArg.getFullName());
            names.remove(helpArg.getShortName());
        } else {
            names = propertyNames;
        }
        throw new CommandFormatException("Unrecognized argument names: " + names);
    }
}
Also used : CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine)

Example 82 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine in project wildfly-core by wildfly.

the class BatchHoldbackHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandFormatException {
    BatchManager batchManager = ctx.getBatchManager();
    if (!batchManager.isBatchActive()) {
        throw new CommandFormatException("No active batch to holdback.");
    }
    String name = null;
    ParsedCommandLine args = ctx.getParsedCommandLine();
    if (args.hasProperties()) {
        name = args.getOtherProperties().get(0);
    }
    if (batchManager.isHeldback(name)) {
        throw new CommandFormatException("There already is " + (name == null ? "unnamed" : "'" + name + "'") + " batch held back.");
    }
    if (!batchManager.holdbackActiveBatch(name)) {
        throw new CommandFormatException("Failed to holdback the batch.");
    }
}
Also used : CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) BatchManager(org.jboss.as.cli.batch.BatchManager)

Example 83 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine in project wildfly-core by wildfly.

the class IfHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    String argsStr = ctx.getArgumentsString();
    if (argsStr == null) {
        throw new CommandFormatException("The command is missing arguments.");
    }
    final BatchManager batchManager = ctx.getBatchManager();
    if (batchManager.isBatchActive()) {
        throw new CommandFormatException("if is not allowed while in batch mode.");
    }
    final ParsedCommandLine args = ctx.getParsedCommandLine();
    final String conditionStr = this.condition.getOriginalValue(args, true);
    int i = argsStr.indexOf(conditionStr);
    if (i < 0) {
        throw new CommandFormatException("Failed to locate '" + conditionStr + "' in '" + argsStr + "'");
    }
    i = argsStr.indexOf("of", i + conditionStr.length());
    if (i < 0) {
        throw new CommandFormatException("Failed to locate 'of' in '" + argsStr + "'");
    }
    final String requestStr = argsStr.substring(i + 2);
    ctx.registerRedirection(new IfElseControlFlow(ctx, condition.resolveOperation(args), requestStr));
}
Also used : CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) BatchManager(org.jboss.as.cli.batch.BatchManager)

Example 84 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine in project wildfly-core by wildfly.

the class EmbedHostControllerHandler method doHandle.

@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine();
    final File jbossHome = getJBossHome(parsedCmd);
    // set up the expected properties, default to JBOSS_HOME/standalone
    final String baseDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_BASE_DIR, jbossHome + File.separator + "domain");
    String domainXml = domainConfig.getValue(parsedCmd);
    if (domainXml == null) {
        domainXml = dashC.getValue(parsedCmd);
    }
    if ((domainConfig.isPresent(parsedCmd) || dashC.isPresent(parsedCmd)) && (domainXml == null || domainXml.isEmpty())) {
        throw new CommandFormatException("The --domain-config (or -c) parameter requires a value.");
    }
    String hostXml = hostConfig.getValue(parsedCmd);
    if (hostConfig.isPresent(parsedCmd) && (hostXml == null || hostXml.isEmpty())) {
        throw new CommandFormatException("The --host-config parameter requires a value.");
    }
    Long bootTimeout = null;
    String timeoutString = timeout.getValue(parsedCmd);
    if (timeout.isPresent(parsedCmd) && (timeoutString == null || timeoutString.isEmpty())) {
        throw new CommandFormatException("The --timeout parameter requires a value.");
    }
    if (timeoutString != null) {
        bootTimeout = TimeUnit.SECONDS.toNanos(Long.parseLong(timeoutString));
    }
    String stdOutString = stdOutHandling.getValue(parsedCmd);
    if (stdOutHandling.isPresent(parsedCmd)) {
        if (stdOutString == null || stdOutString.isEmpty()) {
            throw new CommandFormatException("The --std-out parameter requires a value { echo, discard }.");
        }
        if (!(stdOutString.equals(ECHO) || stdOutString.equals(DISCARD_STDOUT))) {
            throw new CommandFormatException("The --std-out parameter should be one of { echo, discard }.");
        }
    }
    final List<String> args = parsedCmd.getOtherProperties();
    if (!args.isEmpty()) {
        throw new CommandFormatException("The command accepts 0 unnamed argument(s) but received: " + args);
    }
    final EnvironmentRestorer restorer = new EnvironmentRestorer(JBOSS_DOMAIN_LOG_DIR);
    boolean ok = false;
    ThreadLocalContextSelector contextSelector = null;
    try {
        Contexts defaultContexts = restorer.getDefaultContexts();
        StdioContext discardStdoutContext = null;
        if (!ECHO.equalsIgnoreCase(stdOutHandling.getValue(parsedCmd))) {
            PrintStream nullStream = new UncloseablePrintStream(NullOutputStream.getInstance());
            StdioContext currentContext = defaultContexts.getStdioContext();
            discardStdoutContext = StdioContext.create(currentContext.getIn(), nullStream, currentContext.getErr());
        }
        // Configure and get the log context
        String controllerLogDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_LOG_DIR, null);
        if (controllerLogDir == null) {
            controllerLogDir = baseDir + File.separator + "log";
            WildFlySecurityManager.setPropertyPrivileged(JBOSS_DOMAIN_LOG_DIR, controllerLogDir);
        }
        final String controllerCfgDir = WildFlySecurityManager.getPropertyPrivileged(JBOSS_DOMAIN_CONFIG_DIR, baseDir + File.separator + "configuration");
        final LogContext embeddedLogContext = EmbeddedLogContext.configureLogContext(new File(controllerLogDir), new File(controllerCfgDir), "host-controller.log", ctx);
        Contexts localContexts = new Contexts(embeddedLogContext, discardStdoutContext);
        contextSelector = new ThreadLocalContextSelector(localContexts, defaultContexts);
        contextSelector.pushLocal();
        StdioContext.setStdioContextSelector(contextSelector);
        LogContext.setLogContextSelector(contextSelector);
        List<String> cmdsList = new ArrayList<>();
        if (domainXml != null && domainXml.trim().length() > 0) {
            cmdsList.add(DOMAIN_CONFIG);
            cmdsList.add(domainXml.trim());
        }
        if (hostXml != null && hostXml.trim().length() > 0) {
            cmdsList.add(HOST_CONFIG);
            cmdsList.add(hostXml.trim());
        }
        boolean emptyDomain = emptyDomainConfig.isPresent(parsedCmd);
        boolean removeDomain = removeExistingDomainConfig.isPresent(parsedCmd);
        if (emptyDomain) {
            cmdsList.add(EMPTY_DOMAIN_CONFIG);
        }
        if (removeDomain) {
            cmdsList.add(REMOVE_EXISTING_DOMAIN_CONFIG);
        }
        File domainXmlCfgFile = new File(controllerCfgDir + File.separator + (domainConfig.isPresent(parsedCmd) ? domainXml : "domain.xml"));
        if (emptyDomain && !removeDomain && domainXmlCfgFile.exists() && domainXmlCfgFile.length() != 0) {
            throw new CommandFormatException("The specified domain configuration file already exists and has size > 0 and may not be overwritten unless --remove-existing-domain-config is also specified.");
        }
        boolean emptyHost = emptyHostConfig.isPresent(parsedCmd);
        boolean removeHost = removeExistingHostConfig.isPresent(parsedCmd);
        if (emptyHost) {
            cmdsList.add(EMPTY_HOST_CONFIG);
        }
        if (removeHost) {
            cmdsList.add(REMOVE_EXISTING_HOST_CONFIG);
        }
        File hostXmlCfgFile = new File(controllerCfgDir + File.separator + (hostConfig.isPresent(parsedCmd) ? hostXml : "host.xml"));
        if (emptyHost && !removeHost && hostXmlCfgFile.exists() && hostXmlCfgFile.length() != 0) {
            throw new CommandFormatException("The specified host configuration file already exists and has size > 0 and may not be overwritten unless --remove-existing-host-config is also specified.");
        }
        String[] cmds = cmdsList.toArray(new String[cmdsList.size()]);
        final Configuration.Builder configBuilder;
        if (this.jbossHome == null) {
            // Modular environment, note that the jbossHome here is resolved from the JBOSS_HOME environment
            // variable and should never be null according to the getJBossHome() method.
            configBuilder = Configuration.Builder.of(jbossHome).setModuleLoader(ModuleLoader.forClass(getClass())).setCommandArguments(cmds);
        } else {
            configBuilder = Configuration.Builder.of(jbossHome.getAbsoluteFile()).addSystemPackages(EmbeddedControllerHandlerRegistrar.EXTENDED_SYSTEM_PKGS).setCommandArguments(cmds);
        }
        // Disables the logging subsystem from registering an embedded log context if the subsystem is present
        WildFlySecurityManager.setPropertyPrivileged("org.wildfly.logging.embedded", "false");
        final EmbeddedManagedProcess hostController = EmbeddedProcessFactory.createHostController(configBuilder.build());
        hostController.start();
        hostControllerReference.set(new EmbeddedProcessLaunch(hostController, restorer, true));
        ModelControllerClient mcc = new ThreadContextsModelControllerClient(hostController.getModelControllerClient(), contextSelector);
        if (hostController.canQueryProcessState()) {
            // the process state and wait for it even if we are on EMPTY_HOST_CONFIG scenario.
            if (bootTimeout == null || bootTimeout > 0) {
                long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
                String status;
                do {
                    status = hostController.getProcessState();
                    if (status == null || "starting".equals(status)) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new CommandLineException("Interrupted while waiting for embedded server to start");
                        }
                    } else {
                        break;
                    }
                } while (System.nanoTime() < expired);
                if (status == null || "starting".equals(status)) {
                    // we'll assume the loop didn't run for decades
                    assert bootTimeout != null;
                    // Stop server and restore environment
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                    throw new CommandLineException("Embedded host controller did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
                }
            }
        } else {
            // See https://issues.redhat.com/browse/WFLY-13276 for some context.
            if (!emptyHost && (bootTimeout == null || bootTimeout > 0)) {
                long expired = bootTimeout == null ? Long.MAX_VALUE : System.nanoTime() + bootTimeout;
                String status = "starting";
                // read out the host controller name
                final ModelNode getNameOp = new ModelNode();
                getNameOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
                getNameOp.get(ClientConstants.NAME).set(Util.LOCAL_HOST_NAME);
                final ModelNode getStateOp = new ModelNode();
                getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
                ModelNode address = getStateOp.get(ClientConstants.ADDRESS);
                getStateOp.get(ClientConstants.NAME).set(ClientConstants.HOST_STATE);
                do {
                    try {
                        final ModelNode nameResponse = mcc.execute(getNameOp);
                        if (Util.isSuccess(nameResponse)) {
                            // read out the connected HC name
                            final String localName = nameResponse.get(ClientConstants.RESULT).asString();
                            address.set(ClientConstants.HOST, localName);
                            final ModelNode stateResponse = mcc.execute(getStateOp);
                            if (Util.isSuccess(stateResponse)) {
                                status = stateResponse.get(ClientConstants.RESULT).asString();
                            }
                        }
                    } catch (Exception e) {
                    // ignore and try again
                    }
                    if ("starting".equals(status)) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw new CommandLineException("Interrupted while waiting for embedded server to start");
                        }
                    } else {
                        break;
                    }
                } while (System.nanoTime() < expired);
                if ("starting".equals(status)) {
                    // we'll assume the loop didn't run for decades
                    assert bootTimeout != null;
                    // Stop server and restore environment
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                    throw new CommandLineException("Embedded host controller did not exit 'starting' status within " + TimeUnit.NANOSECONDS.toSeconds(bootTimeout) + " seconds");
                }
            }
        }
        // Expose the client to the rest of the CLI last so nothing can be done with
        // it until we're ready
        ctx.bindClient(mcc);
        // Stop the server on any disconnect event
        ctx.addEventListener(new CliEventListener() {

            @Override
            public void cliEvent(CliEvent event, CommandContext ctx) {
                if (event == CliEvent.DISCONNECTED) {
                    StopEmbeddedHostControllerHandler.cleanup(hostControllerReference);
                }
            }
        });
        ok = true;
    } catch (RuntimeException | EmbeddedProcessStartException e) {
        throw new CommandLineException("Cannot start embedded Host Controller", e);
    } finally {
        if (!ok) {
            ctx.disconnectController();
            restorer.restoreEnvironment();
        } else if (contextSelector != null) {
            contextSelector.restore(null);
        }
    }
}
Also used : EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) Configuration(org.wildfly.core.embedded.Configuration) CommandContext(org.jboss.as.cli.CommandContext) CliEventListener(org.jboss.as.cli.CliEventListener) ArrayList(java.util.ArrayList) EmbeddedManagedProcess(org.wildfly.core.embedded.EmbeddedManagedProcess) StdioContext(org.jboss.stdio.StdioContext) CommandLineException(org.jboss.as.cli.CommandLineException) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) PrintStream(java.io.PrintStream) LogContext(org.jboss.logmanager.LogContext) EmbeddedProcessStartException(org.wildfly.core.embedded.EmbeddedProcessStartException) CommandLineException(org.jboss.as.cli.CommandLineException) CommandFormatException(org.jboss.as.cli.CommandFormatException) CommandFormatException(org.jboss.as.cli.CommandFormatException) ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) CliEvent(org.jboss.as.cli.CliEvent) ModelNode(org.jboss.dmr.ModelNode) File(java.io.File)

Example 85 with ParsedCommandLine

use of org.jboss.as.cli.operation.ParsedCommandLine in project wildfly-core by wildfly.

the class VariablesTestCase method testListArgumentValue.

@Test
public void testListArgumentValue() throws Exception {
    final ParsedCommandLine parsed = parse(":op(name=[$" + OP_PROP_VAR_NAME + "])");
    assertEquals("op", parsed.getOperationName());
    assertEquals("[" + OP_PROP_VAR_VALUE + "]", parsed.getPropertyValue("name"));
}
Also used : ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) Test(org.junit.Test)

Aggregations

ParsedCommandLine (org.jboss.as.cli.operation.ParsedCommandLine)95 Test (org.junit.Test)42 CommandFormatException (org.jboss.as.cli.CommandFormatException)38 ModelNode (org.jboss.dmr.ModelNode)26 CommandLineException (org.jboss.as.cli.CommandLineException)14 OperationRequestAddress (org.jboss.as.cli.operation.OperationRequestAddress)14 File (java.io.File)12 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)9 DefaultOperationRequestAddress (org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress)8 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)8 CommandArgument (org.jboss.as.cli.CommandArgument)4 CommandContext (org.jboss.as.cli.CommandContext)4 OperationFormatException (org.jboss.as.cli.operation.OperationFormatException)4 ZipException (java.util.zip.ZipException)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 CommandException (org.aesh.command.CommandException)3 BatchManager (org.jboss.as.cli.batch.BatchManager)3 CommandLineParser (org.jboss.as.cli.operation.CommandLineParser)3 DefaultCallbackHandler (org.jboss.as.cli.operation.impl.DefaultCallbackHandler)3