4 // Copyright (C) 2004-2006 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
;
29 using System
.Diagnostics
;
31 using System
.Reflection
;
32 using System
.Runtime
.InteropServices
;
33 using System
.Threading
;
34 using Thread
= System
.Threading
.Thread
;
38 using Log
= Beagle
.Util
.Log
;
40 namespace Beagle
.Daemon
{
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");
58 server
= new Server ("socket");
60 } catch (InvalidOperationException
) {
67 public static void ReplaceExisting ()
69 Logger
.Log
.Info ("Attempting to replace another beagled.");
72 ShutdownRequest request
= new ShutdownRequest ();
73 Logger
.Log
.Info ("Sending Shutdown");
75 // Give it a second to shut down the messaging server
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;
88 if (prev_rss
== -1 || prev_gc
== -1)
91 if (rss
- prev_rss
> 5000 ||
92 (double) rss
/ (double) prev_rss
> 1.05)
95 if ((double) gc
/ (double) prev_gc
> 1.05)
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
;
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 ();
127 private static void PrintUsage ()
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";
135 "Usage: beagled [OPTIONS]\n\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 ();
166 // Fire up our server
167 if (! StartServer ()) {
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 ();
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
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 ();
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
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
)
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;
266 while (i
< args
.Length
) {
268 string arg
= args
[i
];
270 string next_arg
= i
< args
.Length
? args
[i
] : null;
276 Environment
.Exit (0);
281 // Silently ignore these arguments: they get handled
282 // in the wrapper script.
285 case "--list-backends":
286 Console
.WriteLine ("Current available backends:");
287 Console
.Write (QueryDriver
.ListBackends ());
288 Environment
.Exit (0);
310 arg_heap_shot
= true;
312 arg_debug_memory
= true;
316 case "--debug-memory":
318 arg_debug_memory
= true;
321 case "--indexing-test-mode":
322 arg_indexing_test_mode
= true;
327 if (next_arg
== null) {
328 Console
.WriteLine ("--backend requires a backend name");
329 Environment
.Exit (1);
333 if (next_arg
.StartsWith ("--")) {
334 Console
.WriteLine ("--backend requires a backend name. Invalid name '{0}'", next_arg
);
335 Environment
.Exit (1);
339 if (next_arg
[0] != '+' && next_arg
[0] != '-')
340 QueryDriver
.OnlyAllow (next_arg
);
342 if (next_arg
[0] == '+')
343 QueryDriver
.Allow (next_arg
.Substring (1));
345 QueryDriver
.Deny (next_arg
.Substring (1));
348 ++i
; // we used next_arg
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
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
367 case "--add-static-backend":
368 if (next_arg
!= null)
369 QueryDriver
.AddStaticQueryable (next_arg
);
373 case "--disable-scheduler":
374 arg_disable_scheduler
= true;
377 case "--indexing-delay":
378 if (next_arg
!= null) {
380 QueryDriver
.IndexingDelay
= Int32
.Parse (next_arg
);
382 Console
.WriteLine ("'{0}' is not a valid number of seconds", next_arg
);
383 Environment
.Exit (1);
390 case "--autostarted":
391 if (! Conf
.Searching
.Autostart
) {
392 Console
.WriteLine ("Autostarting is disabled, not starting");
393 Environment
.Exit (0);
398 Console
.WriteLine ("Unknown argument '{0}'", arg
);
399 Environment
.Exit (1);
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);
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
,
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,
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
467 if (SystemInformation
.XssInit ())
468 Logger
.Log
.Debug ("Established a connection to the X server");
470 Logger
.Log
.Debug ("Unable to establish a connection to the X server");
471 XSetIOErrorHandler (BeagleXIOErrorHandler
);
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");
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
) {
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;
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.
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
);
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.
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; }
));
595 Logger
.Log
.Debug ("Initiating shutdown in response to signal.");
596 Shutdown
.BeginShutdown ();
599 /////////////////////////////////////////////////////////////////////////////
601 private static void OnShutdown ()
603 // Stop our Inotify threads
606 // Stop the global scheduler and ask it to shutdown
607 Scheduler
.Global
.Stop (true);
609 // Stop the messaging server
614 /////////////////////////////////////////////////////////////////////////////
617 private static ArrayList exercise_files
= new ArrayList ();
619 private static void ExerciseTheDogHarder ()
622 path
= Environment
.GetEnvironmentVariable ("BEAGLE_EXERCISE_THE_DOG_HARDER");
626 DirectoryInfo dir
= new DirectoryInfo (path
);
627 foreach (FileInfo file
in dir
.GetFiles ())
628 exercise_files
.Add (file
);
629 if (exercise_files
.Count
== 0)
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;
650 lock (exercise_files
) {
652 i
= rng
.Next (exercise_files
.Count
);
653 file
= exercise_files
[i
] as FileInfo
;
654 } while (file
== null);
655 exercise_files
[i
] = null;
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));