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);
257 lprintf(CTDL_INFO, "Database log file cull ended.\n");
262 * Request a checkpoint of the database.
264 static void cdb_checkpoint(void)
267 /* static time_t last_cull = 0L; */
269 ret = dbenv->txn_checkpoint(dbenv,
270 MAX_CHECKPOINT_KBYTES,
271 MAX_CHECKPOINT_MINUTES, 0);
274 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
279 /* After a successful checkpoint, we can cull the unused logs */
282 /* Cull the logs if we haven't done so for 24 hours
283 if ((time(NULL) - last_cull) > 86400L) {
284 last_cull = time(NULL);
291 * Open the various databases we'll be using. Any database which
292 * does not exist should be created. Note that we don't need a
293 * critical section here, because there aren't any active threads
294 * manipulating the database yet.
296 void open_databases(void)
300 char dbfilename[SIZ];
302 char dbdirname[PATH_MAX];
305 char filename[PATH_MAX];
308 getcwd(dbdirname, sizeof dbdirname);
309 strcat(dbdirname, "/data");
311 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
312 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
313 lprintf(CTDL_INFO, " Linked db: %s\n",
314 db_version(NULL, NULL, NULL));
316 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
320 * Silently try to create the database subdirectory. If it's
321 * already there, no problem.
323 mkdir(dbdirname, 0700);
324 chmod(dbdirname, 0700);
325 chown(dbdirname, CTDLUID, (-1));
327 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
328 db_env_set_func_yield(sched_yield);
329 ret = db_env_create(&dbenv, 0);
331 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
335 dbenv->set_errpfx(dbenv, "citserver");
336 dbenv->set_paniccall(dbenv, dbpanic);
339 * We want to specify the shared memory buffer pool cachesize,
340 * but everything else is the default.
342 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
344 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
346 dbenv->close(dbenv, 0);
350 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
351 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
353 dbenv->close(dbenv, 0);
358 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
359 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
360 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
362 ret = dbenv->open(dbenv, dbdirname, flags, 0);
364 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
366 dbenv->close(dbenv, 0);
370 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
372 for (i = 0; i < MAXCDB; ++i) {
374 /* Create a database handle */
375 ret = db_create(&dbp[i], dbenv, 0);
377 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
383 /* Arbitrary names for our tables -- we reference them by
384 * number, so we don't have string names for them.
386 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
388 ret = dbp[i]->open(dbp[i],
393 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
396 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
402 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
403 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
409 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
411 /* Now make sure we own all the files, because in a few milliseconds
412 * we're going to drop root privs.
414 dp = opendir(dbdirname);
416 while (d = readdir(dp), d != NULL) {
417 if (d->d_name[0] != '.') {
418 snprintf(filename, sizeof filename,
419 "%s/%s", dbdirname, d->d_name);
420 chmod(filename, 0600);
421 chown(filename, CTDLUID, (-1));
427 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
432 * Close all of the db database files we've opened. This can be done
433 * in a loop, since it's just a bunch of closes.
435 void close_databases(void)
442 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
444 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
447 for (a = 0; a < MAXCDB; ++a) {
448 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
449 ret = dbp[a]->close(dbp[a], 0);
452 "cdb_*: db_close: %s\n", db_strerror(ret));
457 /* Close the handle. */
458 ret = dbenv->close(dbenv, 0);
461 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
467 * Compression functions only used if we have zlib
471 void cdb_decompress_if_necessary(struct cdbdata *cdb)
473 static int magic = COMPRESS_MAGIC;
474 struct CtdlCompressHeader zheader;
475 char *uncompressed_data;
476 char *compressed_data;
477 uLongf destLen, sourceLen;
481 if (cdb->ptr == NULL)
483 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
486 /* At this point we know we're looking at a compressed item. */
487 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
489 compressed_data = cdb->ptr;
490 compressed_data += sizeof(struct CtdlCompressHeader);
492 sourceLen = (uLongf) zheader.compressed_len;
493 destLen = (uLongf) zheader.uncompressed_len;
494 uncompressed_data = malloc(zheader.uncompressed_len);
496 if (uncompress((Bytef *) uncompressed_data,
497 (uLongf *) & destLen,
498 (const Bytef *) compressed_data,
499 (uLong) sourceLen) != Z_OK) {
500 lprintf(CTDL_EMERG, "uncompress() error\n");
505 cdb->len = (size_t) destLen;
506 cdb->ptr = uncompressed_data;
509 #endif /* HAVE_ZLIB */
513 * Store a piece of data. Returns 0 if the operation was successful. If a
514 * key already exists it should be overwritten.
516 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
524 struct CtdlCompressHeader zheader;
525 char *compressed_data = NULL;
531 memset(&dkey, 0, sizeof(DBT));
532 memset(&ddata, 0, sizeof(DBT));
535 ddata.size = cdatalen;
539 /* Only compress Visit records. Everything else is uncompressed. */
540 if (cdb == CDB_VISIT) {
542 zheader.magic = COMPRESS_MAGIC;
543 zheader.uncompressed_len = cdatalen;
544 buffer_len = ((cdatalen * 101) / 100) + 100
545 + sizeof(struct CtdlCompressHeader);
546 destLen = (uLongf) buffer_len;
547 compressed_data = malloc(buffer_len);
548 if (compress2((Bytef *) (compressed_data +
550 CtdlCompressHeader)),
551 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
553 lprintf(CTDL_EMERG, "compress2() error\n");
556 zheader.compressed_len = (size_t) destLen;
557 memcpy(compressed_data, &zheader,
558 sizeof(struct CtdlCompressHeader));
559 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
560 zheader.compressed_len);
561 ddata.data = compressed_data;
566 ret = dbp[cdb]->put(dbp[cdb], /* db */
567 MYTID, /* transaction ID */
572 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
578 free(compressed_data);
583 bailIfCursor(MYCURSORS,
584 "attempt to write during r/o cursor");
589 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
590 tid, /* transaction ID */
594 if (ret == DB_LOCK_DEADLOCK) {
598 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
599 cdb, db_strerror(ret));
606 free(compressed_data);
615 * Delete a piece of data. Returns 0 if the operation was successful.
617 int cdb_delete(int cdb, void *key, int keylen)
624 memset(&dkey, 0, sizeof dkey);
629 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
631 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
633 if (ret != DB_NOTFOUND)
637 bailIfCursor(MYCURSORS,
638 "attempt to delete during r/o cursor");
643 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
644 && ret != DB_NOTFOUND) {
645 if (ret == DB_LOCK_DEADLOCK) {
649 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
650 cdb, db_strerror(ret));
660 static DBC *localcursor(int cdb)
665 if (MYCURSORS[cdb] == NULL)
666 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
669 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
673 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
682 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
683 * a struct cdbdata which it is the caller's responsibility to free later on
684 * using the cdb_free() routine.
686 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
689 struct cdbdata *tempcdb;
693 memset(&dkey, 0, sizeof(DBT));
698 memset(&dret, 0, sizeof(DBT));
699 dret.flags = DB_DBT_MALLOC;
700 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
705 memset(&dret, 0, sizeof(DBT));
706 dret.flags = DB_DBT_MALLOC;
708 curs = localcursor(cdb);
710 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
713 while (ret == DB_LOCK_DEADLOCK);
717 if ((ret != 0) && (ret != DB_NOTFOUND)) {
718 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
725 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
727 if (tempcdb == NULL) {
729 "cdb_fetch: Cannot allocate memory for tempcdb\n");
733 tempcdb->len = dret.size;
734 tempcdb->ptr = dret.data;
736 cdb_decompress_if_necessary(tempcdb);
743 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
744 * more complex stuff with other database managers in the future).
746 void cdb_free(struct cdbdata *cdb)
752 void cdb_close_cursor(int cdb)
754 if (MYCURSORS[cdb] != NULL)
755 cclose(MYCURSORS[cdb]);
757 MYCURSORS[cdb] = NULL;
761 * Prepare for a sequential search of an entire database.
762 * (There is guaranteed to be no more than one traversal in
763 * progress per thread at any given time.)
765 void cdb_rewind(int cdb)
769 if (MYCURSORS[cdb] != NULL) {
771 "cdb_rewind: must close cursor on database %d before reopening.\n",
774 /* cclose(MYCURSORS[cdb]); */
778 * Now initialize the cursor
780 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
782 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
790 * Fetch the next item in a sequential search. Returns a pointer to a
791 * cdbdata structure, or NULL if we've hit the end.
793 struct cdbdata *cdb_next_item(int cdb)
796 struct cdbdata *cdbret;
799 /* Initialize the key/data pair so the flags aren't set. */
800 memset(&key, 0, sizeof(key));
801 memset(&data, 0, sizeof(data));
802 data.flags = DB_DBT_MALLOC;
804 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
807 if (ret != DB_NOTFOUND) {
808 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
809 cdb, db_strerror(ret));
812 cclose(MYCURSORS[cdb]);
813 MYCURSORS[cdb] = NULL;
814 return NULL; /* presumably, end of file */
817 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
818 cdbret->len = data.size;
819 cdbret->ptr = data.data;
821 cdb_decompress_if_necessary(cdbret);
830 * Transaction-based stuff. I'm writing this as I bake cookies...
833 void cdb_begin_transaction(void)
836 bailIfCursor(MYCURSORS,
837 "can't begin transaction during r/o cursor");
841 "cdb_begin_transaction: ERROR: nested transaction\n");
848 void cdb_end_transaction(void)
852 for (i = 0; i < MAXCDB; i++)
853 if (MYCURSORS[i] != NULL) {
854 lprintf(CTDL_WARNING,
855 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
857 cclose(MYCURSORS[i]);
863 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
872 * Truncate (delete every record)
874 void cdb_trunc(int cdb)
882 "cdb_trunc must not be called in a transaction.\n");
885 bailIfCursor(MYCURSORS,
886 "attempt to write during r/o cursor");
891 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
892 NULL, /* transaction ID */
893 &count, /* #rows deleted */
895 if (ret == DB_LOCK_DEADLOCK) {
900 "cdb_truncate(%d): %s\n", cdb,