s3:dbwrap_ctdb: change db_ctdb_transaction_store() to return NTSTATUS.
[abartlet/samba.git/.git] / source3 / lib / 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 #ifdef CLUSTER_SUPPORT
23 #include "ctdb.h"
24 #include "ctdb_private.h"
25 #include "ctdbd_conn.h"
26 #include "g_lock.h"
27
28 struct db_ctdb_transaction_handle {
29         struct db_ctdb_ctx *ctx;
30         /*
31          * we store the reads and writes done under a transaction:
32          * - one list stores both reads and writes (m_all),
33          * - the other just writes (m_write)
34          */
35         struct ctdb_marshall_buffer *m_all;
36         struct ctdb_marshall_buffer *m_write;
37         uint32_t nesting;
38         bool nested_cancel;
39         char *lock_name;
40 };
41
42 struct db_ctdb_ctx {
43         struct db_context *db;
44         struct tdb_wrap *wtdb;
45         uint32 db_id;
46         struct db_ctdb_transaction_handle *transaction;
47         struct g_lock_ctx *lock_ctx;
48 };
49
50 struct db_ctdb_rec {
51         struct db_ctdb_ctx *ctdb_ctx;
52         struct ctdb_ltdb_header header;
53 };
54
55 static struct db_record *fetch_locked_internal(struct db_ctdb_ctx *ctx,
56                                                TALLOC_CTX *mem_ctx,
57                                                TDB_DATA key,
58                                                bool persistent);
59
60 static NTSTATUS tdb_error_to_ntstatus(struct tdb_context *tdb)
61 {
62         NTSTATUS status;
63         enum TDB_ERROR tret = tdb_error(tdb);
64
65         switch (tret) {
66         case TDB_ERR_EXISTS:
67                 status = NT_STATUS_OBJECT_NAME_COLLISION;
68                 break;
69         case TDB_ERR_NOEXIST:
70                 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
71                 break;
72         default:
73                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
74                 break;
75         }
76
77         return status;
78 }
79
80
81 /**
82  * fetch a record from the tdb, separating out the header
83  * information and returning the body of the record.
84  */
85 static NTSTATUS db_ctdb_ltdb_fetch(struct db_ctdb_ctx *db,
86                                    TDB_DATA key,
87                                    struct ctdb_ltdb_header *header,
88                                    TALLOC_CTX *mem_ctx,
89                                    TDB_DATA *data)
90 {
91         TDB_DATA rec;
92         NTSTATUS status;
93
94         rec = tdb_fetch(db->wtdb->tdb, key);
95         if (rec.dsize < sizeof(struct ctdb_ltdb_header)) {
96                 status = NT_STATUS_NOT_FOUND;
97                 if (data) {
98                         ZERO_STRUCTP(data);
99                 }
100                 if (header) {
101                         header->dmaster = (uint32_t)-1;
102                         header->rsn = 0;
103                 }
104                 goto done;
105         }
106
107         if (header) {
108                 *header = *(struct ctdb_ltdb_header *)rec.dptr;
109         }
110
111         if (data) {
112                 data->dsize = rec.dsize - sizeof(struct ctdb_ltdb_header);
113                 if (data->dsize == 0) {
114                         data->dptr = NULL;
115                 } else {
116                         data->dptr = (unsigned char *)talloc_memdup(mem_ctx,
117                                         rec.dptr
118                                          + sizeof(struct ctdb_ltdb_header),
119                                         data->dsize);
120                         if (data->dptr == NULL) {
121                                 status = NT_STATUS_NO_MEMORY;
122                                 goto done;
123                         }
124                 }
125         }
126
127         status = NT_STATUS_OK;
128
129 done:
130         SAFE_FREE(rec.dptr);
131         return status;
132 }
133
134 /*
135  * Store a record together with the ctdb record header
136  * in the local copy of the database.
137  */
138 static NTSTATUS db_ctdb_ltdb_store(struct db_ctdb_ctx *db,
139                                    TDB_DATA key,
140                                    struct ctdb_ltdb_header *header,
141                                    TDB_DATA data)
142 {
143         TALLOC_CTX *tmp_ctx = talloc_stackframe();
144         TDB_DATA rec;
145         int ret;
146
147         rec.dsize = data.dsize + sizeof(struct ctdb_ltdb_header);
148         rec.dptr = (uint8_t *)talloc_size(tmp_ctx, rec.dsize);
149
150         if (rec.dptr == NULL) {
151                 talloc_free(tmp_ctx);
152                 return NT_STATUS_NO_MEMORY;
153         }
154
155         memcpy(rec.dptr, header, sizeof(struct ctdb_ltdb_header));
156         memcpy(sizeof(struct ctdb_ltdb_header) + (uint8_t *)rec.dptr, data.dptr, data.dsize);
157
158         ret = tdb_store(db->wtdb->tdb, key, rec, TDB_REPLACE);
159
160         talloc_free(tmp_ctx);
161
162         return (ret == 0) ? NT_STATUS_OK
163                           : tdb_error_to_ntstatus(db->wtdb->tdb);
164
165 }
166
167 /*
168   form a ctdb_rec_data record from a key/data pair
169
170   note that header may be NULL. If not NULL then it is included in the data portion
171   of the record
172  */
173 static struct ctdb_rec_data *db_ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid,       
174                                                   TDB_DATA key, 
175                                                   struct ctdb_ltdb_header *header,
176                                                   TDB_DATA data)
177 {
178         size_t length;
179         struct ctdb_rec_data *d;
180
181         length = offsetof(struct ctdb_rec_data, data) + key.dsize + 
182                 data.dsize + (header?sizeof(*header):0);
183         d = (struct ctdb_rec_data *)talloc_size(mem_ctx, length);
184         if (d == NULL) {
185                 return NULL;
186         }
187         d->length = length;
188         d->reqid = reqid;
189         d->keylen = key.dsize;
190         memcpy(&d->data[0], key.dptr, key.dsize);
191         if (header) {
192                 d->datalen = data.dsize + sizeof(*header);
193                 memcpy(&d->data[key.dsize], header, sizeof(*header));
194                 memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
195         } else {
196                 d->datalen = data.dsize;
197                 memcpy(&d->data[key.dsize], data.dptr, data.dsize);
198         }
199         return d;
200 }
201
202
203 /* helper function for marshalling multiple records */
204 static struct ctdb_marshall_buffer *db_ctdb_marshall_add(TALLOC_CTX *mem_ctx, 
205                                                struct ctdb_marshall_buffer *m,
206                                                uint64_t db_id,
207                                                uint32_t reqid,
208                                                TDB_DATA key,
209                                                struct ctdb_ltdb_header *header,
210                                                TDB_DATA data)
211 {
212         struct ctdb_rec_data *r;
213         size_t m_size, r_size;
214         struct ctdb_marshall_buffer *m2 = NULL;
215
216         r = db_ctdb_marshall_record(talloc_tos(), reqid, key, header, data);
217         if (r == NULL) {
218                 talloc_free(m);
219                 return NULL;
220         }
221
222         if (m == NULL) {
223                 m = (struct ctdb_marshall_buffer *)talloc_zero_size(
224                         mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
225                 if (m == NULL) {
226                         goto done;
227                 }
228                 m->db_id = db_id;
229         }
230
231         m_size = talloc_get_size(m);
232         r_size = talloc_get_size(r);
233
234         m2 = (struct ctdb_marshall_buffer *)talloc_realloc_size(
235                 mem_ctx, m,  m_size + r_size);
236         if (m2 == NULL) {
237                 talloc_free(m);
238                 goto done;
239         }
240
241         memcpy(m_size + (uint8_t *)m2, r, r_size);
242
243         m2->count++;
244
245 done:
246         talloc_free(r);
247         return m2;
248 }
249
250 /* we've finished marshalling, return a data blob with the marshalled records */
251 static TDB_DATA db_ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
252 {
253         TDB_DATA data;
254         data.dptr = (uint8_t *)m;
255         data.dsize = talloc_get_size(m);
256         return data;
257 }
258
259 /* 
260    loop over a marshalling buffer 
261
262      - pass r==NULL to start
263      - loop the number of times indicated by m->count
264 */
265 static struct ctdb_rec_data *db_ctdb_marshall_loop_next(struct ctdb_marshall_buffer *m, struct ctdb_rec_data *r,
266                                                      uint32_t *reqid,
267                                                      struct ctdb_ltdb_header *header,
268                                                      TDB_DATA *key, TDB_DATA *data)
269 {
270         if (r == NULL) {
271                 r = (struct ctdb_rec_data *)&m->data[0];
272         } else {
273                 r = (struct ctdb_rec_data *)(r->length + (uint8_t *)r);
274         }
275
276         if (reqid != NULL) {
277                 *reqid = r->reqid;
278         }
279
280         if (key != NULL) {
281                 key->dptr   = &r->data[0];
282                 key->dsize  = r->keylen;
283         }
284         if (data != NULL) {
285                 data->dptr  = &r->data[r->keylen];
286                 data->dsize = r->datalen;
287                 if (header != NULL) {
288                         data->dptr += sizeof(*header);
289                         data->dsize -= sizeof(*header);
290                 }
291         }
292
293         if (header != NULL) {
294                 if (r->datalen < sizeof(*header)) {
295                         return NULL;
296                 }
297                 *header = *(struct ctdb_ltdb_header *)&r->data[r->keylen];
298         }
299
300         return r;
301 }
302
303 /**
304  * CTDB transaction destructor
305  */
306 static int db_ctdb_transaction_destructor(struct db_ctdb_transaction_handle *h)
307 {
308         NTSTATUS status;
309
310         status = g_lock_unlock(h->ctx->lock_ctx, h->lock_name);
311         if (!NT_STATUS_IS_OK(status)) {
312                 DEBUG(0, ("g_lock_unlock failed: %s\n", nt_errstr(status)));
313                 return -1;
314         }
315         return 0;
316 }
317
318 /**
319  * CTDB dbwrap API: transaction_start function
320  * starts a transaction on a persistent database
321  */
322 static int db_ctdb_transaction_start(struct db_context *db)
323 {
324         struct db_ctdb_transaction_handle *h;
325         NTSTATUS status;
326         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
327                                                         struct db_ctdb_ctx);
328
329         if (!db->persistent) {
330                 DEBUG(0,("transactions not supported on non-persistent database 0x%08x\n", 
331                          ctx->db_id));
332                 return -1;
333         }
334
335         if (ctx->transaction) {
336                 ctx->transaction->nesting++;
337                 return 0;
338         }
339
340         h = talloc_zero(db, struct db_ctdb_transaction_handle);
341         if (h == NULL) {
342                 DEBUG(0,(__location__ " oom for transaction handle\n"));                
343                 return -1;
344         }
345
346         h->ctx = ctx;
347
348         h->lock_name = talloc_asprintf(h, "transaction_db_0x%08x",
349                                        (unsigned int)ctx->db_id);
350         if (h->lock_name == NULL) {
351                 DEBUG(0, ("talloc_asprintf failed\n"));
352                 TALLOC_FREE(h);
353                 return -1;
354         }
355
356         /*
357          * Wait a day, i.e. forever...
358          */
359         status = g_lock_lock(ctx->lock_ctx, h->lock_name, G_LOCK_WRITE,
360                              timeval_set(86400, 0));
361         if (!NT_STATUS_IS_OK(status)) {
362                 DEBUG(0, ("g_lock_lock failed: %s\n", nt_errstr(status)));
363                 TALLOC_FREE(h);
364                 return -1;
365         }
366
367         talloc_set_destructor(h, db_ctdb_transaction_destructor);
368
369         ctx->transaction = h;
370
371         DEBUG(5,(__location__ " Started transaction on db 0x%08x\n", ctx->db_id));
372
373         return 0;
374 }
375
376 static bool pull_newest_from_marshall_buffer(struct ctdb_marshall_buffer *buf,
377                                              TDB_DATA key,
378                                              struct ctdb_ltdb_header *pheader,
379                                              TALLOC_CTX *mem_ctx,
380                                              TDB_DATA *pdata)
381 {
382         struct ctdb_rec_data *rec = NULL;
383         struct ctdb_ltdb_header h;
384         bool found;
385         TDB_DATA data;
386         int i;
387
388         if (buf == NULL) {
389                 return false;
390         }
391
392         /*
393          * Walk the list of records written during this
394          * transaction. If we want to read one we have already
395          * written, return the last written sample. Thus we do not do
396          * a "break;" for the first hit, this record might have been
397          * overwritten later.
398          */
399
400         for (i=0; i<buf->count; i++) {
401                 TDB_DATA tkey, tdata;
402                 uint32_t reqid;
403
404                 rec = db_ctdb_marshall_loop_next(buf, rec, &reqid, &h, &tkey,
405                                                  &tdata);
406                 if (rec == NULL) {
407                         return false;
408                 }
409
410                 if (tdb_data_equal(key, tkey)) {
411                         found = true;
412                         data = tdata;
413                 }
414         }
415
416         if (!found) {
417                 return false;
418         }
419
420         if (pdata != NULL) {
421                 data.dptr = (uint8_t *)talloc_memdup(mem_ctx, data.dptr,
422                                                      data.dsize);
423                 if ((data.dsize != 0) && (data.dptr == NULL)) {
424                         return false;
425                 }
426                 *pdata = data;
427         }
428
429         if (pheader != NULL) {
430                 *pheader = h;
431         }
432
433         return true;
434 }
435
436 /*
437   fetch a record inside a transaction
438  */
439 static int db_ctdb_transaction_fetch(struct db_ctdb_ctx *db, 
440                                      TALLOC_CTX *mem_ctx, 
441                                      TDB_DATA key, TDB_DATA *data)
442 {
443         struct db_ctdb_transaction_handle *h = db->transaction;
444         NTSTATUS status;
445         bool found;
446
447         found = pull_newest_from_marshall_buffer(h->m_write, key, NULL,
448                                                  mem_ctx, data);
449         if (found) {
450                 return 0;
451         }
452
453         status = db_ctdb_ltdb_fetch(h->ctx, key, NULL, mem_ctx, data);
454
455         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
456                 *data = tdb_null;
457         } else if (!NT_STATUS_IS_OK(status)) {
458                 return -1;
459         }
460
461         h->m_all = db_ctdb_marshall_add(h, h->m_all, h->ctx->db_id, 1, key,
462                                         NULL, *data);
463         if (h->m_all == NULL) {
464                 DEBUG(0,(__location__ " Failed to add to marshalling "
465                          "record\n"));
466                 data->dsize = 0;
467                 talloc_free(data->dptr);
468                 return -1;
469         }
470
471         return 0;
472 }
473
474
475 static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag);
476 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec);
477
478 static struct db_record *db_ctdb_fetch_locked_transaction(struct db_ctdb_ctx *ctx,
479                                                           TALLOC_CTX *mem_ctx,
480                                                           TDB_DATA key)
481 {
482         struct db_record *result;
483         TDB_DATA ctdb_data;
484
485         if (!(result = talloc(mem_ctx, struct db_record))) {
486                 DEBUG(0, ("talloc failed\n"));
487                 return NULL;
488         }
489
490         result->private_data = ctx->transaction;
491
492         result->key.dsize = key.dsize;
493         result->key.dptr = (uint8 *)talloc_memdup(result, key.dptr, key.dsize);
494         if (result->key.dptr == NULL) {
495                 DEBUG(0, ("talloc failed\n"));
496                 TALLOC_FREE(result);
497                 return NULL;
498         }
499
500         result->store = db_ctdb_store_transaction;
501         result->delete_rec = db_ctdb_delete_transaction;
502
503         if (pull_newest_from_marshall_buffer(ctx->transaction->m_write, key,
504                                              NULL, result, &result->value)) {
505                 return result;
506         }
507
508         ctdb_data = tdb_fetch(ctx->wtdb->tdb, key);
509         if (ctdb_data.dptr == NULL) {
510                 /* create the record */
511                 result->value = tdb_null;
512                 return result;
513         }
514
515         result->value.dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);
516         result->value.dptr = NULL;
517
518         if ((result->value.dsize != 0)
519             && !(result->value.dptr = (uint8 *)talloc_memdup(
520                          result, ctdb_data.dptr + sizeof(struct ctdb_ltdb_header),
521                          result->value.dsize))) {
522                 DEBUG(0, ("talloc failed\n"));
523                 TALLOC_FREE(result);
524         }
525
526         SAFE_FREE(ctdb_data.dptr);
527
528         return result;
529 }
530
531 static int db_ctdb_record_destructor(struct db_record **recp)
532 {
533         struct db_record *rec = talloc_get_type_abort(*recp, struct db_record);
534         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
535                 rec->private_data, struct db_ctdb_transaction_handle);
536         int ret = h->ctx->db->transaction_commit(h->ctx->db);
537         if (ret != 0) {
538                 DEBUG(0,(__location__ " transaction_commit failed\n"));
539         }
540         return 0;
541 }
542
543 /*
544   auto-create a transaction for persistent databases
545  */
546 static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx,
547                                                          TALLOC_CTX *mem_ctx,
548                                                          TDB_DATA key)
549 {
550         int res;
551         struct db_record *rec, **recp;
552
553         res = db_ctdb_transaction_start(ctx->db);
554         if (res == -1) {
555                 return NULL;
556         }
557
558         rec = db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
559         if (rec == NULL) {
560                 ctx->db->transaction_cancel(ctx->db);           
561                 return NULL;
562         }
563
564         /* destroy this transaction when we release the lock */
565         recp = talloc(rec, struct db_record *);
566         if (recp == NULL) {
567                 ctx->db->transaction_cancel(ctx->db);
568                 talloc_free(rec);
569                 return NULL;
570         }
571         *recp = rec;
572         talloc_set_destructor(recp, db_ctdb_record_destructor);
573         return rec;
574 }
575
576
577 /*
578   stores a record inside a transaction
579  */
580 static NTSTATUS db_ctdb_transaction_store(struct db_ctdb_transaction_handle *h,
581                                           TDB_DATA key, TDB_DATA data)
582 {
583         TALLOC_CTX *tmp_ctx = talloc_new(h);
584         TDB_DATA rec;
585         struct ctdb_ltdb_header header;
586
587         ZERO_STRUCT(header);
588
589         /* we need the header so we can update the RSN */
590
591         if (!pull_newest_from_marshall_buffer(h->m_write, key, &header,
592                                               NULL, NULL)) {
593
594                 rec = tdb_fetch(h->ctx->wtdb->tdb, key);
595
596                 if (rec.dptr != NULL) {
597                         memcpy(&header, rec.dptr,
598                                sizeof(struct ctdb_ltdb_header));
599                         rec.dsize -= sizeof(struct ctdb_ltdb_header);
600
601                         /*
602                          * a special case, we are writing the same
603                          * data that is there now
604                          */
605                         if (data.dsize == rec.dsize &&
606                             memcmp(data.dptr,
607                                    rec.dptr + sizeof(struct ctdb_ltdb_header),
608                                    data.dsize) == 0) {
609                                 SAFE_FREE(rec.dptr);
610                                 talloc_free(tmp_ctx);
611                                 return NT_STATUS_OK;
612                         }
613                 }
614                 SAFE_FREE(rec.dptr);
615         }
616
617         header.dmaster = get_my_vnn();
618         header.rsn++;
619
620         h->m_all = db_ctdb_marshall_add(h, h->m_all, h->ctx->db_id, 0, key,
621                                         NULL, data);
622         if (h->m_all == NULL) {
623                 DEBUG(0,(__location__ " Failed to add to marshalling "
624                          "record\n"));
625                 talloc_free(tmp_ctx);
626                 return NT_STATUS_NO_MEMORY;
627         }
628
629         h->m_write = db_ctdb_marshall_add(h, h->m_write, h->ctx->db_id, 0, key, &header, data);
630         if (h->m_write == NULL) {
631                 DEBUG(0,(__location__ " Failed to add to marshalling record\n"));
632                 talloc_free(tmp_ctx);
633                 return NT_STATUS_NO_MEMORY;
634         }
635
636         talloc_free(tmp_ctx);
637         return NT_STATUS_OK;
638 }
639
640
641 /* 
642    a record store inside a transaction
643  */
644 static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag)
645 {
646         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
647                 rec->private_data, struct db_ctdb_transaction_handle);
648         NTSTATUS status;
649
650         status = db_ctdb_transaction_store(h, rec->key, data);
651         return status;
652 }
653
654 /* 
655    a record delete inside a transaction
656  */
657 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec)
658 {
659         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
660                 rec->private_data, struct db_ctdb_transaction_handle);
661         NTSTATUS status;
662
663         status =  db_ctdb_transaction_store(h, rec->key, tdb_null);
664         return status;
665 }
666
667 /*
668   commit a transaction
669  */
670 static int db_ctdb_transaction_commit(struct db_context *db)
671 {
672         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
673                                                         struct db_ctdb_ctx);
674         NTSTATUS rets;
675         int status;
676         struct db_ctdb_transaction_handle *h = ctx->transaction;
677
678         if (h == NULL) {
679                 DEBUG(0,(__location__ " transaction commit with no open transaction on db 0x%08x\n", ctx->db_id));
680                 return -1;
681         }
682
683         if (h->nested_cancel) {
684                 db->transaction_cancel(db);
685                 DEBUG(5,(__location__ " Failed transaction commit after nested cancel\n"));
686                 return -1;
687         }
688
689         if (h->nesting != 0) {
690                 h->nesting--;
691                 return 0;
692         }
693
694         DEBUG(5,(__location__ " Commit transaction on db 0x%08x\n", ctx->db_id));
695
696 again:
697         if (h->m_write == NULL) {
698                 /* no changes were made, potentially after a retry */
699                 goto done;
700         }
701
702         /* tell ctdbd to commit to the other nodes */
703         rets = ctdbd_control_local(messaging_ctdbd_connection(),
704                                    CTDB_CONTROL_TRANS3_COMMIT,
705                                    h->ctx->db_id, 0,
706                                    db_ctdb_marshall_finish(h->m_write),
707                                    NULL, NULL, &status);
708         if (!NT_STATUS_IS_OK(rets) || status != 0) {
709                 /*
710                  * TODO:
711                  * check the database sequence number and
712                  * compare it to the seqnum after applying the
713                  * marshall buffer. If it is the same: return success.
714                  */
715                 goto again;
716         }
717
718 done:
719         h->ctx->transaction = NULL;
720         talloc_free(h);
721         return 0;
722 }
723
724
725 /*
726   cancel a transaction
727  */
728 static int db_ctdb_transaction_cancel(struct db_context *db)
729 {
730         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
731                                                         struct db_ctdb_ctx);
732         struct db_ctdb_transaction_handle *h = ctx->transaction;
733
734         if (h == NULL) {
735                 DEBUG(0,(__location__ " transaction cancel with no open transaction on db 0x%08x\n", ctx->db_id));
736                 return -1;
737         }
738
739         if (h->nesting != 0) {
740                 h->nesting--;
741                 h->nested_cancel = true;
742                 return 0;
743         }
744
745         DEBUG(5,(__location__ " Cancel transaction on db 0x%08x\n", ctx->db_id));
746
747         ctx->transaction = NULL;
748         talloc_free(h);
749         return 0;
750 }
751
752
753 static NTSTATUS db_ctdb_store(struct db_record *rec, TDB_DATA data, int flag)
754 {
755         struct db_ctdb_rec *crec = talloc_get_type_abort(
756                 rec->private_data, struct db_ctdb_rec);
757
758         return db_ctdb_ltdb_store(crec->ctdb_ctx, rec->key, &(crec->header), data);
759 }
760
761
762
763 static NTSTATUS db_ctdb_delete(struct db_record *rec)
764 {
765         TDB_DATA data;
766
767         /*
768          * We have to store the header with empty data. TODO: Fix the
769          * tdb-level cleanup
770          */
771
772         ZERO_STRUCT(data);
773
774         return db_ctdb_store(rec, data, 0);
775
776 }
777
778 static int db_ctdb_record_destr(struct db_record* data)
779 {
780         struct db_ctdb_rec *crec = talloc_get_type_abort(
781                 data->private_data, struct db_ctdb_rec);
782
783         DEBUG(10, (DEBUGLEVEL > 10
784                    ? "Unlocking db %u key %s\n"
785                    : "Unlocking db %u key %.20s\n",
786                    (int)crec->ctdb_ctx->db_id,
787                    hex_encode_talloc(data, (unsigned char *)data->key.dptr,
788                               data->key.dsize)));
789
790         if (tdb_chainunlock(crec->ctdb_ctx->wtdb->tdb, data->key) != 0) {
791                 DEBUG(0, ("tdb_chainunlock failed\n"));
792                 return -1;
793         }
794
795         return 0;
796 }
797
798 static struct db_record *fetch_locked_internal(struct db_ctdb_ctx *ctx,
799                                                TALLOC_CTX *mem_ctx,
800                                                TDB_DATA key,
801                                                bool persistent)
802 {
803         struct db_record *result;
804         struct db_ctdb_rec *crec;
805         NTSTATUS status;
806         TDB_DATA ctdb_data;
807         int migrate_attempts = 0;
808
809         if (!(result = talloc(mem_ctx, struct db_record))) {
810                 DEBUG(0, ("talloc failed\n"));
811                 return NULL;
812         }
813
814         if (!(crec = TALLOC_ZERO_P(result, struct db_ctdb_rec))) {
815                 DEBUG(0, ("talloc failed\n"));
816                 TALLOC_FREE(result);
817                 return NULL;
818         }
819
820         result->private_data = (void *)crec;
821         crec->ctdb_ctx = ctx;
822
823         result->key.dsize = key.dsize;
824         result->key.dptr = (uint8 *)talloc_memdup(result, key.dptr, key.dsize);
825         if (result->key.dptr == NULL) {
826                 DEBUG(0, ("talloc failed\n"));
827                 TALLOC_FREE(result);
828                 return NULL;
829         }
830
831         /*
832          * Do a blocking lock on the record
833          */
834 again:
835
836         if (DEBUGLEVEL >= 10) {
837                 char *keystr = hex_encode_talloc(result, key.dptr, key.dsize);
838                 DEBUG(10, (DEBUGLEVEL > 10
839                            ? "Locking db %u key %s\n"
840                            : "Locking db %u key %.20s\n",
841                            (int)crec->ctdb_ctx->db_id, keystr));
842                 TALLOC_FREE(keystr);
843         }
844
845         if (tdb_chainlock(ctx->wtdb->tdb, key) != 0) {
846                 DEBUG(3, ("tdb_chainlock failed\n"));
847                 TALLOC_FREE(result);
848                 return NULL;
849         }
850
851         result->store = db_ctdb_store;
852         result->delete_rec = db_ctdb_delete;
853         talloc_set_destructor(result, db_ctdb_record_destr);
854
855         ctdb_data = tdb_fetch(ctx->wtdb->tdb, key);
856
857         /*
858          * See if we have a valid record and we are the dmaster. If so, we can
859          * take the shortcut and just return it.
860          */
861
862         if ((ctdb_data.dptr == NULL) ||
863             (ctdb_data.dsize < sizeof(struct ctdb_ltdb_header)) ||
864             ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster != get_my_vnn()
865 #if 0
866             || (random() % 2 != 0)
867 #endif
868 ) {
869                 SAFE_FREE(ctdb_data.dptr);
870                 tdb_chainunlock(ctx->wtdb->tdb, key);
871                 talloc_set_destructor(result, NULL);
872
873                 migrate_attempts += 1;
874
875                 DEBUG(10, ("ctdb_data.dptr = %p, dmaster = %u (%u)\n",
876                            ctdb_data.dptr, ctdb_data.dptr ?
877                            ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster : -1,
878                            get_my_vnn()));
879
880                 status = ctdbd_migrate(messaging_ctdbd_connection(),ctx->db_id, key);
881                 if (!NT_STATUS_IS_OK(status)) {
882                         DEBUG(5, ("ctdb_migrate failed: %s\n",
883                                   nt_errstr(status)));
884                         TALLOC_FREE(result);
885                         return NULL;
886                 }
887                 /* now its migrated, try again */
888                 goto again;
889         }
890
891         if (migrate_attempts > 10) {
892                 DEBUG(0, ("db_ctdb_fetch_locked needed %d attempts\n",
893                           migrate_attempts));
894         }
895
896         memcpy(&crec->header, ctdb_data.dptr, sizeof(crec->header));
897
898         result->value.dsize = ctdb_data.dsize - sizeof(crec->header);
899         result->value.dptr = NULL;
900
901         if ((result->value.dsize != 0)
902             && !(result->value.dptr = (uint8 *)talloc_memdup(
903                          result, ctdb_data.dptr + sizeof(crec->header),
904                          result->value.dsize))) {
905                 DEBUG(0, ("talloc failed\n"));
906                 TALLOC_FREE(result);
907         }
908
909         SAFE_FREE(ctdb_data.dptr);
910
911         return result;
912 }
913
914 static struct db_record *db_ctdb_fetch_locked(struct db_context *db,
915                                               TALLOC_CTX *mem_ctx,
916                                               TDB_DATA key)
917 {
918         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
919                                                         struct db_ctdb_ctx);
920
921         if (ctx->transaction != NULL) {
922                 return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
923         }
924
925         if (db->persistent) {
926                 return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
927         }
928
929         return fetch_locked_internal(ctx, mem_ctx, key, db->persistent);
930 }
931
932 /*
933   fetch (unlocked, no migration) operation on ctdb
934  */
935 static int db_ctdb_fetch(struct db_context *db, TALLOC_CTX *mem_ctx,
936                          TDB_DATA key, TDB_DATA *data)
937 {
938         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
939                                                         struct db_ctdb_ctx);
940         NTSTATUS status;
941         TDB_DATA ctdb_data;
942
943         if (ctx->transaction) {
944                 return db_ctdb_transaction_fetch(ctx, mem_ctx, key, data);
945         }
946
947         /* try a direct fetch */
948         ctdb_data = tdb_fetch(ctx->wtdb->tdb, key);
949
950         /*
951          * See if we have a valid record and we are the dmaster. If so, we can
952          * take the shortcut and just return it.
953          * we bypass the dmaster check for persistent databases
954          */
955         if ((ctdb_data.dptr != NULL) &&
956             (ctdb_data.dsize >= sizeof(struct ctdb_ltdb_header)) &&
957             (db->persistent ||
958              ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster == get_my_vnn())) {
959                 /* we are the dmaster - avoid the ctdb protocol op */
960
961                 data->dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);
962                 if (data->dsize == 0) {
963                         SAFE_FREE(ctdb_data.dptr);
964                         data->dptr = NULL;
965                         return 0;
966                 }
967
968                 data->dptr = (uint8 *)talloc_memdup(
969                         mem_ctx, ctdb_data.dptr+sizeof(struct ctdb_ltdb_header),
970                         data->dsize);
971
972                 SAFE_FREE(ctdb_data.dptr);
973
974                 if (data->dptr == NULL) {
975                         return -1;
976                 }
977                 return 0;
978         }
979
980         SAFE_FREE(ctdb_data.dptr);
981
982         /* we weren't able to get it locally - ask ctdb to fetch it for us */
983         status = ctdbd_fetch(messaging_ctdbd_connection(),ctx->db_id, key, mem_ctx, data);
984         if (!NT_STATUS_IS_OK(status)) {
985                 DEBUG(5, ("ctdbd_fetch failed: %s\n", nt_errstr(status)));
986                 return -1;
987         }
988
989         return 0;
990 }
991
992 struct traverse_state {
993         struct db_context *db;
994         int (*fn)(struct db_record *rec, void *private_data);
995         void *private_data;
996 };
997
998 static void traverse_callback(TDB_DATA key, TDB_DATA data, void *private_data)
999 {
1000         struct traverse_state *state = (struct traverse_state *)private_data;
1001         struct db_record *rec;
1002         TALLOC_CTX *tmp_ctx = talloc_new(state->db);
1003         /* we have to give them a locked record to prevent races */
1004         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, key);
1005         if (rec && rec->value.dsize > 0) {
1006                 state->fn(rec, state->private_data);
1007         }
1008         talloc_free(tmp_ctx);
1009 }
1010
1011 static int traverse_persistent_callback(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1012                                         void *private_data)
1013 {
1014         struct traverse_state *state = (struct traverse_state *)private_data;
1015         struct db_record *rec;
1016         TALLOC_CTX *tmp_ctx = talloc_new(state->db);
1017         int ret = 0;
1018         /* we have to give them a locked record to prevent races */
1019         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, kbuf);
1020         if (rec && rec->value.dsize > 0) {
1021                 ret = state->fn(rec, state->private_data);
1022         }
1023         talloc_free(tmp_ctx);
1024         return ret;
1025 }
1026
1027 static int db_ctdb_traverse(struct db_context *db,
1028                             int (*fn)(struct db_record *rec,
1029                                       void *private_data),
1030                             void *private_data)
1031 {
1032         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1033                                                         struct db_ctdb_ctx);
1034         struct traverse_state state;
1035
1036         state.db = db;
1037         state.fn = fn;
1038         state.private_data = private_data;
1039
1040         if (db->persistent) {
1041                 /* for persistent databases we don't need to do a ctdb traverse,
1042                    we can do a faster local traverse */
1043                 return tdb_traverse(ctx->wtdb->tdb, traverse_persistent_callback, &state);
1044         }
1045
1046
1047         ctdbd_traverse(ctx->db_id, traverse_callback, &state);
1048         return 0;
1049 }
1050
1051 static NTSTATUS db_ctdb_store_deny(struct db_record *rec, TDB_DATA data, int flag)
1052 {
1053         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1054 }
1055
1056 static NTSTATUS db_ctdb_delete_deny(struct db_record *rec)
1057 {
1058         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1059 }
1060
1061 static void traverse_read_callback(TDB_DATA key, TDB_DATA data, void *private_data)
1062 {
1063         struct traverse_state *state = (struct traverse_state *)private_data;
1064         struct db_record rec;
1065         rec.key = key;
1066         rec.value = data;
1067         rec.store = db_ctdb_store_deny;
1068         rec.delete_rec = db_ctdb_delete_deny;
1069         rec.private_data = state->db;
1070         state->fn(&rec, state->private_data);
1071 }
1072
1073 static int traverse_persistent_callback_read(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1074                                         void *private_data)
1075 {
1076         struct traverse_state *state = (struct traverse_state *)private_data;
1077         struct db_record rec;
1078         rec.key = kbuf;
1079         rec.value = dbuf;
1080         rec.store = db_ctdb_store_deny;
1081         rec.delete_rec = db_ctdb_delete_deny;
1082         rec.private_data = state->db;
1083
1084         if (rec.value.dsize <= sizeof(struct ctdb_ltdb_header)) {
1085                 /* a deleted record */
1086                 return 0;
1087         }
1088         rec.value.dsize -= sizeof(struct ctdb_ltdb_header);
1089         rec.value.dptr += sizeof(struct ctdb_ltdb_header);
1090
1091         return state->fn(&rec, state->private_data);
1092 }
1093
1094 static int db_ctdb_traverse_read(struct db_context *db,
1095                                  int (*fn)(struct db_record *rec,
1096                                            void *private_data),
1097                                  void *private_data)
1098 {
1099         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1100                                                         struct db_ctdb_ctx);
1101         struct traverse_state state;
1102
1103         state.db = db;
1104         state.fn = fn;
1105         state.private_data = private_data;
1106
1107         if (db->persistent) {
1108                 /* for persistent databases we don't need to do a ctdb traverse,
1109                    we can do a faster local traverse */
1110                 return tdb_traverse_read(ctx->wtdb->tdb, traverse_persistent_callback_read, &state);
1111         }
1112
1113         ctdbd_traverse(ctx->db_id, traverse_read_callback, &state);
1114         return 0;
1115 }
1116
1117 static int db_ctdb_get_seqnum(struct db_context *db)
1118 {
1119         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1120                                                         struct db_ctdb_ctx);
1121         return tdb_get_seqnum(ctx->wtdb->tdb);
1122 }
1123
1124 static int db_ctdb_get_flags(struct db_context *db)
1125 {
1126         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1127                                                         struct db_ctdb_ctx);
1128         return tdb_get_flags(ctx->wtdb->tdb);
1129 }
1130
1131 struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
1132                                 const char *name,
1133                                 int hash_size, int tdb_flags,
1134                                 int open_flags, mode_t mode)
1135 {
1136         struct db_context *result;
1137         struct db_ctdb_ctx *db_ctdb;
1138         char *db_path;
1139         struct ctdbd_connection *conn;
1140
1141         if (!lp_clustering()) {
1142                 DEBUG(10, ("Clustering disabled -- no ctdb\n"));
1143                 return NULL;
1144         }
1145
1146         if (!(result = TALLOC_ZERO_P(mem_ctx, struct db_context))) {
1147                 DEBUG(0, ("talloc failed\n"));
1148                 TALLOC_FREE(result);
1149                 return NULL;
1150         }
1151
1152         if (!(db_ctdb = TALLOC_P(result, struct db_ctdb_ctx))) {
1153                 DEBUG(0, ("talloc failed\n"));
1154                 TALLOC_FREE(result);
1155                 return NULL;
1156         }
1157
1158         db_ctdb->transaction = NULL;
1159         db_ctdb->db = result;
1160
1161         conn = messaging_ctdbd_connection();
1162
1163         if (!NT_STATUS_IS_OK(ctdbd_db_attach(conn, name, &db_ctdb->db_id, tdb_flags))) {
1164                 DEBUG(0, ("ctdbd_db_attach failed for %s\n", name));
1165                 TALLOC_FREE(result);
1166                 return NULL;
1167         }
1168
1169         db_path = ctdbd_dbpath(conn, db_ctdb, db_ctdb->db_id);
1170
1171         result->persistent = ((tdb_flags & TDB_CLEAR_IF_FIRST) == 0);
1172
1173         /* only pass through specific flags */
1174         tdb_flags &= TDB_SEQNUM;
1175
1176         /* honor permissions if user has specified O_CREAT */
1177         if (open_flags & O_CREAT) {
1178                 chmod(db_path, mode);
1179         }
1180
1181         db_ctdb->wtdb = tdb_wrap_open(db_ctdb, db_path, hash_size, tdb_flags, O_RDWR, 0);
1182         if (db_ctdb->wtdb == NULL) {
1183                 DEBUG(0, ("Could not open tdb %s: %s\n", db_path, strerror(errno)));
1184                 TALLOC_FREE(result);
1185                 return NULL;
1186         }
1187         talloc_free(db_path);
1188
1189         if (result->persistent) {
1190                 db_ctdb->lock_ctx = g_lock_ctx_init(db_ctdb,
1191                                                     ctdb_conn_msg_ctx(conn));
1192                 if (db_ctdb->lock_ctx == NULL) {
1193                         DEBUG(0, ("g_lock_ctx_init failed\n"));
1194                         TALLOC_FREE(result);
1195                         return NULL;
1196                 }
1197         }
1198
1199         result->private_data = (void *)db_ctdb;
1200         result->fetch_locked = db_ctdb_fetch_locked;
1201         result->fetch = db_ctdb_fetch;
1202         result->traverse = db_ctdb_traverse;
1203         result->traverse_read = db_ctdb_traverse_read;
1204         result->get_seqnum = db_ctdb_get_seqnum;
1205         result->get_flags = db_ctdb_get_flags;
1206         result->transaction_start = db_ctdb_transaction_start;
1207         result->transaction_commit = db_ctdb_transaction_commit;
1208         result->transaction_cancel = db_ctdb_transaction_cancel;
1209
1210         DEBUG(3,("db_open_ctdb: opened database '%s' with dbid 0x%x\n",
1211                  name, db_ctdb->db_id));
1212
1213         return result;
1214 }
1215 #endif