03131854e02d72e1c460cfd317c456dbc4866a8b
[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 /* Set to 1 for transaction-based database logging.  This is recommended for
13  * safe recovery in the event of system or application failure.
14  */
15 #define TRANSACTION_BASED       1
16
17 /* Citadel will checkpoint the db at the end of every session, but only if
18  * the specified number of kilobytes has been written, or if the specified
19  * number of minutes has passed, since the last checkpoint.
20  */
21 #define MAX_CHECKPOINT_KBYTES   0
22 #define MAX_CHECKPOINT_MINUTES  15
23
24 /*****************************************************************************/
25
26 #include "sysdep.h"
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <time.h>
31 #include <ctype.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <db.h>
35 #include "citadel.h"
36 #include "server.h"
37 #include "citserver.h"
38 #include "database.h"
39 #include "sysdep_decls.h"
40 #include "dynloader.h"
41
42 DB *dbp[MAXCDB];                /* One DB handle for each Citadel database */
43 DB_ENV *dbenv;                  /* The DB environment (global) */
44
45 struct cdbssd {                 /* Session-specific DB stuff */
46         DBC *cursor;            /* Cursor, for traversals... */
47         DB_TXN *tid;            /* Transaction ID */
48 };
49
50 struct cdbssd *ssd_arr = NULL;
51 int num_ssd = 0;
52 #define MYCURSOR        ssd_arr[CC->cs_pid].cursor
53 #define MYTID           ssd_arr[CC->cs_pid].tid
54
55 /*
56  * Ensure that we have enough space for session-specific data.  We don't
57  * put anything in here that Citadel cares about; this is just database
58  * related stuff like cursors and transactions.
59  */
60 void cdb_allocate_ssd(void) {
61         /*
62          * Make sure we have a cursor allocated for this session
63          */
64
65         lprintf(9, "num_ssd before realloc = %d\n", num_ssd);
66         if (num_ssd <= CC->cs_pid) {
67                 num_ssd = CC->cs_pid + 1;
68                 if (ssd_arr == NULL) {
69                         ssd_arr = (struct cdbssd *)
70                             mallok((sizeof(struct cdbssd) * num_ssd));
71                 } else {
72                         ssd_arr = (struct cdbssd *)
73                             reallok(ssd_arr, (sizeof(struct cdbssd) * num_ssd));
74                 }
75         }
76         lprintf(9, "num_ssd  after realloc = %d\n", num_ssd);
77 }
78
79
80 /*
81  * Reclaim unused space in the databases.  We need to do each one of
82  * these discretely, rather than in a loop.
83  *
84  * This is a stub function in the Sleepycat DB backend, because there is no
85  * such API call available.
86  */
87 void defrag_databases(void)
88 {
89         /* do nothing */
90 }
91
92
93
94 /*
95  * Request a checkpoint of the database.
96  */
97 void cdb_checkpoint(void) {
98         int ret;
99
100         ret = txn_checkpoint(dbenv,
101                                 MAX_CHECKPOINT_KBYTES,
102                                 MAX_CHECKPOINT_MINUTES,
103                                 0);
104         if (ret) {
105                 lprintf(1, "txn_checkpoint: %s\n", db_strerror(ret));
106         }
107 }
108
109
110 /*
111  * Open the various databases we'll be using.  Any database which
112  * does not exist should be created.  Note that we don't need an S_DATABASE
113  * critical section here, because there aren't any active threads manipulating
114  * the database yet -- and besides, it causes problems on BSDI.
115  */
116 void open_databases(void)
117 {
118         int ret;
119         int i;
120         char dbfilename[256];
121         u_int32_t flags = 0;
122
123         /*
124          * Silently try to create the database subdirectory.  If it's
125          * already there, no problem.
126          */
127         system("exec mkdir data 2>/dev/null");
128
129         lprintf(9, "Setting up DB environment\n");
130         ret = db_env_create(&dbenv, 0);
131         if (ret) {
132                 lprintf(1, "db_env_create: %s\n", db_strerror(ret));
133                 exit(ret);
134         }
135         dbenv->set_errpfx(dbenv, "citserver");
136
137         /*
138          * We want to specify the shared memory buffer pool cachesize,
139          * but everything else is the default.
140          */
141         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
142         if (ret) {
143                 lprintf(1, "set_cachesize: %s\n", db_strerror(ret));
144                 dbenv->close(dbenv, 0);
145                 exit(ret);
146         }
147
148         /*
149          * We specify DB_PRIVATE but not DB_INIT_LOCK or DB_THREAD, even
150          * though this is a multithreaded application.  Since Citadel does all
151          * database access in S_DATABASE critical sections, access to the db
152          * is serialized already, so don't bother the database manager with
153          * it.  Besides, it locks up when we do it that way.
154          */
155 #ifdef TRANSACTION_BASED
156         flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN;
157 #else
158         flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE;
159 #endif
160         ret = dbenv->open(dbenv, "./data", flags, 0);
161         if (ret) {
162                 lprintf(1, "dbenv->open: %s\n", db_strerror(ret));
163                 dbenv->close(dbenv, 0);
164                 exit(ret);
165         }
166
167         lprintf(7, "Starting up DB\n");
168
169         for (i = 0; i < MAXCDB; ++i) {
170
171                 /* Create a database handle */
172                 ret = db_create(&dbp[i], dbenv, 0);
173                 if (ret) {
174                         lprintf(1, "db_create: %s\n", db_strerror(ret));
175                         exit(ret);
176                 }
177
178
179                 /* Arbitrary names for our tables -- we reference them by
180                  * number, so we don't have string names for them.
181                  */
182                 sprintf(dbfilename, "cdb.%02x", i);
183
184                 ret = dbp[i]->open(dbp[i],
185                                 dbfilename,
186                                 NULL,
187                                 DB_BTREE,
188                                 DB_CREATE,
189                                 0600);
190                 if (ret) {
191                         lprintf(1, "db_open[%d]: %s\n", i, db_strerror(ret));
192                         exit(ret);
193                 }
194         }
195
196         cdb_allocate_ssd();
197         CtdlRegisterSessionHook(cdb_allocate_ssd, EVT_START);
198 #ifdef TRANSACTION_BASED
199         CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
200 #endif
201 }
202
203
204 /*
205  * Close all of the gdbm database files we've opened.  This can be done
206  * in a loop, since it's just a bunch of closes.
207  */
208 void close_databases(void)
209 {
210         int a;
211         int ret;
212
213         begin_critical_section(S_DATABASE);
214         for (a = 0; a < MAXCDB; ++a) {
215                 lprintf(7, "Closing database %d\n", a);
216                 ret = dbp[a]->close(dbp[a], 0);
217                 if (ret) {
218                         lprintf(1, "db_close: %s\n", db_strerror(ret));
219                 }
220                 
221         }
222
223
224
225         /* Close the handle. */
226         ret = dbenv->close(dbenv, 0);
227         if (ret) {
228                 lprintf(1, "DBENV->close: %s\n", db_strerror(ret));
229         }
230
231
232         end_critical_section(S_DATABASE);
233
234 }
235
236
237 /*
238  * Store a piece of data.  Returns 0 if the operation was successful.  If a
239  * key already exists it should be overwritten.
240  */
241 int cdb_store(int cdb,
242               void *ckey, int ckeylen,
243               void *cdata, int cdatalen)
244 {
245
246         DBT dkey, ddata;
247         int ret;
248
249         memset(&dkey, 0, sizeof(DBT));
250         memset(&ddata, 0, sizeof(DBT));
251         dkey.size = ckeylen;
252         dkey.data = ckey;
253         ddata.size = cdatalen;
254         ddata.data = cdata;
255
256         begin_critical_section(S_DATABASE);
257         ret = dbp[cdb]->put(dbp[cdb],           /* db */
258                                 MYTID,          /* transaction ID */
259                                 &dkey,          /* key */
260                                 &ddata,         /* data */
261                                 0);             /* flags */
262         end_critical_section(S_DATABASE);
263         if (ret) {
264                 lprintf(1, "cdb_store: %s\n", db_strerror(ret));
265                 return (-1);
266         }
267         return (0);
268 }
269
270
271 /*
272  * Delete a piece of data.  Returns 0 if the operation was successful.
273  */
274 int cdb_delete(int cdb, void *key, int keylen)
275 {
276
277         DBT dkey;
278         int ret;
279
280         dkey.size = keylen;
281         dkey.data = key;
282
283         begin_critical_section(S_DATABASE);
284         ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
285         end_critical_section(S_DATABASE);
286         return (ret);
287
288 }
289
290
291
292
293 /*
294  * Fetch a piece of data.  If not found, returns NULL.  Otherwise, it returns
295  * a struct cdbdata which it is the caller's responsibility to free later on
296  * using the cdb_free() routine.
297  */
298 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
299 {
300
301         struct cdbdata *tempcdb;
302         DBT dkey, dret;
303         int ret;
304
305         memset(&dkey, 0, sizeof(DBT));
306         memset(&dret, 0, sizeof(DBT));
307         dkey.size = keylen;
308         dkey.data = key;
309         dret.flags = DB_DBT_MALLOC;
310
311         begin_critical_section(S_DATABASE);
312         ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
313         end_critical_section(S_DATABASE);
314         if ((ret != 0) && (ret != DB_NOTFOUND)) {
315                 lprintf(1, "cdb_fetch: %s\n", db_strerror(ret));
316         }
317         if (ret != 0) return NULL;
318         tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
319         if (tempcdb == NULL) {
320                 lprintf(2, "Cannot allocate memory!\n");
321         }
322         tempcdb->len = dret.size;
323         tempcdb->ptr = dret.data;
324         return (tempcdb);
325 }
326
327
328 /*
329  * Free a cdbdata item (ok, this is really no big deal, but we might need to do
330  * more complex stuff with other database managers in the future).
331  */
332 void cdb_free(struct cdbdata *cdb)
333 {
334         phree(cdb->ptr);
335         phree(cdb);
336 }
337
338
339 /* 
340  * Prepare for a sequential search of an entire database.
341  * (There is guaranteed to be no more than one traversal in
342  * progress per session at any given time.)
343  */
344 void cdb_rewind(int cdb)
345 {
346         int ret = 0;
347
348         /*
349          * Now initialize the cursor
350          */
351         begin_critical_section(S_DATABASE);
352         ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSOR, 0);
353         if (ret) {
354                 lprintf(1, "db_cursor: %s\n", db_strerror(ret));
355         }
356         end_critical_section(S_DATABASE);
357 }
358
359
360 /*
361  * Fetch the next item in a sequential search.  Returns a pointer to a 
362  * cdbdata structure, or NULL if we've hit the end.
363  */
364 struct cdbdata *cdb_next_item(int cdb)
365 {
366         DBT key, data;
367         struct cdbdata *cdbret;
368         int ret = 0;
369
370         /* Initialize the key/data pair so the flags aren't set. */
371         memset(&key, 0, sizeof(key));
372         memset(&data, 0, sizeof(data));
373         data.flags = DB_DBT_MALLOC;
374
375         begin_critical_section(S_DATABASE);
376         ret = MYCURSOR->c_get(MYCURSOR,
377                 &key, &data, DB_NEXT);
378         end_critical_section(S_DATABASE);
379         
380         if (ret) return NULL;           /* presumably, end of file */
381
382         cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
383         cdbret->len = data.size;
384         cdbret->ptr = data.data;
385
386         return (cdbret);
387 }
388
389
390 /*
391  * Transaction-based stuff.  I'm writing this as I bake cookies...
392  */
393
394 void cdb_begin_transaction(void) {
395
396 #ifdef TRANSACTION_BASED
397         txn_begin(dbenv, NULL, &MYTID, 0);
398 #else
399         MYTID = NULL;
400 #endif
401 }
402
403 void cdb_end_transaction(void) {
404 #ifdef TRANSACTION_BASED
405         txn_commit(MYTID, 0);
406 #endif
407 }