Skip to main content
summaryrefslogtreecommitdiffstats
blob: 20a014435bc277734dd3242fd383cda5f0ae7973 (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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * 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:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.ote.client.msg.core.internal;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;
import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import org.eclipse.osee.connection.service.IServiceConnector;
import org.eclipse.osee.framework.jdk.core.util.network.PortUtil;
import org.eclipse.osee.framework.logging.OseeLog;
import org.eclipse.osee.ote.client.msg.IOteMessageService;
import org.eclipse.osee.ote.client.msg.core.IMessageDbFactory;
import org.eclipse.osee.ote.client.msg.core.IMessageSubscription;
import org.eclipse.osee.ote.client.msg.core.db.AbstractMessageDataBase;
import org.eclipse.osee.ote.core.environment.UserTestSessionKey;
import org.eclipse.osee.ote.core.environment.interfaces.IHostTestEnvironment;
import org.eclipse.osee.ote.message.commands.RecordCommand;
import org.eclipse.osee.ote.message.commands.RecordCommand.MessageRecordDetails;
import org.eclipse.osee.ote.message.enums.DataType;
import org.eclipse.osee.ote.message.interfaces.IMsgToolServiceClient;
import org.eclipse.osee.ote.message.interfaces.IRemoteMessageService;
import org.eclipse.osee.ote.message.interfaces.ITestEnvironmentMessageSystem;
import org.eclipse.osee.ote.message.tool.IFileTransferHandle;
import org.eclipse.osee.ote.message.tool.TransferConfig;
import org.eclipse.osee.ote.message.tool.UdpFileTransferHandler;
import org.eclipse.osee.ote.service.ConnectionEvent;
import org.eclipse.osee.ote.service.IMessageDictionary;
import org.eclipse.osee.ote.service.IMessageDictionaryListener;
import org.eclipse.osee.ote.service.IOteClientService;
import org.eclipse.osee.ote.service.ITestConnectionListener;

/**
 * @author Ken J. Aguilar
 */
public class MessageSubscriptionService implements IOteMessageService, IMessageDictionaryListener, ITestConnectionListener, IMsgToolServiceClient {

	/** * Static Fields ** */
	private static final int MAX_CONCURRENT_WORKER_THREADS = Runtime.getRuntime().availableProcessors() + 1;

	private final InetAddress localAddress;
	private final LinkedList<MessageSubscription> subscriptions = new LinkedList<MessageSubscription>();
	private IMsgToolServiceClient exportedThis = null;
	private AbstractMessageDataBase msgDatabase;
	private UdpFileTransferHandler fileTransferHandler;

	private final ExecutorService threadPool =
		Executors.newFixedThreadPool(MAX_CONCURRENT_WORKER_THREADS, new ThreadFactory() {
			private final ThreadGroup group =
				new ThreadGroup(Thread.currentThread().getThreadGroup(), "Msg Watch Workers");
			private int count = 1;

			public Thread newThread(Runnable arg0) {
				Thread thread = new Thread(group, arg0, "Msg Watch Wrkr - " + count++);
				thread.setDaemon(false);
				return thread;
			}

		});

	/**
	 * Monitors a set of channels for message updates and dispatches the updates to worker threads
	 */
	private UpdateDispatcher dispatcher = null;
	private IRemoteMessageService service;

	private final IMessageDbFactory messageDbFactory;
	private final IOteClientService clientService;

	public MessageSubscriptionService(IOteClientService service, IMessageDbFactory messageDbFactory) throws IOException {
		this.messageDbFactory = messageDbFactory;
		localAddress = InetAddress.getLocalHost();
		OseeLog.log(Activator.class, Level.INFO,
				"OTE client message service started on: " + localAddress.getHostAddress());
		clientService = service;
		clientService.addDictionaryListener(this);
		clientService.addConnectionListener(this);
	}

	public synchronized IMessageSubscription subscribe(String name) {
		MessageSubscription subscription = new MessageSubscription(this);
		subscription.bind(name);
		if (msgDatabase != null) {
			subscription.attachMessageDb(msgDatabase);
			if (service != null) {
				subscription.attachService(service);
			}
		}
		subscriptions.add(subscription);
		return subscription;
	}

	/**
	 * Shuts down the client message service. All worker threads will be terminated and all IO resources will be closed.
	 */
	public void shutdown() {
		OseeLog.log(MessageSubscriptionService.class, Level.INFO, "shutting down subscription service");
		clientService.removeDictionaryListener(this);
		clientService.removeConnectionListener(this);
		shutdownDispatcher();
		threadPool.shutdown();
		try {
			threadPool.awaitTermination(5, TimeUnit.SECONDS);
		} catch (InterruptedException ex1) {
			OseeLog.log(Activator.class, Level.WARNING, ex1.toString(), ex1);
		}
	}

	@Override
	public synchronized void onConnectionLost(IServiceConnector connector, IHostTestEnvironment testHost) {
		OseeLog.log(Activator.class, Level.INFO, "connection lost: ote client message service halted");
		shutdownDispatcher();
		msgDatabase.detachService(null);
		for (MessageSubscription subscription : subscriptions) {
			subscription.detachService(null);
		}
		exportedThis = null;
		service = null;
	}

	@Override
	public synchronized void onPostConnect(ConnectionEvent event) {
		assert msgDatabase != null;
		OseeLog.log(Activator.class, Level.INFO, "connecting OTE client message service");
		if (event.getEnvironment() instanceof ITestEnvironmentMessageSystem) {
			ITestEnvironmentMessageSystem env = (ITestEnvironmentMessageSystem) event.getEnvironment();
			try {
				service = env.getMessageToolServiceProxy();
				if (service == null) {
					throw new Exception("could not get message tool service proxy");
				}
				exportedThis = (IMsgToolServiceClient) event.getConnector().export(this);
			} catch (Exception e) {
				OseeLog.log(MessageSubscriptionService.class, Level.SEVERE,
						"failed to create exported Message Tool Client", e);
				service = null;
				exportedThis = null;
				return;
			}

			try {
				dispatcher = new UpdateDispatcher(service.getMsgUpdateSocketAddress());
			} catch (Exception e) {
				OseeLog.log(MessageSubscriptionService.class, Level.SEVERE, "failed to create update dispatcher", e);
				service = null;
				exportedThis = null;
				return;
			}

			try {
				createProccessors();
			} catch (Exception e) {
				OseeLog.log(MessageSubscriptionService.class, Level.SEVERE, "failed to create update processors", e);
				service = null;
				exportedThis = null;
				return;
			}

			msgDatabase.attachToService(service, exportedThis);
			for (MessageSubscription subscription : subscriptions) {
				subscription.attachService(service);
			}
			dispatcher.start();
		}
	}

	private void createProccessors() throws IOException {
		Set<? extends DataType> availableTypes = service.getAvailablePhysicalTypes();

		int port = PortUtil.getInstance().getConsecutiveValidPorts(availableTypes.size());
		for (DataType type : availableTypes) {
			final ChannelProcessor handler = new ChannelProcessor(1, type.getToolingBufferSize(), threadPool, msgDatabase, type);

			dispatcher.addChannel(localAddress, port, type, handler);
			port++;
		}
	}

	private void shutdownDispatcher() {
		if (dispatcher != null && dispatcher.isRunning()) {
			try {
				dispatcher.close();
			} catch (Throwable ex) {
				OseeLog.log(MessageSubscriptionService.class, Level.WARNING, "exception while closing down dispatcher", ex);
			} finally {
				dispatcher = null;
			}
		}
	}

	@Override
	public synchronized void onPreDisconnect(ConnectionEvent event) {
		if (service == null) {
			return;
		}
		msgDatabase.detachService(service);
		for (MessageSubscription subscription : subscriptions) {
			subscription.detachService(service);
		}
		try {
			event.getConnector().unexport(this);
		} catch (Exception e) {
			OseeLog.log(MessageSubscriptionService.class, Level.WARNING, "problems unexporting Message Tool Client", e);
		}
		shutdownDispatcher();
		exportedThis = null;
		service = null;
	}

	@Override
	public void changeIsScheduled(String msgName, boolean isScheduled) throws RemoteException {

	}

	@Override
	public void changeRate(String msgName, double rate) throws RemoteException {

	}

	@Override
	public InetSocketAddress getAddressByType(String messageName, DataType dataType) throws RemoteException {
		final DatagramChannel channel = dispatcher.getChannel(dataType);
		OseeLog.log(Activator.class, Level.INFO, String.format(
				"callback from remote msg manager: msg=%s, type=%s, ip=%s:%d\n", messageName,
				dataType.name(), localAddress.toString(), channel.socket().getLocalPort()));

		return new InetSocketAddress(localAddress, channel.socket().getLocalPort());
	}

	@Override
	public UserTestSessionKey getTestSessionKey() throws RemoteException {
		return clientService.getSessionKey();
	}

	@Override
	public synchronized void onDictionaryLoaded(IMessageDictionary dictionary) {
		msgDatabase = messageDbFactory.createMessageDataBase(dictionary);
		for (MessageSubscription subscription : subscriptions) {
			subscription.attachMessageDb(msgDatabase);
		}
	}

	@Override
	public synchronized void onDictionaryUnloaded(IMessageDictionary dictionary) {
		for (MessageSubscription subscription : subscriptions) {
			subscription.detachMessageDb(msgDatabase);
		}
		msgDatabase = null;
	}

	@Override
	public synchronized IFileTransferHandle startRecording(String fileName, List<MessageRecordDetails> list) throws FileNotFoundException, IOException {
		if (service == null) {
			throw new IllegalStateException("can't record: not connected to test server");
		}
		if (fileTransferHandler == null) {
			fileTransferHandler = new UdpFileTransferHandler();
			fileTransferHandler.start();
		}
		int port = PortUtil.getInstance().getValidPort();
		// get the address of the socket the message recorder is going to write
		// data to
		InetSocketAddress recorderOutputAddress = service.getRecorderSocketAddress();

		// setup a transfer from a socket to a file
		TransferConfig config =
			new TransferConfig(fileName, recorderOutputAddress,
					new InetSocketAddress(InetAddress.getLocalHost(), port),
					TransferConfig.Direction.SOCKET_TO_FILE, 128000);
		IFileTransferHandle handle = fileTransferHandler.registerTransfer(config);

		// send the command to start recording
		RecordCommand cmd =
			new RecordCommand(exportedThis, new InetSocketAddress(InetAddress.getLocalHost(), port), list);
		service.startRecording(cmd);
		OseeLog.log(Activator.class, Level.INFO,
				"recording started with " + list.size() + " entries, recorder output socket="
				+ recorderOutputAddress.toString());
		return handle;
	}

	@Override
	public synchronized void stopRecording() throws RemoteException, IOException {
		try {
			service.stopRecording();
		} finally {
			if (fileTransferHandler != null && fileTransferHandler.hasActiveTransfers()) {
				fileTransferHandler.stopAllTransfers();
			}
			fileTransferHandler = null;
		}
	}

	public AbstractMessageDataBase getMsgDatabase() {
		return msgDatabase;
	}

	public IRemoteMessageService getService() {
		return service;
	}

	public void removeSubscription(MessageSubscription subscription) {
		subscriptions.remove(subscription);
	}
}

Back to the top