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