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