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