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