]> code.citadel.org Git - citadel.git/blob - citadel/database_sleepycat.c
0af8b4b5a4200bf3f032567775ddb00c7cb5e35c
[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 ((ret = log_archive(dbenv, &list, flags)) != 0) {
187                 lprintf(1, "cdb_cull_logs: %s\n", db_strerror(ret));
188                 return;
189         }
190
191         /* Print the list of names. */
192         if (list != NULL) {
193                 for (file = list; *file != NULL; ++file) {
194                         lprintf(9, "Deleting log: %s\n", *file);
195                         unlink(*file);
196                 }
197                 free(list);
198         }
199
200         lprintf(5, "Database log file cull ended.\n");
201 }
202
203
204 /*
205  * Request a checkpoint of the database.
206  */
207 static void cdb_checkpoint(void) {
208         int ret;
209         static time_t last_cull = 0L;
210
211         ret = txn_checkpoint(dbenv,
212                                 MAX_CHECKPOINT_KBYTES,
213                                 MAX_CHECKPOINT_MINUTES,
214                                 0);
215         if ( (ret != 0) && (ret != DB_INCOMPLETE) ) {
216                 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n", db_strerror(ret));
217                 abort();
218         }
219
220         if (ret == DB_INCOMPLETE) {
221                 lprintf(3, "WARNING: txn_checkpoint: %s\n", db_strerror(ret));
222         }
223
224         /* Cull the logs if we haven't done so for 24 hours */
225         if ((time(NULL) - last_cull) > 86400L) {
226                 last_cull = time(NULL);
227                 cdb_cull_logs();
228         }
229
230 }
231
232 /*
233  * Open the various databases we'll be using.  Any database which
234  * does not exist should be created.  Note that we don't need an S_DATABASE
235  * critical section here, because there aren't any active threads manipulating
236  * the database yet -- and besides, it causes problems on BSDI.
237  */
238 void open_databases(void)
239 {
240         int ret;
241         int i;
242         char dbfilename[SIZ];
243         u_int32_t flags = 0;
244
245         lprintf(9, "cdb_*: open_databases() starting\n");
246         /*
247          * Silently try to create the database subdirectory.  If it's
248          * already there, no problem.
249          */
250         system("exec mkdir data 2>/dev/null");
251
252         lprintf(9, "cdb_*: Setting up DB environment\n");
253         db_env_set_func_yield(sched_yield);
254         ret = db_env_create(&dbenv, 0);
255         if (ret) {
256                 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
257                 exit(ret);
258         }
259         dbenv->set_errpfx(dbenv, "citserver");
260
261         /*
262          * We want to specify the shared memory buffer pool cachesize,
263          * but everything else is the default.
264          */
265         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
266         if (ret) {
267                 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
268                 dbenv->close(dbenv, 0);
269                 exit(ret);
270         }
271
272         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
273                 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
274                 dbenv->close(dbenv, 0);
275                 exit(ret);
276         }
277
278         flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
279                 DB_INIT_LOCK|DB_THREAD;
280         ret = dbenv->open(dbenv, "./data", flags, 0);
281         if (ret) {
282                 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
283                 dbenv->close(dbenv, 0);
284                 exit(ret);
285         }
286
287         lprintf(7, "cdb_*: Starting up DB\n");
288
289         for (i = 0; i < MAXCDB; ++i) {
290
291                 /* Create a database handle */
292                 ret = db_create(&dbp[i], dbenv, 0);
293                 if (ret) {
294                         lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
295                         exit(ret);
296                 }
297
298
299                 /* Arbitrary names for our tables -- we reference them by
300                  * number, so we don't have string names for them.
301                  */
302                 sprintf(dbfilename, "cdb.%02x", i);
303
304                 ret = dbp[i]->open(dbp[i],
305                                 dbfilename,
306                                 NULL,
307                                 DB_BTREE,
308                                 DB_CREATE|DB_THREAD,
309                                 0600);
310                 if (ret) {
311                         lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
312                         exit(ret);
313                 }
314         }
315
316         if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
317                 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
318                 exit(1);
319         }
320
321         cdb_allocate_tsd();
322         CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
323         lprintf(9, "cdb_*: open_databases() finished\n");
324 }
325
326
327 /*
328  * Close all of the db database files we've opened.  This can be done
329  * in a loop, since it's just a bunch of closes.
330  */
331 void close_databases(void)
332 {
333         int a;
334         int ret;
335
336         cdb_free_tsd();
337
338         if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
339                 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
340                 abort();
341         }
342
343         for (a = 0; a < MAXCDB; ++a) {
344                 lprintf(7, "cdb_*: Closing database %d\n", a);
345                 ret = dbp[a]->close(dbp[a], 0);
346                 if (ret) {
347                         lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
348                         abort();
349                 }
350                 
351         }
352
353         /* Close the handle. */
354         ret = dbenv->close(dbenv, 0);
355         if (ret) {
356                 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
357                 abort();
358         }
359 }
360
361 /*
362  * Store a piece of data.  Returns 0 if the operation was successful.  If a
363  * key already exists it should be overwritten.
364  */
365 int cdb_store(int cdb,
366               void *ckey, int ckeylen,
367               void *cdata, int cdatalen)
368 {
369
370   DBT dkey, ddata;
371   DB_TXN *tid;
372   int ret;
373   
374   memset(&dkey, 0, sizeof(DBT));
375   memset(&ddata, 0, sizeof(DBT));
376   dkey.size = ckeylen;
377   dkey.data = ckey;
378   ddata.size = cdatalen;
379   ddata.data = cdata;
380   
381   if (MYTID != NULL)
382     {
383       ret = dbp[cdb]->put(dbp[cdb],             /* db */
384                           MYTID,                /* transaction ID */
385                           &dkey,                /* key */
386                           &ddata,               /* data */
387                           0);           /* flags */
388       if (ret)
389         {
390           lprintf(1, "cdb_store(%d): %s\n", cdb,
391                   db_strerror(ret));
392           abort();
393         }
394       return ret;
395       
396     }
397   else
398     {
399       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
400       
401     retry:
402       txbegin(&tid);
403       
404       if ((ret = dbp[cdb]->put(dbp[cdb],    /* db */
405                                tid,         /* transaction ID */
406                                &dkey,       /* key */
407                                &ddata,      /* data */
408                                0)))         /* flags */
409         {
410           if (ret == DB_LOCK_DEADLOCK)
411             {
412               txabort(tid);
413               goto retry;
414             }
415           else
416             {
417               lprintf(1, "cdb_store(%d): %s\n", cdb,
418                       db_strerror(ret));
419               abort();
420             }
421         }
422       else
423         {
424           txcommit(tid);
425           return ret;
426         }
427     }
428 }
429
430
431 /*
432  * Delete a piece of data.  Returns 0 if the operation was successful.
433  */
434 int cdb_delete(int cdb, void *key, int keylen)
435 {
436
437   DBT dkey;
438   DB_TXN *tid;
439   int ret;
440
441   memset(&dkey, 0, sizeof dkey);
442   dkey.size = keylen;
443   dkey.data = key;
444
445   if (MYTID != NULL)
446     {
447       ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
448       if (ret)
449         {
450           lprintf(1, "cdb_delete(%d): %s\n", cdb,
451                   db_strerror(ret));
452           if (ret != DB_NOTFOUND)
453             abort();
454         }
455     }
456   else
457     {
458       bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
459     
460     retry:
461       txbegin(&tid);
462     
463       if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
464           && ret != DB_NOTFOUND)
465         {
466           if (ret == DB_LOCK_DEADLOCK)
467             {
468               txabort(tid);
469               goto retry;
470             }
471           else
472             {
473               lprintf(1, "cdb_delete(%d): %s\n", cdb,
474                       db_strerror(ret));
475               abort();
476             }
477         }
478       else
479         {
480           txcommit(tid);
481         }
482     }
483   return ret;
484 }
485
486 static DBC *localcursor(int cdb)
487 {
488   int ret;
489   DBC *curs;
490
491   if (MYCURSORS[cdb] == NULL)
492     ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
493   else
494     ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
495
496   if (ret)
497     {
498       lprintf(1, "localcursor: %s\n", db_strerror(ret));
499       abort();
500     }
501
502   return curs;
503 }
504
505
506 /*
507  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
508  * a struct cdbdata which it is the caller's responsibility to free later on
509  * using the cdb_free() routine.
510  */
511 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
512 {
513
514   struct cdbdata *tempcdb;
515   DBT dkey, dret;
516   int ret;
517
518   memset(&dkey, 0, sizeof(DBT));
519   dkey.size = keylen;
520   dkey.data = key;
521
522   if (MYTID != NULL)
523     {
524       memset(&dret, 0, sizeof(DBT));
525       dret.flags = DB_DBT_MALLOC;
526       ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
527     }
528   else
529     {
530       DBC *curs;
531
532       do
533         {
534           memset(&dret, 0, sizeof(DBT));
535           dret.flags = DB_DBT_MALLOC;
536
537           curs = localcursor(cdb);
538
539           ret = curs->c_get(curs, &dkey, &dret, DB_SET);
540           cclose(curs);
541         }
542       while (ret == DB_LOCK_DEADLOCK);
543
544     }
545
546   if ((ret != 0) && (ret != DB_NOTFOUND))
547     {
548       lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
549       abort();
550     }
551
552   if (ret != 0) return NULL;
553   tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
554
555   if (tempcdb == NULL)
556     {
557       lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
558       abort();
559     }
560
561   tempcdb->len = dret.size;
562   tempcdb->ptr = dret.data;
563   return (tempcdb);
564 }
565
566
567 /*
568  * Free a cdbdata item (ok, this is really no big deal, but we might need to do
569  * more complex stuff with other database managers in the future).
570  */
571 void cdb_free(struct cdbdata *cdb)
572 {
573         phree(cdb->ptr);
574         phree(cdb);
575 }
576
577 void cdb_close_cursor(int cdb)
578 {
579         if (MYCURSORS[cdb] != NULL)
580                 cclose(MYCURSORS[cdb]);
581
582         MYCURSORS[cdb] = NULL;
583 }
584
585 /* 
586  * Prepare for a sequential search of an entire database.
587  * (There is guaranteed to be no more than one traversal in
588  * progress per thread at any given time.)
589  */
590 void cdb_rewind(int cdb)
591 {
592         int ret = 0;
593
594         if (MYCURSORS[cdb] != NULL)
595                 cclose(MYCURSORS[cdb]);
596
597         /*
598          * Now initialize the cursor
599          */
600         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
601         if (ret) {
602                 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
603                 abort();
604         }
605 }
606
607
608 /*
609  * Fetch the next item in a sequential search.  Returns a pointer to a 
610  * cdbdata structure, or NULL if we've hit the end.
611  */
612 struct cdbdata *cdb_next_item(int cdb)
613 {
614         DBT key, data;
615         struct cdbdata *cdbret;
616         int ret = 0;
617
618         /* Initialize the key/data pair so the flags aren't set. */
619         memset(&key, 0, sizeof(key));
620         memset(&data, 0, sizeof(data));
621         data.flags = DB_DBT_MALLOC;
622
623         ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
624                 &key, &data, DB_NEXT);
625         
626         if (ret) {
627                 if (ret != DB_NOTFOUND) {
628                         lprintf(1, "cdb_next_item(%d): %s\n",
629                                 cdb, db_strerror(ret));
630                         abort();
631                 }
632                 cclose(MYCURSORS[cdb]);
633                 MYCURSORS[cdb] = NULL;
634                 return NULL;            /* presumably, end of file */
635         }
636
637         cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
638         cdbret->len = data.size;
639         cdbret->ptr = data.data;
640
641         return (cdbret);
642 }
643
644
645 /*
646  * Transaction-based stuff.  I'm writing this as I bake cookies...
647  */
648
649 void cdb_begin_transaction(void) {
650
651   bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
652
653   if (MYTID != NULL)
654     {
655       lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
656       abort();
657     }
658
659   txbegin(&MYTID);
660 }
661
662 void cdb_end_transaction(void) {
663   int i;
664
665   for (i = 0; i < MAXCDB; i++)
666     if (MYCURSORS[i] != NULL) {
667       lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
668       cclose(MYCURSORS[i]);
669       MYCURSORS[i] = NULL;
670     }
671
672   if (MYTID == NULL)
673     {
674       lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
675       abort();
676     }
677   else
678     txcommit(MYTID);
679
680   MYTID = NULL;
681 }
682