dbwrap_ctdb: Remove "tryonly" from fetch_locked_internal()
[samba.git] / source3 / lib / dbwrap / 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 #include "lib/tdb_wrap/tdb_wrap.h"
24 #include "util_tdb.h"
25 #include "dbwrap/dbwrap.h"
26 #include "dbwrap/dbwrap_ctdb.h"
27 #include "dbwrap/dbwrap_rbt.h"
28 #include "lib/param/param.h"
29
30 #include "ctdb/include/ctdb_protocol.h"
31 #include "ctdbd_conn.h"
32 #include "dbwrap/dbwrap.h"
33 #include "dbwrap/dbwrap_private.h"
34 #include "dbwrap/dbwrap_ctdb.h"
35 #include "g_lock.h"
36 #include "messages.h"
37 #include "messages_ctdb.h"
38 #include "lib/cluster_support.h"
39 #include "lib/util/tevent_ntstatus.h"
40
41 struct db_ctdb_transaction_handle {
42         struct db_ctdb_ctx *ctx;
43         /*
44          * we store the writes done under a transaction:
45          */
46         struct ctdb_marshall_buffer *m_write;
47         uint32_t nesting;
48         bool nested_cancel;
49         char *lock_name;
50 };
51
52 struct db_ctdb_ctx {
53         struct db_context *db;
54         struct tdb_wrap *wtdb;
55         uint32_t db_id;
56         struct db_ctdb_transaction_handle *transaction;
57         struct g_lock_ctx *lock_ctx;
58
59         /* thresholds for warning messages */
60         int warn_unlock_msecs;
61         int warn_migrate_msecs;
62         int warn_migrate_attempts;
63         int warn_locktime_msecs;
64 };
65
66 struct db_ctdb_rec {
67         struct db_ctdb_ctx *ctdb_ctx;
68         struct ctdb_ltdb_header header;
69         struct timeval lock_time;
70 };
71
72 struct ctdb_async_ctx {
73         bool initialized;
74         struct ctdbd_connection *async_conn;
75 };
76
77 static struct ctdb_async_ctx ctdb_async_ctx;
78
79 static int ctdb_async_ctx_init_internal(TALLOC_CTX *mem_ctx,
80                                         struct tevent_context *ev,
81                                         bool reinit)
82 {
83         int ret;
84
85         if (reinit) {
86                 TALLOC_FREE(ctdb_async_ctx.async_conn);
87                 ctdb_async_ctx.initialized = false;
88         }
89
90         if (ctdb_async_ctx.initialized) {
91                 return 0;
92         }
93
94         become_root();
95         ret = ctdbd_init_async_connection(
96                 mem_ctx,
97                 lp_ctdbd_socket(),
98                 lp_ctdb_timeout(),
99                 &ctdb_async_ctx.async_conn);
100         unbecome_root();
101
102         if (ret != 0 || ctdb_async_ctx.async_conn == NULL) {
103                 DBG_ERR("ctdbd_init_connection failed\n");
104                 return EIO;
105         }
106
107         ctdb_async_ctx.initialized = true;
108         return 0;
109 }
110
111 static int ctdb_async_ctx_init(TALLOC_CTX *mem_ctx, struct tevent_context *ev)
112 {
113         return ctdb_async_ctx_init_internal(mem_ctx, ev, false);
114 }
115
116 int ctdb_async_ctx_reinit(TALLOC_CTX *mem_ctx, struct tevent_context *ev)
117 {
118         return ctdb_async_ctx_init_internal(mem_ctx, ev, true);
119 }
120
121 static NTSTATUS tdb_error_to_ntstatus(struct tdb_context *tdb)
122 {
123         enum TDB_ERROR tret = tdb_error(tdb);
124
125         return map_nt_error_from_tdb(tret);
126 }
127
128 struct db_ctdb_ltdb_parse_state {
129         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
130                        TDB_DATA data, void *private_data);
131         void *private_data;
132 };
133
134 static int db_ctdb_ltdb_parser(TDB_DATA key, TDB_DATA data,
135                                void *private_data)
136 {
137         struct db_ctdb_ltdb_parse_state *state =
138                 (struct db_ctdb_ltdb_parse_state *)private_data;
139
140         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
141                 return -1;
142         }
143
144         state->parser(
145                 key, (struct ctdb_ltdb_header *)data.dptr,
146                 make_tdb_data(data.dptr + sizeof(struct ctdb_ltdb_header),
147                               data.dsize - sizeof(struct ctdb_ltdb_header)),
148                 state->private_data);
149         return 0;
150 }
151
152 static NTSTATUS db_ctdb_ltdb_parse(
153         struct db_ctdb_ctx *db, TDB_DATA key,
154         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
155                        TDB_DATA data, void *private_data),
156         void *private_data)
157 {
158         struct db_ctdb_ltdb_parse_state state;
159         int ret;
160
161         state.parser = parser;
162         state.private_data = private_data;
163
164         ret = tdb_parse_record(db->wtdb->tdb, key, db_ctdb_ltdb_parser,
165                                &state);
166         if (ret == -1) {
167                 return NT_STATUS_NOT_FOUND;
168         }
169         return NT_STATUS_OK;
170 }
171
172 /*
173  * Store a record together with the ctdb record header
174  * in the local copy of the database.
175  */
176 static NTSTATUS db_ctdb_ltdb_store(struct db_ctdb_ctx *db,
177                                    TDB_DATA key,
178                                    struct ctdb_ltdb_header *header,
179                                    const TDB_DATA *dbufs, int num_dbufs)
180 {
181         TDB_DATA recs[num_dbufs+1];
182         int ret;
183
184         recs[0] = (TDB_DATA) { .dptr = (uint8_t *)header,
185                                .dsize = sizeof(struct ctdb_ltdb_header) };
186         memcpy(&recs[1], dbufs, sizeof(TDB_DATA) * num_dbufs);
187
188         ret = tdb_storev(db->wtdb->tdb, key, recs, num_dbufs + 1, TDB_REPLACE);
189
190         return (ret == 0) ? NT_STATUS_OK
191                           : tdb_error_to_ntstatus(db->wtdb->tdb);
192
193 }
194
195 /*
196   form a ctdb_rec_data record from a key/data pair
197  */
198 static struct ctdb_rec_data_old *db_ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid,
199                                                   TDB_DATA key,
200                                                   struct ctdb_ltdb_header *header,
201                                                   TDB_DATA data)
202 {
203         size_t length;
204         struct ctdb_rec_data_old *d;
205
206         length = offsetof(struct ctdb_rec_data_old, data) + key.dsize +
207                 data.dsize + sizeof(*header);
208         d = (struct ctdb_rec_data_old *)talloc_size(mem_ctx, length);
209         if (d == NULL) {
210                 return NULL;
211         }
212         d->length = length;
213         d->reqid = reqid;
214         d->keylen = key.dsize;
215         memcpy(&d->data[0], key.dptr, key.dsize);
216
217         d->datalen = data.dsize + sizeof(*header);
218         memcpy(&d->data[key.dsize], header, sizeof(*header));
219         memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
220         return d;
221 }
222
223
224 /* helper function for marshalling multiple records */
225 static struct ctdb_marshall_buffer *db_ctdb_marshall_add(TALLOC_CTX *mem_ctx,
226                                                struct ctdb_marshall_buffer *m,
227                                                uint32_t db_id,
228                                                uint32_t reqid,
229                                                TDB_DATA key,
230                                                struct ctdb_ltdb_header *header,
231                                                TDB_DATA data)
232 {
233         struct ctdb_rec_data_old *r;
234         size_t m_size, r_size;
235         struct ctdb_marshall_buffer *m2 = NULL;
236
237         r = db_ctdb_marshall_record(talloc_tos(), reqid, key, header, data);
238         if (r == NULL) {
239                 talloc_free(m);
240                 return NULL;
241         }
242
243         if (m == NULL) {
244                 m = (struct ctdb_marshall_buffer *)talloc_zero_size(
245                         mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
246                 if (m == NULL) {
247                         goto done;
248                 }
249                 m->db_id = db_id;
250         }
251
252         m_size = talloc_get_size(m);
253         r_size = talloc_get_size(r);
254
255         m2 = (struct ctdb_marshall_buffer *)talloc_realloc_size(
256                 mem_ctx, m,  m_size + r_size);
257         if (m2 == NULL) {
258                 talloc_free(m);
259                 goto done;
260         }
261
262         memcpy(m_size + (uint8_t *)m2, r, r_size);
263
264         m2->count++;
265
266 done:
267         talloc_free(r);
268         return m2;
269 }
270
271 /* we've finished marshalling, return a data blob with the marshalled records */
272 static TDB_DATA db_ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
273 {
274         TDB_DATA data;
275         data.dptr = (uint8_t *)m;
276         data.dsize = talloc_get_size(m);
277         return data;
278 }
279
280 /*
281    loop over a marshalling buffer
282
283      - pass r==NULL to start
284      - loop the number of times indicated by m->count
285 */
286 static struct ctdb_rec_data_old *db_ctdb_marshall_loop_next_key(
287         struct ctdb_marshall_buffer *m, struct ctdb_rec_data_old *r, TDB_DATA *key)
288 {
289         if (r == NULL) {
290                 r = (struct ctdb_rec_data_old *)&m->data[0];
291         } else {
292                 r = (struct ctdb_rec_data_old *)(r->length + (uint8_t *)r);
293         }
294
295         key->dptr   = &r->data[0];
296         key->dsize  = r->keylen;
297         return r;
298 }
299
300 static bool db_ctdb_marshall_buf_parse(
301         struct ctdb_rec_data_old *r, uint32_t *reqid,
302         struct ctdb_ltdb_header **header, TDB_DATA *data)
303 {
304         if (r->datalen < sizeof(struct ctdb_ltdb_header)) {
305                 return false;
306         }
307
308         *reqid = r->reqid;
309
310         data->dptr  = &r->data[r->keylen] + sizeof(struct ctdb_ltdb_header);
311         data->dsize = r->datalen - sizeof(struct ctdb_ltdb_header);
312
313         *header = (struct ctdb_ltdb_header *)&r->data[r->keylen];
314
315         return true;
316 }
317
318 /**
319  * CTDB transaction destructor
320  */
321 static int db_ctdb_transaction_destructor(struct db_ctdb_transaction_handle *h)
322 {
323         NTSTATUS status;
324
325         status = g_lock_unlock(h->ctx->lock_ctx,
326                                string_term_tdb_data(h->lock_name));
327         if (!NT_STATUS_IS_OK(status)) {
328                 DEBUG(0, ("g_lock_unlock failed for %s: %s\n", h->lock_name,
329                           nt_errstr(status)));
330                 return -1;
331         }
332         return 0;
333 }
334
335 /**
336  * CTDB dbwrap API: transaction_start function
337  * starts a transaction on a persistent database
338  */
339 static int db_ctdb_transaction_start(struct db_context *db)
340 {
341         struct db_ctdb_transaction_handle *h;
342         NTSTATUS status;
343         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
344                                                         struct db_ctdb_ctx);
345
346         if (!db->persistent) {
347                 DEBUG(0,("transactions not supported on non-persistent database 0x%08x\n", 
348                          ctx->db_id));
349                 return -1;
350         }
351
352         if (ctx->transaction) {
353                 ctx->transaction->nesting++;
354                 DEBUG(5, (__location__ " transaction start on db 0x%08x: nesting %d -> %d\n",
355                           ctx->db_id, ctx->transaction->nesting - 1, ctx->transaction->nesting));
356                 return 0;
357         }
358
359         h = talloc_zero(db, struct db_ctdb_transaction_handle);
360         if (h == NULL) {
361                 DEBUG(0,(__location__ " oom for transaction handle\n"));
362                 return -1;
363         }
364
365         h->ctx = ctx;
366
367         h->lock_name = talloc_asprintf(h, "transaction_db_0x%08x",
368                                        (unsigned int)ctx->db_id);
369         if (h->lock_name == NULL) {
370                 DEBUG(0, ("talloc_asprintf failed\n"));
371                 TALLOC_FREE(h);
372                 return -1;
373         }
374
375         /*
376          * Wait a day, i.e. forever...
377          */
378         status = g_lock_lock(ctx->lock_ctx, string_term_tdb_data(h->lock_name),
379                              G_LOCK_WRITE, timeval_set(86400, 0));
380         if (!NT_STATUS_IS_OK(status)) {
381                 DEBUG(0, ("g_lock_lock failed: %s\n", nt_errstr(status)));
382                 TALLOC_FREE(h);
383                 return -1;
384         }
385
386         talloc_set_destructor(h, db_ctdb_transaction_destructor);
387
388         ctx->transaction = h;
389
390         DEBUG(5,(__location__ " transaction started on db 0x%08x\n", ctx->db_id));
391
392         return 0;
393 }
394
395 static bool parse_newest_in_marshall_buffer(
396         struct ctdb_marshall_buffer *buf, TDB_DATA key,
397         void (*parser)(TDB_DATA key, struct ctdb_ltdb_header *header,
398                        TDB_DATA data, void *private_data),
399         void *private_data)
400 {
401         struct ctdb_rec_data_old *rec = NULL;
402         struct ctdb_ltdb_header *h = NULL;
403         TDB_DATA data;
404         uint32_t i;
405
406         if (buf == NULL) {
407                 return false;
408         }
409
410         /*
411          * Walk the list of records written during this
412          * transaction. If we want to read one we have already
413          * written, return the last written sample. Thus we do not do
414          * a "break;" for the first hit, this record might have been
415          * overwritten later.
416          */
417
418         for (i=0; i<buf->count; i++) {
419                 TDB_DATA tkey;
420                 uint32_t reqid;
421
422                 rec = db_ctdb_marshall_loop_next_key(buf, rec, &tkey);
423                 if (rec == NULL) {
424                         return false;
425                 }
426
427                 if (!tdb_data_equal(key, tkey)) {
428                         continue;
429                 }
430
431                 if (!db_ctdb_marshall_buf_parse(rec, &reqid, &h, &data)) {
432                         return false;
433                 }
434         }
435
436         if (h == NULL) {
437                 return false;
438         }
439
440         parser(key, h, data, private_data);
441
442         return true;
443 }
444
445 struct pull_newest_from_marshall_buffer_state {
446         struct ctdb_ltdb_header *pheader;
447         TALLOC_CTX *mem_ctx;
448         TDB_DATA *pdata;
449 };
450
451 static void pull_newest_from_marshall_buffer_parser(
452         TDB_DATA key, struct ctdb_ltdb_header *header,
453         TDB_DATA data, void *private_data)
454 {
455         struct pull_newest_from_marshall_buffer_state *state =
456                 (struct pull_newest_from_marshall_buffer_state *)private_data;
457
458         if (state->pheader != NULL) {
459                 memcpy(state->pheader, header, sizeof(*state->pheader));
460         }
461         if (state->pdata != NULL) {
462                 state->pdata->dsize = data.dsize;
463                 state->pdata->dptr = (uint8_t *)talloc_memdup(
464                         state->mem_ctx, data.dptr, data.dsize);
465         }
466 }
467
468 static bool pull_newest_from_marshall_buffer(struct ctdb_marshall_buffer *buf,
469                                              TDB_DATA key,
470                                              struct ctdb_ltdb_header *pheader,
471                                              TALLOC_CTX *mem_ctx,
472                                              TDB_DATA *pdata)
473 {
474         struct pull_newest_from_marshall_buffer_state state;
475
476         state.pheader = pheader;
477         state.mem_ctx = mem_ctx;
478         state.pdata = pdata;
479
480         if (!parse_newest_in_marshall_buffer(
481                     buf, key, pull_newest_from_marshall_buffer_parser,
482                     &state)) {
483                 return false;
484         }
485         if ((pdata != NULL) && (pdata->dsize != 0) && (pdata->dptr == NULL)) {
486                 /* ENOMEM */
487                 return false;
488         }
489         return true;
490 }
491
492 static NTSTATUS db_ctdb_storev_transaction(struct db_record *rec,
493                                            const TDB_DATA *dbufs, int num_dbufs,
494                                            int flag);
495 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec);
496
497 static struct db_record *db_ctdb_fetch_locked_transaction(struct db_ctdb_ctx *ctx,
498                                                           TALLOC_CTX *mem_ctx,
499                                                           TDB_DATA key)
500 {
501         struct db_record *result;
502         TDB_DATA ctdb_data;
503
504         if (!(result = talloc(mem_ctx, struct db_record))) {
505                 DEBUG(0, ("talloc failed\n"));
506                 return NULL;
507         }
508
509         result->db = ctx->db;
510         result->private_data = ctx->transaction;
511
512         result->key.dsize = key.dsize;
513         result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
514                                                     key.dsize);
515         if (result->key.dptr == NULL) {
516                 DEBUG(0, ("talloc failed\n"));
517                 TALLOC_FREE(result);
518                 return NULL;
519         }
520
521         result->storev = db_ctdb_storev_transaction;
522         result->delete_rec = db_ctdb_delete_transaction;
523
524         if (ctx->transaction == NULL) {
525                 DEBUG(0, ("no transaction available\n"));
526                 TALLOC_FREE(result);
527                 return NULL;
528         }
529         if (pull_newest_from_marshall_buffer(ctx->transaction->m_write, key,
530                                              NULL, result, &result->value)) {
531                 result->value_valid = true;
532                 return result;
533         }
534
535         ctdb_data = tdb_fetch(ctx->wtdb->tdb, key);
536         if (ctdb_data.dptr == NULL) {
537                 /* create the record */
538                 result->value = tdb_null;
539                 result->value_valid = true;
540                 return result;
541         }
542
543         result->value.dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);
544         result->value.dptr = NULL;
545
546         if ((result->value.dsize != 0)
547             && !(result->value.dptr = (uint8_t *)talloc_memdup(
548                          result, ctdb_data.dptr + sizeof(struct ctdb_ltdb_header),
549                          result->value.dsize))) {
550                 DEBUG(0, ("talloc failed\n"));
551                 TALLOC_FREE(result);
552                 return NULL;
553         }
554         result->value_valid = true;
555
556         SAFE_FREE(ctdb_data.dptr);
557
558         return result;
559 }
560
561 static int db_ctdb_record_destructor(struct db_record **recp)
562 {
563         struct db_record *rec = talloc_get_type_abort(*recp, struct db_record);
564         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
565                 rec->private_data, struct db_ctdb_transaction_handle);
566         int ret = h->ctx->db->transaction_commit(h->ctx->db);
567         if (ret != 0) {
568                 DEBUG(0,(__location__ " transaction_commit failed\n"));
569         }
570         return 0;
571 }
572
573 /*
574   auto-create a transaction for persistent databases
575  */
576 static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx,
577                                                          TALLOC_CTX *mem_ctx,
578                                                          TDB_DATA key)
579 {
580         int res;
581         struct db_record *rec, **recp;
582
583         res = db_ctdb_transaction_start(ctx->db);
584         if (res == -1) {
585                 return NULL;
586         }
587
588         rec = db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
589         if (rec == NULL) {
590                 ctx->db->transaction_cancel(ctx->db);
591                 return NULL;
592         }
593
594         /* destroy this transaction when we release the lock */
595         recp = talloc(rec, struct db_record *);
596         if (recp == NULL) {
597                 ctx->db->transaction_cancel(ctx->db);
598                 talloc_free(rec);
599                 return NULL;
600         }
601         *recp = rec;
602         talloc_set_destructor(recp, db_ctdb_record_destructor);
603         return rec;
604 }
605
606
607 /*
608   stores a record inside a transaction
609  */
610 static NTSTATUS db_ctdb_transaction_store(struct db_ctdb_transaction_handle *h,
611                                           TDB_DATA key, TDB_DATA data)
612 {
613         TALLOC_CTX *tmp_ctx = talloc_new(h);
614         TDB_DATA rec;
615         struct ctdb_ltdb_header header;
616
617         ZERO_STRUCT(header);
618
619         /* we need the header so we can update the RSN */
620
621         if (!pull_newest_from_marshall_buffer(h->m_write, key, &header,
622                                               NULL, NULL)) {
623
624                 rec = tdb_fetch(h->ctx->wtdb->tdb, key);
625
626                 if (rec.dptr != NULL) {
627                         memcpy(&header, rec.dptr,
628                                sizeof(struct ctdb_ltdb_header));
629                         rec.dsize -= sizeof(struct ctdb_ltdb_header);
630
631                         /*
632                          * a special case, we are writing the same
633                          * data that is there now
634                          */
635                         if (data.dsize == rec.dsize &&
636                             memcmp(data.dptr,
637                                    rec.dptr + sizeof(struct ctdb_ltdb_header),
638                                    data.dsize) == 0) {
639                                 SAFE_FREE(rec.dptr);
640                                 talloc_free(tmp_ctx);
641                                 return NT_STATUS_OK;
642                         }
643                 }
644                 SAFE_FREE(rec.dptr);
645         }
646
647         header.dmaster = get_my_vnn();
648         header.rsn++;
649
650         h->m_write = db_ctdb_marshall_add(h, h->m_write, h->ctx->db_id, 0, key, &header, data);
651         if (h->m_write == NULL) {
652                 DEBUG(0,(__location__ " Failed to add to marshalling record\n"));
653                 talloc_free(tmp_ctx);
654                 return NT_STATUS_NO_MEMORY;
655         }
656
657         talloc_free(tmp_ctx);
658         return NT_STATUS_OK;
659 }
660
661
662 /* 
663    a record store inside a transaction
664  */
665 static NTSTATUS db_ctdb_storev_transaction(
666         struct db_record *rec, const TDB_DATA *dbufs, int num_dbufs, int flag)
667 {
668         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
669                 rec->private_data, struct db_ctdb_transaction_handle);
670         NTSTATUS status;
671         TDB_DATA data;
672
673         data = dbwrap_merge_dbufs(rec, dbufs, num_dbufs);
674         if (data.dptr == NULL) {
675                 return NT_STATUS_NO_MEMORY;
676         }
677
678         status = db_ctdb_transaction_store(h, rec->key, data);
679
680         TALLOC_FREE(data.dptr);
681
682         return status;
683 }
684
685 /*
686    a record delete inside a transaction
687  */
688 static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec)
689 {
690         struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
691                 rec->private_data, struct db_ctdb_transaction_handle);
692         NTSTATUS status;
693
694         status =  db_ctdb_transaction_store(h, rec->key, tdb_null);
695         return status;
696 }
697
698 static void db_ctdb_fetch_db_seqnum_parser(
699         TDB_DATA key, struct ctdb_ltdb_header *header,
700         TDB_DATA data, void *private_data)
701 {
702         uint64_t *seqnum = (uint64_t *)private_data;
703
704         if (data.dsize != sizeof(uint64_t)) {
705                 *seqnum = 0;
706                 return;
707         }
708         memcpy(seqnum, data.dptr, sizeof(*seqnum));
709 }
710
711 /**
712  * Fetch the db sequence number of a persistent db directly from the db.
713  */
714 static NTSTATUS db_ctdb_fetch_db_seqnum_from_db(struct db_ctdb_ctx *db,
715                                                 uint64_t *seqnum)
716 {
717         NTSTATUS status;
718         TDB_DATA key;
719
720         if (seqnum == NULL) {
721                 return NT_STATUS_INVALID_PARAMETER;
722         }
723
724         key = string_term_tdb_data(CTDB_DB_SEQNUM_KEY);
725
726         status = db_ctdb_ltdb_parse(
727                 db, key, db_ctdb_fetch_db_seqnum_parser, seqnum);
728
729         if (NT_STATUS_IS_OK(status)) {
730                 return NT_STATUS_OK;
731         }
732         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
733                 *seqnum = 0;
734                 return NT_STATUS_OK;
735         }
736         return status;
737 }
738
739 /**
740  * Store the database sequence number inside a transaction.
741  */
742 static NTSTATUS db_ctdb_store_db_seqnum(struct db_ctdb_transaction_handle *h,
743                                         uint64_t seqnum)
744 {
745         NTSTATUS status;
746         TDB_DATA key = string_term_tdb_data(CTDB_DB_SEQNUM_KEY);
747         TDB_DATA data = { .dptr=(uint8_t *)&seqnum, .dsize=sizeof(seqnum) };
748
749         status = db_ctdb_transaction_store(h, key, data);
750
751         return status;
752 }
753
754 /*
755   commit a transaction
756  */
757 static int db_ctdb_transaction_commit(struct db_context *db)
758 {
759         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
760                                                         struct db_ctdb_ctx);
761         NTSTATUS rets;
762         int32_t status;
763         struct db_ctdb_transaction_handle *h = ctx->transaction;
764         uint64_t old_seqnum, new_seqnum;
765         int ret;
766
767         if (h == NULL) {
768                 DEBUG(0,(__location__ " transaction commit with no open transaction on db 0x%08x\n", ctx->db_id));
769                 return -1;
770         }
771
772         if (h->nested_cancel) {
773                 db->transaction_cancel(db);
774                 DEBUG(5,(__location__ " Failed transaction commit after nested cancel\n"));
775                 return -1;
776         }
777
778         if (h->nesting != 0) {
779                 h->nesting--;
780                 DEBUG(5, (__location__ " transaction commit on db 0x%08x: nesting %d -> %d\n",
781                           ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
782                 return 0;
783         }
784
785         if (h->m_write == NULL) {
786                 /*
787                  * No changes were made, so don't change the seqnum,
788                  * don't push to other node, just exit with success.
789                  */
790                 ret = 0;
791                 goto done;
792         }
793
794         DEBUG(5,(__location__ " transaction commit on db 0x%08x\n", ctx->db_id));
795
796         /*
797          * As the last db action before committing, bump the database sequence
798          * number. Note that this undoes all changes to the seqnum records
799          * performed under the transaction. This record is not meant to be
800          * modified by user interaction. It is for internal use only...
801          */
802         rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &old_seqnum);
803         if (!NT_STATUS_IS_OK(rets)) {
804                 DEBUG(1, (__location__ " failed to fetch the db sequence number "
805                           "in transaction commit on db 0x%08x\n", ctx->db_id));
806                 ret = -1;
807                 goto done;
808         }
809
810         new_seqnum = old_seqnum + 1;
811
812         rets = db_ctdb_store_db_seqnum(h, new_seqnum);
813         if (!NT_STATUS_IS_OK(rets)) {
814                 DEBUG(1, (__location__ "failed to store the db sequence number "
815                           " in transaction commit on db 0x%08x\n", ctx->db_id));
816                 ret = -1;
817                 goto done;
818         }
819
820 again:
821         /* tell ctdbd to commit to the other nodes */
822         ret = ctdbd_control_local(messaging_ctdb_connection(),
823                                   CTDB_CONTROL_TRANS3_COMMIT,
824                                   h->ctx->db_id, 0,
825                                   db_ctdb_marshall_finish(h->m_write),
826                                   NULL, NULL, &status);
827         if ((ret != 0) || status != 0) {
828                 /*
829                  * The TRANS3_COMMIT control should only possibly fail when a
830                  * recovery has been running concurrently. In any case, the db
831                  * will be the same on all nodes, either the new copy or the
832                  * old copy.  This can be detected by comparing the old and new
833                  * local sequence numbers.
834                  */
835                 rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &new_seqnum);
836                 if (!NT_STATUS_IS_OK(rets)) {
837                         DEBUG(1, (__location__ " failed to refetch db sequence "
838                                   "number after failed TRANS3_COMMIT\n"));
839                         ret = -1;
840                         goto done;
841                 }
842
843                 if (new_seqnum == old_seqnum) {
844                         /* Recovery prevented all our changes: retry. */
845                         goto again;
846                 }
847                 if (new_seqnum != (old_seqnum + 1)) {
848                         DEBUG(0, (__location__ " ERROR: new_seqnum[%lu] != "
849                                   "old_seqnum[%lu] + (0 or 1) after failed "
850                                   "TRANS3_COMMIT - this should not happen!\n",
851                                   (unsigned long)new_seqnum,
852                                   (unsigned long)old_seqnum));
853                         ret = -1;
854                         goto done;
855                 }
856                 /*
857                  * Recovery propagated our changes to all nodes, completing
858                  * our commit for us - succeed.
859                  */
860         }
861
862         ret = 0;
863
864 done:
865         h->ctx->transaction = NULL;
866         talloc_free(h);
867         return ret;
868 }
869
870
871 /*
872   cancel a transaction
873  */
874 static int db_ctdb_transaction_cancel(struct db_context *db)
875 {
876         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
877                                                         struct db_ctdb_ctx);
878         struct db_ctdb_transaction_handle *h = ctx->transaction;
879
880         if (h == NULL) {
881                 DEBUG(0,(__location__ " transaction cancel with no open transaction on db 0x%08x\n", ctx->db_id));
882                 return -1;
883         }
884
885         if (h->nesting != 0) {
886                 h->nesting--;
887                 h->nested_cancel = true;
888                 DEBUG(5, (__location__ " transaction cancel on db 0x%08x: nesting %d -> %d\n",
889                           ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
890                 return 0;
891         }
892
893         DEBUG(5,(__location__ " Cancel transaction on db 0x%08x\n", ctx->db_id));
894
895         ctx->transaction = NULL;
896         talloc_free(h);
897         return 0;
898 }
899
900
901 static NTSTATUS db_ctdb_storev(struct db_record *rec,
902                                const TDB_DATA *dbufs, int num_dbufs, int flag)
903 {
904         struct db_ctdb_rec *crec = talloc_get_type_abort(
905                 rec->private_data, struct db_ctdb_rec);
906         NTSTATUS status;
907
908         status = db_ctdb_ltdb_store(crec->ctdb_ctx, rec->key, &(crec->header),
909                                     dbufs, num_dbufs);
910         return status;
911 }
912
913
914
915 static NTSTATUS db_ctdb_send_schedule_for_deletion(struct db_record *rec)
916 {
917         NTSTATUS status = NT_STATUS_OK;
918         int ret;
919         struct ctdb_control_schedule_for_deletion *dd;
920         TDB_DATA indata;
921         int32_t cstatus;
922         struct db_ctdb_rec *crec = talloc_get_type_abort(
923                 rec->private_data, struct db_ctdb_rec);
924         struct db_ctdb_ctx *ctx = crec->ctdb_ctx;
925
926         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + rec->key.dsize;
927         indata.dptr = talloc_zero_array(crec, uint8_t, indata.dsize);
928         if (indata.dptr == NULL) {
929                 DEBUG(0, (__location__ " talloc failed!\n"));
930                 return NT_STATUS_NO_MEMORY;
931         }
932
933         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
934         dd->db_id = ctx->db_id;
935         dd->hdr = crec->header;
936         dd->keylen = rec->key.dsize;
937         memcpy(dd->key, rec->key.dptr, rec->key.dsize);
938
939         ret = ctdbd_control_local(messaging_ctdb_connection(),
940                                   CTDB_CONTROL_SCHEDULE_FOR_DELETION,
941                                   crec->ctdb_ctx->db_id,
942                                   CTDB_CTRL_FLAG_NOREPLY, /* flags */
943                                   indata,
944                                   NULL, /* mem_ctx */
945                                   NULL, /* outdata */
946                                   &cstatus);
947         talloc_free(indata.dptr);
948
949         if ((ret != 0) || cstatus != 0) {
950                 DEBUG(1, (__location__ " Error sending local control "
951                           "SCHEDULE_FOR_DELETION: %s, cstatus = %"PRIi32"\n",
952                           strerror(ret), cstatus));
953                 if (ret != 0) {
954                         status = map_nt_error_from_unix(ret);
955                 } else {
956                         status = NT_STATUS_UNSUCCESSFUL;
957                 }
958         }
959
960         return status;
961 }
962
963 static NTSTATUS db_ctdb_delete(struct db_record *rec)
964 {
965         NTSTATUS status;
966
967         /*
968          * We have to store the header with empty data. TODO: Fix the
969          * tdb-level cleanup
970          */
971
972         status = db_ctdb_storev(rec, &tdb_null, 1, 0);
973         if (!NT_STATUS_IS_OK(status)) {
974                 return status;
975         }
976
977         status = db_ctdb_send_schedule_for_deletion(rec);
978         return status;
979 }
980
981 static int db_ctdb_record_destr(struct db_record* data)
982 {
983         struct db_ctdb_rec *crec = talloc_get_type_abort(
984                 data->private_data, struct db_ctdb_rec);
985         int threshold;
986         int ret;
987         struct timeval before;
988         double timediff;
989
990         DEBUG(10, (DEBUGLEVEL > 10
991                    ? "Unlocking db %u key %s\n"
992                    : "Unlocking db %u key %.20s\n",
993                    (int)crec->ctdb_ctx->db_id,
994                    hex_encode_talloc(data, (unsigned char *)data->key.dptr,
995                               data->key.dsize)));
996
997         before = timeval_current();
998
999         ret = tdb_chainunlock(crec->ctdb_ctx->wtdb->tdb, data->key);
1000
1001         timediff = timeval_elapsed(&before);
1002         timediff *= 1000;       /* get us milliseconds */
1003
1004         if (timediff > crec->ctdb_ctx->warn_unlock_msecs) {
1005                 char *key;
1006                 key = hex_encode_talloc(talloc_tos(),
1007                                         (unsigned char *)data->key.dptr,
1008                                         data->key.dsize);
1009                 DEBUG(0, ("tdb_chainunlock on db %s, key %s took %f milliseconds\n",
1010                           tdb_name(crec->ctdb_ctx->wtdb->tdb), key,
1011                           timediff));
1012                 TALLOC_FREE(key);
1013         }
1014
1015         if (ret != 0) {
1016                 DEBUG(0, ("tdb_chainunlock failed\n"));
1017                 return -1;
1018         }
1019
1020         threshold = crec->ctdb_ctx->warn_locktime_msecs;
1021         if (threshold != 0) {
1022                 timediff = timeval_elapsed(&crec->lock_time) * 1000;
1023                 if (timediff > threshold) {
1024                         const char *key;
1025
1026                         key = hex_encode_talloc(data,
1027                                                 (unsigned char *)data->key.dptr,
1028                                                 data->key.dsize);
1029                         DEBUG(0, ("Held tdb lock on db %s, key %s "
1030                                   "%f milliseconds\n",
1031                                   tdb_name(crec->ctdb_ctx->wtdb->tdb),
1032                                   key, timediff));
1033                 }
1034         }
1035
1036         return 0;
1037 }
1038
1039 /**
1040  * Check whether we have a valid local copy of the given record,
1041  * either for reading or for writing.
1042  */
1043 static bool db_ctdb_can_use_local_hdr(const struct ctdb_ltdb_header *hdr,
1044                                       uint32_t my_vnn, bool read_only)
1045 {
1046         if (hdr->dmaster != my_vnn) {
1047                 /* If we're not dmaster, it must be r/o copy. */
1048                 return read_only && (hdr->flags & CTDB_REC_RO_HAVE_READONLY);
1049         }
1050
1051         /*
1052          * If we want write access, no one may have r/o copies.
1053          */
1054         return read_only || !(hdr->flags & CTDB_REC_RO_HAVE_DELEGATIONS);
1055 }
1056
1057 static bool db_ctdb_can_use_local_copy(TDB_DATA ctdb_data, uint32_t my_vnn,
1058                                        bool read_only)
1059 {
1060         if (ctdb_data.dptr == NULL) {
1061                 return false;
1062         }
1063
1064         if (ctdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
1065                 return false;
1066         }
1067
1068         return db_ctdb_can_use_local_hdr(
1069                 (struct ctdb_ltdb_header *)ctdb_data.dptr, my_vnn, read_only);
1070 }
1071
1072 static struct db_record *fetch_locked_internal(struct db_ctdb_ctx *ctx,
1073                                                TALLOC_CTX *mem_ctx,
1074                                                TDB_DATA key)
1075 {
1076         struct db_record *result;
1077         struct db_ctdb_rec *crec;
1078         TDB_DATA ctdb_data;
1079         int migrate_attempts;
1080         struct timeval migrate_start;
1081         struct timeval chainlock_start;
1082         struct timeval ctdb_start_time;
1083         double chainlock_time = 0;
1084         double ctdb_time = 0;
1085         int duration_msecs;
1086         int lockret;
1087         int ret;
1088
1089         if (!(result = talloc(mem_ctx, struct db_record))) {
1090                 DEBUG(0, ("talloc failed\n"));
1091                 return NULL;
1092         }
1093
1094         if (!(crec = talloc_zero(result, struct db_ctdb_rec))) {
1095                 DEBUG(0, ("talloc failed\n"));
1096                 TALLOC_FREE(result);
1097                 return NULL;
1098         }
1099
1100         result->db = ctx->db;
1101         result->private_data = (void *)crec;
1102         crec->ctdb_ctx = ctx;
1103
1104         result->key.dsize = key.dsize;
1105         result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
1106                                                     key.dsize);
1107         if (result->key.dptr == NULL) {
1108                 DEBUG(0, ("talloc failed\n"));
1109                 TALLOC_FREE(result);
1110                 return NULL;
1111         }
1112
1113         migrate_attempts = 0;
1114         GetTimeOfDay(&migrate_start);
1115
1116         /*
1117          * Do a blocking lock on the record
1118          */
1119 again:
1120
1121         if (DEBUGLEVEL >= 10) {
1122                 char *keystr = hex_encode_talloc(result, key.dptr, key.dsize);
1123                 DEBUG(10, (DEBUGLEVEL > 10
1124                            ? "Locking db %u key %s\n"
1125                            : "Locking db %u key %.20s\n",
1126                            (int)crec->ctdb_ctx->db_id, keystr));
1127                 TALLOC_FREE(keystr);
1128         }
1129
1130         GetTimeOfDay(&chainlock_start);
1131         lockret = tdb_chainlock(ctx->wtdb->tdb, key);
1132         chainlock_time += timeval_elapsed(&chainlock_start);
1133
1134         if (lockret != 0) {
1135                 DEBUG(3, ("tdb_chainlock failed\n"));
1136                 TALLOC_FREE(result);
1137                 return NULL;
1138         }
1139
1140         result->storev = db_ctdb_storev;
1141         result->delete_rec = db_ctdb_delete;
1142         talloc_set_destructor(result, db_ctdb_record_destr);
1143
1144         ctdb_data = tdb_fetch(ctx->wtdb->tdb, key);
1145
1146         /*
1147          * See if we have a valid record and we are the dmaster. If so, we can
1148          * take the shortcut and just return it.
1149          */
1150
1151         if (!db_ctdb_can_use_local_copy(ctdb_data, get_my_vnn(), false)) {
1152                 SAFE_FREE(ctdb_data.dptr);
1153                 tdb_chainunlock(ctx->wtdb->tdb, key);
1154                 talloc_set_destructor(result, NULL);
1155
1156                 migrate_attempts += 1;
1157
1158                 DEBUG(10, ("ctdb_data.dptr = %p, dmaster = %"PRIu32" "
1159                            "(%"PRIu32") %"PRIu32"\n",
1160                            ctdb_data.dptr, ctdb_data.dptr ?
1161                            ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster :
1162                            UINT32_MAX,
1163                            get_my_vnn(),
1164                            ctdb_data.dptr ?
1165                            ((struct ctdb_ltdb_header *)ctdb_data.dptr)->flags : 0));
1166
1167                 GetTimeOfDay(&ctdb_start_time);
1168                 ret = ctdbd_migrate(messaging_ctdb_connection(), ctx->db_id,
1169                                     key);
1170                 ctdb_time += timeval_elapsed(&ctdb_start_time);
1171
1172                 if (ret != 0) {
1173                         DEBUG(5, ("ctdbd_migrate failed: %s\n",
1174                                   strerror(ret)));
1175                         TALLOC_FREE(result);
1176                         return NULL;
1177                 }
1178                 /* now its migrated, try again */
1179                 goto again;
1180         }
1181
1182         {
1183                 double duration;
1184                 duration = timeval_elapsed(&migrate_start);
1185
1186                 /*
1187                  * Convert the duration to milliseconds to avoid a
1188                  * floating-point division of
1189                  * lp_parm_int("migrate_duration") by 1000.
1190                  */
1191                 duration_msecs = duration * 1000;
1192         }
1193
1194         if ((migrate_attempts > ctx->warn_migrate_attempts) ||
1195             (duration_msecs > ctx->warn_migrate_msecs)) {
1196                 int chain = 0;
1197
1198                 if (tdb_get_flags(ctx->wtdb->tdb) & TDB_INCOMPATIBLE_HASH) {
1199                         chain = tdb_jenkins_hash(&key) %
1200                                 tdb_hash_size(ctx->wtdb->tdb);
1201                 }
1202
1203                 DEBUG(0, ("db_ctdb_fetch_locked for %s key %s, chain %d "
1204                           "needed %d attempts, %d milliseconds, "
1205                           "chainlock: %f ms, CTDB %f ms\n",
1206                           tdb_name(ctx->wtdb->tdb),
1207                           hex_encode_talloc(talloc_tos(),
1208                                             (unsigned char *)key.dptr,
1209                                             key.dsize),
1210                           chain,
1211                           migrate_attempts, duration_msecs,
1212                           chainlock_time * 1000.0,
1213                           ctdb_time * 1000.0));
1214         }
1215
1216         GetTimeOfDay(&crec->lock_time);
1217
1218         memcpy(&crec->header, ctdb_data.dptr, sizeof(crec->header));
1219
1220         result->value.dsize = ctdb_data.dsize - sizeof(crec->header);
1221         result->value.dptr = NULL;
1222
1223         if (result->value.dsize != 0) {
1224                 result->value.dptr = talloc_memdup(
1225                         result, ctdb_data.dptr + sizeof(crec->header),
1226                         result->value.dsize);
1227                 if (result->value.dptr == NULL) {
1228                         DBG_ERR("talloc failed\n");
1229                         TALLOC_FREE(result);
1230                         return NULL;
1231                 }
1232         }
1233         result->value_valid = true;
1234
1235         SAFE_FREE(ctdb_data.dptr);
1236
1237         return result;
1238 }
1239
1240 static struct db_record *db_ctdb_fetch_locked(struct db_context *db,
1241                                               TALLOC_CTX *mem_ctx,
1242                                               TDB_DATA key)
1243 {
1244         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1245                                                         struct db_ctdb_ctx);
1246
1247         if (ctx->transaction != NULL) {
1248                 return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
1249         }
1250
1251         if (db->persistent) {
1252                 return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
1253         }
1254
1255         return fetch_locked_internal(ctx, mem_ctx, key);
1256 }
1257
1258 struct db_ctdb_parse_record_state {
1259         void (*parser)(TDB_DATA key, TDB_DATA data, void *private_data);
1260         void *private_data;
1261         uint32_t my_vnn;
1262         bool ask_for_readonly_copy;
1263         bool done;
1264         bool empty_record;
1265 };
1266
1267 static void db_ctdb_parse_record_parser(
1268         TDB_DATA key, struct ctdb_ltdb_header *header,
1269         TDB_DATA data, void *private_data)
1270 {
1271         struct db_ctdb_parse_record_state *state =
1272                 (struct db_ctdb_parse_record_state *)private_data;
1273         state->parser(key, data, state->private_data);
1274 }
1275
1276 static void db_ctdb_parse_record_parser_nonpersistent(
1277         TDB_DATA key, struct ctdb_ltdb_header *header,
1278         TDB_DATA data, void *private_data)
1279 {
1280         struct db_ctdb_parse_record_state *state =
1281                 (struct db_ctdb_parse_record_state *)private_data;
1282
1283         if (db_ctdb_can_use_local_hdr(header, state->my_vnn, true)) {
1284                 /*
1285                  * A record consisting only of the ctdb header can be
1286                  * a validly created empty record or a tombstone
1287                  * record of a deleted record (not vacuumed yet). Mark
1288                  * it accordingly.
1289                  */
1290                 state->empty_record = (data.dsize == 0);
1291                 if (!state->empty_record) {
1292                         state->parser(key, data, state->private_data);
1293                 }
1294                 state->done = true;
1295         } else {
1296                 /*
1297                  * We found something in the db, so it seems that this record,
1298                  * while not usable locally right now, is popular. Ask for a
1299                  * R/O copy.
1300                  */
1301                 state->ask_for_readonly_copy = true;
1302         }
1303 }
1304
1305 static NTSTATUS db_ctdb_try_parse_local_record(struct db_ctdb_ctx *ctx,
1306                                                TDB_DATA key,
1307                                                struct db_ctdb_parse_record_state *state)
1308 {
1309         NTSTATUS status;
1310
1311         if (ctx->transaction != NULL) {
1312                 struct db_ctdb_transaction_handle *h = ctx->transaction;
1313                 bool found;
1314
1315                 /*
1316                  * Transactions only happen for persistent db's.
1317                  */
1318
1319                 found = parse_newest_in_marshall_buffer(
1320                         h->m_write, key, db_ctdb_parse_record_parser, state);
1321
1322                 if (found) {
1323                         return NT_STATUS_OK;
1324                 }
1325         }
1326
1327         if (ctx->db->persistent) {
1328                 /*
1329                  * Persistent db, but not found in the transaction buffer
1330                  */
1331                 return db_ctdb_ltdb_parse(
1332                         ctx, key, db_ctdb_parse_record_parser, state);
1333         }
1334
1335         state->done = false;
1336         state->ask_for_readonly_copy = false;
1337
1338         status = db_ctdb_ltdb_parse(
1339                 ctx, key, db_ctdb_parse_record_parser_nonpersistent, state);
1340         if (NT_STATUS_IS_OK(status) && state->done) {
1341                 if (state->empty_record) {
1342                         /*
1343                          * We know authoritatively, that this is an empty
1344                          * record. Since ctdb does not distinguish between empty
1345                          * and deleted records, this can be a record stored as
1346                          * empty or a not-yet-vacuumed tombstone record of a
1347                          * deleted record. Now Samba right now can live without
1348                          * empty records, so we can safely report this record
1349                          * as non-existing.
1350                          *
1351                          * See bugs 10008 and 12005.
1352                          */
1353                         return NT_STATUS_NOT_FOUND;
1354                 }
1355                 return NT_STATUS_OK;
1356         }
1357
1358         return NT_STATUS_MORE_PROCESSING_REQUIRED;
1359 }
1360
1361 static NTSTATUS db_ctdb_parse_record(struct db_context *db, TDB_DATA key,
1362                                      void (*parser)(TDB_DATA key,
1363                                                     TDB_DATA data,
1364                                                     void *private_data),
1365                                      void *private_data)
1366 {
1367         struct db_ctdb_ctx *ctx = talloc_get_type_abort(
1368                 db->private_data, struct db_ctdb_ctx);
1369         struct db_ctdb_parse_record_state state;
1370         NTSTATUS status;
1371         int ret;
1372
1373         state.parser = parser;
1374         state.private_data = private_data;
1375         state.my_vnn = get_my_vnn();
1376         state.empty_record = false;
1377
1378         status = db_ctdb_try_parse_local_record(ctx, key, &state);
1379         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1380                 return status;
1381         }
1382
1383         ret = ctdbd_parse(messaging_ctdb_connection(), ctx->db_id, key,
1384                           state.ask_for_readonly_copy, parser, private_data);
1385         if (ret != 0) {
1386                 if (ret == ENOENT) {
1387                         /*
1388                          * This maps to
1389                          * NT_STATUS_OBJECT_NAME_NOT_FOUND. Our upper
1390                          * layers expect NT_STATUS_NOT_FOUND for "no
1391                          * record around". We need to convert dbwrap
1392                          * to 0/errno away from NTSTATUS ... :-)
1393                          */
1394                         return NT_STATUS_NOT_FOUND;
1395                 }
1396                 return map_nt_error_from_unix(ret);
1397         }
1398         return NT_STATUS_OK;
1399 }
1400
1401 static void db_ctdb_parse_record_done(struct tevent_req *subreq);
1402
1403 static struct tevent_req *db_ctdb_parse_record_send(
1404         TALLOC_CTX *mem_ctx,
1405         struct tevent_context *ev,
1406         struct db_context *db,
1407         TDB_DATA key,
1408         void (*parser)(TDB_DATA key,
1409                        TDB_DATA data,
1410                        void *private_data),
1411         void *private_data,
1412         enum dbwrap_req_state *req_state)
1413 {
1414         struct db_ctdb_ctx *ctx = talloc_get_type_abort(
1415                 db->private_data, struct db_ctdb_ctx);
1416         struct tevent_req *req = NULL;
1417         struct tevent_req *subreq = NULL;
1418         struct db_ctdb_parse_record_state *state = NULL;
1419         NTSTATUS status;
1420
1421         req = tevent_req_create(mem_ctx, &state,
1422                                 struct db_ctdb_parse_record_state);
1423         if (req == NULL) {
1424                 *req_state = DBWRAP_REQ_ERROR;
1425                 return NULL;
1426
1427         }
1428
1429         *state = (struct db_ctdb_parse_record_state) {
1430                 .parser = parser,
1431                 .private_data = private_data,
1432                 .my_vnn = get_my_vnn(),
1433                 .empty_record = false,
1434         };
1435
1436         status = db_ctdb_try_parse_local_record(ctx, key, state);
1437         if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1438                 if (tevent_req_nterror(req, status)) {
1439                         *req_state = DBWRAP_REQ_ERROR;
1440                         return tevent_req_post(req, ev);
1441                 }
1442                 *req_state = DBWRAP_REQ_DONE;
1443                 tevent_req_done(req);
1444                 return tevent_req_post(req, ev);
1445         }
1446
1447         subreq = ctdbd_parse_send(state,
1448                                   ev,
1449                                   ctdb_async_ctx.async_conn,
1450                                   ctx->db_id,
1451                                   key,
1452                                   state->ask_for_readonly_copy,
1453                                   parser,
1454                                   private_data,
1455                                   req_state);
1456         if (tevent_req_nomem(subreq, req)) {
1457                 *req_state = DBWRAP_REQ_ERROR;
1458                 return tevent_req_post(req, ev);
1459         }
1460         tevent_req_set_callback(subreq, db_ctdb_parse_record_done, req);
1461
1462         return req;
1463 }
1464
1465 static void db_ctdb_parse_record_done(struct tevent_req *subreq)
1466 {
1467         struct tevent_req *req = tevent_req_callback_data(
1468                 subreq, struct tevent_req);
1469         int ret;
1470
1471         ret = ctdbd_parse_recv(subreq);
1472         TALLOC_FREE(subreq);
1473         if (ret != 0) {
1474                 if (ret == ENOENT) {
1475                         /*
1476                          * This maps to NT_STATUS_OBJECT_NAME_NOT_FOUND. Our
1477                          * upper layers expect NT_STATUS_NOT_FOUND for "no
1478                          * record around". We need to convert dbwrap to 0/errno
1479                          * away from NTSTATUS ... :-)
1480                          */
1481                         tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
1482                         return;
1483                 }
1484                 tevent_req_nterror(req, map_nt_error_from_unix(ret));
1485                 return;
1486         }
1487
1488         tevent_req_done(req);
1489         return;
1490 }
1491
1492 static NTSTATUS db_ctdb_parse_record_recv(struct tevent_req *req)
1493 {
1494         return tevent_req_simple_recv_ntstatus(req);
1495 }
1496
1497 struct traverse_state {
1498         struct db_context *db;
1499         int (*fn)(struct db_record *rec, void *private_data);
1500         void *private_data;
1501         int count;
1502 };
1503
1504 static void traverse_callback(TDB_DATA key, TDB_DATA data, void *private_data)
1505 {
1506         struct traverse_state *state = (struct traverse_state *)private_data;
1507         struct db_record *rec = NULL;
1508         TALLOC_CTX *tmp_ctx = NULL;
1509
1510         tmp_ctx = talloc_new(state->db);
1511         if (tmp_ctx == NULL) {
1512                 DBG_ERR("talloc_new failed\n");
1513                 return;
1514         }
1515
1516         /* we have to give them a locked record to prevent races */
1517         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, key);
1518         if (rec != NULL && rec->value.dsize > 0) {
1519                 state->fn(rec, state->private_data);
1520                 state->count++;
1521         }
1522         talloc_free(tmp_ctx);
1523 }
1524
1525 static int traverse_persistent_callback(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1526                                         void *private_data)
1527 {
1528         struct traverse_state *state = (struct traverse_state *)private_data;
1529         struct db_record *rec;
1530         TALLOC_CTX *tmp_ctx = talloc_new(state->db);
1531         int ret = 0;
1532
1533         /*
1534          * Skip the __db_sequence_number__ key:
1535          * This is used for persistent transactions internally.
1536          */
1537         if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
1538             strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
1539         {
1540                 goto done;
1541         }
1542
1543         /* we have to give them a locked record to prevent races */
1544         rec = db_ctdb_fetch_locked(state->db, tmp_ctx, kbuf);
1545         if (rec && rec->value.dsize > 0) {
1546                 ret = state->fn(rec, state->private_data);
1547         }
1548
1549 done:
1550         talloc_free(tmp_ctx);
1551         return ret;
1552 }
1553
1554 /* wrapper to use traverse_persistent_callback with dbwrap */
1555 static int traverse_persistent_callback_dbwrap(struct db_record *rec, void* data)
1556 {
1557         return traverse_persistent_callback(NULL, rec->key, rec->value, data);
1558 }
1559
1560 static int db_ctdbd_traverse(uint32_t db_id,
1561                              void (*fn)(TDB_DATA key, TDB_DATA data,
1562                                         void *private_data),
1563                              void *private_data)
1564 {
1565         struct ctdbd_connection *conn;
1566         int ret;
1567
1568         become_root();
1569         ret = ctdbd_init_connection(talloc_tos(), lp_ctdbd_socket(),
1570                                     lp_ctdb_timeout(), &conn);
1571         unbecome_root();
1572         if (ret != 0) {
1573                 DBG_WARNING("ctdbd_init_connection failed: %s\n",
1574                             strerror(ret));
1575                 return ret;
1576         }
1577
1578         ret = ctdbd_traverse(conn, db_id, fn, private_data);
1579         TALLOC_FREE(conn);
1580
1581         if (ret != 0) {
1582                 DBG_WARNING("ctdbd_traverse failed: %s\n",
1583                             strerror(ret));
1584                 return ret;
1585         }
1586
1587         return 0;
1588 }
1589
1590
1591 static int db_ctdb_traverse(struct db_context *db,
1592                             int (*fn)(struct db_record *rec,
1593                                       void *private_data),
1594                             void *private_data)
1595 {
1596         int ret;
1597         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1598                                                         struct db_ctdb_ctx);
1599         struct traverse_state state;
1600
1601         state = (struct traverse_state) {
1602                 .db = db,
1603                 .fn = fn,
1604                 .private_data = private_data,
1605         };
1606
1607         if (db->persistent) {
1608                 struct tdb_context *ltdb = ctx->wtdb->tdb;
1609
1610                 /* for persistent databases we don't need to do a ctdb traverse,
1611                    we can do a faster local traverse */
1612                 ret = tdb_traverse(ltdb, traverse_persistent_callback, &state);
1613                 if (ret < 0) {
1614                         return ret;
1615                 }
1616                 if (ctx->transaction && ctx->transaction->m_write) {
1617                         /*
1618                          * we now have to handle keys not yet
1619                          * present at transaction start
1620                          */
1621                         struct db_context *newkeys = db_open_rbt(talloc_tos());
1622                         struct ctdb_marshall_buffer *mbuf = ctx->transaction->m_write;
1623                         struct ctdb_rec_data_old *rec=NULL;
1624                         uint32_t i;
1625                         int count = 0;
1626                         NTSTATUS status;
1627
1628                         if (newkeys == NULL) {
1629                                 return -1;
1630                         }
1631
1632                         for (i=0; i<mbuf->count; i++) {
1633                                 TDB_DATA key;
1634                                 rec = db_ctdb_marshall_loop_next_key(
1635                                         mbuf, rec, &key);
1636                                 SMB_ASSERT(rec != NULL);
1637
1638                                 if (!tdb_exists(ltdb, key)) {
1639                                         dbwrap_store(newkeys, key, tdb_null, 0);
1640                                 }
1641                         }
1642                         status = dbwrap_traverse(newkeys,
1643                                                  traverse_persistent_callback_dbwrap,
1644                                                  &state,
1645                                                  &count);
1646                         talloc_free(newkeys);
1647                         if (!NT_STATUS_IS_OK(status)) {
1648                                 return -1;
1649                         }
1650                         ret += count;
1651                 }
1652                 return ret;
1653         }
1654
1655         ret = db_ctdbd_traverse(ctx->db_id, traverse_callback, &state);
1656         if (ret != 0) {
1657                 return -1;
1658         }
1659         return state.count;
1660 }
1661
1662 static NTSTATUS db_ctdb_storev_deny(struct db_record *rec,
1663                                     const TDB_DATA *dbufs, int num_dbufs, int flag)
1664 {
1665         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1666 }
1667
1668 static NTSTATUS db_ctdb_delete_deny(struct db_record *rec)
1669 {
1670         return NT_STATUS_MEDIA_WRITE_PROTECTED;
1671 }
1672
1673 static void traverse_read_callback(TDB_DATA key, TDB_DATA data, void *private_data)
1674 {
1675         struct traverse_state *state = (struct traverse_state *)private_data;
1676         struct db_record rec;
1677
1678         ZERO_STRUCT(rec);
1679         rec.db = state->db;
1680         rec.key = key;
1681         rec.value = data;
1682         rec.storev = db_ctdb_storev_deny;
1683         rec.delete_rec = db_ctdb_delete_deny;
1684         rec.private_data = NULL;
1685         rec.value_valid = true;
1686         state->fn(&rec, state->private_data);
1687         state->count++;
1688 }
1689
1690 static int traverse_persistent_callback_read(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
1691                                         void *private_data)
1692 {
1693         struct traverse_state *state = (struct traverse_state *)private_data;
1694         struct db_record rec;
1695
1696         /*
1697          * Skip the __db_sequence_number__ key:
1698          * This is used for persistent transactions internally.
1699          */
1700         if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
1701             strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
1702         {
1703                 return 0;
1704         }
1705
1706         ZERO_STRUCT(rec);
1707         rec.db = state->db;
1708         rec.key = kbuf;
1709         rec.value = dbuf;
1710         rec.value_valid = true;
1711         rec.storev = db_ctdb_storev_deny;
1712         rec.delete_rec = db_ctdb_delete_deny;
1713         rec.private_data = NULL;
1714
1715         if (rec.value.dsize <= sizeof(struct ctdb_ltdb_header)) {
1716                 /* a deleted record */
1717                 return 0;
1718         }
1719         rec.value.dsize -= sizeof(struct ctdb_ltdb_header);
1720         rec.value.dptr += sizeof(struct ctdb_ltdb_header);
1721
1722         state->count++;
1723         return state->fn(&rec, state->private_data);
1724 }
1725
1726 static int db_ctdb_traverse_read(struct db_context *db,
1727                                  int (*fn)(struct db_record *rec,
1728                                            void *private_data),
1729                                  void *private_data)
1730 {
1731         int ret;
1732         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1733                                                         struct db_ctdb_ctx);
1734         struct traverse_state state;
1735
1736         state = (struct traverse_state) {
1737                 .db = db,
1738                 .fn = fn,
1739                 .private_data = private_data,
1740         };
1741
1742         if (db->persistent) {
1743                 /* for persistent databases we don't need to do a ctdb traverse,
1744                    we can do a faster local traverse */
1745                 int nrecs;
1746
1747                 nrecs = tdb_traverse_read(ctx->wtdb->tdb,
1748                                           traverse_persistent_callback_read,
1749                                           &state);
1750                 if (nrecs == -1) {
1751                         return -1;
1752                 }
1753                 return state.count;
1754         }
1755
1756         ret = db_ctdbd_traverse(ctx->db_id, traverse_read_callback, &state);
1757         if (ret != 0) {
1758                 return -1;
1759         }
1760         return state.count;
1761 }
1762
1763 static int db_ctdb_get_seqnum(struct db_context *db)
1764 {
1765         struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
1766                                                         struct db_ctdb_ctx);
1767         return tdb_get_seqnum(ctx->wtdb->tdb);
1768 }
1769
1770 static size_t db_ctdb_id(struct db_context *db, uint8_t *id, size_t idlen)
1771 {
1772         struct db_ctdb_ctx *ctx = talloc_get_type_abort(
1773                 db->private_data, struct db_ctdb_ctx);
1774
1775         if (idlen >= sizeof(ctx->db_id)) {
1776                 memcpy(id, &ctx->db_id, sizeof(ctx->db_id));
1777         }
1778
1779         return sizeof(ctx->db_id);
1780 }
1781
1782 struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
1783                                 struct messaging_context *msg_ctx,
1784                                 const char *name,
1785                                 int hash_size, int tdb_flags,
1786                                 int open_flags, mode_t mode,
1787                                 enum dbwrap_lock_order lock_order,
1788                                 uint64_t dbwrap_flags)
1789 {
1790         struct db_context *result;
1791         struct db_ctdb_ctx *db_ctdb;
1792         char *db_path;
1793         struct loadparm_context *lp_ctx;
1794         TDB_DATA data;
1795         TDB_DATA outdata = {0};
1796         bool persistent = (tdb_flags & TDB_CLEAR_IF_FIRST) == 0;
1797         int32_t cstatus;
1798         int ret;
1799
1800         if (!lp_clustering()) {
1801                 DEBUG(10, ("Clustering disabled -- no ctdb\n"));
1802                 return NULL;
1803         }
1804
1805         if (!(result = talloc_zero(mem_ctx, struct db_context))) {
1806                 DEBUG(0, ("talloc failed\n"));
1807                 TALLOC_FREE(result);
1808                 return NULL;
1809         }
1810
1811         if (!(db_ctdb = talloc(result, struct db_ctdb_ctx))) {
1812                 DEBUG(0, ("talloc failed\n"));
1813                 TALLOC_FREE(result);
1814                 return NULL;
1815         }
1816
1817         result->name = talloc_strdup(result, name);
1818         if (result->name == NULL) {
1819                 DEBUG(0, ("talloc failed\n"));
1820                 TALLOC_FREE(result);
1821                 return NULL;
1822         }
1823
1824         db_ctdb->transaction = NULL;
1825         db_ctdb->db = result;
1826
1827         ret = ctdbd_db_attach(messaging_ctdb_connection(), name,
1828                               &db_ctdb->db_id, persistent);
1829         if (ret != 0) {
1830                 DEBUG(0, ("ctdbd_db_attach failed for %s: %s\n", name,
1831                           strerror(ret)));
1832                 TALLOC_FREE(result);
1833                 return NULL;
1834         }
1835
1836         if (tdb_flags & TDB_SEQNUM) {
1837                 data.dptr = (uint8_t *)&db_ctdb->db_id;
1838                 data.dsize = sizeof(db_ctdb->db_id);
1839
1840                 ret = ctdbd_control_local(messaging_ctdb_connection(),
1841                                           CTDB_CONTROL_ENABLE_SEQNUM,
1842                                           0, 0, data,
1843                                           NULL, NULL, &cstatus);
1844                 if ((ret != 0) || cstatus != 0) {
1845                         DBG_ERR("ctdb_control for enable seqnum "
1846                                 "failed: %s\n", strerror(ret));
1847                         TALLOC_FREE(result);
1848                         return NULL;
1849                 }
1850         }
1851
1852         db_path = ctdbd_dbpath(messaging_ctdb_connection(), db_ctdb,
1853                                db_ctdb->db_id);
1854         if (db_path == NULL) {
1855                 DBG_ERR("ctdbd_dbpath failed\n");
1856                 TALLOC_FREE(result);
1857                 return NULL;
1858         }
1859
1860         result->persistent = persistent;
1861         result->lock_order = lock_order;
1862
1863         data.dptr = (uint8_t *)&db_ctdb->db_id;
1864         data.dsize = sizeof(db_ctdb->db_id);
1865
1866         ret = ctdbd_control_local(messaging_ctdb_connection(),
1867                                   CTDB_CONTROL_DB_OPEN_FLAGS,
1868                                   0, 0, data, NULL, &outdata, &cstatus);
1869         if (ret != 0) {
1870                 DBG_ERR(" ctdb control for db_open_flags "
1871                          "failed: %s\n", strerror(ret));
1872                 TALLOC_FREE(result);
1873                 return NULL;
1874         }
1875
1876         if (cstatus != 0 || outdata.dsize != sizeof(int)) {
1877                 DBG_ERR("ctdb_control for db_open_flags failed\n");
1878                 TALLOC_FREE(outdata.dptr);
1879                 TALLOC_FREE(result);
1880                 return NULL;
1881         }
1882
1883         tdb_flags = *(int *)outdata.dptr;
1884         TALLOC_FREE(outdata.dptr);
1885
1886         if (!result->persistent) {
1887                 ret = ctdb_async_ctx_init(NULL, messaging_tevent_context(msg_ctx));
1888                 if (ret != 0) {
1889                         DBG_ERR("ctdb_async_ctx_init failed: %s\n", strerror(ret));
1890                         TALLOC_FREE(result);
1891                         return NULL;
1892                 }
1893         }
1894
1895         if (!result->persistent &&
1896             (dbwrap_flags & DBWRAP_FLAG_OPTIMIZE_READONLY_ACCESS))
1897         {
1898                 TDB_DATA indata;
1899
1900                 indata = make_tdb_data((uint8_t *)&db_ctdb->db_id,
1901                                        sizeof(db_ctdb->db_id));
1902
1903                 ret = ctdbd_control_local(
1904                         messaging_ctdb_connection(),
1905                         CTDB_CONTROL_SET_DB_READONLY, 0, 0,
1906                         indata, NULL, NULL, &cstatus);
1907                 if ((ret != 0) || (cstatus != 0)) {
1908                         DEBUG(1, ("CTDB_CONTROL_SET_DB_READONLY failed: "
1909                                   "%s, %"PRIi32"\n", strerror(ret), cstatus));
1910                         TALLOC_FREE(result);
1911                         return NULL;
1912                 }
1913         }
1914
1915         lp_ctx = loadparm_init_s3(db_path, loadparm_s3_helpers());
1916
1917         if (hash_size == 0) {
1918                 hash_size = lpcfg_tdb_hash_size(lp_ctx, db_path);
1919         }
1920
1921         db_ctdb->wtdb = tdb_wrap_open(db_ctdb, db_path, hash_size,
1922                                       lpcfg_tdb_flags(lp_ctx, tdb_flags),
1923                                       O_RDWR, 0);
1924         talloc_unlink(db_path, lp_ctx);
1925         if (db_ctdb->wtdb == NULL) {
1926                 DEBUG(0, ("Could not open tdb %s: %s\n", db_path, strerror(errno)));
1927                 TALLOC_FREE(result);
1928                 return NULL;
1929         }
1930         talloc_free(db_path);
1931
1932         /* honor permissions if user has specified O_CREAT */
1933         if (open_flags & O_CREAT) {
1934                 int fd;
1935                 fd = tdb_fd(db_ctdb->wtdb->tdb);
1936                 ret = fchmod(fd, mode);
1937                 if (ret == -1) {
1938                         DBG_WARNING("fchmod failed: %s\n",
1939                                     strerror(errno));
1940                         TALLOC_FREE(result);
1941                         return NULL;
1942                 }
1943         }
1944
1945         if (result->persistent) {
1946                 db_ctdb->lock_ctx = g_lock_ctx_init(db_ctdb, msg_ctx);
1947                 if (db_ctdb->lock_ctx == NULL) {
1948                         DEBUG(0, ("g_lock_ctx_init failed\n"));
1949                         TALLOC_FREE(result);
1950                         return NULL;
1951                 }
1952         }
1953
1954         db_ctdb->warn_unlock_msecs = lp_parm_int(-1, "ctdb",
1955                                                  "unlock_warn_threshold", 5);
1956         db_ctdb->warn_migrate_attempts = lp_parm_int(-1, "ctdb",
1957                                                      "migrate_attempts", 10);
1958         db_ctdb->warn_migrate_msecs = lp_parm_int(-1, "ctdb",
1959                                                   "migrate_duration", 5000);
1960         db_ctdb->warn_locktime_msecs = lp_ctdb_locktime_warn_threshold();
1961
1962         result->private_data = (void *)db_ctdb;
1963         result->fetch_locked = db_ctdb_fetch_locked;
1964         result->parse_record = db_ctdb_parse_record;
1965         result->parse_record_send = db_ctdb_parse_record_send;
1966         result->parse_record_recv = db_ctdb_parse_record_recv;
1967         result->traverse = db_ctdb_traverse;
1968         result->traverse_read = db_ctdb_traverse_read;
1969         result->get_seqnum = db_ctdb_get_seqnum;
1970         result->transaction_start = db_ctdb_transaction_start;
1971         result->transaction_commit = db_ctdb_transaction_commit;
1972         result->transaction_cancel = db_ctdb_transaction_cancel;
1973         result->id = db_ctdb_id;
1974
1975         DEBUG(3,("db_open_ctdb: opened database '%s' with dbid 0x%x\n",
1976                  name, db_ctdb->db_id));
1977
1978         return result;
1979 }