]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb2.h
23f57f84a6906dcb33679defe245fdd34f99ef84
[ccan] / ccan / tdb2 / tdb2.h
1 #ifndef CCAN_TDB2_H
2 #define CCAN_TDB2_H
3
4 /*
5    TDB version 2: trivial database library
6
7    Copyright (C) Andrew Tridgell 1999-2004
8    Copyright (C) Rusty Russell 2010-2011
9
10      ** NOTE! The following LGPL license applies to the tdb
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 3 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 */
27
28 #ifdef  __cplusplus
29 extern "C" {
30 #endif
31
32 #ifndef _SAMBA_BUILD_
33 /* For mode_t */
34 #include <sys/types.h>
35 /* For O_* flags. */
36 #include <sys/stat.h>
37 /* For sig_atomic_t. */
38 #include <signal.h>
39 /* For uint64_t */
40 #include <stdint.h>
41 #endif
42 #include <ccan/compiler/compiler.h>
43
44 union tdb_attribute;
45 struct tdb_context;
46
47 /**
48  * tdb_open - open a database file
49  * @name: the file name (can be NULL if flags contains TDB_INTERNAL)
50  * @tdb_flags: options for this database
51  * @open_flags: flags argument for tdb's open() call.
52  * @mode: mode argument for tdb's open() call.
53  * @attributes: linked list of extra attributes for this tdb.
54  *
55  * This call opens (and potentially creates) a database file.
56  * Multiple processes can have the TDB file open at once.
57  *
58  * On failure it will return NULL, and set errno: it may also call
59  * any log attribute found in @attributes.
60  *
61  * See also:
62  *      union tdb_attribute
63  */
64 struct tdb_context *tdb_open(const char *name, int tdb_flags,
65                              int open_flags, mode_t mode,
66                              union tdb_attribute *attributes);
67
68
69 /* flags for tdb_open() */
70 #define TDB_DEFAULT 0 /* just a readability place holder */
71 #define TDB_INTERNAL 2 /* don't store on disk */
72 #define TDB_NOLOCK   4 /* don't do any locking */
73 #define TDB_NOMMAP   8 /* don't use mmap */
74 #define TDB_CONVERT 16 /* convert endian */
75 #define TDB_NOSYNC   64 /* don't use synchronous transactions */
76
77 /**
78  * tdb_close - close and free a tdb.
79  * @tdb: the tdb context returned from tdb_open()
80  *
81  * This always succeeds, in that @tdb is unusable after this call.  But if
82  * some unexpected error occurred while closing, it will return non-zero
83  * (the only clue as to cause will be via the log attribute).
84  */
85 int tdb_close(struct tdb_context *tdb);
86
87 /**
88  * struct tdb_data - representation of keys or values.
89  * @dptr: the data pointer
90  * @dsize: the size of the data pointed to by dptr.
91  *
92  * This is the "blob" representation of keys and data used by TDB.
93  */
94 typedef struct tdb_data {
95         unsigned char *dptr;
96         size_t dsize;
97 } TDB_DATA;
98
99 /**
100  * tdb_store - store a key/value pair in a tdb.
101  * @tdb: the tdb context returned from tdb_open()
102  * @key: the key
103  * @dbuf: the data to associate with the key.
104  * @flag: TDB_REPLACE, TDB_INSERT or TDB_MODIFY.
105  *
106  * This inserts (or overwrites) a key/value pair in the TDB.  If flag
107  * is TDB_REPLACE, it doesn't matter whether the key exists or not;
108  * TDB_INSERT means it must not exist (TDB_ERR_EXISTS otherwise),
109  * and TDB_MODIFY means it must exist (TDB_ERR_NOEXIST otherwise).
110  *
111  * On success, this returns 0, on failure -1, and sets tdb_error().
112  *
113  * See also:
114  *      tdb_fetch, tdb_transaction_start, tdb_append, tdb_delete.
115  */
116 int tdb_store(struct tdb_context *tdb,
117               struct tdb_data key,
118               struct tdb_data dbuf,
119               int flag);
120
121 /* flags to tdb_store() */
122 #define TDB_REPLACE 1           /* A readability place holder */
123 #define TDB_INSERT 2            /* Don't overwrite an existing entry */
124 #define TDB_MODIFY 3            /* Don't create an existing entry    */
125
126 /**
127  * tdb_fetch - fetch a value from a tdb.
128  * @tdb: the tdb context returned from tdb_open()
129  * @key: the key
130  *
131  * This looks up a key in the database and returns it, or returns tdb_null
132  * and sets tdb_error() if there's a problem (usually, TDB_ERR_NOEXIST).
133  *
134  * It is your responsibility to call free() on the returned structure's
135  * dptr.
136  */
137 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key);
138
139 /**
140  * enum TDB_ERROR - error codes for TDB
141  *
142  * See Also:
143  *      tdb_error(), tdb_errorstr()
144  */
145 enum TDB_ERROR {
146         TDB_SUCCESS=0,          /* No error. */
147         TDB_ERR_CORRUPT,        /* We read the db, and it was bogus. */
148         TDB_ERR_IO,             /* We couldn't read/write the db. */
149         TDB_ERR_LOCK,           /* Locking failed. */
150         TDB_ERR_OOM,            /* Out of Memory. */
151         TDB_ERR_EXISTS,         /* The key already exists. */
152         TDB_ERR_NOEXIST,        /* The key does not exist. */
153         TDB_ERR_EINVAL,         /* You're using it wrong. */
154         TDB_ERR_RDONLY          /* The database is read-only. */
155 };
156
157 /**
158  * tdb_error - fetch the last error value from the tdb.
159  * @tdb: the tdb context returned from tdb_open()
160  *
161  * This returns the last error, or TDB_SUCCESS.  It always returns TDB_SUCCESS
162  * immediately after tdb_open() returns the (non-NULL) tdb context.
163  *
164  * See Also:
165  *      tdb_errorstr()
166  */
167 enum TDB_ERROR tdb_error(const struct tdb_context *tdb);
168
169 /**
170  * tdb_errorstr - map the tdb error onto a constant readable string
171  * @tdb: the tdb context returned from tdb_open()
172  *
173  * This is more useful for displaying errors to users than tdb_error.
174  *
175  * See Also:
176  *      tdb_error()
177  */
178 const char *tdb_errorstr(const struct tdb_context *tdb);
179
180 /**
181  * tdb_append - append a value to a key/value pair in a tdb.
182  * @tdb: the tdb context returned from tdb_open()
183  * @key: the key
184  * @dbuf: the data to append.
185  *
186  * This is equivalent to fetching a record, reallocating .dptr to add the
187  * data, and writing it back, only it's much more efficient.  If the key
188  * doesn't exist, it's equivalent to tdb_store (with an additional hint that
189  * you expect to expand the record in future).
190  *
191  * Returns 0 on success, -1 on failure (and sets tdb_error()).
192  *
193  * See Also:
194  *      tdb_fetch(), tdb_store()
195  */
196 int tdb_append(struct tdb_context *tdb,
197                struct tdb_data key,
198                struct tdb_data dbuf);
199
200 /**
201  * tdb_delete - delete a key from a tdb.
202  * @tdb: the tdb context returned from tdb_open()
203  * @key: the key to delete.
204  *
205  * Returns 0 on success, or -1 on error (usually tdb_error() would be
206  * TDB_ERR_NOEXIST in that case).
207  *
208  * See Also:
209  *      tdb_fetch(), tdb_store()
210  */
211 int tdb_delete(struct tdb_context *tdb, struct tdb_data key);
212
213 /**
214  * tdb_transaction_start - start a transaction
215  * @tdb: the tdb context returned from tdb_open()
216  *
217  * This begins a series of atomic operations.  Other processes will be able
218  * to read the tdb, but not alter it (they will block), nor will they see
219  * any changes until tdb_transaction_commit() is called.
220  *
221  * On failure, returns -1 and sets tdb_error().
222  *
223  * See Also:
224  *      tdb_transaction_cancel, tdb_transaction_commit.
225  */
226 int tdb_transaction_start(struct tdb_context *tdb);
227
228 /**
229  * tdb_transaction_cancel - abandon a transaction
230  * @tdb: the tdb context returned from tdb_open()
231  *
232  * This aborts a transaction, discarding any changes which were made.
233  * tdb_close() does this implicitly.
234  */
235 void tdb_transaction_cancel(struct tdb_context *tdb);
236
237 /**
238  * tdb_transaction_commit - commit a transaction
239  * @tdb: the tdb context returned from tdb_open()
240  *
241  * This completes a transaction, writing any changes which were made.
242  *
243  * fsync() is used to commit the transaction (unless TDB_NOSYNC is set),
244  * making it robust against machine crashes, but very slow compared to
245  * other TDB operations.
246  *
247  * Returns 0 on success, or -1 on failure: this can only be caused by
248  * unexpected errors (eg. I/O or memory); this is no point looping on
249  * transaction failure.
250  *
251  * See Also:
252  *      tdb_transaction_prepare_commit()
253  */
254 int tdb_transaction_commit(struct tdb_context *tdb);
255
256 /**
257  * tdb_transaction_prepare_commit - prepare to commit a transaction
258  * @tdb: the tdb context returned from tdb_open()
259  *
260  * This ensures we have the resources to commit a transaction (using
261  * tdb_transaction_commit): if this succeeds then a transaction will only
262  * fail if the write() or fsync() calls fail.
263  *
264  * Returns 0 on success, or -1 on failure.
265  *
266  * See Also:
267  *      tdb_transaction_commit()
268  */
269 int tdb_transaction_prepare_commit(struct tdb_context *tdb);
270
271 /* FIXME: Make typesafe */
272 typedef int (*tdb_traverse_func)(struct tdb_context *, TDB_DATA, TDB_DATA, void *);
273
274 /**
275  * tdb_traverse - traverse a TDB
276  * @tdb: the tdb context returned from tdb_open()
277  * @fn: the function to call for every key/value pair (or NULL)
278  * @p: the pointer to hand to @f
279  *
280  * This walks the TDB until all they keys have been traversed, or @fn
281  * returns non-zero.  If the traverse function or other processes are
282  * changing data or adding or deleting keys, the traverse may be
283  * unreliable: keys may be skipped or (rarely) visited twice.
284  *
285  * There is one specific exception: the special case of deleting the
286  * current key does not undermine the reliability of the traversal.
287  *
288  * On success, returns the number of keys iterated.  On error returns
289  * -1 and sets tdb_error().
290  */
291 int64_t tdb_traverse(struct tdb_context *tdb, tdb_traverse_func fn, void *p);
292
293 /**
294  * tdb_firstkey - get the "first" key in a TDB
295  * @tdb: the tdb context returned from tdb_open()
296  *
297  * This returns an arbitrary key in the database; with tdb_nextkey() it allows
298  * open-coded traversal of the database.
299  *
300  * On failure, returns tdb_null and sets tdb_error().  On success, returns
301  * a key, or tdb_null and set tdb_error() to TDB_SUCCESS for an empty database.
302  */
303 TDB_DATA tdb_firstkey(struct tdb_context *tdb);
304
305 /**
306  * tdb_nextkey - get the "next" key in a TDB
307  * @tdb: the tdb context returned from tdb_open()
308  * @key: a key returned by tdb_firstkey() or tdb_nextkey().
309  *
310  * This returns another key in the database.  On failure or the last key
311  * it returns tdb_null: tdb_error() will be TDB_SUCCESS if it was the last key.
312  */
313 TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA key);
314
315 /**
316  * tdb_chainlock - lock a record in the TDB
317  * @tdb: the tdb context returned from tdb_open()
318  * @key: the key to lock.
319  *
320  * This prevents any changes from occurring to a group of keys including @key,
321  * even if @key does not exist.  This allows primitive atomic updates of
322  * records without using transactions.
323  *
324  * You cannot begin a transaction while holding a tdb_chainlock(), nor can
325  * you do any operations on any other keys in the database.  This also means
326  * that you cannot hold more than one tdb_chainlock() at a time.
327  *
328  * See Also:
329  *      tdb_chainunlock()
330  */
331 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key);
332
333 /**
334  * tdb_chainunlock - unlock a record in the TDB
335  * @tdb: the tdb context returned from tdb_open()
336  * @key: the key to unlock.
337  */
338 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key);
339
340 /**
341  * tdb_check - check a TDB for consistency
342  * @tdb: the tdb context returned from tdb_open()
343  * @check: function to check each key/data pair (or NULL)
344  * @private_data: pointer for @check
345  *
346  * This performs a consistency check of the open database, optionally calling
347  * a check() function on each record so you can do your own data consistency
348  * checks as well.  If check() returns non-zero, it is considered a failure.
349  *
350  * Returns 0 on success, or -1 on failure and sets tdb_error().
351  */
352 int tdb_check(struct tdb_context *tdb,
353               int (*check)(TDB_DATA key, TDB_DATA data, void *private_data),
354               void *private_data);
355
356 /**
357  * enum tdb_summary_flags - flags for tdb_summary.
358  */
359 enum tdb_summary_flags {
360         TDB_SUMMARY_HISTOGRAMS = 1 /* Draw graphs in the summary. */
361 };
362
363 /**
364  * tdb_summary - return a string describing the TDB state
365  * @tdb: the tdb context returned from tdb_open()
366  * @flags: flags to control the summary output.
367  *
368  * This returns a developer-readable string describing the overall
369  * state of the tdb, such as the percentage used and sizes of records.
370  * It is designed to provide information about the tdb at a glance
371  * without displaying any keys or data in the database.
372  *
373  * On success, returns a nul-terminated multi-line string.  On failure,
374  * returns NULL and sets tdb_error().
375  */
376 char *tdb_summary(struct tdb_context *tdb, enum tdb_summary_flags flags);
377
378
379
380 /**
381  * enum tdb_attribute_type - descriminator for union tdb_attribute.
382  */
383 enum tdb_attribute_type {
384         TDB_ATTRIBUTE_LOG = 0,
385         TDB_ATTRIBUTE_HASH = 1,
386         TDB_ATTRIBUTE_SEED = 2,
387         TDB_ATTRIBUTE_STATS = 3
388 };
389
390 /**
391  * struct tdb_attribute_base - common fields for all tdb attributes.
392  */
393 struct tdb_attribute_base {
394         enum tdb_attribute_type attr;
395         union tdb_attribute *next;
396 };
397
398 /**
399  * enum tdb_log_level - log levels for tdb_attribute_log
400  * @TDB_LOG_ERROR: used to log unrecoverable errors such as I/O errors
401  *                 or internal consistency failures.
402  * @TDB_LOG_USE_ERROR: used to log usage errors such as invalid parameters
403  *                 or writing to a read-only database.
404  * @TDB_LOG_WARNING: used for informational messages on issues which
405  *                   are unusual but handled by TDB internally, such
406  *                   as a failure to mmap or failure to open /dev/urandom.
407  */
408 enum tdb_log_level {
409         TDB_LOG_ERROR,
410         TDB_LOG_USE_ERROR,
411         TDB_LOG_WARNING
412 };
413
414 /**
415  * struct tdb_attribute_log - log function attribute
416  *
417  * This attribute provides a hook for you to log errors.
418  */
419 struct tdb_attribute_log {
420         struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG */
421         void (*log_fn)(struct tdb_context *tdb,
422                        enum tdb_log_level level,
423                        void *log_private,
424                        const char *message);
425         void *log_private;
426 };
427
428 /**
429  * struct tdb_attribute_hash - hash function attribute
430  *
431  * This attribute allows you to provide an alternative hash function.
432  * This hash function will be handed keys from the database; it will also
433  * be handed the 8-byte TDB_HASH_MAGIC value for checking the header (the
434  * tdb_open() will fail if the hash value doesn't match the header).
435  *
436  * Note that if your hash function gives different results on
437  * different machine endians, your tdb will no longer work across
438  * different architectures!
439  */
440 struct tdb_attribute_hash {
441         struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH */
442         uint64_t (*hash_fn)(const void *key, size_t len, uint64_t seed,
443                             void *priv);
444         void *hash_private;
445 };
446
447 /**
448  * struct tdb_attribute_seed - hash function seed attribute
449  *
450  * The hash function seed is normally taken from /dev/urandom (or equivalent)
451  * but can be set manually here.  This is mainly for testing purposes.
452  */
453 struct tdb_attribute_seed {
454         struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_SEED */
455         uint64_t seed;
456 };
457
458 /**
459  * struct tdb_attribute_stats - tdb operational statistics
460  *
461  * This attribute records statistics of various low-level TDB operations.
462  * This can be used to assist performance evaluation.
463  *
464  * New fields will be added at the end, hence the "size" argument which
465  * indicates how large your structure is.  If your size is larger than
466  * that known about by this version of tdb, the size will be reduced to
467  * the known structure size.  Thus you can detect older versions, and
468  * thus know that newer stats will not be updated.
469  */
470 struct tdb_attribute_stats {
471         struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_STATS */
472         size_t size; /* = sizeof(struct tdb_attribute_stats) */
473         uint64_t allocs;
474         uint64_t   alloc_subhash;
475         uint64_t   alloc_chain;
476         uint64_t   alloc_bucket_exact;
477         uint64_t   alloc_bucket_max;
478         uint64_t   alloc_leftover;
479         uint64_t   alloc_coalesce_tried;
480         uint64_t     alloc_coalesce_lockfail;
481         uint64_t     alloc_coalesce_race;
482         uint64_t     alloc_coalesce_succeeded;
483         uint64_t        alloc_coalesce_num_merged;
484         uint64_t compares;
485         uint64_t   compare_wrong_bucket;
486         uint64_t   compare_wrong_offsetbits;
487         uint64_t   compare_wrong_keylen;
488         uint64_t   compare_wrong_rechash;
489         uint64_t   compare_wrong_keycmp;
490         uint64_t expands;
491         uint64_t frees;
492         uint64_t locks;
493         uint64_t    lock_lowlevel;
494         uint64_t    lock_nonblock;
495 };
496
497 /**
498  * union tdb_attribute - tdb attributes.
499  *
500  * This represents all the known attributes.
501  *
502  * See also:
503  *      struct tdb_attribute_log, struct tdb_attribute_hash,
504  *      struct tdb_attribute_seed, struct tdb_attribute_stats.
505  */
506 union tdb_attribute {
507         struct tdb_attribute_base base;
508         struct tdb_attribute_log log;
509         struct tdb_attribute_hash hash;
510         struct tdb_attribute_seed seed;
511         struct tdb_attribute_stats stats;
512 };
513
514 /**
515  * tdb_null - a convenient value for errors.
516  */
517 extern struct tdb_data tdb_null;
518
519 #ifdef  __cplusplus
520 }
521 #endif
522
523 #endif /* tdb2.h */