4 // Copyright (C) 2005 Novell, Inc.
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 // DEALINGS IN THE SOFTWARE.
28 using System
.Collections
;
30 using System
.Net
.Sockets
;
31 using System
.Reflection
;
32 using System
.Threading
;
33 using System
.Xml
.Serialization
;
38 namespace Beagle
.Daemon
{
40 class ConnectionHandler
{
42 private static int connection_count
= 0;
43 private static XmlSerializer resp_serializer
= null;
44 private static XmlSerializer req_serializer
= null;
46 private object client_lock
= new object ();
47 private object blocking_read_lock
= new object ();
49 private UnixClient client
;
50 private RequestMessageExecutor executor
= null; // Only set in the keepalive case
51 private Thread thread
;
52 private bool in_blocking_read
;
54 public ConnectionHandler (UnixClient client
)
59 // Perform expensive serialization all at once. Do this before signal handler is setup.
60 public static void Init ()
62 resp_serializer
= new XmlSerializer (typeof (ResponseWrapper
), ResponseMessage
.Types
);
63 req_serializer
= new XmlSerializer (typeof (RequestWrapper
), RequestMessage
.Types
);
66 public bool SendResponse (ResponseMessage response
)
68 lock (this.client_lock
) {
69 if (this.client
== null)
74 MemoryStream mem_stream
= new MemoryStream ();
75 XmlFu
.SerializeUtf8 (resp_serializer
, mem_stream
, new ResponseWrapper (response
));
76 mem_stream
.Seek (0, SeekOrigin
.Begin
);
77 StreamReader r
= new StreamReader (mem_stream
);
78 Logger
.Log
.Debug ("Sending response:\n{0}\n", r
.ReadToEnd ());
79 mem_stream
.Seek (0, SeekOrigin
.Begin
);
80 mem_stream
.WriteTo (this.client
.GetStream ());
83 XmlFu
.SerializeUtf8 (resp_serializer
, this.client
.GetStream (), new ResponseWrapper (response
));
85 // Send an end of message marker
86 this.client
.GetStream ().WriteByte (0xff);
87 this.client
.GetStream ().Flush ();
88 } catch (Exception e
) {
89 Logger
.Log
.Debug ("Caught an exception sending response. Shutting down socket.");
98 public void CancelIfBlocking ()
100 // Work around some crappy .net behavior. We can't
101 // close a socket and have it exit out of a blocking
102 // read, so we have to abort the thread it's blocking
104 lock (this.blocking_read_lock
) {
105 if (this.in_blocking_read
) {
106 this.thread
.Abort ();
115 // It's important that we abort the thread before we
116 // grab the lock here and close the underlying
117 // UnixClient, or else we'd deadlock between here and
118 // the Read() in HandleConnection()
119 lock (this.client_lock
) {
120 if (this.client
!= null) {
121 this.client
.Close ();
126 if (this.executor
!= null) {
127 this.executor
.Cleanup ();
128 this.executor
.AsyncResponseEvent
-= OnAsyncResponse
;
132 public void WatchCallback (IAsyncResult ar
)
137 bytes_read
= this.client
.GetStream ().EndRead (ar
);
138 } catch (SocketException
) {
139 } catch (IOException
) { }
147 private void SetupWatch ()
149 if (this.client
== null) {
154 this.client
.GetStream ().BeginRead (new byte[1024], 0, 1024,
155 new AsyncCallback (WatchCallback
), null);
158 private void OnAsyncResponse (ResponseMessage response
)
160 if (!SendResponse (response
))
164 public void HandleConnection ()
166 this.thread
= Thread
.CurrentThread
;
168 RequestMessage req
= null;
169 ResponseMessage resp
= null;
171 bool force_close_connection
= false;
173 // Read the data off the socket and store it in a
174 // temporary memory buffer. Once the end-of-message
175 // character has been read, discard remaining data
176 // and deserialize the request.
177 byte[] network_data
= new byte [4096];
178 MemoryStream buffer_stream
= new MemoryStream ();
179 int bytes_read
, total_bytes
= 0, end_index
= -1;
181 // We use the network_data array as an object to represent this worker.
182 Shutdown
.WorkerStart (network_data
, String
.Format ("HandleConnection ({0})", ++connection_count
));
188 lock (this.blocking_read_lock
)
189 this.in_blocking_read
= true;
191 lock (this.client_lock
) {
192 // The connection may have been closed within this loop.
193 if (this.client
!= null)
194 bytes_read
= this.client
.GetStream ().Read (network_data
, 0, 4096);
197 lock (this.blocking_read_lock
)
198 this.in_blocking_read
= false;
199 } catch (Exception e
) {
200 // Aborting the thread mid-read will
201 // cause an IOException to be thorwn,
202 // which sets the ThreadAbortException
203 // as its InnerException.
204 if (!(e
is IOException
|| e
is ThreadAbortException
))
207 Logger
.Log
.Debug ("Bailing out of HandleConnection -- shutdown requested");
208 Server
.MarkHandlerAsKilled (this);
209 Shutdown
.WorkerFinished (network_data
);
213 total_bytes
+= bytes_read
;
215 if (bytes_read
> 0) {
216 // 0xff signifies end of message
217 end_index
= ArrayFu
.IndexOfByte (network_data
, (byte) 0xff);
219 buffer_stream
.Write (network_data
, 0,
220 end_index
== -1 ? bytes_read
: end_index
);
222 } while (bytes_read
> 0 && end_index
== -1);
224 // Something just connected to our socket and then
225 // hung up. The IndexHelper (among other things) does
226 // this to check that a server is still running. It's
227 // no big deal, so just clean up and close without
228 // running any handlers.
229 if (total_bytes
== 0) {
230 force_close_connection
= true;
234 buffer_stream
.Seek (0, SeekOrigin
.Begin
);
237 StreamReader r
= new StreamReader (buffer_stream
);
238 Logger
.Log
.Debug ("Received request:\n{0}\n", r
.ReadToEnd ());
239 buffer_stream
.Seek (0, SeekOrigin
.Begin
);
243 RequestWrapper wrapper
= (RequestWrapper
) req_serializer
.Deserialize (buffer_stream
);
245 req
= wrapper
.Message
;
246 } catch (Exception e
) {
247 resp
= new ErrorResponse (e
);
248 force_close_connection
= true;
251 // If XmlSerializer can't deserialize the payload, we
252 // may get a null payload and not an exception. Or
253 // maybe the client just didn't send one.
254 if (req
== null && resp
== null) {
255 resp
= new ErrorResponse ("Missing payload");
256 force_close_connection
= true;
259 // And if there are no errors, execute the command
262 RequestMessageExecutor exec
;
263 exec
= Server
.GetExecutor (req
);
266 resp
= new ErrorResponse (String
.Format ("No handler available for {0}", req
.GetType ()));
267 force_close_connection
= true;
268 } else if (req
.Keepalive
) {
269 this.executor
= exec
;
270 exec
.AsyncResponseEvent
+= OnAsyncResponse
;
274 resp
= exec
.Execute (req
);
277 // It's okay if the response is null; this means
278 // that keepalive is set and that we'll be sending
279 // back responses asynchronously. First, enforce
280 // that the response is not null if keepalive isn't
282 if (resp
== null && !req
.Keepalive
)
283 resp
= new ErrorResponse ("No response available, but keepalive is not set");
286 //Logger.Log.Debug ("Sending response of type {0}", resp.GetType ());
287 if (!this.SendResponse (resp
))
288 force_close_connection
= true;
292 buffer_stream
.Close ();
294 if (force_close_connection
|| !req
.Keepalive
)
299 Server
.MarkHandlerAsKilled (this);
300 Shutdown
.WorkerFinished (network_data
);
304 public class Server
{
306 private static bool initialized
= false;
308 private string socket_path
;
309 private UnixListener listener
;
310 private static Hashtable live_handlers
= new Hashtable ();
311 private bool running
= false;
313 public Server (string name
)
315 ScanAssemblyForExecutors (Assembly
.GetCallingAssembly ());
317 // Use the default name when passed null
321 this.socket_path
= Path
.Combine (PathFinder
.GetRemoteStorageDir (true), name
);
322 this.listener
= new UnixListener (this.socket_path
);
325 public Server () : this (null)
330 // Perform expensive serialization all at once. Do this before signal handler is setup.
331 public static void Init ()
333 ScanAssemblyForExecutors (Assembly
.GetExecutingAssembly ());
334 Shutdown
.ShutdownEvent
+= OnShutdown
;
335 ConnectionHandler
.Init ();
339 static internal void MarkHandlerAsKilled (ConnectionHandler handler
)
341 lock (live_handlers
) {
342 live_handlers
.Remove (handler
);
346 private static void OnShutdown ()
348 lock (live_handlers
) {
349 foreach (ConnectionHandler handler
in live_handlers
.Values
) {
350 Logger
.Log
.Debug ("CancelIfBlocking {0}", handler
);
351 handler
.CancelIfBlocking ();
358 this.listener
.Start ();
361 if (! Shutdown
.WorkerStart (this, String
.Format ("server '{0}'", socket_path
)))
364 while (this.running
) {
367 // This will block for an incoming connection.
368 // FIXME: But not really, it'll only wait a second.
369 // see the FIXME in UnixListener for more info.
370 client
= this.listener
.AcceptUnixClient ();
371 } catch (SocketException
) {
372 // If the listener is stopped while we
373 // wait for a connection, a
374 // SocketException is thrown.
378 // FIXME: This is a hack to work around a mono
379 // bug. See the FIXMEs in UnixListener.cs for
380 // more info, but client should never be null,
381 // because AcceptUnixClient() should be
382 // throwing a SocketException when the
383 // listener is shut down. So when that is
384 // fixed, remove the if conditional.
386 // If client is null, the socket timed out.
387 if (client
!= null) {
388 ConnectionHandler handler
= new ConnectionHandler (client
);
390 live_handlers
[handler
] = handler
;
391 ExceptionHandlingThread
.Start (new ThreadStart (handler
.HandleConnection
));
395 Shutdown
.WorkerFinished (this);
397 Logger
.Log
.Debug ("Server '{0}' shut down", this.socket_path
);
403 throw new Exception ("Server must be initialized before starting");
405 if (!Shutdown
.ShutdownRequested
)
406 ExceptionHandlingThread
.Start (new ThreadStart (this.Run
));
412 this.running
= false;
413 this.listener
.Stop ();
415 File
.Delete (this.socket_path
);
418 //////////////////////////////////////////////////////////////////////////////
421 // Code to dispatch requests to the correct RequestMessageExecutor.
424 public delegate ResponseMessage
RequestMessageHandler (RequestMessage msg
);
426 // A simple wrapper class to turn a RequestMessageHandler delegate into
427 // a RequestMessageExecutor.
428 private class SimpleRequestMessageExecutor
: RequestMessageExecutor
{
430 RequestMessageHandler handler
;
432 public SimpleRequestMessageExecutor (RequestMessageHandler handler
)
434 this.handler
= handler
;
437 public override ResponseMessage
Execute (RequestMessage req
)
439 return this.handler (req
);
443 static private Hashtable scanned_assemblies
= new Hashtable ();
444 static private Hashtable request_type_to_handler
= new Hashtable ();
445 static private Hashtable request_type_to_executor_type
= new Hashtable ();
447 static public void RegisterRequestMessageHandler (Type request_type
, RequestMessageHandler handler
)
449 request_type_to_handler
[request_type
] = handler
;
452 static public void ScanAssemblyForExecutors (Assembly assembly
)
454 if (scanned_assemblies
.Contains (assembly
))
456 scanned_assemblies
[assembly
] = assembly
;
458 foreach (Type t
in assembly
.GetTypes ()) {
460 if (!t
.IsSubclassOf (typeof (RequestMessageExecutor
)))
463 // Yes, we know it doesn't have a RequestMessageAttribute
464 if (t
== typeof (SimpleRequestMessageExecutor
))
467 Attribute attr
= Attribute
.GetCustomAttribute (t
, typeof (RequestMessageAttribute
));
470 Logger
.Log
.Warn ("No handler attribute for executor {0}", t
);
474 RequestMessageAttribute pra
= (RequestMessageAttribute
) attr
;
476 request_type_to_executor_type
[pra
.MessageType
] = t
;
480 static internal RequestMessageExecutor
GetExecutor (RequestMessage req
)
482 Type req_type
= req
.GetType ();
484 RequestMessageExecutor exec
= null;
486 RequestMessageHandler handler
;
487 handler
= request_type_to_handler
[req_type
] as RequestMessageHandler
;
489 if (handler
!= null) {
490 exec
= new SimpleRequestMessageExecutor (handler
);
492 Type t
= request_type_to_executor_type
[req_type
] as Type
;
494 exec
= (RequestMessageExecutor
) Activator
.CreateInstance (t
);