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