Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FISH-10620 Support for Running asadmin Command from Payara Server Maven Plugin Console #442

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ ExecutionEnvironment getEnvironment() {
}
return environment;
}
protected String getProjectGAV(){

protected String getProjectGAV() {
return mavenProject.getGroupId() + ":" + mavenProject.getArtifactId() + ":" + mavenProject.getVersion();
}

protected Toolchain getToolchain() {
if ( toolchainManager != null ) {
if (toolchainManager != null) {
return toolchainManager.getToolchainFromBuildContext("jdk", mavenSession);
}
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@
public abstract class BaseProcessor implements Configuration {

private BaseProcessor nextProcessor;
Plugin dependencyPlugin =
plugin(groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("3.8.1"));

Plugin dependencyPlugin
= plugin(groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("3.8.1"));

public abstract void handle(ExecutionEnvironment environment) throws MojoExecutionException;

Expand All @@ -62,4 +62,4 @@ void gotoNext(ExecutionEnvironment environment) throws MojoExecutionException {
nextProcessor.handle(environment);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,4 @@ public void setContentType(String contentType) {
this.contentType = contentType;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@
import java.io.File;

public interface Configuration {

String SERVER_GROUPID = "fish.payara.distributions";
String SERVER_ARTIFACTID = "payara";

String DAS_NAME = "server";

String JAVA_EXECUTABLE = "java";
Expand All @@ -52,7 +53,7 @@ public interface Configuration {

String SERVER_THREAD_NAME = "PayaraServerThread";
String SERVER_READY_MESSAGE = "ready in";

// Log parser
String INSTANCE_CONFIGURATION = " \"Instance Configuration\": {";
String HOST_IP_PATTERN = "\"Host\": \"([^\"]+)\"";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@
package fish.payara.maven.plugins.server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.dependency.fromConfiguration.ArtifactItem;

Expand All @@ -61,31 +57,31 @@ public abstract class ServerMojo extends BasePayaraMojo {

@Parameter(property = "payaraServerAbsolutePath")
protected String payaraServerAbsolutePath;

@Parameter(property = "domain", defaultValue = "domain1")
protected String domain;

@Parameter(property = "artifactItem")
protected ArtifactItem artifactItem;

@Parameter(property = "exploded", defaultValue = "false")
protected boolean exploded;

@Parameter(property = "contextRoot")
protected String contextRoot;

@Parameter(property = "remote", defaultValue = "false")
protected boolean remote;

@Parameter(property = "host", defaultValue = "${env.PAYARA_HOST}")
protected String host;

@Parameter(property = "adminPort", defaultValue = "${env.PAYARA_ADMIN_PORT}")
protected String adminPort;

@Parameter(property = "httpPort", defaultValue = "${env.PAYARA_HTTP_PORT}")
protected String httpPort;

@Parameter(property = "httpsPort", defaultValue = "${env.PAYARA_HTTPS_PORT}")
protected String httpsPort;

Expand All @@ -100,7 +96,7 @@ public abstract class ServerMojo extends BasePayaraMojo {

@Parameter(property = "adminUser", defaultValue = "${env.PAYARA_ADMIN_USER}")
protected String adminUser;

@Parameter(property = "instanceName", defaultValue = "${env.PAYARA_INSTANCE}")
protected String instanceName;

Expand All @@ -116,9 +112,9 @@ protected String getAdminPasswordFromFile() {
}
return adminPassword;
}

protected String getAdminPassword() {
if(adminPassword == null) {
if (adminPassword == null) {
adminPassword = getAdminPasswordFromFile();
}
return adminPassword;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@
import java.util.concurrent.TimeUnit;

import static fish.payara.maven.plugins.server.Configuration.*;
import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.maven.project.MavenProject;
Expand Down Expand Up @@ -107,6 +109,7 @@ public class StartMojo extends ServerMojo implements StartTask {
private WebDriver driver;
private String payaraServerURL;
private InstanceManager serverManager;
private String appPath, projectName;

StartMojo() {
threadGroup = new ThreadGroup(SERVER_THREAD_NAME);
Expand Down Expand Up @@ -188,15 +191,15 @@ public void execute() throws MojoExecutionException {
} else {
streamLocalServerLog(instance);
}
String appPath;
if (exploded) {
appPath = evaluateProjectArtifactAbsolutePath("");
} else {
appPath = evaluateProjectArtifactAbsolutePath("." + mavenProject.getPackaging());
}
String projectName = mavenProject.getName().replaceAll("\\s+", "");
projectName = mavenProject.getName().replaceAll("\\s+", "");
serverManager.undeployApplication(projectName, instanceName);
serverManager.deployApplication(projectName, appPath, instanceName, contextRoot);
watchAsadminCommand();
int exitCode = serverProcess.waitFor();
if (exitCode != 0) { // && !autoDeploy
throw new MojoFailureException(ERROR_MESSAGE);
Expand Down Expand Up @@ -224,7 +227,7 @@ public void execute() throws MojoExecutionException {
}
}
} else {
Runtime.getRuntime().addShutdownHook(getShutdownHook());
Runtime.getRuntime().addShutdownHook(killServerProcess());
serverProcessorThread.run();

// if (autoDeploy) {
Expand All @@ -235,14 +238,13 @@ public void execute() throws MojoExecutionException {
}
}

private Thread getShutdownHook() {
private Thread killServerProcess() {
return new Thread(threadGroup, () -> {
if (serverProcess != null && serverProcess.isAlive()) {
try {
String projectName = mavenProject.getName().replaceAll("\\s+", "");
serverManager.undeployApplication(projectName, instanceName);
serverProcess.destroy();
serverProcess.waitFor(1, TimeUnit.MINUTES);
serverProcess.waitFor(15, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
} finally {
serverProcess.destroyForcibly();
Expand Down Expand Up @@ -388,6 +390,54 @@ Process getServerProcess() {
return this.serverProcess;
}

private void watchAsadminCommand() {
Thread thread = new Thread(threadGroup, () -> {
try (Scanner scanner = new Scanner(System.in)) {
String userQuery = null;

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Thread.currentThread().interrupt();
}));

while (!Thread.currentThread().isInterrupted() && !"exit".equals(userQuery)) {
try {
if (scanner.hasNextLine()) {
userQuery = scanner.nextLine();
} else {
Thread.currentThread().interrupt();
break; // Exit if input stream closes
}
} catch (java.util.NoSuchElementException nsee) {
break;
}
try {
if (userQuery.startsWith("asadmin")) {
if (serverManager instanceof LocalInstanceManager) {
String repsonse = ((LocalInstanceManager) serverManager).runAsadminCommand(userQuery.substring(8));
getLog().info(repsonse);
}
} else if (userQuery.equals("deploy")) {
serverManager.undeployApplication(projectName, instanceName);
serverManager.deployApplication(projectName, appPath, instanceName, contextRoot);
} else if (userQuery.equals("undeploy")) {
serverManager.undeployApplication(projectName, instanceName);
} else if (userQuery.equals("exit")) {
Thread.currentThread().interrupt();
getLog().info("watchAsadminCommand exit");
killServerProcess().start();
break;
}
} catch (Exception ex) {
Logger.getLogger(StartMojo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});

thread.setDaemon(false);
thread.start();
}

private Thread streamRemoteServerLog() {
final Thread thread = new Thread(threadGroup, () -> {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
import fish.payara.maven.plugins.server.utils.ServerUtils;
import fish.payara.maven.plugins.server.utils.StringUtils;
import java.io.File;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
Expand All @@ -56,8 +55,10 @@
import java.util.Map;
import org.apache.maven.plugin.logging.Log;
import fish.payara.maven.plugins.server.parser.JDKVersion;
import java.net.URI;
import org.apache.maven.plugin.MojoExecutionException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
*
Expand All @@ -69,7 +70,7 @@ public class LocalInstanceManager extends InstanceManager<PayaraServerLocalInsta
private static final String ERROR_JAVA_VERSION_NOT_FOUND = "Java version not found.";
private static final String ERROR_BOOTSTRAP_JAR_NOT_FOUND = "No bootstrap jar exists.";
private static final String ERROR_JAVA_VM_EXECUTABLE_NOT_FOUND = "Java VM executable for %s was not found.";

public LocalInstanceManager(PayaraServerLocalInstance payaraServer, Log log) {
super(payaraServer, log);
}
Expand Down Expand Up @@ -235,5 +236,64 @@ public boolean isServerAlreadyRunning() {
return false;
}

}
public String runAsadminCommand(String command) throws Exception {
String javaHome = payaraServer.getJDKHome();
if (javaHome == null) {
throw new Exception(ERROR_JAVA_HOME_NOT_FOUND);
}

String javaVmExe = JavaUtils.javaVmExecutableFullPath(javaHome);
if (!Files.exists(Paths.get(javaVmExe))) {
throw new Exception(String.format(ERROR_JAVA_VM_EXECUTABLE_NOT_FOUND, payaraServer.getPath()));
}

String asadminPath = Paths.get(payaraServer.getServerHome(), "bin", "asadmin").toString();
if (!Files.exists(Paths.get(asadminPath))) {
throw new Exception("asadmin executable not found at " + asadminPath);
}

List<String> commandList = new ArrayList<>();

if (System.getProperty("os.name").toLowerCase().contains("win")) {
commandList.add("cmd.exe");
commandList.add("/c");
} else {
commandList.add("/bin/sh");
commandList.add("-c");
}

commandList.add(asadminPath);
commandList.addAll(Arrays.asList(command.split("\\s+")));

ProcessBuilder processBuilder = new ProcessBuilder(commandList);
processBuilder.directory(Paths.get(payaraServer.getServerHome(), "bin").toFile());

Process process = processBuilder.start();

StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
log.error("Error reading process output", e);
}

try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
log.error("Error reading process error output", e);
}

int exitCode = process.waitFor();
if (exitCode != 0) {
log.error("asadmin command failed with exit code " + exitCode);
}
return sb.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
* @author Gaurav Gupta
*/
public abstract class PayaraServerInstance {

protected String adminUser;
protected String adminPassword;

Expand All @@ -60,7 +60,7 @@ public String getAdminUser() {
public void setAdminUser(String adminUser) {
this.adminUser = adminUser;
}

public String getAdminPassword() {
return adminPassword;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public String getHost() {
}

public int getHttpPort() {
if(httpPort > 0) {
if (httpPort > 0) {
return httpPort;
}
if (portReader == null) {
Expand All @@ -127,7 +127,7 @@ public int getHttpPort() {
}

public int getHttpsPort() {
if(httpsPort > 0) {
if (httpsPort > 0) {
return httpsPort;
}
if (portReader == null) {
Expand All @@ -137,7 +137,7 @@ public int getHttpsPort() {
}

public int getAdminPort() {
if(adminPort > 0) {
if (adminPort > 0) {
return adminPort;
}
if (portReader == null) {
Expand Down
Loading