Search in sources :

Example 1 with RemoteServer

use of org.apache.openejb.config.RemoteServer in project tomee by apache.

the class FullRestartContainer method deploy.

@Override
public boolean deploy(final InputStream archive, final String name) throws IOException {
    if (name.endsWith("war")) {
        currentFile = new File(WEBAPP_DIR, name);
    } else {
        currentFile = new File(APPS_DIR, name);
    }
    System.out.println(currentFile);
    writeToFile(currentFile, archive);
    final int port = ServerLocal.getPort(-1);
    if (port > 0) {
        server = new RemoteServer(100, true);
        server.setPortStartup(port);
    } else {
        throw new OpenEJBTCKRuntimeException("Please set the tomee port using the system property 'server.http.port'");
    }
    try {
        server.start();
    } catch (final Exception e) {
        server.destroy();
        e.printStackTrace();
        throw e;
    }
    return (exception = lookup().exception()) == null;
}
Also used : OpenEJBTCKRuntimeException(org.apache.openejb.tck.OpenEJBTCKRuntimeException) File(java.io.File) RemoteServer(org.apache.openejb.config.RemoteServer) OpenEJBTCKRuntimeException(org.apache.openejb.tck.OpenEJBTCKRuntimeException) IOException(java.io.IOException) DeploymentException(org.jboss.testharness.api.DeploymentException)

Example 2 with RemoteServer

use of org.apache.openejb.config.RemoteServer in project tomee by apache.

the class AbstractTomEEMojo method run.

/**
 * Run.
 */
protected void run() {
    if (classpaths == null) {
        // NPE protection when execute is skipped and mojo delegates to run directly
        classpaths = new ArrayList<>();
    }
    // init ports if needed
    tomeeHttpPort = getOrInitPort(tomeeHttpPort);
    tomeeHttpsPort = getOrInitPort(tomeeHttpsPort);
    tomeeAjpPort = getOrInitPort(tomeeAjpPort);
    tomeeShutdownPort = getOrInitPort(tomeeShutdownPort);
    final List<String> strings = generateJVMArgs();
    // init env for RemoteServer
    System.setProperty("openejb.home", catalinaBase.getAbsolutePath());
    if (debug) {
        System.setProperty("openejb.server.debug", "true");
        System.setProperty("server.debug.port", Integer.toString(debugPort));
    }
    System.setProperty("server.shutdown.port", String.valueOf(tomeeShutdownPort));
    System.setProperty("server.shutdown.command", tomeeShutdownCommand);
    // We might need to override static cached env vars in RemoteServer
    // Reason: Multiple execution in same JVM, i.e. in Maven Integration Tests
    Properties override = new Properties();
    override.setProperty("openejb.home", System.getProperty("openejb.home"));
    if (debug) {
        override.setProperty("openejb.server.debug", System.getProperty("openejb.server.debug"));
        override.setProperty("server.debug.port", System.getProperty("server.debug.port"));
    }
    override.setProperty("server.shutdown.port", System.getProperty("server.shutdown.port"));
    override.setProperty("server.shutdown.command", System.getProperty("server.shutdown.command"));
    server = new RemoteServer(override, getConnectAttempts(), debug);
    server.setAdditionalClasspath(getAdditionalClasspath());
    // some shutdown hooks are always added (see UpdatableTomEEMojo)
    addShutdownHooks(server);
    if (TOM_EE.equals(container)) {
        try {
            server.setPortStartup(Integer.parseInt(tomeeHttpPort == null ? tomeeHttpsPort : tomeeHttpPort));
        } catch (final NumberFormatException nfe) {
        // no-op
        }
        getLog().info("Running '" + getClass().getName().replace("TomEEMojo", "").toLowerCase(Locale.ENGLISH) + "'. Configured TomEE in plugin is " + tomeeHost + ":" + server.getPortStartup() + " (plugin shutdown port is " + tomeeShutdownPort + " and https port is " + tomeeHttpsPort + ")");
    } else {
        getLog().info("Running '" + getClass().getSimpleName().replace("TomEEMojo", "").toLowerCase(Locale.ENGLISH));
    }
    // piped when starting remote server so saving it
    final InputStream originalIn = System.in;
    serverCmd(server, strings);
    if (getWaitTomEE()) {
        final CountDownLatch stopCondition = new CountDownLatch(1);
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                stopServer(stopCondition);
            }
        });
        if (useConsole) {
            final Scanner reader = new Scanner(originalIn);
            System.out.flush();
            getLog().info("Waiting for command: " + availableCommands());
            String line;
            while ((line = getNextLine(reader)) != null) {
                if (isQuit(line)) {
                    break;
                }
                if ("ignore".equals(line)) {
                    continue;
                }
                if (!handleLine(line.trim())) {
                    System.out.flush();
                    getLog().warn("Command '" + line + "' not understood. Use one of " + availableCommands());
                }
            }
            reader.close();
            // better than using shutdown hook since it doesn't rely on the hook which are not sent by eclipse for instance
            stopServer(stopCondition);
        }
        try {
            stopCondition.await();
        } catch (final InterruptedException e) {
        // no-op
        }
    }
}
Also used : Scanner(java.util.Scanner) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Properties(java.util.Properties) CountDownLatch(java.util.concurrent.CountDownLatch) RemoteServer(org.apache.openejb.config.RemoteServer)

Example 3 with RemoteServer

use of org.apache.openejb.config.RemoteServer in project tomee by apache.

the class ExecRunner method main.

/**
 * Main function to run the plugin.
 *
 * @param rawArgs the raw args
 * @throws Exception the exception
 */
public static void main(final String[] rawArgs) throws Exception {
    final String[] args;
    if (rawArgs == null || rawArgs.length == 0) {
        args = new String[] { "run" };
    } else {
        args = rawArgs;
    }
    final Properties config = new Properties();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    final InputStream is = contextClassLoader.getResourceAsStream("configuration.properties");
    if (is != null) {
        config.load(new InputStreamReader(is, "UTF-8"));
        is.close();
    } else {
        throw new IllegalArgumentException("Config not found");
    }
    final String distrib = config.getProperty("distribution");
    final String workingDir = config.getProperty("workingDir");
    final InputStream distribIs = contextClassLoader.getResourceAsStream(distrib);
    final File distribOutput = new File(workingDir);
    final File timestampFile = new File(distribOutput, "timestamp.txt");
    final boolean forceDelete = Boolean.getBoolean("tomee.runner.force-delete");
    if (forceDelete || !timestampFile.exists() || Long.parseLong(IO.slurp(timestampFile).replace(System.getProperty("line.separator"), "")) < Long.parseLong(config.getProperty("timestamp"))) {
        if (forceDelete || timestampFile.exists()) {
            System.out.println("Deleting " + distribOutput.getAbsolutePath());
            Files.delete(distribOutput);
        }
        System.out.println("Extracting tomee to " + distribOutput.getAbsolutePath());
        Zips.unzip(distribIs, distribOutput, false);
        IO.writeString(timestampFile, config.getProperty("timestamp", Long.toString(System.currentTimeMillis())));
    }
    final File[] scripts = new File(distribOutput, "bin").listFiles();
    if (scripts != null) {
        // dont use filefilter to avoid dependency issue
        for (final File f : scripts) {
            setExecutable(f);
        }
    }
    String cmd = config.getProperty("command");
    if (cmd.endsWith(SH_BAT_AUTO)) {
        final int lastSlash = cmd.lastIndexOf('/');
        if (lastSlash > 0) {
            final String dir = cmd.substring(0, lastSlash);
            final boolean isWin = System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("win");
            final String script = cmd.substring(lastSlash + 1, cmd.length() - SH_BAT_AUTO.length()).replace('/', isWin ? '\\' : '/') + (isWin ? ".bat" : ".sh");
            final File scriptFile = new File(distribOutput, dir + File.separator + script);
            if (!scriptFile.exists()) {
                throw new IllegalArgumentException("Can't find  " + cmd);
            }
            cmd = scriptFile.getAbsolutePath();
            // in case it is not in bin/
            setExecutable(scriptFile);
        }
    }
    final String additionalArgs = System.getProperty("additionalSystemProperties");
    // build also post here to avoid surprises
    final Map<?, ?> map = new HashMap<>();
    final Collection<Runnable> preTasks = buildRunnables(config.getProperty("preTasks"), map);
    final Collection<Runnable> postTasks = buildRunnables(config.getProperty("postTasks"), map);
    final boolean doWait = Boolean.parseBoolean(config.getProperty("waitFor"));
    if (!doWait && !postTasks.isEmpty()) {
        throw new IllegalArgumentException("You can't use post task if you dont wait for the process.");
    }
    for (final Runnable r : preTasks) {
        r.run();
    }
    try {
        final Collection<String> params = new ArrayList<>();
        if ("java".equals(cmd)) {
            final File base = findBase(distribOutput);
            final QuickServerXmlParser parser = QuickServerXmlParser.parse(new File(base, "conf/server.xml"));
            System.setProperty("openejb.home", base.getAbsolutePath());
            System.setProperty("server.shutdown.port", parser.stop());
            System.setProperty("server.shutdown.command", config.getProperty("shutdownCommand"));
            final RemoteServer server = new RemoteServer();
            server.setPortStartup(Integer.parseInt(parser.http()));
            if (config.containsKey("additionalClasspath")) {
                server.setAdditionalClasspath(config.getProperty("additionalClasspath"));
            }
            final List<String> jvmArgs = new LinkedList<>();
            if (additionalArgs != null) {
                Collections.addAll(jvmArgs, additionalArgs.split(" "));
            }
            for (final String k : config.stringPropertyNames()) {
                if (k.startsWith("jvmArg.")) {
                    jvmArgs.add(config.getProperty(k));
                }
            }
            final String userProps = String.class.cast(map.get("jvmArgs"));
            if (userProps != null) {
                Collections.addAll(jvmArgs, userProps.split(" "));
            }
            if ("run".equals(args[0])) {
                args[0] = "start";
            }
            try {
                server.start(jvmArgs, args[0], true);
            } catch (final Exception e) {
                server.destroy();
                throw e;
            }
            if (doWait) {
                server.getServer().waitFor();
            }
        } else {
            // TODO: split cmd correctly to support multiple inlined segments in cmd
            if (cmd.endsWith(".bat") && !cmd.startsWith("cmd.exe")) {
                params.add("cmd.exe");
                params.add("/c");
            }
            // else suppose the user knows what he does
            params.add(cmd);
            params.addAll(asList(args));
            final ProcessBuilder builder = new ProcessBuilder(params.toArray(new String[params.size()])).inheritIO().directory(findBase(distribOutput));
            final String existingOpts = System.getenv("CATALINA_OPTS");
            final String catalinaOpts = config.getProperty("catalinaOpts");
            if (catalinaOpts != null || existingOpts != null || additionalArgs != null) {
                // inherit from existing env
                builder.environment().put("CATALINA_OPTS", identityOrEmpty(catalinaOpts) + " " + identityOrEmpty(existingOpts) + " " + identityOrEmpty(additionalArgs) + " " + identityOrEmpty(String.class.cast(map.get("jvmArgs"))));
            }
            if (doWait) {
                builder.start().waitFor();
            }
        }
        System.out.flush();
        System.err.flush();
        System.out.println("Exited Successfully!");
    } finally {
        for (final Runnable r : postTasks) {
            r.run();
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Properties(java.util.Properties) LinkedList(java.util.LinkedList) QuickServerXmlParser(org.apache.tomee.util.QuickServerXmlParser) File(java.io.File) RemoteServer(org.apache.openejb.config.RemoteServer)

Example 4 with RemoteServer

use of org.apache.openejb.config.RemoteServer in project tomee by apache.

the class RemoteTomEEContainer method start.

@Override
public void start() throws LifecycleException {
    // see if TomEE is already running by checking the http port
    final int httpPort = configuration.getHttpPort();
    if (Setup.isRunning(configuration.getHost(), httpPort)) {
        String host = "local";
        if (!NetworkUtil.isLocalAddress(configuration.getHost())) {
            // Supply at least this property so that the archive is transmitted on deploy
            if (null == deployerProperties.getProperty(DeployerEjb.OPENEJB_USE_BINARIES)) {
                deployerProperties.setProperty(DeployerEjb.OPENEJB_USE_BINARIES, "true");
            }
            host = "remote";
        }
        logger.info(String.format("TomEE found running on %s port %s", host, httpPort));
        return;
    }
    shutdown = true;
    final String shutdownPort = System.getProperty(RemoteServer.SERVER_SHUTDOWN_PORT);
    final String shutdownHost = System.getProperty(RemoteServer.SERVER_SHUTDOWN_HOST);
    final String shutdownCommand = System.getProperty(RemoteServer.SERVER_SHUTDOWN_COMMAND);
    final String debug = System.getProperty(RemoteServer.OPENEJB_SERVER_DEBUG);
    final String debugPort = System.getProperty(RemoteServer.SERVER_DEBUG_PORT);
    try {
        configure();
        final int stopPort = configuration.getStopPort();
        System.setProperty(RemoteServer.SERVER_SHUTDOWN_PORT, Integer.toString(stopPort));
        System.setProperty(RemoteServer.SERVER_SHUTDOWN_COMMAND, configuration.getStopCommand());
        System.setProperty(RemoteServer.SERVER_SHUTDOWN_HOST, configuration.getStopHost());
        if (configuration.isDebug()) {
            System.setProperty(RemoteServer.OPENEJB_SERVER_DEBUG, "true");
            System.setProperty(RemoteServer.SERVER_DEBUG_PORT, Integer.toString(configuration.getDebugPort()));
        }
        container = new RemoteServer();
        container.setPortStartup(httpPort);
        try {
            container.start(args(), "start", true);
        } catch (final Exception e) {
            container.destroy();
            throw e;
        }
        container.killOnExit();
        if (configuration.getProperties() != null) {
            final Properties props = new Properties();
            IO.readProperties(IO.read(configuration.getProperties().getBytes()), props);
            containerArchives = ArquillianUtil.toDeploy(props);
            for (final Archive<?> archive : containerArchives) {
                deploy(archive);
            }
        }
    } catch (final Exception e) {
        if (container != null) {
            container.destroy();
        }
        logger.log(Level.SEVERE, "Unable to start remote container", e);
        throw new LifecycleException("Unable to start remote container:" + e.getMessage(), e);
    } finally {
        resetSystemProperty(RemoteServer.SERVER_SHUTDOWN_PORT, shutdownPort);
        resetSystemProperty(RemoteServer.SERVER_SHUTDOWN_HOST, shutdownHost);
        resetSystemProperty(RemoteServer.SERVER_SHUTDOWN_COMMAND, shutdownCommand);
        resetSystemProperty(RemoteServer.OPENEJB_SERVER_DEBUG, debug);
        resetSystemProperty(RemoteServer.SERVER_DEBUG_PORT, debugPort);
    }
}
Also used : LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) Properties(java.util.Properties) RemoteServer(org.apache.openejb.config.RemoteServer) NamingException(javax.naming.NamingException) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) IOException(java.io.IOException)

Example 5 with RemoteServer

use of org.apache.openejb.config.RemoteServer in project tomee by apache.

the class TomEEWebappContainer method start.

@Override
public void start() throws LifecycleException {
    // see if TomEE is already running by checking the http port
    final int httpPort = configuration.getHttpPort();
    if (Setup.isRunning(configuration.getHost(), httpPort)) {
        logger.info(String.format("Tomcat found running on port %s", httpPort));
        return;
    }
    shutdown = true;
    final String s = File.separator;
    try {
        final File workingDirectory = new File(configuration.getDir());
        if (workingDirectory.exists()) {
            Files.assertDir(workingDirectory);
        } else {
            Files.mkdir(workingDirectory);
            Files.deleteOnExit(workingDirectory);
        }
        Files.readable(workingDirectory);
        Files.writable(workingDirectory);
        openejbHome = Setup.findHome(workingDirectory);
        Installer installer = null;
        if (openejbHome == null) {
            downloadTomcat(workingDirectory, configuration.getTomcatVersion(), configuration.getDir());
            openejbHome = Setup.findHome(workingDirectory);
            Files.deleteOnExit(openejbHome);
            final File webapp = new File(openejbHome, "webapps" + s + "tomee");
            Files.mkdir(webapp);
            downloadOpenEJBWebapp(webapp, configuration.getDir());
            System.setProperty("catalina.home", openejbHome.getAbsolutePath());
            System.setProperty("catalina.base", openejbHome.getAbsolutePath());
            System.setProperty("openejb.deploymentId.format", System.getProperty("openejb.deploymentId.format", "{appId}/{ejbJarId}/{ejbName}"));
            final Paths paths = new Paths(webapp);
            installer = new Installer(paths, true);
            if (!configuration.isUseInstallerServlet()) {
                installer.installAll();
            }
            wereOpenejbHomeSet = false;
        }
        Files.assertDir(openejbHome);
        Files.readable(openejbHome);
        Files.writable(openejbHome);
        Setup.configureServerXml(openejbHome, configuration);
        Setup.configureSystemProperties(openejbHome, configuration);
        Setup.exportProperties(openejbHome, configuration, true);
        final URL logging = Thread.currentThread().getContextClassLoader().getResource("default.remote.logging.properties");
        if (logging != null) {
            write(logging, new File(openejbHome, "conf" + s + "logging.properties"));
        }
        if (configuration.isRemoveUnusedWebapps()) {
            Setup.removeUselessWebapps(openejbHome, "tomee");
        }
        if (logger.isLoggable(Level.FINE)) {
            final Map<Object, Object> map = new TreeMap<>(System.getProperties());
            for (final Map.Entry<Object, Object> entry : map.entrySet()) {
                System.out.printf("%s = %s\n", entry.getKey(), entry.getValue());
            }
        }
        Setup.installArquillianBeanDiscoverer(openejbHome);
        if (!wereOpenejbHomeSet && configuration.isUseInstallerServlet()) {
            // instead of calling the Installer, let's just do like users do
            // call the servlet installer instead
            final String baseUrl = "http://" + configuration.getHost() + ":" + httpPort + "/tomee/installer";
            assert installer != null;
            installer.addTomEEAdminConfInTomcatUsers(true);
            final RemoteServer tmpContainer = new RemoteServer();
            tmpContainer.setPortStartup(httpPort);
            try {
                tmpContainer.start();
            } catch (final Exception e) {
                tmpContainer.destroy();
                throw e;
            }
            final URL url = new URL(baseUrl);
            logger.info("Calling TomEE Installer Servlet on " + url);
            for (int i = 0; i < Integer.getInteger("tomee.webapp.container.client.retries", 3); i++) {
                final URLConnection uc = url.openConnection();
                // dG9tZWU6dG9tZWU= --> Base64 of tomee:tomee
                final String authorizationString = "Basic dG9tZWU6dG9tZWU=";
                final int timeout = Integer.getInteger("tomee.webapp.container.client.timeout", 60000);
                uc.setConnectTimeout(timeout);
                uc.setReadTimeout(timeout);
                uc.setRequestProperty("Authorization", authorizationString);
                try {
                    final InputStream is = uc.getInputStream();
                    org.apache.openejb.loader.IO.slurp(is);
                    is.close();
                    break;
                } catch (final Exception e) {
                    logger.warning(e.getMessage());
                    Thread.sleep(1000);
                }
            }
            tmpContainer.stop();
            tmpContainer.getServer().waitFor();
        }
        container = new RemoteServer();
        container.setPortStartup(httpPort);
        container.start(Arrays.asList("-Dopenejb.system.apps=true", "-Dtomee.remote.support=true", "-Dorg.apache.openejb.servlet.filters=" + ArquillianFilterRunner.class.getName() + "=" + ServletMethodExecutor.ARQUILLIAN_SERVLET_MAPPING), "start", true);
        container.killOnExit();
    } catch (final Exception e) {
        if (null != container) {
            container.destroy();
        }
        throw new LifecycleException("Unable to start remote container on port: " + httpPort, e);
    }
}
Also used : ArquillianFilterRunner(org.apache.openejb.arquillian.common.ArquillianFilterRunner) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) Installer(org.apache.tomee.installer.Installer) InputStream(java.io.InputStream) TreeMap(java.util.TreeMap) URL(java.net.URL) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) IOException(java.io.IOException) URLConnection(java.net.URLConnection) Paths(org.apache.tomee.installer.Paths) File(java.io.File) TreeMap(java.util.TreeMap) Map(java.util.Map) RemoteServer(org.apache.openejb.config.RemoteServer)

Aggregations

RemoteServer (org.apache.openejb.config.RemoteServer)5 File (java.io.File)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Properties (java.util.Properties)3 LifecycleException (org.jboss.arquillian.container.spi.client.container.LifecycleException)2 BufferedInputStream (java.io.BufferedInputStream)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 URL (java.net.URL)1 URLConnection (java.net.URLConnection)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Scanner (java.util.Scanner)1 TreeMap (java.util.TreeMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 NamingException (javax.naming.NamingException)1 ArquillianFilterRunner (org.apache.openejb.arquillian.common.ArquillianFilterRunner)1