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