* KNotesQueryable.cs: Dont re-index all the notes when the notes file changes. Since...
[beagle.git] / beagled / Server.cs
blobce9c30663d8a8420abc00e7430daabe156ddffe9
1 //
2 // Server.cs
3 //
4 // Copyright (C) 2005 Novell, Inc.
5 //
7 //
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.
27 using System;
28 using System.Collections;
29 using System.IO;
30 using System.Net.Sockets;
31 using System.Reflection;
32 using System.Threading;
33 using System.Xml.Serialization;
34 using Mono.Unix;
36 using Beagle.Util;
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)
56 this.client = 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)
70 return false;
72 try {
73 #if ENABLE_XML_DUMP
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 ());
81 mem_stream.Close ();
82 #else
83 XmlFu.SerializeUtf8 (resp_serializer, this.client.GetStream (), new ResponseWrapper (response));
84 #endif
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 (e, "Caught an exception sending response. Shutting down socket.");
90 return false;
93 return true;
97 public void CancelIfBlocking ()
99 // Work around some crappy .net behavior. We can't
100 // close a socket and have it exit out of a blocking
101 // read, so we have to abort the thread it's blocking
102 // in.
103 lock (this.blocking_read_lock) {
104 if (this.in_blocking_read) {
105 this.thread.Abort ();
110 public void Close ()
112 CancelIfBlocking ();
114 // It's important that we abort the thread before we
115 // grab the lock here and close the underlying
116 // UnixClient, or else we'd deadlock between here and
117 // the Read() in HandleConnection()
118 lock (this.client_lock) {
119 if (this.client != null) {
120 this.client.Close ();
121 this.client = null;
125 if (this.executor != null) {
126 this.executor.Cleanup ();
127 this.executor.AsyncResponseEvent -= OnAsyncResponse;
131 public void WatchCallback (IAsyncResult ar)
133 int bytes_read = 0;
135 try {
136 bytes_read = this.client.GetStream ().EndRead (ar);
137 } catch (SocketException) {
138 } catch (IOException) { }
140 if (bytes_read == 0)
141 Close ();
142 else
143 SetupWatch ();
146 private void SetupWatch ()
148 if (this.client == null) {
149 this.Close ();
150 return;
153 this.client.GetStream ().BeginRead (new byte[1024], 0, 1024,
154 new AsyncCallback (WatchCallback), null);
157 private void OnAsyncResponse (ResponseMessage response)
159 if (!SendResponse (response))
160 Close ();
163 public void HandleConnection ()
165 this.thread = Thread.CurrentThread;
167 RequestMessage req = null;
168 ResponseMessage resp = null;
170 bool force_close_connection = false;
172 // Read the data off the socket and store it in a
173 // temporary memory buffer. Once the end-of-message
174 // character has been read, discard remaining data
175 // and deserialize the request.
176 byte[] network_data = new byte [4096];
177 MemoryStream buffer_stream = new MemoryStream ();
178 int bytes_read, total_bytes = 0, end_index = -1;
180 // We use the network_data array as an object to represent this worker.
181 Shutdown.WorkerStart (network_data, String.Format ("HandleConnection ({0})", ++connection_count));
183 do {
184 bytes_read = 0;
186 try {
187 lock (this.blocking_read_lock)
188 this.in_blocking_read = true;
190 lock (this.client_lock) {
191 // The connection may have been closed within this loop.
192 if (this.client != null)
193 bytes_read = this.client.GetStream ().Read (network_data, 0, 4096);
196 lock (this.blocking_read_lock)
197 this.in_blocking_read = false;
198 } catch (Exception e) {
199 // Aborting the thread mid-read will
200 // cause an IOException to be thorwn,
201 // which sets the ThreadAbortException
202 // as its InnerException.
203 if (!(e is IOException || e is ThreadAbortException))
204 throw;
206 Logger.Log.Debug ("Bailing out of HandleConnection -- shutdown requested");
207 Server.MarkHandlerAsKilled (this);
208 Shutdown.WorkerFinished (network_data);
209 return;
212 total_bytes += bytes_read;
214 if (bytes_read > 0) {
215 // 0xff signifies end of message
216 end_index = ArrayFu.IndexOfByte (network_data, (byte) 0xff);
218 buffer_stream.Write (network_data, 0,
219 end_index == -1 ? bytes_read : end_index);
221 } while (bytes_read > 0 && end_index == -1);
223 // Something just connected to our socket and then
224 // hung up. The IndexHelper (among other things) does
225 // this to check that a server is still running. It's
226 // no big deal, so just clean up and close without
227 // running any handlers.
228 if (total_bytes == 0) {
229 force_close_connection = true;
230 goto cleanup;
233 buffer_stream.Seek (0, SeekOrigin.Begin);
235 #if ENABLE_XML_DUMP
236 StreamReader r = new StreamReader (buffer_stream);
237 Logger.Log.Debug ("Received request:\n{0}\n", r.ReadToEnd ());
238 buffer_stream.Seek (0, SeekOrigin.Begin);
239 #endif
241 try {
242 RequestWrapper wrapper = (RequestWrapper) req_serializer.Deserialize (buffer_stream);
244 req = wrapper.Message;
245 } catch (Exception e) {
246 resp = new ErrorResponse (e);
247 force_close_connection = true;
250 // If XmlSerializer can't deserialize the payload, we
251 // may get a null payload and not an exception. Or
252 // maybe the client just didn't send one.
253 if (req == null && resp == null) {
254 resp = new ErrorResponse ("Missing payload");
255 force_close_connection = true;
258 // And if there are no errors, execute the command
259 if (resp == null) {
261 RequestMessageExecutor exec;
262 exec = Server.GetExecutor (req);
264 if (exec == null) {
265 resp = new ErrorResponse (String.Format ("No handler available for {0}", req.GetType ()));
266 force_close_connection = true;
267 } else if (req.Keepalive) {
268 this.executor = exec;
269 exec.AsyncResponseEvent += OnAsyncResponse;
272 if (exec != null)
273 resp = exec.Execute (req);
276 // It's okay if the response is null; this means
277 // that keepalive is set and that we'll be sending
278 // back responses asynchronously. First, enforce
279 // that the response is not null if keepalive isn't
280 // set.
281 if (resp == null && !req.Keepalive)
282 resp = new ErrorResponse ("No response available, but keepalive is not set");
284 if (resp != null) {
285 //Logger.Log.Debug ("Sending response of type {0}", resp.GetType ());
286 if (!this.SendResponse (resp))
287 force_close_connection = true;
290 cleanup:
291 buffer_stream.Close ();
293 if (force_close_connection || !req.Keepalive)
294 Close ();
295 else
296 SetupWatch ();
298 Server.MarkHandlerAsKilled (this);
299 Shutdown.WorkerFinished (network_data);
303 public class Server {
305 private static bool initialized = false;
307 private string socket_path;
308 private UnixListener listener;
309 private static Hashtable live_handlers = new Hashtable ();
310 private bool running = false;
312 public Server (string name)
314 ScanAssemblyForExecutors (Assembly.GetCallingAssembly ());
316 // Use the default name when passed null
317 if (name == null)
318 name = "socket";
320 this.socket_path = Path.Combine (PathFinder.GetRemoteStorageDir (true), name);
321 this.listener = new UnixListener (this.socket_path);
324 public Server () : this (null)
329 // Perform expensive serialization all at once. Do this before signal handler is setup.
330 public static void Init ()
332 ScanAssemblyForExecutors (Assembly.GetExecutingAssembly ());
333 Shutdown.ShutdownEvent += OnShutdown;
334 ConnectionHandler.Init ();
335 initialized = true;
338 static internal void MarkHandlerAsKilled (ConnectionHandler handler)
340 lock (live_handlers) {
341 live_handlers.Remove (handler);
345 private static void OnShutdown ()
347 lock (live_handlers) {
348 foreach (ConnectionHandler handler in live_handlers.Values) {
349 Logger.Log.Debug ("CancelIfBlocking {0}", handler);
350 handler.CancelIfBlocking ();
355 private void Run ()
357 this.listener.Start ();
358 this.running = true;
360 if (! Shutdown.WorkerStart (this, String.Format ("server '{0}'", socket_path)))
361 return;
363 while (this.running) {
364 UnixClient client;
365 try {
366 // This will block for an incoming connection.
367 // FIXME: But not really, it'll only wait a second.
368 // see the FIXME in UnixListener for more info.
369 client = this.listener.AcceptUnixClient ();
370 } catch (SocketException) {
371 // If the listener is stopped while we
372 // wait for a connection, a
373 // SocketException is thrown.
374 break;
377 // FIXME: This is a hack to work around a mono
378 // bug. See the FIXMEs in UnixListener.cs for
379 // more info, but client should never be null,
380 // because AcceptUnixClient() should be
381 // throwing a SocketException when the
382 // listener is shut down. So when that is
383 // fixed, remove the if conditional.
385 // If client is null, the socket timed out.
386 if (client != null) {
387 ConnectionHandler handler = new ConnectionHandler (client);
388 lock (live_handlers)
389 live_handlers [handler] = handler;
390 ExceptionHandlingThread.Start (new ThreadStart (handler.HandleConnection));
394 Shutdown.WorkerFinished (this);
396 Logger.Log.Debug ("Server '{0}' shut down", this.socket_path);
399 public void Start ()
401 if (!initialized)
402 throw new Exception ("Server must be initialized before starting");
404 if (!Shutdown.ShutdownRequested)
405 ExceptionHandlingThread.Start (new ThreadStart (this.Run));
408 public void Stop ()
410 if (this.running) {
411 this.running = false;
412 this.listener.Stop ();
414 File.Delete (this.socket_path);
417 //////////////////////////////////////////////////////////////////////////////
420 // Code to dispatch requests to the correct RequestMessageExecutor.
423 public delegate ResponseMessage RequestMessageHandler (RequestMessage msg);
425 // A simple wrapper class to turn a RequestMessageHandler delegate into
426 // a RequestMessageExecutor.
427 private class SimpleRequestMessageExecutor : RequestMessageExecutor {
429 RequestMessageHandler handler;
431 public SimpleRequestMessageExecutor (RequestMessageHandler handler)
433 this.handler = handler;
436 public override ResponseMessage Execute (RequestMessage req)
438 return this.handler (req);
442 static private Hashtable scanned_assemblies = new Hashtable ();
443 static private Hashtable request_type_to_handler = new Hashtable ();
444 static private Hashtable request_type_to_executor_type = new Hashtable ();
446 static public void RegisterRequestMessageHandler (Type request_type, RequestMessageHandler handler)
448 request_type_to_handler [request_type] = handler;
451 static public void ScanAssemblyForExecutors (Assembly assembly)
453 if (scanned_assemblies.Contains (assembly))
454 return;
455 scanned_assemblies [assembly] = assembly;
457 foreach (Type t in assembly.GetTypes ()) {
459 if (!t.IsSubclassOf (typeof (RequestMessageExecutor)))
460 continue;
462 // Yes, we know it doesn't have a RequestMessageAttribute
463 if (t == typeof (SimpleRequestMessageExecutor))
464 continue;
466 Attribute attr = Attribute.GetCustomAttribute (t, typeof (RequestMessageAttribute));
468 if (attr == null) {
469 Logger.Log.Warn ("No handler attribute for executor {0}", t);
470 continue;
473 RequestMessageAttribute pra = (RequestMessageAttribute) attr;
475 request_type_to_executor_type [pra.MessageType] = t;
479 static internal RequestMessageExecutor GetExecutor (RequestMessage req)
481 Type req_type = req.GetType ();
483 RequestMessageExecutor exec = null;
485 RequestMessageHandler handler;
486 handler = request_type_to_handler [req_type] as RequestMessageHandler;
488 if (handler != null) {
489 exec = new SimpleRequestMessageExecutor (handler);
490 } else {
491 Type t = request_type_to_executor_type [req_type] as Type;
492 if (t != null)
493 exec = (RequestMessageExecutor) Activator.CreateInstance (t);
496 return exec;