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