4 // Copyright (C) 2004 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.
29 using System
.Collections
;
30 using System
.Reflection
;
32 using System
.Threading
;
34 namespace Beagle
.Daemon
{
36 public class QueryDriver
{
38 // Contains list of queryables explicitly asked by --allow-backend or --backend name
39 // --allow-backend/--backend name : dont read config information and only start backend 'name'
40 static ArrayList excl_allowed_queryables
= new ArrayList ();
42 // Contains list of denied queryables from config/arguments (every queryable is enabled by default)
43 // Unless overruled by --allow-backend/--backend name, deny backend only if names appears here.
44 static ArrayList denied_queryables
= new ArrayList ();
46 static bool to_read_conf
= true; // read backends from conf if true
47 static bool done_reading_conf
= false;
49 static private void ReadBackendsFromConf ()
51 if (! to_read_conf
|| done_reading_conf
)
54 // set flag here to stop Allow() from calling ReadBackendsFromConf() again
55 done_reading_conf
= true;
57 // To allow static indexes, "static" should be in allowed_queryables
58 if (Conf
.Daemon
.AllowStaticBackend
)
61 if (Conf
.Daemon
.DeniedBackends
== null)
64 foreach (string name
in Conf
.Daemon
.DeniedBackends
)
65 denied_queryables
.Add (name
.ToLower ());
68 static public void OnlyAllow (string name
)
70 excl_allowed_queryables
.Add (name
.ToLower ());
74 static public void Allow (string name
)
76 if (! done_reading_conf
&& to_read_conf
)
77 ReadBackendsFromConf ();
79 denied_queryables
.Remove (name
.ToLower ());
82 static public void Deny (string name
)
84 if (! done_reading_conf
&& to_read_conf
)
85 ReadBackendsFromConf ();
87 name
= name
.ToLower ();
88 if (!denied_queryables
.Contains (name
))
89 denied_queryables
.Add (name
);
92 static private bool UseQueryable (string name
)
94 name
= name
.ToLower ();
96 if (excl_allowed_queryables
.Contains (name
))
98 if (excl_allowed_queryables
.Count
!= 0)
101 if (denied_queryables
.Contains (name
))
107 //////////////////////////////////////////////////////////////////////////////////////
109 // Paths to static queryables
111 static ArrayList static_queryables
= new ArrayList ();
113 static public void AddStaticQueryable (string path
) {
115 if (! static_queryables
.Contains (path
))
116 static_queryables
.Add (path
);
119 //////////////////////////////////////////////////////////////////////////////////////
121 // Delay before starting the indexing process
123 static int indexing_delay
= 60; // Default to 60 seconds
125 public static int IndexingDelay
{
126 set { indexing_delay = value; }
129 //////////////////////////////////////////////////////////////////////////////////////
131 // Use introspection to find all classes that implement IQueryable, the construct
132 // associated Queryables objects.
134 static ArrayList queryables
= new ArrayList ();
135 static Hashtable iqueryable_to_queryable
= new Hashtable ();
137 static bool ThisApiSoVeryIsBroken (Type m
, object criteria
)
139 return m
== (Type
) criteria
;
142 static bool TypeImplementsInterface (Type t
, Type iface
)
144 Type
[] impls
= t
.FindInterfaces (new TypeFilter (ThisApiSoVeryIsBroken
),
146 return impls
.Length
> 0;
149 // For every type in the assembly that
150 // (1) implements IQueryable
151 // (2) Has a QueryableFlavor attribute attached
152 // assemble a Queryable object and stick it into our list of queryables.
153 static void ScanAssembly (Assembly assembly
)
157 foreach (Type type
in ReflectionFu
.ScanAssemblyForInterface (assembly
, typeof (IQueryable
))) {
158 bool type_accepted
= false;
159 foreach (QueryableFlavor flavor
in ReflectionFu
.ScanTypeForAttribute (type
, typeof (QueryableFlavor
))) {
160 if (! UseQueryable (flavor
.Name
))
163 if (flavor
.RequireInotify
&& ! Inotify
.Enabled
) {
164 Logger
.Log
.Warn ("Can't start backend '{0}' without inotify", flavor
.Name
);
168 if (flavor
.RequireExtendedAttributes
&& ! ExtendedAttribute
.Supported
) {
169 Logger
.Log
.Warn ("Can't start backend '{0}' without extended attributes", flavor
.Name
);
173 IQueryable iq
= null;
175 iq
= Activator
.CreateInstance (type
) as IQueryable
;
176 } catch (Exception e
) {
177 Logger
.Log
.Error (e
, "Caught exception while instantiating {0} backend", flavor
.Name
);
181 Queryable q
= new Queryable (flavor
, iq
);
183 iqueryable_to_queryable
[iq
] = q
;
185 type_accepted
= true;
193 object[] attributes
= type
.GetCustomAttributes (false);
194 foreach (object attribute
in attributes
) {
195 PropertyKeywordMapping mapping
= attribute
as PropertyKeywordMapping
;
198 //Logger.Log.Debug (mapping.Keyword + " => "
199 // + mapping.PropertyName +
200 // + " is-keyword=" + mapping.IsKeyword + " ("
201 // + mapping.Description + ") "
202 // + "(" + type.FullName + ")");
203 PropertyKeywordFu
.RegisterMapping (mapping
);
207 Logger
.Log
.Debug ("Found {0} backends in {1}", count
, assembly
.Location
);
210 ////////////////////////////////////////////////////////
212 public static void ReadKeywordMappings ()
214 Logger
.Log
.Debug ("Reading mapping from filters");
215 ArrayList assemblies
= ReflectionFu
.ScanEnvironmentForAssemblies ("BEAGLE_FILTER_PATH", PathFinder
.FilterDir
);
217 foreach (Assembly assembly
in assemblies
) {
218 foreach (Type type
in assembly
.GetTypes ())
219 if (type
.FullName
.StartsWith ("Beagle.Filters")) {
221 if (type
.IsNestedPrivate
||
222 type
.IsNestedPublic
||
223 type
.IsNestedAssembly
||
227 object[] attributes
= type
.GetCustomAttributes (false);
228 foreach (object attribute
in attributes
) {
230 PropertyKeywordMapping mapping
= attribute
as PropertyKeywordMapping
;
233 //Logger.Log.Debug (mapping.Keyword + " => "
234 // + mapping.PropertyName
235 // + " is-keyword=" + mapping.IsKeyword + " ("
236 // + mapping.Description + ") "
237 // + "(" + type.FullName + ")");
238 PropertyKeywordFu
.RegisterMapping (mapping
);
244 ////////////////////////////////////////////////////////
246 // Scans PathFinder.SystemIndexesDir after available
247 // system-wide indexes.
248 static void LoadSystemIndexes ()
250 if (!Directory
.Exists (PathFinder
.SystemIndexesDir
))
253 Logger
.Log
.Info ("Loading system static indexes.");
257 foreach (DirectoryInfo index_dir
in new DirectoryInfo (PathFinder
.SystemIndexesDir
).GetDirectories ()) {
258 if (! UseQueryable (index_dir
.Name
))
261 if (LoadStaticQueryable (index_dir
, QueryDomain
.System
))
265 Logger
.Log
.Info ("Found {0} system-wide indexes.", count
);
268 // Scans configuration for user-specified index paths
269 // to load StaticQueryables from.
270 static void LoadStaticQueryables ()
274 if (UseQueryable ("static")) {
275 Logger
.Log
.Info ("Loading user-configured static indexes.");
276 foreach (string path
in Conf
.Daemon
.StaticQueryables
)
277 static_queryables
.Add (path
);
280 foreach (string path
in static_queryables
) {
281 DirectoryInfo index_dir
= new DirectoryInfo (StringFu
.SanitizePath (path
));
283 if (!index_dir
.Exists
)
286 // FIXME: QueryDomain might be other than local
287 if (LoadStaticQueryable (index_dir
, QueryDomain
.Local
))
291 Logger
.Log
.Info ("Found {0} user-configured static indexes..", count
);
294 // Instantiates and loads a StaticQueryable from an index directory
295 static private bool LoadStaticQueryable (DirectoryInfo index_dir
, QueryDomain query_domain
)
297 StaticQueryable static_queryable
= null;
299 if (!index_dir
.Exists
)
303 static_queryable
= new StaticQueryable (index_dir
.Name
, index_dir
.FullName
, true);
304 } catch (InvalidOperationException
) {
305 Logger
.Log
.Warn ("Unable to create read-only index (likely due to index version mismatch): {0}", index_dir
.FullName
);
307 } catch (Exception e
) {
308 Logger
.Log
.Error (e
, "Caught exception while instantiating static queryable: {0}", index_dir
.Name
);
312 if (static_queryable
!= null) {
313 QueryableFlavor flavor
= new QueryableFlavor ();
314 flavor
.Name
= index_dir
.Name
;
315 flavor
.Domain
= query_domain
;
317 Queryable queryable
= new Queryable (flavor
, static_queryable
);
318 queryables
.Add (queryable
);
320 iqueryable_to_queryable
[static_queryable
] = queryable
;
328 ////////////////////////////////////////////////////////
330 private static ArrayList assemblies
= null;
332 // Perform expensive initialization steps all at once.
333 // Should be done before SignalHandler comes into play.
334 static public void Init ()
336 ReadBackendsFromConf ();
337 assemblies
= ReflectionFu
.ScanEnvironmentForAssemblies ("BEAGLE_BACKEND_PATH", PathFinder
.BackendDir
);
340 static public void Start ()
342 // Only add the executing assembly if we haven't already loaded it.
343 if (assemblies
.IndexOf (Assembly
.GetExecutingAssembly ()) == -1)
344 assemblies
.Add (Assembly
.GetExecutingAssembly ());
346 foreach (Assembly assembly
in assemblies
) {
347 ScanAssembly (assembly
);
349 // This allows backends to define their
351 Server
.ScanAssemblyForExecutors (assembly
);
354 ReadKeywordMappings ();
356 LoadSystemIndexes ();
357 LoadStaticQueryables ();
359 if (indexing_delay
<= 0 || Environment
.GetEnvironmentVariable ("BEAGLE_EXERCISE_THE_DOG") != null)
362 Logger
.Log
.Debug ("Waiting {0} seconds before starting queryables", indexing_delay
);
363 GLib
.Timeout
.Add ((uint) indexing_delay
* 1000, new GLib
.TimeoutHandler (StartQueryables
));
367 static private bool StartQueryables ()
369 Logger
.Log
.Debug ("Starting queryables");
371 foreach (Queryable q
in queryables
) {
372 Logger
.Log
.Info ("Starting backend: '{0}'", q
.Name
);
379 static public string ListBackends ()
381 ArrayList assemblies
= ReflectionFu
.ScanEnvironmentForAssemblies ("BEAGLE_BACKEND_PATH", PathFinder
.BackendDir
);
383 // Only add the executing assembly if we haven't already loaded it.
384 if (assemblies
.IndexOf (Assembly
.GetExecutingAssembly ()) == -1)
385 assemblies
.Add (Assembly
.GetExecutingAssembly ());
387 string ret
= "User:\n";
389 foreach (Assembly assembly
in assemblies
) {
390 foreach (Type type
in ReflectionFu
.ScanAssemblyForInterface (assembly
, typeof (IQueryable
))) {
391 foreach (QueryableFlavor flavor
in ReflectionFu
.ScanTypeForAttribute (type
, typeof (QueryableFlavor
)))
392 ret
+= String
.Format (" - {0}\n", flavor
.Name
);
396 if (!Directory
.Exists (PathFinder
.SystemIndexesDir
))
400 foreach (DirectoryInfo index_dir
in new DirectoryInfo (PathFinder
.SystemIndexesDir
).GetDirectories ()) {
401 ret
+= String
.Format (" - {0}\n", index_dir
.Name
);
407 static public Queryable
GetQueryable (string name
)
409 foreach (Queryable q
in queryables
) {
417 static public Queryable
GetQueryable (IQueryable iqueryable
)
419 return (Queryable
) iqueryable_to_queryable
[iqueryable
];
422 ////////////////////////////////////////////////////////
424 public delegate void ChangedHandler (Queryable queryable
,
425 IQueryableChangeData changeData
);
427 static public event ChangedHandler ChangedEvent
;
429 // A method to fire the ChangedEvent event.
430 static public void QueryableChanged (IQueryable iqueryable
,
431 IQueryableChangeData change_data
)
433 if (ChangedEvent
!= null) {
434 Queryable queryable
= iqueryable_to_queryable
[iqueryable
] as Queryable
;
435 ChangedEvent (queryable
, change_data
);
439 ////////////////////////////////////////////////////////
441 private class QueryClosure
: IQueryWorker
{
446 IQueryableChangeData change_data
;
448 public QueryClosure (Queryable queryable
,
451 IQueryableChangeData change_data
)
453 this.queryable
= queryable
;
455 this.result
= result
;
456 this.change_data
= change_data
;
459 public void DoWork ()
461 queryable
.DoQuery (query
, result
, change_data
);
465 static public void DoOneQuery (Queryable queryable
,
468 IQueryableChangeData change_data
)
470 if (queryable
.AcceptQuery (query
)) {
471 QueryClosure qc
= new QueryClosure (queryable
, query
, result
, change_data
);
472 result
.AttachWorker (qc
);
476 static void AddSearchTermInfo (QueryPart part
,
477 SearchTermResponse response
, StringBuilder sb
)
479 if (part
.Logic
== QueryPartLogic
.Prohibited
)
482 if (part
is QueryPart_Or
) {
483 ICollection sub_parts
;
484 sub_parts
= ((QueryPart_Or
) part
).SubParts
;
485 foreach (QueryPart qp
in sub_parts
)
486 AddSearchTermInfo (qp
, response
, sb
);
490 if (! (part
is QueryPart_Text
))
494 tp
= (QueryPart_Text
) part
;
497 split
= tp
.Text
.Split (' ');
499 // First, remove stop words
500 for (int i
= 0; i
< split
.Length
; ++i
)
501 if (LuceneCommon
.IsStopWord (split
[i
]))
504 // Assemble the phrase minus stop words
506 for (int i
= 0; i
< split
.Length
; ++i
) {
507 if (split
[i
] == null)
511 sb
.Append (split
[i
]);
513 response
.ExactText
.Add (sb
.ToString ());
515 // Now assemble a stemmed version
516 sb
.Length
= 0; // clear the previous value
517 for (int i
= 0; i
< split
.Length
; ++i
) {
518 if (split
[i
] == null)
522 sb
.Append (LuceneCommon
.Stem (split
[i
]));
524 response
.StemmedText
.Add (sb
.ToString ());
527 ////////////////////////////////////////////////////////
529 static private void DehumanizeQuery (Query query
)
531 // We need to remap any QueryPart_Human parts into
532 // lower-level part types. First, we find any
533 // QueryPart_Human parts and explode them into
534 // lower-level types.
535 ArrayList new_parts
= null;
536 foreach (QueryPart abstract_part
in query
.Parts
) {
537 if (abstract_part
is QueryPart_Human
) {
538 QueryPart_Human human
= abstract_part
as QueryPart_Human
;
539 if (new_parts
== null)
540 new_parts
= new ArrayList ();
541 foreach (QueryPart sub_part
in QueryStringParser
.Parse (human
.QueryString
))
542 new_parts
.Add (sub_part
);
546 // If we found any QueryPart_Human parts, copy the
547 // non-Human parts over and then replace the parts in
549 if (new_parts
!= null) {
550 foreach (QueryPart abstract_part
in query
.Parts
) {
551 if (! (abstract_part
is QueryPart_Human
))
552 new_parts
.Add (abstract_part
);
556 foreach (QueryPart part
in new_parts
)
557 query
.AddPart (part
);
562 static private SearchTermResponse
AssembleSearchTermResponse (Query query
)
564 StringBuilder sb
= new StringBuilder ();
565 SearchTermResponse search_term_response
;
566 search_term_response
= new SearchTermResponse ();
567 foreach (QueryPart part
in query
.Parts
)
568 AddSearchTermInfo (part
, search_term_response
, sb
);
569 return search_term_response
;
572 static private void QueryEachQueryable (Query query
,
575 // The extra pair of calls to WorkerStart/WorkerFinished ensures:
576 // (1) that the QueryResult will fire the StartedEvent
577 // and FinishedEvent, even if no queryable accepts the
579 // (2) that the FinishedEvent will only get called when all of the
580 // backends have had time to finish.
582 object dummy_worker
= new object ();
584 if (! result
.WorkerStart (dummy_worker
))
587 foreach (Queryable queryable
in queryables
)
588 DoOneQuery (queryable
, query
, result
, null);
590 result
.WorkerFinished (dummy_worker
);
593 static public void DoQueryLocal (Query query
,
596 DehumanizeQuery (query
);
598 SearchTermResponse search_term_response
;
599 search_term_response
= AssembleSearchTermResponse (query
);
600 query
.ProcessSearchTermResponse (search_term_response
);
602 QueryEachQueryable (query
, result
);
605 static public void DoQuery (Query query
,
607 RequestMessageExecutor
.AsyncResponse send_response
)
609 DehumanizeQuery (query
);
611 SearchTermResponse search_term_response
;
612 search_term_response
= AssembleSearchTermResponse (query
);
613 send_response (search_term_response
);
615 QueryEachQueryable (query
, result
);
618 ////////////////////////////////////////////////////////
620 static public IEnumerable
GetIndexInformation ()
622 foreach (Queryable q
in queryables
)
623 yield return q
.GetQueryableStatus ();
626 ////////////////////////////////////////////////////////
628 static public bool IsIndexing
{
630 foreach (Queryable q
in queryables
) {
631 QueryableStatus status
= q
.GetQueryableStatus ();
633 if (status
.IsIndexing
)