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