Tokenize 001234 as 1234. Include a testing function in NoiseFilter to figure out...
[beagle.git] / beagled / BeagleDaemon.cs
blob7ba4f4381964f35e9fbab6e06b74496269cbd764
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.IO;
30 using System.Reflection;
31 using System.Runtime.InteropServices;
32 using System.Threading;
33 using Thread = System.Threading.Thread;
34 using GLib;
36 using Beagle.Util;
37 using Log = Beagle.Util.Log;
39 namespace Beagle.Daemon {
40 class BeagleDaemon {
42 public static Thread MainLoopThread = null;
43 private static MainLoop main_loop = null;
45 private static Server server = null;
47 private static bool arg_replace = false;
48 private static bool arg_disable_scheduler = false;
49 private static bool arg_indexing_test_mode = false;
51 public static bool StartServer ()
53 Logger.Log.Debug ("Starting messaging server");
55 try {
56 server = new Server ("socket");
57 server.Start ();
58 } catch (InvalidOperationException) {
59 return false;
62 return true;
65 public static void ReplaceExisting ()
67 Logger.Log.Info ("Attempting to replace another beagled.");
69 do {
70 ShutdownRequest request = new ShutdownRequest ();
71 Logger.Log.Info ("Sending Shutdown");
72 request.Send ();
73 // Give it a second to shut down the messaging server
74 Thread.Sleep (1000);
75 } while (! StartServer ());
78 private static void LogMemoryUsage ()
80 while (! Shutdown.ShutdownRequested) {
81 int vm_rss = SystemInformation.VmRss;
83 SystemInformation.LogMemoryUsage ();
85 if (vm_rss > 300 * 1024) {
86 Logger.Log.Debug ("VmRss too large --- shutting down");
87 Shutdown.BeginShutdown ();
90 Thread.Sleep (5000);
94 private static void PrintUsage ()
96 string usage =
97 "beagled: The daemon to the Beagle search system.\n" +
98 "Web page: http://beagle-project.org\n" +
99 "Copyright (C) 2004-2006 Novell, Inc.\n\n";
101 usage +=
102 "Usage: beagled [OPTIONS]\n\n" +
103 "Options:\n" +
104 " --foreground, --fg\tRun the daemon in the foreground.\n" +
105 " --background, --bg\tRun the daemon in the background.\n" +
106 " --replace\t\tReplace a running daemon with a new instance.\n" +
107 " --debug\t\tWrite out debugging information.\n" +
108 " --debug-memory\tWrite out debugging information about memory use.\n" +
109 " --indexing-test-mode\tRun in foreground, and exit when fully indexed.\n" +
110 " --indexing-delay\tTime to wait before indexing. (Default 60 seconds)\n" +
111 " --backend\t\tConfigure which backends to use. Specifically:\n" +
112 " --backend <name>\tOnly start backend 'name'\n" +
113 " --backend +<name>\tAdditionally start backend 'name'\n" +
114 " --backend -<name>\tDisable backend 'name'\n" +
115 " --allow-backend\t(DEPRECATED) Start only the specific backend.\n" +
116 " --deny-backend\t(DEPRECATED) Deny a specific backend.\n" +
117 " --list-backends\tList all the available backends.\n" +
118 " --add-static-backend\tAdd a static backend by path.\n" +
119 " --disable-scheduler\tDisable the use of the scheduler.\n" +
120 " --help\t\tPrint this usage message.\n";
122 Console.WriteLine (usage);
125 public static bool StartupProcess ()
127 Log.Debug ("Beginning main loop");
129 // Profile our initialization
130 Stopwatch stopwatch = new Stopwatch ();
131 stopwatch.Start ();
133 // Fire up our server
134 if (! StartServer ()) {
135 if (arg_replace)
137 ReplaceExisting ();
139 else {
140 Logger.Log.Error ("Could not set up the listener for beagle requests. "
141 + "There is probably another beagled instance running. "
142 + "Use --replace to replace the running service");
143 Environment.Exit (1);
147 // Set up out-of-process indexing
148 LuceneQueryable.IndexerHook = new LuceneQueryable.IndexerCreator (RemoteIndexer.NewRemoteIndexer);
150 // Initialize synchronization to keep the indexes local if PathFinder.StorageDir
151 // is on a non-block device, or if BEAGLE_SYNCHRONIZE_LOCALLY is set
152 if ((! SystemInformation.IsPathOnBlockDevice (PathFinder.StorageDir) && Conf.Daemon.IndexSynchronization) ||
153 Environment.GetEnvironmentVariable ("BEAGLE_SYNCHRONIZE_LOCALLY") != null)
154 IndexSynchronization.Initialize ();
156 // Start the query driver.
157 Logger.Log.Debug ("Starting QueryDriver");
158 QueryDriver.Start ();
160 bool initially_on_battery = SystemInformation.UsingBattery && ! Conf.Indexing.IndexOnBattery;
162 // Start the Global Scheduler thread
163 if (! arg_disable_scheduler) {
164 if (! initially_on_battery) {
165 Logger.Log.Debug ("Starting Scheduler thread");
166 Scheduler.Global.Start ();
167 } else
168 Log.Debug ("Beagle started on battery, not starting scheduler thread");
171 // Poll the battery status so we can shut down the
172 // scheduler if needed. Ideally at some point this
173 // will become some sort of D-BUS signal, probably from
174 // something like gnome-power-manager.
175 prev_on_battery = initially_on_battery;
176 GLib.Timeout.Add (5000, CheckBatteryStatus);
178 // Start our Inotify threads
179 Inotify.Start ();
181 // Test if the FileAdvise stuff is working: This will print a
182 // warning if not. The actual advice calls will fail silently.
183 FileAdvise.TestAdvise ();
185 Conf.WatchForUpdates ();
187 stopwatch.Stop ();
189 Logger.Log.Debug ("Daemon initialization finished after {0}", stopwatch);
191 SystemInformation.LogMemoryUsage ();
193 if (arg_indexing_test_mode) {
194 Thread.Sleep (1000); // Ugly paranoia: wait a second for the backends to settle.
195 Logger.Log.Debug ("Running in indexing test mode");
196 Scheduler.Global.EmptyQueueEvent += OnEmptySchedulerQueue;
197 Scheduler.Global.Add (null); // pulse the scheduler
199 return false;
202 private static void OnEmptySchedulerQueue ()
204 Logger.Log.Debug ("Scheduler queue is empty: terminating immediately");
205 Shutdown.BeginShutdown ();
206 Environment.Exit (0); // Ugly work-around: We need to call Exit here to avoid deadlocking.
209 public static void Main (string[] args)
211 try {
212 DoMain (args);
213 } catch (Exception ex) {
214 Logger.Log.Error (ex, "Unhandled exception thrown. Exiting immediately.");
215 Environment.Exit (1);
219 [DllImport("libgobject-2.0.so.0")]
220 static extern void g_type_init ();
222 public static void DoMain (string[] args)
224 SystemInformation.InternalCallInitializer.Init ();
225 SystemInformation.SetProcessName ("beagled");
227 // Process the command-line arguments
228 bool arg_debug = false;
229 bool arg_debug_memory = false;
230 bool arg_fg = false;
232 int i = 0;
233 while (i < args.Length) {
235 string arg = args [i];
236 ++i;
237 string next_arg = i < args.Length ? args [i] : null;
239 switch (arg) {
240 case "-h":
241 case "--help":
242 PrintUsage ();
243 Environment.Exit (0);
244 break;
246 case "--heap-buddy":
247 case "--heap-shot":
248 case "--mdb":
249 case "--mono-debug":
250 // Silently ignore these arguments: they get handled
251 // in the wrapper script.
252 break;
254 case "--list-backends":
255 Console.WriteLine ("Current available backends:");
256 Console.Write (QueryDriver.ListBackends ());
257 Environment.Exit (0);
258 break;
260 case "--fg":
261 case "--foreground":
262 arg_fg = true;
263 break;
265 case "--bg":
266 case "--background":
267 arg_fg = false;
268 break;
270 case "--replace":
271 arg_replace = true;
272 break;
274 case "--debug":
275 arg_debug = true;
276 break;
278 case "--debug-memory":
279 arg_debug = true;
280 arg_debug_memory = true;
281 break;
283 case "--indexing-test-mode":
284 arg_indexing_test_mode = true;
285 arg_fg = true;
286 break;
288 case "--backend":
289 if (next_arg == null) {
290 Console.WriteLine ("--backend requires a backend name");
291 Environment.Exit (1);
292 break;
295 if (next_arg.StartsWith ("--")) {
296 Console.WriteLine ("--backend requires a backend name. Invalid name '{0}'", next_arg);
297 Environment.Exit (1);
298 break;
301 if (next_arg [0] != '+' && next_arg [0] != '-')
302 QueryDriver.OnlyAllow (next_arg);
303 else {
304 if (next_arg [0] == '+')
305 QueryDriver.Allow (next_arg.Substring (1));
306 else
307 QueryDriver.Deny (next_arg.Substring (1));
310 ++i; // we used next_arg
311 break;
313 case "--allow-backend":
314 // --allow-backend is deprecated, use --backends 'name' instead
315 // it will disable reading the list of enabled/disabled backends
316 // from conf and start the backend given
317 if (next_arg != null)
318 QueryDriver.OnlyAllow (next_arg);
319 ++i; // we used next_arg
320 break;
322 case "--deny-backend":
323 // deprecated: use --backends -'name' instead
324 if (next_arg != null)
325 QueryDriver.Deny (next_arg);
326 ++i; // we used next_arg
327 break;
329 case "--add-static-backend":
330 if (next_arg != null)
331 QueryDriver.AddStaticQueryable (next_arg);
332 ++i;
333 break;
335 case "--disable-scheduler":
336 arg_disable_scheduler = true;
337 break;
339 case "--indexing-delay":
340 if (next_arg != null) {
341 try {
342 QueryDriver.IndexingDelay = Int32.Parse (next_arg);
343 } catch {
344 Console.WriteLine ("'{0}' is not a valid number of seconds", next_arg);
345 Environment.Exit (1);
349 ++i;
350 break;
352 case "--autostarted":
353 if (! Conf.Searching.Autostart) {
354 Console.WriteLine ("Autostarting is disabled, not starting");
355 Environment.Exit (0);
357 break;
359 default:
360 Console.WriteLine ("Unknown argument '{0}'", arg);
361 Environment.Exit (1);
362 break;
367 if (arg_indexing_test_mode) {
368 LuceneQueryable.OptimizeRightAway = true;
372 // Bail out if we are trying to run as root
373 if (Environment.UserName == "root" && Environment.GetEnvironmentVariable ("SUDO_USER") != null) {
374 Console.WriteLine ("You appear to be running beagle using sudo. This can cause problems with");
375 Console.WriteLine ("permissions in your .beagle and .wapi directories if you later try to run");
376 Console.WriteLine ("as an unprivileged user. If you need to run beagle as root, please use");
377 Console.WriteLine ("'su -c' instead.");
378 Environment.Exit (-1);
381 if (Environment.UserName == "root" && ! Conf.Daemon.AllowRoot) {
382 Console.WriteLine ("You can not run beagle as root. Beagle is designed to run from your own");
383 Console.WriteLine ("user account. If you want to create multiuser or system-wide indexes, use");
384 Console.WriteLine ("the beagle-build-index tool.");
385 Console.WriteLine ();
386 Console.WriteLine ("You can override this setting using the beagle-config or beagle-settings tools.");
387 Environment.Exit (-1);
390 try {
391 string tmp = PathFinder.HomeDir;
392 } catch (Exception e) {
393 Console.WriteLine ("Unable to start the daemon: {0}", e.Message);
394 Environment.Exit (-1);
397 MainLoopThread = Thread.CurrentThread;
399 Log.Initialize (PathFinder.LogDir,
400 "Beagle",
401 // FIXME: We always turn on full debugging output! We are still
402 // debugging this code, after all...
403 //arg_debug ? LogLevel.Debug : LogLevel.Warn,
404 LogLevel.Debug,
405 arg_fg);
407 Logger.Log.Info ("Starting Beagle Daemon (version {0})", ExternalStringsHack.Version);
409 Logger.Log.Info ("Running on {0}", SystemInformation.MonoRuntimeVersion);
411 Logger.Log.Debug ("Command Line: {0}",
412 Environment.CommandLine != null ? Environment.CommandLine : "(null)");
414 if (! ExtendedAttribute.Supported) {
415 Logger.Log.Warn ("Extended attributes are not supported on this filesystem. " +
416 "Performance will suffer as a result.");
419 // Start our memory-logging thread
420 if (arg_debug_memory)
421 ExceptionHandlingThread.Start (new ThreadStart (LogMemoryUsage));
423 // Do BEAGLE_EXERCISE_THE_DOG_HARDER-related processing.
424 ExerciseTheDogHarder ();
426 // Initialize GObject type system
427 g_type_init ();
429 if (SystemInformation.XssInit ())
430 Logger.Log.Debug ("Established a connection to the X server");
431 else
432 Logger.Log.Debug ("Unable to establish a connection to the X server");
433 XSetIOErrorHandler (BeagleXIOErrorHandler);
435 QueryDriver.Init ();
436 Server.Init ();
438 SetupSignalHandlers ();
439 Shutdown.ShutdownEvent += OnShutdown;
441 main_loop = new MainLoop ();
442 Shutdown.RegisterMainLoop (main_loop);
444 // Defer all actual startup until the main loop is
445 // running. That way shutdowns during the startup
446 // process work correctly.
447 GLib.Idle.Add (new GLib.IdleHandler (StartupProcess));
449 // Start our event loop.
450 Logger.Log.Debug ("Starting main loop");
451 main_loop.Run ();
453 // We're out of the main loop now, join all the
454 // running threads so we can exit cleanly.
455 ExceptionHandlingThread.JoinAllThreads ();
457 // If we placed our sockets in a temp directory, try to clean it up
458 // Note: this may fail because the helper is still running
459 if (PathFinder.GetRemoteStorageDir (false) != PathFinder.StorageDir) {
460 try {
461 Directory.Delete (PathFinder.GetRemoteStorageDir (false));
462 } catch (IOException) { }
465 Log.Info ("Beagle daemon process shut down cleanly.");
468 /////////////////////////////////////////////////////////////////////////////
470 private static bool prev_on_battery = false;
472 private static bool CheckBatteryStatus ()
474 if (prev_on_battery && (! SystemInformation.UsingBattery || Conf.Indexing.IndexOnBattery)) {
475 if (! SystemInformation.UsingBattery)
476 Log.Info ("Deletected a switch from battery to AC power. Restarting scheduler.");
477 Scheduler.Global.Start ();
478 prev_on_battery = false;
479 } else if (! prev_on_battery && SystemInformation.UsingBattery && ! Conf.Indexing.IndexOnBattery) {
480 Log.Info ("Detected a switch from AC power to battery. Stopping scheduler.");
481 Scheduler.Global.Stop ();
482 prev_on_battery = true;
485 return true;
489 /////////////////////////////////////////////////////////////////////////////
491 private delegate int XIOErrorHandler (IntPtr display);
493 [DllImport ("libX11.so.6")]
494 extern static private int XSetIOErrorHandler (XIOErrorHandler handler);
496 private static int BeagleXIOErrorHandler (IntPtr display)
498 Logger.Log.Debug ("Lost our connection to the X server! Trying to shut down gracefully");
500 if (! Shutdown.ShutdownRequested)
501 Shutdown.BeginShutdown ();
503 Logger.Log.Debug ("Xlib is forcing us to exit!");
505 ExceptionHandlingThread.SpewLiveThreads ();
507 // Returning will cause xlib to exit immediately.
508 return 0;
511 /////////////////////////////////////////////////////////////////////////////
513 private static void SetupSignalHandlers ()
515 // Force OurSignalHandler to be JITed
516 OurSignalHandler (-1);
518 // Set up our signal handler
519 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGINT, OurSignalHandler);
520 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGTERM, OurSignalHandler);
521 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGUSR1, OurSignalHandler);
523 // Ignore SIGPIPE
524 Mono.Unix.Native.Stdlib.signal (Mono.Unix.Native.Signum.SIGPIPE, Mono.Unix.Native.Stdlib.SIG_IGN);
527 // Mono signal handler allows setting of global variables;
528 // anything else e.g. function calls, even reentrant native methods are risky
529 private static void OurSignalHandler (int signal)
531 // This allows us to call OurSignalHandler w/o doing anything.
532 // We want to call it once to ensure that it is pre-JITed.
533 if (signal < 0)
534 return;
536 // Set shutdown flag to true so that other threads can stop initializing
537 if ((Mono.Unix.Native.Signum) signal != Mono.Unix.Native.Signum.SIGUSR1)
538 Shutdown.ShutdownRequested = true;
540 // Do all signal handling work in the main loop and not in the signal handler.
541 GLib.Idle.Add (new GLib.IdleHandler (delegate () { HandleSignal (signal); return false; }));
544 private static void HandleSignal (int signal)
546 Logger.Log.Debug ("Handling signal {0} ({1})", signal, (Mono.Unix.Native.Signum) signal);
548 // If we get SIGUSR1, turn the debugging level up.
549 if ((Mono.Unix.Native.Signum) signal == Mono.Unix.Native.Signum.SIGUSR1) {
550 LogLevel old_level = Log.Level;
551 Log.Level = LogLevel.Debug;
552 Log.Debug ("Moving from log level {0} to Debug", old_level);
553 GLib.Idle.Add (new GLib.IdleHandler (delegate () { RemoteIndexer.SignalRemoteIndexer (); return false; }));
554 return;
557 Logger.Log.Debug ("Initiating shutdown in response to signal.");
558 Shutdown.BeginShutdown ();
561 /////////////////////////////////////////////////////////////////////////////
563 private static void OnShutdown ()
565 // Stop our Inotify threads
566 Inotify.Stop ();
568 // Stop the global scheduler and ask it to shutdown
569 Scheduler.Global.Stop (true);
571 // Stop the messaging server
572 if (server != null)
573 server.Stop ();
576 /////////////////////////////////////////////////////////////////////////////
579 private static ArrayList exercise_files = new ArrayList ();
581 private static void ExerciseTheDogHarder ()
583 string path;
584 path = Environment.GetEnvironmentVariable ("BEAGLE_EXERCISE_THE_DOG_HARDER");
585 if (path == null)
586 return;
588 DirectoryInfo dir = new DirectoryInfo (path);
589 foreach (FileInfo file in dir.GetFiles ())
590 exercise_files.Add (file);
591 if (exercise_files.Count == 0)
592 return;
594 int N = 5;
595 if (N > exercise_files.Count)
596 N = exercise_files.Count;
598 for (int i = 0; i < N; ++i)
599 ExceptionHandlingThread.Start (new ThreadStart (ExerciseTheDogHarderWorker));
602 private static void ExerciseTheDogHarderWorker ()
604 Random rng = new Random ();
606 while (! Shutdown.ShutdownRequested) {
608 FileInfo file = null;
609 int i;
612 lock (exercise_files) {
613 do {
614 i = rng.Next (exercise_files.Count);
615 file = exercise_files [i] as FileInfo;
616 } while (file == null);
617 exercise_files [i] = null;
620 string target;
621 target = Path.Combine (PathFinder.HomeDir, "_HARDER_" + file.Name);
623 Logger.Log.Debug ("ETDH: Copying {0}", file.Name);
624 file.CopyTo (target, true);
626 lock (exercise_files)
627 exercise_files [i] = file;
629 Thread.Sleep (500 + rng.Next (500));