s3:dbwrap: Store warning thresholds in db_ctdb_ctx
[obnox/samba/samba-obnox.git] / source3 / lib / dbwrap / dbwrap_ctdb.c
1 /*
2    Unix SMB/CIFS implementation.
3    Database interface wrapper around ctdbd
4    Copyright (C) Volker Lendecke 2007-2009
5    Copyright (C) Michael Adam 2009
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/filesys.h"
23 #include "lib/tdb_wrap/tdb_wrap.h"
24 #include "util_tdb.h"
25 #include "dbwrap/dbwrap.h"
26 #include "dbwrap/dbwrap_ctdb.h"
27 #include "dbwrap/dbwrap_rbt.h"
28 #include "lib/param/param.h"
29
30 #ifdef CLUSTER_SUPPORT
31
32 /*
33  * It is not possible to include ctdb.h and tdb_compat.h (included via
34  * some other include above) without warnings. This fixes those
35  * warnings.
36  */
37
38 #ifdef typesafe_cb
39 #undef typesafe_cb
40 #endif
41
42 #ifdef typesafe_cb_preargs
43 #undef typesafe_cb_preargs
44 #endif
45
46 #ifdef typesafe_cb_postargs
47 #undef typesafe_cb_postargs
48 #endif
49
50 #include "ctdb.h"
51 #include "ctdb_private.h"
52 #include "ctdbd_conn.h"
53 #include "dbwrap/dbwrap.h"
54 #include "dbwrap/dbwrap_private.h"
55 #include "dbwrap/dbwrap_ctdb.h"
56 #include "g_lock.h"
57 #include "messages.h"
58
59 struct db_ctdb_transaction_handle {
60         struct db_ctdb_ctx *ctx;
61         /*
62          * we store the writes done under a transaction:
63          */
64         struct ctdb_marshall_buffer *m_write;
65         uint32_t nesting;
66         bool nested_cancel;
67         char *lock_name;
68 };
69
70 struct db_ctdb_ctx {
71         struct db_context *db;
72         struct tdb_wrap *wtdb;
73         uint32_t db_id;
74         struct db_ctdb_transaction_handle *transaction;
75         struct g_lock_ctx *lock_ctx;
76
77         /* thresholds for warning messages */
78         int warn_unlock_msecs;
79         int warn_migrate_msecs;
80         int warn_migrate_attempts;
81         int warn_locktime_msecs;
82 };
83
84 struct db_ctdb_rec {
85         struct db_ctdb_ctx *ctdb_ctx;
86         struct ctdb_ltdb_header header;
87         struct timeval lock_time;
88 };
89
90 static NTSTATUS tdb_error_to_ntstatus(struct tdb_context *tdb)
91 {
92         enum TDB_ERROR tret = tdb_error(tdb);
93
94         return map_nt_error_from_tdb(tret);
95 }
96
97 struct db_ctdb_ltdb_parse_state {
98         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
99                        TDB_DATA data, void *private_data);
100         void *private_data;
101 };
102
103 static int db_ctdb_ltdb_parser(TDB_DATA key, TDB_DATA data,
104                                void *private_data)
105 {
106         struct db_ctdb_ltdb_parse_state *state =
107                 (struct db_ctdb_ltdb_parse_state *)private_data;
108
109         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
110                 return -1;
111         }
112         if (data.dsize == sizeof(struct ctdb_ltdb_header)) {
113                 /*
114                  * Making this a separate case that needs fixing
115                  * separately. This is an empty record. ctdbd does not
116                  * distinguish between empty and deleted records. Samba right
117                  * now can live without empty records, so lets treat zero-size
118                  * (i.e. deleted) records as non-existing.
119                  */
120                 return -1;
121         }
122         state->parser(
123                 key, (struct ctdb_ltdb_header *)data.dptr,
124                 make_tdb_data(data.dptr + sizeof(struct ctdb_ltdb_header),
125                               data.dsize - sizeof(struct ctdb_ltdb_header)),
126                 state->private_data);
127         return 0;
128 }
129
130 static NTSTATUS db_ctdb_ltdb_parse(
131         struct db_ctdb_ctx *db, TDB_DATA key,
132         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
133                        TDB_DATA data, void *private_data),
134         void *private_data)
135 {
136         struct db_ctdb_ltdb_parse_state state;
137         int ret;
138
139         state.parser = parser;
140         state.private_data = private_data;
141
142         ret = tdb_parse_record(db->wtdb->tdb, key, db_ctdb_ltdb_parser,
143                                &state);
144         if (ret == -1) {
145                 return NT_STATUS_NOT_FOUND;
146         }
147         return NT_STATUS_OK;
148 }
149
150 /*
151  * Store a record together with the ctdb record header
152  * in the local copy of the database.
153  */
154 static NTSTATUS db_ctdb_ltdb_store(struct db_ctdb_ctx *db,
155                                    TDB_DATA key,
156                                    struct ctdb_ltdb_header *header,
157                                    TDB_DATA data)
158 {
159         TDB_DATA rec;
160         int ret;
161
162         rec.dsize = data.dsize + sizeof(struct ctdb_ltdb_header);
163         rec.dptr = (uint8_t *)talloc_size(talloc_tos(), rec.dsize);
164
165         if (rec.dptr == NULL) {
166                 return NT_STATUS_NO_MEMORY;
167         }
168
169         memcpy(rec.dptr, header, sizeof(struct ctdb_ltdb_header));
170         memcpy(sizeof(struct ctdb_ltdb_header) + (uint8_t *)rec.dptr, data.dptr, data.dsize);
171
172         ret = tdb_store(db->wtdb->tdb, key, rec, TDB_REPLACE);
173
174         talloc_free(rec.dptr);
175
176         return (ret == 0) ? NT_STATUS_OK
177                           : tdb_error_to_ntstatus(db->wtdb->tdb);
178
179 }
180
181 /*
182   form a ctdb_rec_data record from a key/data pair
183  */
184 static struct ctdb_rec_data *db_ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid,
185                                                   TDB_DATA key,
186                                                   struct ctdb_ltdb_header *header,
187                                                   TDB_DATA data)
188 {
189         size_t length;
190         struct ctdb_rec_data *d;
191
192         length = offsetof(struct ctdb_rec_data, data) + key.dsize +
193                 data.dsize + sizeof(*header);
194         d = (struct ctdb_rec_data *)talloc_size(mem_ctx, length);
195         if (d == NULL) {
196                 return NULL;
197         }
198         d->length = length;
199         d->reqid = reqid;
200         d->keylen = key.dsize;
201         memcpy(&d->data[0], key.dptr, key.dsize);
202
203         d->datalen = data.dsize + sizeof(*header);
204         memcpy(&d->data[key.dsize], header, sizeof(*header));
205         memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
206         return d;
207 }
208
209
210 /* helper function for marshalling multiple records */
211 static struct ctdb_marshall_buffer *db_ctdb_marshall_add(TALLOC_CTX *mem_ctx,
212                                                struct ctdb_marshall_buffer *m,
213                                                uint64_t db_id,
214                                                uint32_t reqid,
215                                                TDB_DATA key,
216                                                struct ctdb_ltdb_header *header,
217                                                TDB_DATA data)
218 {
219         struct ctdb_rec_data *r;
220         size_t m_size, r_size;
221         struct ctdb_marshall_buffer *m2 = NULL;
222
223         r = db_ctdb_marshall_record(talloc_tos(), reqid, key, header, data);
224         if (r == NULL) {
225                 talloc_free(m);
226                 return NULL;
227         }
228
229         if (m == NULL) {
230                 m = (struct ctdb_marshall_buffer *)talloc_zero_size(
231                         mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
232                 if (m == NULL) {
233                         goto done;
234                 }
235                 m->db_id = db_id;
236         }
237
238         m_size = talloc_get_size(m);
239         r_size = talloc_get_size(r);
240
241         m2 = (struct ctdb_marshall_buffer *)talloc_realloc_size(
242                 mem_ctx, m,  m_size + r_size);
243         if (m2 == NULL) {
244                 talloc_free(m);
245                 goto done;
246         }
247
248         memcpy(m_size + (uint8_t *)m2, r, r_size);
249
250         m2->count++;
251
252 done:
253         talloc_free(r);
254         return m2;
255 }
256
257 /* we've finished marshalling, return a data blob with the marshalled records */
258 static TDB_DATA db_ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
259 {
260         TDB_DATA data;
261         data.dptr = (uint8_t *)m;
262         data.dsize = talloc_get_size(m);
263         return data;
264 }
265
266 /*
267    loop over a marshalling buffer
268
269      - pass r==NULL to start
270      - loop the number of times indicated by m->count
271 */
272 static struct ctdb_rec_data *db_ctdb_marshall_loop_next_key(
273         struct ctdb_marshall_buffer *m, struct ctdb_rec_data *r, TDB_DATA *key)
274 {
275         if (r == NULL) {
276                 r = (struct ctdb_rec_data *)&m->data[0];
277         } else {
278                 r = (struct ctdb_rec_data *)(r->length + (uint8_t *)r);
279         }
280
281         key->dptr   = &r->data[0];
282         key->dsize  = r->keylen;
283         return r;
284 }
285
286 static bool db_ctdb_marshall_buf_parse(
287         struct ctdb_rec_data *r, uint32_t *reqid,
288         struct ctdb_ltdb_header **header, TDB_DATA *data)
289 {
290         if (r->datalen < sizeof(struct ctdb_ltdb_header)) {
291                 return false;
292         }
293
294         *reqid = r->reqid;
295
296         data->dptr  = &r->data[r->keylen] + sizeof(struct ctdb_ltdb_header);
297         data->dsize = r->datalen - sizeof(struct ctdb_ltdb_header);
298
299         *header = (struct ctdb_ltdb_header *)&r->data[r->keylen];
300
301         return true;
302 }
303
304 /**
305  * CTDB transaction destructor
306  */
307 static int db_ctdb_transaction_destructor(struct db_ctdb_transaction_handle *h)
308 {
309         NTSTATUS status;
310
311         status = g_lock_unlock(h->ctx->lock_ctx, h->lock_name);
312         if (!NT_STATUS_IS_OK(status)) {
313                 DEBUG(0, ("g_lock_unlock failed for %s: %s\n", h->lock_name,
314                           nt_errstr(status)));
315                 return -1;
316         }
317         return 0;
318 }
319
320 /**
321  * CTDB dbwrap API: transaction_start function
322  * starts a transaction on a persistent database
323  */
324 static int db_ctdb_transaction_start(struct db_context *db)
325 {
326         struct db_ctdb_transaction_handle *h;
327         NTSTATUS status;
328         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
329                                                         struct db_ctdb_ctx);
330
331         if (!db->persistent) {
332                 DEBUG(0,("transactions not supported on non-persistent database 0x%08x\n", 
333                          ctx->db_id));
334                 return -1;
335         }
336
337         if (ctx->transaction) {
338                 ctx->transaction->nesting++;
339                 DEBUG(5, (__location__ " transaction start on db 0x%08x: nesting %d -> %d\n",
340                           ctx->db_id, ctx->transaction->nesting - 1, ctx->transaction->nesting));
341                 return 0;
342         }
343
344         h = talloc_zero(db, struct db_ctdb_transaction_handle);
345         if (h == NULL) {
346                 DEBUG(0,(__location__ " oom for transaction handle\n"));
347                 return -1;
348         }
349
350         h->ctx = ctx;
351
352         h->lock_name = talloc_asprintf(h, "transaction_db_0x%08x",
353                                        (unsigned int)ctx->db_id);
354         if (h->lock_name == NULL) {
355                 DEBUG(0, ("talloc_asprintf failed\n"));
356                 TALLOC_FREE(h);
357                 return -1;
358         }
359
360         /*
361          * Wait a day, i.e. forever...
362          */
363         status = g_lock_lock(ctx->lock_ctx, h->lock_name, G_LOCK_WRITE,
364                              timeval_set(86400, 0));
365         if (!NT_STATUS_IS_OK(status)) {
366                 DEBUG(0, ("g_lock_lock failed: %s\n", nt_errstr(status)));
367                 TALLOC_FREE(h);
368                 return -1;
369         }
370
371         talloc_set_destructor(h, db_ctdb_transaction_destructor);
372
373         ctx->transaction = h;
374
375         DEBUG(5,(__location__ " transaction started on db 0x%08x\n", ctx->db_id));
376
377         return 0;
378 }
379
380 static bool parse_newest_in_marshall_buffer(
381         struct ctdb_marshall_buffer *buf, TDB_DATA key,
382         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
383                        TDB_DATA data, void *private_data),
384         void *private_data)
385 {
386         struct ctdb_rec_data *rec = NULL;
387         struct ctdb_ltdb_header *h = NULL;
388         TDB_DATA data;
389         int i;
390
391         if (buf == NULL) {
392                 return false;
393         }
394
395         /*
396          * Walk the list of records written during this
397          * transaction. If we want to read one we have already
398          * written, return the last written sample. Thus we do not do
399          * a "break;" for the first hit, this record might have been
400          * overwritten later.
401          */
402
403         for (i=0; i<buf->count; i++) {
404                 TDB_DATA tkey;
405                 uint32_t reqid;
406
407                 rec = db_ctdb_marshall_loop_next_key(buf, rec, &tkey);
408                 if (rec == NULL) {
409                         return false;
410                 }
411
412                 if (!tdb_data_equal(key, tkey)) {
413                         continue;
414                 }
415
416                 if (!db_ctdb_marshall_buf_parse(rec, &reqid, &h, &data)) {
417                         return false;
418                 }
419         }
420
421         if (h == NULL) {
422                 return false;
423         }
424
425         parser(key, h, data, private_data);
426
427         return true;
428 }
429
430 struct pull_newest_from_marshall_buffer_state {
431         struct ctdb_ltdb_header *pheader;
432         TALLOC_CTX *mem_ctx;
433         TDB_DATA *pdata;
434 };
435
436 static void pull_newest_from_marshall_buffer_parser(
437         TDB_DATA key, struct ctdb_ltdb_header *header,
438         TDB_DATA data, void *private_data)
439 {
440         struct pull_newest_from_marshall_buffer_state *state =
441                 (struct pull_newest_from_marshall_buffer_state *)private_data;
442
443         if (state->pheader != NULL) {
444                 memcpy(state->pheader, header, sizeof(*state->pheader));
445         }
446         if (state->pdata != NULL) {
447                 state->pdata->dsize = data.dsize;
448                 state->pdata->dptr = (uint8_t *)talloc_memdup(
449                         state->mem_ctx, data.dptr, data.dsize);
450         }
451 }
452
453 static bool pull_newest_from_marshall_buffer(struct ctdb_marshall_buffer *buf,
454                                              TDB_DATA key,
455                                              struct ctdb_ltdb_header *pheader,
456                                              TALLOC_CTX *mem_ctx,
457                                              TDB_DATA *pdata)
458 {
459         struct pull_newest_from_marshall_buffer_state state;
460
461         state.pheader = pheader;
462         state.mem_ctx = mem_ctx;
463         state.pdata = pdata;
464
465         if (!parse_newest_in_marshall_buffer(
466                     buf, key, pull_newest_from_marshall_buffer_parser,
467                     &state)) {
468                 return false;
469         }
470         if ((pdata != NULL) && (pdata->dsize != 0) && (pdata->dptr == NULL)) {
471                 /* ENOMEM */
472                 return false;
473         }
474         return true;
475 }
476
477 static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag);
478 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec);
479
480 static struct db_record *db_ctdb_fetch_locked_transaction(struct db_ctdb_ctx *ctx,
481                                                           TALLOC_CTX *mem_ctx,
482                                                           TDB_DATA key)
483 {
484         struct db_record *result;
485         TDB_DATA ctdb_data;
486
487         if (!(result = talloc(mem_ctx, struct db_record))) {
488                 DEBUG(0, ("talloc failed\n"));
489                 return NULL;
490         }
491
492         result->db = ctx->db;
493         result->private_data = ctx->transaction;
494
495         result->key.dsize = key.dsize;
496         result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
497                                                     key.dsize);
498         if (result->key.dptr == NULL) {
499                 DEBUG(0, ("talloc failed\n"));
500                 TALLOC_FREE(result);
501                 return NULL;
502         }
503
504         result->store = db_ctdb_store_transaction;
505         result->delete_rec = db_ctdb_delete_transaction;
506
507         if (pull_newest_from_marshall_buffer(ctx->transaction->m_write, key,
508                                              NULL, result, &result->value)) {
509                 return result;
510         }
511
512         ctdb_data = tdb_fetch_compat(ctx->wtdb->tdb, key);
513         if (ctdb_data.dptr == NULL) {
514                 /* create the record */
515                 result->value = tdb_null;
516                 return result;
517         }
518
519         result->value.dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);
520         result->value.dptr = NULL;
521
522         if ((result->value.dsize != 0)
523             && !(result->value.dptr = (uint8_t *)talloc_memdup(
524                          result, ctdb_data.dptr + sizeof(struct ctdb_ltdb_header),
525                          result->value.dsize))) {
526                 DEBUG(0, ("talloc failed\n"));
527                 TALLOC_FREE(result);
528         }
529
530         SAFE_FREE(ctdb_data.dptr);
531
532         return result;
533 }
534
535 static int db_ctdb_record_destructor(struct db_record **recp)
536 {
537         struct db_record *rec = talloc_get_type_abort(*recp, struct db_record);
538         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
539                 rec->private_data, struct db_ctdb_transaction_handle);
540         int ret = h->ctx->db->transaction_commit(h->ctx->db);
541         if (ret != 0) {
542                 DEBUG(0,(__location__ " transaction_commit failed\n"));
543         }
544         return 0;
545 }
546
547 /*
548   auto-create a transaction for persistent databases
549  */
550 static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx,
551                                                          TALLOC_CTX *mem_ctx,
552                                                          TDB_DATA key)
553 {
554         int res;
555         struct db_record *rec, **recp;
556
557         res = db_ctdb_transaction_start(ctx->db);
558         if (res == -1) {
559                 return NULL;
560         }
561
562         rec = db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
563         if (rec == NULL) {
564                 ctx->db->transaction_cancel(ctx->db);
565                 return NULL;
566         }
567
568         /* destroy this transaction when we release the lock */
569         recp = talloc(rec, struct db_record *);
570         if (recp == NULL) {
571                 ctx->db->transaction_cancel(ctx->db);
572                 talloc_free(rec);
573                 return NULL;
574         }
575         *recp = rec;
576         talloc_set_destructor(recp, db_ctdb_record_destructor);
577         return rec;
578 }
579
580
581 /*
582   stores a record inside a transaction
583  */
584 static NTSTATUS db_ctdb_transaction_store(struct db_ctdb_transaction_handle *h,
585                                           TDB_DATA key, TDB_DATA data)
586 {
587         TALLOC_CTX *tmp_ctx = talloc_new(h);
588         TDB_DATA rec;
589         struct ctdb_ltdb_header header;
590
591         ZERO_STRUCT(header);
592
593         /* we need the header so we can update the RSN */
594
595         if (!pull_newest_from_marshall_buffer(h->m_write, key, &header,
596                                               NULL, NULL)) {
597
598                 rec = tdb_fetch_compat(h->ctx->wtdb->tdb, key);
599
600                 if (rec.dptr != NULL) {
601                         memcpy(&header, rec.dptr,
602                                sizeof(struct ctdb_ltdb_header));
603                         rec.dsize -= sizeof(struct ctdb_ltdb_header);
604
605                         /*
606                          * a special case, we are writing the same
607                          * data that is there now
608                          */
609                         if (data.dsize == rec.dsize &&
610                             memcmp(data.dptr,
611                                    rec.dptr + sizeof(struct ctdb_ltdb_header),
612                                    data.dsize) == 0) {
613                                 SAFE_FREE(rec.dptr);
614                                 talloc_free(tmp_ctx);
615                                 return NT_STATUS_OK;
616                         }
617                 }
618                 SAFE_FREE(rec.dptr);
619         }
620
621         header.dmaster = get_my_vnn();
622         header.rsn++;
623
624         h->m_write = db_ctdb_marshall_add(h, h->m_write, h->ctx->db_id, 0, key, &header, data);
625         if (h->m_write == NULL) {
626                 DEBUG(0,(__location__ " Failed to add to marshalling record\n"));
627                 talloc_free(tmp_ctx);
628                 return NT_STATUS_NO_MEMORY;
629         }
630
631         talloc_free(tmp_ctx);
632         return NT_STATUS_OK;
633 }
634
635
636 /* 
637    a record store inside a transaction
638  */
639 static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag)
640 {
641         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
642                 rec->private_data, struct db_ctdb_transaction_handle);
643         NTSTATUS status;
644
645         status = db_ctdb_transaction_store(h, rec->key, data);
646         return status;
647 }
648
649 /*
650    a record delete inside a transaction
651  */
652 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec)
653 {
654         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
655                 rec->private_data, struct db_ctdb_transaction_handle);
656         NTSTATUS status;
657
658         status =  db_ctdb_transaction_store(h, rec->key, tdb_null);
659         return status;
660 }
661
662 static void db_ctdb_fetch_db_seqnum_parser(
663         TDB_DATA key, struct ctdb_ltdb_header *header,
664         TDB_DATA data, void *private_data)
665 {
666         uint64_t *seqnum = (uint64_t *)private_data;
667
668         if (data.dsize != sizeof(uint64_t)) {
669                 *seqnum = 0;
670                 return;
671         }
672         memcpy(seqnum, data.dptr, sizeof(*seqnum));
673 }
674
675 /**
676  * Fetch the db sequence number of a persistent db directly from the db.
677  */
678 static NTSTATUS db_ctdb_fetch_db_seqnum_from_db(struct db_ctdb_ctx *db,
679                                                 uint64_t *seqnum)
680 {
681         NTSTATUS status;
682         TDB_DATA key;
683
684         if (seqnum == NULL) {
685                 return NT_STATUS_INVALID_PARAMETER;
686         }
687
688         key = string_term_tdb_data(CTDB_DB_SEQNUM_KEY);
689
690         status = db_ctdb_ltdb_parse(
691                 db, key, db_ctdb_fetch_db_seqnum_parser, seqnum);
692
693         if (NT_STATUS_IS_OK(status)) {
694                 return NT_STATUS_OK;
695         }
696         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
697                 *seqnum = 0;
698                 return NT_STATUS_OK;
699         }
700         return status;
701 }
702
703 /**
704  * Store the database sequence number inside a transaction.
705  */
706 static NTSTATUS db_ctdb_store_db_seqnum(struct db_ctdb_transaction_handle *h,
707                                         uint64_t seqnum)
708 {
709         NTSTATUS status;
710         const char *keyname = CTDB_DB_SEQNUM_KEY;
711         TDB_DATA key;
712         TDB_DATA data;
713
714         key = string_term_tdb_data(keyname);
715
716         data.dptr = (uint8_t *)&seqnum;
717         data.dsize = sizeof(uint64_t);
718
719         status = db_ctdb_transaction_store(h, key, data);
720
721         return status;
722 }
723
724 /*
725   commit a transaction
726  */
727 static int db_ctdb_transaction_commit(struct db_context *db)
728 {
729         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
730                                                         struct db_ctdb_ctx);
731         NTSTATUS rets;
732         int status;
733         struct db_ctdb_transaction_handle *h = ctx->transaction;
734         uint64_t old_seqnum, new_seqnum;
735         int ret;
736
737         if (h == NULL) {
738                 DEBUG(0,(__location__ " transaction commit with no open transaction on db 0x%08x\n", ctx->db_id));
739                 return -1;
740         }
741
742         if (h->nested_cancel) {
743                 db->transaction_cancel(db);
744                 DEBUG(5,(__location__ " Failed transaction commit after nested cancel\n"));
745                 return -1;
746         }
747
748         if (h->nesting != 0) {
749                 h->nesting--;
750                 DEBUG(5, (__location__ " transaction commit on db 0x%08x: nesting %d -> %d\n",
751                           ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
752                 return 0;
753         }
754
755         if (h->m_write == NULL) {
756                 /*
757                  * No changes were made, so don't change the seqnum,
758                  * don't push to other node, just exit with success.
759                  */
760                 ret = 0;
761                 goto done;
762         }
763
764         DEBUG(5,(__location__ " transaction commit on db 0x%08x\n", ctx->db_id));
765
766         /*
767          * As the last db action before committing, bump the database sequence
768          * number. Note that this undoes all changes to the seqnum records
769          * performed under the transaction. This record is not meant to be
770          * modified by user interaction. It is for internal use only...
771          */
772         rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &old_seqnum);
773         if (!NT_STATUS_IS_OK(rets)) {
774                 DEBUG(1, (__location__ " failed to fetch the db sequence number "
775                           "in transaction commit on db 0x%08x\n", ctx->db_id));
776                 ret = -1;
777                 goto done;
778         }
779
780         new_seqnum = old_seqnum + 1;
781
782         rets = db_ctdb_store_db_seqnum(h, new_seqnum);
783         if (!NT_STATUS_IS_OK(rets)) {
784                 DEBUG(1, (__location__ "failed to store the db sequence number "
785                           " in transaction commit on db 0x%08x\n", ctx->db_id));
786                 ret = -1;
787                 goto done;
788         }
789
790 again:
791         /* tell ctdbd to commit to the other nodes */
792         rets = ctdbd_control_local(messaging_ctdbd_connection(),
793                                    CTDB_CONTROL_TRANS3_COMMIT,
794                                    h->ctx->db_id, 0,
795                                    db_ctdb_marshall_finish(h->m_write),
796                                    NULL, NULL, &status);
797         if (!NT_STATUS_IS_OK(rets) || status != 0) {
798                 /*
799                  * The TRANS3_COMMIT control should only possibly fail when a
800                  * recovery has been running concurrently. In any case, the db
801                  * will be the same on all nodes, either the new copy or the
802                  * old copy.  This can be detected by comparing the old and new
803                  * local sequence numbers.
804                  */
805                 rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &new_seqnum);
806                 if (!NT_STATUS_IS_OK(rets)) {
807                         DEBUG(1, (__location__ " failed to refetch db sequence "
808                                   "number after failed TRANS3_COMMIT\n"));
809                         ret = -1;
810                         goto done;
811                 }
812
813                 if (new_seqnum == old_seqnum) {
814                         /* Recovery prevented all our changes: retry. */
815                         goto again;
816                 }
817                 if (new_seqnum != (old_seqnum + 1)) {
818                         DEBUG(0, (__location__ " ERROR: new_seqnum[%lu] != "
819                                   "old_seqnum[%lu] + (0 or 1) after failed "
820                                   "TRANS3_COMMIT - this should not happen!\n",
821                                   (unsigned long)new_seqnum,
822                                   (unsigned long)old_seqnum));
823                         ret = -1;
824                         goto done;
825                 }
826                 /*
827                  * Recovery propagated our changes to all nodes, completing
828                  * our commit for us - succeed.
829                  */
830         }
831
832         ret = 0;
833
834 done:
835         h->ctx->transaction = NULL;
836         talloc_free(h);
837         return ret;
838 }
839
840
841 /*
842   cancel a transaction
843  */
844 static int db_ctdb_transaction_cancel(struct db_context *db)
845 {
846         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
847                                                         struct db_ctdb_ctx);
848         struct db_ctdb_transaction_handle *h = ctx->transaction;
849
850         if (h == NULL) {
851                 DEBUG(0,(__location__ " transaction cancel with no open transaction on db 0x%08x\n", ctx->db_id));
852                 return -1;
853         }
854
855         if (h->nesting != 0) {
856                 h->nesting--;
857                 h->nested_cancel = true;
858                 DEBUG(5, (__location__ " transaction cancel on db 0x%08x: nesting %d -> %d\n",
859                           ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
860                 return 0;
861         }
862
863         DEBUG(5,(__location__ " Cancel transaction on db 0x%08x\n", ctx->db_id));
864
865         ctx->transaction = NULL;
866         talloc_free(h);
867         return 0;
868 }
869
870
871 static NTSTATUS db_ctdb_store(struct db_record *rec, TDB_DATA data, int flag)
872 {
873         struct db_ctdb_rec *crec = talloc_get_type_abort(
874                 rec->private_data, struct db_ctdb_rec);
875
876         return db_ctdb_ltdb_store(crec->ctdb_ctx, rec->key, &(crec->header), data);
877 }
878
879
880
881 #ifdef HAVE_CTDB_CONTROL_SCHEDULE_FOR_DELETION_DECL
882 static NTSTATUS db_ctdb_send_schedule_for_deletion(struct db_record *rec)
883 {
884         NTSTATUS status;
885         struct ctdb_control_schedule_for_deletion *dd;
886         TDB_DATA indata;
887         int cstatus;
888         struct db_ctdb_rec *crec = talloc_get_type_abort(
889                 rec->private_data, struct db_ctdb_rec);
890
891         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + rec->key.dsize;
892         indata.dptr = talloc_zero_array(crec, uint8_t, indata.dsize);
893         if (indata.dptr == NULL) {
894                 DEBUG(0, (__location__ " talloc failed!\n"));
895                 return NT_STATUS_NO_MEMORY;
896         }
897
898         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
899         dd->db_id = crec->ctdb_ctx->db_id;
900         dd->hdr = crec->header;
901         dd->keylen = rec->key.dsize;
902         memcpy(dd->key, rec->key.dptr, rec->key.dsize);
903
904         status = ctdbd_control_local(messaging_ctdbd_connection(),
905                                      CTDB_CONTROL_SCHEDULE_FOR_DELETION,
906                                      crec->ctdb_ctx->db_id,
907                                      CTDB_CTRL_FLAG_NOREPLY, /* flags */
908                                      indata,
909                                      NULL, /* outdata */
910                                      NULL, /* errmsg */
911                                      &cstatus);
912         talloc_free(indata.dptr);
913
914         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
915                 DEBUG(1, (__location__ " Error sending local control "
916                           "SCHEDULE_FOR_DELETION: %s, cstatus = %d\n",
917                           nt_errstr(status), cstatus));
918                 if (NT_STATUS_IS_OK(status)) {
919                         status = NT_STATUS_UNSUCCESSFUL;
920                 }
921         }
922
923         return status;
924 }
925 #endif
926
927 static NTSTATUS db_ctdb_delete(struct db_record *rec)
928 {
929         NTSTATUS status;
930
931         /*
932          * We have to store the header with empty data. TODO: Fix the
933          * tdb-level cleanup
934          */
935
936         status = db_ctdb_store(rec, tdb_null, 0);
937         if (!NT_STATUS_IS_OK(status)) {
938                 return status;
939         }
940
941 #ifdef HAVE_CTDB_CONTROL_SCHEDULE_FOR_DELETION_DECL
942         status = db_ctdb_send_schedule_for_deletion(rec);
943 #endif
944
945         return status;
946 }
947
948 static int db_ctdb_record_destr(struct db_record* data)
949 {
950         struct db_ctdb_rec *crec = talloc_get_type_abort(
951                 data->private_data, struct db_ctdb_rec);
952         int threshold;
953         int ret;
954         struct timeval before;
955         double timediff;
956
957         DEBUG(10, (DEBUGLEVEL > 10
958                    ? "Unlocking db %u key %s\n"
959                    : "Unlocking db %u key %.20s\n",
960                    (int)crec->ctdb_ctx->db_id,
961                    hex_encode_talloc(data, (unsigned char *)data->key.dptr,
962                               data->key.dsize)));
963
964         before = timeval_current();
965
966         ret = tdb_chainunlock(crec->ctdb_ctx->wtdb->tdb, data->key);
967
968         timediff = timeval_elapsed(&before);
969         timediff *= 1000;       /* get us milliseconds */
970
971         if (timediff > crec->ctdb_ctx->warn_unlock_msecs) {
972                 char *key;
973                 key = hex_encode_talloc(talloc_tos(),
974                                         (unsigned char *)data->key.dptr,
975                                         data->key.dsize);
976                 DEBUG(0, ("tdb_chainunlock on db %s, key %s took %f milliseconds\n",
977                           tdb_name(crec->ctdb_ctx->wtdb->tdb), key,
978                           timediff));
979                 TALLOC_FREE(key);
980         }
981
982         if (ret != 0) {
983                 DEBUG(0, ("tdb_chainunlock failed\n"));
984                 return -1;
985         }
986
987         threshold = crec->ctdb_ctx->warn_locktime_msecs;
988         if (threshold != 0) {
989                 timediff = timeval_elapsed(&crec->lock_time);
990                 if ((timediff * 1000) > threshold) {
991                         const char *key;
992
993                         key = hex_encode_talloc(data,
994                                                 (unsigned char *)data->key.dptr,
995                                                 data->key.dsize);
996                         DEBUG(0, ("Held tdb lock on db %s, key %s %f seconds\n",
997                                   tdb_name(crec->ctdb_ctx->wtdb->tdb), key,
998                                   timediff));
999                 }
1000         }
1001
1002         return 0;
1003 }
1004
1005 /**
1006  * Check whether we have a valid local copy of the given record,
1007  * either for reading or for writing.
1008  */
1009 static bool db_ctdb_can_use_local_hdr(const struct ctdb_ltdb_header *hdr,
1010                                       bool read_only)
1011 {
1012 #ifdef HAVE_CTDB_WANT_READONLY_DECL
1013         if (hdr->dmaster != get_my_vnn()) {
1014                 /* If we're not dmaster, it must be r/o copy. */
1015                 return read_only && (hdr->flags & CTDB_REC_RO_HAVE_READONLY);
1016         }
1017
1018         /*
1019          * If we want write access, no one may have r/o copies.
1020          */
1021         return read_only || !(hdr->flags & CTDB_REC_RO_HAVE_DELEGATIONS);
1022 #else
1023         return (hdr->dmaster == get_my_vnn());
1024 #endif
1025 }
1026
1027 static bool db_ctdb_can_use_local_copy(TDB_DATA ctdb_data, bool read_only)
1028 {
1029         if (ctdb_data.dptr == NULL) {
1030                 return false;
1031         }
1032
1033         if (ctdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
1034                 return false;
1035         }
1036
1037         return db_ctdb_can_use_local_hdr(
1038                 (struct ctdb_ltdb_header *)ctdb_data.dptr, read_only);
1039 }
1040
1041 static struct db_record *fetch_locked_internal(struct db_ctdb_ctx *ctx,
1042                                                TALLOC_CTX *mem_ctx,
1043                                                TDB_DATA key,
1044                                                bool tryonly)
1045 {
1046         struct db_record *result;
1047         struct db_ctdb_rec *crec;
1048         NTSTATUS status;
1049         TDB_DATA ctdb_data;
1050         int migrate_attempts;
1051         struct timeval migrate_start;
1052         struct timeval chainlock_start;
1053         struct timeval ctdb_start_time;
1054         double chainlock_time = 0;
1055         double ctdb_time = 0;
1056         int duration_msecs;
1057         int lockret;
1058
1059         if (!(result = talloc(mem_ctx, struct db_record))) {
1060                 DEBUG(0, ("talloc failed\n"));
1061                 return NULL;
1062         }
1063
1064         if (!(crec = talloc_zero(result, struct db_ctdb_rec))) {
1065                 DEBUG(0, ("talloc failed\n"));
1066                 TALLOC_FREE(result);
1067                 return NULL;
1068         }
1069
1070         result->db = ctx->db;
1071         result->private_data = (void *)crec;
1072         crec->ctdb_ctx = ctx;
1073
1074         result->key.dsize = key.dsize;
1075         result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
1076                                                     key.dsize);
1077         if (result->key.dptr == NULL) {
1078                 DEBUG(0, ("talloc failed\n"));
1079                 TALLOC_FREE(result);
1080                 return NULL;
1081         }
1082
1083         migrate_attempts = 0;
1084         GetTimeOfDay(&migrate_start);
1085
1086         /*
1087          * Do a blocking lock on the record
1088          */
1089 again:
1090
1091         if (DEBUGLEVEL >= 10) {
1092                 char *keystr = hex_encode_talloc(result, key.dptr, key.dsize);
1093                 DEBUG(10, (DEBUGLEVEL > 10
1094                            ? "Locking db %u key %s\n"
1095                            : "Locking db %u key %.20s\n",
1096                            (int)crec->ctdb_ctx->db_id, keystr));
1097                 TALLOC_FREE(keystr);
1098         }
1099
1100         GetTimeOfDay(&chainlock_start);
1101         lockret = tryonly
1102                 ? tdb_chainlock_nonblock(ctx->wtdb->tdb, key)
1103                 : tdb_chainlock(ctx->wtdb->tdb, key);
1104         chainlock_time += timeval_elapsed(&chainlock_start);
1105
1106         if (lockret != 0) {
1107                 DEBUG(3, ("tdb_chainlock failed\n"));
1108                 TALLOC_FREE(result);
1109                 return NULL;
1110         }
1111
1112         result->store = db_ctdb_store;
1113         result->delete_rec = db_ctdb_delete;
1114         talloc_set_destructor(result, db_ctdb_record_destr);
1115
1116         ctdb_data = tdb_fetch_compat(ctx->wtdb->tdb, key);
1117
1118         /*
1119          * See if we have a valid record and we are the dmaster. If so, we can
1120          * take the shortcut and just return it.
1121          */
1122
1123         if (!db_ctdb_can_use_local_copy(ctdb_data, false)) {
1124                 SAFE_FREE(ctdb_data.dptr);
1125                 tdb_chainunlock(ctx->wtdb->tdb, key);
1126                 talloc_set_destructor(result, NULL);
1127
1128                 if (tryonly && (migrate_attempts != 0)) {
1129                         DEBUG(5, ("record migrated away again\n"));
1130                         TALLOC_FREE(result);
1131                         return NULL;
1132                 }
1133
1134                 migrate_attempts += 1;
1135
1136                 DEBUG(10, ("ctdb_data.dptr = %p, dmaster = %u (%u) %u\n",
1137                            ctdb_data.dptr, ctdb_data.dptr ?
1138                            ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster : -1,
1139                            get_my_vnn(),
1140                            ctdb_data.dptr ?
1141                            ((struct ctdb_ltdb_header *)ctdb_data.dptr)->flags : 0));
1142
1143                 GetTimeOfDay(&ctdb_start_time);
1144                 status = ctdbd_migrate(messaging_ctdbd_connection(), ctx->db_id,
1145                                        key);
1146                 ctdb_time += timeval_elapsed(&ctdb_start_time);
1147
1148                 if (!NT_STATUS_IS_OK(status)) {
1149                         DEBUG(5, ("ctdb_migrate failed: %s\n",
1150                                   nt_errstr(status)));
1151                         TALLOC_FREE(result);
1152                         return NULL;
1153                 }
1154                 /* now its migrated, try again */
1155                 goto again;
1156         }
1157
1158         {
1159                 double duration;
1160                 duration = timeval_elapsed(&migrate_start);
1161
1162                 /*
1163                  * Convert the duration to milliseconds to avoid a
1164                  * floating-point division of
1165                  * lp_parm_int("migrate_duration") by 1000.
1166                  */
1167                 duration_msecs = duration * 1000;
1168         }
1169
1170         if ((migrate_attempts > ctx->warn_migrate_attempts) ||
1171             (duration_msecs > ctx->warn_migrate_msecs)) {
1172                 int chain = 0;
1173
1174                 if (tdb_get_flags(ctx->wtdb->tdb) & TDB_INCOMPATIBLE_HASH) {
1175                         chain = tdb_jenkins_hash(&key) %
1176                                 tdb_hash_size(ctx->wtdb->tdb);
1177                 }
1178
1179                 DEBUG(0, ("db_ctdb_fetch_locked for %s key %s, chain %d "
1180                           "needed %d attempts, %d milliseconds, "
1181                           "chainlock: %d ms, CTDB %d ms\n",
1182                           tdb_name(ctx->wtdb->tdb),
1183                           hex_encode_talloc(talloc_tos(),
1184                                             (unsigned char *)key.dptr,
1185                                             key.dsize),
1186                           chain,
1187                           migrate_attempts, duration_msecs,
1188                           (int) chainlock_time * 1000,
1189                           (int) ctdb_time * 1000));
1190         }
1191
1192         GetTimeOfDay(&crec->lock_time);
1193
1194         memcpy(&crec->header, ctdb_data.dptr, sizeof(crec->header));
1195
1196         result->value.dsize = ctdb_data.dsize - sizeof(crec->header);
1197         result->value.dptr = NULL;
1198
1199         if ((result->value.dsize != 0)
1200             && !(result->value.dptr = (uint8_t *)talloc_memdup(
1201                          result, ctdb_data.dptr + sizeof(crec->header),
1202                          result->value.dsize))) {
1203                 DEBUG(0, ("talloc failed\n"));
1204                 TALLOC_FREE(result);
1205         }
1206
1207         SAFE_FREE(ctdb_data.dptr);
1208
1209         return result;
1210 }
1211
1212 static struct db_record *db_ctdb_fetch_locked(struct db_context *db,
1213                                               TALLOC_CTX *mem_ctx,
1214                                               TDB_DATA key)
1215 {
1216         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1217                                                         struct db_ctdb_ctx);
1218
1219         if (ctx->transaction != NULL) {
1220                 return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
1221         }
1222
1223         if (db->persistent) {
1224                 return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
1225         }
1226
1227         return fetch_locked_internal(ctx, mem_ctx, key, false);
1228 }
1229
1230 static struct db_record *db_ctdb_try_fetch_locked(struct db_context *db,
1231                                                   TALLOC_CTX *mem_ctx,
1232                                                   TDB_DATA key)
1233 {
1234         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1235                                                         struct db_ctdb_ctx);
1236
1237         if (ctx->transaction != NULL) {
1238                 return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
1239         }
1240
1241         if (db->persistent) {
1242                 return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
1243         }
1244
1245         return fetch_locked_internal(ctx, mem_ctx, key, true);
1246 }
1247
1248 struct db_ctdb_parse_record_state {
1249         void (*parser)(TDB_DATA key, TDB_DATA data, void *private_data);
1250         void *private_data;
1251         bool ask_for_readonly_copy;
1252         bool done;
1253 };
1254
1255 static void db_ctdb_parse_record_parser(
1256         TDB_DATA key, struct ctdb_ltdb_header *header,
1257         TDB_DATA data, void *private_data)
1258 {
1259         struct db_ctdb_parse_record_state *state =
1260                 (struct db_ctdb_parse_record_state *)private_data;
1261         state->parser(key, data, state->private_data);
1262 }
1263
1264 static void db_ctdb_parse_record_parser_nonpersistent(
1265         TDB_DATA key, struct ctdb_ltdb_header *header,
1266         TDB_DATA data, void *private_data)
1267 {
1268         struct db_ctdb_parse_record_state *state =
1269                 (struct db_ctdb_parse_record_state *)private_data;
1270
1271         if (db_ctdb_can_use_local_hdr(header, true)) {
1272                 state->parser(key, data, state->private_data);
1273                 state->done = true;
1274         } else {
1275                 /*
1276                  * We found something in the db, so it seems that this record,
1277                  * while not usable locally right now, is popular. Ask for a
1278                  * R/O copy.
1279                  */
1280                 state->ask_for_readonly_copy = true;
1281         }
1282 }
1283
1284 static NTSTATUS db_ctdb_parse_record(struct db_context *db, TDB_DATA key,
1285                                      void (*parser)(TDB_DATA key,
1286                                                     TDB_DATA data,
1287                                                     void *private_data),
1288                                      void *private_data)
1289 {
1290         struct db_ctdb_ctx *ctx = talloc_get_type_abort(
1291                 db->private_data, struct db_ctdb_ctx);
1292         struct db_ctdb_parse_record_state state;
1293         NTSTATUS status;
1294
1295         state.parser = parser;
1296         state.private_data = private_data;
1297
1298         if (ctx->transaction != NULL) {
1299                 struct db_ctdb_transaction_handle *h = ctx->transaction;
1300                 bool found;
1301
1302                 /*
1303                  * Transactions only happen for persistent db's.
1304                  */
1305
1306                 found = parse_newest_in_marshall_buffer(
1307                         h->m_write, key, db_ctdb_parse_record_parser, &state);
1308
1309                 if (found) {
1310                         return NT_STATUS_OK;
1311                 }
1312         }
1313
1314         if (db->persistent) {
1315                 /*
1316                  * Persistent db, but not found in the transaction buffer
1317                  */
1318                 return db_ctdb_ltdb_parse(
1319                         ctx, key, db_ctdb_parse_record_parser, &state);
1320         }
1321
1322         state.done = false;
1323         state.ask_for_readonly_copy = false;
1324
1325         status = db_ctdb_ltdb_parse(
1326                 ctx, key, db_ctdb_parse_record_parser_nonpersistent, &state);
1327         if (NT_STATUS_IS_OK(status) && state.done) {
1328                 return NT_STATUS_OK;
1329         }
1330
1331         return ctdbd_parse(messaging_ctdbd_connection(), ctx->db_id, key,
1332                            state.ask_for_readonly_copy, parser, private_data);
1333 }
1334
1335 struct traverse_state {
1336         struct db_context *db;
1337         int (*fn)(struct db_record *rec, void *private_data);
1338         void *private_data;
1339         int count;
1340 };
1341
1342 static void traverse_callback(TDB_DATA key, TDB_DATA data, void *private_data)
1343 {
1344         struct traverse_state *state = (struct traverse_state *)private_data;
1345         struct db_record *rec;
1346         TALLOC_CTX *tmp_ctx = talloc_new(state->db);
1347         /* we have to give them a locked record to prevent races */
1348         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, key);
1349         if (rec && rec->value.dsize > 0) {
1350                 state->fn(rec, state->private_data);
1351         }
1352         talloc_free(tmp_ctx);
1353 }
1354
1355 static int traverse_persistent_callback(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1356                                         void *private_data)
1357 {
1358         struct traverse_state *state = (struct traverse_state *)private_data;
1359         struct db_record *rec;
1360         TALLOC_CTX *tmp_ctx = talloc_new(state->db);
1361         int ret = 0;
1362
1363         /*
1364          * Skip the __db_sequence_number__ key:
1365          * This is used for persistent transactions internally.
1366          */
1367         if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
1368             strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
1369         {
1370                 goto done;
1371         }
1372
1373         /* we have to give them a locked record to prevent races */
1374         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, kbuf);
1375         if (rec && rec->value.dsize > 0) {
1376                 ret = state->fn(rec, state->private_data);
1377         }
1378
1379 done:
1380         talloc_free(tmp_ctx);
1381         return ret;
1382 }
1383
1384 /* wrapper to use traverse_persistent_callback with dbwrap */
1385 static int traverse_persistent_callback_dbwrap(struct db_record *rec, void* data)
1386 {
1387         return traverse_persistent_callback(NULL, rec->key, rec->value, data);
1388 }
1389
1390
1391 static int db_ctdb_traverse(struct db_context *db,
1392                             int (*fn)(struct db_record *rec,
1393                                       void *private_data),
1394                             void *private_data)
1395 {
1396         NTSTATUS status;
1397         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1398                                                         struct db_ctdb_ctx);
1399         struct traverse_state state;
1400
1401         state.db = db;
1402         state.fn = fn;
1403         state.private_data = private_data;
1404         state.count = 0;
1405
1406         if (db->persistent) {
1407                 struct tdb_context *ltdb = ctx->wtdb->tdb;
1408                 int ret;
1409
1410                 /* for persistent databases we don't need to do a ctdb traverse,
1411                    we can do a faster local traverse */
1412                 ret = tdb_traverse(ltdb, traverse_persistent_callback, &state);
1413                 if (ret < 0) {
1414                         return ret;
1415                 }
1416                 if (ctx->transaction && ctx->transaction->m_write) {
1417                         /*
1418                          * we now have to handle keys not yet
1419                          * present at transaction start
1420                          */
1421                         struct db_context *newkeys = db_open_rbt(talloc_tos());
1422                         struct ctdb_marshall_buffer *mbuf = ctx->transaction->m_write;
1423                         struct ctdb_rec_data *rec=NULL;
1424                         int i;
1425                         int count = 0;
1426
1427                         if (newkeys == NULL) {
1428                                 return -1;
1429                         }
1430
1431                         for (i=0; i<mbuf->count; i++) {
1432                                 TDB_DATA key;
1433                                 rec = db_ctdb_marshall_loop_next_key(
1434                                         mbuf, rec, &key);
1435                                 SMB_ASSERT(rec != NULL);
1436
1437                                 if (!tdb_exists(ltdb, key)) {
1438                                         dbwrap_store(newkeys, key, tdb_null, 0);
1439                                 }
1440                         }
1441                         status = dbwrap_traverse(newkeys,
1442                                                  traverse_persistent_callback_dbwrap,
1443                                                  &state,
1444                                                  &count);
1445                         talloc_free(newkeys);
1446                         if (!NT_STATUS_IS_OK(status)) {
1447                                 return -1;
1448                         }
1449                         ret += count;
1450                 }
1451                 return ret;
1452         }
1453
1454         status = ctdbd_traverse(ctx->db_id, traverse_callback, &state);
1455         if (!NT_STATUS_IS_OK(status)) {
1456                 return -1;
1457         }
1458         return state.count;
1459 }
1460
1461 static NTSTATUS db_ctdb_store_deny(struct db_record *rec, TDB_DATA data, int flag)
1462 {
1463         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1464 }
1465
1466 static NTSTATUS db_ctdb_delete_deny(struct db_record *rec)
1467 {
1468         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1469 }
1470
1471 static void traverse_read_callback(TDB_DATA key, TDB_DATA data, void *private_data)
1472 {
1473         struct traverse_state *state = (struct traverse_state *)private_data;
1474         struct db_record rec;
1475
1476         ZERO_STRUCT(rec);
1477         rec.db = state->db;
1478         rec.key = key;
1479         rec.value = data;
1480         rec.store = db_ctdb_store_deny;
1481         rec.delete_rec = db_ctdb_delete_deny;
1482         rec.private_data = NULL;
1483         state->fn(&rec, state->private_data);
1484         state->count++;
1485 }
1486
1487 static int traverse_persistent_callback_read(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1488                                         void *private_data)
1489 {
1490         struct traverse_state *state = (struct traverse_state *)private_data;
1491         struct db_record rec;
1492
1493         /*
1494          * Skip the __db_sequence_number__ key:
1495          * This is used for persistent transactions internally.
1496          */
1497         if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
1498             strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
1499         {
1500                 return 0;
1501         }
1502
1503         ZERO_STRUCT(rec);
1504         rec.db = state->db;
1505         rec.key = kbuf;
1506         rec.value = dbuf;
1507         rec.store = db_ctdb_store_deny;
1508         rec.delete_rec = db_ctdb_delete_deny;
1509         rec.private_data = NULL;
1510
1511         if (rec.value.dsize <= sizeof(struct ctdb_ltdb_header)) {
1512                 /* a deleted record */
1513                 return 0;
1514         }
1515         rec.value.dsize -= sizeof(struct ctdb_ltdb_header);
1516         rec.value.dptr += sizeof(struct ctdb_ltdb_header);
1517
1518         state->count++;
1519         return state->fn(&rec, state->private_data);
1520 }
1521
1522 static int db_ctdb_traverse_read(struct db_context *db,
1523                                  int (*fn)(struct db_record *rec,
1524                                            void *private_data),
1525                                  void *private_data)
1526 {
1527         NTSTATUS status;
1528         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1529                                                         struct db_ctdb_ctx);
1530         struct traverse_state state;
1531
1532         state.db = db;
1533         state.fn = fn;
1534         state.private_data = private_data;
1535         state.count = 0;
1536
1537         if (db->persistent) {
1538                 /* for persistent databases we don't need to do a ctdb traverse,
1539                    we can do a faster local traverse */
1540                 return tdb_traverse_read(ctx->wtdb->tdb, traverse_persistent_callback_read, &state);
1541         }
1542
1543         status = ctdbd_traverse(ctx->db_id, traverse_read_callback, &state);
1544         if (!NT_STATUS_IS_OK(status)) {
1545                 return -1;
1546         }
1547         return state.count;
1548 }
1549
1550 static int db_ctdb_get_seqnum(struct db_context *db)
1551 {
1552         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1553                                                         struct db_ctdb_ctx);
1554         return tdb_get_seqnum(ctx->wtdb->tdb);
1555 }
1556
1557 static void db_ctdb_id(struct db_context *db, const uint8_t **id,
1558                        size_t *idlen)
1559 {
1560         struct db_ctdb_ctx *ctx = talloc_get_type_abort(
1561                 db->private_data, struct db_ctdb_ctx);
1562
1563         *id = (uint8_t *)&ctx->db_id;
1564         *idlen = sizeof(ctx->db_id);
1565 }
1566
1567 struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
1568                                 const char *name,
1569                                 int hash_size, int tdb_flags,
1570                                 int open_flags, mode_t mode,
1571                                 enum dbwrap_lock_order lock_order)
1572 {
1573         struct db_context *result;
1574         struct db_ctdb_ctx *db_ctdb;
1575         char *db_path;
1576         struct ctdbd_connection *conn;
1577         struct loadparm_context *lp_ctx;
1578         struct ctdb_db_priority prio;
1579         NTSTATUS status;
1580         int cstatus;
1581
1582         if (!lp_clustering()) {
1583                 DEBUG(10, ("Clustering disabled -- no ctdb\n"));
1584                 return NULL;
1585         }
1586
1587         if (!(result = talloc_zero(mem_ctx, struct db_context))) {
1588                 DEBUG(0, ("talloc failed\n"));
1589                 TALLOC_FREE(result);
1590                 return NULL;
1591         }
1592
1593         if (!(db_ctdb = talloc(result, struct db_ctdb_ctx))) {
1594                 DEBUG(0, ("talloc failed\n"));
1595                 TALLOC_FREE(result);
1596                 return NULL;
1597         }
1598
1599         result->name = talloc_strdup(result, name);
1600         if (result->name == NULL) {
1601                 DEBUG(0, ("talloc failed\n"));
1602                 TALLOC_FREE(result);
1603                 return NULL;
1604         }
1605
1606         db_ctdb->transaction = NULL;
1607         db_ctdb->db = result;
1608
1609         conn = messaging_ctdbd_connection();
1610         if (conn == NULL) {
1611                 DEBUG(1, ("Could not connect to ctdb\n"));
1612                 TALLOC_FREE(result);
1613                 return NULL;
1614         }
1615
1616         if (!NT_STATUS_IS_OK(ctdbd_db_attach(conn, name, &db_ctdb->db_id, tdb_flags))) {
1617                 DEBUG(0, ("ctdbd_db_attach failed for %s\n", name));
1618                 TALLOC_FREE(result);
1619                 return NULL;
1620         }
1621
1622         db_path = ctdbd_dbpath(conn, db_ctdb, db_ctdb->db_id);
1623
1624         result->persistent = ((tdb_flags & TDB_CLEAR_IF_FIRST) == 0);
1625         result->lock_order = lock_order;
1626
1627         /* only pass through specific flags */
1628         tdb_flags &= TDB_SEQNUM;
1629
1630         /* honor permissions if user has specified O_CREAT */
1631         if (open_flags & O_CREAT) {
1632                 chmod(db_path, mode);
1633         }
1634
1635         prio.db_id = db_ctdb->db_id;
1636         prio.priority = lock_order;
1637
1638         status = ctdbd_control_local(
1639                 conn, CTDB_CONTROL_SET_DB_PRIORITY, 0, 0,
1640                 make_tdb_data((uint8_t *)&prio, sizeof(prio)),
1641                 NULL, NULL, &cstatus);
1642
1643         if (!NT_STATUS_IS_OK(status) || (cstatus != 0)) {
1644                 DEBUG(1, ("CTDB_CONTROL_SET_DB_PRIORITY failed: %s, %d\n",
1645                           nt_errstr(status), cstatus));
1646                 TALLOC_FREE(result);
1647                 return NULL;
1648         }
1649
1650         lp_ctx = loadparm_init_s3(db_path, loadparm_s3_helpers());
1651
1652         db_ctdb->wtdb = tdb_wrap_open(db_ctdb, db_path, hash_size, tdb_flags,
1653                                       O_RDWR, 0, lp_ctx);
1654         talloc_unlink(db_path, lp_ctx);
1655         if (db_ctdb->wtdb == NULL) {
1656                 DEBUG(0, ("Could not open tdb %s: %s\n", db_path, strerror(errno)));
1657                 TALLOC_FREE(result);
1658                 return NULL;
1659         }
1660         talloc_free(db_path);
1661
1662         if (result->persistent) {
1663                 db_ctdb->lock_ctx = g_lock_ctx_init(db_ctdb,
1664                                                     ctdb_conn_msg_ctx(conn));
1665                 if (db_ctdb->lock_ctx == NULL) {
1666                         DEBUG(0, ("g_lock_ctx_init failed\n"));
1667                         TALLOC_FREE(result);
1668                         return NULL;
1669                 }
1670         }
1671
1672         db_ctdb->warn_unlock_msecs = lp_parm_int(-1, "ctdb",
1673                                                  "unlock_warn_threshold", 5);
1674         db_ctdb->warn_migrate_attempts = lp_parm_int(-1, "ctdb",
1675                                                      "migrate_attempts", 10);
1676         db_ctdb->warn_migrate_msecs = lp_parm_int(-1, "ctdb",
1677                                                   "migrate_duration", 5000);
1678         db_ctdb->warn_locktime_msecs = lp_ctdb_locktime_warn_threshold();
1679
1680         result->private_data = (void *)db_ctdb;
1681         result->fetch_locked = db_ctdb_fetch_locked;
1682         result->try_fetch_locked = db_ctdb_try_fetch_locked;
1683         result->parse_record = db_ctdb_parse_record;
1684         result->traverse = db_ctdb_traverse;
1685         result->traverse_read = db_ctdb_traverse_read;
1686         result->get_seqnum = db_ctdb_get_seqnum;
1687         result->transaction_start = db_ctdb_transaction_start;
1688         result->transaction_commit = db_ctdb_transaction_commit;
1689         result->transaction_cancel = db_ctdb_transaction_cancel;
1690         result->id = db_ctdb_id;
1691         result->stored_callback = NULL;
1692
1693         DEBUG(3,("db_open_ctdb: opened database '%s' with dbid 0x%x\n",
1694                  name, db_ctdb->db_id));
1695
1696         return result;
1697 }
1698
1699 #else /* CLUSTER_SUPPORT */
1700
1701 struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
1702                                 const char *name,
1703                                 int hash_size, int tdb_flags,
1704                                 int open_flags, mode_t mode,
1705                                 enum dbwrap_lock_order lock_order)
1706 {
1707         DEBUG(3, ("db_open_ctdb: no cluster support!\n"));
1708         errno = ENOSYS;
1709         return NULL;
1710 }
1711
1712 #endif