]> code.citadel.org Git - citadel.git/blob - citadel/database_sleepycat.c
203192305c0b1927ffb95f69438e38bfffd3fc44
[citadel.git] / citadel / database_sleepycat.c
1 /*
2  * $Id$
3  *
4  * Sleepycat (Berkeley) DB driver for Citadel/UX
5  *
6  */
7
8 /*****************************************************************************
9        Tunable configuration parameters for the Sleepycat DB back end
10  *****************************************************************************/
11
12 /* Citadel will checkpoint the db at the end of every session, but only if
13  * the specified number of kilobytes has been written, or if the specified
14  * number of minutes has passed, since the last checkpoint.
15  */
16 #define MAX_CHECKPOINT_KBYTES   256
17 #define MAX_CHECKPOINT_MINUTES  15
18
19 /*****************************************************************************/
20
21 #ifdef DLL_EXPORT
22 #define IN_LIBCIT
23 #endif
24
25 #include "sysdep.h"
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <dirent.h>
35
36 #ifdef HAVE_DB3_DB_H
37 #include <db3/db.h>
38 #else
39 #include <db.h>
40 #endif
41
42 #include <pthread.h>
43 #include "citadel.h"
44 #include "server.h"
45 #include "dynloader.h"
46 #include "citserver.h"
47 #include "database.h"
48 #include "sysdep_decls.h"
49
50 static DB *dbp[MAXCDB];         /* One DB handle for each Citadel database */
51 static DB_ENV *dbenv;           /* The DB environment (global) */
52
53 struct cdbtsd {                 /* Thread-specific DB stuff */
54         DB_TXN *tid;            /* Transaction handle */
55         DBC *cursors[MAXCDB];   /* Cursors, for traversals... */
56 };
57
58 static pthread_key_t tsdkey;
59
60 #define MYCURSORS       (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
61 #define MYTID           (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
62
63 /* just a little helper function */
64 static void txabort(DB_TXN *tid) {
65         int ret = txn_abort(tid);
66
67         if (ret) {
68                 lprintf(1, "cdb_*: txn_abort: %s\n", db_strerror(ret));
69                 abort();
70         }
71 }
72
73 /* this one is even more helpful than the last. */
74 static void txcommit(DB_TXN *tid) {
75         int ret = txn_commit(tid, 0);
76
77         if (ret) {
78                 lprintf(1, "cdb_*: txn_commit: %s\n", db_strerror(ret));
79                 abort();
80         }
81 }
82
83 /* are you sensing a pattern yet? */
84 static void txbegin(DB_TXN **tid) {
85         int ret = txn_begin(dbenv, NULL, tid, 0);
86
87         if (ret) {
88                 lprintf(1, "cdb_*: txn_begin: %s\n", db_strerror(ret));
89                 abort();
90         }
91 }
92
93 static void cclose(DBC *cursor) {
94         int ret;
95
96         if ((ret = cursor->c_close(cursor))) {
97                 lprintf(1, "cdb_*: c_close: %s\n", db_strerror(ret));
98                 abort();
99         }
100 }
101
102 static void bailIfCursor(DBC **cursors, const char *msg)
103 {
104   int i;
105
106   for (i = 0; i < MAXCDB; i++)
107     if (cursors[i] != NULL)
108       {
109         lprintf(1, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
110         abort();
111       }
112 }
113
114 static void check_handles(void *arg) {
115         if (arg != NULL) {
116                 struct cdbtsd *tsd = (struct cdbtsd *)arg;
117
118                 bailIfCursor(tsd->cursors, "in check_handles");
119
120                 if (tsd->tid != NULL) {
121                         lprintf(1, "cdb_*: transaction still in progress!");
122                         abort();
123                 }
124         }
125 }
126
127 static void dest_tsd(void *arg) {
128         if (arg != NULL) {
129                 check_handles(arg);
130                 phree(arg);
131         }
132 }
133
134 /*
135  * Ensure that we have a key for thread-specific data.  We don't
136  * put anything in here that Citadel cares about; this is just database
137  * related stuff like cursors and transactions.
138  *
139  * This should be called immediately after startup by any thread which wants
140  * to use database calls, except for whatever thread calls open_databases.
141  */
142 void cdb_allocate_tsd(void) {
143         struct cdbtsd *tsd;
144
145         if (pthread_getspecific(tsdkey) != NULL)
146                 return;
147
148         tsd = mallok(sizeof *tsd);
149
150         tsd->tid = NULL;
151
152         memset(tsd->cursors, 0, sizeof tsd->cursors);
153         pthread_setspecific(tsdkey, tsd);
154 }
155
156 void cdb_free_tsd(void) {
157         dest_tsd(pthread_getspecific(tsdkey));
158         pthread_setspecific(tsdkey, NULL);
159 }
160
161 void cdb_check_handles(void) {
162         check_handles(pthread_getspecific(tsdkey));
163 }
164
165
166 /*
167  * Reclaim unused space in the databases.  We need to do each one of
168  * these discretely, rather than in a loop.
169  *
170  * This is a stub function in the Sleepycat DB backend, because there is no
171  * such API call available.
172  */
173 void defrag_databases(void)
174 {
175         /* do nothing */
176 }
177
178
179 /*
180  * Cull the database logs
181  */
182 static void cdb_cull_logs(void) {
183         u_int32_t flags;
184         int ret;
185         char **file, **list;
186
187         lprintf(5, "Database log file cull started.\n");
188
189         flags = DB_ARCH_ABS;
190
191         /* Get the list of names. */
192 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
193         if ((ret = log_archive(dbenv, &list, flags, NULL)) != 0) {
194 #else
195         if ((ret = log_archive(dbenv, &list, flags)) != 0) {
196 #endif
197                 lprintf(1, "cdb_cull_logs: %s\n", db_strerror(ret));
198                 return;
199         }
200
201         /* Print the list of names. */
202         if (list != NULL) {
203                 for (file = list; *file != NULL; ++file) {
204                         lprintf(9, "Deleting log: %s\n", *file);
205                         unlink(*file);
206                 }
207                 free(list);
208         }
209
210         lprintf(5, "Database log file cull ended.\n");
211 }
212
213
214 /*
215  * Request a checkpoint of the database.
216  */
217 static void cdb_checkpoint(void) {
218         int ret;
219         static time_t last_cull = 0L;
220
221         ret = txn_checkpoint(dbenv,
222                                 MAX_CHECKPOINT_KBYTES,
223                                 MAX_CHECKPOINT_MINUTES,
224                                 0);
225         if ( (ret != 0) && (ret != DB_INCOMPLETE) ) {
226                 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n", db_strerror(ret));
227                 abort();
228         }
229
230         if (ret == DB_INCOMPLETE) {
231                 lprintf(3, "WARNING: txn_checkpoint: %s\n", db_strerror(ret));
232         }
233
234         /* Cull the logs if we haven't done so for 24 hours */
235         if ((time(NULL) - last_cull) > 86400L) {
236                 last_cull = time(NULL);
237                 cdb_cull_logs();
238         }
239
240 }
241
242 /*
243  * Open the various databases we'll be using.  Any database which
244  * does not exist should be created.  Note that we don't need an S_DATABASE
245  * critical section here, because there aren't any active threads manipulating
246  * the database yet -- and besides, it causes problems on BSDI.
247  */
248 void open_databases(void)
249 {
250         int ret;
251         int i;
252         char dbfilename[SIZ];
253         u_int32_t flags = 0;
254
255         lprintf(9, "cdb_*: open_databases() starting\n");
256         /*
257          * Silently try to create the database subdirectory.  If it's
258          * already there, no problem.
259          */
260         system("exec mkdir data 2>/dev/null");
261
262         lprintf(9, "cdb_*: Setting up DB environment\n");
263         db_env_set_func_yield(sched_yield);
264         ret = db_env_create(&dbenv, 0);
265         if (ret) {
266                 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
267                 exit(ret);
268         }
269         dbenv->set_errpfx(dbenv, "citserver");
270
271         /*
272          * We want to specify the shared memory buffer pool cachesize,
273          * but everything else is the default.
274          */
275         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
276         if (ret) {
277                 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
278                 dbenv->close(dbenv, 0);
279                 exit(ret);
280         }
281
282         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
283                 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
284                 dbenv->close(dbenv, 0);
285                 exit(ret);
286         }
287
288         flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
289                 DB_INIT_LOCK|DB_THREAD;
290         ret = dbenv->open(dbenv, "./data", flags, 0);
291         if (ret) {
292                 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
293                 dbenv->close(dbenv, 0);
294                 exit(ret);
295         }
296
297         lprintf(7, "cdb_*: Starting up DB\n");
298
299         for (i = 0; i < MAXCDB; ++i) {
300
301                 /* Create a database handle */
302                 ret = db_create(&dbp[i], dbenv, 0);
303                 if (ret) {
304                         lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
305                         exit(ret);
306                 }
307
308
309                 /* Arbitrary names for our tables -- we reference them by
310                  * number, so we don't have string names for them.
311                  */
312                 sprintf(dbfilename, "cdb.%02x", i);
313
314                 ret = dbp[i]->open(dbp[i],
315                                 dbfilename,
316                                 NULL,
317                                 DB_BTREE,
318                                 DB_CREATE|DB_THREAD,
319                                 0600);
320                 if (ret) {
321                         lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
322                         exit(ret);
323                 }
324         }
325
326         if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
327                 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
328                 exit(1);
329         }
330
331         cdb_allocate_tsd();
332         CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
333         lprintf(9, "cdb_*: open_databases() finished\n");
334 }
335
336
337 /*
338  * Close all of the db database files we've opened.  This can be done
339  * in a loop, since it's just a bunch of closes.
340  */
341 void close_databases(void)
342 {
343         int a;
344         int ret;
345
346         cdb_free_tsd();
347
348         if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
349                 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
350                 abort();
351         }
352
353         for (a = 0; a < MAXCDB; ++a) {
354                 lprintf(7, "cdb_*: Closing database %d\n", a);
355                 ret = dbp[a]->close(dbp[a], 0);
356                 if (ret) {
357                         lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
358                         abort();
359                 }
360                 
361         }
362
363         /* Close the handle. */
364         ret = dbenv->close(dbenv, 0);
365         if (ret) {
366                 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
367                 abort();
368         }
369 }
370
371 /*
372  * Store a piece of data.  Returns 0 if the operation was successful.  If a
373  * key already exists it should be overwritten.
374  */
375 int cdb_store(int cdb,
376               void *ckey, int ckeylen,
377               void *cdata, int cdatalen)
378 {
379
380   DBT dkey, ddata;
381   DB_TXN *tid;
382   int ret;
383   
384   memset(&dkey, 0, sizeof(DBT));
385   memset(&ddata, 0, sizeof(DBT));
386   dkey.size = ckeylen;
387   dkey.data = ckey;
388   ddata.size = cdatalen;
389   ddata.data = cdata;
390   
391   if (MYTID != NULL)
392     {
393       ret = dbp[cdb]->put(dbp[cdb],             /* db */
394                           MYTID,                /* transaction ID */
395                           &dkey,                /* key */
396                           &ddata,               /* data */
397                           0);           /* flags */
398       if (ret)
399         {
400           lprintf(1, "cdb_store(%d): %s\n", cdb,
401                   db_strerror(ret));
402           abort();
403         }
404       return ret;
405       
406     }
407   else
408     {
409       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
410       
411     retry:
412       txbegin(&tid);
413       
414       if ((ret = dbp[cdb]->put(dbp[cdb],    /* db */
415                                tid,         /* transaction ID */
416                                &dkey,       /* key */
417                                &ddata,      /* data */
418                                0)))         /* flags */
419         {
420           if (ret == DB_LOCK_DEADLOCK)
421             {
422               txabort(tid);
423               goto retry;
424             }
425           else
426             {
427               lprintf(1, "cdb_store(%d): %s\n", cdb,
428                       db_strerror(ret));
429               abort();
430             }
431         }
432       else
433         {
434           txcommit(tid);
435           return ret;
436         }
437     }
438 }
439
440
441 /*
442  * Delete a piece of data.  Returns 0 if the operation was successful.
443  */
444 int cdb_delete(int cdb, void *key, int keylen)
445 {
446
447   DBT dkey;
448   DB_TXN *tid;
449   int ret;
450
451   memset(&dkey, 0, sizeof dkey);
452   dkey.size = keylen;
453   dkey.data = key;
454
455   if (MYTID != NULL)
456     {
457       ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
458       if (ret)
459         {
460           lprintf(1, "cdb_delete(%d): %s\n", cdb,
461                   db_strerror(ret));
462           if (ret != DB_NOTFOUND)
463             abort();
464         }
465     }
466   else
467     {
468       bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
469     
470     retry:
471       txbegin(&tid);
472     
473       if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
474           && ret != DB_NOTFOUND)
475         {
476           if (ret == DB_LOCK_DEADLOCK)
477             {
478               txabort(tid);
479               goto retry;
480             }
481           else
482             {
483               lprintf(1, "cdb_delete(%d): %s\n", cdb,
484                       db_strerror(ret));
485               abort();
486             }
487         }
488       else
489         {
490           txcommit(tid);
491         }
492     }
493   return ret;
494 }
495
496 static DBC *localcursor(int cdb)
497 {
498   int ret;
499   DBC *curs;
500
501   if (MYCURSORS[cdb] == NULL)
502     ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
503   else
504     ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
505
506   if (ret)
507     {
508       lprintf(1, "localcursor: %s\n", db_strerror(ret));
509       abort();
510     }
511
512   return curs;
513 }
514
515
516 /*
517  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
518  * a struct cdbdata which it is the caller's responsibility to free later on
519  * using the cdb_free() routine.
520  */
521 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
522 {
523
524   struct cdbdata *tempcdb;
525   DBT dkey, dret;
526   int ret;
527
528   memset(&dkey, 0, sizeof(DBT));
529   dkey.size = keylen;
530   dkey.data = key;
531
532   if (MYTID != NULL)
533     {
534       memset(&dret, 0, sizeof(DBT));
535       dret.flags = DB_DBT_MALLOC;
536       ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
537     }
538   else
539     {
540       DBC *curs;
541
542       do
543         {
544           memset(&dret, 0, sizeof(DBT));
545           dret.flags = DB_DBT_MALLOC;
546
547           curs = localcursor(cdb);
548
549           ret = curs->c_get(curs, &dkey, &dret, DB_SET);
550           cclose(curs);
551         }
552       while (ret == DB_LOCK_DEADLOCK);
553
554     }
555
556   if ((ret != 0) && (ret != DB_NOTFOUND))
557     {
558       lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
559       abort();
560     }
561
562   if (ret != 0) return NULL;
563   tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
564
565   if (tempcdb == NULL)
566     {
567       lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
568       abort();
569     }
570
571   tempcdb->len = dret.size;
572   tempcdb->ptr = dret.data;
573   return (tempcdb);
574 }
575
576
577 /*
578  * Free a cdbdata item (ok, this is really no big deal, but we might need to do
579  * more complex stuff with other database managers in the future).
580  */
581 void cdb_free(struct cdbdata *cdb)
582 {
583         phree(cdb->ptr);
584         phree(cdb);
585 }
586
587 void cdb_close_cursor(int cdb)
588 {
589         if (MYCURSORS[cdb] != NULL)
590                 cclose(MYCURSORS[cdb]);
591
592         MYCURSORS[cdb] = NULL;
593 }
594
595 /* 
596  * Prepare for a sequential search of an entire database.
597  * (There is guaranteed to be no more than one traversal in
598  * progress per thread at any given time.)
599  */
600 void cdb_rewind(int cdb)
601 {
602         int ret = 0;
603
604         if (MYCURSORS[cdb] != NULL)
605                 cclose(MYCURSORS[cdb]);
606
607         /*
608          * Now initialize the cursor
609          */
610         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
611         if (ret) {
612                 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
613                 abort();
614         }
615 }
616
617
618 /*
619  * Fetch the next item in a sequential search.  Returns a pointer to a 
620  * cdbdata structure, or NULL if we've hit the end.
621  */
622 struct cdbdata *cdb_next_item(int cdb)
623 {
624         DBT key, data;
625         struct cdbdata *cdbret;
626         int ret = 0;
627
628         /* Initialize the key/data pair so the flags aren't set. */
629         memset(&key, 0, sizeof(key));
630         memset(&data, 0, sizeof(data));
631         data.flags = DB_DBT_MALLOC;
632
633         ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
634                 &key, &data, DB_NEXT);
635         
636         if (ret) {
637                 if (ret != DB_NOTFOUND) {
638                         lprintf(1, "cdb_next_item(%d): %s\n",
639                                 cdb, db_strerror(ret));
640                         abort();
641                 }
642                 cclose(MYCURSORS[cdb]);
643                 MYCURSORS[cdb] = NULL;
644                 return NULL;            /* presumably, end of file */
645         }
646
647         cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
648         cdbret->len = data.size;
649         cdbret->ptr = data.data;
650
651         return (cdbret);
652 }
653
654
655 /*
656  * Transaction-based stuff.  I'm writing this as I bake cookies...
657  */
658
659 void cdb_begin_transaction(void) {
660
661   bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
662
663   if (MYTID != NULL)
664     {
665       lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
666       abort();
667     }
668
669   txbegin(&MYTID);
670 }
671
672 void cdb_end_transaction(void) {
673   int i;
674
675   for (i = 0; i < MAXCDB; i++)
676     if (MYCURSORS[i] != NULL) {
677       lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
678       cclose(MYCURSORS[i]);
679       MYCURSORS[i] = NULL;
680     }
681
682   if (MYTID == NULL)
683     {
684       lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
685       abort();
686     }
687   else
688     txcommit(MYTID);
689
690   MYTID = NULL;
691 }
692