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