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