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