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