MaxPeerCountChurnGenerator.java 14.2 KB
Newer Older
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
/*
 * Copyright (c) 2005-2010 KOM – Multimedia Communications Lab
 *
 * This file is part of PeerfactSim.KOM.
 * 
 * PeerfactSim.KOM is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * PeerfactSim.KOM is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PeerfactSim.KOM.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tud.kom.p2psim.impl.churn;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
31
import java.util.Random;
32
33
34
35
36
37
38
39
40
41

import de.tud.kom.p2psim.api.common.SimHost;
import de.tud.kom.p2psim.api.network.SimNetworkComponent;
import de.tud.kom.p2psim.impl.scenario.DefaultConfigurator;
import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.util.oracle.GlobalOracle;
import de.tud.kom.p2psim.impl.util.toolkits.CollectionHelpers;
import de.tud.kom.p2psim.impl.util.toolkits.Predicates;
import de.tudarmstadt.maki.simonstrator.api.Event;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
42
import de.tudarmstadt.maki.simonstrator.api.Randoms;
43
import de.tudarmstadt.maki.simonstrator.api.Time;
44
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;
45
import de.tudarmstadt.maki.simonstrator.api.component.GlobalComponent;
46
import de.tudarmstadt.maki.simonstrator.api.component.LifecycleComponent;
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;

/**
 * ChurnModel that follows a defined "trace" in a csv file. The trace must
 * consist of the following parameters per line:
 * 
 * startTime, intervalLength numberOfClients
 * 
 * startTime - the time when the specified number of nodes is to be set.
 * 
 * intervalLength - the time in which the specified number of nodes (startTime)
 * must be achieved by the model. Those two together also form the inter
 * join/leaving rate.
 * 
 * numberOfClients - the number of clients to be achieved.
 * 
63
 * The model checks for a minimum intervalLength of 1 minute.
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 * 
 * 
 * @author Nils Richerzhagen
 * @version 1.0, Nov 24, 2015
 */
public class MaxPeerCountChurnGenerator
		implements EventHandler, GlobalComponent {

	private static final int _PeerCountEvent = 1001;

	private static final int _CHURN_START = 1002;

	private static final int _CHURN_EVENT = 1003;

	private static final int _CHURN_NOCHURN_HOSTS = 1004;

	private final String commentsDelimiter = "#";

	private final String SEP = ",";

84
85
	private final long _minBurstLength = 1 * Time.MINUTE;

86
	private final int maxNumberOfNodes;
87

88
89
90
91
92
	/**
	 * Default behavior: this generator operates on a NetLayer.
	 */
	private Class<? extends LifecycleComponent> targetClass = SimNetworkComponent.class;

93
94
95
96
97
98
99
100
	/**
	 * {@link ChurnInfo} from the csv file.
	 */
	private LinkedList<ChurnInfo> churnInfos = new LinkedList<ChurnInfo>();

	private PriorityQueue<HostSessionInfo> onlineHostsSortedByOnlineTime;

	private PriorityQueue<HostSessionInfo> offlineHostsSortedByOfflineTime;
101
	
102
	private Random rnd = Randoms.getRandom(MaxPeerCountChurnGenerator.class);
103
104
105
106
107
108
109
110
111
112
113

	/**
	 * Comparator used to sort client infos by offline time
	 */
	private static final Comparator<HostSessionInfo> COMP_TIME = new Comparator<MaxPeerCountChurnGenerator.HostSessionInfo>() {
		@Override
		public int compare(HostSessionInfo o1, HostSessionInfo o2) {
			return ((Long) o1.timestamp).compareTo(o2.timestamp);
		}
	};

114
	@XMLConfigurableConstructor({ "file", "maxNumberOfNodes" })
115
116
	public MaxPeerCountChurnGenerator(String file, int maxNumberOfNodes) {
		this.maxNumberOfNodes = maxNumberOfNodes;
Julian Zobel's avatar
Julian Zobel committed
117
		parseTrace(file);		
118
	}
Julian Zobel's avatar
Julian Zobel committed
119
120
121
122
123
124
125
126
127
	
	@XMLConfigurableConstructor({ "churnStart", "maxNumberOfNodes", "burstLength" })
	public MaxPeerCountChurnGenerator(long churnStart, int maxNumberOfNodes, long burstLength) {
		this.maxNumberOfNodes = maxNumberOfNodes;		
		churnInfos.add(new ChurnInfo(churnStart, burstLength, maxNumberOfNodes));
		this.setChurnStart(churnStart);
	}
	
	
128

129
130
131
132
133
134
135
136
137
138
139
	/**
	 * A class that implements the {@link LifecycleComponent}-interface and can
	 * then be controlled by this generator.
	 * 
	 * @param targetClass
	 */
	@SuppressWarnings("unchecked")
	public void setTargetClass(Class<?> targetClass) {
		this.targetClass = (Class<? extends LifecycleComponent>) targetClass;
	}

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
	/**
	 * Called by the configurator.
	 * 
	 * @param churnStart
	 */
	public void setChurnStart(long churnStart) {
		// Event.scheduleWithDelay(churnStart, this, null, _CHURN_START);
		Event.scheduleImmediately(this, null, _CHURN_START);
	}

	public void initialize() {
		for (ChurnInfo churnInfo : churnInfos) {
			Event.scheduleWithDelay(churnInfo.getStartTime(), this, churnInfo,
					_PeerCountEvent);
		}
	}

	/**
	 * Start adapting on new churn rate, when next churnInfo is valid.
	 */
	private void configureMaxPeerCount(ChurnInfo currentChurnInfo) {
		long currentTime = Simulator.getCurrentTime();

		assert currentChurnInfo
				.getStartTime() == currentTime : "The ChurnInfo to use is scheduled for the exact time, thus it should be the same.";

		/*
		 * Wanted number > current number. --> need nodes = go online
		 */
		if (currentChurnInfo
				.getNumberOfClients() >= onlineHostsSortedByOnlineTime.size()) {
			int count = currentChurnInfo.getNumberOfClients()
					- onlineHostsSortedByOnlineTime.size();

			for (int i = 0; i < count; i++) {
				/*
				 * Schedule the required number of hosts for going online
				 * churnEvent. Get oldest entry in sortedOffline list and put
				 * online.
				 */
				HostSessionInfo hostSessionInfo = offlineHostsSortedByOfflineTime
						.poll();
				assert hostSessionInfo != null : "HostSessionInfo shouldn't be null - means to few hosts were configured.";

184
				ChurnEvent churnEvent = new ChurnEvent(hostSessionInfo.component, true);
185
186
				long currentJoin = i
						* (currentChurnInfo.getBurstLength() / count);
187
188
				// Add rnd-offset
				currentJoin += (long) (rnd.nextDouble() * (currentChurnInfo.getBurstLength() / count));
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
				Event.scheduleWithDelay(currentJoin, this, churnEvent,
						_CHURN_EVENT);
			}
		}
		/*
		 * Wanted number < currentNumber --> remove nodes = goOffline
		 */
		else if (currentChurnInfo
				.getNumberOfClients() < onlineHostsSortedByOnlineTime.size()) {
			int count = onlineHostsSortedByOnlineTime.size()
					- currentChurnInfo.getNumberOfClients();

			for (int i = 0; i < count; i++) {
				/*
				 * Schedule the required number of hosts for going offline
				 * churnEvent. Get oldest entry in sortedOnline list and put
				 * offline.
				 */
				HostSessionInfo hostSessionInfo = onlineHostsSortedByOnlineTime
						.poll();
				assert hostSessionInfo != null : "HostSessionInfo shouldn't be null - means no hosts were online.";

211
				ChurnEvent churnEvent = new ChurnEvent(hostSessionInfo.component,
212
213
214
						false);
				long currentLeave = i
						* (currentChurnInfo.getBurstLength() / count);
215
216
				// Add rnd-offset
				currentLeave += (long) (rnd.nextDouble() * (currentChurnInfo.getBurstLength() / count));
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
				Event.scheduleWithDelay(currentLeave, this, churnEvent,
						_CHURN_EVENT);
			}
		} else {
			throw new AssertionError();
		}
	}

	@Override
	public void eventOccurred(Object content, int type) {
		if (type == _PeerCountEvent) {
			ChurnInfo churnInfo = (ChurnInfo) content;
			configureMaxPeerCount(churnInfo);
		} else if (type == _CHURN_EVENT) {
			long currentTime = Simulator.getCurrentTime();
			ChurnEvent churnEvent = (ChurnEvent) content;
233
234
			if (churnEvent.start) {
				churnEvent.component.startComponent();
235
				onlineHostsSortedByOnlineTime
236
						.add(new HostSessionInfo(churnEvent.component, currentTime));
237
			} else {
238
				churnEvent.component.stopComponent();
239
				offlineHostsSortedByOfflineTime
240
						.add(new HostSessionInfo(churnEvent.component, currentTime));
241
242
243
244
			}
		} else if (type == _CHURN_START) {
			initialize();

245
246
247
			/*
			 * FIXME we might want to add means to filter not only based on the host property?
			 */
248
249
250
251
252
253
254
255
256
			List<SimHost> hosts = new ArrayList<SimHost>(this.filterHosts());
			this.prepare(hosts);

			offlineHostsSortedByOfflineTime = new PriorityQueue<HostSessionInfo>(
					(int) Math.ceil(hosts.size() / 10.0), COMP_TIME);
			onlineHostsSortedByOnlineTime = new PriorityQueue<HostSessionInfo>(
					(int) Math.ceil(hosts.size() / 10.0), COMP_TIME);

			long currentTime = Simulator.getCurrentTime();
257
258
259
260
261
262
263
264
265
266
			/*
			 * Find class (LifecycleComponent) implementation per host
			 */
			for (SimHost simHost : hosts) {
				try {
					LifecycleComponent comp = simHost.getComponent(targetClass);
					offlineHostsSortedByOfflineTime.add(new HostSessionInfo(comp, currentTime));
				} catch (ComponentNotAvailableException e) {
					throw new AssertionError("No implementation of "+targetClass+" found on host "+simHost);
				}
267
268
			}
		} else if (type == _CHURN_NOCHURN_HOSTS) {
269
			// Start on all no-churn hosts (e.g., they will be active right from the beginning)
270
			List<SimHost> nochurnhosts = (List<SimHost>) content;
271
			
272
			for (SimHost host : nochurnhosts) {
273
274
275
276
				try {
					LifecycleComponent comp = host.getComponent(targetClass);
					if (!comp.isActive()) {
						comp.startComponent();
277
					}
278
279
				} catch (ComponentNotAvailableException e) {
					// Filtered hosts might not even have the component
280
281
282
283
284
285
286
287
288
289
				}
			}
		}
	}

	/**
	 * Send hosts offline! Should be used to start with churnHosts in offline
	 * state.
	 * 
	 * @param hosts
290
	 * @deprecated use startOffline-flag in the netlayer-config instead!
291
	 */
292
	@Deprecated
293
294
	private void prepare(List<SimHost> hosts) {
		for (SimHost host : hosts) {
295
296
297
298
			try {
				LifecycleComponent comp = host.getComponent(targetClass);
				if (comp.isActive()) {
					comp.stopComponent();
299
				}
300
301
			} catch (ComponentNotAvailableException e) {
				// Filtered hosts might not even have the component
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
			}
		}
	}

	/**
	 * Gets all hosts and takes all churn affected hosts. Schedules the non
	 * affected host to go online immediately.
	 * 
	 * @return
	 */
	private List<SimHost> filterHosts() {
		List<SimHost> tmp = GlobalOracle.getHosts();
		List<SimHost> filteredHosts = new LinkedList<SimHost>();

		CollectionHelpers.filter(tmp, filteredHosts,
				Predicates.IS_CHURN_AFFECTED);
		List<SimHost> noChurn = new LinkedList<SimHost>();
		noChurn.addAll(tmp);
		noChurn.removeAll(filteredHosts);
		Event.scheduleImmediately(this, noChurn, _CHURN_NOCHURN_HOSTS);
		return filteredHosts;
	}

	/**
	 * Reads the file given by the configuration and parses the churn events.
	 * 
	 * @param filename
	 */
	private void parseTrace(String filename) {
		System.out.println("==============================");
		System.out.println("Reading trace from " + filename);

		/*
		 * This parser works for the following csv file structure.
		 * 
		 * startTime, intervalLength numberOfClients
		 * 
		 */
		BufferedReader csv = null;
		boolean entrySuccessfullyRead = false;

		try {
			csv = new BufferedReader(new FileReader(filename));

			long previousEndTime = 0;

			while (csv.ready()) {
				String line = csv.readLine();
				if (line.length() == 0 || line.startsWith(commentsDelimiter))
					continue;

				if (line.indexOf(SEP) > -1) {
					String[] parts = line.split(SEP);

					if (parts.length == 3) {
						try {

							long startTime = DefaultConfigurator.parseNumber(
									parts[0].replaceAll("\\s+", ""),
									Long.class);
							long burstLength = DefaultConfigurator.parseNumber(
									parts[1].replaceAll("\\s+", ""),
									Long.class);
							int numberOfClients = DefaultConfigurator
									.parseNumber(
											parts[2].replaceAll("\\s+", ""),
											Integer.class);

							// Insanity Checks
							assert startTime >= previousEndTime : "Start time for next fluctuation must be greater than previous end time.";

373
374
375
							assert burstLength >= _minBurstLength : "The minimal length of the burst must be at least 1m.";

							assert numberOfClients > 0 : "Number of nodes must be positive.";
376

377
							assert numberOfClients <= maxNumberOfNodes : "Cannot configure more nodes than configured in configuration.";
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
							previousEndTime = startTime + burstLength;

							churnInfos.add(new ChurnInfo(startTime, burstLength,
									numberOfClients));

							entrySuccessfullyRead = true;

						} catch (NumberFormatException e) {
							// Ignore leading comments
							if (entrySuccessfullyRead) {
								// System.err.println("CSV ParseError " +
								// line);
							}
						}
					} else {
						throw new AssertionError("To many/few columns in CSV.");
					}
				}
			}
		} catch (Exception e) {
			System.err.println("Could not open " + filename);
			throw new RuntimeException("Could not open " + filename);
		} finally {
			if (csv != null) {
				try {
					csv.close();
				} catch (IOException e) {
					//
				}
			}
		}
	}

	/**
	 * 
	 * @author Nils Richerzhagen
	 * @version 1.0, Nov 25, 2015
	 */
	private class HostSessionInfo {

419
		public final LifecycleComponent component;
420
421
422

		public final long timestamp;

423
424
		public HostSessionInfo(LifecycleComponent component, long timestamp) {
			this.component = component;
425
426
427
428
429
430
			this.timestamp = timestamp;
		}
	}

	private class ChurnEvent {

431
		public final LifecycleComponent component;
432

433
		public final boolean start;
434

435
436
437
		ChurnEvent(LifecycleComponent component, boolean start) {
			this.component = component;
			this.start = start;
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
		}
	}

	/**
	 * Churn Info for the fluctuation intervals.
	 * 
	 * @author Nils Richerzhagen
	 */
	private class ChurnInfo {

		/**
		 * The time the burst starts.
		 */
		private long startTime;

		/**
		 * The time the burst takes.
		 */
		private long burstLength;

		/**
		 * The max number of nodes that join during that burst.
		 */
		private int numberOfClients;

		public ChurnInfo(long startTime, long burstLength,
				int numberOfClients) {
			this.startTime = startTime;
			this.burstLength = burstLength;
			this.numberOfClients = numberOfClients;
		}

		public long getStartTime() {
			return startTime;
		}

		public int getNumberOfClients() {
			return numberOfClients;
		}

		public long getBurstLength() {
			return burstLength;
		}
	}
}