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