View Javadoc

1   package cz.cuni.amis.pogamut.ut2004multi.communication.worldview;
2   
3   import java.io.IOException;
4   import java.util.HashMap;
5   import java.util.LinkedList;
6   import java.util.List;
7   import java.util.Map;
8   import java.util.concurrent.CountDownLatch;
9   import java.util.concurrent.TimeUnit;
10  import java.util.logging.ConsoleHandler;
11  import java.util.logging.FileHandler;
12  import java.util.logging.Formatter;
13  import java.util.logging.Level;
14  import java.util.logging.Logger;
15  import java.util.logging.SimpleFormatter;
16  
17  import org.junit.Ignore;
18  import org.junit.Test;
19  
20  import cz.cuni.amis.pogamut.base.agent.IAgentId;
21  import cz.cuni.amis.pogamut.base.communication.mediator.IMediator;
22  import cz.cuni.amis.pogamut.base.communication.worldview.object.WorldObjectId;
23  import cz.cuni.amis.pogamut.base.component.controller.ComponentDependencies;
24  import cz.cuni.amis.pogamut.base.component.controller.ComponentDependencyType;
25  import cz.cuni.amis.pogamut.base.component.lifecyclebus.LifecycleBus;
26  import cz.cuni.amis.pogamut.base.utils.logging.AgentLogger;
27  import cz.cuni.amis.pogamut.base.utils.logging.IAgentLogger;
28  import cz.cuni.amis.pogamut.multi.agent.ITeamedAgentId;
29  import cz.cuni.amis.pogamut.multi.agent.impl.TeamId;
30  import cz.cuni.amis.pogamut.multi.agent.impl.TeamedAgentId;
31  import cz.cuni.amis.pogamut.multi.communication.worldview.ILocalWorldView;
32  import cz.cuni.amis.pogamut.multi.communication.worldview.ISharedWorldView;
33  import cz.cuni.amis.pogamut.multi.communication.worldview.impl.BatchAwareLocalWorldView;
34  import cz.cuni.amis.pogamut.ut2004.communication.messages.gbinfomessages.BeginMessage;
35  import cz.cuni.amis.pogamut.ut2004.communication.messages.gbinfomessages.EndMessage;
36  import cz.cuni.amis.pogamut.ut2004.component.ComponentStub;
37  import cz.cuni.amis.pogamut.ut2004multi.communication.worldview.objects.TestCompositeViewableObject;
38  import cz.cuni.amis.pogamut.ut2004multi.communication.worldview.objects.TestCompositeViewableObjectMessage;
39  import cz.cuni.amis.pogamut.ut2004multi.communication.worldview.stubs.MediatorStub;
40  import cz.cuni.amis.pogamut.ut2004multi.communication.worldview.stubs.UT2004TestLocalWorldView;
41  import cz.cuni.amis.pogamut.ut2004multi.communication.worldview.stubs.UT2004TestSharedWorldView;
42  import cz.cuni.amis.tests.BaseTest;
43  import cz.cuni.amis.utils.StopWatch;
44  
45  
46  @Ignore		
47  public class Test01_UT2004VisionLocalWorldView_simpleTest extends BaseTest {
48  	
49  	private static final long GLOBAL_TIMEOUT_IN_MINUTES = 10;
50  
51  	public static FileHandler fh;
52  	
53  	public static Logger global;
54  	public static List<IAgentLogger> agentLogs;
55  	
56  	
57  	public static ISharedWorldView sharedWV;
58  	
59  	
60  	public static void setLogLevel( Level level)
61  	{
62  		global.setLevel(level);
63  		for ( IAgentLogger log : agentLogs)
64  		{
65  			log.setLevel(level);
66  		}
67  	}
68  	
69  	public static void initSWV()
70  	{
71  		try {
72  			fh = new FileHandler("./log01");
73  		} catch (SecurityException e) {
74  			// TODO Auto-generated catch block
75  			e.printStackTrace();
76  		} catch (IOException e) {
77  			// TODO Auto-generated catch block
78  			e.printStackTrace();
79  		}
80  		Formatter f = new SimpleFormatter();
81  		fh.setFormatter(f);
82  		
83  		agentLogs = new LinkedList<IAgentLogger>();
84  		
85  		global = Logger.getLogger("Global");
86  		global.setLevel(Level.FINER);
87  		ConsoleHandler consoleHandler = new ConsoleHandler();
88  		consoleHandler.setLevel(Level.FINER);
89  		global.addHandler( consoleHandler );
90  		global.addHandler(fh);
91  		sharedWV = new UT2004TestSharedWorldView(global);
92  	}
93  	
94  	public static class Handler
95  	{
96  		Map<IAgentId, Integer> cycles;
97  		
98  		public Handler()
99  		{
100 			cycles = new HashMap<IAgentId, Integer>();
101 		}
102 		
103 		public void addNew( IAgentId id, int cycles)
104 		{
105 			this.cycles.put(id, cycles);
106 		}
107 		
108 		public boolean allFinished()
109 		{
110 			for ( Integer i : cycles.values() )
111 			{
112 				if ( i >= 0)
113 				{
114 					return false;
115 				}
116 			}
117 			return true;
118 		}
119 		
120 		public synchronized void setEnd( IAgentId id)
121 		{
122 			this.cycles.put(id, -1);
123 		}
124 		
125 		public  synchronized void decrease( IAgentId id)
126 		{
127 			int n = cycles.get(id);
128 			--n;
129 			cycles.put(id, n);
130 		}
131 		
132 		public int cyclesToRun( IAgentId id)
133 		{
134 			return ( cycles.get(id ));
135 		}
136 	}
137 	
138 	/**
139 	 * Generates a single batch of events on specified time for specified worldView on run();
140 	 * @author srlok
141 	 *
142 	 */
143 	public static class EventGenerator extends Thread
144 	{
145 		int events;
146 		long time;
147 		ILocalWorldView localWV;
148 		TeamedAgentId agentId;
149 		
150 		public EventGenerator( int events, long time, ILocalWorldView localWV)
151 		{
152 			this.events = events;
153 			this.time = time;
154 			this.localWV = localWV;
155 			agentId = (TeamedAgentId) localWV.getAgentId();
156 		}
157 		
158 		protected void generateEvents()
159 		{
160 			System.out.println(agentId + " : generating Events [Time:" + time + "]" );
161 			localWV.notify( new BeginMessage(this.time));
162 			
163 			for ( int i = 0; i < events; ++i)
164 			{
165 				WorldObjectId id = WorldObjectId.get("TestObject["+i+"]");
166 				TestCompositeViewableObject obj = new TestCompositeViewableObjectMessage(id, this.time, "LS:"+agentId.toString()+"["+i+"]"+"("+time+")",
167 						i+time, "ShS:"+agentId.getTeamId().toString()+"["+i+"]"+"("+time+")",
168 						i+1000+time, "StaticString["+i+"]" , (long)i, true);
169 				localWV.notify(obj.createUpdateEvent(time, agentId.getTeamId()));
170 			}
171 			
172 			localWV.notify( new EndMessage(this.time ) );
173 			System.out.println(agentId + ": generating end");
174 		}
175 	
176 		@Override
177 		public void run()
178 		{
179 			try {
180 				generateEvents();
181 			} catch (Exception e) {
182 				e.printStackTrace();
183 				failure = true;
184 				totalCountDown2();
185 				return;
186 			}
187 			latch2.countDown();
188 		}
189 	}
190 	
191 	public static class LogicRunner extends Thread
192 	{
193 		protected BatchAwareLocalWorldView wv;
194 		protected ITeamedAgentId id;
195 		
196 		int runs;
197 		int objects;
198 		long sleepTime;
199 		Handler handler;
200 		ComponentStub starter;
201 		
202 		public LogicRunner(ITeamedAgentId id, int runs, int objects, long sleepTime, Handler handler)
203 		{
204 			IAgentLogger log = new AgentLogger(id);
205 			agentLogs.add(log);
206 			log.setLevel(Level.ALL);
207 			log.addDefaultConsoleHandler();
208 			log.addDefaultHandler(fh);
209 			LifecycleBus bus = new LifecycleBus(log);
210 			IMediator m = new MediatorStub(log);
211 			starter = new ComponentStub(log,bus );
212 			try
213 			{
214 			wv = new UT2004TestLocalWorldView( new ComponentDependencies(ComponentDependencyType.STARTS_WITH).add(starter),
215 					m, bus, log, sharedWV, id);
216 			}
217 			catch (Exception e)
218 			
219 			{
220 				failure = true;
221 				e.printStackTrace();
222 			}
223 			//wv.setInitialTime(TimeKey.get(0));
224 			
225 			this.id = id;
226 			this.runs = runs;
227 			this.objects = objects;
228 			this.sleepTime = sleepTime;
229 			this.handler = handler;
230 			handler.addNew(id, runs);
231 		}
232 		
233 		public void startWV()
234 		{			
235 			starter.getController().manualStart("Test");
236 		}
237 		
238 		public void setSleepTime( long newSleepTime )
239 		{
240 			this.sleepTime = newSleepTime;
241 		}
242 		
243 		@Override
244 		public void run() 
245 		{
246 			try {
247 				System.out.println( id + " : Logic Runner run()");
248 				for ( int r = 0; r <= runs; ++r)
249 				{
250 					if (failure) throw new RuntimeException("FAILURE DETECTED!");
251 					wv.lock();
252 					System.out.println( id + "Runner run ["+r+"] remaining : time " + wv.getCurrentTimeKey().getTime() + ", remaining runs " + handler.cyclesToRun(id) );
253 					for ( int i = 0; i < objects; ++i)
254 					{
255 						long t = wv.getCurrentTimeKey().getTime();
256 						
257 						TestCompositeViewableObject obj = (TestCompositeViewableObject) wv.get( WorldObjectId.get("TestObject["+i+"]") );
258 						
259 						if ( obj == null )
260 						{
261 							global.severe( id + " : NULL");
262 							throw new RuntimeException("Object is null.");
263 						}
264 						
265 						if ( obj.getLocalLong() != i + t)
266 						{
267 							global.severe(obj.getId() + " : " + obj.getLocalString() );
268 							global.severe("LocalLong fail on  object " + i + " in run " + r + " ; on WV time " + t );
269 							handler.setEnd(id);
270 							throw new RuntimeException("LocalLong fail on  object " + i + " in run " + r + " ; on WV time " + t );
271 						}						
272 						
273 						if ( !obj.getLocalString().equals("LS:"+id.toString()+"["+i+"]"+"("+t+")"))
274 						{
275 							throw new RuntimeException("LocalString fail");
276 						}
277 						
278 						if ( obj.getSharedLong() != i+1000+t )
279 						{	
280 							global.severe( id + " : " + obj.getSharedLong() + " instead of " + (i+1000+t));
281 							throw new RuntimeException("SharedLong fail");
282 						}
283 						if ( !obj.getSharedString().equals("ShS:"+id.getTeamId().toString()+"["+i+"]"+"("+t+")"))
284 						{
285 							throw new RuntimeException("SharedString fail : " + obj.getSharedString());
286 						}
287 						if ( obj.getStaticLong() != i )
288 						{
289 							throw new RuntimeException("StaticLong fail");
290 						}
291 						if ( !obj.getStaticString().equals( "StaticString["+i+"]"))
292 						{
293 							throw new RuntimeException("StaticString fail");
294 						}						
295 					}
296 					this.sleep(sleepTime);
297 					wv.unlock();
298 					handler.decrease(id);
299 				}
300 			} catch (Exception e) {
301 				e.printStackTrace();
302 				failure = true;
303 				totalCountDown();
304 				return;
305 			}
306 			latch.countDown();
307 		}
308 	}
309 	
310 	/**
311 	 * Manages different event generators...
312 	 * this is responsible for increasing timeKey and generating batches of events for all worldViews.
313 	 * @author srlok
314 	 *
315 	 */
316 	public static class EventGeneratorHandler extends Thread
317 	{
318 		Map<TeamedAgentId, ILocalWorldView> localWorldViews;
319 		int eventsPerCycle;
320 		long currentTime;
321 		Handler handler;
322 		long sleepTime;
323 		
324 		public EventGeneratorHandler( int eventsPerCycle, long initTime, long sleepTime, Handler handlerInstance)
325 		{
326 			this.eventsPerCycle = eventsPerCycle;
327 			this.currentTime = initTime;
328 			this.handler = handlerInstance;
329 			this.sleepTime = sleepTime;
330 			localWorldViews = new HashMap<TeamedAgentId,ILocalWorldView>();
331 		}
332 		
333 		public void addWorldView( ILocalWorldView wv)
334 		{
335 			this.localWorldViews.put( (TeamedAgentId)wv.getAgentId() , wv);
336 		}
337 		
338 		@Override
339 		public void run()
340 		{
341 			try {
342 				while ( !handler.allFinished() )
343 				{
344 					if (failure) throw new RuntimeException("FAILURE DETECTED!");
345 					List<Thread> thrds = new LinkedList<Thread>();
346 					for ( TeamedAgentId id : localWorldViews.keySet() )
347 					{
348 						if ( handler.cyclesToRun(id) >= 0)
349 						{
350 							thrds.add( new EventGenerator(eventsPerCycle, currentTime, localWorldViews.get(id)) );
351 						}
352 					}
353 					latch2 = new CountDownLatch(thrds.size());
354 					for (Thread t : thrds)
355 					{
356 						t.start();
357 					}
358 					latch2.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);					
359 					if (latch2.getCount() > 0 || failure) {
360 						throw new RuntimeException("FAILURE DETECTED!");
361 					}
362 					++currentTime;
363 					sleep(sleepTime);					
364 				}
365 			} catch (Exception e) {
366 				e.printStackTrace();
367 				failure = true;
368 				totalCountDown();	
369 				return;
370 			}
371 			latch.countDown();
372 		}		
373 		
374 	}
375 	
376 	static boolean failure = false;
377 	
378 	static CountDownLatch latch;
379 	static CountDownLatch latch2;
380 	
381 	@Test
382 	public void simpleTest()
383 	{
384 		initSWV();
385 		int events = 250; // number of events per batch
386 		int runs = 150;   // number of logic runs
387 		long sleepTime = 40; // sleep time between batches (generated)
388 		long runnerSleepTime = 20; // sleep time inside logic
389 		Handler hndlr = new Handler();
390 		List<Thread> thrds = new LinkedList<Thread>();
391 		int agents = 1;
392 		latch = new CountDownLatch(agents+1);
393 		TeamId tId = new TeamId("RED");
394 		
395 		EventGeneratorHandler eventHandler = new EventGeneratorHandler(events, 0, sleepTime, hndlr);
396 		
397 		StopWatch watch = new StopWatch();
398 		
399 		for ( int i = 0; i < agents; ++i )
400 		{
401 			TeamedAgentId aId = new TeamedAgentId("Agent["+i+"]");
402 			aId.setTeamId(tId);
403 			LogicRunner r = new LogicRunner(aId, runs, events, runnerSleepTime,  hndlr);			
404 			eventHandler.addWorldView(r.wv);
405 			thrds.add(r);
406 			r.startWV();
407 		}
408 		setLogLevel(Level.INFO);
409 		for ( Thread t : thrds)
410 		{
411 			t.start();
412 		}
413 		eventHandler.start();
414 		
415 		try {
416 			
417 			latch.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
418 			if (latch.getCount() > 0 || failure) {
419 				failure = true;
420 				throw new RuntimeException("FAILURE!!!");
421 			}
422 			
423 		} catch (InterruptedException e) {
424 			failure = true;
425 			throw new RuntimeException(e);
426 		}
427 		
428 		System.out.println("Test took: " + watch.stopStr());
429 		
430 		thrds = null;
431 		eventHandler = null;
432 		sharedWV = null;
433 		
434 		try
435 		{
436 			//CheckInstances.waitGCTotal();
437 		}
438 		catch (Exception e )
439 		{
440 			System.out.println("WARNING : ");
441 			//e.printStackTrace();
442 		}
443 		
444 		System.out.println("---/// TEST OK ///---");
445 	}
446 	
447 	@Test
448 	public void multipleAgentsTest()
449 	{
450 		initSWV();
451 		int events = 150; // number of events per batch
452 		int runs = 150;   // number of logic runs
453 		long sleepTime = 40; // sleep time between batches (generated)
454 		long runnerSleepTime = 20; // sleep time inside logic
455 		Handler hndlr = new Handler();
456 		List<Thread> thrds = new LinkedList<Thread>();
457 		int agents = 4;
458 		latch = new CountDownLatch(agents+1);
459 		TeamId tId = new TeamId("RED");
460 		
461 		EventGeneratorHandler eventHandler = new EventGeneratorHandler(events, 0, sleepTime, hndlr);
462 		
463 		StopWatch watch = new StopWatch();
464 		
465 		for ( int i = 0; i < agents; ++i )
466 		{
467 			TeamedAgentId aId = new TeamedAgentId("Agent["+i+"]");
468 			aId.setTeamId(tId);
469 			LogicRunner r = new LogicRunner(aId, runs, events, runnerSleepTime,  hndlr);			
470 			eventHandler.addWorldView(r.wv);
471 			thrds.add(r);
472 			r.startWV();
473 		}
474 		setLogLevel(Level.INFO);
475 		for ( Thread t : thrds)
476 		{
477 			t.start();
478 		}
479 		eventHandler.start();
480 		
481 		try {
482 			
483 			latch.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
484 			if (latch.getCount() > 0 || failure) {
485 				failure = true;
486 				throw new RuntimeException("FAILURE!!!");
487 			}
488 			
489 		} catch (InterruptedException e) {
490 			failure = true;
491 			throw new RuntimeException(e);
492 		}
493 		
494 		System.out.println("Test took: " + watch.stopStr());
495 		
496 		thrds = null;
497 		eventHandler = null;
498 		sharedWV = null;
499 		
500 		try
501 		{
502 			//CheckInstances.waitGCTotal();
503 		}
504 		catch (Exception e )
505 		{
506 			System.out.println("WARNING : ");
507 			//e.printStackTrace();
508 		}
509 		
510 		System.out.println("---/// TEST OK ///---");
511 	}
512 
513 	public static void totalCountDown2() {
514 		while (latch2.getCount() > 0) latch2.countDown();
515 	}
516 
517 	public static void totalCountDown() {
518 		while (latch.getCount() > 0) latch.countDown();
519 	}
520 	
521 	
522 	
523 }