]> git.ozlabs.org Git - ccan/blob - ccan/ntdb/ntdb.h
ntdb: next-generation trivial key-value database
[ccan] / ccan / ntdb / ntdb.h
1 #ifndef CCAN_NTDB_H
2 #define CCAN_NTDB_H
3
4 /*
5    NTDB: trivial database library version 2
6
7    Copyright (C) Andrew Tridgell 1999-2004
8    Copyright (C) Rusty Russell 2010-2012
9
10      ** NOTE! The following LGPL license applies to the ntdb
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 #ifdef HAVE_LIBREPLACE
33 #include <replace.h>
34 #include <system/filesys.h>
35 #else
36 #if HAVE_FILE_OFFSET_BITS
37 #define _FILE_OFFSET_BITS 64
38 #endif
39
40 #ifndef _PUBLIC_
41 #ifdef HAVE_VISIBILITY_ATTR
42 #define _PUBLIC_ __attribute__((visibility("default")))
43 #else
44 #define _PUBLIC_
45 #endif
46 #endif
47
48 /* For mode_t */
49 #include <sys/types.h>
50 /* For O_* flags. */
51 #include <sys/stat.h>
52 /* For sig_atomic_t. */
53 #include <signal.h>
54 /* For uint64_t */
55 #include <stdint.h>
56 /* For bool */
57 #include <stdbool.h>
58 /* For memcmp */
59 #include <string.h>
60 #endif
61
62 #if HAVE_CCAN
63 #include <ccan/compiler/compiler.h>
64 #include <ccan/typesafe_cb/typesafe_cb.h>
65 #include <ccan/cast/cast.h>
66 #else
67 #ifndef typesafe_cb_preargs
68 /* Failing to have CCAN just mean less typesafe protection, etc. */
69 #define typesafe_cb_preargs(rtype, atype, fn, arg, ...) \
70         ((rtype (*)(__VA_ARGS__, atype))(fn))
71 #endif
72 #ifndef cast_const
73 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
74 #define cast_const(type, expr) ((type)((intptr_t)(expr)))
75 #else
76 #define cast_const(type, expr) ((type *)(expr))
77 #endif
78 #endif
79 #endif /* !HAVE_CCAN */
80
81 union ntdb_attribute;
82 struct ntdb_context;
83
84 /**
85  * struct TDB_DATA - (n)tdb data blob
86  *
87  * To ease compatibility, we use 'struct TDB_DATA' from tdb.h, so if
88  * you want to include both tdb.h and ntdb.h, you need to #include
89  * tdb.h first.
90  */
91 #ifndef __TDB_H__
92 struct TDB_DATA {
93         unsigned char *dptr;
94         size_t dsize;
95 };
96 #endif
97
98 typedef struct TDB_DATA NTDB_DATA;
99
100 /**
101  * ntdb_open - open a database file
102  * @name: the file name (or database name if flags contains NTDB_INTERNAL)
103  * @ntdb_flags: options for this database
104  * @open_flags: flags argument for ntdb's open() call.
105  * @mode: mode argument for ntdb's open() call.
106  * @attributes: linked list of extra attributes for this ntdb.
107  *
108  * This call opens (and potentially creates) a database file.
109  * Multiple processes can have the NTDB file open at once.
110  *
111  * On failure it will return NULL, and set errno: it may also call
112  * any log attribute found in @attributes.
113  *
114  * See also:
115  *      union ntdb_attribute
116  */
117 struct ntdb_context *ntdb_open(const char *name, int ntdb_flags,
118                                int open_flags, mode_t mode,
119                                union ntdb_attribute *attributes);
120
121
122 /* flags for ntdb_open() */
123 #define NTDB_DEFAULT 0 /* just a readability place holder */
124 #define NTDB_INTERNAL 2 /* don't store on disk */
125 #define NTDB_NOLOCK   4 /* don't do any locking */
126 #define NTDB_NOMMAP   8 /* don't use mmap */
127 #define NTDB_CONVERT 16 /* convert endian */
128 #define NTDB_NOSYNC   64 /* don't use synchronous transactions */
129 #define NTDB_SEQNUM   128 /* maintain a sequence number */
130 #define NTDB_ALLOW_NESTING   256 /* fake nested transactions */
131 #define NTDB_RDONLY   512 /* implied by O_RDONLY */
132 #define NTDB_CANT_CHECK  2048 /* has a feature which we don't understand */
133
134 /**
135  * ntdb_close - close and free a ntdb.
136  * @ntdb: the ntdb context returned from ntdb_open()
137  *
138  * This always succeeds, in that @ntdb is unusable after this call.  But if
139  * some unexpected error occurred while closing, it will return non-zero
140  * (the only clue as to cause will be via the log attribute).
141  */
142 int ntdb_close(struct ntdb_context *ntdb);
143
144 /**
145  * enum NTDB_ERROR - error returns for NTDB
146  *
147  * See Also:
148  *      ntdb_errorstr()
149  */
150 enum NTDB_ERROR {
151         NTDB_SUCCESS    = 0,    /* No error. */
152         NTDB_ERR_CORRUPT = -1,  /* We read the db, and it was bogus. */
153         NTDB_ERR_IO     = -2,   /* We couldn't read/write the db. */
154         NTDB_ERR_LOCK   = -3,   /* Locking failed. */
155         NTDB_ERR_OOM    = -4,   /* Out of Memory. */
156         NTDB_ERR_EXISTS = -5,   /* The key already exists. */
157         NTDB_ERR_NOEXIST        = -6,   /* The key does not exist. */
158         NTDB_ERR_EINVAL = -7,   /* You're using it wrong. */
159         NTDB_ERR_RDONLY = -8,   /* The database is read-only. */
160         NTDB_ERR_LAST = NTDB_ERR_RDONLY
161 };
162
163 /**
164  * ntdb_store - store a key/value pair in a ntdb.
165  * @ntdb: the ntdb context returned from ntdb_open()
166  * @key: the key
167  * @dbuf: the data to associate with the key.
168  * @flag: NTDB_REPLACE, NTDB_INSERT or NTDB_MODIFY.
169  *
170  * This inserts (or overwrites) a key/value pair in the NTDB.  If flag
171  * is NTDB_REPLACE, it doesn't matter whether the key exists or not;
172  * NTDB_INSERT means it must not exist (returns NTDB_ERR_EXISTS otherwise),
173  * and NTDB_MODIFY means it must exist (returns NTDB_ERR_NOEXIST otherwise).
174  *
175  * On success, this returns NTDB_SUCCESS.
176  *
177  * See also:
178  *      ntdb_fetch, ntdb_transaction_start, ntdb_append, ntdb_delete.
179  */
180 enum NTDB_ERROR ntdb_store(struct ntdb_context *ntdb,
181                            NTDB_DATA key,
182                            NTDB_DATA dbuf,
183                            int flag);
184
185 /* flags to ntdb_store() */
186 #define NTDB_REPLACE 1          /* A readability place holder */
187 #define NTDB_INSERT 2           /* Don't overwrite an existing entry */
188 #define NTDB_MODIFY 3           /* Don't create an existing entry    */
189
190 /**
191  * ntdb_fetch - fetch a value from a ntdb.
192  * @ntdb: the ntdb context returned from ntdb_open()
193  * @key: the key
194  * @data: pointer to data.
195  *
196  * This looks up a key in the database and sets it in @data.
197  *
198  * If it returns NTDB_SUCCESS, the key was found: it is your
199  * responsibility to call free() on @data->dptr.
200  *
201  * Otherwise, it returns an error (usually, NTDB_ERR_NOEXIST) and @data is
202  * undefined.
203  */
204 enum NTDB_ERROR ntdb_fetch(struct ntdb_context *ntdb, NTDB_DATA key,
205                            NTDB_DATA *data);
206
207 /**
208  * ntdb_errorstr - map the ntdb error onto a constant readable string
209  * @ecode: the enum NTDB_ERROR to map.
210  *
211  * This is useful for displaying errors to users.
212  */
213 const char *ntdb_errorstr(enum NTDB_ERROR ecode);
214
215 /**
216  * ntdb_append - append a value to a key/value pair in a ntdb.
217  * @ntdb: the ntdb context returned from ntdb_open()
218  * @key: the key
219  * @dbuf: the data to append.
220  *
221  * This is equivalent to fetching a record, reallocating .dptr to add the
222  * data, and writing it back, only it's much more efficient.  If the key
223  * doesn't exist, it's equivalent to ntdb_store (with an additional hint that
224  * you expect to expand the record in future).
225  *
226  * See Also:
227  *      ntdb_fetch(), ntdb_store()
228  */
229 enum NTDB_ERROR ntdb_append(struct ntdb_context *ntdb,
230                             NTDB_DATA key, NTDB_DATA dbuf);
231
232 /**
233  * ntdb_delete - delete a key from a ntdb.
234  * @ntdb: the ntdb context returned from ntdb_open()
235  * @key: the key to delete.
236  *
237  * Returns NTDB_SUCCESS on success, or an error (usually NTDB_ERR_NOEXIST).
238  *
239  * See Also:
240  *      ntdb_fetch(), ntdb_store()
241  */
242 enum NTDB_ERROR ntdb_delete(struct ntdb_context *ntdb, NTDB_DATA key);
243
244 /**
245  * ntdb_exists - does a key exist in the database?
246  * @ntdb: the ntdb context returned from ntdb_open()
247  * @key: the key to search for.
248  *
249  * Returns true if it exists, or false if it doesn't or any other error.
250  */
251 bool ntdb_exists(struct ntdb_context *ntdb, NTDB_DATA key);
252
253 /**
254  * ntdb_deq - are NTDB_DATA equal?
255  * @a: one NTDB_DATA
256  * @b: another NTDB_DATA
257  */
258 static inline bool ntdb_deq(NTDB_DATA a, NTDB_DATA b)
259 {
260         return a.dsize == b.dsize && memcmp(a.dptr, b.dptr, a.dsize) == 0;
261 }
262
263 /**
264  * ntdb_mkdata - make a NTDB_DATA from const data
265  * @p: the constant pointer
266  * @len: the length
267  *
268  * As the dptr member of NTDB_DATA is not constant, you need to
269  * cast it.  This function keeps thost casts in one place, as well as
270  * suppressing the warning some compilers give when casting away a
271  * qualifier (eg. gcc with -Wcast-qual)
272  */
273 static inline NTDB_DATA ntdb_mkdata(const void *p, size_t len)
274 {
275         NTDB_DATA d;
276         d.dptr = cast_const(void *, p);
277         d.dsize = len;
278         return d;
279 }
280
281 /**
282  * ntdb_transaction_start - start a transaction
283  * @ntdb: the ntdb context returned from ntdb_open()
284  *
285  * This begins a series of atomic operations.  Other processes will be able
286  * to read the ntdb, but not alter it (they will block), nor will they see
287  * any changes until ntdb_transaction_commit() is called.
288  *
289  * Note that if the NTDB_ALLOW_NESTING flag is set, a ntdb_transaction_start()
290  * within a transaction will succeed, but it's not a real transaction:
291  * (1) An inner transaction which is committed is not actually committed until
292  *     the outer transaction is; if the outer transaction is cancelled, the
293  *     inner ones are discarded.
294  * (2) ntdb_transaction_cancel() marks the outer transaction as having an error,
295  *     so the final ntdb_transaction_commit() will fail.
296  * (3) the outer transaction will see the results of the inner transaction.
297  *
298  * See Also:
299  *      ntdb_transaction_cancel, ntdb_transaction_commit.
300  */
301 enum NTDB_ERROR ntdb_transaction_start(struct ntdb_context *ntdb);
302
303 /**
304  * ntdb_transaction_cancel - abandon a transaction
305  * @ntdb: the ntdb context returned from ntdb_open()
306  *
307  * This aborts a transaction, discarding any changes which were made.
308  * ntdb_close() does this implicitly.
309  */
310 void ntdb_transaction_cancel(struct ntdb_context *ntdb);
311
312 /**
313  * ntdb_transaction_commit - commit a transaction
314  * @ntdb: the ntdb context returned from ntdb_open()
315  *
316  * This completes a transaction, writing any changes which were made.
317  *
318  * fsync() is used to commit the transaction (unless NTDB_NOSYNC is set),
319  * making it robust against machine crashes, but very slow compared to
320  * other NTDB operations.
321  *
322  * A failure can only be caused by unexpected errors (eg. I/O or
323  * memory); this is no point looping on transaction failure.
324  *
325  * See Also:
326  *      ntdb_transaction_prepare_commit()
327  */
328 enum NTDB_ERROR ntdb_transaction_commit(struct ntdb_context *ntdb);
329
330 /**
331  * ntdb_transaction_prepare_commit - prepare to commit a transaction
332  * @ntdb: the ntdb context returned from ntdb_open()
333  *
334  * This ensures we have the resources to commit a transaction (using
335  * ntdb_transaction_commit): if this succeeds then a transaction will only
336  * fail if the write() or fsync() calls fail.
337  *
338  * If this fails you must still call ntdb_transaction_cancel() to cancel
339  * the transaction.
340  *
341  * See Also:
342  *      ntdb_transaction_commit()
343  */
344 enum NTDB_ERROR ntdb_transaction_prepare_commit(struct ntdb_context *ntdb);
345
346 /**
347  * ntdb_traverse - traverse a NTDB
348  * @ntdb: the ntdb context returned from ntdb_open()
349  * @fn: the function to call for every key/value pair (or NULL)
350  * @p: the pointer to hand to @f
351  *
352  * This walks the NTDB until all they keys have been traversed, or @fn
353  * returns non-zero.  If the traverse function or other processes are
354  * changing data or adding or deleting keys, the traverse may be
355  * unreliable: keys may be skipped or (rarely) visited twice.
356  *
357  * There is one specific exception: the special case of deleting the
358  * current key does not undermine the reliability of the traversal.
359  *
360  * On success, returns the number of keys iterated.  On error returns
361  * a negative enum NTDB_ERROR value.
362  */
363 #define ntdb_traverse(ntdb, fn, p)                                      \
364         ntdb_traverse_(ntdb, typesafe_cb_preargs(int, void *, (fn), (p), \
365                                                  struct ntdb_context *, \
366                                                  NTDB_DATA, NTDB_DATA), (p))
367
368 int64_t ntdb_traverse_(struct ntdb_context *ntdb,
369                        int (*fn)(struct ntdb_context *,
370                                  NTDB_DATA, NTDB_DATA, void *), void *p);
371
372 /**
373  * ntdb_parse_record - operate directly on data in the database.
374  * @ntdb: the ntdb context returned from ntdb_open()
375  * @key: the key whose record we should hand to @parse
376  * @parse: the function to call for the data
377  * @data: the private pointer to hand to @parse (types must match).
378  *
379  * This avoids a copy for many cases, by handing you a pointer into
380  * the memory-mapped database.  It also locks the record to prevent
381  * other accesses at the same time, so it won't change.
382  *
383  * Within the @parse callback you can perform read operations on the
384  * database, but no write operations: no ntdb_store() or
385  * ntdb_delete(), for example.  The exception is if you call
386  * ntdb_lockall() before ntdb_parse_record().
387  *
388  * Never alter the data handed to parse()!
389  */
390 #define ntdb_parse_record(ntdb, key, parse, data)                       \
391         ntdb_parse_record_((ntdb), (key),                               \
392                            typesafe_cb_preargs(enum NTDB_ERROR, void *, \
393                                                (parse), (data),         \
394                                                NTDB_DATA, NTDB_DATA), (data))
395
396 enum NTDB_ERROR ntdb_parse_record_(struct ntdb_context *ntdb,
397                                    NTDB_DATA key,
398                                    enum NTDB_ERROR (*parse)(NTDB_DATA k,
399                                                             NTDB_DATA d,
400                                                             void *data),
401                                    void *data);
402
403 /**
404  * ntdb_get_seqnum - get a database sequence number
405  * @ntdb: the ntdb context returned from ntdb_open()
406  *
407  * This returns a sequence number: any change to the database from a
408  * ntdb context opened with the NTDB_SEQNUM flag will cause that number
409  * to increment.  Note that the incrementing is unreliable (it is done
410  * without locking), so this is only useful as an optimization.
411  *
412  * For example, you may have a regular database backup routine which
413  * does not operate if the sequence number is unchanged.  In the
414  * unlikely event of a failed increment, it will be backed up next
415  * time any way.
416  *
417  * Returns an enum NTDB_ERROR (ie. negative) on error.
418  */
419 int64_t ntdb_get_seqnum(struct ntdb_context *ntdb);
420
421 /**
422  * ntdb_firstkey - get the "first" key in a NTDB
423  * @ntdb: the ntdb context returned from ntdb_open()
424  * @key: pointer to key.
425  *
426  * This returns an arbitrary key in the database; with ntdb_nextkey() it allows
427  * open-coded traversal of the database, though it is slightly less efficient
428  * than ntdb_traverse.
429  *
430  * It is your responsibility to free @key->dptr on success.
431  *
432  * Returns NTDB_ERR_NOEXIST if the database is empty.
433  */
434 enum NTDB_ERROR ntdb_firstkey(struct ntdb_context *ntdb, NTDB_DATA *key);
435
436 /**
437  * ntdb_nextkey - get the "next" key in a NTDB
438  * @ntdb: the ntdb context returned from ntdb_open()
439  * @key: a key returned by ntdb_firstkey() or ntdb_nextkey().
440  *
441  * This returns another key in the database; it will free @key.dptr for
442  * your convenience.
443  *
444  * Returns NTDB_ERR_NOEXIST if there are no more keys.
445  */
446 enum NTDB_ERROR ntdb_nextkey(struct ntdb_context *ntdb, NTDB_DATA *key);
447
448 /**
449  * ntdb_chainlock - lock a record in the NTDB
450  * @ntdb: the ntdb context returned from ntdb_open()
451  * @key: the key to lock.
452  *
453  * This prevents any access occurring to a group of keys including @key,
454  * even if @key does not exist.  This allows primitive atomic updates of
455  * records without using transactions.
456  *
457  * You cannot begin a transaction while holding a ntdb_chainlock(), nor can
458  * you do any operations on any other keys in the database.  This also means
459  * that you cannot hold more than one ntdb_chainlock() at a time.
460  *
461  * See Also:
462  *      ntdb_chainunlock()
463  */
464 enum NTDB_ERROR ntdb_chainlock(struct ntdb_context *ntdb, NTDB_DATA key);
465
466 /**
467  * ntdb_chainunlock - unlock a record in the NTDB
468  * @ntdb: the ntdb context returned from ntdb_open()
469  * @key: the key to unlock.
470  *
471  * The key must have previously been locked by ntdb_chainlock().
472  */
473 void ntdb_chainunlock(struct ntdb_context *ntdb, NTDB_DATA key);
474
475 /**
476  * ntdb_chainlock_read - lock a record in the NTDB, for reading
477  * @ntdb: the ntdb context returned from ntdb_open()
478  * @key: the key to lock.
479  *
480  * This prevents any changes from occurring to a group of keys including @key,
481  * even if @key does not exist.  This allows primitive atomic updates of
482  * records without using transactions.
483  *
484  * You cannot begin a transaction while holding a ntdb_chainlock_read(), nor can
485  * you do any operations on any other keys in the database.  This also means
486  * that you cannot hold more than one ntdb_chainlock()/read() at a time.
487  *
488  * See Also:
489  *      ntdb_chainlock()
490  */
491 enum NTDB_ERROR ntdb_chainlock_read(struct ntdb_context *ntdb, NTDB_DATA key);
492
493 /**
494  * ntdb_chainunlock_read - unlock a record in the NTDB for reading
495  * @ntdb: the ntdb context returned from ntdb_open()
496  * @key: the key to unlock.
497  *
498  * The key must have previously been locked by ntdb_chainlock_read().
499  */
500 void ntdb_chainunlock_read(struct ntdb_context *ntdb, NTDB_DATA key);
501
502 /**
503  * ntdb_lockall - lock the entire NTDB
504  * @ntdb: the ntdb context returned from ntdb_open()
505  *
506  * You cannot hold a ntdb_chainlock while calling this.  It nests, so you
507  * must call ntdb_unlockall as many times as you call ntdb_lockall.
508  */
509 enum NTDB_ERROR ntdb_lockall(struct ntdb_context *ntdb);
510
511 /**
512  * ntdb_unlockall - unlock the entire NTDB
513  * @ntdb: the ntdb context returned from ntdb_open()
514  */
515 void ntdb_unlockall(struct ntdb_context *ntdb);
516
517 /**
518  * ntdb_lockall_read - lock the entire NTDB for reading
519  * @ntdb: the ntdb context returned from ntdb_open()
520  *
521  * This prevents others writing to the database, eg. ntdb_delete, ntdb_store,
522  * ntdb_append, but not ntdb_fetch.
523  *
524  * You cannot hold a ntdb_chainlock while calling this.  It nests, so you
525  * must call ntdb_unlockall_read as many times as you call ntdb_lockall_read.
526  */
527 enum NTDB_ERROR ntdb_lockall_read(struct ntdb_context *ntdb);
528
529 /**
530  * ntdb_unlockall_read - unlock the entire NTDB for reading
531  * @ntdb: the ntdb context returned from ntdb_open()
532  */
533 void ntdb_unlockall_read(struct ntdb_context *ntdb);
534
535 /**
536  * ntdb_wipe_all - wipe the database clean
537  * @ntdb: the ntdb context returned from ntdb_open()
538  *
539  * Completely erase the database.  This is faster than iterating through
540  * each key and doing ntdb_delete.
541  */
542 enum NTDB_ERROR ntdb_wipe_all(struct ntdb_context *ntdb);
543
544 /**
545  * ntdb_repack - repack the database
546  * @ntdb: the ntdb context returned from ntdb_open()
547  *
548  * This repacks the database; if it is suffering from a great deal of
549  * fragmentation this might help.  However, it can take twice the
550  * memory of the existing NTDB.
551  */
552 enum NTDB_ERROR ntdb_repack(struct ntdb_context *ntdb);
553
554 /**
555  * ntdb_check - check a NTDB for consistency
556  * @ntdb: the ntdb context returned from ntdb_open()
557  * @check: function to check each key/data pair (or NULL)
558  * @data: argument for @check, must match type.
559  *
560  * This performs a consistency check of the open database, optionally calling
561  * a check() function on each record so you can do your own data consistency
562  * checks as well.  If check() returns an error, that is returned from
563  * ntdb_check().
564  *
565  * Note that the NTDB uses a feature which we don't understand which
566  * indicates we can't run ntdb_check(), this will log a warning to that
567  * effect and return NTDB_SUCCESS.  You can detect this condition by
568  * looking for NTDB_CANT_CHECK in ntdb_get_flags().
569  *
570  * Returns NTDB_SUCCESS or an error.
571  */
572 #define ntdb_check(ntdb, check, data)                                   \
573         ntdb_check_((ntdb), typesafe_cb_preargs(enum NTDB_ERROR, void *, \
574                                                 (check), (data),        \
575                                                 NTDB_DATA,              \
576                                                 NTDB_DATA),             \
577                     (data))
578
579 enum NTDB_ERROR ntdb_check_(struct ntdb_context *ntdb,
580                             enum NTDB_ERROR (*check)(NTDB_DATA k,
581                                                      NTDB_DATA d,
582                                                      void *data),
583                             void *data);
584
585 /**
586  * enum ntdb_summary_flags - flags for ntdb_summary.
587  */
588 enum ntdb_summary_flags {
589         NTDB_SUMMARY_HISTOGRAMS = 1 /* Draw graphs in the summary. */
590 };
591
592 /**
593  * ntdb_summary - return a string describing the NTDB state
594  * @ntdb: the ntdb context returned from ntdb_open()
595  * @flags: flags to control the summary output.
596  * @summary: pointer to string to allocate.
597  *
598  * This returns a developer-readable string describing the overall
599  * state of the ntdb, such as the percentage used and sizes of records.
600  * It is designed to provide information about the ntdb at a glance
601  * without displaying any keys or data in the database.
602  *
603  * On success, sets @summary to point to a malloc()'ed nul-terminated
604  * multi-line string.  It is your responsibility to free() it.
605  */
606 enum NTDB_ERROR ntdb_summary(struct ntdb_context *ntdb,
607                              enum ntdb_summary_flags flags,
608                              char **summary);
609
610
611 /**
612  * ntdb_get_flags - return the flags for a ntdb
613  * @ntdb: the ntdb context returned from ntdb_open()
614  *
615  * This returns the flags on the current ntdb.  Some of these are caused by
616  * the flags argument to ntdb_open(), others (such as NTDB_CONVERT) are
617  * intuited.
618  */
619 unsigned int ntdb_get_flags(struct ntdb_context *ntdb);
620
621 /**
622  * ntdb_add_flag - set a flag for a ntdb
623  * @ntdb: the ntdb context returned from ntdb_open()
624  * @flag: one of NTDB_NOLOCK, NTDB_NOMMAP, NTDB_NOSYNC or NTDB_ALLOW_NESTING.
625  *
626  * You can use this to set a flag on the NTDB.  You cannot set these flags
627  * on a NTDB_INTERNAL ntdb.
628  */
629 void ntdb_add_flag(struct ntdb_context *ntdb, unsigned flag);
630
631 /**
632  * ntdb_remove_flag - unset a flag for a ntdb
633  * @ntdb: the ntdb context returned from ntdb_open()
634  * @flag: one of NTDB_NOLOCK, NTDB_NOMMAP, NTDB_NOSYNC or NTDB_ALLOW_NESTING.
635  *
636  * You can use this to clear a flag on the NTDB.  You cannot clear flags
637  * on a NTDB_INTERNAL ntdb.
638  */
639 void ntdb_remove_flag(struct ntdb_context *ntdb, unsigned flag);
640
641 /**
642  * enum ntdb_attribute_type - descriminator for union ntdb_attribute.
643  */
644 enum ntdb_attribute_type {
645         NTDB_ATTRIBUTE_LOG = 0,
646         NTDB_ATTRIBUTE_HASH = 1,
647         NTDB_ATTRIBUTE_SEED = 2,
648         NTDB_ATTRIBUTE_STATS = 3,
649         NTDB_ATTRIBUTE_OPENHOOK = 4,
650         NTDB_ATTRIBUTE_FLOCK = 5,
651         NTDB_ATTRIBUTE_ALLOCATOR = 6,
652         NTDB_ATTRIBUTE_HASHSIZE = 7
653 };
654
655 /**
656  * ntdb_get_attribute - get an attribute for an existing ntdb
657  * @ntdb: the ntdb context returned from ntdb_open()
658  * @attr: the union ntdb_attribute to set.
659  *
660  * This gets an attribute from a NTDB which has previously been set (or
661  * may return the default values).  Set @attr.base.attr to the
662  * attribute type you want get.
663  */
664 enum NTDB_ERROR ntdb_get_attribute(struct ntdb_context *ntdb,
665                                    union ntdb_attribute *attr);
666
667 /**
668  * ntdb_set_attribute - set an attribute for an existing ntdb
669  * @ntdb: the ntdb context returned from ntdb_open()
670  * @attr: the union ntdb_attribute to set.
671  *
672  * This sets an attribute on a NTDB, overriding any previous attribute
673  * of the same type.  It returns NTDB_ERR_EINVAL if the attribute is
674  * unknown or invalid.
675  *
676  * Note that NTDB_ATTRIBUTE_HASH, NTDB_ATTRIBUTE_SEED, and
677  * NTDB_ATTRIBUTE_OPENHOOK cannot currently be set after ntdb_open.
678  */
679 enum NTDB_ERROR ntdb_set_attribute(struct ntdb_context *ntdb,
680                                    const union ntdb_attribute *attr);
681
682 /**
683  * ntdb_unset_attribute - reset an attribute for an existing ntdb
684  * @ntdb: the ntdb context returned from ntdb_open()
685  * @type: the attribute type to unset.
686  *
687  * This unsets an attribute on a NTDB, returning it to the defaults
688  * (where applicable).
689  *
690  * Note that it only makes sense for NTDB_ATTRIBUTE_LOG and NTDB_ATTRIBUTE_FLOCK
691  * to be unset.
692  */
693 void ntdb_unset_attribute(struct ntdb_context *ntdb,
694                           enum ntdb_attribute_type type);
695
696 /**
697  * ntdb_name - get the name of a ntdb
698  * @ntdb: the ntdb context returned from ntdb_open()
699  *
700  * This returns a copy of the name string, made at ntdb_open() time.
701  *
702  * This is mostly useful for logging.
703  */
704 const char *ntdb_name(const struct ntdb_context *ntdb);
705
706 /**
707  * ntdb_fd - get the file descriptor of a ntdb
708  * @ntdb: the ntdb context returned from ntdb_open()
709  *
710  * This returns the file descriptor for the underlying database file, or -1
711  * for NTDB_INTERNAL.
712  */
713 int ntdb_fd(const struct ntdb_context *ntdb);
714
715 /**
716  * ntdb_foreach - iterate through every open NTDB.
717  * @fn: the function to call for every NTDB
718  * @p: the pointer to hand to @fn
719  *
720  * NTDB internally keeps track of all open TDBs; this function allows you to
721  * iterate through them.  If @fn returns non-zero, traversal stops.
722  */
723 #define ntdb_foreach(fn, p)                                             \
724         ntdb_foreach_(typesafe_cb_preargs(int, void *, (fn), (p),       \
725                                           struct ntdb_context *), (p))
726
727 void ntdb_foreach_(int (*fn)(struct ntdb_context *, void *), void *p);
728
729 /**
730  * struct ntdb_attribute_base - common fields for all ntdb attributes.
731  */
732 struct ntdb_attribute_base {
733         enum ntdb_attribute_type attr;
734         union ntdb_attribute *next;
735 };
736
737 /**
738  * enum ntdb_log_level - log levels for ntdb_attribute_log
739  * @NTDB_LOG_ERROR: used to log unrecoverable errors such as I/O errors
740  *                 or internal consistency failures.
741  * @NTDB_LOG_USE_ERROR: used to log usage errors such as invalid parameters
742  *                 or writing to a read-only database.
743  * @NTDB_LOG_WARNING: used for informational messages on issues which
744  *                   are unusual but handled by NTDB internally, such
745  *                   as a failure to mmap or failure to open /dev/urandom.
746  *                   It's also used when ntdb_open() fails without O_CREAT
747  *                   because a file does not exist.
748  */
749 enum ntdb_log_level {
750         NTDB_LOG_ERROR,
751         NTDB_LOG_USE_ERROR,
752         NTDB_LOG_WARNING
753 };
754
755 /**
756  * struct ntdb_attribute_log - log function attribute
757  *
758  * This attribute provides a hook for you to log errors.
759  */
760 struct ntdb_attribute_log {
761         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_LOG */
762         void (*fn)(struct ntdb_context *ntdb,
763                    enum ntdb_log_level level,
764                    enum NTDB_ERROR ecode,
765                    const char *message,
766                    void *data);
767         void *data;
768 };
769
770 /**
771  * struct ntdb_attribute_hash - hash function attribute
772  *
773  * This attribute allows you to provide an alternative hash function.
774  * This hash function will be handed keys from the database; it will also
775  * be handed the 8-byte NTDB_HASH_MAGIC value for checking the header (the
776  * ntdb_open() will fail if the hash value doesn't match the header).
777  *
778  * Note that if your hash function gives different results on
779  * different machine endians, your ntdb will no longer work across
780  * different architectures!
781  */
782 struct ntdb_attribute_hash {
783         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_HASH */
784         uint32_t (*fn)(const void *key, size_t len, uint32_t seed,
785                        void *data);
786         void *data;
787 };
788
789 /**
790  * struct ntdb_attribute_seed - hash function seed attribute
791  *
792  * The hash function seed is normally taken from /dev/urandom (or equivalent)
793  * but can be set manually here.  This is mainly for testing purposes.
794  */
795 struct ntdb_attribute_seed {
796         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_SEED */
797         uint64_t seed;
798 };
799
800 /**
801  * struct ntdb_attribute_stats - ntdb operational statistics
802  *
803  * This attribute records statistics of various low-level NTDB operations.
804  * This can be used to assist performance evaluation.  This is only
805  * useful for ntdb_get_attribute().
806  *
807  * New fields will be added at the end, hence the "size" argument which
808  * indicates how large your structure is: it must be filled in before
809  * calling ntdb_get_attribute(), which will overwrite it with the size
810  * ntdb knows about.
811  */
812 struct ntdb_attribute_stats {
813         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_STATS */
814         size_t size; /* = sizeof(struct ntdb_attribute_stats) */
815         uint64_t allocs;
816         uint64_t   alloc_subhash;
817         uint64_t   alloc_chain;
818         uint64_t   alloc_bucket_exact;
819         uint64_t   alloc_bucket_max;
820         uint64_t   alloc_leftover;
821         uint64_t   alloc_coalesce_tried;
822         uint64_t     alloc_coalesce_iterate_clash;
823         uint64_t     alloc_coalesce_lockfail;
824         uint64_t     alloc_coalesce_race;
825         uint64_t     alloc_coalesce_succeeded;
826         uint64_t       alloc_coalesce_num_merged;
827         uint64_t compares;
828         uint64_t   compare_wrong_offsetbits;
829         uint64_t   compare_wrong_keylen;
830         uint64_t   compare_wrong_rechash;
831         uint64_t   compare_wrong_keycmp;
832         uint64_t transactions;
833         uint64_t   transaction_cancel;
834         uint64_t   transaction_nest;
835         uint64_t   transaction_expand_file;
836         uint64_t   transaction_read_direct;
837         uint64_t      transaction_read_direct_fail;
838         uint64_t   transaction_write_direct;
839         uint64_t      transaction_write_direct_fail;
840         uint64_t traverses;
841         uint64_t        traverse_val_vanished;
842         uint64_t expands;
843         uint64_t frees;
844         uint64_t locks;
845         uint64_t   lock_lowlevel;
846         uint64_t   lock_nonblock;
847         uint64_t     lock_nonblock_fail;
848 };
849
850 /**
851  * struct ntdb_attribute_openhook - ntdb special effects hook for open
852  *
853  * This attribute contains a function to call once we have the OPEN_LOCK
854  * for the ntdb, but before we've examined its contents.  If this succeeds,
855  * the ntdb will be populated if it's then zero-length.
856  *
857  * This is a hack to allow support for TDB-style TDB_CLEAR_IF_FIRST
858  * behaviour.
859  */
860 struct ntdb_attribute_openhook {
861         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_OPENHOOK */
862         enum NTDB_ERROR (*fn)(int fd, void *data);
863         void *data;
864 };
865
866 /**
867  * struct ntdb_attribute_flock - ntdb special effects hook for file locking
868  *
869  * This attribute contains function to call to place locks on a file; it can
870  * be used to support non-blocking operations or lock proxying.
871  *
872  * They should return 0 on success, -1 on failure and set errno.
873  *
874  * An error will be logged on error if errno is neither EAGAIN nor EINTR
875  * (normally it would only return EAGAIN if waitflag is false, and
876  * loop internally on EINTR).
877  */
878 struct ntdb_attribute_flock {
879         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_FLOCK */
880         int (*lock)(int fd,int rw, off_t off, off_t len, bool waitflag, void *);
881         int (*unlock)(int fd, int rw, off_t off, off_t len, void *);
882         void *data;
883 };
884
885 /**
886  * struct ntdb_attribute_hashsize - ntdb hashsize setting.
887  *
888  * This attribute is only settable on ntdb_open; it indicates that we create
889  * a hashtable of the given size, rather than the default.
890  */
891 struct ntdb_attribute_hashsize {
892         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_HASHSIZE */
893         uint32_t size;
894 };
895
896 /**
897  * struct ntdb_attribute_allocator - allocator for ntdb to use.
898  *
899  * You can replace malloc/free with your own allocation functions.
900  * The allocator takes an "owner" pointer, which is either NULL (for
901  * the initial struct ntdb_context and struct ntdb_file), or a
902  * previously allocated pointer.  This is useful for relationship
903  * tracking, such as the talloc library.
904  *
905  * The expand function is realloc, but only ever used to expand an
906  * existing allocation.
907  *
908  * Be careful mixing allocators: two ntdb_contexts which have the same file
909  * open will share the same struct ntdb_file.  This may be allocated by one
910  * ntdb's allocator, and freed by the other.
911  */
912 struct ntdb_attribute_allocator {
913         struct ntdb_attribute_base base; /* .attr = NTDB_ATTRIBUTE_ALLOCATOR */
914         void *(*alloc)(const void *owner, size_t len, void *priv_data);
915         void *(*expand)(void *old, size_t newlen, void *priv_data);
916         void (*free)(void *old, void *priv_data);
917         void *priv_data;
918 };
919
920 /**
921  * union ntdb_attribute - ntdb attributes.
922  *
923  * This represents all the known attributes.
924  *
925  * See also:
926  *      struct ntdb_attribute_log, struct ntdb_attribute_hash,
927  *      struct ntdb_attribute_seed, struct ntdb_attribute_stats,
928  *      struct ntdb_attribute_openhook, struct ntdb_attribute_flock,
929  *      struct ntdb_attribute_allocator alloc.
930  */
931 union ntdb_attribute {
932         struct ntdb_attribute_base base;
933         struct ntdb_attribute_log log;
934         struct ntdb_attribute_hash hash;
935         struct ntdb_attribute_seed seed;
936         struct ntdb_attribute_stats stats;
937         struct ntdb_attribute_openhook openhook;
938         struct ntdb_attribute_flock flock;
939         struct ntdb_attribute_allocator alloc;
940         struct ntdb_attribute_hashsize hashsize;
941 };
942
943 #ifdef  __cplusplus
944 }
945 #endif
946
947 #endif /* ntdb.h */