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