lttng: Fix most compiler warnings as per the new settings
[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 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.rse.services.shells.HostShellProcessAdapter;
33 import org.eclipse.rse.services.shells.IHostShell;
34 import org.eclipse.rse.services.shells.IShellService;
35
36 /**
37 * <p>
38 * Implementation of remote command execution using RSE's shell service.
39 * </p>
40 *
41 * @author Patrick Tasse
42 * @author Bernd Hufmann
43 */
44 public class CommandShell implements ICommandShell {
45
46 // ------------------------------------------------------------------------
47 // Constants
48 // ------------------------------------------------------------------------
49
50 /** Sub-string to be echo'ed when running command in shell, used to indicate that the command has finished running */
51 public final static String DONE_MARKUP_STRING = "--RSE:donedonedone:--"; //$NON-NLS-1$
52
53 /** Sub-string to be echoed when running a command in shell. */
54 public final static String BEGIN_END_TAG = "BEGIN-END-TAG:"; //$NON-NLS-1$
55
56 /** Command delimiter for shell */
57 public final static String CMD_DELIMITER = "\n"; //$NON-NLS-1$
58
59 /** Shell "echo" command */
60 public final static String SHELL_ECHO_CMD = " echo "; //$NON-NLS-1$
61
62 /** Default command separator */
63 public final static char CMD_SEPARATOR = ';';
64
65 /** Default timeout value used for executing commands, in milliseconds */
66 private final static int DEFAULT_TIMEOUT_VALUE = 15000;
67
68 // ------------------------------------------------------------------------
69 // Attributes
70 // ------------------------------------------------------------------------
71 private IRemoteSystemProxy fProxy = null;
72 private IHostShell fHostShell = null;
73 private BufferedReader fInputBufferReader = null;
74 private BufferedReader fErrorBufferReader = null;
75 private final ExecutorService fExecutor = Executors.newFixedThreadPool(1);
76 private boolean fIsConnected = false;
77 private final Random fRandom = new Random(System.currentTimeMillis());
78 private int fReturnValue;
79
80 // ------------------------------------------------------------------------
81 // Constructors
82 // ------------------------------------------------------------------------
83
84 /**
85 * Create a new command shell
86 *
87 * @param proxy
88 * The RSE proxy for this shell
89 */
90 public CommandShell(IRemoteSystemProxy proxy) {
91 fProxy = proxy;
92 }
93
94 // ------------------------------------------------------------------------
95 // Operations
96 // ------------------------------------------------------------------------
97 /*
98 * (non-Javadoc)
99 * @see org.eclipse.linuxtools.internal.lttng2.ui.views.control.service.ICommandShell#connect()
100 */
101 @Override
102 public void connect() throws ExecutionException {
103 IShellService shellService = fProxy.getShellService();
104 Process p = null;
105 try {
106 fHostShell = shellService.launchShell("", new String[0], new NullProgressMonitor()); //$NON-NLS-1$
107 p = new HostShellProcessAdapter(fHostShell);
108 } catch (Exception e) {
109 throw new ExecutionException(Messages.TraceControl_CommandShellError, e);
110 }
111 fInputBufferReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
112 fErrorBufferReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
113 fIsConnected = true;
114 }
115
116 /*
117 * (non-Javadoc)
118 * @see org.eclipse.linuxtools.internal.lttng2.ui.views.control.service.ICommandShell#disconnect()
119 */
120 @Override
121 public void disconnect() {
122 fIsConnected = false;
123 try {
124 fInputBufferReader.close();
125 fErrorBufferReader.close();
126 } catch (IOException e) {
127 // ignore
128 }
129 }
130
131 /*
132 * (non-Javadoc)
133 * @see org.eclipse.linuxtools.internal.lttng2.ui.views.control.service.ICommandShell#executeCommand(java.lang.String, org.eclipse.core.runtime.IProgressMonitor)
134 */
135 @Override
136 public ICommandResult executeCommand(String command, IProgressMonitor monitor) throws ExecutionException {
137 return executeCommand(command, monitor, true);
138 }
139
140 /*
141 * (non-Javadoc)
142 * @see org.eclipse.linuxtools.internal.lttng2.ui.views.control.service.ICommandShell#executeCommand(java.lang.String, org.eclipse.core.runtime.IProgressMonitor, boolean)
143 */
144 @Override
145 public ICommandResult executeCommand(final String command, final IProgressMonitor monitor, final boolean checkReturnValue) throws ExecutionException {
146 if (fIsConnected) {
147 FutureTask<CommandResult> future = new FutureTask<CommandResult>(new Callable<CommandResult>() {
148 @Override
149 public CommandResult call() throws IOException, CancellationException {
150 final ArrayList<String> result = new ArrayList<String>();
151
152 synchronized (fHostShell) {
153 // Initialize return value which will be updated in isAliasEchoResult()
154 fReturnValue = 0;
155
156 int startAlias = fRandom.nextInt();
157 int endAlias = fRandom.nextInt();
158 fHostShell.writeToShell(formatShellCommand(command, startAlias, endAlias));
159
160 String nextLine;
161 boolean isStartFound = false;
162 while ((nextLine = fInputBufferReader.readLine()) != null) {
163
164 if (monitor.isCanceled()) {
165 flushInput();
166 throw new CancellationException();
167 }
168
169 // check if line contains echoed start alias
170 if (isAliasEchoResult(nextLine, startAlias, true)) {
171 isStartFound = true;
172 continue;
173 }
174
175 // check if line contains is the end mark-up. This will retrieve also
176 // the return value of the actual command.
177 if (isAliasEchoResult(nextLine, endAlias, false)) {
178 break;
179 }
180
181 // Ignore line if
182 // 1) start hasn't been found or
183 // 2) line is an echo of the command or
184 // 3) line is an echo of the end mark-up
185 if (!isStartFound ||
186 isCommandEcho(nextLine, command) ||
187 nextLine.contains(getEchoResult(endAlias)))
188 {
189 continue;
190 }
191
192 // Now it's time add to the result
193 result.add(nextLine);
194 }
195
196 // Read any left over output
197 flushInput();
198
199 // Read error stream output when command failed.
200 if (fReturnValue != 0) {
201 while(fErrorBufferReader.ready()) {
202 if ((nextLine = fErrorBufferReader.readLine()) != null) {
203 result.add(nextLine);
204 }
205 }
206 }
207 }
208 return new CommandResult(fReturnValue, result.toArray(new String[result.size()]));
209 }
210 });
211
212 fExecutor.execute(future);
213
214 try {
215 return future.get(DEFAULT_TIMEOUT_VALUE, TimeUnit.MILLISECONDS);
216 } catch (java.util.concurrent.ExecutionException ex) {
217 throw new ExecutionException(Messages.TraceControl_ExecutionFailure, ex);
218 } catch (InterruptedException ex) {
219 throw new ExecutionException(Messages.TraceControl_ExecutionCancelled, ex);
220 } catch (TimeoutException ex) {
221 throw new ExecutionException(Messages.TraceControl_ExecutionTimeout, ex);
222 }
223 }
224 throw new ExecutionException(Messages.TraceControl_ShellNotConnected, null);
225 }
226
227 // ------------------------------------------------------------------------
228 // Helper methods
229 // ------------------------------------------------------------------------
230 /**
231 * Flushes the buffer reader
232 * @throws IOException
233 */
234 private void flushInput() throws IOException {
235 char[] cbuf = new char[1];
236 while (fInputBufferReader.ready()) {
237 if (fInputBufferReader.read(cbuf, 0, 1) == -1) {
238 break;
239 }
240 }
241 }
242
243 /**
244 * Format the command to be sent into the shell command with start and end marker strings.
245 * The start marker is need to know when the actual command output starts. The end marker
246 * string is needed so we can tell that end of output has been reached.
247 *
248 * @param cmd The actual command
249 * @param startAlias The command alias for start marker
250 * @param endAlias The command alias for end marker
251 * @return formatted command string
252 */
253 private static String formatShellCommand(String cmd, int startAlias, int endAlias) {
254 if (cmd == null || cmd.equals("")) { //$NON-NLS-1$
255 return cmd;
256 }
257 StringBuffer formattedCommand = new StringBuffer();
258 // Make multi-line command.
259 // Wrap actual command with start marker and end marker to wrap actual command.
260 formattedCommand.append(getEchoCmd(startAlias));
261 formattedCommand.append(CMD_DELIMITER);
262 formattedCommand.append(cmd);
263 formattedCommand.append(CMD_DELIMITER);
264 formattedCommand.append(getEchoCmd(endAlias));
265 formattedCommand.append(CMD_DELIMITER);
266 return formattedCommand.toString();
267 }
268
269 /**
270 * Creates a echo command line in the format: echo <start tag> <alias> <end tag> $?
271 *
272 * @param alias The command alias integer to be included in the echoed message.
273 * @return the echo command line
274 */
275 private static String getEchoCmd(int alias) {
276 return SHELL_ECHO_CMD + getEchoResult(alias) + "$?"; //$NON-NLS-1$
277 }
278
279 /**
280 * Creates the expected result for a given command alias:
281 * <start tag> <alias> <end tag> $?
282 *
283 * @param alias The command alias integer to be included in the echoed message.
284 * @return the expected echo result
285 */
286 private static String getEchoResult(int alias) {
287 return BEGIN_END_TAG + String.valueOf(alias) + DONE_MARKUP_STRING;
288 }
289
290 /**
291 * Verifies if given command line contains a command alias echo result.
292 *
293 * @param line The output line to test.
294 * @param alias The command alias
295 * @param checkReturnValue <code>true</code> to retrieve command result (previous command) <code>false</code>
296 * @return <code>true</code> if output line is a command alias echo result else <code>false</code>
297 */
298 private boolean isAliasEchoResult(String line, int alias, boolean checkReturnValue) {
299 String expected = getEchoResult(alias);
300 if (line.startsWith(expected)) {
301 if (!checkReturnValue) {
302 try {
303 int k = Integer.valueOf(line.substring(expected.length()));
304 fReturnValue = k;
305 } catch (NumberFormatException e) {
306 // do nothing
307 }
308 }
309 return true;
310 }
311 int index = line.indexOf(expected);
312 if (index > 0) {
313 if (line.indexOf(SHELL_ECHO_CMD) == -1) {
314 return true;
315 }
316 }
317
318 return false;
319 }
320
321 /**
322 * Verifies if output line is an echo of the given command line. If the
323 * output line is longer then the maximum line lengths (e.g. for ssh), the
324 * shell adds a line break character. This method takes this in
325 * consideration by comparing the command line without any whitespaces.
326 *
327 * @param line
328 * The output line to verify
329 * @param cmd
330 * The command executed
331 * @return <code>true</code> if it's an echoed command line else
332 * <code>false</code>
333 */
334 @SuppressWarnings("nls")
335 private static boolean isCommandEcho(String line, String cmd) {
336 String s1 = line.replaceAll("\\s","");
337 String s2 = cmd.replaceAll("\\s","");
338 s2 = s2.replaceAll("(\\*)", "(\\\\*)");
339 String patternStr = ".*(" + s2 +")$";
340 return s1.matches(patternStr);
341 }
342 }
This page took 0.038542 seconds and 5 git commands to generate.