Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
   * as indicated by the @authors tag. All rights reserved.
   * See the copyright.txt in the distribution for a
   * full listing of individual contributors.
   *
   * This copyrighted material is made available to anyone wishing to use,
   * modify, copy, or redistribute it subject to the terms and conditions
  * of the GNU Lesser General Public License, v. 2.1.
  * This program is distributed in the hope that it will be useful, but WITHOUT A
  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
  * You should have received a copy of the GNU Lesser General Public License,
  * v.2.1 along with this distribution; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  * MA  02110-1301, USA.
  */
 package org.jboss.as.test.integration.domain.management.util;
 
 import java.io.File;
 import java.net.URI;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
Utility for controlling the lifecycle of a domain.

Author(s):
Kabir Khan
 
 public class DomainLifecycleUtil {
 
     public static final String SLAVE_HOST_USERNAME = "slave";
     public static final String SLAVE_HOST_PASSWORD = "slave_us3r_password";
 
     private static final ThreadFactory threadFactory = new AsyncThreadFactory();
 
     private final Logger log = Logger.getLogger(DomainLifecycleUtil.class.getName());
 
     // The ProcessController process wrapper
     private ProcessWrapper process;
     // The connection to the HC, which can be shared across multiple clients
     private DomainTestConnection connection;
     // A shared domain client
     private DomainTestClient domainClient;
 
 //    private Map<ServerIdentity, ControlledProcessState.State> serverStatuses = new HashMap<ServerIdentity, ControlledProcessState.State>();
     private ExecutorService executor;
 
     private final WildFlyManagedConfiguration configuration;
     private final PathAddress address;
     private final boolean closeClientConfig;
 
     public DomainLifecycleUtil(final WildFlyManagedConfiguration configurationthrows IOException {
         this(configuration, DomainControllerClientConfig.create(), true);
     }
 
     public DomainLifecycleUtil(final WildFlyManagedConfiguration configurationfinal DomainControllerClientConfig clientConfiguration) {
        this(configurationclientConfigurationfalse);
    }
    private DomainLifecycleUtil(final WildFlyManagedConfiguration configuration,
                                final DomainControllerClientConfig clientConfigurationfinal boolean closeClientConfig) {
        assert configuration != null : "configuration is null";
        assert clientConfiguration != null : "clientConfiguration is null";
        this. = configuration;
        this. = clientConfiguration;
        this. = PathAddress.pathAddress(PathElement.pathElement(.configuration.getHostName()));
        this. = closeClientConfig;
    }
        return ;
    }
    public PathAddress getAddress() {
        return ;
    }
    public void start() {
        try {
            .validate();
            final String address = NetworkUtils.formatPossibleIpv6Address(.getHostControllerManagementAddress());
            final int port = .getHostControllerManagementPort();
            final URI connectionURI = new URI(.getHostControllerManagementProtocol(), nulladdressportnullnullnull);
            // Create the connection - this will try to connect on the first request
            final DomainCommandBuilder commandBuilder;
            final String jbossHome = .getJbossHome();
            if (.getControllerJavaHome() == null) {
                commandBuilder = DomainCommandBuilder.of(jbossHome);
            } else {
                commandBuilder = DomainCommandBuilder.of(jbossHome.getControllerJavaHome());
            }
            final String jbossOptions = System.getProperty("jboss.options");
            if (jbossOptions != null) {
                final String[] javaOpts = jbossOptions.split("\\s+");
                commandBuilder.setHostControllerJavaOptions(javaOpts)
                        .setProcessControllerJavaOptions(javaOpts);
            }
            if (.getJavaVmArguments() != null) {
                final String[] javaOpts = .getJavaVmArguments().split("\\s+");
                commandBuilder.addHostControllerJavaOptions(javaOpts)
                        .addProcessControllerJavaOptions(javaOpts);
            }
            final String jbossArgs = System.getProperty("jboss.domain.server.args");
            if (jbossArgs != null) {
                commandBuilder.addServerArguments(jbossArgs.split("\\s+"));
            }
            // Set the Java Home for the servers
            if (.getJavaHome() != null) {
                commandBuilder.setServerJavaHome(.getJavaHome());
            }
            if (.getDomainDirectory() != null) {
                commandBuilder.setBaseDirectory(.getDomainDirectory());
            }
            if (.getModulePath() != null && !.getModulePath().isEmpty()) {
                commandBuilder.setModuleDirs(.getModulePath().split(Pattern.quote(.)));
            }
            final Path domainDir = commandBuilder.getBaseDirectory();
            final Path configDir = commandBuilder.getConfigurationDirectory();
            if (.getMgmtUsersFile() != null) {
                copyConfigFile(.getMgmtUsersFile(), configDirnull);
            } else {
                // No point backing up the file in a test scenario, just write what we need.
                final String text = "slave=" + new UsernamePasswordHashUtil().generateHashedHexURP("ManagementRealm".toCharArray());
                createFile(configDir.resolve("mgmt-users.properties"), text);
            }
            if (.getMgmtGroupsFile() != null) {
                copyConfigFile(.getMgmtGroupsFile(), configDirnull);
            } else {
                // Put out empty mgmt-groups.properties.
                createFile(configDir.resolve("mgmt-groups.properties"), "# Management groups");
            }
            // Put out empty application realm properties files so servers don't complain
            createFile(configDir.resolve("application-users.properties"), "# Application users");
            createFile(configDir.resolve("application-roles.properties"), "# Application roles");
            // Copy the logging.properties file
            copyConfigFile(Paths.get(jbossHome"domain""configuration""logging.properties"), configDirnull);
            final List<Stringipv6Args = new ArrayList<>();
            TestSuiteEnvironment.getIpv6Args(ipv6Args);
            commandBuilder.addHostControllerJavaOptions(ipv6Args)
                    .addProcessControllerJavaOptions(ipv6Args);
            if (.getHostCommandLineProperties() != null) {
                commandBuilder.addHostControllerJavaOptions(.getHostCommandLineProperties().split("\\s+"));
            }
            if (.isAdminOnly()) {
                commandBuilder.setAdminOnly();
            }
            if (.isBackupDC()) {
                commandBuilder.setBackup();
            }
            if (.isCachedDC()) {
                commandBuilder.setCachedDomainController();
            }
            if (.getDomainConfigFile() != null) {
                final String prefix = .isCachedDC() ? null : "testing-";
                final String name = copyConfigFile(.getDomainConfigFile(), configDirprefix);
                if (.isReadOnlyDomain()) {
                    commandBuilder.setReadOnlyDomainConfiguration(name);
                } else if (!.isCachedDC()) {
                    commandBuilder.setDomainConfiguration(name);
                }
            }
            if (.getHostConfigFile() != null) {
                final String name = copyConfigFile(.getHostConfigFile(), configDir);
                if (.isReadOnlyHost()) {
                    commandBuilder.setReadOnlyHostConfiguration(name);
                } else {
                    commandBuilder.setHostConfiguration(name);
                }
            }
            if (.getHostControllerManagementAddress() != null) {
                commandBuilder.setProcessControllerAddress(.getHostControllerManagementAddress());
            }
            // the process working dir
            final String workingDir = domainDir.toString();
            // Start the process
            final ProcessWrapper wrapper = new ProcessWrapper(.getHostName(), commandBuilder, Collections.<StringString>emptyMap(), workingDir);
            wrapper.start();
             = wrapper;
            long start = System.currentTimeMillis();
            if (!.isAdminOnly()) {
                // Wait a bit to let HC get going
                ..sleep(2);
                // Wait for the servers to be started
                awaitServers(start);
                .info("All servers started in " + (System.currentTimeMillis() - start) + " ms");
            }
            // Wait for the HC to be in running state. Normally if all servers are started, this is redundant
            // but there may not be any servers or we may be in --admin-only mode
            awaitHostController(start);
            .info("HostController started in " + (System.currentTimeMillis() - start) + " ms");
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Could not start container"e);
        }
    }
    public Future<VoidstartAsync() {
        Callable<Voidc = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                start();
                return null;
            }
        };
        return getExecutorService().submit(c);
    }
    public int getProcessExitCode() {
        return .getExitValue();
    }

    
Stop and wait for the process to exit.
    public synchronized void stop() {
        RuntimeException toThrow = null;
        try {
            if ( != null) {
                .stop();
                .waitFor();
                 = null;
            }
        } catch (Exception e) {
            toThrow = new RuntimeException("Could not stop container"e);
        } finally {
            closeConnection();
            final ExecutorService exec = ;
            if (exec != null) {
                exec.shutdownNow();
                 = null;
            }
            if () {
                try {
                    .close();
                } catch (Exception e) {
                    if (toThrow == null) {
                        toThrow = new RuntimeException("Could not stop client configuration"e);
                    }
                }
            }
        }
        if (toThrow != null) {
            throw toThrow;
        }
    }
    public Future<VoidstopAsync() {
        Callable<Voidc = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                stop();
                return null;
            }
        };
        return Executors.newSingleThreadExecutor().submit(c);
    }

    
Execute an operation and wait until the connection is closed. This is only useful for :reload and :shutdown operations.

Parameters:
operation the operation to execute
Returns:
the operation result
Throws:
java.io.IOException for any error
    public ModelNode executeAwaitConnectionClosed(final ModelNode operationthrows IOException {
        final DomainTestClient client = internalGetOrCreateClient();
        final Channel channel = client.getChannel();
        ifnull == channel )
            throw new IllegalStateException("Didn't get a remoting channel from the DomainTestClient.");
        final Connection ref = channel.getConnection();
        ModelNode result = new ModelNode();
        try {
            result = client.execute(operation);
            // IN case the operation wasn't successful, don't bother waiting
            if(! "success".equals(result.get("outcome").asString())) {
                return result;
            }
        } catch(Exception e) {
            if(e instanceof IOException) {
                final Throwable cause = e.getCause();
                if(cause instanceof ExecutionException) {
                    // ignore, this might happen if the channel gets closed before we got the response
                } else {
                    throw (IOExceptione;
                }
            } else {
                throw new RuntimeException(e);
            }
        }
        try {
            if(channel != null) {
                // Wait for the channel to close
                channel.awaitClosed();
            }
            // Wait for the connection to be closed
            .awaitConnectionClosed(ref);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return result;
    }

    
Try to connect to the host controller.

    public void connect() throws IOException {
        connect(30, .);
    }

    
Try to connect to the host controller.

Parameters:
timeout the timeout
timeUnit the timeUnit
    public void connect(final long timeoutfinal TimeUnit timeUnitthrows IOException {
        final DomainTestConnection connection = this.;
        if(connection == null) {
            throw new IllegalStateException();
        }
        final long deadline = System.currentTimeMillis() + timeUnit.toMillis(timeout);
        for(;;) {
            long remaining = deadline - System.currentTimeMillis();
            if(remaining <= 0) {
                return;
            }
            try {
                // Open a connection
                connection.connect();
                return;
            } catch (IOException e) {
                remaining = deadline - System.currentTimeMillis();
                if(remaining <= 0) {
                    throw e;
                }
            }
        }
    }

    
Create a new model controller client. The client can (and should) be closed without affecting other usages.

Returns:
the domain client
    public DomainClient createDomainClient() {
        final DomainTestConnection connection = this.;
        if(connection == null) {
            throw new IllegalStateException();
        }
        return DomainClient.Factory.create(connection.createClient());
    }

    
Get a shared domain client.

Returns:
the domain client
    public synchronized DomainClient getDomainClient() {
        return DomainClient.Factory.create(internalGetOrCreateClient());
    }

    
Wait for all auto-start servers for the host to reach org.jboss.as.controller.ControlledProcessState.State.RUNNING
    public void awaitServers(long startthrows InterruptedExceptionTimeoutException {
        boolean serversAvailable = false;
        long deadline = start + .getStartupTimeoutInSeconds() * 1000;
        while (!serversAvailable && getProcessExitCode() < 0) {
            long remaining = deadline - System.currentTimeMillis();
            if(remaining <= 0) {
                break;
            }
            ..sleep(250);
            serversAvailable = areServersStarted();
        }
        if (!serversAvailable) {
            throw new TimeoutException(String.format("Managed servers were not started within [%d] seconds".getStartupTimeoutInSeconds()));
        }
    }
    public void awaitHostController(long startthrows InterruptedExceptionTimeoutException {
        boolean hcAvailable = false;
        long deadline = start + .getStartupTimeoutInSeconds() * 1000;
        while (!hcAvailable && getProcessExitCode() < 0) {
            long remaining = deadline - System.currentTimeMillis();
            if(remaining <= 0) {
                break;
            }
            ..sleep(250);
            hcAvailable = isHostControllerStarted();
        }
        if (!hcAvailable) {
            throw new TimeoutException(String.format("HostController was not started within [%d] seconds".getStartupTimeoutInSeconds()));
        }
    }
    private synchronized DomainTestClient internalGetOrCreateClient() {
        // Perhaps get rid of the shared client...
        if ( == null) {
            try {
                 = .createClient();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return ;
    }
    private synchronized ExecutorService getExecutorService() {
        if ( == null) {
             = Executors.newSingleThreadExecutor();
        }
        return ;
    }
    public boolean areServersStarted() {
        try {
            Map<ServerIdentityControlledProcessState.Statestatuses = getServerStatuses();
            for (Map.Entry<ServerIdentityControlledProcessState.Stateentry : statuses.entrySet()) {
                switch (entry.getValue()) {
                    case :
                        continue;
                    default:
                        .log(.entry.getKey() + " status is " + entry.getValue());
                        return false;
                }
            }
//            serverStatuses.putAll(statuses);
            return true;
        } catch (Exception ignored) {
            // ignore, as we will get exceptions until the management comm services start
        }
        return false;
    }
    public boolean isHostControllerStarted() {
        try {
            ModelNode address = new ModelNode();
            address.add("host".getHostName());
            ControlledProcessState.State status = Enum.valueOf(ControlledProcessState.State.classreadAttribute("host-state"address).asString().toUpperCase(.));
            return status == ..;
        } catch (Exception ignored) {
            //
        }
        return false;
    }
    private synchronized void closeConnection() {
        if ( != null) {
            try {
                 = null;
                .close();
            } catch (Exception e) {
                .log(."Caught exception closing DomainTestConnection"e);
            }
        }
    }
        ModelNode op = new ModelNode();
        op.get("operation").set("read-children-names");
        op.get("child-type").set("server-config");
        op.get("address").add("host".getHostName());
        ModelNode opResult = executeForResult(new OperationBuilder(op).build());
        Set<Stringservers = new HashSet<String>();
        for (ModelNode server : opResult.asList()) {
            servers.add(server.asString());
        }
        for (String server : servers) {
            ModelNode address = new ModelNode();
            address.add("host".getHostName());
            address.add("server-config"server);
            String group = readAttribute("group"address).resolve().asString();
            if (!readAttribute("auto-start"address).resolve().asBoolean()) {
                continue;
            }
            // Make sure the server is started before trying to contact it
            final ServerIdentity id = new ServerIdentity(.getHostName(), groupserver);
            if (!readAttribute("status"address).asString().equals("STARTED")) {
                result.put(id..);
                continue;
            }
            address = new ModelNode();
            address.add("host".getHostName());
            address.add("server"server);
            ControlledProcessState.State status = Enum.valueOf(ControlledProcessState.State.classreadAttribute("server-state"address).asString().toUpperCase(.));
            result.put(idstatus);
        }
        return result;
    }
    private ModelNode readAttribute(String nameModelNode address) {
        ModelNode op = new ModelNode();
        op.get("operation").set("read-attribute");
        op.get("address").set(address);
        op.get("name").set(name);
        return executeForResult(new OperationBuilder(op).build());
    }
    public ModelNode executeForResult(ModelNode op) {
        return executeForResult(new OperationBuilder(op).build());
    }
    public ModelNode executeForResult(Operation op) {
        try {
            ModelNode result = getDomainClient().execute(op);
            if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
                return result.get("result");
            } else if (result.hasDefined("failure-description")) {
                throw new RuntimeException(result.get("failure-description").toString());
            } else if (result.hasDefined("domain-failure-description")) {
                throw new RuntimeException(result.get("domain-failure-description").toString());
            } else if (result.hasDefined("host-failure-descriptions")) {
                throw new RuntimeException(result.get("host-failure-descriptions").toString());
            } else {
                throw new RuntimeException("Operation outcome is " + result.get("outcome").asString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static final class AsyncThreadFactory implements ThreadFactory {
        private int threadCount;
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(rDomainLifecycleUtil.class.getSimpleName() + "-" + (++));
            t.setDaemon(true);
            return t;
        }
    }
    private static String copyConfigFile(final String filefinal String dir) {
        return copyConfigFile(filedir"testing-");
    }
    private static String copyConfigFile(final String filefinal Path dir) {
        return copyConfigFile(Paths.get(file), dir"testing-");
    }
    private static String copyConfigFile(final String filefinal String dirfinal String prefix) {
        return copyConfigFile(Paths.get(file), Paths.get(dir), prefix);
    }
    private static String copyConfigFile(final String filefinal Path dirfinal String prefix) {
        return copyConfigFile(Paths.get(file), dirprefix);
    }
    private static String copyConfigFile(final Path filefinal Path dirfinal String prefix) {
        final String p = prefix == null ? "" : prefix;
        final Path to = dir.resolve(p + file.getFileName());
        try {
            return Files.copy(fileto..).getFileName().toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private static void createFile(final Path filefinal String linethrows IOException {
        try (final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file.), true)) {
            pw.println(line);
        }
    }
New to GrepCode? Check out our FAQ X