summaryrefslogtreecommitdiffstats
path: root/plugins/org.yocto.remote.utils/src/org/yocto
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/org.yocto.remote.utils/src/org/yocto')
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Activator.java62
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandOutputProcessor.java43
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandResponseHandler.java44
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandRunnable.java44
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommonHelper.java46
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleHelper.java38
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleRunnable.java47
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/DialogRunnable.java26
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ICommandResponseHandler.java16
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Messages.java35
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/OutputProcessor.java112
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ProcessStreamBuffer.java87
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteHelper.java680
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteMachine.java202
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteShellExec.java140
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ShellSession.java332
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/TerminalHandler.java132
-rw-r--r--plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/YoctoCommand.java63
18 files changed, 2149 insertions, 0 deletions
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Activator.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Activator.java
new file mode 100644
index 0000000..da66a3e
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Activator.java
@@ -0,0 +1,62 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.ui.plugin.AbstractUIPlugin;
14import org.osgi.framework.BundleContext;
15
16/**
17 * The activator class controls the plug-in life cycle
18 */
19public class Activator extends AbstractUIPlugin {
20
21 // The plug-in ID
22 public static final String PLUGIN_ID = "org.yocto.remote.utils"; //$NON-NLS-1$
23
24 // The shared instance
25 private static Activator plugin;
26
27 /**
28 * The constructor
29 */
30 public Activator() {
31 }
32
33 /*
34 * (non-Javadoc)
35 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
36 */
37 @Override
38 public void start(BundleContext context) throws Exception {
39 super.start(context);
40 plugin = this;
41 }
42
43 /*
44 * (non-Javadoc)
45 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
46 */
47 @Override
48 public void stop(BundleContext context) throws Exception {
49 plugin = null;
50 super.stop(context);
51 }
52
53 /**
54 * Returns the shared instance
55 *
56 * @return the shared instance
57 */
58 public static Activator getDefault() {
59 return plugin;
60 }
61
62}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandOutputProcessor.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandOutputProcessor.java
new file mode 100644
index 0000000..081e6d4
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandOutputProcessor.java
@@ -0,0 +1,43 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.core.runtime.IProgressMonitor;
14import org.eclipse.rse.services.shells.IHostShell;
15
16public class CommandOutputProcessor extends OutputProcessor {
17
18 public CommandOutputProcessor(IProgressMonitor monitor,
19 IHostShell hostShell, CommandResponseHandler cmdHandler, String task) {
20 super(monitor, hostShell, cmdHandler, task);
21 }
22
23 @Override
24 protected boolean isErrChStop(char ch) {
25 return (ch == '\n');
26 }
27
28 @Override
29 protected boolean isOutChStop(char ch) {
30 return (ch == '\n');
31 }
32
33 @Override
34 protected void processOutputBufferLine(char ch, String str) {
35 processBuffer.addOutputLine(str);
36 }
37
38 @Override
39 protected void processErrorBufferLine(char ch, String str) {
40 processBuffer.addErrorLine(str);
41 }
42
43}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandResponseHandler.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandResponseHandler.java
new file mode 100644
index 0000000..f02fbfa
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandResponseHandler.java
@@ -0,0 +1,44 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.ui.console.MessageConsole;
14import org.eclipse.ui.console.MessageConsoleStream;
15
16public class CommandResponseHandler implements ICommandResponseHandler {
17 private MessageConsoleStream consoleStream;
18 private Boolean errorOccured = false;
19
20 public CommandResponseHandler(MessageConsole console) {
21 try {
22 this.consoleStream = console.newMessageStream();
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
26 }
27
28 public Boolean hasError() {
29 return errorOccured;
30 }
31
32 @Override
33 public void response(String line, boolean isError) {
34 try {
35 if (isError) {
36 errorOccured = true;
37 }
38 consoleStream.println(line);
39 } catch (Exception e) {
40 e.printStackTrace();
41 }
42 }
43
44} \ No newline at end of file
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandRunnable.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandRunnable.java
new file mode 100644
index 0000000..8cbda18
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommandRunnable.java
@@ -0,0 +1,44 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.core.runtime.CoreException;
14import org.eclipse.core.runtime.IProgressMonitor;
15import org.eclipse.rse.core.model.IHost;
16import org.eclipse.rse.services.shells.IHostShell;
17
18public class CommandRunnable implements Runnable{
19 private IHostShell hostShell;
20 private final IHost connection;
21 private final YoctoCommand cmd;
22 private final IProgressMonitor monitor;
23 private final CommandResponseHandler cmdHandler;
24
25 CommandRunnable(IHost connection, YoctoCommand cmd, IProgressMonitor monitor){
26 this.connection = connection;
27 this.cmdHandler = RemoteHelper.getCommandHandler(connection);
28 this.cmd = cmd;
29 this.monitor = monitor;
30 this.hostShell = null;
31 }
32 @Override
33 public void run() {
34 try {
35 hostShell = RemoteHelper.runCommandRemote(connection, cmd, monitor);
36 cmd.setProcessBuffer(RemoteHelper.processOutput(monitor, hostShell, cmdHandler));
37 } catch (CoreException e) {
38 e.printStackTrace();
39 } catch (Exception e) {
40 e.printStackTrace();
41 }
42 }
43
44}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommonHelper.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommonHelper.java
new file mode 100644
index 0000000..23afd38
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/CommonHelper.java
@@ -0,0 +1,46 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.core.runtime.IStatus;
14import org.eclipse.core.runtime.Status;
15import org.eclipse.jface.dialogs.ErrorDialog;
16import org.eclipse.swt.widgets.Display;
17
18public class CommonHelper {
19
20 static public boolean isExecAvail(String exec) {
21 boolean ret = false;
22 try {
23 Process p = Runtime.getRuntime().exec(new String[] {"which", exec});
24 p.waitFor();
25 if(p.exitValue() == 0) {
26 ret = true;
27 }
28 } catch (Exception e) {
29 e.printStackTrace();
30 }
31 return ret;
32 }
33
34 public static void showErrorDialog(final String dialogTitle, final String errorMessage, final String reason) {
35 //needs to be run in the ui thread otherwise swt throws invalid thread access
36 Display.getDefault().syncExec(new Runnable() {
37 @Override
38 public void run() {
39 ErrorDialog.openError(null, dialogTitle, errorMessage,
40 new Status(IStatus.ERROR,Activator.PLUGIN_ID,reason));
41 }
42 });
43
44 }
45
46}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleHelper.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleHelper.java
new file mode 100644
index 0000000..9c5c244
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleHelper.java
@@ -0,0 +1,38 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.swt.widgets.Display;
14import org.eclipse.ui.console.ConsolePlugin;
15import org.eclipse.ui.console.IConsole;
16import org.eclipse.ui.console.IConsoleManager;
17import org.eclipse.ui.console.MessageConsole;
18
19public class ConsoleHelper {
20 public static final String YOCTO_CONSOLE = "Yocto Project Console";
21
22 public static MessageConsole findConsole(String name) {
23 ConsolePlugin plugin = ConsolePlugin.getDefault();
24 IConsoleManager conMan = plugin.getConsoleManager();
25 IConsole[] existing = conMan.getConsoles();
26 for (int i = 0; i < existing.length; i++)
27 if (name.equals(existing[i].getName()))
28 return (MessageConsole) existing[i];
29 // no console found, so create a new one
30 MessageConsole myConsole = new MessageConsole(name, null);
31 conMan.addConsoles(new IConsole[] { myConsole });
32 return myConsole;
33 }
34
35 public static void showConsole(MessageConsole console){
36 Display.getDefault().syncExec(new ConsoleRunnable(console));
37 }
38}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleRunnable.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleRunnable.java
new file mode 100644
index 0000000..e5fe666
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ConsoleRunnable.java
@@ -0,0 +1,47 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.ui.IWorkbench;
14import org.eclipse.ui.IWorkbenchPage;
15import org.eclipse.ui.IWorkbenchWindow;
16import org.eclipse.ui.PlatformUI;
17import org.eclipse.ui.console.IConsoleConstants;
18import org.eclipse.ui.console.IConsoleView;
19import org.eclipse.ui.console.MessageConsole;
20
21public class ConsoleRunnable implements Runnable{
22 MessageConsole console;
23 ConsoleRunnable (MessageConsole console){
24 this.console = console;
25 }
26 @Override
27 public void run() {
28 IWorkbench wb = PlatformUI.getWorkbench();
29 if (wb == null)
30 return;
31 IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
32 if (win == null)
33 return;
34 IWorkbenchPage page = win.getActivePage();
35 if (page == null)
36 return;
37 String id = IConsoleConstants.ID_CONSOLE_VIEW;
38 try {
39 IConsoleView view = (IConsoleView) page.showView(id);
40 if (view == null)
41 return;
42 view.display(console);
43 } catch (Exception e) {
44 e.printStackTrace();
45 }
46 }
47} \ No newline at end of file
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/DialogRunnable.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/DialogRunnable.java
new file mode 100644
index 0000000..5fbab76
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/DialogRunnable.java
@@ -0,0 +1,26 @@
1package org.yocto.remote.utils;
2
3import org.eclipse.jface.dialogs.MessageDialog;
4
5public class DialogRunnable implements Runnable{
6 int type = 0;
7 boolean result;
8 public static final int QUESTION = 1;
9 public static final int ERROR = 2;
10 String title;
11 String message;
12
13 DialogRunnable(String title, String message, int type){
14 this.title = title;
15 this.message = message;
16 this.type = type;
17 }
18 @Override
19 public void run() {
20 if (type == QUESTION) {
21 result = MessageDialog.openQuestion(null, title, message);
22 } else if (type == ERROR) {
23 MessageDialog.openError(null, title, message);
24 }
25 }
26} \ No newline at end of file
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ICommandResponseHandler.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ICommandResponseHandler.java
new file mode 100644
index 0000000..193d57c
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ICommandResponseHandler.java
@@ -0,0 +1,16 @@
1/*****************************************************************************
2 * Copyright (c) 2013 Ken Gilmer, Intel Corporation
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ken Gilmer - initial API and implementation
10 * Ioana Grigoropol (Intel) - move to separate remote utilities plugin
11 *******************************************************************************/
12package org.yocto.remote.utils;
13
14public interface ICommandResponseHandler {
15 public void response(String line, boolean isError);
16}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Messages.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Messages.java
new file mode 100644
index 0000000..fc696d6
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/Messages.java
@@ -0,0 +1,35 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.osgi.util.NLS;
14
15public class Messages extends NLS {
16
17 private static final String BUNDLE_NAME = "org.yocto.remote.utils.messages"; //$NON-NLS-1$
18
19 public static String ErrorNoSubsystem;
20 public static String ErrorConnectSubsystem;
21
22 public static String InfoDownload;
23 public static String InfoUpload;
24
25 public static String RemoteShellExec_1;
26 public static String RemoteShellExec_2;
27
28 static {
29 // initialize resource bundle
30 NLS.initializeMessages(BUNDLE_NAME, Messages.class);
31 }
32
33 private Messages() {
34 }
35}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/OutputProcessor.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/OutputProcessor.java
new file mode 100644
index 0000000..401a782
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/OutputProcessor.java
@@ -0,0 +1,112 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import java.io.BufferedReader;
14import java.io.IOException;
15import java.io.InputStreamReader;
16import java.util.concurrent.locks.Lock;
17
18import org.eclipse.core.runtime.IProgressMonitor;
19import org.eclipse.rse.internal.services.local.shells.LocalHostShell;
20import org.eclipse.rse.internal.services.shells.TerminalServiceHostShell;
21import org.eclipse.rse.services.shells.HostShellProcessAdapter;
22import org.eclipse.rse.services.shells.IHostShell;
23
24public abstract class OutputProcessor{
25 private static final int ERROR_BUFFER = 1;
26 private static final int OUTPUT_BUFFER = 2;
27 protected String task;
28 protected ProcessStreamBuffer processBuffer;
29 protected IHostShell hostShell;
30 protected CommandResponseHandler cmdHandler;
31 protected IProgressMonitor monitor;
32
33 public OutputProcessor(IProgressMonitor monitor, IHostShell hostShell, CommandResponseHandler cmdHandler, String task){
34 this.monitor = monitor;
35 this.hostShell = hostShell;
36 this.processBuffer = new ProcessStreamBuffer(hostShell instanceof TerminalServiceHostShell);
37 this.cmdHandler = cmdHandler;
38 this.task = task;
39 }
40 public ProcessStreamBuffer processOutput() throws Exception{
41 if (hostShell == null)
42 throw new Exception("An error has occured while trying to run remote command!");
43 monitor.beginTask(this.task, RemoteHelper.TOTALWORKLOAD);
44 Lock lock = null;
45 if (hostShell instanceof LocalHostShell) {
46 lock = ((LocalHostShell)hostShell).getLock();
47 lock.lock();
48 }
49 BufferedReader inbr = null;
50 BufferedReader errbr = null;
51
52 if (hostShell instanceof LocalHostShell) {
53 inbr = ((LocalHostShell)hostShell).getReader(false);
54 errbr = ((LocalHostShell)hostShell).getReader(true);
55 } else {
56 Process p = new HostShellProcessAdapter(hostShell);
57 inbr = new BufferedReader(new InputStreamReader(p.getInputStream()));
58 errbr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
59 }
60 boolean cancel = false;
61 while (!cancel) {
62 if(monitor.isCanceled()) {
63 cancel = true;
64 if (lock != null)
65 lock.unlock();
66 throw new InterruptedException("User Cancelled");
67 }
68 processBuffer(errbr, ERROR_BUFFER);
69 processBuffer(inbr, OUTPUT_BUFFER);
70 cancel = true;
71 }
72 if (lock != null)
73 lock.unlock();
74 return processBuffer;
75 }
76 protected abstract boolean isErrChStop(char ch);
77 protected abstract boolean isOutChStop(char ch);
78 protected boolean isChStop(char ch, int type){
79 if (type == ERROR_BUFFER)
80 return isErrChStop(ch);
81 else if(type == OUTPUT_BUFFER)
82 return isOutChStop(ch);
83 return false;
84 }
85 protected abstract void processOutputBufferLine(char ch, String str);
86 protected abstract void processErrorBufferLine(char ch, String str);
87 protected void processBufferLine(String str, char ch, int type){
88 if (type == ERROR_BUFFER)
89 processErrorBufferLine(ch, str);
90 else if(type == OUTPUT_BUFFER)
91 processOutputBufferLine(ch, str);
92 }
93 protected void processBuffer(BufferedReader br, int type) throws IOException{
94 StringBuffer buffer = new StringBuffer();
95 int c;
96 if (br != null)
97 while ((c = br.read()) != -1) {
98 char ch = (char) c;
99 buffer.append(ch);
100 if (isChStop(ch, type)){
101 String str = buffer.toString();
102 processBufferLine(str, ch, type);
103 System.out.println(str);
104 if (str.trim().equals(RemoteHelper.TERMINATOR)) {
105 break;
106 }
107 cmdHandler.response(str, false);
108 buffer.delete(0, buffer.length());
109 }
110 }
111 }
112} \ No newline at end of file
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ProcessStreamBuffer.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ProcessStreamBuffer.java
new file mode 100644
index 0000000..111f607
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ProcessStreamBuffer.java
@@ -0,0 +1,87 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import java.util.ArrayList;
14import java.util.List;
15import java.util.regex.Pattern;
16
17public class ProcessStreamBuffer {
18 private static final String WHITESPACES = "\\s+";
19 List<String> errorLines;
20 List<String> outputLines;
21 boolean isTerminal;
22
23 ProcessStreamBuffer(boolean isTerminal){
24 this.isTerminal = isTerminal;
25 errorLines = new ArrayList<String>();
26 outputLines = new ArrayList<String>();
27 }
28
29 public void addErrorLine(String line){
30 errorLines.add(line);
31 }
32 public void addOutputLine(String line){
33 outputLines.add(line);
34 }
35
36 public List<String> getOutputLines(){
37 return outputLines;
38 }
39
40 public List<String> getErrorLines(){
41 return errorLines;
42 }
43
44 public String getMergedOutputLines(){
45 String returnVal = "";
46 for (int i = 0; i < outputLines.size(); i++) {
47 String line = outputLines.get(i);
48 returnVal += line;
49 if (outputLines.size() > 1 && i != outputLines.size() - 1)
50 returnVal += "\n";
51 }
52 return returnVal;
53 }
54
55 public boolean hasErrors() {
56 return errorLines.size() != 0;
57 }
58
59 public String getLastOutputLineContaining(String str) {
60 if (!errorLines.isEmpty())
61 return null;
62 for (int i = outputLines.size() - 1; i >= 0; i--){
63 String line = outputLines.get(i);
64 if (line.replaceAll(WHITESPACES, "").contains(str.replaceAll(WHITESPACES, "")))
65 return line;
66 }
67 return null;
68 }
69
70 public String getOutputLineContaining(String arg, String pattern) {
71 List<String> lines = null;
72 if (isTerminal)
73 lines = errorLines;
74 else
75 lines = outputLines;
76 for (int i = lines.size() - 1; i >= 0; i--){
77 String line = lines.get(i);
78 if (line.contains(arg)) {
79 String[] tokens = line.split("\\s+");
80 if (Pattern.matches(pattern, tokens[0])) {
81 return tokens[0];
82 }
83 }
84 }
85 return "";
86 }
87}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteHelper.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteHelper.java
new file mode 100644
index 0000000..e0097ec
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteHelper.java
@@ -0,0 +1,680 @@
1/********************************************************************************
2 * Copyright (c) 2013 MontaVista Software, Inc and Others.
3 * This program and the accompanying materials are made available under the terms
4 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
5 * available at http://www.eclipse.org/legal/epl-v10.html
6 *
7 * Contributors:
8 * Anna Dushistova (MontaVista) - initial API and implementation
9 * Lianhao Lu (Intel) - Modified to add other file operations.
10 * Ioana Grigoropol (Intel) - Separated remote functionality
11 ********************************************************************************/
12package org.yocto.remote.utils;
13
14import java.io.BufferedInputStream;
15import java.io.BufferedOutputStream;
16import java.io.BufferedReader;
17import java.io.File;
18import java.io.FileInputStream;
19import java.io.FileNotFoundException;
20import java.io.FileOutputStream;
21import java.io.FileReader;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.PrintWriter;
25import java.net.URI;
26import java.net.URISyntaxException;
27import java.nio.file.Files;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.HashMap;
31import java.util.Iterator;
32import java.util.List;
33import java.util.Map;
34
35import org.eclipse.core.internal.filesystem.InternalFileSystemCore;
36import org.eclipse.core.internal.resources.LocalMetaArea;
37import org.eclipse.core.internal.resources.Workspace;
38import org.eclipse.core.resources.ResourcesPlugin;
39import org.eclipse.core.runtime.CoreException;
40import org.eclipse.core.runtime.FileLocator;
41import org.eclipse.core.runtime.IPath;
42import org.eclipse.core.runtime.IProgressMonitor;
43import org.eclipse.core.runtime.IStatus;
44import org.eclipse.core.runtime.MultiStatus;
45import org.eclipse.core.runtime.NullProgressMonitor;
46import org.eclipse.core.runtime.Path;
47import org.eclipse.core.runtime.Status;
48import org.eclipse.core.runtime.SubProgressMonitor;
49import org.eclipse.osgi.util.NLS;
50import org.eclipse.rse.core.IRSECoreStatusCodes;
51import org.eclipse.rse.core.IRSEInitListener;
52import org.eclipse.rse.core.IRSESystemType;
53import org.eclipse.rse.core.IRSEUserIdConstants;
54import org.eclipse.rse.core.RSECorePlugin;
55import org.eclipse.rse.core.model.IHost;
56import org.eclipse.rse.core.model.ISubSystemConfigurationCategories;
57import org.eclipse.rse.core.model.ISubSystemConfigurator;
58import org.eclipse.rse.core.model.ISystemHostPool;
59import org.eclipse.rse.core.model.ISystemRegistry;
60import org.eclipse.rse.core.IRSECoreRegistry;
61import org.eclipse.rse.core.subsystems.ISubSystem;
62import org.eclipse.rse.core.subsystems.ISubSystemConfiguration;
63import org.eclipse.rse.internal.core.RSEInitJob;
64import org.eclipse.rse.internal.ui.view.SystemPerspectiveHelpers;
65import org.eclipse.rse.services.IService;
66import org.eclipse.rse.services.clientserver.messages.SystemMessageException;
67import org.eclipse.rse.services.files.IFileService;
68import org.eclipse.rse.services.files.IHostFile;
69import org.eclipse.rse.services.shells.HostShellProcessAdapter;
70import org.eclipse.rse.services.shells.IHostShell;
71import org.eclipse.rse.services.shells.IShellService;
72import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility;
73import org.eclipse.rse.subsystems.files.core.servicesubsystem.FileServiceSubSystem;
74import org.eclipse.rse.subsystems.files.core.servicesubsystem.IFileServiceSubSystem;
75import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem;
76import org.eclipse.rse.subsystems.shells.core.subsystems.servicesubsystem.IShellServiceSubSystem;
77import org.eclipse.rse.subsystems.terminals.core.ITerminalServiceSubSystem;
78import org.eclipse.rse.ui.RSEUIPlugin;
79import org.eclipse.rse.ui.SystemBasePlugin;
80import org.eclipse.rse.ui.SystemConnectionForm;
81import org.eclipse.ui.console.MessageConsole;
82
83public class RemoteHelper {
84 private final static String EXIT_CMD = "exit"; //$NON-NLS-1$
85 private final static String CMD_DELIMITER = ";"; //$NON-NLS-1$
86 private final static String LOCAL_CONN_NAME = "Local";
87 private final static String CONNECTION_NAME = "127.0.0.1";
88 private final static String HOST_NAME = "LOCALHOST";
89 public static final String TERMINATOR = "234o987dsfkcqiuwey18837032843259d";//$NON-NLS-1$
90 public static final int TOTALWORKLOAD = 100;
91 private static Map<IHost, RemoteMachine> machines;
92
93 public static IPath getWorkspaceMetaArea(){
94 Workspace workspace = (Workspace)ResourcesPlugin.getWorkspace();
95 LocalMetaArea metaDataArea = workspace.getMetaArea();
96 return metaDataArea.getLocation();
97 }
98 public static void storeProjDescrInMetaArea(IHost conn, String projName, String remoteSrc){
99 IPath path = getWorkspaceMetaArea();
100 String sep = File.separator;
101 String localDest = path.toString() + sep + ".projects" + sep + projName + sep + ".project";
102 try {
103 getRemoteFile(conn, localDest, remoteSrc + sep + ".project", new NullProgressMonitor());
104 } catch (Exception e) {
105 e.printStackTrace();
106 }
107 }
108 public static String retrieveProjRootFromMetaArea(String projName){
109 IPath path = getWorkspaceMetaArea();
110 String sep = File.separator;
111 return path.toString() + sep + ".projects" + sep + projName + sep;
112 }
113 public static void storeURIInMetaArea(String projName, URI uri){
114 IPath path = getWorkspaceMetaArea();
115 String sep = File.separator;
116 File f = new File(path.toString() + sep + ".projects" + sep + projName + sep + ".originalURI");
117 PrintWriter writer;
118 try {
119 writer = new PrintWriter(f);
120 writer.println(uri.getScheme());
121 writer.println(uri.getHost());
122 writer.println(uri.getPath());
123 writer.println(uri.getFragment());
124 writer.close();
125 } catch (FileNotFoundException e) {
126 e.printStackTrace();
127 }
128 }
129
130 public static URI retrieveURIFromMetaArea(String projName){
131 IPath path = getWorkspaceMetaArea();
132 String sep = File.separator;
133 File f = new File(path.toString() + sep + ".projects" + sep + projName + sep + ".originalURI");
134 try {
135 BufferedReader buf = new BufferedReader(new FileReader(f));
136 String line = null;
137 List<String> elems = new ArrayList<String>();
138 while((line = buf.readLine()) != null){
139 if (line.equals("null"))
140 line = null;
141 elems.add(line);
142 }
143 buf.close();
144 if (elems.size() == 4){
145 URI uri = new URI(elems.get(0), elems.get(1), elems.get(2), elems.get(3));
146 return uri;
147 }
148 } catch (IOException e) {
149 e.printStackTrace();
150 } catch (URISyntaxException e) {
151 e.printStackTrace();
152 }
153 return null;
154 }
155
156 public static boolean isInitialized(final URI uri){
157 boolean init = RSECorePlugin.isInitComplete(RSECorePlugin.INIT_MODEL);
158 if (!init) {
159 RSEInitJob.getInstance().addInitListener(new IRSEInitListener() {
160 @Override
161 public void phaseComplete(int arg0) {
162 try {
163 InternalFileSystemCore.getInstance().getStore(uri);
164 } catch (CoreException e) {
165 e.printStackTrace();
166 }
167 }
168 });
169 }
170 return init;
171 }
172
173 public static IHost getRemoteConnectionByName(String remoteConnection) {
174 if (remoteConnection == null)
175 return null;
176 IHost[] connections = RSECorePlugin.getTheSystemRegistry().getHosts();
177 for (int i = 0; i < connections.length; i++)
178 if (connections[i].getAliasName().equals(remoteConnection))
179 return connections[i];
180 return null;
181 }
182
183 public static ISubSystem getFileSubsystem(IHost host) {
184 if (host == null)
185 return null;
186 ISubSystem[] subSystems = host.getSubSystems();
187 for (int i = 0; i < subSystems.length; i++) {
188 if (subSystems[i] instanceof IFileServiceSubSystem)
189 return subSystems[i];
190 }
191 return null;
192 }
193
194 public static ISubSystem getShellSubsystem(IHost host) {
195 if (host == null)
196 return null;
197 ISubSystem[] subSystems = host.getSubSystems();
198 for (int i = 0; i < subSystems.length; i++) {
199 if (subSystems[i] instanceof IShellServiceSubSystem)
200 return subSystems[i];
201 }
202 return null;
203 }
204
205 public static IHost[] getSuitableConnections() {
206
207 //we only get RSE connections with files&cmds subsystem
208 ArrayList <IHost> filConnections = new ArrayList <IHost>(Arrays.asList(RSECorePlugin.getTheSystemRegistry()
209 .getHostsBySubSystemConfigurationCategory(ISubSystemConfigurationCategories.SUBSYSTEM_CATEGORY_FILES))); //$NON-NLS-1$
210
211 ArrayList <IHost> terminalConnections = new ArrayList <IHost>(Arrays.asList(RSECorePlugin.getTheSystemRegistry()
212 .getHostsBySubSystemConfigurationCategory("terminal")));//$NON-NLS-1$
213
214 ArrayList <IHost> shellConnections = new ArrayList <IHost>(Arrays.asList(RSECorePlugin.getTheSystemRegistry()
215 .getHostsBySubSystemConfigurationCategory("shells"))); //$NON-NLS-1$
216
217 Iterator <IHost>iter = filConnections.iterator();
218 while(iter.hasNext()){
219 IHost fileConnection = iter.next();
220 if(!terminalConnections.contains(fileConnection) && !shellConnections.contains(fileConnection)){
221 iter.remove();
222 }
223 IRSESystemType sysType = fileConnection.getSystemType();
224 if (sysType == null || !sysType.isEnabled()) {
225 iter.remove();
226 }
227 }
228
229 return filConnections.toArray(new IHost[filConnections.size()]);
230 }
231
232 public static void putRemoteFileInPlugin(IHost connection, String locaPathInPlugin, String remoteExePath,
233 IProgressMonitor monitor) throws Exception {
234
235 assert(connection != null);
236 monitor.beginTask(Messages.InfoUpload, 100);
237
238 IFileService fileService;
239 try {
240 fileService = getConnectedRemoteFileService(
241 connection,
242 new SubProgressMonitor(monitor, 5));
243 InputStream inputStream = FileLocator.openStream(
244 Activator.getDefault().getBundle(), new Path(locaPathInPlugin), false);
245 Path remotePath = new Path(remoteExePath);
246
247 //TODO workaround for now
248 //in case the underlying scp file service doesn't support inputStream upload
249 BufferedInputStream bis = new BufferedInputStream(inputStream);
250 File tempFile = File.createTempFile("scp", "temp"); //$NON-NLS-1$ //$NON-NLS-2$
251 FileOutputStream os = new FileOutputStream(tempFile);
252 BufferedOutputStream bos = new BufferedOutputStream(os);
253 byte[] buffer = new byte[1024];
254 int readCount;
255 while( (readCount = bis.read(buffer)) > 0)
256 {
257 bos.write(buffer, 0, readCount);
258 }
259 bos.close();
260 fileService.upload(tempFile, remotePath.removeLastSegments(1)
261 .toString(), remotePath.lastSegment(), true, null, null,
262 new SubProgressMonitor(monitor, 80));
263 // Need to change the permissions to match the original file
264 // permissions because of a bug in upload
265 remoteShellExec(
266 connection,
267 "", "chmod", "+x " + spaceEscapify(remotePath.toString()), new SubProgressMonitor(monitor, 5)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
268
269 } finally {
270 monitor.done();
271 }
272 return;
273 }
274
275 public static void getRemoteFile(IHost connection, String localExePath, String remoteExePath,
276 IProgressMonitor monitor) throws Exception {
277
278 assert(connection!=null);
279 monitor.beginTask(Messages.InfoDownload, 100);
280
281 IFileService fileService;
282 try {
283 fileService = getConnectedRemoteFileService(
284 connection,
285 new SubProgressMonitor(monitor, 10));
286 File file = new File(localExePath);
287 monitor.worked(5);
288 Path remotePath = new Path(remoteExePath);
289 fileService.download(remotePath.removeLastSegments(1).toString(),
290 remotePath.lastSegment(),file,true, null,
291 new SubProgressMonitor(monitor, 85));
292 // Need to change the permissions to match the original file
293 // permissions because of a bug in upload
294 //RemoteApplication p = remoteShellExec(
295 // config,
296 // "", "chmod", "+x " + spaceEscapify(remotePath.toString()), new SubProgressMonitor(monitor, 5)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
297 //Thread.sleep(500);
298 //p.destroy();
299
300 } finally {
301 monitor.done();
302 }
303 return;
304 }
305
306 public static ITerminalServiceSubSystem getTerminalSubSystem(
307 IHost connection) {
308 ISystemRegistry systemRegistry = RSECorePlugin.getTheSystemRegistry();
309 ISubSystem[] subsystems = systemRegistry.getSubSystems(connection);
310 for (int i = 0; i < subsystems.length; i++) {
311 if (subsystems[i] instanceof ITerminalServiceSubSystem) {
312 ITerminalServiceSubSystem subSystem = (ITerminalServiceSubSystem) subsystems[i];
313 return subSystem;
314 }
315 }
316 return null;
317 }
318
319 public static String spaceEscapify(String inputString) {
320 if (inputString == null)
321 return null;
322
323 return inputString.replaceAll(" ", "\\\\ "); //$NON-NLS-1$ //$NON-NLS-2$
324 }
325
326 public static Process remoteShellExec(IHost connection,
327 String prelaunchCmd, String remoteCommandPath, String arguments,
328 IProgressMonitor monitor) throws CoreException {
329
330 monitor.beginTask(NLS.bind(Messages.RemoteShellExec_1,
331 remoteCommandPath, arguments), 10);
332 String realRemoteCommand = arguments == null ? spaceEscapify(remoteCommandPath)
333 : spaceEscapify(remoteCommandPath) + " " + arguments; //$NON-NLS-1$
334
335 String remoteCommand = realRemoteCommand + CMD_DELIMITER + EXIT_CMD;
336
337 if(prelaunchCmd != null) {
338 if (!prelaunchCmd.trim().equals("")) //$NON-NLS-1$
339 remoteCommand = prelaunchCmd + CMD_DELIMITER + remoteCommand;
340 }
341
342 IShellService shellService;
343 Process p = null;
344 try {
345 shellService = (IShellService) getConnectedShellService(
346 connection,
347 new SubProgressMonitor(monitor, 7));
348
349 // This is necessary because runCommand does not actually run the
350 // command right now.
351 String env[] = new String[0];
352 try {
353 IHostShell hostShell = shellService.launchShell(
354 "", env, new SubProgressMonitor(monitor, 3)); //$NON-NLS-1$
355 hostShell.writeToShell(remoteCommand);
356 p = new HostShellProcessAdapter(hostShell);
357 } catch (Exception e) {
358 if (p != null) {
359 p.destroy();
360 }
361 abort(Messages.RemoteShellExec_2, e,
362 IRSECoreStatusCodes.EXCEPTION_OCCURRED);
363 }
364 } catch (Exception e1) {
365 abort(e1.getMessage(), e1,
366 IRSECoreStatusCodes.EXCEPTION_OCCURRED);
367 }
368
369 monitor.done();
370 return p;
371 }
372
373 /**
374 * Throws a core exception with an error status object built from the given
375 * message, lower level exception, and error code.
376 *
377 * @param message
378 * the status message
379 * @param exception
380 * lower level exception associated with the error, or
381 * <code>null</code> if none
382 * @param code
383 * error code
384 */
385 public static void abort(String message, Throwable exception, int code) throws CoreException {
386 IStatus status;
387 if (exception != null) {
388 MultiStatus multiStatus = new MultiStatus(Activator.PLUGIN_ID, code, message, exception);
389 multiStatus.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, code, exception.getLocalizedMessage(), exception));
390 status = multiStatus;
391 } else {
392 status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, code, message, null);
393 }
394 throw new CoreException(status);
395 }
396 /**
397 * Checks whether a IHost associated system's is enabled and not a local one
398 * @param host
399 * @return
400 */
401 public static boolean isHostViable(IHost host) {
402 IRSESystemType sysType = host.getSystemType();
403 if (sysType != null && sysType.isEnabled() && !sysType.isLocal())
404 return true;
405 return false;
406 }
407
408 /**
409 * Ensures that RSECorePlugin is initialized before performing any actions
410 */
411 public static void waitForRSEInitCompletition() {
412 if (!RSECorePlugin.isInitComplete(RSECorePlugin.INIT_MODEL))
413 try {
414 RSECorePlugin.waitForInitCompletion(RSECorePlugin.INIT_MODEL);
415 } catch (InterruptedException e) {
416 return;
417 }
418 }
419 public static RemoteMachine getRemoteMachine(IHost connection){
420 if (!getMachines().containsKey(connection))
421 getMachines().put(connection, new RemoteMachine(connection));
422 return getMachines().get(connection);
423 }
424
425 private static Map<IHost, RemoteMachine> getMachines() {
426 if (machines == null)
427 machines = new HashMap<IHost, RemoteMachine>();
428 return machines;
429 }
430
431 public static MessageConsole getConsole(IHost connection) {
432 return getRemoteMachine(connection).getConsole();
433 }
434
435 public static CommandResponseHandler getCommandHandler(IHost connection) {
436 return getRemoteMachine(connection).getCmdHandler();
437 }
438
439 public static ProcessStreamBuffer processOutput(IProgressMonitor monitor, IHostShell hostShell, CommandResponseHandler cmdHandler) throws Exception {
440 return new CommandOutputProcessor(monitor, hostShell, cmdHandler, "").processOutput();
441 }
442
443 public static IHost getRemoteConnectionForURI(URI uri, IProgressMonitor monitor) {
444 if (uri == null)
445 return null;
446
447 String host = uri.getHost();
448 if (host == null) {
449 // this is a local connection
450 ISystemRegistry sr = RSECorePlugin.getTheSystemRegistry();
451 IHost local = null;
452 while (local == null) {
453 local = sr.getLocalHost();
454 }
455 return local;
456 }
457 ISystemRegistry sr = RSECorePlugin.getTheSystemRegistry();
458 IHost[] connections = sr.getHosts();
459
460 IHost unconnected = null;
461 for (IHost conn : connections) {
462 if (host.equalsIgnoreCase(conn.getHostName())) {
463 IRemoteFileSubSystem fss = getRemoteFileSubSystem(conn);
464 if (fss != null && fss.isConnected())
465 return conn;
466 unconnected = conn;
467 }
468 }
469
470 return unconnected;
471 }
472
473 public static IRemoteFileSubSystem getRemoteFileSubSystem(IHost host) {
474 IRemoteFileSubSystem candidate = null;
475 IRemoteFileSubSystem otherServiceCandidate = null;
476 IRemoteFileSubSystem[] subSystems = RemoteFileUtility.getFileSubSystems(host);
477
478 for (IRemoteFileSubSystem subSystem : subSystems) {
479 if (subSystem instanceof FileServiceSubSystem) {
480 if (subSystem.isConnected())
481 return subSystem;
482
483 if (otherServiceCandidate == null)
484 otherServiceCandidate = subSystem;
485
486 } else if (candidate == null || (subSystem.isConnected() && !candidate.isConnected()))
487 candidate = subSystem;
488
489 }
490 if (candidate != null && candidate.isConnected())
491 return candidate;
492 if (otherServiceCandidate != null)
493 return otherServiceCandidate;
494 return null;
495 }
496
497 public static IFileService getConnectedRemoteFileService(IHost connection, IProgressMonitor monitor) throws Exception {
498 return getRemoteMachine(connection).getRemoteFileService(monitor);
499 }
500
501 public static IHostFile[] getRemoteDirContent(IHost connection, String remoteParent, String fileFilter, int fileType, IProgressMonitor monitor){
502
503 try {
504 IFileService fileServ = getConnectedRemoteFileService(connection, monitor);
505 return fileServ.list(remoteParent, fileFilter, fileType, monitor);
506 } catch (SystemMessageException e) {
507 e.printStackTrace();
508 } catch (Exception e) {
509 e.printStackTrace();
510 }
511 return null;
512 }
513
514 public static IService getConnectedShellService(IHost connection, IProgressMonitor monitor) throws Exception {
515 return getRemoteMachine(connection).getShellService(monitor);
516 }
517
518 public static void handleRunCommandRemote(IHost connection, YoctoCommand cmd, IProgressMonitor monitor){
519 try {
520 CommandRunnable cmdRun = new CommandRunnable(connection, cmd, monitor);
521 cmdRun.run();
522 } catch (Exception e) {
523 e.printStackTrace();
524 }
525 }
526
527 public static IHostShell runCommandRemote(IHost connection, YoctoCommand cmd,
528 IProgressMonitor monitor) throws CoreException {
529
530 monitor.beginTask(NLS.bind(Messages.RemoteShellExec_1,
531 cmd, cmd.getArguments()), 10);
532
533 String remoteCommand = cmd.getCommand() + " " + cmd.getArguments() + " ; echo " + TERMINATOR + "; exit ;";
534
535 IShellService shellService;
536 try {
537 shellService = (IShellService) getConnectedShellService(connection, new SubProgressMonitor(monitor, 7));
538
539 String env[] = getRemoteMachine(connection).prepareEnvString(monitor);
540
541 try {
542 IHostShell hostShell = shellService.runCommand(cmd.getInitialDirectory(), remoteCommand, env, new SubProgressMonitor(monitor, 3));
543 return hostShell;
544 } catch (Exception e) {
545 e.printStackTrace();
546 }
547 } catch (Exception e1) {
548 e1.printStackTrace();
549 }
550 return null;
551 }
552
553 public static IHostFile getRemoteHostFile(IHost connection, String remoteFilePath, IProgressMonitor monitor){
554 assert(connection != null);
555 monitor.beginTask(Messages.InfoDownload, 100);
556
557 try {
558 IFileService fileService = getConnectedRemoteFileService(connection, new SubProgressMonitor(monitor, 10));
559 Path remotePath = new Path(remoteFilePath);
560 IHostFile remoteFile = fileService.getFile(remotePath.removeLastSegments(1).toString(), remotePath.lastSegment(), new SubProgressMonitor(monitor, 5));
561 return remoteFile;
562 } catch (Exception e) {
563 e.printStackTrace();
564 }finally {
565 monitor.done();
566 }
567 return null;
568 }
569
570 public static InputStream getRemoteInputStream(IHost connection, String parentPath, String remoteFilePath, IProgressMonitor monitor){
571 assert(connection != null);
572 monitor.beginTask(Messages.InfoDownload, 100);
573
574 try {
575 IFileService fileService = getConnectedRemoteFileService(connection, new SubProgressMonitor(monitor, 10));
576
577 return fileService.getInputStream(parentPath, remoteFilePath, false, monitor);
578 } catch (Exception e) {
579 e.printStackTrace();
580 }finally {
581 monitor.done();
582 }
583 return null;
584 }
585
586 public static URI createNewURI(URI oldURI, String name) {
587 try {
588 String sep = oldURI.getPath().endsWith("/") ? "" : "/";
589 return new URI(oldURI.getScheme(), oldURI.getHost(), oldURI.getPath() + sep + name, oldURI.getFragment());
590 } catch (URISyntaxException e) {
591 e.printStackTrace();
592 return null;
593 }
594 }
595
596 public static boolean fileExistsRemote(IHost conn, IProgressMonitor monitor, String path) {
597 try {
598 IFileService fs = getConnectedRemoteFileService(conn, monitor);
599 int nameStart = path.lastIndexOf("/");
600 String parentPath = path.substring(0, nameStart);
601 String name = path.substring(nameStart + 1);
602 IHostFile hostFile = fs.getFile(parentPath, name, monitor);
603
604 return hostFile.exists();
605 } catch (Exception e) {
606 e.printStackTrace();
607 }
608 return false;
609 }
610
611 public static IHost createLocalConnection() {
612 IHost createdHost = null;
613 try {
614
615 ISubSystemConfigurator[] configurators = getSubSystemConfigurators();
616
617 IRSESystemType systemType = getSSHSystemType();
618 ISystemRegistry sr = RSECorePlugin.getTheSystemRegistry();
619 IHost[] connections = sr.getHosts();
620 for (IHost conn : connections) {
621 if (conn.getName().equals(LOCAL_CONN_NAME)) {
622 ISystemHostPool pool = conn.getHostPool();
623 createdHost = sr.createHost(pool.getSystemProfile().getName(), systemType, CONNECTION_NAME, HOST_NAME, "", "",IRSEUserIdConstants.USERID_LOCATION_NOTSET,configurators);
624 break;
625 }
626 }
627
628 // a tweak that is the result of UCD feedback. Phil
629 if ((createdHost != null) && SystemPerspectiveHelpers.isRSEPerspectiveActive()) {
630 if (systemType.getId().equals(IRSESystemType.SYSTEMTYPE_ISERIES_ID)) {
631 ISubSystem[] objSubSystems = sr.getSubSystemsBySubSystemConfigurationCategory("nativefiles", createdHost); //$NON-NLS-1$
632 if ((objSubSystems != null) && (objSubSystems.length > 0))// might be in product that doesn't have iSeries plugins
633 RSEUIPlugin.getTheSystemRegistryUI().expandSubSystem(objSubSystems[0]);
634 else
635 RSEUIPlugin.getTheSystemRegistryUI().expandHost(createdHost);
636 } else
637 RSEUIPlugin.getTheSystemRegistryUI().expandHost(createdHost);
638 }
639 } catch (Exception exc) {
640 exc.printStackTrace();
641 }
642 return createdHost;
643 }
644
645 private static IRSESystemType getSSHSystemType() {
646 IRSECoreRegistry coreReg = RSECorePlugin.getTheCoreRegistry();
647 return coreReg.getSystemTypeById("org.eclipse.rse.systemtype.ssh");
648 }
649
650 private static ISubSystemConfigurator[] getSubSystemConfigurators()
651 {
652 // what kind of subsystems do we have here?
653 ISystemRegistry sr = RSECorePlugin.getTheSystemRegistry();
654 ISubSystemConfiguration[] configurations = sr.getSubSystemConfigurationsBySystemType(getSSHSystemType(), true);
655
656 ArrayList configList = new ArrayList();
657 for (int i = 0; i < configurations.length; i++){
658 ISubSystemConfiguration configuration = configurations[i];
659
660 class DefaultConfigurator implements ISubSystemConfigurator {
661 private ISubSystemConfiguration _configuration;
662 public DefaultConfigurator(ISubSystemConfiguration configuration){
663 _configuration = configuration;
664 }
665
666 public boolean applyValues(ISubSystem ss) {
667 return true;
668 }
669
670 public ISubSystemConfiguration getSubSystemConfiguration() {
671 return _configuration;
672 }
673 }
674 configList.add(new DefaultConfigurator(configuration));
675 }
676
677 return (ISubSystemConfigurator[])configList.toArray(new ISubSystemConfigurator[configList.size()]);
678
679 }
680}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteMachine.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteMachine.java
new file mode 100644
index 0000000..92cfc15
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteMachine.java
@@ -0,0 +1,202 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import java.util.ArrayList;
14import java.util.HashMap;
15import java.util.List;
16import java.util.Map;
17
18import org.eclipse.core.runtime.CoreException;
19import org.eclipse.core.runtime.IProgressMonitor;
20import org.eclipse.core.runtime.NullProgressMonitor;
21import org.eclipse.core.runtime.OperationCanceledException;
22import org.eclipse.core.runtime.Status;
23import org.eclipse.core.runtime.SubProgressMonitor;
24import org.eclipse.rse.core.model.IHost;
25import org.eclipse.rse.core.subsystems.ISubSystem;
26import org.eclipse.rse.internal.services.local.shells.LocalShellService;
27import org.eclipse.rse.services.clientserver.messages.SystemMessageException;
28import org.eclipse.rse.services.files.IFileService;
29import org.eclipse.rse.services.shells.IHostShell;
30import org.eclipse.rse.services.shells.IShellService;
31import org.eclipse.rse.subsystems.files.core.servicesubsystem.IFileServiceSubSystem;
32import org.eclipse.rse.subsystems.shells.core.subsystems.servicesubsystem.IShellServiceSubSystem;
33import org.eclipse.ui.console.MessageConsole;
34
35public class RemoteMachine {
36 public static final String PROXY = "proxy";
37
38 private Map<String, String> environment;
39 private MessageConsole console;
40 private CommandResponseHandler cmdHandler;
41 private IShellService shellService;
42 private IHost connection;
43
44 private ISubSystem fileSubSystem;
45 private IFileService fileService;
46
47 public RemoteMachine(IHost connection) {
48 setConnection(connection);
49 }
50
51 public String[] prepareEnvString(IProgressMonitor monitor){
52 String[] env = null;
53 try {
54 if (shellService instanceof LocalShellService) {
55 env = shellService.getHostEnvironment();
56 } else {
57 List<String> envList = new ArrayList<String>();
58 getRemoteEnvProxyVars(monitor);
59 String value = "";
60 for (String varName : environment.keySet()){
61 value = varName + "=" + environment.get(varName);
62 envList.add(value);
63 }
64 env = envList.toArray(new String[envList.size()]);
65 }
66 } catch (Exception e) {
67 e.printStackTrace();
68 }
69
70 return env;
71 }
72 public void getRemoteEnvProxyVars(IProgressMonitor monitor){
73 try {
74 if (environment != null && !environment.isEmpty())
75 return;
76
77 environment = new HashMap<String, String>();
78
79 IShellService shellService = getShellService(new SubProgressMonitor(monitor, 7));
80
81 ProcessStreamBuffer buffer = null;
82 try {
83 SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 3);
84 IHostShell hostShell = shellService.runCommand("", "env" + " ; echo " + RemoteHelper.TERMINATOR + "; exit;", new String[]{}, subMonitor);
85 buffer = RemoteHelper.processOutput(subMonitor, hostShell, cmdHandler);
86 for(int i = 0; i < buffer.getOutputLines().size(); i++) {
87 String out = buffer.getOutputLines().get(i);
88 String[] tokens = out.split("=");
89 if (tokens.length != 2)
90 continue;
91 String varName = tokens[0];
92 String varValue = tokens[1];
93 if (varName.contains(PROXY))
94 environment.put(varName, varValue);
95 }
96 } catch (Exception e) {
97 e.printStackTrace();
98 }
99
100 } catch (Exception e) {
101 e.printStackTrace();
102 }
103 }
104
105 public Map<String, String> getEnvironment() {
106 return environment;
107 }
108 public void setEnvironment(Map<String, String> environment) {
109 this.environment = environment;
110 }
111 public MessageConsole getConsole() {
112 if (console == null)
113 console = ConsoleHelper.findConsole(ConsoleHelper.YOCTO_CONSOLE);
114
115 ConsoleHelper.showConsole(console);
116 return console;
117 }
118 public CommandResponseHandler getCmdHandler() {
119 if (cmdHandler == null)
120 cmdHandler = new CommandResponseHandler(getConsole());
121 return cmdHandler;
122 }
123
124 public IShellService getShellService(IProgressMonitor monitor) throws Exception {
125 if (shellService != null)
126 return shellService;
127
128 final ISubSystem subsystem = getShellSubsystem();
129
130 if (subsystem == null)
131 throw new Exception(Messages.ErrorNoSubsystem);
132
133 try {
134 subsystem.connect(monitor, false);
135 } catch (CoreException e) {
136 throw e;
137 } catch (OperationCanceledException e) {
138 throw new CoreException(Status.CANCEL_STATUS);
139 }
140
141 if (!subsystem.isConnected())
142 throw new Exception(Messages.ErrorConnectSubsystem);
143
144 shellService = ((IShellServiceSubSystem) subsystem).getShellService();
145 return shellService;
146 }
147
148 private ISubSystem getShellSubsystem() {
149 if (connection == null)
150 return null;
151 ISubSystem[] subSystems = connection.getSubSystems();
152 for (int i = 0; i < subSystems.length; i++) {
153 if (subSystems[i] instanceof IShellServiceSubSystem)
154 return subSystems[i];
155 }
156 return null;
157 }
158
159 public IHost getConnection() {
160 return connection;
161 }
162 public void setConnection(IHost connection) {
163 this.connection = connection;
164 }
165
166 public IFileService getRemoteFileService(IProgressMonitor monitor) throws Exception {
167 if (fileService == null) {
168
169 while(getFileSubsystem() == null)
170 Thread.sleep(2);
171 try {
172 getFileSubsystem().connect(monitor, false);
173 } catch (CoreException e) {
174 throw e;
175 } catch (OperationCanceledException e) {
176 throw new CoreException(Status.CANCEL_STATUS);
177 }
178
179 if (!getFileSubsystem().isConnected())
180 throw new Exception(Messages.ErrorConnectSubsystem);
181
182 fileService = ((IFileServiceSubSystem) getFileSubsystem()).getFileService();
183 }
184 return fileService;
185 }
186
187 public ISubSystem getFileSubsystem() {
188 if (fileSubSystem == null) {
189 if (connection == null)
190 return null;
191 ISubSystem[] subSystems = connection.getSubSystems();
192 for (int i = 0; i < subSystems.length; i++) {
193 if (subSystems[i] instanceof IFileServiceSubSystem) {
194 fileSubSystem = subSystems[i];
195 break;
196 }
197 }
198 }
199 return fileSubSystem;
200 }
201
202}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteShellExec.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteShellExec.java
new file mode 100644
index 0000000..711088c
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/RemoteShellExec.java
@@ -0,0 +1,140 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import java.io.BufferedReader;
14import java.io.IOException;
15import java.io.InputStream;
16import java.io.InputStreamReader;
17import java.io.OutputStream;
18
19import org.eclipse.core.runtime.IProgressMonitor;
20import org.eclipse.rse.core.model.IHost;
21
22public class RemoteShellExec {
23
24 public static final int
25 STATE_NULL = 0,
26 STATE_RUNNING = 1,
27 STATE_EXITED = 2;
28
29 private final String command;
30 private final IHost host;
31
32 private InputStream fInStream;
33 private OutputStream fOutStream;
34 private InputStream fErrStream;
35 private Process remoteShellProcess;
36
37 private int exitCode = 0;
38 private int status = STATE_NULL;
39
40 private final String RETURN_VALUE_TAG = "org.yocto.sdk.remotetools.RVTAG";
41 private final String RETURN_VALUE_CMD = ";echo \"" + RETURN_VALUE_TAG + "$?\"";
42
43 public RemoteShellExec(IHost host, String command) {
44 assert(host != null);
45 this.host = host;
46 this.command = command;
47 }
48
49 public int getStatus() {
50 return status;
51 }
52
53 public int getExitCode() {
54 return exitCode;
55 }
56
57 private void reset() {
58 fInStream = null;
59 fOutStream = null;
60 fErrStream = null;
61
62 remoteShellProcess = null;
63 exitCode = 0;
64 status = STATE_NULL;
65 }
66
67 public InputStream getInputStream() {
68 return fInStream;
69 }
70
71 public OutputStream getOutputStream() {
72 return fOutStream;
73 }
74
75 public InputStream getErrStream() {
76 return fErrStream;
77 }
78
79 public synchronized void start(String prelaunchCmd, String argument, IProgressMonitor monitor) throws Exception {
80 if(status == STATE_RUNNING)
81 return;
82
83 reset();
84 argument = (argument == null ? RETURN_VALUE_CMD : argument + RETURN_VALUE_CMD);
85 remoteShellProcess = RemoteHelper.remoteShellExec(this.host, prelaunchCmd, this.command, argument, monitor);
86 fInStream = remoteShellProcess.getInputStream();
87 fOutStream = remoteShellProcess.getOutputStream();
88 fErrStream = remoteShellProcess.getErrorStream();
89 status = STATE_RUNNING;
90 }
91
92 public synchronized void terminate() throws Exception {
93 if(status != STATE_RUNNING || remoteShellProcess != null)
94 return;
95
96 remoteShellProcess.destroy();
97 reset();
98 }
99
100 public int waitFor(IProgressMonitor monitor) throws InterruptedException {
101 while(status == STATE_RUNNING) {
102 if(monitor != null) {
103 if(monitor.isCanceled()) {
104 throw new InterruptedException("User Cancelled");
105 }
106 }
107
108 try {
109 remoteShellProcess.waitFor();
110 }catch(InterruptedException e){
111 //get the return value
112 try {
113 if(fInStream.available() != 0) {
114 BufferedReader in = new BufferedReader(new InputStreamReader(fInStream));
115 String thisline;
116 int idx;
117 while((thisline = in.readLine()) != null) {
118 if(thisline.indexOf(RETURN_VALUE_CMD) == -1) {
119 idx = thisline.indexOf(RETURN_VALUE_TAG);
120 if(idx != -1) {
121 try {
122 exitCode=(new Integer(thisline.substring(idx+RETURN_VALUE_TAG.length()))).intValue();
123 }catch(NumberFormatException e2) {
124 }
125 break;
126 }
127 }
128 }
129 }
130 }catch(IOException e1) {
131 //do nothing
132 }
133 }finally {
134 status=STATE_EXITED;
135 }
136 }
137 return exitCode;
138 }
139}
140
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ShellSession.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ShellSession.java
new file mode 100644
index 0000000..0922824
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/ShellSession.java
@@ -0,0 +1,332 @@
1/*****************************************************************************
2 * Copyright (c) 2013 Ken Gilmer
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ken Gilmer - initial API and implementation
10 * Jessica Zhang - Adopt for Yocto Tools plugin
11 *******************************************************************************/
12package org.yocto.remote.utils;
13
14import java.io.BufferedReader;
15import java.io.File;
16import java.io.IOException;
17import java.io.InputStream;
18import java.io.InputStreamReader;
19import java.io.OutputStream;
20import java.io.OutputStreamWriter;
21import java.lang.reflect.InvocationTargetException;
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24
25import org.eclipse.swt.widgets.Display;
26
27public class ShellSession {
28 /**
29 * Bash shell
30 */
31 public static final int SHELL_TYPE_BASH = 1;
32 /**
33 * sh shell
34 */
35 public static final int SHELL_TYPE_SH = 2;
36 private volatile boolean interrupt = false;
37 /**
38 * String used to isolate command execution
39 */
40 public static final String TERMINATOR = "build$";
41 public static final String LT = System.getProperty("line.separator");
42 private Process process;
43
44 private OutputStream pos = null;
45
46 private String shellPath = null;
47 private final String initCmd;
48 private final File root;
49 private final File builddir;
50
51 private OutputStreamWriter out;
52
53 public static String getFilePath(String file) throws IOException {
54 File f = new File(file);
55
56 if (!f.exists() || f.isDirectory()) {
57 throw new IOException("Path passed is not a file: " + file);
58 }
59
60 StringBuffer sb = new StringBuffer();
61
62 String elems[] = file.split(File.separator);
63
64 for (int i = 0; i < elems.length - 1; ++i) {
65 sb.append(elems[i]);
66 sb.append(File.separator);
67 }
68
69 return sb.toString();
70 }
71
72 public ShellSession(int shellType, File root, File builddir, String initCmd, OutputStream out) throws IOException {
73 this.root = root;
74 this.builddir = builddir;
75 this.initCmd = initCmd;
76 if (out == null) {
77 this.out = new OutputStreamWriter(null);
78 } else {
79 this.out = new OutputStreamWriter(out);
80 }
81 if (shellType == SHELL_TYPE_SH) {
82 shellPath = "/bin/sh";
83 }
84 shellPath = "/bin/bash";
85
86 initializeShell();
87 }
88
89 private void initializeShell() throws IOException {
90 process = Runtime.getRuntime().exec(shellPath);
91 pos = process.getOutputStream();
92
93 if (root != null) {
94 execute("cd " + root.getAbsolutePath());
95 }
96
97 if (initCmd != null) {
98 execute("source " + initCmd + " " + builddir.getAbsolutePath());
99 }
100 }
101
102 synchronized
103 public String execute(String command, int[] retCode) throws IOException {
104 String errorMessage = null;
105
106 interrupt = false;
107 out.write(command);
108 out.write(LT);
109
110 sendToProcessAndTerminate(command);
111
112 if (process.getErrorStream().available() > 0) {
113 byte[] msg = new byte[process.getErrorStream().available()];
114
115 process.getErrorStream().read(msg, 0, msg.length);
116 String msg_str = new String(msg);
117 out.write(msg_str);
118 out.write(LT);
119 if (!msg_str.contains("WARNING"))
120 errorMessage = "Error while executing: " + command + LT + new String(msg);
121 }
122
123 BufferedReader br = new BufferedReader(new InputStreamReader(process
124 .getInputStream()));
125
126 StringBuffer sb = new StringBuffer();
127 String line = null;
128
129 while (true) {
130 line = br.readLine();
131 if (line != null) {
132 sb.append(line);
133 sb.append(LT);
134 out.write(line);
135 out.write(LT);
136 }
137 if (line.endsWith(TERMINATOR))
138 break;
139 }
140 if (interrupt) {
141 process.destroy();
142 initializeShell();
143 interrupt = false;
144 }else if (line != null && retCode != null) {
145 try {
146 retCode[0]=Integer.parseInt(line.substring(0,line.lastIndexOf(TERMINATOR)));
147 }catch (NumberFormatException e) {
148 throw new IOException("Can NOT get return code" + command + LT + line);
149 }
150 }
151 out.flush();
152 if (errorMessage != null) {
153 throw new IOException(errorMessage);
154 }
155 return sb.toString();
156 }
157
158 synchronized
159 public void execute(String command) throws IOException {
160 interrupt = false;
161 String errorMessage = null;
162
163 sendToProcessAndTerminate(command);
164 boolean cancel = false;
165 try {
166 InputStream is = process.getInputStream();
167 InputStream es = process.getErrorStream();
168 String info;
169 while (!cancel) {
170 info = null;
171 StringBuffer buffer = new StringBuffer();
172 int c;
173 while (is.available() > 0) {
174 c = is.read();
175 char ch = (char) c;
176 buffer.append(ch);
177 if (ch == '\n') {
178 info = buffer.toString();
179 if (!info.trim().endsWith(TERMINATOR)) {
180 out.write(info);
181 out.write(LT);
182 buffer.delete(0, buffer.length());
183 } else {
184 cancel = true;
185 break;
186 }
187 }
188 }
189 while (es.available() > 0) {
190 c = es.read();
191 char ch = (char) c;
192 buffer.append(ch);
193 if (ch == '\n') {
194 info = buffer.toString();
195 if (!info.contains("WARNING"))
196 errorMessage += info;
197 out.write(info);
198 out.write(LT);
199 buffer.delete(0, buffer.length());
200 }
201 }
202 }
203 } catch (IOException e) {
204 try {
205 throw new InvocationTargetException(e);
206 } catch (InvocationTargetException e1) {
207 e1.printStackTrace();
208 }
209 }
210 out.flush();
211 if (errorMessage != null) {
212 throw new IOException(errorMessage);
213 }
214 if (interrupt) {
215 process.destroy();
216 initializeShell();
217 interrupt = false;
218 }
219 }
220 synchronized
221 public boolean ensureKnownHostKey(String user, String host) throws IOException {
222
223 boolean loadKeysMatch = false;
224 boolean accepted = false;
225 Process proc = Runtime.getRuntime().exec("ssh -o LogLevel=DEBUG3 " + user + "@" + host);
226 Pattern patternLoad = Pattern.compile("^debug3: load_hostkeys: loaded (\\d+) keys");
227 Pattern patternAuthSucceeded = Pattern.compile("^debug1: Authentication succeeded.*");
228
229 try {
230 InputStream es = proc.getErrorStream();
231 String info;
232 while (!loadKeysMatch) {
233 info = null;
234 StringBuffer buffer = new StringBuffer();
235 int c;
236 while (es.available() > 0) {
237 c = es.read();
238 char ch = (char) c;
239 buffer.append(ch);
240 if (ch == '\r') {
241 info = buffer.toString().trim();
242 Matcher m = patternLoad.matcher(info);
243 if(m.matches()) {
244 int keys = new Integer(m.group(1));
245 if (keys == 0) {
246 proc.destroy();
247 DialogRunnable runnable = new DialogRunnable("Host authenticity", "The authenticity of host '" + host + "(" + host + ")' can't be established.\nAre you sure you want to continue connecting ?", DialogRunnable.QUESTION);
248 Display.getDefault().syncExec(runnable);
249 accepted = runnable.result;
250 if (accepted){
251 proc = Runtime.getRuntime().exec("ssh -o StrictHostKeyChecking=no " + user + "@" + host);//add host key to known_hosts
252 try {
253 Thread.sleep(2000); //wait for process to finish
254 } catch (InterruptedException e) {
255 e.printStackTrace();
256 }
257 proc.destroy();
258 } else {
259 Display.getDefault().syncExec( new DialogRunnable("Host authenticity", "Host key verification failed.", DialogRunnable.ERROR));
260 }
261 } else {
262 String errorMsg = "";
263 // wait to check if key is the same and authentication succeeds
264 while (es.available() > 0) {
265 c = es.read();
266 ch = (char) c;
267 buffer.append(ch);
268 if (ch == '\r') {
269 info = buffer.toString().trim();
270 Matcher mAuthS = patternAuthSucceeded.matcher(info);
271 if(mAuthS.matches()) {
272 accepted = true;
273 break;
274 } else {
275 if (!info.startsWith("debug"))
276 errorMsg += info + "\n";
277 }
278 try {
279 Thread.sleep(100);
280 } catch (InterruptedException e) {
281 // TODO Auto-generated catch block
282 e.printStackTrace();
283 }
284 buffer.delete(0, buffer.length());
285 }
286 }
287 if (!accepted && !errorMsg.isEmpty()) {
288 Display.getDefault().syncExec( new DialogRunnable("Host authenticity", errorMsg, DialogRunnable.ERROR));
289 }
290 }
291 loadKeysMatch = true;
292 break;
293 }
294 buffer.delete(0, buffer.length());
295 }
296 }
297 }
298 es.close();
299 } catch (IOException e) {
300 try {
301 throw new InvocationTargetException(e);
302 } catch (InvocationTargetException e1) {
303 e1.printStackTrace();
304 }
305 }
306 return accepted;
307 }
308
309 /**
310 * Send command string to shell process and add special terminator string so
311 * reader knows when output is complete.
312 *
313 * @param command
314 * @throws IOException
315 */
316 private void sendToProcessAndTerminate(String command) throws IOException {
317 pos.write(command.getBytes());
318 pos.write(LT.getBytes());
319 pos.flush();
320 pos.write("echo $?".getBytes());
321 pos.write(TERMINATOR.getBytes());
322 pos.write(LT.getBytes());
323 pos.flush();
324 }
325
326 /**
327 * Interrupt any running processes.
328 */
329 public void interrupt() {
330 interrupt = true;
331 }
332}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/TerminalHandler.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/TerminalHandler.java
new file mode 100644
index 0000000..af5a5da
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/TerminalHandler.java
@@ -0,0 +1,132 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Intel - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13import org.eclipse.core.commands.AbstractHandler;
14import org.eclipse.core.commands.ExecutionException;
15import org.eclipse.core.runtime.IProgressMonitor;
16import org.eclipse.core.runtime.NullProgressMonitor;
17import org.eclipse.core.runtime.OperationCanceledException;
18import org.eclipse.jface.dialogs.ProgressMonitorDialog;
19import org.eclipse.jface.operation.IRunnableWithProgress;
20import org.eclipse.rse.core.model.IHost;
21import org.eclipse.rse.internal.terminals.ui.TerminalServiceHelper;
22import org.eclipse.rse.internal.terminals.ui.views.RSETerminalConnector;
23import org.eclipse.rse.internal.terminals.ui.views.TerminalViewTab;
24import org.eclipse.rse.internal.terminals.ui.views.TerminalViewer;
25import org.eclipse.rse.internal.terminals.ui.views.TerminalsUI;
26import org.eclipse.rse.services.terminals.ITerminalShell;
27import org.eclipse.rse.subsystems.terminals.core.ITerminalServiceSubSystem;
28import org.eclipse.rse.subsystems.terminals.core.elements.TerminalElement;
29import org.eclipse.rse.ui.SystemBasePlugin;
30import org.eclipse.swt.custom.CTabItem;
31import org.eclipse.swt.events.DisposeEvent;
32import org.eclipse.swt.events.DisposeListener;
33import org.eclipse.swt.widgets.Shell;
34import org.eclipse.tm.internal.terminal.control.ITerminalViewControl;
35import org.eclipse.tm.internal.terminal.provisional.api.ITerminalConnector;
36
37abstract public class TerminalHandler extends AbstractHandler {
38
39
40 protected Shell shell;
41
42 protected String changeTerm = "export TERM=vt100;";
43
44 abstract protected String getInitCmd();
45 abstract protected String getConnnectionName();
46 abstract protected String getDialogTitle();
47
48 protected String changeTerm() {
49 return changeTerm;
50 }
51
52 protected ITerminalShell getTerminalShellFromTab(CTabItem item) {
53 ITerminalShell terminalShell = null;
54 ITerminalViewControl terminalViewControl = (ITerminalViewControl) item
55 .getData(TerminalViewTab.DATA_KEY_CONTROL);
56 ITerminalConnector terminalConnector = terminalViewControl
57 .getTerminalConnector();
58 if (terminalConnector instanceof RSETerminalConnector) {
59 RSETerminalConnector rseTerminalConnector = (RSETerminalConnector) terminalConnector;
60 terminalShell = rseTerminalConnector.getTerminalHostShell();
61 }
62 return terminalShell;
63 }
64
65 protected boolean preProcess(final ITerminalServiceSubSystem terminalSubSystem) {
66 if (!terminalSubSystem.isConnected()) {
67 try {
68 ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
69 dialog.run(true, true, new IRunnableWithProgress(){
70 @Override
71 public void run(IProgressMonitor monitor) {
72 monitor.beginTask("Connecting to remote target ...", 100);
73 try {
74 terminalSubSystem.connect(new NullProgressMonitor(), false);
75 monitor.done();
76 } catch (Exception e) {
77 CommonHelper.showErrorDialog("Connection failure", null, e.getMessage());
78 monitor.done();
79
80 }
81 }
82 });
83 } catch (OperationCanceledException e) {
84 // user canceled, return silently
85 return false;
86 } catch (Exception e) {
87 SystemBasePlugin.logError(e.getLocalizedMessage(), e);
88 return false;
89 }
90 } else
91 return true;
92 return false;
93 }
94
95 public void execute(IHost host) throws ExecutionException {
96
97 final ITerminalServiceSubSystem terminalSubSystem = RemoteHelper.getTerminalSubSystem(host);
98
99 if (terminalSubSystem != null) {
100 TerminalsUI terminalsUI = TerminalsUI.getInstance();
101 TerminalViewer viewer = terminalsUI.activateTerminalsView();
102 if (preProcess(terminalSubSystem)) {
103 CTabItem tab = viewer.getTabFolder().createTabItem(
104 terminalSubSystem.getHost(), changeTerm() + getInitCmd());
105 //since RSETerminalConnector not exit the shell during the diconnection,
106 //we have manually exit it here
107 try {
108 tab.addDisposeListener(new DisposeListener() {
109 @Override
110 public void widgetDisposed(DisposeEvent e) {
111 Object source = e.getSource();
112 if (source instanceof CTabItem) {
113 CTabItem currentItem = (CTabItem) source;
114 ITerminalShell shell=getTerminalShellFromTab(currentItem);
115 if(shell!=null) {
116 shell.exit();
117 }
118 }
119 }
120 });
121 }catch(Exception e) {
122 e.printStackTrace();
123 }
124 TerminalElement element = TerminalServiceHelper
125 .createTerminalElement(tab, terminalSubSystem);
126 terminalSubSystem.addChild(element);
127
128 }
129 }
130 }
131
132}
diff --git a/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/YoctoCommand.java b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/YoctoCommand.java
new file mode 100644
index 0000000..23292d8
--- /dev/null
+++ b/plugins/org.yocto.remote.utils/src/org/yocto/remote/utils/YoctoCommand.java
@@ -0,0 +1,63 @@
1/*******************************************************************************
2 * Copyright (c) 2013 Intel Corporation.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Ioana Grigoropol(Intel) - initial API and implementation
10 *******************************************************************************/
11package org.yocto.remote.utils;
12
13
14public class YoctoCommand {
15 private String command;
16 private String initialDirectory;
17 private String arguments;
18 private ProcessStreamBuffer processBuffer;
19
20 public YoctoCommand(String command, String initialDirectory, String arguments){
21 this.setCommand(command);
22 this.setInitialDirectory(initialDirectory);
23 this.setArguments(arguments);
24 this.setProcessBuffer(new ProcessStreamBuffer(false));
25 }
26
27 public String getCommand() {
28 return command;
29 }
30
31 public void setCommand(String command) {
32 this.command = "bash -l -c \"" + command + "\"";
33 }
34
35 public String getInitialDirectory() {
36 return initialDirectory;
37 }
38
39 public void setInitialDirectory(String initialDirectory) {
40 this.initialDirectory = initialDirectory;
41 }
42
43 public String getArguments() {
44 return arguments;
45 }
46
47 public void setArguments(String arguments) {
48 this.arguments = arguments;
49 }
50
51 public ProcessStreamBuffer getProcessBuffer() {
52 return processBuffer;
53 }
54
55 public void setProcessBuffer(ProcessStreamBuffer processBuffer) {
56 this.processBuffer = processBuffer;
57 }
58
59 @Override
60 public String toString() {
61 return command + " " + arguments;
62 }
63}