summaryrefslogtreecommitdiff
path: root/CSharp/Ivy/IvyPPC/Ivy.cs
blob: 60c3ff422bd20f29cfd0378140fa516ed0124b6e (plain)
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
/// François-Régis Colin
/// http://www.tls.cena.fr/products/ivy/
/// *
/// (C) CENA
/// *
namespace IvyBus
{
	using System;
	using System.IO;
	using System.Collections;
	using System.Net;
	using System.Net.Sockets;
	using System.Threading;
	using System.Configuration;
	using System.Windows.Forms;
	
	/// <summary> The Main bus Class
	/// </summary>
	public class Ivy 
	{
		/* Event handler */
		public delegate void DirectMessageHandler (IvyClient app, int id, string arg );
		public delegate void ClientConnectedHandler (IvyClient app);
		public delegate void ClientDisconnectedHandler (IvyClient app);
		public delegate bool DieHandler (IvyClient app, int id );

		public delegate void MessageHandler (IvyClient app, string[] args );
		

		/* Event */
		/// <summary>fires when a new client connect to the bus</summary>
		/// <param name='appcb'>A callback handling the notification of connexions and
		/// disconnections, may be null
		/// 
		/// </param>
		public event ClientConnectedHandler clientConnected;
		/// <summary>fires when a client discconnect from the bus</summary>
		public event ClientDisconnectedHandler clientDisconnected;
		/// <summary>fires when a client receive a direct message from another client</summary>
		public event DirectMessageHandler directMessageReceived;
		/// <summary>fires when somebody ask for killing every client on the bus</summary>
		public event DieHandler dieReceived;

		/// <summary>IvyClients accesses the list of the connected clients</summary>
		public Hashtable IvyClients
		{
			get
			{
				return clients;
			}
			
		}
		public bool Debug
		{
			get
			{
				return debug;
			}
			
		}
		/// <summary>ClientNames accesses the name list of the connected clients</summary>
		private String ClientNames
		{
			get
			{
				String s = appName + " clients are: ";
				lock( clients.SyncRoot )
				{
					foreach (IvyClient client in  clients.Values )
					{
						s += client.ApplicationName + " ";
					}
				}
				return s;
			}
			
		}
		/// <summary>AppName the application name</summary>
		
		public String AppName
		{
			get
			{
				return appName;
			}
			
		}
		
		///  the name of the application on the bus
		internal String appName;
		/// the protocol version number
		internal const int PROCOCOLVERSION = 3;
		/// the port for the UDP rendez vous, if none is supplied
		internal const int DEFAULT_PORT = 2010;
		/// the domain for the UDP rendez vous
		internal static readonly String DEFAULT_DOMAIN = "127.255.255.255:" + DEFAULT_PORT;
		internal const String libVersion = "1.0.0";
		
		private bool debug;
		private static int serial = 0; /* an unique ID for each regexp */
		private TcpListener app;
		private ArrayList watchers;
		private volatile Thread serverThread; // to ensure quick communication of the end
		private Hashtable callbacks;
		private Hashtable clients;
		private String[] messages_classes = null;
		private bool stopped = false;
		internal int applicationPort; /* Application port number */
		internal Hashtable regexp_out;
		internal String ready_message = null;
		
		// for synchronous event 
		private Control syncControl = null;
		/// <summary> Readies the structures for the software bus connexion.
		/// </summary>
		/// <example> This sample shows how to start working with Ivy.
		/// <code>
		/// Ivy bus = new Ivy("Dummy agent","ready");
		/// bus.bindMsg("(.*)",new Ivy.MessageHandler(myMessageListener));
		/// bus.start(null);
		/// </code>
		/// How to send & receive:
		/// the Ivy agent A performs <c>b.bindMsg("^Hello (*)",cb);</c>
		/// the Ivy agent B performs <c>b2.sendMsg("Hello world");</c>
		/// a thread in A will run the callback cb with its second argument set
		/// to a array of String, with one single element, "world"
		/// </example>
		/// <remarks>
		/// the real work begin in the start() method
		/// </remarks>
		/// <seealso cref=" Ivy.start"/>
		/// <param name='name'>The name of your Ivy agent on the software bus
		/// </param>
		/// <param name='message'>The hellow message you will send once ready
		/// </param>
		public Ivy(String name, String message)
		{
			callbacks = new Hashtable();
			clients = Hashtable.Synchronized( new Hashtable() );
			regexp_out = new Hashtable();
			appName = name;
			ready_message = message;
			String debug_str = ConfigurationSettings.AppSettings["IVY_DEBUG"];
			if ( debug_str != null ) 
				debug = bool.Parse(debug_str);	
		}
		public Ivy(String name, String message, Control sync) :this( name, message ) 
		{
			syncControl = sync;	
		}
		
		/// <summary> connects the Ivy bus to a domain or list of domains.
		/// </summary>
		/// <remarks>
		/// One thread (IvyWatcher) for each traffic rendezvous (either UDP broadcast or TCP Multicast).
		/// One thread (serverThread/Ivy) to accept incoming connexions on server socket.
		/// a thread for each IvyClient when the connexion has been done.
		/// </remarks>
		/// <param name='domainbus'>a domain of the form 10.0.0:1234, it is similar to the
		/// netmask without the trailing .255. This will determine the meeting point
		/// of the different applications. Right now, this is done with an UDP
		/// broadcast. Beware of routing problems ! You can also use a comma
		/// separated list of domains.
		/// *
		/// 
		/// </param>
		public void  start(String domainbus)
		{
			if (domainbus == null)
				domainbus = Environment.GetEnvironmentVariable("IVYBUS");
			if (domainbus == null)
				domainbus = DEFAULT_DOMAIN;
			try
			{
				app = new TcpListener(0);
				app.Start();
				applicationPort =  ((IPEndPoint) app.LocalEndpoint).Port;
			}
			catch (IOException e)
			{
				throw new IvyException("can't open TCP service socket " + e);
			}
			traceDebug("lib: " + libVersion + " protocol: " + PROCOCOLVERSION + " TCP service open on port " + applicationPort);
			watchers = new ArrayList();
			
			Domain[] d = parseDomains(domainbus);
			// readies the rendezvous : an IvyWatcher (thread) per domain bus
			 for (int index = 0; index < d.Length; index++)
			{
				IvyWatcher watcher = new IvyWatcher(this, d[index].Domainaddr, d[index].Port);
				watchers.Add(watcher);
			}
			serverThread = new Thread(new ThreadStart(this.Run));
			serverThread.Start();
			// sends the broadcasts and listen to incoming connexions
			 for (int i = 0; i < watchers.Count; i++)
			{
				((IvyWatcher) watchers[i]).start();
			}
		}
		/* a small private method for debbugging purposes */
		
		public String domains(String toparse)
		{
			String s = "broadcasting on ";
			Ivy.Domain[] d = parseDomains(toparse);
			for (int index = 0; index < d.Length; index++)
			{
				s += d[index].Domainaddr + ":" + d[index].Port + " ";
			}
			return s;
		}
		
		internal Domain[] parseDomains(String domainbus)
		{
			String[] st = domainbus.Split(',');
			Domain[] d = new Domain[st.Length];
			for (int i = 0; i < st.Length; i++)
			{
				d[i] = new Domain(IvyWatcher.getDomain(st[i]), IvyWatcher.getPort(st[i]));
			}
			return d;
		}
		
		/// <summary> disconnects from the Ivy bus
		/// </summary>
		public void  stop()
		{
			lock(this)
			{
				if (stopped)
					return ;
				stopped = true;
				traceDebug("beginning stopping the bus");
				try
				{
					// stopping the serverThread
					Thread t = serverThread;
					serverThread = null;
					if (t != null)
						t.Interrupt();
					// The serverThread might be stopped even before having been created
					if (app != null)
						app.Stop();
					// stopping the IvyWatchers
					if ( watchers != null )
						for (int i = 0; i < watchers.Count; i++)
						{
							((IvyWatcher) watchers[i]).stop();
						}
					// stopping the remaining IvyClients
					lock( clients.SyncRoot )
					{
						foreach (IvyClient c in clients.Values )
						{
							c.close(true); // will notify the reading thread
							//removeClient(c); already donne in the thread
						}
					}
				}
				catch (IOException e)
				{
					traceDebug("IOexception Stop ");
				}
				traceDebug("the bus should have stopped so far");
			}
		}
		
		
		/// <summary> Send a message to someone on the bus
		/// </summary>
		/// <remarks>
		/// Performs a pattern matching according to everyone's regexps, and sends
		/// the results to the relevant ivy agents.
		/// There is one thread for each client connected, we could also
		/// create another thread each time we send a message.
		/// </remarks>
		/// <param name='message'>A message which will be compared to the regular
		/// expressions of the different clients
		/// </param>
		/// <returns>the number of messages actually sent
		/// 
		/// </returns>
		public int sendMsg(String message)
		{
			int count = 0;
			// an alternate implementation would one sender thread per client
			// instead of one for all the clients. It might be a performance issue
			lock ( clients.SyncRoot )
			{
				foreach (IvyClient client in clients.Values )
				{
					count += client.sendMsg(message);
				}
			}
			return count;
		}
		/// <summary> Send a formated message to someone on the bus
		/// </summary>
		/// <remarks>
		/// Performs a pattern matching according to everyone's regexps, and sends
		/// the results to the relevant ivy agents.
		/// There is one thread for each client connected, we could also
		/// create another thread each time we send a message.
		/// </remarks>
		/// <param name='format'>A string message format to build  the message
		/// <param name='args'>args used in message format
		/// </param>
		/// <returns>the number of messages actually sent
		/// 
		/// </returns>
		public int sendMsg(string format, params object[] args )
		{
			return sendMsg( string.Format( format, args ) );
		}
		
		/// <summary> Subscribes to a regular expression.
		/// </summary>
		/// <remarks>
		/// The callback will be executed with
		/// the saved parameters of the regexp as arguments when a message will sent
		/// by another agent. A program doesn't receive its own messages.
		/// </remarks>
		/// 
		/// <param name='regexp'>a regular expression, groups are done with parenthesis
		/// </param>
		/// <param name='callback'>any objects implementing the Ivy.MessageListener
		/// </param>
		/// <returns>the id of the regular expression
		/// 
		/// </returns>
		public int bindMsg(String regexp, MessageHandler callback)
		{
			// creates a new binding (regexp,callback)
			Int32 key = serial++;
			lock (regexp_out.SyncRoot) regexp_out.Add( key, regexp);
			lock (callback) callbacks.Add( key, callback);
			// notifies the other clients this new regexp
			lock ( clients.SyncRoot )
			{
				foreach (IvyClient c in clients.Values )
				{
					c.sendRegexp(key, regexp);
				}
			}
			return key;
		}
		
		/// <summary> unsubscribes a regular expression
		/// </summary>
		/// <param name='id'>the id of the regular expression, returned when it was bound
		/// 
		/// </param>
		public void  unBindMsg(int id)
		{
			if ((regexp_out[id] == null) || (callbacks[id] == null))
			{
				throw new IvyException("client wants to remove an unexistant regexp " + id);
			}
			lock( clients.SyncRoot )
			{
				foreach (IvyClient c in clients.Values )
				{
					c.delRegexp(id);
				}
			}
		}
		
		/// <summary> unsubscribes a regular expression
		/// </summary>
		/// <returns>a boolean, true if the regexp existed, false otherwise or
		/// whenever an exception occured during unbinding
		/// </returns>
		/// <param name='re'>the string for the regular expression
		/// 
		/// </param>
		public bool unBindMsg(String re)
		{
			foreach (Int32 k in regexp_out.Keys )
			{
				if (((String) regexp_out[k]).CompareTo(re) == 0)
				{
					try
					{
						unBindMsg(k);
					}
					catch (IvyException ie)
					{
						return false;
					}
					return true;
				}
			}
			return false;
		}
		internal void FireDirectMessage (IvyClient app, int id, string arg )
		{
			if ( directMessageReceived != null )
			{
				if ( syncControl != null )
					syncControl.Invoke( directMessageReceived, new object[]{app,id,arg});
				else directMessageReceived( app, id, arg);
			}
		}
		internal void FireClientConnected (IvyClient app)
		{
			if ( clientConnected != null )
			{
				if ( syncControl != null )
					syncControl.Invoke( clientConnected, new object[]{app});
				else clientConnected( app);
			}
		}
		internal void FireClientDisconnected (IvyClient app)
		{
			if ( clientDisconnected != null )
			{
				if ( syncControl != null )
					syncControl.Invoke( clientDisconnected, new object[]{app});
				else clientDisconnected( app);
			}
		}
		internal bool FireDie (IvyClient app, int id )
		{
			if ( dieReceived != null )
			{
				if ( syncControl != null )
				 syncControl.Invoke( dieReceived, new object[]{app,id});
			 else return dieReceived( app, id);
			}
			return false;
		}

	
		/*
		* removes a client from the list
		*/
		internal void  removeClient(IvyClient c)
		{
			lock( clients.SyncRoot )
			{
				clients.Remove(c.ClientKey);
			}
		}
		
		
		/// <summary> gives a list of IvyClient(s) with the name given in parameter
		/// </summary>
		/// <param name='name'>The name of the Ivy agent you're looking for
		/// </param>
		public ArrayList getIvyClientsByName(String name)
		{
			ArrayList v = new ArrayList();
			foreach (IvyClient ic in  clients.Values )
			{
				if (((ic.ApplicationName).CompareTo(name)) == 0)
					v.Add(ic);
			}
			return v;
		}
		
		/////////////////////////////////////////////////////////////////:
		//
		// Protected methods
		//
		/////////////////////////////////////////////////////////////////:
		
		internal void  addClient(MyTcpClient socket)
		{
			if (stopped)
					return ;
			IvyClient client = new IvyClient(this,socket);
			lock ( clients.SyncRoot )
			{
				clients.Add( client.ClientKey, client);
			}
			traceDebug(ClientNames);
		}
		
		internal void  callCallback(IvyClient client, Int32 key, String[] tab)
		{
			MessageHandler callback = (MessageHandler) callbacks[key];
			if (callback == null)
			{
				throw new IvyException("(callCallback) Not regexp matching id " + key);
			}
			if ( syncControl != null )
				syncControl.Invoke( callback, new object[]{client,tab});
			else callback(client, tab);
		}
		
		private static String[] myTokenize(String s, String separator)
		{
			int index = 0, last = 0, length = s.Length;
			ArrayList v = new ArrayList();
			if (length != 0)
				while (true)
				{
					index = s.IndexOf(separator, last);
					if (index == - 1)
					{
						v.Add(s.Substring(last, (length) - (last)));
						break;
					}
					else if (index < s.Length)
					{
						v.Add(s.Substring(last, (index) - (last)));
						last = index + 1;
					}
					else
					{
						break;
					}
				}
			String[] tab = new String[v.Count];
			v.CopyTo(tab);
			return tab;
		}
		
		public static String getDomain(String domainbus)
		{
			if (domainbus == null)
			{
				domainbus = ConfigurationSettings.AppSettings["IVYBUS"];
			}
			if (domainbus == null)
			{
				domainbus = Environment.GetEnvironmentVariable("IVYBUS");
			}
			if (domainbus == null)
				domainbus = DEFAULT_DOMAIN;
			return domainbus;
		}
		
		
		/// checks the "validity" of a regular expression.
		internal bool CheckRegexp(String exp)
		{
			bool regexp_ok = true;
			if (exp.StartsWith("^") && messages_classes != null)
			{
				regexp_ok = false;
				 for (int i = 0; i < messages_classes.Length; i++)
				{
					if (messages_classes[i].Equals(exp.Substring(1)))
						return true;
				}
			}
			return regexp_ok;
		}
		
		/*
		* prevents two clients from connecting to each other at the same time
		* there might still be a lingering bug here, that we could avoid with the
		* SchizoToken.
		*/
		internal bool checkConnected(IvyClient clnt)
		{
			if (clnt.AppPort == 0)
				return false;
			lock( clients.SyncRoot )
			{
				foreach (IvyClient client in clients.Values )
				{
					if (clnt != client && client.sameClient(clnt))
						return true;
				}
			}
			return false;
		}
		
		/*
		* the service socket thread reader main loop
		*/
		private void  Run()
		{
			traceDebug("Ivy service Thread started"); 
			bool running = true;
			while (running)
			{
				try
				{
					Socket sock = app.AcceptSocket();
					MyTcpClient socket = new MyTcpClient(sock);
					if (stopped)
						break;
					// early disconnexion
					addClient(socket); // the peer called me
				}
				catch (IOException e)
				{
				
					traceDebug("Error IvyServer exception:  " + e.Message);
					Console.Out.WriteLine("Ivy server socket reader caught an exception " + e.Message);
					// e.printStackTrace();
				}
				catch (SocketException e)
				{
					traceDebug("my server socket has been closed");
					running = false;
				}
			}
			traceDebug("Ivy service Thread stopped");
		}
		
		
		private void  traceDebug(String s)
		{
			if (debug)
				Console.Out.WriteLine("-->ivy<-- " + s);
		}
		
		internal class Domain
		{
			public virtual String Domainaddr
			{
				get
				{
					return domainaddr;
				}
				
			}
			public virtual int Port
			{
				get
				{
					return port;
				}
				
			}
			private String domainaddr;
			private int port;
			public Domain( String domainaddr, int port)
			{
				this.domainaddr = domainaddr; this.port = port;
			}
			public override String ToString()
			{
				return domainaddr + ":" + port;
			}
		}
		
		
		/*
		* unitary test. Normally, running Ivy.Ivy should stop in 2.3 seconds :)
		*/
		[STAThread]
		public static void  Main(String[] args)
		{
			Ivy bus = new Ivy("Test Unitaire", "TU ready");
			try
			{
				bus.start(null);
				try
				{
					Thread.Sleep(new TimeSpan(10000 * 2000));
				}
				catch (ThreadInterruptedException ie)
				{
				}
				bus.stop();
			}
			catch (IvyException ie)
			{
				Console.Error.WriteLine( ie.Message );
				Console.Error.WriteLine( ie.StackTrace );
			}
		}
	}
}