]> code.citadel.org Git - citadel.git/blob - citadel/server/modules/fulltext/serv_fulltext.c
Rewrite of the indexer is complete!
[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                 begin_critical_section(S_INDEXER);
106                 cdb_begin_transaction();
107                 for (i=0; i<array_len(tokens_in_this_message); ++i) {
108
109                         // Identify the bucket which we will be modifying
110                         memcpy(&tok, array_get_element_at(tokens_in_this_message, i), sizeof(int));
111         
112                         // fetch the bucket
113                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
114                         long *newbucket = malloc(cdb_bucket.len + sizeof(long));
115                         int nmsgs = cdb_bucket.len / sizeof(long);
116
117                         if (op == 1) {                                          // indexing, add this message to the bucket
118                                 memcpy(&newbucket[0], cdb_bucket.ptr, cdb_bucket.len);
119                                 int already_there = 0;
120                                 for (j=0; j<nmsgs; ++j) {
121                                         if (newbucket[j] == msgnum) {
122                                                 already_there = 1;
123                                         }
124                                 }
125                                 if (already_there == 0) {
126                                         memcpy(&newbucket[nmsgs++], &msgnum, sizeof(long));
127                                 }
128                         }
129
130                         else if (op == 0) {                                     // deindexing, remove this message from the bucket
131                                 memcpy(newbucket, cdb_bucket.ptr, cdb_bucket.len);
132                                 for (j=0; j<nmsgs; ++j) {
133                                         if ((newbucket[j] == msgnum) || (newbucket[j] == 0)) {
134                                                 memcpy(&newbucket[j], &newbucket[j+1], ((nmsgs-j)*sizeof(long)));
135                                                 --j;
136                                                 --nmsgs;
137                                         }
138                                 }
139                         }
140
141                         // Then write it back to disk
142                         cdb_store(CDB_FULLTEXT, &tok, sizeof(int), newbucket, (nmsgs*sizeof(long)));
143                         free(newbucket);
144
145                         if (server_shutting_down) break;
146                 }
147                 cdb_end_transaction();
148                 end_critical_section(S_INDEXER);
149                 CtdlSetConfigLong("MMfulltext", msgnum);
150         }
151         array_free(tokens_in_this_message);
152 }
153
154
155 // Scan a room for messages to index.
156 void ft_index_room(struct ctdlroom *qrbuf, void *data) {
157         if (server_shutting_down) {
158                 return;
159         }
160
161         int num_msgs = 0;
162         long *msglist;
163         int i;
164
165         // 2023aug30 ajc - old code did another CtdlGetRoom() here.  Not only is that redundant,
166         // but for some reason it also made Berkeley DB deadlock after a while.  I don't know why.
167
168         // qrbuf is already populated.  fetch the list of messages in this room.
169         num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
170
171         // Identify messages which have NOT yet been seen by the indexer.
172         if (msglist != NULL) {
173                 for (i=0; i<num_msgs; ++i) {
174                         if (
175                                 (msglist[i] > 0)
176                                 && (msglist[i] > highest_msg_already_indexed)
177                                 && (msglist[i] <= highest_msg_to_be_indexed)
178                            ) {
179                                 array_append(messages_to_be_indexed, &msglist[i]);
180                         }
181                 }
182                 free(msglist);
183         }
184 }
185
186
187 // Begin the fulltext indexing process.
188 void do_fulltext_indexing(void) {
189         int i;
190         static time_t last_progress = 0L;
191         static int is_running = 0;
192         if (is_running) return;         // Concurrency check - only one can run 
193         is_running = 1;
194
195         // Don't do this if the site doesn't have it enabled.
196         if (!CtdlGetConfigInt("c_enable_fulltext")) {
197                 return;
198         }
199         syslog(LOG_DEBUG, "fulltext: indexing started");
200
201         // If we've switched wordbreaker modules, burn the index and start over.
202         begin_critical_section(S_CONTROL);
203         if (CtdlGetConfigInt("MM_fulltext_wordbreaker") != FT_WORDBREAKER_ID) {
204                 syslog(LOG_DEBUG, "fulltext: wb ver on disk = %d, code ver = %d",
205                         CtdlGetConfigInt("MM_fulltext_wordbreaker"), FT_WORDBREAKER_ID
206                 );
207                 syslog(LOG_INFO, "fulltext: (re)initializing index");
208                 cdb_trunc(CDB_FULLTEXT);
209                 CtdlSetConfigLong("MMfulltext", 0);
210         }
211         end_critical_section(S_CONTROL);
212
213         // Silently return if our fulltext index is up to date with new messages.
214         if ((CtdlGetConfigLong("MMfulltext") >= CtdlGetConfigLong("MMhighest"))) {
215                 return;         // nothing to do!
216         }
217
218         highest_msg_already_indexed = CtdlGetConfigLong("MMfulltext");
219         highest_msg_to_be_indexed = CtdlGetConfigLong("MMhighest");
220         messages_to_be_indexed = array_new(sizeof(long));
221
222         // Now go through each room and find messages to index.
223         CtdlForEachRoom(ft_index_room, NULL);                           // load all msg pointers
224         array_sort(messages_to_be_indexed, longcmp);                    // sort them
225
226         // Here it is ... do each message!
227         long msgnum = 0;
228         long prev_msgnum = 0;
229         for (i=0; i<array_len(messages_to_be_indexed); ++i) {
230                 memcpy(&msgnum, array_get_element_at(messages_to_be_indexed, i), sizeof(long));
231
232                 if (msgnum != prev_msgnum) {                            // careful to avoid dupes
233                         ft_index_message(msgnum, 1);
234                 }
235
236                 prev_msgnum = msgnum;
237         }
238
239         array_free(messages_to_be_indexed);
240
241         CtdlSetConfigInt("MM_fulltext_wordbreaker", FT_WORDBREAKER_ID);
242
243         syslog(LOG_DEBUG, "fulltext: indexing finished");
244         is_running = 0;
245         return;
246 }
247
248
249 // API call to perform searches.
250 // (This one does the "all of these words" search.)
251 // Caller is responsible for freeing the message list.
252 Array *CtdlFullTextSearch(const char *search_string) {
253         int i, j, tok;
254         struct cdbdata cdb_bucket;
255         long msgnum, smsgnum;
256         int count;
257
258         Array *r = array_new(sizeof(long));
259         if (!r) return(NULL);
260         Array *t = wordbreaker(search_string);
261
262         if ((t != NULL) && (array_len(t) > 0)) {
263                 for (i=0; i<array_len(t); ++i) {
264                         memcpy(&tok, array_get_element_at(t, i), sizeof(int));
265                         cdb_bucket = cdb_fetch(CDB_FULLTEXT, &tok, sizeof(int));
266                         if (cdb_bucket.ptr != NULL) {
267                                 for (j=0; j<(cdb_bucket.len / sizeof(long)); ++j) {
268                                         memcpy(&msgnum, cdb_bucket.ptr + (j*sizeof(long)), sizeof(long));
269                                         array_append(r, &msgnum);
270                                 }
271                         }
272                 }
273         }
274
275         // We need to return any message containing ALL of the tokens.
276         // If a message number appears in the array `n` times, where `n` is the number of search words,
277         // that means it matched all search words.
278         array_sort(r, longcmp);
279         for (i=0; i<array_len(r); ++i) {
280                 memcpy(&msgnum, array_get_element_at(r, i), sizeof(long));
281                 count = 1;
282                 for (j=i+1; j<array_len(r); ++j) {
283                         memcpy(&smsgnum, array_get_element_at(r, j), sizeof(long));
284                         if (msgnum == smsgnum) {
285                                 ++count;
286                                 array_delete_element_at(r, j);
287                                 --j;
288                         }
289                 }
290                 if (count != array_len(t)) {
291                         array_delete_element_at(r, i);
292                         --i;
293                 }
294         }
295
296         array_free(t);
297         return(r);
298 }
299
300
301 // This search command is for diagnostic purposes and may be removed or replaced.
302 void cmd_srch(char *argbuf) {
303         int i;
304         char search_string[SIZ];
305         Array *matches = NULL;
306         long msgnum;
307
308         if (CtdlAccessCheck(ac_logged_in)) return;
309
310         if (!CtdlGetConfigInt("c_enable_fulltext")) {
311                 cprintf("%d Full text index is not enabled on this server.\n", ERROR + CMD_NOT_SUPPORTED);
312                 return;
313         }
314
315         extract_token(search_string, argbuf, 0, '|', sizeof search_string);
316         matches = CtdlFullTextSearch(search_string);
317
318         cprintf("%d %d msgs match all search words:\n", LISTING_FOLLOWS, array_len(matches));
319         if ((matches != NULL) && (array_len(matches) > 0)) {
320                 for (i=0; i<array_len(matches); ++i) {
321                         memcpy(&msgnum, array_get_element_at(matches, i), sizeof(long));
322                         cprintf("%ld\n", msgnum);
323                 }
324         }
325         if (matches != NULL) {
326                 array_free(matches);
327         }
328         cprintf("000\n");
329 }
330
331
332 void ft_delete_remove(char *room, long msgnum) {
333         if (room) return;
334         
335         // Remove from fulltext index
336         if (CtdlGetConfigInt("c_enable_fulltext")) {
337                 ft_index_message(msgnum, 0);
338         }
339 }
340
341
342 // Initialization function, called from modules_init.c
343 char *ctdl_module_init_fulltext(void) {
344         if (!threading) {
345                 CtdlRegisterProtoHook(cmd_srch, "SRCH", "Full text search");
346                 CtdlRegisterDeleteHook(ft_delete_remove);
347                 CtdlRegisterSessionHook(do_fulltext_indexing, EVT_TIMER, PRIO_CLEANUP + 300);
348         }
349         // return our module name for the log
350         return "fulltext";
351 }