1 package org
.argeo
.slc
.jsch
;
3 import java
.io
.BufferedReader
;
4 import java
.io
.BufferedWriter
;
6 import java
.io
.FileOutputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
9 import java
.io
.InputStreamReader
;
10 import java
.io
.OutputStream
;
11 import java
.io
.OutputStreamWriter
;
12 import java
.util
.ArrayList
;
13 import java
.util
.HashMap
;
14 import java
.util
.Hashtable
;
15 import java
.util
.List
;
17 import java
.util
.StringTokenizer
;
19 import org
.apache
.commons
.io
.IOUtils
;
20 import org
.apache
.commons
.logging
.Log
;
21 import org
.apache
.commons
.logging
.LogFactory
;
22 import org
.argeo
.slc
.SlcException
;
23 import org
.argeo
.slc
.core
.execution
.ExecutionResources
;
24 import org
.argeo
.slc
.core
.execution
.tasks
.SystemCall
;
25 import org
.springframework
.core
.io
.Resource
;
26 import org
.springframework
.util
.StringUtils
;
28 import com
.jcraft
.jsch
.Channel
;
29 import com
.jcraft
.jsch
.ChannelExec
;
30 import com
.jcraft
.jsch
.ChannelShell
;
31 import com
.jcraft
.jsch
.Session
;
33 public class RemoteExec
extends AbstractJschTask
{
34 private final static Log log
= LogFactory
.getLog(RemoteExec
.class);
36 private Boolean failOnBadExitStatus
= true;
38 private List
<String
> commands
= new ArrayList
<String
>();
39 private String command
;
40 private SystemCall systemCall
;
41 private List
<SystemCall
> systemCalls
= new ArrayList
<SystemCall
>();
42 private Resource script
;
43 private Boolean xForwarding
= false;
44 private Boolean agentForwarding
= false;
45 private Boolean forceShell
= false;
46 private Map
<String
, String
> env
= new HashMap
<String
, String
>();
47 private Resource stdIn
= null;
48 private Resource stdOut
= null;
49 private ExecutionResources executionResources
;
54 * If set, stdout is written to it as a list of lines. Cleared before each
57 private List
<String
> stdOutLines
= null;
58 private Boolean logEvenIfStdOutLines
= false;
59 private Boolean quiet
= false;
64 public RemoteExec(SshTarget sshTarget
, String cmd
) {
65 setSshTarget(sshTarget
);
69 public void run(Session session
) {
70 List
<String
> commandsToUse
= new ArrayList
<String
>(commands
);
71 String commandToUse
= command
;
72 // convert system calls
73 if (systemCall
!= null) {
75 throw new SlcException("Cannot specify command AND systemCall");
76 commandToUse
= convertSystemCall(systemCall
);
79 if (systemCalls
.size() != 0) {
80 if (commandsToUse
.size() != 0)
81 throw new SlcException(
82 "Cannot specify commands AND systemCalls");
83 for (SystemCall systemCall
: systemCalls
)
84 commandsToUse
.add(convertSystemCall(systemCall
));
88 // TODO: simply pass the script as a string command
89 if (commandsToUse
.size() != 0)
90 throw new SlcException("Cannot specify commands and script");
91 BufferedReader reader
= null;
93 reader
= new BufferedReader(new InputStreamReader(script
96 while ((line
= reader
.readLine()) != null) {
97 if (!StringUtils
.hasText(line
))
99 commandsToUse
.add(line
);
101 } catch (IOException e
) {
102 throw new SlcException("Cannot read script " + script
, e
);
104 IOUtils
.closeQuietly(reader
);
109 // for the time being do not interpret both \n and ;
111 // until we know how to parse ; within ""
112 if (commandToUse
.indexOf('\n') >= 0) {
113 StringTokenizer st
= new StringTokenizer(commandToUse
, "\n");
114 while (st
.hasMoreTokens()) {
115 String cmd
= st
.nextToken();
116 commandsToUse
.add(cmd
);
118 } else if (commandToUse
.indexOf(';') >= 0) {
119 StringTokenizer st
= new StringTokenizer(commandToUse
, ";");
120 while (st
.hasMoreTokens()) {
121 String cmd
= st
.nextToken();
122 commandsToUse
.add(cmd
);
125 commandsToUse
.add(commandToUse
);
132 if (commandsToUse
.size() > 0) {
133 commandsToUse
.add(0, "su - " + user
);
134 commandsToUse
.add("exit");
136 if (command
.indexOf('\"') >= 0)
137 throw new SlcException(
138 "Don't know how to su a command with \", use shell instead.");
139 commandToUse
= "su - " + user
+ " -c \"" + command
+ "\"";
143 // execute command(s)
144 if (commandToUse
!= null) {
145 if (commandsToUse
.size() != 0)
146 throw new SlcException(
147 "Specify either a single command or a list of commands.");
148 remoteExec(session
, commandToUse
);
150 if (commandsToUse
.size() == 0)
151 throw new SlcException(
152 "Neither a single command or a list of commands has been specified.");
154 remoteExec(session
, commandsToUse
, script
!= null ?
"script "
155 + script
.getFilename() : commandsToUse
.size() + " commands");
159 protected String
convertSystemCall(SystemCall systemCall
) {
160 // TODO: prepend environment variables
161 // TODO: deal with exec dir
162 return systemCall
.asCommand();
165 protected void remoteExec(Session session
, final List
<String
> commands
,
166 String description
) {
168 final ChannelShell channel
= (ChannelShell
) session
169 .openChannel("shell");
170 channel
.setInputStream(null);
171 channel
.setXForwarding(xForwarding
);
172 channel
.setAgentForwarding(agentForwarding
);
173 channel
.setEnv(new Hashtable
<String
, String
>(env
));
176 * // Choose the pty-type "vt102".
177 * ((ChannelShell)channel).setPtyType("vt102");
180 final BufferedWriter writer
= new BufferedWriter(
181 new OutputStreamWriter(channel
.getOutputStream()));
183 if (log
.isDebugEnabled())
184 log
.debug("Run " + description
+ " on " + getSshTarget()
188 // write commands to shell
189 Thread writerThread
= new Thread("Shell writer " + getSshTarget()) {
193 for (String line
: commands
) {
194 if (!StringUtils
.hasText(line
))
199 writer
.append("exit");
202 // channel.disconnect();
203 } catch (IOException e
) {
204 throw new SlcException("Cannot write to shell on "
205 + getSshTarget(), e
);
207 IOUtils
.closeQuietly(writer
);
211 writerThread
.start();
214 checkExitStatus(channel
);
215 channel
.disconnect();
217 } catch (Exception e
) {
218 throw new SlcException("Cannot use SSH shell on " + getSshTarget(),
224 protected void remoteExec(Session session
, String command
) {
226 final ChannelExec channel
= (ChannelExec
) session
227 .openChannel("exec");
228 channel
.setCommand(command
);
230 channel
.setInputStream(null);
231 channel
.setXForwarding(xForwarding
);
232 channel
.setAgentForwarding(agentForwarding
);
233 channel
.setEnv(new Hashtable
<String
, String
>(env
));
234 channel
.setErrStream(null);
239 if (log
.isDebugEnabled())
240 log
.debug("Run '" + command
+ "' on " + getSshTarget() + "...");
244 Thread stdInThread
= new Thread("Stdin " + getSshTarget()) {
247 OutputStream out
= null;
249 out
= channel
.getOutputStream();
250 IOUtils
.copy(stdIn
.getInputStream(), out
);
251 } catch (IOException e
) {
252 throw new SlcException("Cannot write stdin on "
253 + getSshTarget(), e
);
255 IOUtils
.closeQuietly(out
);
262 checkExitStatus(channel
);
263 channel
.disconnect();
264 } catch (Exception e
) {
265 throw new SlcException("Cannot execute remotely '" + command
266 + "' on " + getSshTarget(), e
);
270 protected void readStdErr(final ChannelExec channel
) {
271 new Thread("stderr " + getSshTarget()) {
273 BufferedReader stdErr
= null;
275 InputStream in
= channel
.getErrStream();
276 stdErr
= new BufferedReader(new InputStreamReader(in
));
278 while ((line
= stdErr
.readLine()) != null) {
279 if (!line
.trim().equals(""))
282 } catch (IOException e
) {
283 if (log
.isDebugEnabled())
284 log
.error("Cannot read stderr from " + getSshTarget(),
287 IOUtils
.closeQuietly(stdErr
);
293 protected void readStdOut(Channel channel
) {
294 if (stdOut
!= null) {
295 OutputStream localStdOut
= createOutputStream(stdOut
);
297 IOUtils
.copy(channel
.getInputStream(), localStdOut
);
298 } catch (IOException e
) {
299 throw new SlcException("Cannot redirect stdout", e
);
301 IOUtils
.closeQuietly(localStdOut
);
304 BufferedReader stdOut
= null;
306 InputStream in
= channel
.getInputStream();
307 stdOut
= new BufferedReader(new InputStreamReader(in
));
309 while ((line
= stdOut
.readLine()) != null) {
310 if (!line
.trim().equals("")) {
312 if (stdOutLines
!= null) {
313 stdOutLines
.add(line
);
314 if (logEvenIfStdOutLines
&& !quiet
)
322 } catch (IOException e
) {
323 if (log
.isDebugEnabled())
324 log
.error("Cannot read stdout from " + getSshTarget(), e
);
326 IOUtils
.closeQuietly(stdOut
);
331 protected void checkExitStatus(Channel channel
) {
332 if (channel
.isClosed()) {
333 int exitStatus
= channel
.getExitStatus();
334 if (exitStatus
== 0) {
335 if (log
.isTraceEnabled())
336 log
.trace("Remote execution exit status: " + exitStatus
);
338 String msg
= "Remote execution failed with " + " exit status: "
340 if (failOnBadExitStatus
)
341 throw new SlcException(msg
);
349 protected OutputStream
createOutputStream(Resource target
) {
350 FileOutputStream out
= null;
354 if (executionResources
!= null)
355 file
= new File(executionResources
.getAsOsPath(target
, true));
357 file
= target
.getFile();
358 out
= new FileOutputStream(file
, false);
359 } catch (IOException e
) {
360 log
.error("Cannot get file for " + target
, e
);
361 IOUtils
.closeQuietly(out
);
366 public void setCommand(String command
) {
367 this.command
= command
;
370 public void setCommands(List
<String
> commands
) {
371 this.commands
= commands
;
374 public void setFailOnBadExitStatus(Boolean failOnBadExitStatus
) {
375 this.failOnBadExitStatus
= failOnBadExitStatus
;
378 public void setSystemCall(SystemCall systemCall
) {
379 this.systemCall
= systemCall
;
382 public void setSystemCalls(List
<SystemCall
> systemCalls
) {
383 this.systemCalls
= systemCalls
;
386 public void setScript(Resource script
) {
387 this.script
= script
;
390 public void setxForwarding(Boolean xForwarding
) {
391 this.xForwarding
= xForwarding
;
394 public void setAgentForwarding(Boolean agentForwarding
) {
395 this.agentForwarding
= agentForwarding
;
398 public void setEnv(Map
<String
, String
> env
) {
402 public void setForceShell(Boolean forceShell
) {
403 this.forceShell
= forceShell
;
406 public List
<String
> getCommands() {
410 public void setStdOutLines(List
<String
> stdOutLines
) {
411 this.stdOutLines
= stdOutLines
;
414 public void setLogEvenIfStdOutLines(Boolean logEvenIfStdOutLines
) {
415 this.logEvenIfStdOutLines
= logEvenIfStdOutLines
;
418 public void setQuiet(Boolean quiet
) {
422 public void setStdIn(Resource stdIn
) {
426 public void setStdOut(Resource stdOut
) {
427 this.stdOut
= stdOut
;
430 public void setExecutionResources(ExecutionResources executionResources
) {
431 this.executionResources
= executionResources
;
434 public void setUser(String user
) {