Remove debug spew
[beagle.git] / beagled / BeagleDaemon.cs
blob8ac5cc625a040934e7f430cf3cc2518633c032dd
1 //
2 // BeagleDaemon.cs
3 //
4 // Copyright (C) 2004-2006 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.Diagnostics;
30 using System.IO;
31 using System.Reflection;
32 using System.Runtime.InteropServices;
33 using System.Threading;
34 using Thread = System.Threading.Thread;
35 using GLib;
37 using Beagle.Util;
38 using Log = Beagle.Util.Log;
40 namespace Beagle.Daemon {
41 class BeagleDaemon {
43 public static Thread MainLoopThread = null;
44 private static MainLoop main_loop = null;
46 private static Server server = null;
48 private static bool arg_replace = false;
49 private static bool arg_disable_scheduler = false;
50 private static bool arg_indexing_test_mode = false;
51 private static bool arg_heap_shot = false;
53 public static bool StartServer ()
55 Logger.Log.Debug ("Starting messaging server");
57 try {
58 server = new Server ("socket");
59 server.Start ();
60 } catch (InvalidOperationException) {
61 return false;
64 return true;
67 public static void ReplaceExisting ()
69 Logger.Log.Info ("Attempting to replace another beagled.");
71 do {
72 ShutdownRequest request = new ShutdownRequest ();
73 Logger.Log.Info ("Sending Shutdown");
74 request.Send ();
75 // Give it a second to shut down the messaging server
76 Thread.Sleep (1000);
77 } while (! StartServer ());
80 private static int prev_rss = -1;
81 private static long prev_gc = -1;
83 private static void MaybeSendSigprof (int rss, long gc)
85 bool send_sigprof = false;
87 try {
88 if (prev_rss == -1 || prev_gc == -1)
89 return;
91 if (rss - prev_rss > 5000 ||
92 (double) rss / (double) prev_rss > 1.05)
93 send_sigprof = true;
95 if ((double) gc / (double) prev_gc > 1.05)
96 send_sigprof = true;
97 } finally {
98 prev_rss = rss;
99 prev_gc = gc;
101 if (send_sigprof) {
102 Log.Debug ("Suspicious memory size change detected. Sending SIGPROF to ourself");
103 Mono.Unix.Native.Syscall.kill (Process.GetCurrentProcess ().Id, Mono.Unix.Native.Signum.SIGPROF);
108 private static void LogMemoryUsage ()
110 while (! Shutdown.ShutdownRequested) {
111 SystemInformation.LogMemoryUsage ();
113 int vm_rss = SystemInformation.VmRss;
115 if (arg_heap_shot)
116 MaybeSendSigprof (vm_rss, GC.GetTotalMemory (false));
118 if (vm_rss > 300 * 1024) {
119 Logger.Log.Debug ("VmRss too large --- shutting down");
120 Shutdown.BeginShutdown ();
123 Thread.Sleep (5000);
127 private static void PrintUsage ()
129 string usage =
130 "beagled: The daemon to the Beagle search system.\n" +
131 "Web page: http://beagle-project.org\n" +
132 "Copyright (C) 2004-2006 Novell, Inc.\n\n";
134 usage +=
135 "Usage: beagled [OPTIONS]\n\n" +
136 "Options:\n" +
137 " --foreground, --fg\tRun the daemon in the foreground.\n" +
138 " --background, --bg\tRun the daemon in the background.\n" +
139 " --replace\t\tReplace a running daemon with a new instance.\n" +
140 " --debug\t\tWrite out debugging information.\n" +
141 " --debug-memory\tWrite out debugging information about memory use.\n" +
142 " --indexing-test-mode\tRun in foreground, and exit when fully indexed.\n" +
143 " --indexing-delay\tTime to wait before indexing. (Default 60 seconds)\n" +
144 " --backend\t\tConfigure which backends to use. Specifically:\n" +
145 " --backend <name>\tOnly start backend 'name'\n" +
146 " --backend +<name>\tAdditionally start backend 'name'\n" +
147 " --backend -<name>\tDisable backend 'name'\n" +
148 " --allow-backend\t(DEPRECATED) Start only the specific backend.\n" +
149 " --deny-backend\t(DEPRECATED) Deny a specific backend.\n" +
150 " --list-backends\tList all the available backends.\n" +
151 " --add-static-backend\tAdd a static backend by path.\n" +
152 " --disable-scheduler\tDisable the use of the scheduler.\n" +
153 " --help\t\tPrint this usage message.\n";
155 Console.WriteLine (usage);
158 public static bool StartupProcess ()
160 Log.Debug ("Beginning main loop");
162 // Profile our initialization
163 Stopwatch stopwatch = new Stopwatch ();
164 stopwatch.Start ();
166 // Fire up our server
167 if (! StartServer ()) {
168 if (arg_replace)
170 ReplaceExisting ();
172 else {
173 Logger.Log.Error ("Could not set up the listener for beagle requests. "
174 + "There is probably another beagled instance running. "
175 + "Use --replace to replace the running service");
176 Environment.Exit (1);
180 // Set up out-of-process indexing
181 LuceneQueryable.IndexerHook = new LuceneQueryable.IndexerCreator (RemoteIndexer.NewRemoteIndexer);
183 // Initialize synchronization to keep the indexes local if PathFinder.StorageDir
184 // is on a non-block device, or if BEAGLE_SYNCHRONIZE_LOCALLY is set
185 if ((! SystemInformation.IsPathOnBlockDevice (PathFinder.StorageDir) && Conf.Daemon.IndexSynchronization) ||
186 Environment.GetEnvironmentVariable ("BEAGLE_SYNCHRONIZE_LOCALLY") != null)
187 IndexSynchronization.Initialize ();
189 // Start the query driver.
190 Logger.Log.Debug ("Starting QueryDriver");
191 QueryDriver.Start ();
193 bool initially_on_battery = SystemInformation.UsingBattery && ! Conf.Indexing.IndexOnBattery;
195 // Start the Global Scheduler thread
196 if (! arg_disable_scheduler) {
197 if (! initially_on_battery) {
198 Logger.Log.Debug ("Starting Scheduler thread");
199 Scheduler.Global.Start ();
200 } else
201 Log.Debug ("Beagle started on battery, not starting scheduler thread");
204 // Poll the battery status so we can shut down the
205 // scheduler if needed. Ideally at some point this
206 // will become some sort of D-BUS signal, probably from
207 // something like gnome-power-manager.
208 prev_on_battery = initially_on_battery;
209 GLib.Timeout.Add (5000, CheckBatteryStatus);
211 // Start our Inotify threads
212 Inotify.Start ();
214 // Test if the FileAdvise stuff is working: This will print a
215 // warning if not. The actual advice calls will fail silently.
216 FileAdvise.TestAdvise ();
218 Conf.WatchForUpdates ();
220 stopwatch.Stop ();
222 Logger.Log.Debug ("Daemon initialization finished after {0}", stopwatch);
224 SystemInformation.LogMemoryUsage ();
226 if (arg_indexing_test_mode) {
227 Thread.Sleep (1000); // Ugly paranoia: wait a second for the backends to settle.
228 Logger.Log.Debug ("Running in indexing test mode");
229 Scheduler.Global.EmptyQueueEvent += OnEmptySchedulerQueue;
230 Scheduler.Global.Add (null); // pulse the scheduler
232 return false;
235 private static void OnEmptySchedulerQueue ()
237 Logger.Log.Debug ("Scheduler queue is empty: terminating immediately");
238 Shutdown.BeginShutdown ();
239 Environment.Exit (0); // Ugly work-around: We need to call Exit here to avoid deadlocking.
242 public static void Main (string[] args)
244 try {
245 DoMain (args);
246 } catch (Exception ex) {
247 Logger.Log.Error (ex, "Unhandled exception thrown. Exiting immediately.");
248 Environment.Exit (1);
252 [DllImport("libgobject-2.0.so.0")]
253 static extern void g_type_init ();
255 public static void DoMain (string[] args)
257 SystemInformation.InternalCallInitializer.Init ();
258 SystemInformation.SetProcessName ("beagled");
260 // Process the command-line arguments
261 bool arg_debug = false;
262 bool arg_debug_memory = false;
263 bool arg_fg = false;
265 int i = 0;
266 while (i < args.Length) {
268 string arg = args [i];
269 ++i;
270 string next_arg = i < args.Length ? args [i] : null;
272 switch (arg) {
273 case "-h":
274 case "--help":
275 PrintUsage ();
276 Environment.Exit (0);
277 break;
279 case "--mdb":
280 case "--mono-debug":
281 // Silently ignore these arguments: they get handled
282 // in the wrapper script.
283 break;
285 case "--list-backends":
286 Console.WriteLine ("Current available backends:");
287 Console.Write (QueryDriver.ListBackends ());
288 Environment.Exit (0);
289 break;
291 case "--fg":
292 case "--foreground":
293 arg_fg = true;
294 break;
296 case "--bg":
297 case "--background":
298 arg_fg = false;
299 break;
301 case "--replace":
302 arg_replace = true;
303 break;
305 case "--debug":
306 arg_debug = true;
307 break;
309 case "--heap-shot":
310 arg_heap_shot = true;
311 arg_debug = true;
312 arg_debug_memory = true;
313 break;
315 case "--heap-buddy":
316 case "--debug-memory":
317 arg_debug = true;
318 arg_debug_memory = true;
319 break;
321 case "--indexing-test-mode":
322 arg_indexing_test_mode = true;
323 arg_fg = true;
324 break;
326 case "--backend":
327 if (next_arg == null) {
328 Console.WriteLine ("--backend requires a backend name");
329 Environment.Exit (1);
330 break;
333 if (next_arg.StartsWith ("--")) {
334 Console.WriteLine ("--backend requires a backend name. Invalid name '{0}'", next_arg);
335 Environment.Exit (1);
336 break;
339 if (next_arg [0] != '+' && next_arg [0] != '-')
340 QueryDriver.OnlyAllow (next_arg);
341 else {
342 if (next_arg [0] == '+')
343 QueryDriver.Allow (next_arg.Substring (1));
344 else
345 QueryDriver.Deny (next_arg.Substring (1));
348 ++i; // we used next_arg
349 break;
351 case "--allow-backend":
352 // --allow-backend is deprecated, use --backends 'name' instead
353 // it will disable reading the list of enabled/disabled backends
354 // from conf and start the backend given
355 if (next_arg != null)
356 QueryDriver.OnlyAllow (next_arg);
357 ++i; // we used next_arg
358 break;
360 case "--deny-backend":
361 // deprecated: use --backends -'name' instead
362 if (next_arg != null)
363 QueryDriver.Deny (next_arg);
364 ++i; // we used next_arg
365 break;
367 case "--add-static-backend":
368 if (next_arg != null)
369 QueryDriver.AddStaticQueryable (next_arg);
370 ++i;
371 break;
373 case "--disable-scheduler":
374 arg_disable_scheduler = true;
375 break;
377 case "--indexing-delay":
378 if (next_arg != null) {
379 try {
380 QueryDriver.IndexingDelay = Int32.Parse (next_arg);
381 } catch {
382 Console.WriteLine ("'{0}' is not a valid number of seconds", next_arg);
383 Environment.Exit (1);
387 ++i;
388 break;
390 case "--autostarted":
391 if (! Conf.Searching.Autostart) {
392 Console.WriteLine ("Autostarting is disabled, not starting");
393 Environment.Exit (0);
395 break;
397 default:
398 Console.WriteLine ("Unknown argument '{0}'", arg);
399 Environment.Exit (1);
400 break;
405 if (arg_indexing_test_mode) {
406 LuceneQueryable.OptimizeRightAway = true;
410 // Bail out if we are trying to run as root
411 if (Environment.UserName == "root" && Environment.GetEnvironmentVariable ("SUDO_USER") != null) {
412 Console.WriteLine ("You appear to be running beagle using sudo. This can cause problems with");
413 Console.WriteLine ("permissions in your .beagle and .wapi directories if you later try to run");
414 Console.WriteLine ("as an unprivileged user. If you need to run beagle as root, please use");
415 Console.WriteLine ("'su -c' instead.");
416 Environment.Exit (-1);
419 if (Environment.UserName == "root" && ! Conf.Daemon.AllowRoot) {
420 Console.WriteLine ("You can not run beagle as root. Beagle is designed to run from your own");
421 Console.WriteLine ("user account. If you want to create multiuser or system-wide indexes, use");
422 Console.WriteLine ("the beagle-build-index tool.");
423 Console.WriteLine ();
424 Console.WriteLine ("You can override this setting using the beagle-config or beagle-settings tools.");
425 Environment.Exit (-1);
428 try {
429 string tmp = PathFinder.HomeDir;
430 } catch (Exception e) {
431 Console.WriteLine ("Unable to start the daemon: {0}", e.Message);
432 Environment.Exit (-1);
435 MainLoopThread = Thread.CurrentThread;
437 Log.Initialize (PathFinder.LogDir,
438 "Beagle",
439 // FIXME: We always turn on full debugging output! We are still
440 // debugging this code, after all...
441 //arg_debug ? LogLevel.Debug : LogLevel.Warn,
442 LogLevel.Debug,
443 arg_fg);
445 Logger.Log.Info ("Starting Beagle Daemon (version {0})", ExternalStringsHack.Version);
447 Logger.Log.Info ("Running on {0}", SystemInformation.MonoRuntimeVersion);
449 Logger.Log.Debug ("Command Line: {0}",
450 Environment.CommandLine != null ? Environment.CommandLine : "(null)");
452 if (! ExtendedAttribute.Supported) {
453 Logger.Log.Warn ("Extended attributes are not supported on this filesystem. " +
454 "Performance will suffer as a result.");
457 // Start our memory-logging thread
458 if (arg_debug_memory)
459 ExceptionHandlingThread.Start (new ThreadStart (LogMemoryUsage));
461 // Do BEAGLE_EXERCISE_THE_DOG_HARDER-related processing.
462 ExerciseTheDogHarder ();
464 // Initialize GObject type system
465 g_type_init ();
467 if (SystemInformation.XssInit ())
468 Logger.Log.Debug ("Established a connection to the X server");
469 else
470 Logger.Log.Debug ("Unable to establish a connection to the X server");
471 XSetIOErrorHandler (BeagleXIOErrorHandler);
473 QueryDriver.Init ();
474 Server.Init ();
476 SetupSignalHandlers ();
477 Shutdown.ShutdownEvent += OnShutdown;
479 main_loop = new MainLoop ();
480 Shutdown.RegisterMainLoop (main_loop);
482 // Defer all actual startup until the main loop is
483 // running. That way shutdowns during the startup
484 // process work correctly.
485 GLib.Idle.Add (new GLib.IdleHandler (StartupProcess));
487 // Start our event loop.
488 Logger.Log.Debug ("Starting main loop");
489 main_loop.Run ();
491 // We're out of the main loop now, join all the
492 // running threads so we can exit cleanly.
493 ExceptionHandlingThread.JoinAllThreads ();
495 // If we placed our sockets in a temp directory, try to clean it up
496 // Note: this may fail because the helper is still running
497 if (PathFinder.GetRemoteStorageDir (false) != PathFinder.StorageDir) {
498 try {
499 Directory.Delete (PathFinder.GetRemoteStorageDir (false));
500 } catch (IOException) { }
503 Log.Info ("Beagle daemon process shut down cleanly.");
506 /////////////////////////////////////////////////////////////////////////////
508 private static bool prev_on_battery = false;
510 private static bool CheckBatteryStatus ()
512 if (prev_on_battery && (! SystemInformation.UsingBattery || Conf.Indexing.IndexOnBattery)) {
513 if (! SystemInformation.UsingBattery)
514 Log.Info ("Deletected a switch from battery to AC power. Restarting scheduler.");
515 Scheduler.Global.Start ();
516 prev_on_battery = false;
517 } else if (! prev_on_battery && SystemInformation.UsingBattery && ! Conf.Indexing.IndexOnBattery) {
518 Log.Info ("Detected a switch from AC power to battery. Stopping scheduler.");
519 Scheduler.Global.Stop ();
520 prev_on_battery = true;
523 return true;
527 /////////////////////////////////////////////////////////////////////////////
529 private delegate int XIOErrorHandler (IntPtr display);
531 [DllImport ("libX11.so.6")]
532 extern static private int XSetIOErrorHandler (XIOErrorHandler handler);
534 private static int BeagleXIOErrorHandler (IntPtr display)
536 Logger.Log.Debug ("Lost our connection to the X server! Trying to shut down gracefully");
538 if (! Shutdown.ShutdownRequested)
539 Shutdown.BeginShutdown ();
541 Logger.Log.Debug ("Xlib is forcing us to exit!");
543 ExceptionHandlingThread.SpewLiveThreads ();
545 // Returning will cause xlib to exit immediately.
546 return 0;
549 /////////////////////////////////////////////////////////////////////////////
551 private static void SetupSignalHandlers ()
553 // Force OurSignalHandler to be JITed
554 OurSignalHandler (-1);
556 // Set up our signal handler
557 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGINT, OurSignalHandler);
558 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGTERM, OurSignalHandler);
559 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGUSR1, OurSignalHandler);
561 // Ignore SIGPIPE
562 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGPIPE, Mono.Unix.Native.Stdlib.SIG_IGN);
565 // Mono signal handler allows setting of global variables;
566 // anything else e.g. function calls, even reentrant native methods are risky
567 private static void OurSignalHandler (int signal)
569 // This allows us to call OurSignalHandler w/o doing anything.
570 // We want to call it once to ensure that it is pre-JITed.
571 if (signal < 0)
572 return;
574 // Set shutdown flag to true so that other threads can stop initializing
575 if ((Mono.Unix.Native.Signum) signal != Mono.Unix.Native.Signum.SIGUSR1)
576 Shutdown.ShutdownRequested = true;
578 // Do all signal handling work in the main loop and not in the signal handler.
579 GLib.Idle.Add (new GLib.IdleHandler (delegate () { HandleSignal (signal); return false; }));
582 private static void HandleSignal (int signal)
584 Logger.Log.Debug ("Handling signal {0} ({1})", signal, (Mono.Unix.Native.Signum) signal);
586 // If we get SIGUSR1, turn the debugging level up.
587 if ((Mono.Unix.Native.Signum) signal == Mono.Unix.Native.Signum.SIGUSR1) {
588 LogLevel old_level = Log.Level;
589 Log.Level = LogLevel.Debug;
590 Log.Debug ("Moving from log level {0} to Debug", old_level);
591 GLib.Idle.Add (new GLib.IdleHandler (delegate () { RemoteIndexer.SignalRemoteIndexer (); return false; }));
592 return;
595 Logger.Log.Debug ("Initiating shutdown in response to signal.");
596 Shutdown.BeginShutdown ();
599 /////////////////////////////////////////////////////////////////////////////
601 private static void OnShutdown ()
603 // Stop our Inotify threads
604 Inotify.Stop ();
606 // Stop the global scheduler and ask it to shutdown
607 Scheduler.Global.Stop (true);
609 // Stop the messaging server
610 if (server != null)
611 server.Stop ();
614 /////////////////////////////////////////////////////////////////////////////
617 private static ArrayList exercise_files = new ArrayList ();
619 private static void ExerciseTheDogHarder ()
621 string path;
622 path = Environment.GetEnvironmentVariable ("BEAGLE_EXERCISE_THE_DOG_HARDER");
623 if (path == null)
624 return;
626 DirectoryInfo dir = new DirectoryInfo (path);
627 foreach (FileInfo file in dir.GetFiles ())
628 exercise_files.Add (file);
629 if (exercise_files.Count == 0)
630 return;
632 int N = 5;
633 if (N > exercise_files.Count)
634 N = exercise_files.Count;
636 for (int i = 0; i < N; ++i)
637 ExceptionHandlingThread.Start (new ThreadStart (ExerciseTheDogHarderWorker));
640 private static void ExerciseTheDogHarderWorker ()
642 Random rng = new Random ();
644 while (! Shutdown.ShutdownRequested) {
646 FileInfo file = null;
647 int i;
650 lock (exercise_files) {
651 do {
652 i = rng.Next (exercise_files.Count);
653 file = exercise_files [i] as FileInfo;
654 } while (file == null);
655 exercise_files [i] = null;
658 string target;
659 target = Path.Combine (PathFinder.HomeDir, "_HARDER_" + file.Name);
661 Logger.Log.Debug ("ETDH: Copying {0}", file.Name);
662 file.CopyTo (target, true);
664 lock (exercise_files)
665 exercise_files [i] = file;
667 Thread.Sleep (500 + rng.Next (500));