4 * Sleepycat (Berkeley) DB driver for Citadel
8 /*****************************************************************************
9 Tunable configuration parameters for the Sleepycat DB back end
10 *****************************************************************************/
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.
16 #define MAX_CHECKPOINT_KBYTES 256
17 #define MAX_CHECKPOINT_MINUTES 15
19 /*****************************************************************************/
32 #include <sys/types.h>
38 #elif defined(HAVE_DB4_DB_H)
41 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
45 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
46 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
53 #include "serv_extensions.h"
54 #include "citserver.h"
57 #include "sysdep_decls.h"
60 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
61 static DB_ENV *dbenv; /* The DB environment (global) */
63 struct cdbtsd { /* Thread-specific DB stuff */
64 DB_TXN *tid; /* Transaction handle */
65 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
72 static pthread_key_t tsdkey;
74 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
75 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
77 /* just a little helper function */
78 static void txabort(DB_TXN * tid)
82 ret = tid->abort(tid);
85 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
91 /* this one is even more helpful than the last. */
92 static void txcommit(DB_TXN * tid)
96 ret = tid->commit(tid, 0);
99 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
105 /* are you sensing a pattern yet? */
106 static void txbegin(DB_TXN ** tid)
110 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
113 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
119 static void dbpanic(DB_ENV * env, int errval)
121 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
124 static void cclose(DBC * cursor)
128 if ((ret = cursor->c_close(cursor))) {
129 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
135 static void bailIfCursor(DBC ** cursors, const char *msg)
139 for (i = 0; i < MAXCDB; i++)
140 if (cursors[i] != NULL) {
142 "cdb_*: cursor still in progress on cdb %d: %s\n",
148 static void check_handles(void *arg)
151 struct cdbtsd *tsd = (struct cdbtsd *) arg;
153 bailIfCursor(tsd->cursors, "in check_handles");
155 if (tsd->tid != NULL) {
157 "cdb_*: transaction still in progress!");
163 static void dest_tsd(void *arg)
172 * Ensure that we have a key for thread-specific data. We don't
173 * put anything in here that Citadel cares about; this is just database
174 * related stuff like cursors and transactions.
176 * This should be called immediately after startup by any thread which wants
177 * to use database calls, except for whatever thread calls open_databases.
179 void cdb_allocate_tsd(void)
183 if (pthread_getspecific(tsdkey) != NULL)
186 tsd = malloc(sizeof(struct cdbtsd));
190 memset(tsd->cursors, 0, sizeof tsd->cursors);
191 pthread_setspecific(tsdkey, tsd);
194 void cdb_free_tsd(void)
196 dest_tsd(pthread_getspecific(tsdkey));
197 pthread_setspecific(tsdkey, NULL);
200 void cdb_check_handles(void)
202 check_handles(pthread_getspecific(tsdkey));
207 * Reclaim unused space in the databases. We need to do each one of
208 * these discretely, rather than in a loop.
210 * This is a stub function in the Sleepycat DB backend, because there is no
211 * such API call available.
213 void defrag_databases(void)
220 * Cull the database logs
222 static void cdb_cull_logs(void)
231 /* Get the list of names. */
232 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
233 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
237 /* Print the list of names. */
239 for (file = list; *file != NULL; ++file) {
240 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
243 snprintf(errmsg, sizeof(errmsg),
244 " ** ERROR **\n \n \n "
245 "Citadel was unable to delete the "
246 "database log file '%s' because of the "
247 "following error:\n \n %s\n \n"
248 " This log file is no longer in use "
249 "and may be safely deleted.\n",
250 *file, strerror(errno));
251 aide_message(errmsg);
260 * Request a checkpoint of the database.
262 static void cdb_checkpoint(void)
265 static time_t last_run = 0L;
267 /* Only do a checkpoint once per minute. */
268 if ((time(NULL) - last_run) < 60L) {
271 last_run = time(NULL);
273 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
274 ret = dbenv->txn_checkpoint(dbenv,
275 MAX_CHECKPOINT_KBYTES,
276 MAX_CHECKPOINT_MINUTES, 0);
279 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
284 /* After a successful checkpoint, we can cull the unused logs */
285 if (config.c_auto_cull) {
292 * Main loop for the checkpoint thread.
294 void *checkpoint_thread(void *arg) {
295 struct CitContext checkpointCC;
297 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
299 memset(&checkpointCC, 0, sizeof(struct CitContext));
300 checkpointCC.internal_pgm = 1;
301 checkpointCC.cs_pid = 0;
302 pthread_setspecific(MyConKey, (void *)&checkpointCC );
306 while (!time_to_die) {
311 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
316 * Open the various databases we'll be using. Any database which
317 * does not exist should be created. Note that we don't need a
318 * critical section here, because there aren't any active threads
319 * manipulating the database yet.
321 void open_databases(void)
325 char dbfilename[SIZ];
327 char dbdirname[PATH_MAX];
330 char filename[PATH_MAX];
333 getcwd(dbdirname, sizeof dbdirname);
334 strcat(dbdirname, "/data");
336 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
337 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
338 lprintf(CTDL_INFO, " Linked db: %s\n",
339 db_version(NULL, NULL, NULL));
341 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
345 * Silently try to create the database subdirectory. If it's
346 * already there, no problem.
348 mkdir(dbdirname, 0700);
349 chmod(dbdirname, 0700);
350 chown(dbdirname, CTDLUID, (-1));
352 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
353 db_env_set_func_yield(sched_yield);
354 ret = db_env_create(&dbenv, 0);
356 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
360 dbenv->set_errpfx(dbenv, "citserver");
361 dbenv->set_paniccall(dbenv, dbpanic);
364 * We want to specify the shared memory buffer pool cachesize,
365 * but everything else is the default.
367 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
369 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
371 dbenv->close(dbenv, 0);
375 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
376 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
378 dbenv->close(dbenv, 0);
383 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
384 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
385 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
387 ret = dbenv->open(dbenv, dbdirname, flags, 0);
389 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
391 dbenv->close(dbenv, 0);
395 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
397 for (i = 0; i < MAXCDB; ++i) {
399 /* Create a database handle */
400 ret = db_create(&dbp[i], dbenv, 0);
402 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
408 /* Arbitrary names for our tables -- we reference them by
409 * number, so we don't have string names for them.
411 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
413 ret = dbp[i]->open(dbp[i],
418 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
421 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
427 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
428 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
435 /* Now make sure we own all the files, because in a few milliseconds
436 * we're going to drop root privs.
438 dp = opendir(dbdirname);
440 while (d = readdir(dp), d != NULL) {
441 if (d->d_name[0] != '.') {
442 snprintf(filename, sizeof filename,
443 "%s/%s", dbdirname, d->d_name);
444 chmod(filename, 0600);
445 chown(filename, CTDLUID, (-1));
451 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
456 * Close all of the db database files we've opened. This can be done
457 * in a loop, since it's just a bunch of closes.
459 void close_databases(void)
466 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
468 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
471 for (a = 0; a < MAXCDB; ++a) {
472 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
473 ret = dbp[a]->close(dbp[a], 0);
476 "cdb_*: db_close: %s\n", db_strerror(ret));
481 /* Close the handle. */
482 ret = dbenv->close(dbenv, 0);
485 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
491 * Compression functions only used if we have zlib
495 void cdb_decompress_if_necessary(struct cdbdata *cdb)
497 static int magic = COMPRESS_MAGIC;
498 struct CtdlCompressHeader zheader;
499 char *uncompressed_data;
500 char *compressed_data;
501 uLongf destLen, sourceLen;
505 if (cdb->ptr == NULL)
507 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
510 /* At this point we know we're looking at a compressed item. */
511 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
513 compressed_data = cdb->ptr;
514 compressed_data += sizeof(struct CtdlCompressHeader);
516 sourceLen = (uLongf) zheader.compressed_len;
517 destLen = (uLongf) zheader.uncompressed_len;
518 uncompressed_data = malloc(zheader.uncompressed_len);
520 if (uncompress((Bytef *) uncompressed_data,
521 (uLongf *) & destLen,
522 (const Bytef *) compressed_data,
523 (uLong) sourceLen) != Z_OK) {
524 lprintf(CTDL_EMERG, "uncompress() error\n");
529 cdb->len = (size_t) destLen;
530 cdb->ptr = uncompressed_data;
533 #endif /* HAVE_ZLIB */
537 * Store a piece of data. Returns 0 if the operation was successful. If a
538 * key already exists it should be overwritten.
540 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
548 struct CtdlCompressHeader zheader;
549 char *compressed_data = NULL;
555 memset(&dkey, 0, sizeof(DBT));
556 memset(&ddata, 0, sizeof(DBT));
559 ddata.size = cdatalen;
563 /* Only compress Visit records. Everything else is uncompressed. */
564 if (cdb == CDB_VISIT) {
566 zheader.magic = COMPRESS_MAGIC;
567 zheader.uncompressed_len = cdatalen;
568 buffer_len = ((cdatalen * 101) / 100) + 100
569 + sizeof(struct CtdlCompressHeader);
570 destLen = (uLongf) buffer_len;
571 compressed_data = malloc(buffer_len);
572 if (compress2((Bytef *) (compressed_data +
574 CtdlCompressHeader)),
575 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
577 lprintf(CTDL_EMERG, "compress2() error\n");
580 zheader.compressed_len = (size_t) destLen;
581 memcpy(compressed_data, &zheader,
582 sizeof(struct CtdlCompressHeader));
583 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
584 zheader.compressed_len);
585 ddata.data = compressed_data;
590 ret = dbp[cdb]->put(dbp[cdb], /* db */
591 MYTID, /* transaction ID */
596 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
602 free(compressed_data);
607 bailIfCursor(MYCURSORS,
608 "attempt to write during r/o cursor");
613 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
614 tid, /* transaction ID */
618 if (ret == DB_LOCK_DEADLOCK) {
622 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
623 cdb, db_strerror(ret));
630 free(compressed_data);
639 * Delete a piece of data. Returns 0 if the operation was successful.
641 int cdb_delete(int cdb, void *key, int keylen)
648 memset(&dkey, 0, sizeof dkey);
653 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
655 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
657 if (ret != DB_NOTFOUND)
661 bailIfCursor(MYCURSORS,
662 "attempt to delete during r/o cursor");
667 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
668 && ret != DB_NOTFOUND) {
669 if (ret == DB_LOCK_DEADLOCK) {
673 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
674 cdb, db_strerror(ret));
684 static DBC *localcursor(int cdb)
689 if (MYCURSORS[cdb] == NULL)
690 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
693 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
697 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
706 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
707 * a struct cdbdata which it is the caller's responsibility to free later on
708 * using the cdb_free() routine.
710 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
713 struct cdbdata *tempcdb;
717 memset(&dkey, 0, sizeof(DBT));
722 memset(&dret, 0, sizeof(DBT));
723 dret.flags = DB_DBT_MALLOC;
724 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
729 memset(&dret, 0, sizeof(DBT));
730 dret.flags = DB_DBT_MALLOC;
732 curs = localcursor(cdb);
734 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
737 while (ret == DB_LOCK_DEADLOCK);
741 if ((ret != 0) && (ret != DB_NOTFOUND)) {
742 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
749 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
751 if (tempcdb == NULL) {
753 "cdb_fetch: Cannot allocate memory for tempcdb\n");
757 tempcdb->len = dret.size;
758 tempcdb->ptr = dret.data;
760 cdb_decompress_if_necessary(tempcdb);
767 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
768 * more complex stuff with other database managers in the future).
770 void cdb_free(struct cdbdata *cdb)
776 void cdb_close_cursor(int cdb)
778 if (MYCURSORS[cdb] != NULL)
779 cclose(MYCURSORS[cdb]);
781 MYCURSORS[cdb] = NULL;
785 * Prepare for a sequential search of an entire database.
786 * (There is guaranteed to be no more than one traversal in
787 * progress per thread at any given time.)
789 void cdb_rewind(int cdb)
793 if (MYCURSORS[cdb] != NULL) {
795 "cdb_rewind: must close cursor on database %d before reopening.\n",
798 /* cclose(MYCURSORS[cdb]); */
802 * Now initialize the cursor
804 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
806 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
814 * Fetch the next item in a sequential search. Returns a pointer to a
815 * cdbdata structure, or NULL if we've hit the end.
817 struct cdbdata *cdb_next_item(int cdb)
820 struct cdbdata *cdbret;
823 /* Initialize the key/data pair so the flags aren't set. */
824 memset(&key, 0, sizeof(key));
825 memset(&data, 0, sizeof(data));
826 data.flags = DB_DBT_MALLOC;
828 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
831 if (ret != DB_NOTFOUND) {
832 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
833 cdb, db_strerror(ret));
836 cclose(MYCURSORS[cdb]);
837 MYCURSORS[cdb] = NULL;
838 return NULL; /* presumably, end of file */
841 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
842 cdbret->len = data.size;
843 cdbret->ptr = data.data;
845 cdb_decompress_if_necessary(cdbret);
854 * Transaction-based stuff. I'm writing this as I bake cookies...
857 void cdb_begin_transaction(void)
860 bailIfCursor(MYCURSORS,
861 "can't begin transaction during r/o cursor");
865 "cdb_begin_transaction: ERROR: nested transaction\n");
872 void cdb_end_transaction(void)
876 for (i = 0; i < MAXCDB; i++)
877 if (MYCURSORS[i] != NULL) {
878 lprintf(CTDL_WARNING,
879 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
881 cclose(MYCURSORS[i]);
887 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
896 * Truncate (delete every record)
898 void cdb_trunc(int cdb)
906 "cdb_trunc must not be called in a transaction.\n");
909 bailIfCursor(MYCURSORS,
910 "attempt to write during r/o cursor");
915 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
916 NULL, /* transaction ID */
917 &count, /* #rows deleted */
919 if (ret == DB_LOCK_DEADLOCK) {
924 "cdb_truncate(%d): %s\n", cdb,