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