Skip to content

Commit

Permalink
Additional cleanups - formatting, syntax, logging
Browse files Browse the repository at this point in the history
Signed-off-by: David Matějček <[email protected]>
  • Loading branch information
dmatej committed Jan 23, 2025
1 parent a047d32 commit 6fc795a
Show file tree
Hide file tree
Showing 26 changed files with 556 additions and 580 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ public String[] addJvmOptions(String[] options) throws InvalidJvmOptionException
}
final Set alreadyExist = new HashSet();
JvmOptionsElement last = last();
for (int i = 0; i < options.length; i++) {
if (!head.hasOption(options[i])) {
JvmOptionsElement x = new JvmOptionsElement(options[i]);
for (String option : options) {
if (!head.hasOption(option)) {
JvmOptionsElement x = new JvmOptionsElement(option);
last.setNext(x);
last = x;
} else {
alreadyExist.add(options[i]);
alreadyExist.add(option);
}
}
return toStringArray(alreadyExist);
Expand Down Expand Up @@ -115,9 +115,9 @@ public String[] deleteJvmOptions(String[] options) {
}

final Set donotExist = new HashSet();
for (int i = 0; i < options.length; i++) {
if (!head.deleteJvmOption(options[i])) {
donotExist.add(options[i]);
for (String option : options) {
if (!head.deleteJvmOption(option)) {
donotExist.add(option);
}
}
return toStringArray(donotExist);
Expand Down Expand Up @@ -209,6 +209,7 @@ void setNext(JvmOptionsElement element) {
throw new UnsupportedOperationException();
}
};

private final Set jvmOptions = new LinkedHashSet();
private JvmOptionsElement next;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright (c) 2025 Contributors to the Eclipse Foundation
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
Expand All @@ -24,6 +25,7 @@
import jakarta.inject.Inject;

import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -86,15 +88,12 @@ public void execute(AdminCommandContext context) {
TokenResolver resolver = null;

// Create a resolver that can replace system properties in strings
Map<String, String> systemPropsMap =
new HashMap<String, String>((Map)(System.getProperties()));
Map<String, String> systemPropsMap = new HashMap<String, String>((Map) (System.getProperties()));
resolver = new TokenResolver(systemPropsMap);
String resolvedInstallDir = resolver.resolve(installdir);
File actualInstallDir = new File( resolvedInstallDir+"/" + NodeUtils.LANDMARK_FILE);


if (!actualInstallDir.exists()){
report.setMessage(Strings.get("invalid.installdir",installdir));
Path resolvedInstallDir = new File(resolver.resolve(installdir)).toPath();
Path actualInstallDir = resolvedInstallDir.resolve(NodeUtils.LANDMARK_FILE);
if (!actualInstallDir.toFile().exists()) {
report.setMessage(Strings.get("invalid.installdir", installdir));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return;
}
Expand All @@ -103,12 +102,15 @@ public void execute(AdminCommandContext context) {
CommandInvocation ci = cr.getCommandInvocation("_create-node", report, context.getSubject());
ParameterMap map = new ParameterMap();
map.add("DEFAULT", name);
if (StringUtils.ok(nodedir))
if (StringUtils.ok(nodedir)) {
map.add(NodeUtils.PARAM_NODEDIR, nodedir);
if (StringUtils.ok(installdir))
}
if (StringUtils.ok(installdir)) {
map.add(NodeUtils.PARAM_INSTALLDIR, installdir);
if (StringUtils.ok(nodehost))
}
if (StringUtils.ok(nodehost)) {
map.add(NodeUtils.PARAM_NODEHOST, nodehost);
}
map.add(NodeUtils.PARAM_TYPE,"CONFIG");
ci.parameters(map);
ci.execute();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ update.node.ssh.not.updated=Node not updated. To force an update of the \
update.node.config.missing.attribute={1} attribute is required to update node {0}.
update.node.config.defaultnode=Cannot update node {0}. It is the built-in localhost node.
node.ssh.invalid.params=Warning: some parameters appear to be invalid.
ssh.bad.connect=Could not connect to host {0} using {1}.
ssh.bad.connect=Could not connect to host {0} using {1}. Cause: {2}
ssh.invalid.port=Invalid port number {0}.
key.path.not.absolute=Key file path {0} must be an absolute path.
key.path.not.found=Key file {0} not found. The key file path must be reachable by the DAS.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
import com.sun.enterprise.util.net.NetUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Path;
Expand All @@ -45,6 +43,7 @@
import org.glassfish.api.admin.ParameterMap;
import org.glassfish.api.admin.SSHCommandExecutionException;
import org.glassfish.cluster.ssh.connect.NodeRunner;
import org.glassfish.cluster.ssh.launcher.SSHException;
import org.glassfish.cluster.ssh.launcher.SSHLauncher;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.internal.api.RelativePathResolver;
Expand Down Expand Up @@ -284,16 +283,10 @@ private void pingSSHConnection(Node node) throws CommandValidationException {
SSHLauncher sshL = new SSHLauncher(node);
try {
sshL.pingConnection();
} catch (Exception e) {
String m1 = e.getMessage();
String m2 = "";
Throwable e2 = e.getCause();
if (e2 != null) {
m2 = e2.getMessage();
}
String msg = Strings.get("ssh.bad.connect", node.getNodeHost(), "SSH");
logger.log(WARNING, StringUtils.cat(": ", msg, m1, m2), e);
throw new CommandValidationException(StringUtils.cat(NL, msg, m1, m2), e);
} catch (SSHException e) {
String msg = Strings.get("ssh.bad.connect", node.getNodeHost(), "SSH", e.getMessage());
logger.log(WARNING, msg, e);
throw new CommandValidationException(msg, e);
}
}

Expand Down Expand Up @@ -337,25 +330,14 @@ private void validateSSHConnection(ParameterMap map) throws
sshpassword, keyFile == null ? null : new File(keyFile), sshkeypassphrase);
try {
Path pathToCheck = resolvedInstallDir.resolve(LANDMARK_FILE);
if (!sshLauncher.exists(pathToCheck)) {
throw new FileNotFoundException(
if (!installFlag && !sshLauncher.exists(pathToCheck)) {
throw new CommandValidationException(
"Invalid install directory: could not find " + pathToCheck + " on " + host);
}
} catch (IOException e) {
String m1 = e.getMessage();
String m2 = "";
Throwable e2 = e.getCause();
if (e2 != null) {
m2 = e2.getMessage();
}
if (e instanceof FileNotFoundException) {
if (!installFlag) {
throw new CommandValidationException(StringUtils.cat(NL, m1, m2), e);
}
} else {
String msg = Strings.get("ssh.bad.connect", nodehost, "SSH");
throw new CommandValidationException(StringUtils.cat(NL, msg, m1, m2), e);
}
} catch (SSHException e) {
String msg = Strings.get("ssh.bad.connect", nodehost, "SSH", e.getMessage());
logger.log(WARNING, msg, e);
throw new CommandValidationException(msg, e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@

package com.sun.enterprise.v3.admin.cluster;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.sun.enterprise.config.serverbeans.Node;
import com.sun.enterprise.util.cluster.RemoteType;
import com.sun.enterprise.util.io.FileUtils;
Expand All @@ -32,6 +30,7 @@
import java.net.URI;
import java.nio.file.Path;

import org.glassfish.cluster.ssh.launcher.SSHException;
import org.glassfish.cluster.ssh.launcher.SSHLauncher;
import org.glassfish.cluster.ssh.launcher.SSHSession;
import org.glassfish.cluster.ssh.sftp.SFTPClient;
Expand All @@ -51,13 +50,12 @@ public abstract class SecureAdminBootstrapHelper implements AutoCloseable {
Path.of("config", "keystore.jks"),
Path.of("config", "cacerts.jks")
};
private static final String[] SECURE_ADMIN_FILE_DIRS_TO_CREATE = new String[] {"config"};
private static final Path[] SECURE_ADMIN_FILE_DIRS_TO_CREATE = new Path[] {Path.of("config")};

/**
* Creates a new helper for delivering files needed for secure admin to the remote instance.
* @param sshL
*
* @param adminHost host or ip address of host which hosts DAS.
* @param sshL
* @param dasInstanceDir directory of the local instance - source for the required files
* @param remoteNodeDir directory of the remote node on the remote system
* @param instance name of the instance on the remote node to bootstrap
Expand Down Expand Up @@ -111,7 +109,7 @@ public static SecureAdminBootstrapHelper getLocalHelper(final File existingInsta
/**
* Cleans up any allocated resources.
*/
protected abstract void mkdirs(String dirURI) throws IOException;
protected abstract void mkdirs(Path dir) throws IOException;

@Override
public void close() {
Expand Down Expand Up @@ -164,7 +162,7 @@ public void bootstrapInstance() throws BootstrapException {
}

private void mkdirs() throws IOException {
for (String dirPath : SECURE_ADMIN_FILE_DIRS_TO_CREATE) {
for (Path dirPath : SECURE_ADMIN_FILE_DIRS_TO_CREATE) {
mkdirs(dirPath);
}
}
Expand Down Expand Up @@ -234,42 +232,33 @@ private SSHHelper(
launcher = sshLauncher;
try {
session = launcher.openSession();
} catch (JSchException e) {
throw new BootstrapException(launcher, e);
} catch (SSHException e) {
throw new BootstrapException(e);
}
try {
ftpClient = session.createSFTPClient();
} catch (JSchException e) {
} catch (SSHException e) {
if (session != null) {
session.close();
}
throw new BootstrapException(launcher, e);
throw new BootstrapException(e);
}
}

@Override
protected void mkdirs(String dir) throws IOException {
Path remoteDir = remoteInstanceDir.resolve(Path.of(dir));
protected void mkdirs(Path dir) throws IOException {
Path remoteDir = remoteInstanceDir.resolve(dir);
LOG.log(Level.DEBUG, "Trying to create directories for remote path {0}", remoteDir);
int instanceDirPermissions;
try {
SftpATTRS attrs = ftpClient.lstat(remoteNodeDir);
if (attrs == null) {
throw new IOException("Remote path " + remoteNodeDir + " does not exist.");
}
instanceDirPermissions = attrs.getPermissions();
} catch (SftpException ex) {
throw new IOException(remoteNodeDir.toString(), ex);
SftpATTRS attrs = ftpClient.lstat(remoteNodeDir);
if (attrs == null) {
throw new IOException("Remote path " + remoteNodeDir + " does not exist.");
}
int instanceDirPermissions = attrs.getPermissions();
LOG.log(Level.DEBUG, "Creating remote bootstrap directory " + remoteDir + " with permissions "
+ Integer.toOctalString(instanceDirPermissions));
try {
ftpClient.mkdirs(remoteDir);
if (launcher.getCapabilities().isChmodSupported()) {
ftpClient.chmod(remoteDir, instanceDirPermissions);
}
} catch (SftpException ex) {
throw new IOException(remoteDir.toString(), ex);
ftpClient.mkdirs(remoteDir);
if (launcher.getCapabilities().isChmodSupported()) {
ftpClient.chmod(remoteDir, instanceDirPermissions);
}
}

Expand All @@ -285,11 +274,7 @@ public void close() {

@Override
void writeToFile(final Path remotePath, final File localFile) throws IOException {
try {
ftpClient.put(localFile, remotePath);
} catch (SftpException ex) {
throw new IOException(ex);
}
ftpClient.put(localFile, remotePath);
}

@Override
Expand All @@ -298,21 +283,17 @@ protected void backdateInstanceDomainXML() throws BootstrapException {
try {
setLastModified(remoteDomainXML, 0);
} catch (IOException ex) {
throw new BootstrapException(launcher, ex);
throw new BootstrapException(ex);
}
LOG.log(Level.DEBUG, "Backdated the instance's copy of domain.xml");
}

/**
* Times over ssh are expressed as seconds since 01 Jan 1970.
*/
@Override
void setLastModified(final Path path, final long when) throws IOException {
/*
* Times over ssh are expressed as seconds since 01 Jan 1970.
*/
try {
ftpClient.setTimeModified(path, when);
} catch (SftpException e) {
throw new IOException(e);
}
ftpClient.setTimeModified(path, when);
}
}

Expand All @@ -329,8 +310,8 @@ private LocalHelper(final File existingInstanceDir, final File newInstanceDir) {
}

@Override
protected void mkdirs(String dir) {
final File newDir = new File(newInstanceDirURI.resolve(dir));
protected void mkdirs(Path dir) {
final File newDir = Path.of(newInstanceDirURI).resolve(dir).toFile();
if (!newDir.exists() && !newDir.mkdirs()) {
throw new RuntimeException(Strings.get("secure.admin.boot.errCreDir", newDir.getAbsolutePath()));
}
Expand All @@ -339,15 +320,15 @@ protected void mkdirs(String dir) {
@Override
public void copyBootstrapFiles() throws IOException {
for (Path relativePathToFile : SECURE_ADMIN_FILE_REL_URIS_TO_COPY) {
final File origin = new File(existingInstanceDirURI.resolve(relativePathToFile.toString()));
final File dest = new File(newInstanceDirURI.resolve(relativePathToFile.toString()));
final File origin = Path.of(existingInstanceDirURI).resolve(relativePathToFile).toFile();
final File dest = Path.of(newInstanceDirURI).resolve(relativePathToFile).toFile();
FileUtils.copy(origin, dest);
}
}

@Override
protected void backdateInstanceDomainXML() throws BootstrapException {
final File newDomainXMLFile = new File(newInstanceDirURI.resolve(DOMAIN_XML_PATH.toString()));
final File newDomainXMLFile = Path.of(newInstanceDirURI).resolve(DOMAIN_XML_PATH).toFile();
if (!newDomainXMLFile.setLastModified(0)) {
throw new RuntimeException(Strings.get("secure.admin.boot.errSetLastMod", newDomainXMLFile.getAbsolutePath()));
}
Expand All @@ -357,10 +338,6 @@ protected void backdateInstanceDomainXML() throws BootstrapException {
public static class BootstrapException extends Exception {
private static final long serialVersionUID = -5488899043810477670L;

public BootstrapException(final SSHLauncher launcher, final Exception ex) {
super(ex.getMessage() + "; SSH settings: " + launcher, ex);
}

public BootstrapException(final String message, final Exception ex) {
super(message + "; Cause: " + ex.getMessage(), ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public final void execute(AdminCommandContext context) {
try {
sshL.setupKey(node, sshpublickeyfile, generatekey, realPass);
} catch (IOException ce) {
logger.log(Level.INFO, "SSH key setup failed: " + ce);
logger.log(Level.INFO, "SSH key setup failed.", ce);
report.setMessage(Strings.get("setup.ssh.failed", ce.getMessage()));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return;
Expand Down
Loading

0 comments on commit 6fc795a

Please sign in to comment.