Skip to content
Advertisement

Jsch running a remote jar with combined tail command is not working properly

I am trying to run a number of standalone spring boot jars on a remote linux server(on different ports) over SSH with JSch. I use tail on my command, because i need tomcat server logs. When i start service that runs standalone jars, some jars is not running.

Here is a sample script that i use to run standalone jars :

nohup java -jar foo.jar –server.port=10000 > log.txt 2> errors.txt & tail -f log.txt

and here is my code :

StringBuilder sb = new StringBuilder();
Session session = null;
ChannelExec channel = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
    String command1 = "nohup java -jar " + jarFileDir + "/" + jarFileName + " --server.port=" + port
            + " > " + jarFileDir + "/log.txt 2> " + jarFileDir + "/errors.txt & tail -f " + jarFileDir + "/log.txt";

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    session = jsch.getSession(username, ip, port);
    session.setPassword(password);
    session.setConfig(config);
    session.connect();

    channel = (ChannelExec)session.openChannel("exec");
    channel.setPty(true);
    isr = new InputStreamReader(channel.getInputStream());
    br = new BufferedReader(isr);
    channel.setCommand(command1);
    channel.connect();

    String msg;
    while ((msg = br.readLine()) != null) {
        //jar logs is being readed and processed here
    }

} catch (Exception e) {
    //handle exception
} finally {
    //close all the connections
    if (br != null) br.close();
    if (isr != null) isr.close();
    if (channel != null) channel.disconnect();
    if (session != null) session.disconnect();
}

And the logs about issue is here :

tail: cannot open ‘log.txt’ for reading: No such file or directory tail: no files remaining

Advertisement

Answer

nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt & tail -f log.txt

You’re running two separate commands here:

nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt
tail -f log.txt

This has a race condition. The second command could start up and try to open log.txt before the first command has a chance to create the file.

The fix is to make sure log.txt is created before starting the tail command. You could do this:

touch log.txt
nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt &
tail -f log.txt

Or as one line:

touch log.txt; nohup java etc... & tail -f log.txt
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement