Search in sources :

Example 1 with SwarmExecutor

use of org.wildfly.swarm.tools.exec.SwarmExecutor in project wildfly-swarm by wildfly-swarm.

the class StartMojo method warExecutor.

protected SwarmExecutor warExecutor() throws MojoFailureException {
    getLog().info("Starting .war");
    String finalName = this.project.getBuild().getFinalName();
    if (!finalName.endsWith(".war")) {
        finalName = finalName + ".war";
    }
    Path warPath = Paths.get(this.projectBuildDir, finalName);
    SwarmExecutor executor = executor(warPath, finalName, false);
    // Specify swarm.app.path property so that repackaged war is used
    executor.withProperty(BootstrapProperties.APP_PATH, warPath.toString());
    return executor;
}
Also used : Path(java.nio.file.Path) SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor)

Example 2 with SwarmExecutor

use of org.wildfly.swarm.tools.exec.SwarmExecutor in project wildfly-swarm by wildfly-swarm.

the class UberjarSimpleContainer method start.

@Override
public void start(Archive<?> archive) throws Exception {
    archive.add(EmptyAsset.INSTANCE, "META-INF/arquillian-testable");
    ContextRoot contextRoot = null;
    if (archive.getName().endsWith(".war")) {
        contextRoot = new ContextRoot("/");
        Node jbossWebNode = archive.as(WebArchive.class).get("WEB-INF/jboss-web.xml");
        if (jbossWebNode != null) {
            if (jbossWebNode.getAsset() != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(jbossWebNode.getAsset().openStream()))) {
                    String content = String.join("\n", reader.lines().collect(Collectors.toList()));
                    Pattern pattern = Pattern.compile("<context-root>(.+)</context-root>");
                    Matcher matcher = pattern.matcher(content);
                    if (matcher.find()) {
                        contextRoot = new ContextRoot(matcher.group(1));
                    }
                }
            }
        }
        this.deploymentContext.getObjectStore().add(ContextRoot.class, contextRoot);
    }
    MainSpecifier mainSpecifier = containerContext.getObjectStore().get(MainSpecifier.class);
    boolean annotatedCreateSwarm = false;
    Method swarmMethod = getAnnotatedMethodWithAnnotation(this.testClass, CreateSwarm.class);
    List<Class<?>> types = determineTypes(this.testClass);
    // preflight check it
    if (swarmMethod != null) {
        if (Modifier.isStatic(swarmMethod.getModifiers())) {
            // good to go
            annotatedCreateSwarm = true;
            types.add(CreateSwarm.class);
            types.add(AnnotationBasedMain.class);
            archive.as(JARArchive.class).addModule("org.wildfly.swarm.container");
            archive.as(JARArchive.class).addModule("org.wildfly.swarm.configuration");
        } else {
            throw new IllegalArgumentException(String.format("Method annotated with %s is %s but it is not static", CreateSwarm.class.getSimpleName(), swarmMethod));
        }
    }
    if (types.size() > 0) {
        try {
            ((ClassContainer<?>) archive).addClasses(types.toArray(new Class[types.size()]));
        } catch (UnsupportedOperationException e) {
            // TODO Remove the try/catch when SHRINKWRAP-510 is resolved and we update to latest SW
            archive.as(JARArchive.class).addClasses(types.toArray(new Class[types.size()]));
        }
    }
    final ShrinkwrapArtifactResolvingHelper resolvingHelper = ShrinkwrapArtifactResolvingHelper.defaultInstance();
    BuildTool tool = new BuildTool(resolvingHelper).fractionDetectionMode(BuildTool.FractionDetectionMode.when_missing).bundleDependencies(false);
    String additionalModules = System.getProperty(SwarmInternalProperties.BUILD_MODULES);
    // See https://issues.jboss.org/browse/SWARM-571
    if (null == additionalModules) {
        // see if we can find it
        File modulesDir = new File("target/classes/modules");
        additionalModules = modulesDir.exists() ? modulesDir.getAbsolutePath() : null;
    }
    if (additionalModules != null) {
        tool.additionalModules(Stream.of(additionalModules.split(":")).map(File::new).filter(File::exists).map(File::getAbsolutePath).collect(Collectors.toList()));
    }
    final SwarmExecutor executor = new SwarmExecutor().withDefaultSystemProperties();
    if (annotatedCreateSwarm) {
        executor.withProperty(AnnotationBasedMain.ANNOTATED_CLASS_NAME, this.testClass.getName());
    }
    if (contextRoot != null) {
        executor.withProperty(SwarmProperties.CONTEXT_PATH, contextRoot.context());
    }
    executor.withProperty("swarm.inhibit.auto-stop", "true");
    String additionalRepos = System.getProperty(SwarmInternalProperties.BUILD_REPOS);
    if (additionalRepos != null) {
        additionalRepos = additionalRepos + ",";
    } else {
        additionalRepos = "";
    }
    additionalRepos = additionalRepos + "https://repository.jboss.org/nexus/content/groups/public/";
    executor.withProperty("remote.maven.repo", additionalRepos);
    // project dependencies
    FileSystemLayout fsLayout = FileSystemLayout.create();
    DeclaredDependencies declaredDependencies = DependencyDeclarationFactory.newInstance(fsLayout).create(fsLayout, resolvingHelper);
    tool.declaredDependencies(declaredDependencies);
    // see DependenciesContainer#addAllDependencies()
    if (archive instanceof DependenciesContainer) {
        DependenciesContainer<?> depContainer = (DependenciesContainer<?>) archive;
        if (depContainer.hasMarker(DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
            munge(depContainer, declaredDependencies);
        }
    } else if (archive instanceof WebArchive) {
        // Handle the default deployment of type WAR
        WebArchive webArchive = (WebArchive) archive;
        if (MarkerContainer.hasMarker(webArchive, DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
            munge(webArchive, declaredDependencies);
        }
    }
    tool.projectArchive(archive);
    final String debug = System.getProperty(SwarmProperties.DEBUG_PORT);
    if (debug != null) {
        try {
            executor.withDebug(Integer.parseInt(debug));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(String.format("Failed to parse %s of \"%s\"", SwarmProperties.DEBUG_PORT, debug), e);
        }
    }
    if (mainSpecifier != null) {
        tool.mainClass(mainSpecifier.getClassName());
        String[] args = mainSpecifier.getArgs();
        for (String arg : args) {
            executor.withArgument(arg);
        }
    } else if (annotatedCreateSwarm) {
        tool.mainClass(AnnotationBasedMain.class.getName());
    } else {
        Optional<String> mainClassName = Optional.empty();
        Node node = archive.get("META-INF/arquillian-main-class");
        if (node != null && node.getAsset() != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(node.getAsset().openStream()))) {
                mainClassName = reader.lines().findFirst();
            }
        }
        tool.mainClass(mainClassName.orElse(Swarm.class.getName()));
    }
    if (this.testClass != null) {
        tool.testClass(this.testClass.getName());
    }
    Archive<?> wrapped = null;
    try {
        wrapped = tool.build();
    } catch (Throwable t) {
        t.printStackTrace();
        throw t;
    }
    if (BootstrapProperties.flagIsSet(SwarmInternalProperties.EXPORT_UBERJAR)) {
        final File out = new File(wrapped.getName());
        System.err.println("Exporting swarm jar to " + out.getAbsolutePath());
        wrapped.as(ZipExporter.class).exportTo(out, true);
    }
    /* for (Map.Entry<ArchivePath, Node> each : wrapped.getContent().entrySet()) {
                System.err.println("-> " + each.getKey());
            }*/
    File executable = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "arquillian", "-swarm.jar");
    wrapped.as(ZipExporter.class).exportTo(executable, true);
    executable.deleteOnExit();
    String mavenRepoLocal = System.getProperty("maven.repo.local");
    if (mavenRepoLocal != null) {
        executor.withProperty("maven.repo.local", mavenRepoLocal);
    }
    executor.withProperty("java.net.preferIPv4Stack", "true");
    File processFile = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "mainprocessfile", null);
    executor.withProcessFile(processFile);
    executor.withJVMArguments(getJavaVmArgumentsList());
    executor.withExecutableJar(executable.toPath());
    workingDirectory = TempFileManager.INSTANCE.newTempDirectory("arquillian", null);
    executor.withWorkingDirectory(workingDirectory.toPath());
    this.process = executor.execute();
    this.process.getOutputStream().close();
    this.process.awaitReadiness(2, TimeUnit.MINUTES);
    if (!this.process.isAlive()) {
        throw new DeploymentException("Process failed to start");
    }
    if (this.process.getError() != null) {
        throw new DeploymentException("Error starting process", this.process.getError());
    }
}
Also used : Matcher(java.util.regex.Matcher) ClassContainer(org.jboss.shrinkwrap.api.container.ClassContainer) ZipExporter(org.jboss.shrinkwrap.api.exporter.ZipExporter) Node(org.jboss.shrinkwrap.api.Node) FileSystemLayout(org.wildfly.swarm.internal.FileSystemLayout) Swarm(org.wildfly.swarm.Swarm) CreateSwarm(org.wildfly.swarm.arquillian.CreateSwarm) ShrinkwrapArtifactResolvingHelper(org.wildfly.swarm.arquillian.resolver.ShrinkwrapArtifactResolvingHelper) ContextRoot(org.wildfly.swarm.arquillian.adapter.resources.ContextRoot) JARArchive(org.wildfly.swarm.spi.api.JARArchive) Pattern(java.util.regex.Pattern) InputStreamReader(java.io.InputStreamReader) Optional(java.util.Optional) SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor) DependenciesContainer(org.wildfly.swarm.spi.api.DependenciesContainer) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) Method(java.lang.reflect.Method) BuildTool(org.wildfly.swarm.tools.BuildTool) BufferedReader(java.io.BufferedReader) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) File(java.io.File)

Example 3 with SwarmExecutor

use of org.wildfly.swarm.tools.exec.SwarmExecutor in project wildfly-swarm by wildfly-swarm.

the class MultiStartMojo method startArtifact.

@SuppressWarnings("unchecked")
protected void startArtifact(Artifact artifact, XmlPlexusConfiguration process) throws InvalidPluginDescriptorException, PluginResolutionException, PluginDescriptorParsingException, PluginNotFoundException, PluginConfigurationException, MojoFailureException, MojoExecutionException, PluginManagerException {
    List<SwarmProcess> procs = (List<SwarmProcess>) getPluginContext().get(SWARM_PROCESS);
    if (procs == null) {
        procs = new ArrayList<>();
        getPluginContext().put(SWARM_PROCESS, procs);
    }
    SwarmExecutor executor = new SwarmExecutor();
    executor.withExecutableJar(artifact.getFile().toPath());
    executor.withProperties(this.properties);
    executor.withEnvironment(this.environment);
    PlexusConfiguration props = process.getChild("properties");
    for (PlexusConfiguration each : props.getChildren()) {
        executor.withProperty(each.getName(), each.getValue());
    }
    PlexusConfiguration env = process.getChild("environment");
    for (PlexusConfiguration each : env.getChildren()) {
        executor.withEnvironment(each.getName(), each.getValue());
    }
    int startTimeoutSeconds;
    try {
        startTimeoutSeconds = Integer.valueOf(props.getChild("start.timeout.seconds").getValue("30"));
    } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException("Wrong format of the start timeout for " + artifact + "!. Integer expected.", nfe);
    }
    try {
        SwarmProcess launched = executor.execute();
        launched.awaitReadiness(startTimeoutSeconds, TimeUnit.SECONDS);
        procs.add(launched);
    } catch (IOException | InterruptedException e) {
        throw new MojoFailureException("Unable to execute: " + artifact, e);
    }
}
Also used : XmlPlexusConfiguration(org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration) PlexusConfiguration(org.codehaus.plexus.configuration.PlexusConfiguration) SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SwarmProcess(org.wildfly.swarm.tools.exec.SwarmProcess) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with SwarmExecutor

use of org.wildfly.swarm.tools.exec.SwarmExecutor in project wildfly-swarm by wildfly-swarm.

the class StartMojo method executeSpecific.

@SuppressWarnings({ "unchecked", "ThrowableResultOfMethodCallIgnored" })
@Override
public void executeSpecific() throws MojoExecutionException, MojoFailureException {
    initProperties(true);
    initEnvironment();
    final SwarmExecutor executor;
    if (this.useUberJar) {
        executor = uberJarExecutor();
    } else if (this.project.getPackaging().equals("war")) {
        executor = warExecutor();
    } else if (this.project.getPackaging().equals("jar")) {
        executor = jarExecutor();
    } else {
        throw new MojoExecutionException("Unsupported packaging: " + this.project.getPackaging());
    }
    executor.withJVMArguments(this.jvmArguments);
    if (this.argumentsProp != null) {
        StringTokenizer args = new StringTokenizer(this.argumentsProp);
        while (args.hasMoreTokens()) {
            this.arguments.add(args.nextToken());
        }
    }
    executor.withArguments(this.arguments);
    final SwarmProcess process;
    try {
        File tmp;
        try {
            tmp = Files.createTempFile("swarm-process-file", null).toFile();
        } catch (IOException e) {
            throw new MojoFailureException("Error while creating process file");
        }
        process = executor.withDebug(debugPort).withProcessFile(tmp).withProperties(this.properties).withStdoutFile(this.stdoutFile != null ? this.stdoutFile.toPath() : null).withStderrFile(this.stderrFile != null ? this.stderrFile.toPath() : null).withEnvironment(this.environment).withWorkingDirectory(this.project.getBasedir().toPath()).withProperty("remote.maven.repo", String.join(",", this.project.getRemoteProjectRepositories().stream().map(RemoteRepository::getUrl).collect(Collectors.toList()))).execute();
        int startTimeoutSeconds;
        try {
            startTimeoutSeconds = Integer.valueOf(this.properties.getProperty("start.timeout.seconds", "120"));
        } catch (NumberFormatException nfe) {
            throw new IllegalArgumentException("Wrong format of the start timeout!. Integer expected.", nfe);
        }
        process.awaitReadiness(startTimeoutSeconds, TimeUnit.SECONDS);
        if (!process.isAlive()) {
            throw new MojoFailureException("Process failed to start");
        }
        if (process.getError() != null) {
            throw new MojoFailureException("Error starting process", process.getError());
        }
    } catch (IOException e) {
        throw new MojoFailureException("unable to execute", e);
    } catch (InterruptedException e) {
        throw new MojoFailureException("Error waiting for deployment", e);
    }
    List<SwarmProcess> procs = (List<SwarmProcess>) getPluginContext().get("swarm-process");
    if (procs == null) {
        procs = new ArrayList<>();
        getPluginContext().put("swarm-process", procs);
    }
    procs.add(process);
    if (waitForProcess) {
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            try {
                process.stop(10, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
            // Do nothing
            }
        } finally {
            process.destroyForcibly();
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SwarmProcess(org.wildfly.swarm.tools.exec.SwarmProcess) StringTokenizer(java.util.StringTokenizer) ArrayList(java.util.ArrayList) FractionList(org.wildfly.swarm.fractions.FractionList) List(java.util.List) File(java.io.File)

Example 5 with SwarmExecutor

use of org.wildfly.swarm.tools.exec.SwarmExecutor in project wildfly-swarm by wildfly-swarm.

the class StartMojo method uberJarExecutor.

protected SwarmExecutor uberJarExecutor() throws MojoFailureException {
    getLog().info("Starting -swarm.jar");
    String finalName = this.project.getBuild().getFinalName();
    if (finalName.endsWith(".war") || finalName.endsWith(".jar")) {
        finalName = finalName.substring(0, finalName.length() - 4);
    }
    return new SwarmExecutor().withExecutableJar(Paths.get(this.projectBuildDir, finalName + "-swarm.jar"));
}
Also used : SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor)

Aggregations

SwarmExecutor (org.wildfly.swarm.tools.exec.SwarmExecutor)5 File (java.io.File)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 MojoFailureException (org.apache.maven.plugin.MojoFailureException)2 SwarmProcess (org.wildfly.swarm.tools.exec.SwarmProcess)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 Method (java.lang.reflect.Method)1 Path (java.nio.file.Path)1 Optional (java.util.Optional)1 StringTokenizer (java.util.StringTokenizer)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 PlexusConfiguration (org.codehaus.plexus.configuration.PlexusConfiguration)1 XmlPlexusConfiguration (org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration)1 DeploymentException (org.jboss.arquillian.container.spi.client.container.DeploymentException)1 Node (org.jboss.shrinkwrap.api.Node)1