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);
259 * Manually initiate log file cull.
261 void cmd_cull(char *argbuf) {
262 if (CtdlAccessCheck(ac_internal)) return;
264 cprintf("%d Database log file cull completed.\n", CIT_OK);
269 * Request a checkpoint of the database.
271 static void cdb_checkpoint(void)
274 static time_t last_run = 0L;
276 /* Only do a checkpoint once per minute. */
277 if ((time(NULL) - last_run) < 60L) {
280 last_run = time(NULL);
282 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
283 ret = dbenv->txn_checkpoint(dbenv,
284 MAX_CHECKPOINT_KBYTES,
285 MAX_CHECKPOINT_MINUTES, 0);
288 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
293 /* After a successful checkpoint, we can cull the unused logs */
294 if (config.c_auto_cull) {
301 * Main loop for the checkpoint thread.
303 void *checkpoint_thread(void *arg) {
304 struct CitContext checkpointCC;
306 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
308 memset(&checkpointCC, 0, sizeof(struct CitContext));
309 checkpointCC.internal_pgm = 1;
310 checkpointCC.cs_pid = 0;
311 pthread_setspecific(MyConKey, (void *)&checkpointCC );
315 while (!time_to_die) {
320 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
325 * Open the various databases we'll be using. Any database which
326 * does not exist should be created. Note that we don't need a
327 * critical section here, because there aren't any active threads
328 * manipulating the database yet.
330 void open_databases(void)
334 char dbfilename[SIZ];
336 char dbdirname[PATH_MAX];
339 char filename[PATH_MAX];
342 getcwd(dbdirname, sizeof dbdirname);
343 strcat(dbdirname, "/data");
345 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
346 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
347 lprintf(CTDL_INFO, " Linked db: %s\n",
348 db_version(NULL, NULL, NULL));
350 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
354 * Silently try to create the database subdirectory. If it's
355 * already there, no problem.
357 mkdir(dbdirname, 0700);
358 chmod(dbdirname, 0700);
359 chown(dbdirname, CTDLUID, (-1));
361 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
362 db_env_set_func_yield(sched_yield);
363 ret = db_env_create(&dbenv, 0);
365 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
369 dbenv->set_errpfx(dbenv, "citserver");
370 dbenv->set_paniccall(dbenv, dbpanic);
373 * We want to specify the shared memory buffer pool cachesize,
374 * but everything else is the default.
376 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
378 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
380 dbenv->close(dbenv, 0);
384 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
385 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
387 dbenv->close(dbenv, 0);
392 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
393 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
394 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
396 ret = dbenv->open(dbenv, dbdirname, flags, 0);
398 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
400 dbenv->close(dbenv, 0);
404 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
406 for (i = 0; i < MAXCDB; ++i) {
408 /* Create a database handle */
409 ret = db_create(&dbp[i], dbenv, 0);
411 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
417 /* Arbitrary names for our tables -- we reference them by
418 * number, so we don't have string names for them.
420 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
422 ret = dbp[i]->open(dbp[i],
427 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
430 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
436 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
437 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
444 /* Now make sure we own all the files, because in a few milliseconds
445 * we're going to drop root privs.
447 dp = opendir(dbdirname);
449 while (d = readdir(dp), d != NULL) {
450 if (d->d_name[0] != '.') {
451 snprintf(filename, sizeof filename,
452 "%s/%s", dbdirname, d->d_name);
453 chmod(filename, 0600);
454 chown(filename, CTDLUID, (-1));
460 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
462 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
467 * Close all of the db database files we've opened. This can be done
468 * in a loop, since it's just a bunch of closes.
470 void close_databases(void)
477 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
479 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
482 for (a = 0; a < MAXCDB; ++a) {
483 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
484 ret = dbp[a]->close(dbp[a], 0);
487 "cdb_*: db_close: %s\n", db_strerror(ret));
492 /* Close the handle. */
493 ret = dbenv->close(dbenv, 0);
496 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
502 * Compression functions only used if we have zlib
506 void cdb_decompress_if_necessary(struct cdbdata *cdb)
508 static int magic = COMPRESS_MAGIC;
509 struct CtdlCompressHeader zheader;
510 char *uncompressed_data;
511 char *compressed_data;
512 uLongf destLen, sourceLen;
516 if (cdb->ptr == NULL)
518 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
521 /* At this point we know we're looking at a compressed item. */
522 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
524 compressed_data = cdb->ptr;
525 compressed_data += sizeof(struct CtdlCompressHeader);
527 sourceLen = (uLongf) zheader.compressed_len;
528 destLen = (uLongf) zheader.uncompressed_len;
529 uncompressed_data = malloc(zheader.uncompressed_len);
531 if (uncompress((Bytef *) uncompressed_data,
532 (uLongf *) & destLen,
533 (const Bytef *) compressed_data,
534 (uLong) sourceLen) != Z_OK) {
535 lprintf(CTDL_EMERG, "uncompress() error\n");
540 cdb->len = (size_t) destLen;
541 cdb->ptr = uncompressed_data;
544 #endif /* HAVE_ZLIB */
548 * Store a piece of data. Returns 0 if the operation was successful. If a
549 * key already exists it should be overwritten.
551 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
559 struct CtdlCompressHeader zheader;
560 char *compressed_data = NULL;
566 memset(&dkey, 0, sizeof(DBT));
567 memset(&ddata, 0, sizeof(DBT));
570 ddata.size = cdatalen;
574 /* Only compress Visit records. Everything else is uncompressed. */
575 if (cdb == CDB_VISIT) {
577 zheader.magic = COMPRESS_MAGIC;
578 zheader.uncompressed_len = cdatalen;
579 buffer_len = ((cdatalen * 101) / 100) + 100
580 + sizeof(struct CtdlCompressHeader);
581 destLen = (uLongf) buffer_len;
582 compressed_data = malloc(buffer_len);
583 if (compress2((Bytef *) (compressed_data +
585 CtdlCompressHeader)),
586 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
588 lprintf(CTDL_EMERG, "compress2() error\n");
591 zheader.compressed_len = (size_t) destLen;
592 memcpy(compressed_data, &zheader,
593 sizeof(struct CtdlCompressHeader));
594 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
595 zheader.compressed_len);
596 ddata.data = compressed_data;
601 ret = dbp[cdb]->put(dbp[cdb], /* db */
602 MYTID, /* transaction ID */
607 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
613 free(compressed_data);
618 bailIfCursor(MYCURSORS,
619 "attempt to write during r/o cursor");
624 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
625 tid, /* transaction ID */
629 if (ret == DB_LOCK_DEADLOCK) {
633 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
634 cdb, db_strerror(ret));
641 free(compressed_data);
650 * Delete a piece of data. Returns 0 if the operation was successful.
652 int cdb_delete(int cdb, void *key, int keylen)
659 memset(&dkey, 0, sizeof dkey);
664 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
666 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
668 if (ret != DB_NOTFOUND)
672 bailIfCursor(MYCURSORS,
673 "attempt to delete during r/o cursor");
678 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
679 && ret != DB_NOTFOUND) {
680 if (ret == DB_LOCK_DEADLOCK) {
684 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
685 cdb, db_strerror(ret));
695 static DBC *localcursor(int cdb)
700 if (MYCURSORS[cdb] == NULL)
701 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
704 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
708 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
717 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
718 * a struct cdbdata which it is the caller's responsibility to free later on
719 * using the cdb_free() routine.
721 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
724 struct cdbdata *tempcdb;
728 memset(&dkey, 0, sizeof(DBT));
733 memset(&dret, 0, sizeof(DBT));
734 dret.flags = DB_DBT_MALLOC;
735 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
740 memset(&dret, 0, sizeof(DBT));
741 dret.flags = DB_DBT_MALLOC;
743 curs = localcursor(cdb);
745 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
748 while (ret == DB_LOCK_DEADLOCK);
752 if ((ret != 0) && (ret != DB_NOTFOUND)) {
753 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
760 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
762 if (tempcdb == NULL) {
764 "cdb_fetch: Cannot allocate memory for tempcdb\n");
768 tempcdb->len = dret.size;
769 tempcdb->ptr = dret.data;
771 cdb_decompress_if_necessary(tempcdb);
778 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
779 * more complex stuff with other database managers in the future).
781 void cdb_free(struct cdbdata *cdb)
787 void cdb_close_cursor(int cdb)
789 if (MYCURSORS[cdb] != NULL)
790 cclose(MYCURSORS[cdb]);
792 MYCURSORS[cdb] = NULL;
796 * Prepare for a sequential search of an entire database.
797 * (There is guaranteed to be no more than one traversal in
798 * progress per thread at any given time.)
800 void cdb_rewind(int cdb)
804 if (MYCURSORS[cdb] != NULL) {
806 "cdb_rewind: must close cursor on database %d before reopening.\n",
809 /* cclose(MYCURSORS[cdb]); */
813 * Now initialize the cursor
815 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
817 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
825 * Fetch the next item in a sequential search. Returns a pointer to a
826 * cdbdata structure, or NULL if we've hit the end.
828 struct cdbdata *cdb_next_item(int cdb)
831 struct cdbdata *cdbret;
834 /* Initialize the key/data pair so the flags aren't set. */
835 memset(&key, 0, sizeof(key));
836 memset(&data, 0, sizeof(data));
837 data.flags = DB_DBT_MALLOC;
839 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
842 if (ret != DB_NOTFOUND) {
843 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
844 cdb, db_strerror(ret));
847 cclose(MYCURSORS[cdb]);
848 MYCURSORS[cdb] = NULL;
849 return NULL; /* presumably, end of file */
852 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
853 cdbret->len = data.size;
854 cdbret->ptr = data.data;
856 cdb_decompress_if_necessary(cdbret);
865 * Transaction-based stuff. I'm writing this as I bake cookies...
868 void cdb_begin_transaction(void)
871 bailIfCursor(MYCURSORS,
872 "can't begin transaction during r/o cursor");
876 "cdb_begin_transaction: ERROR: nested transaction\n");
883 void cdb_end_transaction(void)
887 for (i = 0; i < MAXCDB; i++)
888 if (MYCURSORS[i] != NULL) {
889 lprintf(CTDL_WARNING,
890 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
892 cclose(MYCURSORS[i]);
898 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
907 * Truncate (delete every record)
909 void cdb_trunc(int cdb)
917 "cdb_trunc must not be called in a transaction.\n");
920 bailIfCursor(MYCURSORS,
921 "attempt to write during r/o cursor");
926 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
927 NULL, /* transaction ID */
928 &count, /* #rows deleted */
930 if (ret == DB_LOCK_DEADLOCK) {
935 "cdb_truncate(%d): %s\n", cdb,