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
;
30 using System
.Reflection
;
31 using System
.Runtime
.InteropServices
;
32 using System
.Threading
;
38 #if ENABLE_WEBSERVICES
39 using Beagle
.WebService
;
42 namespace Beagle
.Daemon
{
45 public static Thread MainLoopThread
= null;
47 private static Server server
= null;
49 private static bool arg_replace
= false;
50 private static bool arg_disable_scheduler
= false;
51 private static bool arg_indexing_test_mode
= false;
53 public static bool StartServer ()
55 Logger
.Log
.Debug ("Starting messaging server");
57 server
= new Server ("socket");
59 } catch (InvalidOperationException
) {
66 public static void ReplaceExisting ()
68 Logger
.Log
.Info ("Attempting to replace another beagled.");
71 ShutdownRequest request
= new ShutdownRequest ();
72 Logger
.Log
.Info ("Sending Shutdown");
74 // Give it a second to shut down the messaging server
76 } while (! StartServer ());
79 private static void LogMemoryUsage ()
81 while (! Shutdown
.ShutdownRequested
) {
82 int vm_size
= SystemInformation
.VmSize
;
83 int vm_rss
= SystemInformation
.VmRss
;
85 Logger
.Log
.Debug ("Memory usage: VmSize={0:.0} MB, VmRSS={1:.0} MB, GC.GetTotalMemory={2}",
86 vm_size
/1024.0, vm_rss
/1024.0, GC
.GetTotalMemory (false));
88 if (vm_size
> 300 * 1024) {
89 Logger
.Log
.Debug ("VmSize too large --- shutting down");
90 Shutdown
.BeginShutdown ();
97 private static void PrintUsage ()
100 "beagled: The daemon to the Beagle search system.\n" +
101 "Web page: http://beagle-project.org\n" +
102 "Copyright (C) 2004-2006 Novell, Inc.\n\n";
105 "Usage: beagled [OPTIONS]\n\n" +
107 " --foreground, --fg\tRun the daemon in the foreground.\n" +
108 " --background, --bg\tRun the daemon in the background.\n" +
109 " --replace\t\tReplace a running daemon with a new instance.\n" +
110 " --debug\t\tWrite out debugging information.\n" +
111 " --debug-memory\tWrite out debugging information about memory use.\n" +
112 " --indexing-test-mode\tRun in foreground, and exit when fully indexed.\n" +
113 " --indexing-delay\tTime to wait before indexing. (Default 60 seconds)\n" +
114 " --backend\t\tConfigure which backends to use. Specifically:\n" +
115 " --backend <name>\tOnly start backend 'name'\n" +
116 " --backend +<name>\tAdditionally start backend 'name'\n" +
117 " --backend -<name>\tDisable backend 'name'\n" +
118 " --allow-backend\t(DEPRECATED) Start only the specific backend.\n" +
119 " --deny-backend\t(DEPRECATED) Deny a specific backend.\n" +
120 " --list-backends\tList all the available backends.\n" +
121 " --add-static-backend\tAdd a static backend by path.\n" +
122 " --disable-scheduler\tDisable the use of the scheduler.\n" +
123 " --help\t\tPrint this usage message.\n";
125 #if ENABLE_WEBSERVICES
127 " --web-global\t\tAllow global access to the Web & WebService interfaces.\n" +
128 " --web-port\t\tPort to use for the internal web server.\n" +
129 " --web-root\t\tRoot directory to use for the internal web server.\n" +
130 " --web-disable\t\tDisable Web & WebServices functionality.\n";
133 Console
.WriteLine (usage
);
136 public static bool StartupProcess ()
138 // Profile our initialization
139 Stopwatch stopwatch
= new Stopwatch ();
142 SetupSignalHandlers ();
144 // Fire up our server
145 if (! StartServer ()) {
148 #if ENABLE_WEBSERVICES
149 WebServiceBackEnd
.Stop();
154 Logger
.Log
.Error ("Could not set up the listener for beagle requests. "
155 + "There is probably another beagled instance running. "
156 + "Use --replace to replace the running service");
157 Environment
.Exit (1);
161 // Set up out-of-process indexing
162 if (Environment
.GetEnvironmentVariable ("BEAGLE_ENABLE_IN_PROCESS_INDEXING") == null)
163 LuceneQueryable
.IndexerHook
= new LuceneQueryable
.IndexerCreator (RemoteIndexer
.NewRemoteIndexer
);
165 // Initialize syncronization to keep the indexes local if PathFinder.HomeDir
166 // is on a non-block device, or if BEAGLE_SYNCHRONIZE_LOCALLY is set
167 if ((! SystemInformation
.IsPathOnBlockDevice (PathFinder
.HomeDir
) && Conf
.Daemon
.IndexSynchronization
) ||
168 Environment
.GetEnvironmentVariable ("BEAGLE_SYNCHRONIZE_LOCALLY") != null)
169 IndexSynchronization
.Initialize ();
171 // Start the query driver.
172 Logger
.Log
.Debug ("Starting QueryDriver");
173 QueryDriver
.Start ();
175 // Start the Global Scheduler thread
176 if (! arg_disable_scheduler
) {
177 Logger
.Log
.Debug ("Starting Scheduler thread");
178 Scheduler
.Global
.Start ();
181 // Start our Inotify threads
184 // Test if the FileAdvise stuff is working: This will print a
185 // warning if not. The actual advice calls will fail silently.
186 FileAdvise
.TestAdvise ();
188 #if ENABLE_WEBSERVICES
189 //Beagle Web, WebService access initialization code:
190 WebServiceBackEnd
.Start();
192 Shutdown
.ShutdownEvent
+= OnShutdown
;
194 Conf
.WatchForUpdates ();
198 Logger
.Log
.Debug ("Daemon initialization finished after {0}", stopwatch
);
200 if (arg_indexing_test_mode
) {
201 Thread
.Sleep (1000); // Ugly paranoia: wait a second for the backends to settle.
202 Logger
.Log
.Debug ("Running in indexing test mode");
203 Scheduler
.Global
.EmptyQueueEvent
+= OnEmptySchedulerQueue
;
204 Scheduler
.Global
.Add (null); // pulse the scheduler
209 static void OnEmptySchedulerQueue ()
211 Logger
.Log
.Debug ("Scheduler queue is empty: terminating immediately");
212 Shutdown
.BeginShutdown ();
213 Environment
.Exit (0); // Ugly work-around: We need to call Exit here to avoid deadlocking.
216 public static void Main (string[] args
)
220 } catch (Exception ex
) {
221 Logger
.Log
.Error ("Unhandled exception thrown. Exiting immediately.");
222 Logger
.Log
.Error (ex
);
223 Environment
.Exit (1);
227 public static void DoMain (string[] args
)
229 SystemInformation
.SetProcessName ("beagled");
231 // Process the command-line arguments
232 bool arg_debug
= false;
233 bool arg_debug_memory
= false;
237 while (i
< args
.Length
) {
239 string arg
= args
[i
];
241 string next_arg
= i
< args
.Length
? args
[i
] : null;
247 Environment
.Exit (0);
251 // Silently ignore the --heap-buddy argument: it gets handled
252 // in the wrapper script.
255 case "--list-backends":
256 Console
.WriteLine ("Current available backends:");
257 Console
.Write (QueryDriver
.ListBackends ());
258 Environment
.Exit (0);
279 case "--debug-memory":
281 arg_debug_memory
= true;
284 case "--indexing-test-mode":
285 arg_indexing_test_mode
= true;
290 if (next_arg
== null) {
291 Console
.WriteLine ("--backend requires a backend name");
292 Environment
.Exit (1);
296 if (next_arg
.StartsWith ("--")) {
297 Console
.WriteLine ("--backend requires a backend name. Invalid name '{0}'", next_arg
);
298 Environment
.Exit (1);
302 if (next_arg
[0] != '+' && next_arg
[0] != '-')
303 QueryDriver
.OnlyAllow (next_arg
);
305 if (next_arg
[0] == '+')
306 QueryDriver
.Allow (next_arg
.Substring (1));
308 QueryDriver
.Deny (next_arg
.Substring (1));
311 ++i
; // we used next_arg
314 case "--allow-backend":
315 // --allow-backend is deprecated, use --backends 'name' instead
316 // it will disable reading the list of enabled/disabled backends
317 // from conf and start the backend given
318 if (next_arg
!= null)
319 QueryDriver
.OnlyAllow (next_arg
);
320 ++i
; // we used next_arg
323 case "--deny-backend":
324 // deprecated: use --backends -'name' instead
325 if (next_arg
!= null)
326 QueryDriver
.Deny (next_arg
);
327 ++i
; // we used next_arg
330 case "--add-static-backend":
331 if (next_arg
!= null)
332 QueryDriver
.AddStaticQueryable (next_arg
);
336 case "--disable-scheduler":
337 arg_disable_scheduler
= true;
340 case "--indexing-delay":
341 if (next_arg
!= null) {
343 QueryDriver
.IndexingDelay
= Int32
.Parse (next_arg
);
345 Console
.WriteLine ("'{0}' is not a valid number of seconds", next_arg
);
346 Environment
.Exit (1);
353 case "--autostarted":
354 if (! Conf
.Searching
.Autostart
) {
355 Console
.WriteLine ("Autostarting is disabled, not starting");
356 Environment
.Exit (0);
359 #if ENABLE_WEBSERVICES
361 WebServiceBackEnd
.web_global
= true;
362 WebServiceBackEnd
.web_start
= true;
366 WebServiceBackEnd
.web_port
= next_arg
;
368 WebServiceBackEnd
.web_start
= true;
372 WebServiceBackEnd
.web_rootDir
= next_arg
;
374 WebServiceBackEnd
.web_start
= true;
377 case "--web-disable":
378 WebServiceBackEnd
.web_start
= false;
382 Console
.WriteLine ("Unknown argument '{0}'", arg
);
383 Environment
.Exit (1);
389 if (arg_indexing_test_mode
) {
390 LuceneQueryable
.OptimizeRightAway
= true;
394 // Bail out if we are trying to run as root
395 if (Environment
.UserName
== "root" && Environment
.GetEnvironmentVariable ("SUDO_USER") != null) {
396 Console
.WriteLine ("You appear to be running beagle using sudo. This can cause problems with");
397 Console
.WriteLine ("permissions in your .beagle and .wapi directories if you later try to run");
398 Console
.WriteLine ("as an unprivileged user. If you need to run beagle as root, please use");
399 Console
.WriteLine ("'su -c' instead.");
400 Environment
.Exit (-1);
403 if (Environment
.UserName
== "root" && ! Conf
.Daemon
.AllowRoot
) {
404 Console
.WriteLine ("You can not run beagle as root. Beagle is designed to run from your own");
405 Console
.WriteLine ("user account. If you want to create multiuser or system-wide indexes, use");
406 Console
.WriteLine ("the beagle-build-index tool.");
407 Console
.WriteLine ();
408 Console
.WriteLine ("You can override this setting using the beagle-config or beagle-settings tools.");
409 Environment
.Exit (-1);
413 string tmp
= PathFinder
.HomeDir
;
414 } catch (Exception e
) {
415 Console
.WriteLine ("Unable to start the daemon: {0}", e
.Message
);
416 Environment
.Exit (-1);
419 MainLoopThread
= Thread
.CurrentThread
;
421 Log
.Initialize (PathFinder
.LogDir
,
423 // FIXME: We always turn on full debugging output! We are still
424 // debugging this code, after all...
425 //arg_debug ? LogLevel.Debug : LogLevel.Warn,
429 Logger
.Log
.Info ("Starting Beagle Daemon (version {0})", ExternalStringsHack
.Version
);
431 Logger
.Log
.Info ("Running on {0}", SystemInformation
.MonoRuntimeVersion
);
433 Logger
.Log
.Debug ("Command Line: {0}",
434 Environment
.CommandLine
!= null ? Environment
.CommandLine
: "(null)");
436 if (! ExtendedAttribute
.Supported
) {
437 Logger
.Log
.Warn ("Extended attributes are not supported on this filesystem. " +
438 "Performance will suffer as a result.");
441 // Start our memory-logging thread
442 if (arg_debug_memory
)
443 ExceptionHandlingThread
.Start (new ThreadStart (LogMemoryUsage
));
445 // Do BEAGLE_EXERCISE_THE_DOG_HARDER-related processing.
446 ExerciseTheDogHarder ();
448 if (Application
.InitCheck ("beagled", ref args
))
449 Logger
.Log
.Debug ("Established a connection to the X server");
451 Logger
.Log
.Debug ("Unable to establish a connection to the X server");
453 XSetIOErrorHandler (BeagleXIOErrorHandler
);
455 // Defer all actual startup until the main loop is
456 // running. That way shutdowns during the startup
457 // process work correctly.
458 GLib
.Idle
.Add (new GLib
.IdleHandler (StartupProcess
));
460 // Start our event loop.
461 Logger
.Log
.Debug ("Starting main loop");
465 // If we placed our sockets in a temp directory, try to clean it up
466 // Note: this may fail because the helper is still running
467 if (PathFinder
.GetRemoteStorageDir (false) != PathFinder
.StorageDir
) {
469 Directory
.Delete (PathFinder
.GetRemoteStorageDir (false));
470 } catch (IOException
) { }
473 Logger
.Log
.Debug ("Leaving BeagleDaemon.Main");
477 ExceptionHandlingThread
.SpewLiveThreads ();
481 /////////////////////////////////////////////////////////////////////////////
483 private delegate int XIOErrorHandler (IntPtr display
);
485 [DllImport ("libX11.so.6")]
486 extern static private int XSetIOErrorHandler (XIOErrorHandler handler
);
488 private static int BeagleXIOErrorHandler (IntPtr display
)
490 Logger
.Log
.Debug ("Lost our connection to the X server! Trying to shut down gracefully");
492 if (! Shutdown
.ShutdownRequested
)
493 Shutdown
.BeginShutdown ();
495 Logger
.Log
.Debug ("Xlib is forcing us to exit!");
497 ExceptionHandlingThread
.SpewLiveThreads ();
499 // Returning will cause xlib to exit immediately.
503 /////////////////////////////////////////////////////////////////////////////
505 static void SetupSignalHandlers ()
507 // Force OurSignalHandler to be JITed
508 OurSignalHandler (-1);
510 // Set up our signal handler
511 Mono
.Unix
.Native
.Stdlib
.signal (Mono
.Unix
.Native
.Signum
.SIGINT
, OurSignalHandler
);
512 Mono
.Unix
.Native
.Stdlib
.signal (Mono
.Unix
.Native
.Signum
.SIGTERM
, OurSignalHandler
);
515 Mono
.Unix
.Native
.Stdlib
.signal (Mono
.Unix
.Native
.Signum
.SIGPIPE
, Mono
.Unix
.Native
.Stdlib
.SIG_IGN
);
518 // Our handler triggers an orderly shutdown when it receives a signal.
519 // However, this can be annoying if the process gets wedged during
520 // shutdown. To deal with that case, we make a note of the time when
521 // the first signal comes in, and we allow signals to unconditionally
522 // kill the process after 5 seconds have passed.
523 static DateTime signal_time
= DateTime
.MinValue
;
524 static void OurSignalHandler (int signal
)
526 // This allows us to call OurSignalHandler w/o doing anything.
527 // We want to call it once to ensure that it is pre-JITed.
531 Logger
.Log
.Debug ("Handling signal {0} ({1})", signal
, (Mono
.Unix
.Native
.Signum
) signal
);
533 bool first_signal
= false;
534 if (signal_time
== DateTime
.MinValue
) {
535 signal_time
= DateTime
.Now
;
539 if (Shutdown
.ShutdownRequested
) {
542 Logger
.Log
.Debug ("Shutdown already in progress.");
544 double t
= (DateTime
.Now
- signal_time
).TotalSeconds
;
545 const double min_t
= 5;
548 Logger
.Log
.Debug ("Signals can force an immediate shutdown in {0:0.00}s", min_t
-t
);
550 Logger
.Log
.Debug ("Forcing immediate shutdown.");
551 Environment
.Exit (0);
556 Logger
.Log
.Debug ("Initiating shutdown in response to signal.");
557 Shutdown
.BeginShutdown ();
561 /////////////////////////////////////////////////////////////////////////////
563 private static void OnShutdown ()
565 #if ENABLE_WEBSERVICES
566 WebServiceBackEnd
.Stop();
568 // Stop our Inotify threads
571 // Shut down the global scheduler
572 Scheduler
.Global
.Stop ();
574 // Stop the messaging server
578 /////////////////////////////////////////////////////////////////////////////
581 private static ArrayList exercise_files
= new ArrayList ();
583 private static void ExerciseTheDogHarder ()
586 path
= Environment
.GetEnvironmentVariable ("BEAGLE_EXERCISE_THE_DOG_HARDER");
590 DirectoryInfo dir
= new DirectoryInfo (path
);
591 foreach (FileInfo file
in dir
.GetFiles ())
592 exercise_files
.Add (file
);
593 if (exercise_files
.Count
== 0)
597 if (N
> exercise_files
.Count
)
598 N
= exercise_files
.Count
;
600 for (int i
= 0; i
< N
; ++i
)
601 ExceptionHandlingThread
.Start (new ThreadStart (ExerciseTheDogHarderWorker
));
604 private static void ExerciseTheDogHarderWorker ()
606 Random rng
= new Random ();
608 while (! Shutdown
.ShutdownRequested
) {
610 FileInfo file
= null;
614 lock (exercise_files
) {
616 i
= rng
.Next (exercise_files
.Count
);
617 file
= exercise_files
[i
] as FileInfo
;
618 } while (file
== null);
619 exercise_files
[i
] = null;
623 target
= Path
.Combine (PathFinder
.HomeDir
, "_HARDER_" + file
.Name
);
625 Logger
.Log
.Debug ("ETDH: Copying {0}", file
.Name
);
626 file
.CopyTo (target
, true);
628 lock (exercise_files
)
629 exercise_files
[i
] = file
;
631 Thread
.Sleep (500 + rng
.Next (500));