tmf/lttng: Update 2014 copyrights
[deliverable/tracecompass.git] / org.eclipse.linuxtools.lttng2.ui / src / org / eclipse / linuxtools / internal / lttng2 / ui / views / control / remote / CommandShell.java
1 /**********************************************************************
2 * Copyright (c) 2012, 2014 Ericsson
3 *
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
8 *
9 * Contributors:
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;
14
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;
27
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;
36
37 /**
38 * <p>
39 * Implementation of remote command execution using RSE's shell service.
40 * </p>
41 *
42 * @author Patrick Tasse
43 * @author Bernd Hufmann
44 */
45 public class CommandShell implements ICommandShell {
46
47 // ------------------------------------------------------------------------
48 // Constants
49 // ------------------------------------------------------------------------
50
51 /** Sub-string to be echo'ed when running command in shell, used to indicate that the command has finished running */
52 public static final String DONE_MARKUP_STRING = "--RSE:donedonedone:--"; //$NON-NLS-1$
53
54 /** Sub-string to be echoed when running a command in shell. */
55 public static final String BEGIN_END_TAG = "BEGIN-END-TAG:"; //$NON-NLS-1$
56
57 /** Command delimiter for shell */
58 public static final String CMD_DELIMITER = "\n"; //$NON-NLS-1$
59
60 /** Shell "echo" command */
61 public static final String SHELL_ECHO_CMD = " echo "; //$NON-NLS-1$
62
63 /** Default command separator */
64 public static final char CMD_SEPARATOR = ';';
65
66 // ------------------------------------------------------------------------
67 // Attributes
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;
77
78 // ------------------------------------------------------------------------
79 // Constructors
80 // ------------------------------------------------------------------------
81
82 /**
83 * Create a new command shell
84 *
85 * @param proxy
86 * The RSE proxy for this shell
87 */
88 public CommandShell(IRemoteSystemProxy proxy) {
89 fProxy = proxy;
90 }
91
92 // ------------------------------------------------------------------------
93 // Operations
94 // ------------------------------------------------------------------------
95
96 @Override
97 public void connect() throws ExecutionException {
98 IShellService shellService = fProxy.getShellService();
99 Process p = null;
100 try {
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);
105 }
106 fInputBufferReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
107 fErrorBufferReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
108 fIsConnected = true;
109 }
110
111 @Override
112 public void disconnect() {
113 fIsConnected = false;
114 try {
115 fInputBufferReader.close();
116 fErrorBufferReader.close();
117 } catch (IOException e) {
118 // ignore
119 }
120 }
121
122 @Override
123 public ICommandResult executeCommand(String command, IProgressMonitor monitor) throws ExecutionException {
124 return executeCommand(command, monitor, true);
125 }
126
127 @Override
128 public ICommandResult executeCommand(final String command, final IProgressMonitor monitor, final boolean checkReturnValue) throws ExecutionException {
129 if (fIsConnected) {
130 FutureTask<CommandResult> future = new FutureTask<>(new Callable<CommandResult>() {
131 @Override
132 public CommandResult call() throws IOException, CancellationException {
133 final ArrayList<String> result = new ArrayList<>();
134
135 synchronized (fHostShell) {
136 // Initialize return value which will be updated in isAliasEchoResult()
137 fReturnValue = 0;
138
139 int startAlias = fRandom.nextInt();
140 int endAlias = fRandom.nextInt();
141 fHostShell.writeToShell(formatShellCommand(command, startAlias, endAlias));
142
143 String nextLine;
144 boolean isStartFound = false;
145 while ((nextLine = fInputBufferReader.readLine()) != null) {
146
147 if (monitor.isCanceled()) {
148 flushInput();
149 throw new CancellationException();
150 }
151
152 // check if line contains echoed start alias
153 if (isAliasEchoResult(nextLine, startAlias, true)) {
154 isStartFound = true;
155 continue;
156 }
157
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)) {
161 break;
162 }
163
164 // Ignore line if
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
168 if (!isStartFound ||
169 isCommandEcho(nextLine, command) ||
170 nextLine.contains(getEchoResult(endAlias)))
171 {
172 continue;
173 }
174
175 // Now it's time add to the result
176 result.add(nextLine);
177 }
178
179 // Read any left over output
180 flushInput();
181
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);
187 }
188 }
189 }
190 }
191 return new CommandResult(fReturnValue, result.toArray(new String[result.size()]));
192 }
193 });
194
195 fExecutor.execute(future);
196
197 try {
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);
205 }
206 }
207 throw new ExecutionException(Messages.TraceControl_ShellNotConnected, null);
208 }
209
210 // ------------------------------------------------------------------------
211 // Helper methods
212 // ------------------------------------------------------------------------
213 /**
214 * Flushes the buffer reader
215 * @throws IOException
216 */
217 private void flushInput() throws IOException {
218 char[] cbuf = new char[1];
219 while (fInputBufferReader.ready()) {
220 if (fInputBufferReader.read(cbuf, 0, 1) == -1) {
221 break;
222 }
223 }
224 }
225
226 /**
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.
230 *
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
235 */
236 private static String formatShellCommand(String cmd, int startAlias, int endAlias) {
237 if (cmd == null || cmd.equals("")) { //$NON-NLS-1$
238 return cmd;
239 }
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();
250 }
251
252 /**
253 * Creates a echo command line in the format: echo <start tag> <alias> <end tag> $?
254 *
255 * @param alias The command alias integer to be included in the echoed message.
256 * @return the echo command line
257 */
258 private static String getEchoCmd(int alias) {
259 return SHELL_ECHO_CMD + getEchoResult(alias) + "$?"; //$NON-NLS-1$
260 }
261
262 /**
263 * Creates the expected result for a given command alias:
264 * <start tag> <alias> <end tag> $?
265 *
266 * @param alias The command alias integer to be included in the echoed message.
267 * @return the expected echo result
268 */
269 private static String getEchoResult(int alias) {
270 return BEGIN_END_TAG + String.valueOf(alias) + DONE_MARKUP_STRING;
271 }
272
273 /**
274 * Verifies if given command line contains a command alias echo result.
275 *
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>
280 */
281 private boolean isAliasEchoResult(String line, int alias, boolean checkReturnValue) {
282 String expected = getEchoResult(alias);
283 if (line.startsWith(expected)) {
284 if (!checkReturnValue) {
285 try {
286 int k = Integer.valueOf(line.substring(expected.length()));
287 fReturnValue = k;
288 } catch (NumberFormatException e) {
289 // do nothing
290 }
291 }
292 return true;
293 }
294 int index = line.indexOf(expected);
295 if ((index > 0) && (line.indexOf(SHELL_ECHO_CMD) == -1)) {
296 return true;
297 }
298
299 return false;
300 }
301
302 /**
303 * Verifies if output line is an echo of the given command line. If the
304 * output line is longer then the maximum line lengths (e.g. for ssh), the
305 * shell adds a line break character. This method takes this in
306 * consideration by comparing the command line without any whitespaces.
307 *
308 * @param line
309 * The output line to verify
310 * @param cmd
311 * The command executed
312 * @return <code>true</code> if it's an echoed command line else
313 * <code>false</code>
314 */
315 @SuppressWarnings("nls")
316 private static boolean isCommandEcho(String line, String cmd) {
317 String s1 = line.replaceAll("\\s","");
318 String s2 = cmd.replaceAll("\\s","");
319 s2 = s2.replaceAll("(\\*)", "(\\\\*)");
320 String patternStr = ".*(" + s2 +")$";
321 return s1.matches(patternStr);
322 }
323 }
This page took 0.056744 seconds and 6 git commands to generate.