Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b00388c53ee4c54ee8aad63e7cc8272fba3bb9a1 (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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*******************************************************************************
 * Copyright (c) 2011, 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.tcf.locator.nodes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.ILocator;
import org.eclipse.tcf.te.runtime.utils.net.IPAddressUtil;
import org.eclipse.tcf.te.tcf.core.Tcf;
import org.eclipse.tcf.te.tcf.core.listeners.interfaces.IChannelStateChangeListener;
import org.eclipse.tcf.te.tcf.locator.Scanner;
import org.eclipse.tcf.te.tcf.locator.activator.CoreBundleActivator;
import org.eclipse.tcf.te.tcf.locator.interfaces.IModelListener;
import org.eclipse.tcf.te.tcf.locator.interfaces.IScanner;
import org.eclipse.tcf.te.tcf.locator.interfaces.ITracing;
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.interfaces.services.ILocatorModelPeerNodeQueryService;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelRefreshService;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelService;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelUpdateService;
import org.eclipse.tcf.te.tcf.locator.listener.ChannelStateChangeListener;
import org.eclipse.tcf.te.tcf.locator.listener.LocatorListener;
import org.eclipse.tcf.te.tcf.locator.services.LocatorModelLookupService;
import org.eclipse.tcf.te.tcf.locator.services.LocatorModelPeerNodeQueryService;
import org.eclipse.tcf.te.tcf.locator.services.LocatorModelRefreshService;
import org.eclipse.tcf.te.tcf.locator.services.LocatorModelUpdateService;


/**
 * Default locator model implementation.
 */
public class LocatorModel extends PlatformObject implements ILocatorModel {
	// The unique model id
	private final UUID uniqueId = UUID.randomUUID();
	// Flag to mark the model disposed
	private boolean disposed;

	// The list of known peers
	/* default */ final Map<String, IPeerModel> peers = new HashMap<String, IPeerModel>();
	// The list of "proxied" peers per proxy peer id
	/* default */ final Map<String, List<IPeerModel>> peerChildren = new HashMap<String, List<IPeerModel>>();

	// Reference to the scanner
	private IScanner scanner = null;

	// Reference to the model locator listener
	private ILocator.LocatorListener locatorListener = null;
	// Reference to the model channel state change listener
	private IChannelStateChangeListener channelStateChangeListener = null;

	// The list of registered model listeners
	private final List<IModelListener> modelListener = new ArrayList<IModelListener>();

	// Reference to the refresh service
	private final ILocatorModelRefreshService refreshService = new LocatorModelRefreshService(this);
	// Reference to the lookup service
	private final ILocatorModelLookupService lookupService = new LocatorModelLookupService(this);
	// Reference to the update service
	private final ILocatorModelUpdateService updateService = new LocatorModelUpdateService(this);
	// Reference to the query service
	private final ILocatorModelPeerNodeQueryService queryService = new LocatorModelPeerNodeQueryService(this);

	/**
	 * Constructor.
	 */
	public LocatorModel() {
		super();
		disposed = false;

		channelStateChangeListener = new ChannelStateChangeListener(this);
		Tcf.addChannelStateChangeListener(channelStateChangeListener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#addListener(org.eclipse.tcf.te.tcf.locator.core.interfaces.IModelListener)
	 */
	@Override
	public void addListener(IModelListener listener) {
		Assert.isNotNull(listener);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.addListener( " + listener + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$
		}

		if (!modelListener.contains(listener)) modelListener.add(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#removeListener(org.eclipse.tcf.te.tcf.locator.core.interfaces.IModelListener)
	 */
	@Override
	public void removeListener(IModelListener listener) {
		Assert.isNotNull(listener);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.removeListener( " + listener + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$
		}

		modelListener.remove(listener);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel#getListener()
	 */
	@Override
	public IModelListener[] getListener() {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		return modelListener.toArray(new IModelListener[modelListener.size()]);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#dispose()
	 */
	@Override
	public void dispose() {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.dispose()", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$
		}

		// If already disposed, we are done immediately
		if (disposed) return;

		disposed = true;

		final IModelListener[] listeners = getListener();
		if (listeners.length > 0) {
			Protocol.invokeLater(new Runnable() {
				@Override
				public void run() {
					for (IModelListener listener : listeners) {
						listener.locatorModelDisposed(LocatorModel.this);
					}
				}
			});
		}
		modelListener.clear();

		if (locatorListener != null) {
			Protocol.getLocator().removeListener(locatorListener);
			locatorListener = null;
		}

		if (channelStateChangeListener != null) {
			Tcf.removeChannelStateChangeListener(channelStateChangeListener);
			channelStateChangeListener = null;
		}

		if (scanner != null) {
			stopScanner();
			scanner = null;
		}

		peers.clear();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#isDisposed()
	 */
	@Override
	public boolean isDisposed() {
		return disposed;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getPeers()
	 */
	@Override
	public IPeerModel[] getPeers() {
		final AtomicReference<IPeerModel[]> result = new AtomicReference<IPeerModel[]>();

		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				result.set(peers.values().toArray(new IPeerModel[peers.values().size()]));
			}
		};

		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeAndWait(runnable);

		return result.get();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel#getChildren(java.lang.String)
	 */
	@Override
    public List<IPeerModel> getChildren(final String parentPeerID) {
		Assert.isNotNull(parentPeerID);

		final AtomicReference<List<IPeerModel>> result = new AtomicReference<List<IPeerModel>>();

		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				List<IPeerModel> children = peerChildren.get(parentPeerID);
				if (children == null) children = Collections.emptyList();
				result.set(children);
			}
		};

		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeAndWait(runnable);

		return Collections.unmodifiableList(result.get());
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel#setChildren(java.lang.String, java.util.List)
	 */
	@Override
    public void setChildren(String parentPeerID, List<IPeerModel> children) {
		Assert.isNotNull(parentPeerID);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (children == null || children.size() == 0) {
			peerChildren.remove(parentPeerID);
		} else {
			peerChildren.put(parentPeerID, new ArrayList<IPeerModel>(children));
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.runtime.PlatformObject#getAdapter(java.lang.Class)
	 */
	@Override
	public Object getAdapter(Class adapter) {
		if (adapter.isAssignableFrom(ILocator.LocatorListener.class)) {
			return locatorListener;
		}
		if (adapter.isAssignableFrom(IScanner.class)) {
			return scanner;
		}
		if (adapter.isAssignableFrom(ILocatorModelRefreshService.class)) {
			return refreshService;
		}
		if (adapter.isAssignableFrom(ILocatorModelLookupService.class)) {
			return lookupService;
		}
		if (adapter.isAssignableFrom(ILocatorModelUpdateService.class)) {
			return updateService;
		}
		if (adapter.isAssignableFrom(ILocatorModelPeerNodeQueryService.class)) {
			return queryService;
		}
		if (adapter.isAssignableFrom(Map.class)) {
			return peers;
		}

		return super.getAdapter(adapter);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
	    return uniqueId.hashCode();
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public final boolean equals(Object obj) {
		if (obj instanceof LocatorModel) {
			return uniqueId.equals(((LocatorModel)obj).uniqueId);
		}
		return super.equals(obj);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getService(java.lang.Class)
	 */
	@Override
	@SuppressWarnings("unchecked")
	public <V extends ILocatorModelService> V getService(Class<V> serviceInterface) {
		Assert.isNotNull(serviceInterface);
		return (V)getAdapter(serviceInterface);
	}

	/**
	 * Check if the locator listener has been created and registered
	 * to the global locator service.
	 * <p>
	 * <b>Note:</b> This method is not intended to be call from clients.
	 */
	public void checkLocatorListener() {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(Protocol.getLocator());

		if (locatorListener == null) {
			locatorListener = doCreateLocatorListener(this);
			Protocol.getLocator().addListener(locatorListener);
		}
	}

	/**
	 * Creates the locator listener instance.
	 *
	 * @param model The parent model. Must not be <code>null</code>.
	 * @return The locator listener instance.
	 */
	protected ILocator.LocatorListener doCreateLocatorListener(ILocatorModel model) {
		Assert.isNotNull(model);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		return new LocatorListener(model);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getScanner()
	 */
	@Override
	public IScanner getScanner() {
		if (scanner == null) scanner = new Scanner(this);
		return scanner;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#startScanner(long, long)
	 */
	@Override
	public void startScanner(long delay, long schedule) {
		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.startScanner( " + delay + ", " + schedule + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		}

		IScanner scanner = getScanner();
		Assert.isNotNull(scanner);

		// Pass on the schedule parameter
		Map<String, Object> config = new HashMap<String, Object>(scanner.getConfiguration());
		config.put(IScanner.PROP_SCHEDULE, Long.valueOf(schedule));
		scanner.setConfiguration(config);

		// The default scanner implementation is a job.
		// -> schedule here if it is a job
		if (scanner instanceof Job) {
			Job job = (Job)scanner;
			job.setSystem(true);
			job.setPriority(Job.DECORATE);
			job.schedule(delay);
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#stopScanner()
	 */
	@Override
	public void stopScanner() {
		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.stopScanner()", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$
		}

		if (scanner != null) {
			// Terminate the scanner
			scanner.terminate();
			// Reset the scanner reference
			scanner = null;
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel#validatePeer(org.eclipse.tcf.protocol.IPeer)
	 */
	@Override
	public IPeer validatePeer(IPeer peer) {
		Assert.isNotNull(peer);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeer( " + peer.getID() + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$
		}

		IPeer result = peer;

		// Get the loopback address
		String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress();
		// Get the peer IP
		String peerIP = peer.getAttributes().get(IPeer.ATTR_IP_HOST);

		// If the peer node is for local host, we ignore all peers not being
		// associated with the loopback address.
		if (IPAddressUtil.getInstance().isLocalHost(peerIP) && !loopback.equals(peerIP)) {
			// Not loopback address -> drop the peer
			result = null;

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
				CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeer: local host peer but not loopback address -> peer node dropped" //$NON-NLS-1$
															, ITracing.ID_TRACE_LOCATOR_MODEL, this);
			}
		}

	    return result;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.ILocatorModel#validatePeerNodeForAdd(org.eclipse.tcf.te.tcf.locator.core.interfaces.nodes.IPeerModel)
	 */
	@Override
	public IPeerModel validatePeerNodeForAdd(IPeerModel node) {
		Assert.isNotNull(node);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// Get the peer from the peer node
		IPeer peer = node.getPeer();
		if (peer == null) return node;

		// Skip static peer IP address validation
		boolean isStatic = node.isStatic();
		if (isStatic) return node;

		// Skip validation if the transport type is not TCP or SSL
		String transport = peer.getTransportName();
		if (transport == null || !"TCP".equals(transport) && !"SSL".equals(transport)){ //$NON-NLS-1$ //$NON-NLS-2$
			return node;
		}

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd( " + peer.getID() + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$
		}

		IPeerModel result = node;

		// Get the loopback address
		String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress();
		// Get the peer IP
		String peerIP = peer.getAttributes().get(IPeer.ATTR_IP_HOST);

		// If the peer node is for local host, we ignore all peers not being
		// associated with the loopback address.
		if (IPAddressUtil.getInstance().isLocalHost(peerIP) && !loopback.equals(peerIP)) {
			boolean drop = true;

			// Simulator nodes appears on local host IP addresses too, but does not have
			// a loopback peer available. We have to check the agent ID to determine if
			// a specific node can be dropped
			String agentID = peer.getAgentID();
			if (agentID != null) {
				// Get all discovered peers
				Map<String, IPeer> peers = Protocol.getLocator().getPeers();
				// Sort them by agent id
				Map<String, List<IPeer>> byAgentID = new HashMap<String, List<IPeer>>();

				for (IPeer candidate : peers.values()) {
					if (candidate.getAgentID() == null) continue;

					List<IPeer> l = byAgentID.get(candidate.getAgentID());
					if (l == null) {
						l = new ArrayList<IPeer>();
						byAgentID.put(candidate.getAgentID(), l);
					}
					Assert.isNotNull(l);
					if (!l.contains(candidate)) l.add(candidate);
				}

				// Check all peers found for the same agent ID as the current peer to validate
				List<IPeer> candidates = byAgentID.get(agentID);
				if (candidates != null && candidates.size() > 1) {
					// Check if the found peers contains one with the loopback address
					drop = false;
					for (IPeer candidate : candidates) {
						String ip = candidate.getAttributes().get(IPeer.ATTR_IP_HOST);
						if (IPAddressUtil.getInstance().isLocalHost(ip) && loopback.equals(ip)) {
							drop = true;
							break;
						}
					}
				} else {
					// No other node for this agent ID -> do not drop the peer
					drop = false;
				}
			}


			if (drop) {
				// Not loopback address -> drop the peer
				result = null;

				if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
					CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: local host peer but not loopback address -> peer node dropped", //$NON-NLS-1$
																ITracing.ID_TRACE_LOCATOR_MODEL, this);
				}
			}
		}

		// Continue filtering if the node is not yet dropped
		if (result != null) {
			// Peers are filtered by agent id. Don't add the peer node
			// if we have another peer node already having the same agent id
			String agentId = peer.getAgentID();
			IPeerModel[] previousNodes = agentId != null ? getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(agentId) : new IPeerModel[0];

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
				CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: agentId=" + agentId + ", Matching peer nodes " //$NON-NLS-1$ //$NON-NLS-2$
															+ (previousNodes.length > 0 ? "found (" + previousNodes.length +")" : "not found --> DONE") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
															, ITracing.ID_TRACE_LOCATOR_MODEL, this);
			}

			for (IPeerModel previousNode : previousNodes) {
				// Get the peer for the previous node
				IPeer previousPeer = previousNode.getPeer();
				if (previousPeer != null) {
					// Get the IP address of the previous node
					String previousPeerIP = previousPeer.getAttributes().get(IPeer.ATTR_IP_HOST);
					if (IPAddressUtil.getInstance().isLocalHost(previousPeerIP) && !loopback.equals(previousPeerIP) && loopback.equals(peerIP)) {
						// Remove the previous node from the model
						getService(ILocatorModelUpdateService.class).remove(previousNode);

						if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
							CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: Previous peer removed and replaced by new peer representing the loopback address" //$NON-NLS-1$
											, ITracing.ID_TRACE_LOCATOR_MODEL, this);
						}

						continue;
					}

					// Get the ports
					String peerPort = peer.getAttributes().get(IPeer.ATTR_IP_PORT);
					if (peerPort == null || "".equals(peerPort)) peerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$
					String previousPeerPort = previousPeer.getAttributes().get(IPeer.ATTR_IP_PORT);
					if (previousPeerPort == null || "".equals(previousPeerPort)) previousPeerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$

					if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
						CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: peerIP=" + peerIP //$NON-NLS-1$
										+ ", peerPort=" + peerPort + ", previousPeerPort=" + previousPeerPort //$NON-NLS-1$ //$NON-NLS-2$
										, ITracing.ID_TRACE_LOCATOR_MODEL, this);
					}

					// If the ports of the agent instances are identical,
					// than try to find the best representation of the agent instance
					if (peerPort.equals(previousPeerPort))  {
						// Drop the current node
						result = null;

						if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
							CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: Previous peer node kept, new peer node dropped" //$NON-NLS-1$
											, ITracing.ID_TRACE_LOCATOR_MODEL, this);
						}


						// Break the loop if the ports matched
						break;
					}

					if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
						CoreBundleActivator.getTraceHandler().trace("LocatorModel.validatePeerNodeForAdd: Previous peer node kept, new peer node added (Port mismatch)" //$NON-NLS-1$
										, ITracing.ID_TRACE_LOCATOR_MODEL, this);
					}
				}
			}
		}

		return result;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel#validateChildPeerNodeForAdd(org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel)
	 */
	@Override
	public IPeerModel validateChildPeerNodeForAdd(final IPeerModel node) {
		Assert.isNotNull(node);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.validateChildPeerNodeForAdd( " + node.getPeerId() + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$
		}

		// Determine the parent node. If null, the child node is invalid
		// and cannot be added
		final IPeerModel parent = node.getParent(IPeerModel.class);
		if (parent == null) return null;

		return validateChildPeerNodeForAdd(parent, node);
	}

	/**
	 * Validates the given child peer model node in relation to the given parent peer model node
	 * hierarchy.
	 * <p>
	 * The method is recursive.
	 *
	 * @param parent The parent model node. Must not be <code>null</code>.
	 * @param node The child model node. Must not be <code>null</code>.
	 *
	 * @return The validated child peer model node, or <code>null</code>.
	 */
	protected IPeerModel validateChildPeerNodeForAdd(IPeerModel parent, IPeerModel node) {
		Assert.isNotNull(parent);
		Assert.isNotNull(node);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.validateChildPeerNodeForAdd( " + parent.getPeerId() + ", " + node.getPeerId() + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		}

		// Validate against the given parent
		if (doValidateChildPeerNodeForAdd(parent, node) == null) {
			return null;
		}

		// If the parent node is child node by itself, validate the
		// child node against the parent parent node.
		if (parent.getParent(IPeerModel.class) != null) {
			IPeerModel parentParentNode = parent.getParent(IPeerModel.class);
			if (doValidateChildPeerNodeForAdd(parentParentNode, node) == null) {
				return null;
			}

			// And validate the child node against all child nodes of the parent parent.
			List<IPeerModel> childrenList = getChildren(parentParentNode.getPeerId());
			IPeerModel[] children = childrenList.toArray(new IPeerModel[childrenList.size()]);
			for (IPeerModel parentParentChild : children) {
				if (node.equals(parentParentChild) || parent.equals(parentParentChild)) {
					return null;
				}
				if (doValidateChildPeerNodeForAdd(parentParentChild, node) == null) {
					return null;
				}
			}
		}

		return node;
	}

	/**
	 * Validates the given child peer model node in relation to the given parent peer model node.
	 * <p>
	 * The method is non-recursive.
	 *
	 * @param parent The parent model node. Must not be <code>null</code>.
	 * @param node The child model node. Must not be <code>null</code>.
	 *
	 * @return The validated child peer model node, or <code>null</code>.
	 */
	protected IPeerModel doValidateChildPeerNodeForAdd(IPeerModel parent, IPeerModel node) {
		Assert.isNotNull(parent);
		Assert.isNotNull(node);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITracing.ID_TRACE_LOCATOR_MODEL)) {
			CoreBundleActivator.getTraceHandler().trace("LocatorModel.doValidateChildPeerNodeForAdd( " + parent.getPeerId() + ", " + node.getPeerId() + " )", ITracing.ID_TRACE_LOCATOR_MODEL, this); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		}

		// If the child node is already visible as root node, drop the child node
		String id = node.getPeerId();
		if (isRootNode(id)) {
			return null;
		}

		int beginIndex = id.indexOf(':');
		int endIndex = id.lastIndexOf(':');
		String ip = beginIndex != -1 && endIndex != -1 ? id.substring(beginIndex+1, endIndex) : ""; //$NON-NLS-1$

		// Get the loopback address
		String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress();
		// Empty IP address means loopback
		if ("".equals(ip)) ip = loopback; //$NON-NLS-1$

		// If the IP is a localhost IP, try the loopback IP
		if (IPAddressUtil.getInstance().isLocalHost(ip)) {
			// Build up the new id to lookup
			StringBuilder newId = new StringBuilder();
			newId.append(id.substring(0, beginIndex));
			newId.append(':');
			newId.append(loopback);
			newId.append(':');
			newId.append(id.substring(endIndex + 1));

			// Try the lookup again
			if (isRootNode(newId.toString())) {
				return null;
			}
		}

		// Get the peer from the peer node
		IPeer peer = node.getPeer();

		// If the child peer represents the same agent as the parent peer,
		// drop the child peer
		String parentAgentID = parent.getPeer().getAgentID();
		if (parentAgentID != null && parentAgentID.equals(peer.getAgentID())) {
			return null;
		}
		// If the child peer represents the same agent as another child peer,
		// drop the child peer
		String agentID = node.getPeer().getAgentID();
		if (agentID != null) {
			IPeerModel[] matches = getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(parent.getPeerId(), agentID);
			for (IPeerModel match : matches) {
				if (agentID.equals(match.getPeer().getAgentID())) {
					// Try to keep the peer with the real IP, filter the "127.0.0.1" peer
					if ("127.0.0.1".equals(node.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST)) //$NON-NLS-1$
							&& !"127.0.0.1".equals(match.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST))) { //$NON-NLS-1$
						// Keep the other child node
						return null;
					}

					if (!"127.0.0.1".equals(node.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST)) //$NON-NLS-1$
							&& "127.0.0.1".equals(match.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST))) { //$NON-NLS-1$
						// Keep the node
						getService(ILocatorModelUpdateService.class).removeChild(match);
					}

					// If both nodes have a IP different from "127.0.0.1", keep the first node
					if (!"127.0.0.1".equals(node.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST)) //$NON-NLS-1$
							&& !"127.0.0.1".equals(match.getPeer().getAttributes().get(IPeer.ATTR_IP_HOST))) { //$NON-NLS-1$
						// Keep the other child node
						return null;
					}
				}
			}
		}
		// If the child peer's IP address and port are the same as the parent's
		// IP address and port, drop the child node
		Map<String, String> parentPeerAttributes = parent.getPeer().getAttributes();
		if (parentPeerAttributes.get(IPeer.ATTR_IP_HOST) != null && parentPeerAttributes.get(IPeer.ATTR_IP_HOST).equals(peer.getAttributes().get(IPeer.ATTR_IP_HOST))) {
			String parentPort = parentPeerAttributes.get(IPeer.ATTR_IP_PORT);
			if (parentPort == null) parentPort = "1534"; //$NON-NLS-1$
			String port = peer.getAttributes().get(IPeer.ATTR_IP_PORT);
			if (port == null) port = "1534"; //$NON-NLS-1$

			if (parentPort.equals(port)) return null;
		}

		return node;
	}

	/**
	 * Checks if the given peer id belongs to an already known root node
	 * or to one of the discovered nodes.
	 *
	 * @param id The peer id. Must not be <code>null</code>.
	 * @return <code>True</code> if the given id belongs to a root node, <code>false</code> otherwise.
	 */
	private boolean isRootNode(String id) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(id);

		boolean isRoot = false;

		if (getService(ILocatorModelLookupService.class).lkupPeerModelById(id) != null) {
			isRoot = true;
		} else {
			Map<String, IPeer> peers = Protocol.getLocator().getPeers();
			if (peers.containsKey(id)) {
				isRoot = true;
			}
		}

		return isRoot;
	}
}

Back to the top