1 /**********************************************************************
2 * Copyright (c) 2012, 2013 Ericsson
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Patrick Tasse - Initial API and implementation
11 * Bernd Hufmann - Updated using Executor Framework
12 **********************************************************************/
13 package org
.eclipse
.linuxtools
.internal
.lttng2
.ui
.views
.control
.remote
;
15 import java
.io
.BufferedReader
;
16 import java
.io
.IOException
;
17 import java
.io
.InputStreamReader
;
18 import java
.util
.ArrayList
;
19 import java
.util
.Random
;
20 import java
.util
.concurrent
.Callable
;
21 import java
.util
.concurrent
.CancellationException
;
22 import java
.util
.concurrent
.ExecutorService
;
23 import java
.util
.concurrent
.Executors
;
24 import java
.util
.concurrent
.FutureTask
;
25 import java
.util
.concurrent
.TimeUnit
;
26 import java
.util
.concurrent
.TimeoutException
;
28 import org
.eclipse
.core
.commands
.ExecutionException
;
29 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
30 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
31 import org
.eclipse
.linuxtools
.internal
.lttng2
.ui
.views
.control
.messages
.Messages
;
32 import org
.eclipse
.linuxtools
.internal
.lttng2
.ui
.views
.control
.preferences
.ControlPreferences
;
33 import org
.eclipse
.rse
.services
.shells
.HostShellProcessAdapter
;
34 import org
.eclipse
.rse
.services
.shells
.IHostShell
;
35 import org
.eclipse
.rse
.services
.shells
.IShellService
;
39 * Implementation of remote command execution using RSE's shell service.
42 * @author Patrick Tasse
43 * @author Bernd Hufmann
45 public class CommandShell
implements ICommandShell
{
47 // ------------------------------------------------------------------------
49 // ------------------------------------------------------------------------
51 /** Sub-string to be echo'ed when running command in shell, used to indicate that the command has finished running */
52 public final static String DONE_MARKUP_STRING
= "--RSE:donedonedone:--"; //$NON-NLS-1$
54 /** Sub-string to be echoed when running a command in shell. */
55 public final static String BEGIN_END_TAG
= "BEGIN-END-TAG:"; //$NON-NLS-1$
57 /** Command delimiter for shell */
58 public final static String CMD_DELIMITER
= "\n"; //$NON-NLS-1$
60 /** Shell "echo" command */
61 public final static String SHELL_ECHO_CMD
= " echo "; //$NON-NLS-1$
63 /** Default command separator */
64 public final static char CMD_SEPARATOR
= ';';
66 // ------------------------------------------------------------------------
68 // ------------------------------------------------------------------------
69 private IRemoteSystemProxy fProxy
= null;
70 private IHostShell fHostShell
= null;
71 private BufferedReader fInputBufferReader
= null;
72 private BufferedReader fErrorBufferReader
= null;
73 private final ExecutorService fExecutor
= Executors
.newFixedThreadPool(1);
74 private boolean fIsConnected
= false;
75 private final Random fRandom
= new Random(System
.currentTimeMillis());
76 private int fReturnValue
;
78 // ------------------------------------------------------------------------
80 // ------------------------------------------------------------------------
83 * Create a new command shell
86 * The RSE proxy for this shell
88 public CommandShell(IRemoteSystemProxy proxy
) {
92 // ------------------------------------------------------------------------
94 // ------------------------------------------------------------------------
97 public void connect() throws ExecutionException
{
98 IShellService shellService
= fProxy
.getShellService();
101 fHostShell
= shellService
.launchShell("", new String
[0], new NullProgressMonitor()); //$NON-NLS-1$
102 p
= new HostShellProcessAdapter(fHostShell
);
103 } catch (Exception e
) {
104 throw new ExecutionException(Messages
.TraceControl_CommandShellError
, e
);
106 fInputBufferReader
= new BufferedReader(new InputStreamReader(p
.getInputStream()));
107 fErrorBufferReader
= new BufferedReader(new InputStreamReader(p
.getErrorStream()));
112 public void disconnect() {
113 fIsConnected
= false;
115 fInputBufferReader
.close();
116 fErrorBufferReader
.close();
117 } catch (IOException e
) {
123 public ICommandResult
executeCommand(String command
, IProgressMonitor monitor
) throws ExecutionException
{
124 return executeCommand(command
, monitor
, true);
128 public ICommandResult
executeCommand(final String command
, final IProgressMonitor monitor
, final boolean checkReturnValue
) throws ExecutionException
{
130 FutureTask
<CommandResult
> future
= new FutureTask
<CommandResult
>(new Callable
<CommandResult
>() {
132 public CommandResult
call() throws IOException
, CancellationException
{
133 final ArrayList
<String
> result
= new ArrayList
<String
>();
135 synchronized (fHostShell
) {
136 // Initialize return value which will be updated in isAliasEchoResult()
139 int startAlias
= fRandom
.nextInt();
140 int endAlias
= fRandom
.nextInt();
141 fHostShell
.writeToShell(formatShellCommand(command
, startAlias
, endAlias
));
144 boolean isStartFound
= false;
145 while ((nextLine
= fInputBufferReader
.readLine()) != null) {
147 if (monitor
.isCanceled()) {
149 throw new CancellationException();
152 // check if line contains echoed start alias
153 if (isAliasEchoResult(nextLine
, startAlias
, true)) {
158 // check if line contains is the end mark-up. This will retrieve also
159 // the return value of the actual command.
160 if (isAliasEchoResult(nextLine
, endAlias
, false)) {
165 // 1) start hasn't been found or
166 // 2) line is an echo of the command or
167 // 3) line is an echo of the end mark-up
169 isCommandEcho(nextLine
, command
) ||
170 nextLine
.contains(getEchoResult(endAlias
)))
175 // Now it's time add to the result
176 result
.add(nextLine
);
179 // Read any left over output
182 // Read error stream output when command failed.
183 if (fReturnValue
!= 0) {
184 while(fErrorBufferReader
.ready()) {
185 if ((nextLine
= fErrorBufferReader
.readLine()) != null) {
186 result
.add(nextLine
);
191 return new CommandResult(fReturnValue
, result
.toArray(new String
[result
.size()]));
195 fExecutor
.execute(future
);
198 return future
.get(ControlPreferences
.getInstance().getCommandTimeout(), TimeUnit
.SECONDS
);
199 } catch (java
.util
.concurrent
.ExecutionException ex
) {
200 throw new ExecutionException(Messages
.TraceControl_ExecutionFailure
, ex
);
201 } catch (InterruptedException ex
) {
202 throw new ExecutionException(Messages
.TraceControl_ExecutionCancelled
, ex
);
203 } catch (TimeoutException ex
) {
204 throw new ExecutionException(Messages
.TraceControl_ExecutionTimeout
, ex
);
207 throw new ExecutionException(Messages
.TraceControl_ShellNotConnected
, null);
210 // ------------------------------------------------------------------------
212 // ------------------------------------------------------------------------
214 * Flushes the buffer reader
215 * @throws IOException
217 private void flushInput() throws IOException
{
218 char[] cbuf
= new char[1];
219 while (fInputBufferReader
.ready()) {
220 if (fInputBufferReader
.read(cbuf
, 0, 1) == -1) {
227 * Format the command to be sent into the shell command with start and end marker strings.
228 * The start marker is need to know when the actual command output starts. The end marker
229 * string is needed so we can tell that end of output has been reached.
231 * @param cmd The actual command
232 * @param startAlias The command alias for start marker
233 * @param endAlias The command alias for end marker
234 * @return formatted command string
236 private static String
formatShellCommand(String cmd
, int startAlias
, int endAlias
) {
237 if (cmd
== null || cmd
.equals("")) { //$NON-NLS-1$
240 StringBuffer formattedCommand
= new StringBuffer();
241 // Make multi-line command.
242 // Wrap actual command with start marker and end marker to wrap actual command.
243 formattedCommand
.append(getEchoCmd(startAlias
));
244 formattedCommand
.append(CMD_DELIMITER
);
245 formattedCommand
.append(cmd
);
246 formattedCommand
.append(CMD_DELIMITER
);
247 formattedCommand
.append(getEchoCmd(endAlias
));
248 formattedCommand
.append(CMD_DELIMITER
);
249 return formattedCommand
.toString();
253 * Creates a echo command line in the format: echo <start tag> <alias> <end tag> $?
255 * @param alias The command alias integer to be included in the echoed message.
256 * @return the echo command line
258 private static String
getEchoCmd(int alias
) {
259 return SHELL_ECHO_CMD
+ getEchoResult(alias
) + "$?"; //$NON-NLS-1$
263 * Creates the expected result for a given command alias:
264 * <start tag> <alias> <end tag> $?
266 * @param alias The command alias integer to be included in the echoed message.
267 * @return the expected echo result
269 private static String
getEchoResult(int alias
) {
270 return BEGIN_END_TAG
+ String
.valueOf(alias
) + DONE_MARKUP_STRING
;
274 * Verifies if given command line contains a command alias echo result.
276 * @param line The output line to test.
277 * @param alias The command alias
278 * @param checkReturnValue <code>true</code> to retrieve command result (previous command) <code>false</code>
279 * @return <code>true</code> if output line is a command alias echo result else <code>false</code>
281 private boolean isAliasEchoResult(String line
, int alias
, boolean checkReturnValue
) {
282 String expected
= getEchoResult(alias
);
283 if (line
.startsWith(expected
)) {
284 if (!checkReturnValue
) {
286 int k
= Integer
.valueOf(line
.substring(expected
.length()));
288 } catch (NumberFormatException e
) {
294 int index
= line
.indexOf(expected
);
296 if (line
.indexOf(SHELL_ECHO_CMD
) == -1) {
305 * Verifies if output line is an echo of the given command line. If the
306 * output line is longer then the maximum line lengths (e.g. for ssh), the
307 * shell adds a line break character. This method takes this in
308 * consideration by comparing the command line without any whitespaces.
311 * The output line to verify
313 * The command executed
314 * @return <code>true</code> if it's an echoed command line else
317 @SuppressWarnings("nls")
318 private static boolean isCommandEcho(String line
, String cmd
) {
319 String s1
= line
.replaceAll("\\s","");
320 String s2
= cmd
.replaceAll("\\s","");
321 s2
= s2
.replaceAll("(\\*)", "(\\\\*)");
322 String patternStr
= ".*(" + s2
+")$";
323 return s1
.matches(patternStr
);