]> code.citadel.org Git - citadel.git/blob - citadel/server/modules/fulltext/serv_fulltext.c
Rewrote the indexer
[citadel.git] / citadel / server / modules / fulltext / serv_fulltext.c
1 // This module handles fulltext indexing of the message base.
2 //
3 // Copyright (c) 2005-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
7
8 #include "../../sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17 #include <time.h>
18 #include <sys/wait.h>
19 #include <string.h>
20 #include <limits.h>
21 #include <libcitadel.h>
22 #include "../../citadel_defs.h"
23 #include "../../server.h"
24 #include "../../citserver.h"
25 #include "../../support.h"
26 #include "../../config.h"
27 #include "../../room_ops.h"
28 #include "../../database.h"
29 #include "../../msgbase.h"
30 #include "../../control.h"
31 #include "serv_fulltext.h"
32 #include "ft_wordbreaker.h"
33 #include "../../threads.h"
34 #include "../../context.h"
35 #include "../../ctdl_module.h"
36
37
38 // These can be global variables because only one indexer runs at a time.
39 Array *messages_to_be_indexed = NULL;
40 long highest_msg_already_indexed = 0;
41 long highest_msg_to_be_indexed = 0;
42
43
44 // Compare function
45 int longcmp(const void *rec1, const void *rec2) {
46         long i1, i2;
47
48         i1 = *(const long *)rec1;
49         i2 = *(const long *)rec2;
50
51         if (i1 > i2) return(1);
52         if (i1 < i2) return(-1);
53         return(0);
54 }
55
56
57 // Index or de-index a message.  (op == 1 to index, 0 to de-index)
58 void ft_index_message(long msgnum, int op) {
59         int i, j;
60         Array *tokens_in_this_message = NULL;
61         struct cdbdata cdb_bucket;
62         StrBuf *msgtext;
63         char *txt;
64         int tok;
65         struct CtdlMessage *msg = NULL;
66
67         if (msgnum == 0) return;
68
69         msg = CtdlFetchMessage(msgnum, 1);
70         if (msg == NULL) {
71                 // This is not necessarily an error condition; it could simply mean that the message was
72                 // deleted before it could be indexed.  This happens often when the load tester is running.
73                 syslog(LOG_ERR, "fulltext: ft_index_message() could not load msg %ld", msgnum);
74                 return;
75         }
76
77         if (!CM_IsEmpty(msg, eSuppressIdx)) {
78                 syslog(LOG_DEBUG, "fulltext: ft_index_message() excluded msg %ld", msgnum);
79                 CM_Free(msg);
80                 return;
81         }
82
83         syslog(LOG_DEBUG, "fulltext: ft_index_message() %s msg %ld", (op ? "adding" : "removing") , msgnum);
84
85         // Output the message as text before indexing it, so we don't end up indexing a bunch of encoded base64, etc.
86         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
87         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_ALL, 0, 1, 0);
88         CM_Free(msg);
89         msgtext = CC->redirect_buffer;
90         CC->redirect_buffer = NULL;
91         if (msgtext != NULL) {
92                 syslog(LOG_DEBUG, "fulltext: wordbreaking message %ld (%d bytes)", msgnum, StrLength(msgtext));
93         }
94         txt = SmashStrBuf(&msgtext);
95         tokens_in_this_message = wordbreaker(txt);
96         free(txt);
97
98         syslog(LOG_DEBUG, "fulltext: %sindexing message %ld [%d tokens]",
99                 (op ? "" : "de"),
100                 msgnum,
101                 array_len(tokens_in_this_message)
102         );
103
104         if (array_len(tokens_in_this_message) > 0) {
105                 cdb_begin_transaction();
106                 for (i=0; i<array_len(tokens_in_this_message); ++i) {
107
108                         // Identify the bucket which we will be modifying
109                         memcpy(&tok, array_get_element_at(tokens_in_this_message, i), sizeof(int));
110         
111                         // fetch the bucket
112                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
113                         long *newbucket = malloc(cdb_bucket.len + sizeof(long));
114                         int nmsgs = cdb_bucket.len / sizeof(long);
115
116                         if (op == 1) {                                          // indexing, add this message to the bucket
117                                 memcpy(&newbucket[0], cdb_bucket.ptr, cdb_bucket.len);
118                                 memcpy(&newbucket[nmsgs++], &msgnum, sizeof(long));
119                         }
120
121                         else if (op == 0) {                                     // deindexing, remove this message from the bucket
122                                 memcpy(newbucket, cdb_bucket.ptr, cdb_bucket.len);
123                                 for (j=0; j<nmsgs; ++j) {
124                                         if ((newbucket[j] == msgnum) || (newbucket[j] == 0)) {
125                                                 fprintf(stderr, "removing %ld\n", newbucket[j]);
126                                                 memcpy(&newbucket[j], &newbucket[j+1], ((nmsgs-j)*sizeof(long)));
127                                                 --j;
128                                                 --nmsgs;
129                                         }
130                                 }
131                         }
132
133                         // Then write it back to disk
134                         cdb_store(CDB_FULLTEXT, &tok, sizeof(int), newbucket, (nmsgs*sizeof(long)));
135                         free(newbucket);
136
137                         if (server_shutting_down) break;
138                 }
139                 cdb_end_transaction();
140                 CtdlSetConfigLong("MMfulltext", msgnum);
141         }
142         array_free(tokens_in_this_message);
143 }
144
145
146 // Scan a room for messages to index.
147 void ft_index_room(struct ctdlroom *qrbuf, void *data) {
148         if (server_shutting_down) {
149                 return;
150         }
151
152         int num_msgs = 0;
153         long *msglist;
154         int i;
155
156         // 2023aug30 ajc - old code did another CtdlGetRoom() here.  Not only is that redundant,
157         // but for some reason it also made Berkeley DB deadlock after a while.  I don't know why.
158
159         // qrbuf is already populated.  fetch the list of messages in this room.
160         num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
161
162         // Identify messages which have NOT yet been seen by the indexer.
163         if (msglist != NULL) {
164                 for (i=0; i<num_msgs; ++i) {
165                         if (
166                                 (msglist[i] > 0)
167                                 && (msglist[i] > highest_msg_already_indexed)
168                                 && (msglist[i] <= highest_msg_to_be_indexed)
169                            ) {
170                                 array_append(messages_to_be_indexed, &msglist[i]);
171                         }
172                 }
173                 free(msglist);
174         }
175 }
176
177
178 // Begin the fulltext indexing process.
179 void do_fulltext_indexing(void) {
180         int i;
181         static time_t last_progress = 0L;
182         static int is_running = 0;
183         if (is_running) return;         // Concurrency check - only one can run 
184         is_running = 1;
185
186         // Don't do this if the site doesn't have it enabled.
187         if (!CtdlGetConfigInt("c_enable_fulltext")) {
188                 return;
189         }
190         syslog(LOG_DEBUG, "fulltext: indexing started");
191
192         // If we've switched wordbreaker modules, burn the index and start over.
193         begin_critical_section(S_CONTROL);
194         if (CtdlGetConfigInt("MM_fulltext_wordbreaker") != FT_WORDBREAKER_ID) {
195                 syslog(LOG_DEBUG, "fulltext: wb ver on disk = %d, code ver = %d",
196                         CtdlGetConfigInt("MM_fulltext_wordbreaker"), FT_WORDBREAKER_ID
197                 );
198                 syslog(LOG_INFO, "fulltext: (re)initializing index");
199                 cdb_trunc(CDB_FULLTEXT);
200                 CtdlSetConfigLong("MMfulltext", 0);
201         }
202         end_critical_section(S_CONTROL);
203
204         // Silently return if our fulltext index is up to date with new messages.
205         if ((CtdlGetConfigLong("MMfulltext") >= CtdlGetConfigLong("MMhighest"))) {
206                 return;         // nothing to do!
207         }
208
209         highest_msg_already_indexed = CtdlGetConfigLong("MMfulltext");
210         highest_msg_to_be_indexed = CtdlGetConfigLong("MMhighest");
211         messages_to_be_indexed = array_new(sizeof(long));
212
213         // Now go through each room and find messages to index.
214         CtdlForEachRoom(ft_index_room, NULL);                           // load all msg pointers
215         array_sort(messages_to_be_indexed, longcmp);                    // sort them
216
217         // Here it is ... do each message!
218         long msgnum = 0;
219         long prev_msgnum = 0;
220         for (i=0; i<array_len(messages_to_be_indexed); ++i) {
221                 memcpy(&msgnum, array_get_element_at(messages_to_be_indexed, i), sizeof(long));
222
223                 if (msgnum != prev_msgnum) {                            // careful to avoid dupes
224                         ft_index_message(msgnum, 1);
225                 }
226
227                 prev_msgnum = msgnum;
228         }
229
230         array_free(messages_to_be_indexed);
231
232         CtdlSetConfigInt("MM_fulltext_wordbreaker", FT_WORDBREAKER_ID);
233
234         syslog(LOG_DEBUG, "fulltext: indexing finished");
235         is_running = 0;
236         return;
237 }
238
239
240 // API call to perform searches.
241 // (This one does the "all of these words" search.)
242 // Caller is responsible for freeing the message list.
243 void ft_search(int *fts_num_msgs, long **fts_msgs, const char *search_string) {
244         Array *t = NULL;
245         int i, j;
246         struct cdbdata cdb_bucket;
247         int num_all_msgs = 0;
248         long *all_msgs = NULL;
249         int num_ret_msgs = 0;
250         int num_ret_alloc = 0;
251         long *ret_msgs = NULL;
252         int tok;
253
254 #if 0
255         t = wordbreaker(search_string);
256         if (array_len(t) > 0) {
257                 for (i=0; i<array_len(t); ++i) {
258
259                         // search for tokens[i]
260                         memcpy(&tok, array_get_element_at(t, i), sizeof(int));
261
262                         // fetch the bucket, Liza
263                         if (ftc_msgs[tok] == NULL) {
264                                 cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
265                                 if (cdb_bucket.ptr != NULL) {
266                                         ftc_num_msgs[tok] = cdb_bucket.len / sizeof(long);
267                                         ftc_msgs[tok] = (long *) malloc(cdb_bucket.len);
268                                         memcpy(ftc_msgs[tok], cdb_bucket.ptr, cdb_bucket.len);
269                                 }
270                                 else {
271                                         ftc_num_msgs[tok] = 0;
272                                         ftc_msgs[tok] = malloc(sizeof(long));
273                                 }
274                         }
275
276                         num_all_msgs += ftc_num_msgs[tok];
277                         if (num_all_msgs > 0) {
278                                 all_msgs = realloc(all_msgs, num_all_msgs*sizeof(long) );
279                                 memcpy(&all_msgs[num_all_msgs-ftc_num_msgs[tok]], ftc_msgs[tok], ftc_num_msgs[tok]*sizeof(long) );
280                         }
281
282                 }
283                 array_free(t);
284                 if (all_msgs != NULL) {
285                         qsort(all_msgs, num_all_msgs, sizeof(long), longcmp);
286
287                         // At this point, if a message appears array_len(t) times in the
288                         // list, then it contains all of the search tokens.
289                         if (num_all_msgs >= array_len(t))
290                                 for (j=0; j<(num_all_msgs-array_len(t)+1); ++j) {
291                                         if (all_msgs[j] == all_msgs[j+array_len(t)-1]) {
292                                                 ++num_ret_msgs;
293                                                 if (num_ret_msgs > num_ret_alloc) {
294                                                         num_ret_alloc += 64;
295                                                         ret_msgs = realloc(ret_msgs, (num_ret_alloc*sizeof(long)) );
296                                                 }
297                                                 ret_msgs[num_ret_msgs - 1] = all_msgs[j];
298                                                 
299                                         }
300                                 }
301                         free(all_msgs);
302                 }
303         }
304
305         *fts_num_msgs = num_ret_msgs;
306         *fts_msgs = ret_msgs;
307 #endif
308 }
309
310
311 // This search command is for diagnostic purposes and may be removed or replaced.
312 void cmd_srch(char *argbuf) {
313         int num_msgs = 0;
314         long *msgs = NULL;
315         int i;
316         char search_string[256];
317
318         if (CtdlAccessCheck(ac_logged_in)) return;
319
320         if (!CtdlGetConfigInt("c_enable_fulltext")) {
321                 cprintf("%d Full text index is not enabled on this server.\n", ERROR + CMD_NOT_SUPPORTED);
322                 return;
323         }
324
325         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
326         ft_search(&num_msgs, &msgs, search_string);
327
328         cprintf("%d %d msgs match all search words:\n", LISTING_FOLLOWS, num_msgs);
329         if (num_msgs > 0) {
330                 for (i=0; i<num_msgs; ++i) {
331                         cprintf("%ld\n", msgs[i]);
332                 }
333         }
334         if (msgs != NULL) free(msgs);
335         cprintf("000\n");
336 }
337
338
339 void ft_delete_remove(char *room, long msgnum) {
340         if (room) return;
341         
342         // Remove from fulltext index
343         if (CtdlGetConfigInt("c_enable_fulltext")) {
344                 ft_index_message(msgnum, 0);
345         }
346 }
347
348
349 // Initialization function, called from modules_init.c
350 char *ctdl_module_init_fulltext(void) {
351         if (!threading) {
352                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
353                 CtdlRegisterDeleteHook(ft_delete_remove);
354                 CtdlRegisterSearchFuncHook(ft_search, "fulltext");
355                 CtdlRegisterSessionHook(do_fulltext_indexing, EVT_TIMER, PRIO_CLEANUP + 300);
356         }
357         // return our module name for the log
358         return "fulltext";
359 }