Skip to content

Commit

Permalink
[Bug] Close SSH session after remote shell finish (#15348)
Browse files Browse the repository at this point in the history
* Close SSH session after remote shell finish

---------

Co-authored-by: David Zollo <[email protected]>
  • Loading branch information
ruanwenjun and davidzollo authored Dec 25, 2023
1 parent b73194b commit 9212531
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.config.keys.loader.KeyPairResourceLoader;
import org.apache.sshd.common.session.SessionHeartbeatController;
import org.apache.sshd.common.util.security.SecurityUtils;

import java.security.KeyPair;
import java.time.Duration;
import java.util.Collection;

public class SSHUtils {
Expand Down Expand Up @@ -57,6 +59,7 @@ public static ClientSession getSession(SshClient client, SSHConnectionParam conn
throw new Exception("Failed to add public key identity", e);
}
}
session.setSessionHeartbeat(SessionHeartbeatController.HeartbeatType.RESERVED, Duration.ofSeconds(3));
return session;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,21 @@
import java.util.HashMap;
import java.util.Map;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RemoteExecutor {
public class RemoteExecutor implements AutoCloseable {

static final String REMOTE_SHELL_HOME = "/tmp/dolphinscheduler-remote-shell-%s/";
static final String STATUS_TAG_MESSAGE = "DOLPHINSCHEDULER-REMOTE-SHELL-TASK-STATUS-";
static final int TRACK_INTERVAL = 5000;

protected Map<String, String> taskOutputParams = new HashMap<>();

SshClient sshClient;
ClientSession session;
SSHConnectionParam sshConnectionParam;
private SshClient sshClient;
private ClientSession session;
private SSHConnectionParam sshConnectionParam;

public RemoteExecutor(SSHConnectionParam sshConnectionParam) {

Expand Down Expand Up @@ -205,6 +206,18 @@ private String getRemoteShellHome() {
return String.format(REMOTE_SHELL_HOME, sshConnectionParam.getUser());
}

@SneakyThrows
@Override
public void close() {
if (session != null && session.isOpen()) {
session.close();
}
if (sshClient != null && sshClient.isStarted()) {
sshClient.close();
}

}

static class COMMAND {

private COMMAND() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ public void init() {

@Override
public void handle(TaskCallBack taskCallBack) throws TaskException {
try {
// add task close method to release resource
try (RemoteExecutor executor = remoteExecutor) {
// construct process
String localFile = buildCommand();
int exitCode = remoteExecutor.run(taskId, localFile);
Expand Down

0 comments on commit 9212531

Please sign in to comment.