* Compress VISIT records using zlib if available. This reduces the object
[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
36 #ifdef HAVE_DB_H
37 #include <db.h>
38 #elif defined(HAVE_DB4_DB_H)
39 #include <db4/db.h>
40 #elif defined(HAVE_DB3_DB_H)
41 #include <db3/db.h>
42 #else
43 #error Neither <db.h> nor <db3/db.h> was found by configure. Install db3-devel.
44 #endif
45
46 #include <pthread.h>
47 #include "citadel.h"
48 #include "server.h"
49 #include "dynloader.h"
50 #include "citserver.h"
51 #include "database.h"
52 #include "msgbase.h"
53 #include "sysdep_decls.h"
54
55 static DB *dbp[MAXCDB];         /* One DB handle for each Citadel database */
56 static DB_ENV *dbenv;           /* The DB environment (global) */
57
58 struct cdbtsd {                 /* Thread-specific DB stuff */
59         DB_TXN *tid;            /* Transaction handle */
60         DBC *cursors[MAXCDB];   /* Cursors, for traversals... */
61 };
62
63 #ifdef HAVE_ZLIB
64 #include <zlib.h>
65 #endif
66
67 static pthread_key_t tsdkey;
68
69 #define MYCURSORS       (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
70 #define MYTID           (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
71
72 /* just a little helper function */
73 static void txabort(DB_TXN *tid) {
74         int ret = txn_abort(tid);
75
76         if (ret) {
77                 lprintf(1, "cdb_*: txn_abort: %s\n", db_strerror(ret));
78                 abort();
79         }
80 }
81
82 /* this one is even more helpful than the last. */
83 static void txcommit(DB_TXN *tid) {
84         int ret = txn_commit(tid, 0);
85
86         if (ret) {
87                 lprintf(1, "cdb_*: txn_commit: %s\n", db_strerror(ret));
88                 abort();
89         }
90 }
91
92 /* are you sensing a pattern yet? */
93 static void txbegin(DB_TXN **tid) {
94         int ret = txn_begin(dbenv, NULL, tid, 0);
95
96         if (ret) {
97                 lprintf(1, "cdb_*: txn_begin: %s\n", db_strerror(ret));
98                 abort();
99         }
100 }
101
102 static void cclose(DBC *cursor) {
103         int ret;
104
105         if ((ret = cursor->c_close(cursor))) {
106                 lprintf(1, "cdb_*: c_close: %s\n", db_strerror(ret));
107                 abort();
108         }
109 }
110
111 static void bailIfCursor(DBC **cursors, const char *msg)
112 {
113   int i;
114
115   for (i = 0; i < MAXCDB; i++)
116     if (cursors[i] != NULL)
117       {
118         lprintf(1, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
119         abort();
120       }
121 }
122
123 static void check_handles(void *arg) {
124         if (arg != NULL) {
125                 struct cdbtsd *tsd = (struct cdbtsd *)arg;
126
127                 bailIfCursor(tsd->cursors, "in check_handles");
128
129                 if (tsd->tid != NULL) {
130                         lprintf(1, "cdb_*: transaction still in progress!");
131                         abort();
132                 }
133         }
134 }
135
136 static void dest_tsd(void *arg) {
137         if (arg != NULL) {
138                 check_handles(arg);
139                 phree(arg);
140         }
141 }
142
143 /*
144  * Ensure that we have a key for thread-specific data.  We don't
145  * put anything in here that Citadel cares about; this is just database
146  * related stuff like cursors and transactions.
147  *
148  * This should be called immediately after startup by any thread which wants
149  * to use database calls, except for whatever thread calls open_databases.
150  */
151 void cdb_allocate_tsd(void) {
152         struct cdbtsd *tsd;
153
154         if (pthread_getspecific(tsdkey) != NULL)
155                 return;
156
157         tsd = mallok(sizeof *tsd);
158
159         tsd->tid = NULL;
160
161         memset(tsd->cursors, 0, sizeof tsd->cursors);
162         pthread_setspecific(tsdkey, tsd);
163 }
164
165 void cdb_free_tsd(void) {
166         dest_tsd(pthread_getspecific(tsdkey));
167         pthread_setspecific(tsdkey, NULL);
168 }
169
170 void cdb_check_handles(void) {
171         check_handles(pthread_getspecific(tsdkey));
172 }
173
174
175 /*
176  * Reclaim unused space in the databases.  We need to do each one of
177  * these discretely, rather than in a loop.
178  *
179  * This is a stub function in the Sleepycat DB backend, because there is no
180  * such API call available.
181  */
182 void defrag_databases(void)
183 {
184         /* do nothing */
185 }
186
187
188 /*
189  * Cull the database logs
190  */
191 static void cdb_cull_logs(void) {
192         u_int32_t flags;
193         int ret;
194         char **file, **list;
195         char errmsg[SIZ];
196
197         lprintf(5, "Database log file cull started.\n");
198
199         flags = DB_ARCH_ABS;
200
201         /* Get the list of names. */
202 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
203         if ((ret = log_archive(dbenv, &list, flags, NULL)) != 0) {
204 #elif DB_VERSION_MAJOR >= 4
205         if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
206 #else
207         if ((ret = log_archive(dbenv, &list, flags)) != 0) {
208 #endif
209                 lprintf(1, "cdb_cull_logs: %s\n", db_strerror(ret));
210                 return;
211         }
212
213         /* Print the list of names. */
214         if (list != NULL) {
215                 for (file = list; *file != NULL; ++file) {
216                         lprintf(9, "Deleting log: %s\n", *file);
217                         ret = unlink(*file);
218                         if (ret != 0) {
219                                 snprintf(errmsg, sizeof(errmsg),
220                                         " ** ERROR **\n \n \n "
221                                         "Citadel was unable to delete the "
222                                         "database log file '%s' because of the "
223                                         "following error:\n \n %s\n \n"
224                                         " This log file is no longer in use "
225                                         "and may be safely deleted.\n",
226                                         *file,
227                                         strerror(errno));
228                                 aide_message(errmsg);
229                         }
230                 }
231                 free(list);
232         }
233
234         lprintf(5, "Database log file cull ended.\n");
235 }
236
237
238 /*
239  * Request a checkpoint of the database.
240  */
241 static void cdb_checkpoint(void) {
242         int ret;
243         static time_t last_cull = 0L;
244
245 #if DB_VERSION_MAJOR >= 4
246         ret = dbenv->txn_checkpoint(dbenv,
247 #else
248         ret = txn_checkpoint(dbenv,
249 #endif
250                                 MAX_CHECKPOINT_KBYTES,
251                                 MAX_CHECKPOINT_MINUTES,
252                                 0);
253         if ( (ret != 0) && (ret != DB_INCOMPLETE) ) {
254                 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n", db_strerror(ret));
255                 abort();
256         }
257
258         if (ret == DB_INCOMPLETE) {
259                 lprintf(3, "WARNING: txn_checkpoint: %s\n", db_strerror(ret));
260         }
261
262         /* Cull the logs if we haven't done so for 24 hours */
263         if ((time(NULL) - last_cull) > 86400L) {
264                 last_cull = time(NULL);
265                 cdb_cull_logs();
266         }
267
268 }
269
270 /*
271  * Open the various databases we'll be using.  Any database which
272  * does not exist should be created.  Note that we don't need an S_DATABASE
273  * critical section here, because there aren't any active threads manipulating
274  * the database yet -- and besides, it causes problems on BSDI.
275  */
276 void open_databases(void)
277 {
278         int ret;
279         int i;
280         char dbfilename[SIZ];
281         u_int32_t flags = 0;
282
283         lprintf(9, "cdb_*: open_databases() starting\n");
284 #ifdef HAVE_ZLIB
285         lprintf(5, "zlib compression version %s\n", zlibVersion());
286 #endif
287
288         /*
289          * Silently try to create the database subdirectory.  If it's
290          * already there, no problem.
291          */
292         system("exec mkdir data 2>/dev/null");
293
294         lprintf(9, "cdb_*: Setting up DB environment\n");
295         db_env_set_func_yield(sched_yield);
296         ret = db_env_create(&dbenv, 0);
297         if (ret) {
298                 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
299                 exit(ret);
300         }
301         dbenv->set_errpfx(dbenv, "citserver");
302
303         /*
304          * We want to specify the shared memory buffer pool cachesize,
305          * but everything else is the default.
306          */
307         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
308         if (ret) {
309                 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
310                 dbenv->close(dbenv, 0);
311                 exit(ret);
312         }
313
314         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
315                 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
316                 dbenv->close(dbenv, 0);
317                 exit(ret);
318         }
319
320         flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
321                 DB_INIT_LOCK|DB_THREAD;
322         ret = dbenv->open(dbenv, "./data", flags, 0);
323         if (ret) {
324                 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
325                 dbenv->close(dbenv, 0);
326                 exit(ret);
327         }
328
329         lprintf(7, "cdb_*: Starting up DB\n");
330
331         for (i = 0; i < MAXCDB; ++i) {
332
333                 /* Create a database handle */
334                 ret = db_create(&dbp[i], dbenv, 0);
335                 if (ret) {
336                         lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
337                         exit(ret);
338                 }
339
340
341                 /* Arbitrary names for our tables -- we reference them by
342                  * number, so we don't have string names for them.
343                  */
344                 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
345
346                 ret = dbp[i]->open(dbp[i],
347                                 dbfilename,
348                                 NULL,
349                                 DB_BTREE,
350                                 DB_CREATE|DB_THREAD,
351                                 0600);
352                 if (ret) {
353                         lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
354                         exit(ret);
355                 }
356         }
357
358         if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
359                 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
360                 exit(1);
361         }
362
363         cdb_allocate_tsd();
364         CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
365         lprintf(9, "cdb_*: open_databases() finished\n");
366 }
367
368
369 /*
370  * Close all of the db database files we've opened.  This can be done
371  * in a loop, since it's just a bunch of closes.
372  */
373 void close_databases(void)
374 {
375         int a;
376         int ret;
377
378         cdb_free_tsd();
379
380 #if DB_VERSION_MAJOR >= 4
381         if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
382 #else
383         if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
384 #endif
385                 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
386                 abort();
387         }
388
389         for (a = 0; a < MAXCDB; ++a) {
390                 lprintf(7, "cdb_*: Closing database %d\n", a);
391                 ret = dbp[a]->close(dbp[a], 0);
392                 if (ret) {
393                         lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
394                         abort();
395                 }
396                 
397         }
398
399         /* Close the handle. */
400         ret = dbenv->close(dbenv, 0);
401         if (ret) {
402                 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
403                 abort();
404         }
405 }
406
407
408 /*
409  * Compression functions only used if we have zlib
410  */
411 #ifdef HAVE_ZLIB
412
413 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
414         static int magic = COMPRESS_MAGIC;
415         struct CtdlCompressHeader zheader;
416         char *uncompressed_data;
417         char *compressed_data;
418         uLongf destLen, sourceLen;
419
420         if (cdb == NULL) return;
421         if (cdb->ptr == NULL) return;
422         if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
423
424         /* At this point we know we're looking at a compressed item. */
425         memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
426
427         compressed_data = cdb->ptr;
428         compressed_data += sizeof(struct CtdlCompressHeader);
429
430         sourceLen = (uLongf) zheader.compressed_len;
431         destLen = (uLongf) zheader.uncompressed_len;
432         uncompressed_data = mallok(zheader.uncompressed_len);
433
434         if (uncompress( (Bytef *) uncompressed_data,
435                         &destLen,
436                         compressed_data,
437                         sourceLen
438         ) != Z_OK) {
439                 lprintf(1, "uncompress() error\n");
440                 abort();
441         }
442
443         phree(cdb->ptr);
444         cdb->len = (size_t) destLen;
445         cdb->ptr = uncompressed_data;
446 }
447
448 #endif  /* HAVE_ZLIB */
449         
450
451 /*
452  * Store a piece of data.  Returns 0 if the operation was successful.  If a
453  * key already exists it should be overwritten.
454  */
455 int cdb_store(int cdb,
456               void *ckey, int ckeylen,
457               void *cdata, int cdatalen)
458 {
459
460   DBT dkey, ddata;
461   DB_TXN *tid;
462   int ret;
463
464 #ifdef HAVE_ZLIB
465         struct CtdlCompressHeader zheader;
466         char *compressed_data = NULL;
467         int compressing = 0;
468         size_t buffer_len;
469         uLongf destLen;
470 #endif
471   
472   memset(&dkey, 0, sizeof(DBT));
473   memset(&ddata, 0, sizeof(DBT));
474   dkey.size = ckeylen;
475   dkey.data = ckey;
476   ddata.size = cdatalen;
477   ddata.data = cdata;
478
479 #ifdef HAVE_ZLIB
480         /* Only compress Visit records.  Everything else is uncompressed. */
481         if (cdb == CDB_VISIT) {
482                 compressing = 1;
483                 zheader.magic = COMPRESS_MAGIC;
484                 zheader.uncompressed_len = cdatalen;
485                 buffer_len = ( (cdatalen * 101) / 100 ) + 100
486                                 + sizeof(struct CtdlCompressHeader) ;
487                 destLen = (uLongf) buffer_len;
488                 compressed_data = mallok(buffer_len);
489                 if (compress2(
490                         (Bytef *) (compressed_data +
491                                         sizeof(struct CtdlCompressHeader)),
492                         &destLen,
493                         (Bytef *) cdata,
494                         (uLongf) cdatalen,
495                         1
496                 ) != Z_OK) {
497                         lprintf(1, "compress2() error\n");
498                         abort();
499                 }
500                 zheader.compressed_len = (size_t) destLen;
501                 memcpy(compressed_data, &zheader,
502                         sizeof(struct CtdlCompressHeader));
503                 ddata.size = (size_t)  (sizeof(struct CtdlCompressHeader) +
504                                                 zheader.compressed_len);
505                 ddata.data = compressed_data;
506         }
507 #endif
508   
509   if (MYTID != NULL)
510     {
511       ret = dbp[cdb]->put(dbp[cdb],             /* db */
512                           MYTID,                /* transaction ID */
513                           &dkey,                /* key */
514                           &ddata,               /* data */
515                           0);           /* flags */
516       if (ret)
517         {
518           lprintf(1, "cdb_store(%d): %s\n", cdb,
519                   db_strerror(ret));
520           abort();
521         }
522 #ifdef HAVE_ZLIB
523       if (compressing) phree(compressed_data);
524 #endif
525       return ret;
526       
527     }
528   else
529     {
530       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
531       
532     retry:
533       txbegin(&tid);
534       
535       if ((ret = dbp[cdb]->put(dbp[cdb],    /* db */
536                                tid,         /* transaction ID */
537                                &dkey,       /* key */
538                                &ddata,      /* data */
539                                0)))         /* flags */
540         {
541           if (ret == DB_LOCK_DEADLOCK)
542             {
543               txabort(tid);
544               goto retry;
545             }
546           else
547             {
548               lprintf(1, "cdb_store(%d): %s\n", cdb,
549                       db_strerror(ret));
550               abort();
551             }
552         }
553       else
554         {
555           txcommit(tid);
556 #ifdef HAVE_ZLIB
557           if (compressing) phree(compressed_data);
558 #endif
559           return ret;
560         }
561     }
562 }
563
564
565 /*
566  * Delete a piece of data.  Returns 0 if the operation was successful.
567  */
568 int cdb_delete(int cdb, void *key, int keylen)
569 {
570
571   DBT dkey;
572   DB_TXN *tid;
573   int ret;
574
575   memset(&dkey, 0, sizeof dkey);
576   dkey.size = keylen;
577   dkey.data = key;
578
579   if (MYTID != NULL)
580     {
581       ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
582       if (ret)
583         {
584           lprintf(1, "cdb_delete(%d): %s\n", cdb,
585                   db_strerror(ret));
586           if (ret != DB_NOTFOUND)
587             abort();
588         }
589     }
590   else
591     {
592       bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
593     
594     retry:
595       txbegin(&tid);
596     
597       if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
598           && ret != DB_NOTFOUND)
599         {
600           if (ret == DB_LOCK_DEADLOCK)
601             {
602               txabort(tid);
603               goto retry;
604             }
605           else
606             {
607               lprintf(1, "cdb_delete(%d): %s\n", cdb,
608                       db_strerror(ret));
609               abort();
610             }
611         }
612       else
613         {
614           txcommit(tid);
615         }
616     }
617   return ret;
618 }
619
620 static DBC *localcursor(int cdb)
621 {
622   int ret;
623   DBC *curs;
624
625   if (MYCURSORS[cdb] == NULL)
626     ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
627   else
628     ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
629
630   if (ret)
631     {
632       lprintf(1, "localcursor: %s\n", db_strerror(ret));
633       abort();
634     }
635
636   return curs;
637 }
638
639
640 /*
641  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
642  * a struct cdbdata which it is the caller's responsibility to free later on
643  * using the cdb_free() routine.
644  */
645 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
646 {
647
648   struct cdbdata *tempcdb;
649   DBT dkey, dret;
650   int ret;
651
652   memset(&dkey, 0, sizeof(DBT));
653   dkey.size = keylen;
654   dkey.data = key;
655
656   if (MYTID != NULL)
657     {
658       memset(&dret, 0, sizeof(DBT));
659       dret.flags = DB_DBT_MALLOC;
660       ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
661     }
662   else
663     {
664       DBC *curs;
665
666       do
667         {
668           memset(&dret, 0, sizeof(DBT));
669           dret.flags = DB_DBT_MALLOC;
670
671           curs = localcursor(cdb);
672
673           ret = curs->c_get(curs, &dkey, &dret, DB_SET);
674           cclose(curs);
675         }
676       while (ret == DB_LOCK_DEADLOCK);
677
678     }
679
680   if ((ret != 0) && (ret != DB_NOTFOUND))
681     {
682       lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
683       abort();
684     }
685
686   if (ret != 0) return NULL;
687   tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
688
689   if (tempcdb == NULL)
690     {
691       lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
692       abort();
693     }
694
695   tempcdb->len = dret.size;
696   tempcdb->ptr = dret.data;
697   cdb_decompress_if_necessary(tempcdb);
698   return (tempcdb);
699 }
700
701
702 /*
703  * Free a cdbdata item (ok, this is really no big deal, but we might need to do
704  * more complex stuff with other database managers in the future).
705  */
706 void cdb_free(struct cdbdata *cdb)
707 {
708         phree(cdb->ptr);
709         phree(cdb);
710 }
711
712 void cdb_close_cursor(int cdb)
713 {
714         if (MYCURSORS[cdb] != NULL)
715                 cclose(MYCURSORS[cdb]);
716
717         MYCURSORS[cdb] = NULL;
718 }
719
720 /* 
721  * Prepare for a sequential search of an entire database.
722  * (There is guaranteed to be no more than one traversal in
723  * progress per thread at any given time.)
724  */
725 void cdb_rewind(int cdb)
726 {
727         int ret = 0;
728
729         if (MYCURSORS[cdb] != NULL)
730                 cclose(MYCURSORS[cdb]);
731
732         /*
733          * Now initialize the cursor
734          */
735         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
736         if (ret) {
737                 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
738                 abort();
739         }
740 }
741
742
743 /*
744  * Fetch the next item in a sequential search.  Returns a pointer to a 
745  * cdbdata structure, or NULL if we've hit the end.
746  */
747 struct cdbdata *cdb_next_item(int cdb)
748 {
749         DBT key, data;
750         struct cdbdata *cdbret;
751         int ret = 0;
752
753         /* Initialize the key/data pair so the flags aren't set. */
754         memset(&key, 0, sizeof(key));
755         memset(&data, 0, sizeof(data));
756         data.flags = DB_DBT_MALLOC;
757
758         ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
759                 &key, &data, DB_NEXT);
760         
761         if (ret) {
762                 if (ret != DB_NOTFOUND) {
763                         lprintf(1, "cdb_next_item(%d): %s\n",
764                                 cdb, db_strerror(ret));
765                         abort();
766                 }
767                 cclose(MYCURSORS[cdb]);
768                 MYCURSORS[cdb] = NULL;
769                 return NULL;            /* presumably, end of file */
770         }
771
772         cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
773         cdbret->len = data.size;
774         cdbret->ptr = data.data;
775         cdb_decompress_if_necessary(cdbret);
776
777         return (cdbret);
778 }
779
780
781
782 /*
783  * Transaction-based stuff.  I'm writing this as I bake cookies...
784  */
785
786 void cdb_begin_transaction(void) {
787
788   bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
789
790   if (MYTID != NULL)
791     {
792       lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
793       abort();
794     }
795
796   txbegin(&MYTID);
797 }
798
799 void cdb_end_transaction(void) {
800   int i;
801
802   for (i = 0; i < MAXCDB; i++)
803     if (MYCURSORS[i] != NULL) {
804       lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
805       cclose(MYCURSORS[i]);
806       MYCURSORS[i] = NULL;
807     }
808
809   if (MYTID == NULL)
810     {
811       lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
812       abort();
813     }
814   else
815     txcommit(MYTID);
816
817   MYTID = NULL;
818 }
819
820 /*
821  * Truncate (delete every record)
822  */
823 void cdb_trunc(int cdb)
824 {
825   DB_TXN *tid;
826   int ret;
827 #if DB_VERSION_MAJOR > 3 || DB_VERSION_MINOR > 2
828   u_int32_t count;
829 #endif
830   
831   if (MYTID != NULL)
832     {
833       lprintf(1, "cdb_trunc must not be called in a transaction.\n");
834       abort();
835     }
836   else
837     {
838       bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
839       
840 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
841       for (;;)
842         {
843           DBT key, data;
844
845           /* Initialize the key/data pair so the flags aren't set. */
846           memset(&key, 0, sizeof(key));
847           memset(&data, 0, sizeof(data));
848
849           txbegin(&tid);
850           
851           ret = dbp[cdb]->cursor(dbp[cdb], tid, &MYCURSORS[cdb], 0);
852           if (ret)
853             {
854               lprintf(1, "cdb_trunc: db_cursor: %s\n", db_strerror(ret));
855               abort();
856             }
857
858           ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
859                                       &key, &data, DB_NEXT);
860           if (ret)
861             {
862               cclose(MYCURSORS[cdb]);
863               txabort(tid);
864               if (ret == DB_LOCK_DEADLOCK)
865                 continue;
866
867               if (ret == DB_NOTFOUND)
868                 break;
869
870               lprintf(1, "cdb_trunc: c_get: %s\n", db_strerror(ret));
871               abort();
872             }
873
874           ret = MYCURSORS[cdb]->c_del(MYCURSORS[cdb], 0);
875           if (ret)
876             {
877               cclose(MYCURSORS[cdb]);
878               txabort(tid);
879               if (ret == DB_LOCK_DEADLOCK)
880                 continue;
881
882               lprintf(1, "cdb_trunc: c_del: %s\n", db_strerror(ret));
883               abort();
884             }
885
886           cclose(MYCURSORS[cdb]);
887           txcommit(tid);
888         }
889 #else
890     retry:
891       txbegin(&tid);
892       
893       if ((ret = dbp[cdb]->truncate(dbp[cdb],    /* db */
894                                     tid,         /* transaction ID */
895                                     &count,      /* #rows deleted */
896                                     0)))         /* flags */
897         {
898           if (ret == DB_LOCK_DEADLOCK)
899             {
900               txabort(tid);
901               goto retry;
902             }
903           else
904             {
905               lprintf(1, "cdb_truncate(%d): %s\n", cdb,
906                       db_strerror(ret));
907               abort();
908             }
909         }
910       else
911         {
912           txcommit(tid);
913         }
914 #endif
915     }
916 }