Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f79d47dacc4f2f66d7cff9a631d199c823d35ea0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*******************************************************************************
 * Copyright (c) 2012 Wind River Systems, Inc. and others. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.te.tests.tcf;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.core.runtime.IPath;
import org.eclipse.tcf.core.TransientPeer;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.runtime.model.factory.Factory;
import org.eclipse.tcf.te.runtime.utils.Host;
import org.eclipse.tcf.te.runtime.utils.net.IPAddressUtil;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelLookupService;
import org.eclipse.tcf.te.tcf.locator.model.Model;
import org.eclipse.tcf.te.tests.CoreTestCase;

/**
 * TCF test case implementation.
 * <p>
 * Launches a TCF agent at local host and make it available for a test case.
 */
public class TcfTestCase extends CoreTestCase {
	// The agent launcher instance
	private AgentLauncher launcher;
	// The peer instance
	protected IPeer peer;
	// The peer model instance
	protected IPeerModel peerModel;

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tests.CoreTestCase#setUp()
	 */
	@Override
	protected void setUp() throws Exception {
	    super.setUp();
	    launchAgent();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tests.CoreTestCase#tearDown()
	 */
	@Override
	protected void tearDown() throws Exception {
		if (launcher != null) launcher.dispose();
		peer = null;
		peerModel = null;
	    super.tearDown();
	}

	/**
	 * Launches a TCF agent at local host.
	 */
	protected void launchAgent() {
		// Get the agent location
		IPath path = getAgentLocation();
		assertNotNull("Cannot determine TCF agent location.", path); //$NON-NLS-1$
		// Add the agent executable name
		path = path.append("agent"); //$NON-NLS-1$
		if (Host.isWindowsHost()) path = path.addFileExtension("exe"); //$NON-NLS-1$
		assertTrue("Invalid agent location: " + path.toString(), path.toFile().isFile()); //$NON-NLS-1$

		Throwable error = null;
		String message = null;

		// If the agent is not marked executable on Linux, we have to change that
		if (Host.isLinuxHost() && !path.toFile().canExecute()) {
			try {
				Runtime.getRuntime().exec(new String[] { "chmod", "u+x", path.toString() }); //$NON-NLS-1$ //$NON-NLS-2$
			} catch (IOException e) {
				error = e;
				message = e.getLocalizedMessage();
			}
		}
		assertNull("Failed to make the agent executable for the current user.", message); //$NON-NLS-1$

		error = null;
		message = null;

		assertTrue("Agent should be executable but is not.", path.toFile().canExecute()); //$NON-NLS-1$

		// Create the agent launcher
		launcher = new AgentLauncher(path);
		try {
			launcher.launch();
		} catch (Throwable e) {
			error = e;
			message = e.getLocalizedMessage();
		}
		assertNull("Failed to launch agent: " + message, error); //$NON-NLS-1$

		error = null;
		message = null;

		assertNotNull("Process handle not associated with launcher.", launcher.getProcess()); //$NON-NLS-1$
		assertNotNull("Process output reader not associated with launcher.", launcher.getOutputReader()); //$NON-NLS-1$

		Process process = launcher.getProcess();
		int exitCode = -1;
		try {
			exitCode = process.exitValue();
		} catch (IllegalThreadStateException e) {
			error = e;
			message = e.getLocalizedMessage();
		}
		assertNotNull("Agent process died with exit code " + exitCode, error); //$NON-NLS-1$

		error = null;
		message = null;

		// The agent is started with "-S" to write out the peer attributes in JSON format.
		String output = null;
		int counter = 10;
		while (counter > 0 && output == null) {
			// Try to read in the output
			output = launcher.getOutputReader().getOutput();
			if ("".equals(output)) { //$NON-NLS-1$
				output = null;
				waitAndDispatch(200);
			}
			counter--;
		}
		assertNotNull("Failed to read output from agent.", output); //$NON-NLS-1$

		// Strip away "Server-Properties:"
		output = output.replace("Server-Properties:", " "); //$NON-NLS-1$ //$NON-NLS-2$
		output = output.trim();

		// Read into an object
		Object object = parseOne(output);
		@SuppressWarnings("unchecked")
        final Map<String, String> attrs = new HashMap<String, String>((Map<String, String>)object);

		// Lookup the corresponding peer object
		final ILocatorModel model = Model.getModel();
		assertNotNull("Failed to access locator model instance.", model); //$NON-NLS-1$

		// The expected peer id is "<transport>:<canonical IP>:<port>"
		String transport = attrs.get(IPeer.ATTR_TRANSPORT_NAME);
		assertNotNull("Unexpected return value 'null'.", transport); //$NON-NLS-1$
		String port = attrs.get(IPeer.ATTR_IP_PORT);
		assertNotNull("Unexpected return value 'null'.", port); //$NON-NLS-1$
		String ip = IPAddressUtil.getInstance().getIPv4LoopbackAddress();
		assertNotNull("Unexpected return value 'null'.", ip); //$NON-NLS-1$

		final String id = transport + ":" + ip + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$
		final AtomicReference<IPeerModel> node = new AtomicReference<IPeerModel>();

		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				node.set(model.getService(ILocatorModelLookupService.class).lkupPeerModelById(id));
				// If the peer model is not found by id, try the agent id as fallback.
				if (node.get() == null) {
					String agentID = attrs.get(IPeer.ATTR_AGENT_ID);
					assertNotNull("Unexpected return value 'null'.", agentID); //$NON-NLS-1$
					IPeerModel[] candidates = model.getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(agentID);
					if (candidates != null && candidates.length > 0) node.set(candidates[0]);
				}
			}
		};
		assertFalse("Test is running in TCF dispatch thread.", Protocol.isDispatchThread()); //$NON-NLS-1$
		Protocol.invokeAndWait(runnable);

		// If the peer model is still not found, we create a transient peer
		if (node.get() == null) {
			attrs.put(IPeer.ATTR_ID, id);
			attrs.put(IPeer.ATTR_IP_HOST, ip);
			peer = new TransientPeer(attrs);
			peerModel = Factory.getInstance().newInstance(IPeerModel.class, new Object[] { model, peer });
		} else {
			peerModel = node.get();
			peer = peerModel.getPeer();
		}
		assertNotNull("Failed to determine the peer to use for the tests.", peer); //$NON-NLS-1$
	}

	/**
	 * Returns the agent location.
	 *
	 * @return The agent location or <code>null</code> if not found.
	 */
	protected IPath getAgentLocation() {
		return getDataLocation("agent", true, true); //$NON-NLS-1$
	}

	/**
	 * Parses a object from the given encoded string.
	 *
	 * @param encoded The encoded string. Must not be <code>null</code>.
	 * @return The object
	 */
	private static Object parseOne(final String encoded) {
		assertNotNull(encoded);

		final AtomicReference<Object> object = new AtomicReference<Object>();
		final AtomicReference<String> message = new AtomicReference<String>();
		final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					object.set(JSON.parseOne(encoded.getBytes("UTF-8"))); //$NON-NLS-1$
				} catch (IOException e) {
					error.set(e);
					message.set(e.getLocalizedMessage());
				}
			}
		};
		assertFalse("Test is running in TCF dispatch thread.", Protocol.isDispatchThread()); //$NON-NLS-1$
		Protocol.invokeAndWait(runnable);

		assertNull("Failed to parse server properties: " + message.get(), error.get()); //$NON-NLS-1$
		assertTrue("Server properties object is not of expected type Map.", object.get() instanceof Map); //$NON-NLS-1$

		return object.get();
	}
}

Back to the top