More removal of $Id$ tags
[citadel.git] / citadel / modules / fulltext / serv_fulltext.c
1 /*
2  * This module handles fulltext indexing of the message base.
3  * Copyright (c) 2005-2009 by the citadel.org team
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 3 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <pwd.h>
28 #include <errno.h>
29 #include <sys/types.h>
30
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
33 # include <time.h>
34 #else
35 # if HAVE_SYS_TIME_H
36 #  include <sys/time.h>
37 # else
38 #  include <time.h>
39 # endif
40 #endif
41
42 #include <sys/wait.h>
43 #include <string.h>
44 #include <limits.h>
45 #include <libcitadel.h>
46 #include "citadel.h"
47 #include "server.h"
48 #include "citserver.h"
49 #include "support.h"
50 #include "config.h"
51 #include "database.h"
52 #include "msgbase.h"
53 #include "control.h"
54 #include "serv_fulltext.h"
55 #include "ft_wordbreaker.h"
56 #include "threads.h"
57 #include "context.h"
58
59 #include "ctdl_module.h"
60
61
62
63 long ft_newhighest = 0L;
64 long *ft_newmsgs = NULL;
65 int ft_num_msgs = 0;
66 int ft_num_alloc = 0;
67
68
69 int ftc_num_msgs[65536];
70 long *ftc_msgs[65536];
71
72
73 /*
74  * Compare function
75  */
76 int longcmp(const void *rec1, const void *rec2) {
77         long i1, i2;
78
79         i1 = *(const long *)rec1;
80         i2 = *(const long *)rec2;
81
82         if (i1 > i2) return(1);
83         if (i1 < i2) return(-1);
84         return(0);
85 }
86
87 /*
88  * Flush our index cache out to disk.
89  */
90 void ft_flush_cache(void) {
91         int i;
92         time_t last_update = 0;
93
94         for (i=0; i<65536; ++i) {
95                 if ((time(NULL) - last_update) >= 10) {
96                         CtdlLogPrintf(CTDL_INFO,
97                                 "Flushing index cache to disk (%d%% complete)\n",
98                                 (i * 100 / 65536)
99                         );
100                         last_update = time(NULL);
101                 }
102                 if (ftc_msgs[i] != NULL) {
103                         cdb_store(CDB_FULLTEXT, &i, sizeof(int), ftc_msgs[i],
104                                 (ftc_num_msgs[i] * sizeof(long)));
105                         ftc_num_msgs[i] = 0;
106                         free(ftc_msgs[i]);
107                         ftc_msgs[i] = NULL;
108                 }
109         }
110         CtdlLogPrintf(CTDL_INFO, "Flushed index cache to disk (100%% complete)\n");
111 }
112
113
114 /*
115  * Index or de-index a message.  (op == 1 to index, 0 to de-index)
116  */
117 void ft_index_message(long msgnum, int op) {
118         int num_tokens = 0;
119         int *tokens = NULL;
120         int i, j;
121         struct cdbdata *cdb_bucket;
122         StrBuf *msgtext;
123         char *txt;
124         int tok;
125         struct CtdlMessage *msg = NULL;
126
127         msg = CtdlFetchMessage(msgnum, 1);
128         if (msg == NULL) {
129                 CtdlLogPrintf(CTDL_ERR, "ft_index_message() could not load msg %ld\n", msgnum);
130                 return;
131         }
132
133         if (msg->cm_fields['1'] != NULL) {
134                 CtdlLogPrintf(CTDL_DEBUG, "ft_index_message() excluded msg %ld\n", msgnum);
135                 CtdlFreeMessage(msg);
136                 return;
137         }
138
139         CtdlLogPrintf(CTDL_DEBUG, "ft_index_message() %s msg %ld\n",
140                 (op ? "adding" : "removing") , msgnum
141         );
142
143         /* Output the message as text before indexing it, so we don't end up
144          * indexing a bunch of encoded base64, etc.
145          */
146         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
147         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_ALL, 0, 1, 0);
148         CtdlFreeMessage(msg);
149         msgtext = CC->redirect_buffer;
150         CC->redirect_buffer = NULL;
151         CtdlLogPrintf(CTDL_DEBUG, "Wordbreaking message %ld...\n", msgnum);
152         txt = SmashStrBuf(&msgtext);
153         wordbreaker(txt, &num_tokens, &tokens);
154         free(txt);
155
156         CtdlLogPrintf(CTDL_DEBUG, "Indexing message %ld [%d tokens]\n", msgnum, num_tokens);
157         if (num_tokens > 0) {
158                 for (i=0; i<num_tokens; ++i) {
159
160                         /* Add the message to the relevant token bucket */
161
162                         /* search for tokens[i] */
163                         tok = tokens[i];
164
165                         if ( (tok >= 0) && (tok <= 65535) ) {
166                                 /* fetch the bucket, Liza */
167                                 if (ftc_msgs[tok] == NULL) {
168                                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
169                                         if (cdb_bucket != NULL) {
170                                                 ftc_num_msgs[tok] = cdb_bucket->len / sizeof(long);
171                                                 ftc_msgs[tok] = (long *)cdb_bucket->ptr;
172                                                 cdb_bucket->ptr = NULL;
173                                                 cdb_free(cdb_bucket);
174                                         }
175                                         else {
176                                                 ftc_num_msgs[tok] = 0;
177                                                 ftc_msgs[tok] = malloc(sizeof(long));
178                                         }
179                                 }
180         
181         
182                                 if (op == 1) {  /* add to index */
183                                         ++ftc_num_msgs[tok];
184                                         ftc_msgs[tok] = realloc(ftc_msgs[tok],
185                                                                 ftc_num_msgs[tok]*sizeof(long));
186                                         ftc_msgs[tok][ftc_num_msgs[tok] - 1] = msgnum;
187                                 }
188         
189                                 if (op == 0) {  /* remove from index */
190                                         if (ftc_num_msgs[tok] >= 1) {
191                                                 for (j=0; j<ftc_num_msgs[tok]; ++j) {
192                                                         if (ftc_msgs[tok][j] == msgnum) {
193                                                                 memmove(&ftc_msgs[tok][j], &ftc_msgs[tok][j+1], ((ftc_num_msgs[tok] - j - 1)*sizeof(long)));
194                                                                 --ftc_num_msgs[tok];
195                                                                 --j;
196                                                         }
197                                                 }
198                                         }
199                                 }
200                         }
201                         else {
202                                 CtdlLogPrintf(CTDL_ALERT, "Invalid token %d !!\n", tok);
203                         }
204                 }
205
206                 free(tokens);
207         }
208 }
209
210
211
212 /*
213  * Add a message to the list of those to be indexed.
214  */
215 void ft_index_msg(long msgnum, void *userdata) {
216
217         if ((msgnum > CitControl.MMfulltext) && (msgnum <= ft_newhighest)) {
218                 ++ft_num_msgs;
219                 if (ft_num_msgs > ft_num_alloc) {
220                         ft_num_alloc += 1024;
221                         ft_newmsgs = realloc(ft_newmsgs,
222                                 (ft_num_alloc * sizeof(long)));
223                 }
224                 ft_newmsgs[ft_num_msgs - 1] = msgnum;
225         }
226
227 }
228
229 /*
230  * Scan a room for messages to index.
231  */
232 void ft_index_room(struct ctdlroom *qrbuf, void *data)
233 {
234         if (CtdlThreadCheckStop())
235                 return;
236                 
237         CtdlGetRoom(&CC->room, qrbuf->QRname);
238         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, ft_index_msg, NULL);
239 }
240
241
242 /*
243  * Begin the fulltext indexing process.
244  */
245 void do_fulltext_indexing(void) {
246         int i;
247         static time_t last_index = 0L;
248         static time_t last_progress = 0L;
249         time_t run_time = 0L;
250         time_t end_time = 0L;
251         
252         /*
253          * Don't do this if the site doesn't have it enabled.
254          */
255         if (!config.c_enable_fulltext) {
256                 return;
257         }
258
259         /*
260          * Make sure we don't run the indexer too frequently.
261          * FIXME move the setting into config
262          */
263 /*
264  * The thread sleeps for 300 seconds so we don't need this here any more
265  
266         if ( (time(NULL) - last_index) < 300L) {
267                 return;
268         }
269 */
270
271         /*
272          * Check to see whether the fulltext index is up to date; if there
273          * are no messages to index, don't waste any more time trying.
274          */
275         if ((CitControl.MMfulltext >= CitControl.MMhighest) && (CitControl.fulltext_wordbreaker == FT_WORDBREAKER_ID)) {
276                 return;         /* nothing to do! */
277         }
278         
279         run_time = time(NULL);
280         CtdlLogPrintf(CTDL_DEBUG, "do_fulltext_indexing() started (%ld)\n", run_time);
281         
282         /*
283          * If we've switched wordbreaker modules, burn the index and start
284          * over.
285          */
286         begin_critical_section(S_CONTROL);
287         if (CitControl.fulltext_wordbreaker != FT_WORDBREAKER_ID) {
288                 CtdlLogPrintf(CTDL_DEBUG, "wb ver on disk = %d, code ver = %d\n",
289                         CitControl.fulltext_wordbreaker, FT_WORDBREAKER_ID);
290                 CtdlLogPrintf(CTDL_INFO, "(re)initializing full text index\n");
291                 cdb_trunc(CDB_FULLTEXT);
292                 CitControl.MMfulltext = 0L;
293                 put_control();
294         }
295         end_critical_section(S_CONTROL);
296
297         /*
298          * Now go through each room and find messages to index.
299          */
300         ft_newhighest = CitControl.MMhighest;
301         CtdlForEachRoom(ft_index_room, NULL);   /* load all msg pointers */
302
303         if (ft_num_msgs > 0) {
304                 qsort(ft_newmsgs, ft_num_msgs, sizeof(long), longcmp);
305                 for (i=0; i<(ft_num_msgs-1); ++i) { /* purge dups */
306                         if (ft_newmsgs[i] == ft_newmsgs[i+1]) {
307                                 memmove(&ft_newmsgs[i], &ft_newmsgs[i+1],
308                                         ((ft_num_msgs - i - 1)*sizeof(long)));
309                                 --ft_num_msgs;
310                                 --i;
311                         }
312                 }
313
314                 /* Here it is ... do each message! */
315                 for (i=0; i<ft_num_msgs; ++i) {
316                         if (time(NULL) != last_progress) {
317                                 CtdlLogPrintf(CTDL_DEBUG,
318                                         "Indexed %d of %d messages (%d%%)\n",
319                                                 i, ft_num_msgs,
320                                                 ((i*100) / ft_num_msgs)
321                                 );
322                                 last_progress = time(NULL);
323                         }
324                         ft_index_message(ft_newmsgs[i], 1);
325
326                         /* Check to see if we need to quit early */
327                         if (CtdlThreadCheckStop()) {
328                                 CtdlLogPrintf(CTDL_DEBUG, "Indexer quitting early\n");
329                                 ft_newhighest = ft_newmsgs[i];
330                                 break;
331                         }
332
333                         /* Check to see if we have to maybe flush to disk */
334                         if (i >= FT_MAX_CACHE) {
335                                 CtdlLogPrintf(CTDL_DEBUG, "Time to flush.\n");
336                                 ft_newhighest = ft_newmsgs[i];
337                                 break;
338                         }
339
340                 }
341
342                 free(ft_newmsgs);
343                 ft_num_msgs = 0;
344                 ft_num_alloc = 0;
345                 ft_newmsgs = NULL;
346         }
347         end_time = time(NULL);
348
349         if (CtdlThreadCheckStop())
350                 return;
351         
352         CtdlLogPrintf(CTDL_DEBUG, "do_fulltext_indexing() duration (%ld)\n", end_time - run_time);
353                 
354         /* Save our place so we don't have to do this again */
355         ft_flush_cache();
356         begin_critical_section(S_CONTROL);
357         CitControl.MMfulltext = ft_newhighest;
358         CitControl.fulltext_wordbreaker = FT_WORDBREAKER_ID;
359         put_control();
360         end_critical_section(S_CONTROL);
361         last_index = time(NULL);
362
363         CtdlLogPrintf(CTDL_DEBUG, "do_fulltext_indexing() finished\n");
364         return;
365 }
366
367 /*
368  * Main loop for the indexer thread.
369  */
370 void *indexer_thread(void *arg) {
371         struct CitContext indexerCC;
372
373
374         CtdlFillSystemContext(&indexerCC, "indexer");
375         citthread_setspecific(MyConKey, (void *)&indexerCC );
376         CtdlLogPrintf(CTDL_DEBUG, "indexer_thread() initializing\n");
377
378         while (!CtdlThreadCheckStop()) {
379                 do_fulltext_indexing();
380                 CtdlThreadSleep(300);
381         }
382
383         CtdlLogPrintf(CTDL_DEBUG, "indexer_thread() exiting\n");
384         CtdlClearSystemContext();
385         return NULL;
386 }
387
388
389
390 /*
391  * API call to perform searches.
392  * (This one does the "all of these words" search.)
393  * Caller is responsible for freeing the message list.
394  */
395 void ft_search(int *fts_num_msgs, long **fts_msgs, const char *search_string) {
396         int num_tokens = 0;
397         int *tokens = NULL;
398         int i, j;
399         struct cdbdata *cdb_bucket;
400         int num_all_msgs = 0;
401         long *all_msgs = NULL;
402         int num_ret_msgs = 0;
403         int num_ret_alloc = 0;
404         long *ret_msgs = NULL;
405         int tok;
406
407         wordbreaker(search_string, &num_tokens, &tokens);
408         if (num_tokens > 0) {
409                 for (i=0; i<num_tokens; ++i) {
410
411                         /* search for tokens[i] */
412                         tok = tokens[i];
413
414                         /* fetch the bucket, Liza */
415                         if (ftc_msgs[tok] == NULL) {
416                                 cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
417                                 if (cdb_bucket != NULL) {
418                                         ftc_num_msgs[tok] = cdb_bucket->len / sizeof(long);
419                                         ftc_msgs[tok] = (long *)cdb_bucket->ptr;
420                                         cdb_bucket->ptr = NULL;
421                                         cdb_free(cdb_bucket);
422                                 }
423                                 else {
424                                         ftc_num_msgs[tok] = 0;
425                                         ftc_msgs[tok] = malloc(sizeof(long));
426                                 }
427                         }
428
429                         num_all_msgs += ftc_num_msgs[tok];
430                         if (num_all_msgs > 0) {
431                                 all_msgs = realloc(all_msgs, num_all_msgs*sizeof(long) );
432                                 memcpy(&all_msgs[num_all_msgs-ftc_num_msgs[tok]],
433                                         ftc_msgs[tok], ftc_num_msgs[tok]*sizeof(long) );
434                         }
435
436                 }
437                 free(tokens);
438                 qsort(all_msgs, num_all_msgs, sizeof(long), longcmp);
439
440                 /*
441                  * At this point, if a message appears num_tokens times in the
442                  * list, then it contains all of the search tokens.
443                  */
444                 if (num_all_msgs >= num_tokens)
445                    for (j=0; j<(num_all_msgs-num_tokens+1); ++j) {
446                         if (all_msgs[j] == all_msgs[j+num_tokens-1]) {
447
448                                 ++num_ret_msgs;
449                                 if (num_ret_msgs > num_ret_alloc) {
450                                         num_ret_alloc += 64;
451                                         ret_msgs = realloc(ret_msgs,
452                                                 (num_ret_alloc*sizeof(long)) );
453                                 }
454                                 ret_msgs[num_ret_msgs - 1] = all_msgs[j];
455
456                         }
457                 }
458
459                 free(all_msgs);
460         }
461
462         *fts_num_msgs = num_ret_msgs;
463         *fts_msgs = ret_msgs;
464 }
465
466
467 /*
468  * This search command is for diagnostic purposes and may be removed or replaced.
469  */
470 void cmd_srch(char *argbuf) {
471         int num_msgs = 0;
472         long *msgs = NULL;
473         int i;
474         char search_string[256];
475
476         if (CtdlAccessCheck(ac_logged_in)) return;
477
478         if (!config.c_enable_fulltext) {
479                 cprintf("%d Full text index is not enabled on this server.\n",
480                         ERROR + CMD_NOT_SUPPORTED);
481                 return;
482         }
483
484         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
485         ft_search(&num_msgs, &msgs, search_string);
486
487         cprintf("%d %d msgs match all search words:\n",
488                 LISTING_FOLLOWS, num_msgs);
489         if (num_msgs > 0) {
490                 for (i=0; i<num_msgs; ++i) {
491                         cprintf("%ld\n", msgs[i]);
492                 }
493         }
494         if (msgs != NULL) free(msgs);
495         cprintf("000\n");
496 }
497
498 /*
499  * Zero out our index cache.
500  */
501 void initialize_ft_cache(void) {
502         memset(ftc_num_msgs, 0, (65536 * sizeof(int)));
503         memset(ftc_msgs, 0, (65536 * sizeof(long *)));
504 }
505
506
507 void ft_delete_remove(char *room, long msgnum)
508 {
509         if (room) return;
510         
511         /* Remove from fulltext index */
512         if (config.c_enable_fulltext) {
513                 ft_index_message(msgnum, 0);
514         }
515 }
516
517 /*****************************************************************************/
518
519 CTDL_MODULE_INIT(fulltext)
520 {
521         if (!threading)
522         {
523                 initialize_ft_cache();
524                 initialize_noise_words();
525                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
526                 CtdlRegisterDeleteHook(ft_delete_remove);
527                 CtdlRegisterSearchFuncHook(ft_search, "fulltext");
528                 CtdlRegisterCleanupHook(noise_word_cleanup);
529         }
530         else
531         {
532                 CtdlThreadCreate("Indexer", CTDLTHREAD_BIGSTACK, indexer_thread, NULL);
533         }
534         /* return our Subversion id for the Log */
535         return "fulltext";
536 }