summaryrefslogtreecommitdiff
path: root/source3/lib/dbwrap/dbwrap_ctdb.c
blob: e4c87ead4f5b46901e759057ea4fc420f089bb92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
/*
   Unix SMB/CIFS implementation.
   Database interface wrapper around ctdbd
   Copyright (C) Volker Lendecke 2007-2009
   Copyright (C) Michael Adam 2009

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "includes.h"
#include "system/filesys.h"
#include "lib/tdb_wrap/tdb_wrap.h"
#include "util_tdb.h"
#include "dbwrap/dbwrap.h"
#include "dbwrap/dbwrap_ctdb.h"
#include "dbwrap/dbwrap_rbt.h"
#include "lib/param/param.h"

#ifdef CLUSTER_SUPPORT

/*
 * It is not possible to include ctdb.h and tdb_compat.h (included via
 * some other include above) without warnings. This fixes those
 * warnings.
 */

#ifdef typesafe_cb
#undef typesafe_cb
#endif

#ifdef typesafe_cb_preargs
#undef typesafe_cb_preargs
#endif

#ifdef typesafe_cb_postargs
#undef typesafe_cb_postargs
#endif

#include "ctdb.h"
#include "ctdb_private.h"
#include "ctdbd_conn.h"
#include "dbwrap/dbwrap.h"
#include "dbwrap/dbwrap_private.h"
#include "dbwrap/dbwrap_ctdb.h"
#include "g_lock.h"
#include "messages.h"

struct db_ctdb_transaction_handle {
	struct db_ctdb_ctx *ctx;
	/*
	 * we store the writes done under a transaction:
	 */
	struct ctdb_marshall_buffer *m_write;
	uint32_t nesting;
	bool nested_cancel;
	char *lock_name;
};

struct db_ctdb_ctx {
	struct db_context *db;
	struct tdb_wrap *wtdb;
	uint32_t db_id;
	struct db_ctdb_transaction_handle *transaction;
	struct g_lock_ctx *lock_ctx;
};

struct db_ctdb_rec {
	struct db_ctdb_ctx *ctdb_ctx;
	struct ctdb_ltdb_header header;
	struct timeval lock_time;
};

static NTSTATUS tdb_error_to_ntstatus(struct tdb_context *tdb)
{
	enum TDB_ERROR tret = tdb_error(tdb);

	return map_nt_error_from_tdb(tret);
}


/**
 * fetch a record from the tdb, separating out the header
 * information and returning the body of the record.
 */
static NTSTATUS db_ctdb_ltdb_fetch(struct db_ctdb_ctx *db,
				   TDB_DATA key,
				   struct ctdb_ltdb_header *header,
				   TALLOC_CTX *mem_ctx,
				   TDB_DATA *data)
{
	TDB_DATA rec;
	NTSTATUS status;

	rec = tdb_fetch_compat(db->wtdb->tdb, key);
	if (rec.dsize < sizeof(struct ctdb_ltdb_header)) {
		status = NT_STATUS_NOT_FOUND;
		if (data) {
			ZERO_STRUCTP(data);
		}
		if (header) {
			header->dmaster = (uint32_t)-1;
			header->rsn = 0;
		}
		goto done;
	}

	if (header) {
		*header = *(struct ctdb_ltdb_header *)rec.dptr;
	}

	if (data) {
		data->dsize = rec.dsize - sizeof(struct ctdb_ltdb_header);
		if (data->dsize == 0) {
			data->dptr = NULL;
		} else {
			data->dptr = (unsigned char *)talloc_memdup(mem_ctx,
					rec.dptr
					 + sizeof(struct ctdb_ltdb_header),
					data->dsize);
			if (data->dptr == NULL) {
				status = NT_STATUS_NO_MEMORY;
				goto done;
			}
		}
	}

	status = NT_STATUS_OK;

done:
	SAFE_FREE(rec.dptr);
	return status;
}

/*
 * Store a record together with the ctdb record header
 * in the local copy of the database.
 */
static NTSTATUS db_ctdb_ltdb_store(struct db_ctdb_ctx *db,
				   TDB_DATA key,
				   struct ctdb_ltdb_header *header,
				   TDB_DATA data)
{
	TALLOC_CTX *tmp_ctx = talloc_stackframe();
	TDB_DATA rec;
	int ret;

	rec.dsize = data.dsize + sizeof(struct ctdb_ltdb_header);
	rec.dptr = (uint8_t *)talloc_size(tmp_ctx, rec.dsize);

	if (rec.dptr == NULL) {
		talloc_free(tmp_ctx);
		return NT_STATUS_NO_MEMORY;
	}

	memcpy(rec.dptr, header, sizeof(struct ctdb_ltdb_header));
	memcpy(sizeof(struct ctdb_ltdb_header) + (uint8_t *)rec.dptr, data.dptr, data.dsize);

	ret = tdb_store(db->wtdb->tdb, key, rec, TDB_REPLACE);

	talloc_free(tmp_ctx);

	return (ret == 0) ? NT_STATUS_OK
			  : tdb_error_to_ntstatus(db->wtdb->tdb);

}

/*
  form a ctdb_rec_data record from a key/data pair

  note that header may be NULL. If not NULL then it is included in the data portion
  of the record
 */
static struct ctdb_rec_data *db_ctdb_marshall_record(TALLOC_CTX *mem_ctx, uint32_t reqid,
						  TDB_DATA key,
						  struct ctdb_ltdb_header *header,
						  TDB_DATA data)
{
	size_t length;
	struct ctdb_rec_data *d;

	length = offsetof(struct ctdb_rec_data, data) + key.dsize +
		data.dsize + (header?sizeof(*header):0);
	d = (struct ctdb_rec_data *)talloc_size(mem_ctx, length);
	if (d == NULL) {
		return NULL;
	}
	d->length = length;
	d->reqid = reqid;
	d->keylen = key.dsize;
	memcpy(&d->data[0], key.dptr, key.dsize);
	if (header) {
		d->datalen = data.dsize + sizeof(*header);
		memcpy(&d->data[key.dsize], header, sizeof(*header));
		memcpy(&d->data[key.dsize+sizeof(*header)], data.dptr, data.dsize);
	} else {
		d->datalen = data.dsize;
		memcpy(&d->data[key.dsize], data.dptr, data.dsize);
	}
	return d;
}


/* helper function for marshalling multiple records */
static struct ctdb_marshall_buffer *db_ctdb_marshall_add(TALLOC_CTX *mem_ctx,
					       struct ctdb_marshall_buffer *m,
					       uint64_t db_id,
					       uint32_t reqid,
					       TDB_DATA key,
					       struct ctdb_ltdb_header *header,
					       TDB_DATA data)
{
	struct ctdb_rec_data *r;
	size_t m_size, r_size;
	struct ctdb_marshall_buffer *m2 = NULL;

	r = db_ctdb_marshall_record(talloc_tos(), reqid, key, header, data);
	if (r == NULL) {
		talloc_free(m);
		return NULL;
	}

	if (m == NULL) {
		m = (struct ctdb_marshall_buffer *)talloc_zero_size(
			mem_ctx, offsetof(struct ctdb_marshall_buffer, data));
		if (m == NULL) {
			goto done;
		}
		m->db_id = db_id;
	}

	m_size = talloc_get_size(m);
	r_size = talloc_get_size(r);

	m2 = (struct ctdb_marshall_buffer *)talloc_realloc_size(
		mem_ctx, m,  m_size + r_size);
	if (m2 == NULL) {
		talloc_free(m);
		goto done;
	}

	memcpy(m_size + (uint8_t *)m2, r, r_size);

	m2->count++;

done:
	talloc_free(r);
	return m2;
}

/* we've finished marshalling, return a data blob with the marshalled records */
static TDB_DATA db_ctdb_marshall_finish(struct ctdb_marshall_buffer *m)
{
	TDB_DATA data;
	data.dptr = (uint8_t *)m;
	data.dsize = talloc_get_size(m);
	return data;
}

/*
   loop over a marshalling buffer

     - pass r==NULL to start
     - loop the number of times indicated by m->count
*/
static struct ctdb_rec_data *db_ctdb_marshall_loop_next(struct ctdb_marshall_buffer *m, struct ctdb_rec_data *r,
						     uint32_t *reqid,
						     struct ctdb_ltdb_header *header,
						     TDB_DATA *key, TDB_DATA *data)
{
	if (r == NULL) {
		r = (struct ctdb_rec_data *)&m->data[0];
	} else {
		r = (struct ctdb_rec_data *)(r->length + (uint8_t *)r);
	}

	if (reqid != NULL) {
		*reqid = r->reqid;
	}

	if (key != NULL) {
		key->dptr   = &r->data[0];
		key->dsize  = r->keylen;
	}
	if (data != NULL) {
		data->dptr  = &r->data[r->keylen];
		data->dsize = r->datalen;
		if (header != NULL) {
			data->dptr += sizeof(*header);
			data->dsize -= sizeof(*header);
		}
	}

	if (header != NULL) {
		if (r->datalen < sizeof(*header)) {
			return NULL;
		}
		*header = *(struct ctdb_ltdb_header *)&r->data[r->keylen];
	}

	return r;
}

/**
 * CTDB transaction destructor
 */
static int db_ctdb_transaction_destructor(struct db_ctdb_transaction_handle *h)
{
	NTSTATUS status;

	status = g_lock_unlock(h->ctx->lock_ctx, h->lock_name);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("g_lock_unlock failed for %s: %s\n", h->lock_name,
			  nt_errstr(status)));
		return -1;
	}
	return 0;
}

/**
 * CTDB dbwrap API: transaction_start function
 * starts a transaction on a persistent database
 */
static int db_ctdb_transaction_start(struct db_context *db)
{
	struct db_ctdb_transaction_handle *h;
	NTSTATUS status;
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);

	if (!db->persistent) {
		DEBUG(0,("transactions not supported on non-persistent database 0x%08x\n", 
			 ctx->db_id));
		return -1;
	}

	if (ctx->transaction) {
		ctx->transaction->nesting++;
		DEBUG(5, (__location__ " transaction start on db 0x%08x: nesting %d -> %d\n",
			  ctx->db_id, ctx->transaction->nesting - 1, ctx->transaction->nesting));
		return 0;
	}

	h = talloc_zero(db, struct db_ctdb_transaction_handle);
	if (h == NULL) {
		DEBUG(0,(__location__ " oom for transaction handle\n"));
		return -1;
	}

	h->ctx = ctx;

	h->lock_name = talloc_asprintf(h, "transaction_db_0x%08x",
				       (unsigned int)ctx->db_id);
	if (h->lock_name == NULL) {
		DEBUG(0, ("talloc_asprintf failed\n"));
		TALLOC_FREE(h);
		return -1;
	}

	/*
	 * Wait a day, i.e. forever...
	 */
	status = g_lock_lock(ctx->lock_ctx, h->lock_name, G_LOCK_WRITE,
			     timeval_set(86400, 0));
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("g_lock_lock failed: %s\n", nt_errstr(status)));
		TALLOC_FREE(h);
		return -1;
	}

	talloc_set_destructor(h, db_ctdb_transaction_destructor);

	ctx->transaction = h;

	DEBUG(5,(__location__ " transaction started on db 0x%08x\n", ctx->db_id));

	return 0;
}

static bool pull_newest_from_marshall_buffer(struct ctdb_marshall_buffer *buf,
					     TDB_DATA key,
					     struct ctdb_ltdb_header *pheader,
					     TALLOC_CTX *mem_ctx,
					     TDB_DATA *pdata)
{
	struct ctdb_rec_data *rec = NULL;
	struct ctdb_ltdb_header h;
	bool found = false;
	TDB_DATA data;
	int i;

	if (buf == NULL) {
		return false;
	}

	ZERO_STRUCT(h);
	ZERO_STRUCT(data);

	/*
	 * Walk the list of records written during this
	 * transaction. If we want to read one we have already
	 * written, return the last written sample. Thus we do not do
	 * a "break;" for the first hit, this record might have been
	 * overwritten later.
	 */

	for (i=0; i<buf->count; i++) {
		TDB_DATA tkey, tdata;
		uint32_t reqid;
		struct ctdb_ltdb_header hdr;

		ZERO_STRUCT(hdr);

		rec = db_ctdb_marshall_loop_next(buf, rec, &reqid, &hdr, &tkey,
						 &tdata);
		if (rec == NULL) {
			return false;
		}

		if (tdb_data_equal(key, tkey)) {
			found = true;
			data = tdata;
			h = hdr;
		}
	}

	if (!found) {
		return false;
	}

	if (pdata != NULL) {
		data.dptr = (uint8_t *)talloc_memdup(mem_ctx, data.dptr,
						     data.dsize);
		if ((data.dsize != 0) && (data.dptr == NULL)) {
			return false;
		}
		*pdata = data;
	}

	if (pheader != NULL) {
		*pheader = h;
	}

	return true;
}

/*
  fetch a record inside a transaction
 */
static NTSTATUS db_ctdb_transaction_fetch(struct db_ctdb_ctx *db,
					  TALLOC_CTX *mem_ctx,
					  TDB_DATA key, TDB_DATA *data)
{
	struct db_ctdb_transaction_handle *h = db->transaction;
	NTSTATUS status;
	bool found;

	found = pull_newest_from_marshall_buffer(h->m_write, key, NULL,
						 mem_ctx, data);
	if (found) {
		return NT_STATUS_OK;
	}

	status = db_ctdb_ltdb_fetch(h->ctx, key, NULL, mem_ctx, data);

	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		*data = tdb_null;
	}

	return status;
}

/**
 * Fetch a record from a persistent database
 * without record locking and without an active transaction.
 *
 * This just fetches from the local database copy.
 * Since the databases are kept in syc cluster-wide,
 * there is no point in doing a ctdb call to fetch the
 * record from the lmaster. It does even harm since migration
 * of records bump their RSN and hence render the persistent
 * database inconsistent.
 */
static NTSTATUS db_ctdb_fetch_persistent(struct db_ctdb_ctx *db,
					 TALLOC_CTX *mem_ctx,
					 TDB_DATA key, TDB_DATA *data)
{
	NTSTATUS status;

	status = db_ctdb_ltdb_fetch(db, key, NULL, mem_ctx, data);

	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		*data = tdb_null;
	}

	return status;
}

static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag);
static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec);

static struct db_record *db_ctdb_fetch_locked_transaction(struct db_ctdb_ctx *ctx,
							  TALLOC_CTX *mem_ctx,
							  TDB_DATA key)
{
	struct db_record *result;
	TDB_DATA ctdb_data;

	if (!(result = talloc(mem_ctx, struct db_record))) {
		DEBUG(0, ("talloc failed\n"));
		return NULL;
	}

	result->private_data = ctx->transaction;

	result->key.dsize = key.dsize;
	result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
						    key.dsize);
	if (result->key.dptr == NULL) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	result->store = db_ctdb_store_transaction;
	result->delete_rec = db_ctdb_delete_transaction;

	if (pull_newest_from_marshall_buffer(ctx->transaction->m_write, key,
					     NULL, result, &result->value)) {
		return result;
	}

	ctdb_data = tdb_fetch_compat(ctx->wtdb->tdb, key);
	if (ctdb_data.dptr == NULL) {
		/* create the record */
		result->value = tdb_null;
		return result;
	}

	result->value.dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);
	result->value.dptr = NULL;

	if ((result->value.dsize != 0)
	    && !(result->value.dptr = (uint8_t *)talloc_memdup(
			 result, ctdb_data.dptr + sizeof(struct ctdb_ltdb_header),
			 result->value.dsize))) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
	}

	SAFE_FREE(ctdb_data.dptr);

	return result;
}

static int db_ctdb_record_destructor(struct db_record **recp)
{
	struct db_record *rec = talloc_get_type_abort(*recp, struct db_record);
	struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
		rec->private_data, struct db_ctdb_transaction_handle);
	int ret = h->ctx->db->transaction_commit(h->ctx->db);
	if (ret != 0) {
		DEBUG(0,(__location__ " transaction_commit failed\n"));
	}
	return 0;
}

/*
  auto-create a transaction for persistent databases
 */
static struct db_record *db_ctdb_fetch_locked_persistent(struct db_ctdb_ctx *ctx,
							 TALLOC_CTX *mem_ctx,
							 TDB_DATA key)
{
	int res;
	struct db_record *rec, **recp;

	res = db_ctdb_transaction_start(ctx->db);
	if (res == -1) {
		return NULL;
	}

	rec = db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
	if (rec == NULL) {
		ctx->db->transaction_cancel(ctx->db);
		return NULL;
	}

	/* destroy this transaction when we release the lock */
	recp = talloc(rec, struct db_record *);
	if (recp == NULL) {
		ctx->db->transaction_cancel(ctx->db);
		talloc_free(rec);
		return NULL;
	}
	*recp = rec;
	talloc_set_destructor(recp, db_ctdb_record_destructor);
	return rec;
}


/*
  stores a record inside a transaction
 */
static NTSTATUS db_ctdb_transaction_store(struct db_ctdb_transaction_handle *h,
					  TDB_DATA key, TDB_DATA data)
{
	TALLOC_CTX *tmp_ctx = talloc_new(h);
	TDB_DATA rec;
	struct ctdb_ltdb_header header;

	ZERO_STRUCT(header);

	/* we need the header so we can update the RSN */

	if (!pull_newest_from_marshall_buffer(h->m_write, key, &header,
					      NULL, NULL)) {

		rec = tdb_fetch_compat(h->ctx->wtdb->tdb, key);

		if (rec.dptr != NULL) {
			memcpy(&header, rec.dptr,
			       sizeof(struct ctdb_ltdb_header));
			rec.dsize -= sizeof(struct ctdb_ltdb_header);

			/*
			 * a special case, we are writing the same
			 * data that is there now
			 */
			if (data.dsize == rec.dsize &&
			    memcmp(data.dptr,
				   rec.dptr + sizeof(struct ctdb_ltdb_header),
				   data.dsize) == 0) {
				SAFE_FREE(rec.dptr);
				talloc_free(tmp_ctx);
				return NT_STATUS_OK;
			}
		}
		SAFE_FREE(rec.dptr);
	}

	header.dmaster = get_my_vnn();
	header.rsn++;

	h->m_write = db_ctdb_marshall_add(h, h->m_write, h->ctx->db_id, 0, key, &header, data);
	if (h->m_write == NULL) {
		DEBUG(0,(__location__ " Failed to add to marshalling record\n"));
		talloc_free(tmp_ctx);
		return NT_STATUS_NO_MEMORY;
	}

	talloc_free(tmp_ctx);
	return NT_STATUS_OK;
}


/* 
   a record store inside a transaction
 */
static NTSTATUS db_ctdb_store_transaction(struct db_record *rec, TDB_DATA data, int flag)
{
	struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
		rec->private_data, struct db_ctdb_transaction_handle);
	NTSTATUS status;

	status = db_ctdb_transaction_store(h, rec->key, data);
	return status;
}

/*
   a record delete inside a transaction
 */
static NTSTATUS db_ctdb_delete_transaction(struct db_record *rec)
{
	struct db_ctdb_transaction_handle *h = talloc_get_type_abort(
		rec->private_data, struct db_ctdb_transaction_handle);
	NTSTATUS status;

	status =  db_ctdb_transaction_store(h, rec->key, tdb_null);
	return status;
}

/**
 * Fetch the db sequence number of a persistent db directly from the db.
 */
static NTSTATUS db_ctdb_fetch_db_seqnum_from_db(struct db_ctdb_ctx *db,
						uint64_t *seqnum)
{
	NTSTATUS status;
	const char *keyname = CTDB_DB_SEQNUM_KEY;
	TDB_DATA key;
	TDB_DATA data;
	struct ctdb_ltdb_header header;
	TALLOC_CTX *mem_ctx = talloc_stackframe();

	if (seqnum == NULL) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	key = string_term_tdb_data(keyname);

	status = db_ctdb_ltdb_fetch(db, key, &header, mem_ctx, &data);
	if (!NT_STATUS_IS_OK(status) &&
	    !NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND))
	{
		goto done;
	}

	status = NT_STATUS_OK;

	if (data.dsize != sizeof(uint64_t)) {
		*seqnum = 0;
		goto done;
	}

	*seqnum = *(uint64_t *)data.dptr;

done:
	TALLOC_FREE(mem_ctx);
	return status;
}

/**
 * Store the database sequence number inside a transaction.
 */
static NTSTATUS db_ctdb_store_db_seqnum(struct db_ctdb_transaction_handle *h,
					uint64_t seqnum)
{
	NTSTATUS status;
	const char *keyname = CTDB_DB_SEQNUM_KEY;
	TDB_DATA key;
	TDB_DATA data;

	key = string_term_tdb_data(keyname);

	data.dptr = (uint8_t *)&seqnum;
	data.dsize = sizeof(uint64_t);

	status = db_ctdb_transaction_store(h, key, data);

	return status;
}

/*
  commit a transaction
 */
static int db_ctdb_transaction_commit(struct db_context *db)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);
	NTSTATUS rets;
	int status;
	struct db_ctdb_transaction_handle *h = ctx->transaction;
	uint64_t old_seqnum, new_seqnum;
	int ret;

	if (h == NULL) {
		DEBUG(0,(__location__ " transaction commit with no open transaction on db 0x%08x\n", ctx->db_id));
		return -1;
	}

	if (h->nested_cancel) {
		db->transaction_cancel(db);
		DEBUG(5,(__location__ " Failed transaction commit after nested cancel\n"));
		return -1;
	}

	if (h->nesting != 0) {
		h->nesting--;
		DEBUG(5, (__location__ " transaction commit on db 0x%08x: nesting %d -> %d\n",
			  ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
		return 0;
	}

	if (h->m_write == NULL) {
		/*
		 * No changes were made, so don't change the seqnum,
		 * don't push to other node, just exit with success.
		 */
		ret = 0;
		goto done;
	}

	DEBUG(5,(__location__ " transaction commit on db 0x%08x\n", ctx->db_id));

	/*
	 * As the last db action before committing, bump the database sequence
	 * number. Note that this undoes all changes to the seqnum records
	 * performed under the transaction. This record is not meant to be
	 * modified by user interaction. It is for internal use only...
	 */
	rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &old_seqnum);
	if (!NT_STATUS_IS_OK(rets)) {
		DEBUG(1, (__location__ " failed to fetch the db sequence number "
			  "in transaction commit on db 0x%08x\n", ctx->db_id));
		ret = -1;
		goto done;
	}

	new_seqnum = old_seqnum + 1;

	rets = db_ctdb_store_db_seqnum(h, new_seqnum);
	if (!NT_STATUS_IS_OK(rets)) {
		DEBUG(1, (__location__ "failed to store the db sequence number "
			  " in transaction commit on db 0x%08x\n", ctx->db_id));
		ret = -1;
		goto done;
	}

again:
	/* tell ctdbd to commit to the other nodes */
	rets = ctdbd_control_local(messaging_ctdbd_connection(),
				   CTDB_CONTROL_TRANS3_COMMIT,
				   h->ctx->db_id, 0,
				   db_ctdb_marshall_finish(h->m_write),
				   NULL, NULL, &status);
	if (!NT_STATUS_IS_OK(rets) || status != 0) {
		/*
		 * The TRANS3_COMMIT control should only possibly fail when a
		 * recovery has been running concurrently. In any case, the db
		 * will be the same on all nodes, either the new copy or the
		 * old copy.  This can be detected by comparing the old and new
		 * local sequence numbers.
		 */
		rets = db_ctdb_fetch_db_seqnum_from_db(ctx, &new_seqnum);
		if (!NT_STATUS_IS_OK(rets)) {
			DEBUG(1, (__location__ " failed to refetch db sequence "
				  "number after failed TRANS3_COMMIT\n"));
			ret = -1;
			goto done;
		}

		if (new_seqnum == old_seqnum) {
			/* Recovery prevented all our changes: retry. */
			goto again;
		} else if (new_seqnum != (old_seqnum + 1)) {
			DEBUG(0, (__location__ " ERROR: new_seqnum[%lu] != "
				  "old_seqnum[%lu] + (0 or 1) after failed "
				  "TRANS3_COMMIT - this should not happen!\n",
				  (unsigned long)new_seqnum,
				  (unsigned long)old_seqnum));
			ret = -1;
			goto done;
		}
		/*
		 * Recovery propagated our changes to all nodes, completing
		 * our commit for us - succeed.
		 */
	}

	ret = 0;

done:
	h->ctx->transaction = NULL;
	talloc_free(h);
	return ret;
}


/*
  cancel a transaction
 */
static int db_ctdb_transaction_cancel(struct db_context *db)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);
	struct db_ctdb_transaction_handle *h = ctx->transaction;

	if (h == NULL) {
		DEBUG(0,(__location__ " transaction cancel with no open transaction on db 0x%08x\n", ctx->db_id));
		return -1;
	}

	if (h->nesting != 0) {
		h->nesting--;
		h->nested_cancel = true;
		DEBUG(5, (__location__ " transaction cancel on db 0x%08x: nesting %d -> %d\n",
			  ctx->db_id, ctx->transaction->nesting + 1, ctx->transaction->nesting));
		return 0;
	}

	DEBUG(5,(__location__ " Cancel transaction on db 0x%08x\n", ctx->db_id));

	ctx->transaction = NULL;
	talloc_free(h);
	return 0;
}


static NTSTATUS db_ctdb_store(struct db_record *rec, TDB_DATA data, int flag)
{
	struct db_ctdb_rec *crec = talloc_get_type_abort(
		rec->private_data, struct db_ctdb_rec);

	return db_ctdb_ltdb_store(crec->ctdb_ctx, rec->key, &(crec->header), data);
}



#ifdef HAVE_CTDB_CONTROL_SCHEDULE_FOR_DELETION_DECL
static NTSTATUS db_ctdb_send_schedule_for_deletion(struct db_record *rec)
{
	NTSTATUS status;
	struct ctdb_control_schedule_for_deletion *dd;
	TDB_DATA indata;
	int cstatus;
	struct db_ctdb_rec *crec = talloc_get_type_abort(
		rec->private_data, struct db_ctdb_rec);

	indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + rec->key.dsize;
	indata.dptr = talloc_zero_array(crec, uint8_t, indata.dsize);
	if (indata.dptr == NULL) {
		DEBUG(0, (__location__ " talloc failed!\n"));
		return NT_STATUS_NO_MEMORY;
	}

	dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
	dd->db_id = crec->ctdb_ctx->db_id;
	dd->hdr = crec->header;
	dd->keylen = rec->key.dsize;
	memcpy(dd->key, rec->key.dptr, rec->key.dsize);

	status = ctdbd_control_local(messaging_ctdbd_connection(),
				     CTDB_CONTROL_SCHEDULE_FOR_DELETION,
				     crec->ctdb_ctx->db_id,
				     CTDB_CTRL_FLAG_NOREPLY, /* flags */
				     indata,
				     NULL, /* outdata */
				     NULL, /* errmsg */
				     &cstatus);
	talloc_free(indata.dptr);

	if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
		DEBUG(1, (__location__ " Error sending local control "
			  "SCHEDULE_FOR_DELETION: %s, cstatus = %d\n",
			  nt_errstr(status), cstatus));
		if (NT_STATUS_IS_OK(status)) {
			status = NT_STATUS_UNSUCCESSFUL;
		}
	}

	return status;
}
#endif

static NTSTATUS db_ctdb_delete(struct db_record *rec)
{
	TDB_DATA data;
	NTSTATUS status;

	/*
	 * We have to store the header with empty data. TODO: Fix the
	 * tdb-level cleanup
	 */

	ZERO_STRUCT(data);

	status = db_ctdb_store(rec, data, 0);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

#ifdef HAVE_CTDB_CONTROL_SCHEDULE_FOR_DELETION_DECL
	status = db_ctdb_send_schedule_for_deletion(rec);
#endif

	return status;
}

static int db_ctdb_record_destr(struct db_record* data)
{
	struct db_ctdb_rec *crec = talloc_get_type_abort(
		data->private_data, struct db_ctdb_rec);
	int threshold;

	DEBUG(10, (DEBUGLEVEL > 10
		   ? "Unlocking db %u key %s\n"
		   : "Unlocking db %u key %.20s\n",
		   (int)crec->ctdb_ctx->db_id,
		   hex_encode_talloc(data, (unsigned char *)data->key.dptr,
			      data->key.dsize)));

	tdb_chainunlock(crec->ctdb_ctx->wtdb->tdb, data->key);

	threshold = lp_ctdb_locktime_warn_threshold();
	if (threshold != 0) {
		double timediff = timeval_elapsed(&crec->lock_time);
		if ((timediff * 1000) > threshold) {
			const char *key;

			key = hex_encode_talloc(data,
						(unsigned char *)data->key.dptr,
						data->key.dsize);
			DEBUG(0, ("Held tdb lock on db %s, key %s %f seconds\n",
				  tdb_name(crec->ctdb_ctx->wtdb->tdb), key,
				  timediff));
		}
	}

	return 0;
}

/**
 * Check whether we have a valid local copy of the given record,
 * either for reading or for writing.
 */
static bool db_ctdb_can_use_local_copy(TDB_DATA ctdb_data, bool read_only)
{
	struct ctdb_ltdb_header *hdr;

	if (ctdb_data.dptr == NULL)
		return false;

	if (ctdb_data.dsize < sizeof(struct ctdb_ltdb_header))
		return false;

	hdr = (struct ctdb_ltdb_header *)ctdb_data.dptr;

#ifdef HAVE_CTDB_WANT_READONLY_DECL
	if (hdr->dmaster != get_my_vnn()) {
		/* If we're not dmaster, it must be r/o copy. */
		return read_only && (hdr->flags & CTDB_REC_RO_HAVE_READONLY);
	}

	/*
	 * If we want write access, no one may have r/o copies.
	 */
	return read_only || !(hdr->flags & CTDB_REC_RO_HAVE_DELEGATIONS);
#else
	return (hdr->dmaster == get_my_vnn());
#endif
}

static struct db_record *fetch_locked_internal(struct db_ctdb_ctx *ctx,
					       TALLOC_CTX *mem_ctx,
					       TDB_DATA key,
					       bool tryonly)
{
	struct db_record *result;
	struct db_ctdb_rec *crec;
	NTSTATUS status;
	TDB_DATA ctdb_data;
	int migrate_attempts = 0;
	int lockret;

	if (!(result = talloc(mem_ctx, struct db_record))) {
		DEBUG(0, ("talloc failed\n"));
		return NULL;
	}

	if (!(crec = talloc_zero(result, struct db_ctdb_rec))) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	result->db = ctx->db;
	result->private_data = (void *)crec;
	crec->ctdb_ctx = ctx;

	result->key.dsize = key.dsize;
	result->key.dptr = (uint8_t *)talloc_memdup(result, key.dptr,
						    key.dsize);
	if (result->key.dptr == NULL) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	/*
	 * Do a blocking lock on the record
	 */
again:

	if (DEBUGLEVEL >= 10) {
		char *keystr = hex_encode_talloc(result, key.dptr, key.dsize);
		DEBUG(10, (DEBUGLEVEL > 10
			   ? "Locking db %u key %s\n"
			   : "Locking db %u key %.20s\n",
			   (int)crec->ctdb_ctx->db_id, keystr));
		TALLOC_FREE(keystr);
	}

	lockret = tryonly
		? tdb_chainlock_nonblock(ctx->wtdb->tdb, key)
		: tdb_chainlock(ctx->wtdb->tdb, key);
	if (lockret != 0) {
		DEBUG(3, ("tdb_chainlock failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	result->store = db_ctdb_store;
	result->delete_rec = db_ctdb_delete;
	talloc_set_destructor(result, db_ctdb_record_destr);

	ctdb_data = tdb_fetch_compat(ctx->wtdb->tdb, key);

	/*
	 * See if we have a valid record and we are the dmaster. If so, we can
	 * take the shortcut and just return it.
	 */

	if (!db_ctdb_can_use_local_copy(ctdb_data, false)) {
		SAFE_FREE(ctdb_data.dptr);
		tdb_chainunlock(ctx->wtdb->tdb, key);
		talloc_set_destructor(result, NULL);

		if (tryonly && (migrate_attempts != 0)) {
			DEBUG(5, ("record migrated away again\n"));
			TALLOC_FREE(result);
			return NULL;
		}

		migrate_attempts += 1;

		DEBUG(10, ("ctdb_data.dptr = %p, dmaster = %u (%u) %u\n",
			   ctdb_data.dptr, ctdb_data.dptr ?
			   ((struct ctdb_ltdb_header *)ctdb_data.dptr)->dmaster : -1,
			   get_my_vnn(),
			   ctdb_data.dptr ?
			   ((struct ctdb_ltdb_header *)ctdb_data.dptr)->flags : 0));

		status = ctdbd_migrate(messaging_ctdbd_connection(), ctx->db_id,
				       key);
		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(5, ("ctdb_migrate failed: %s\n",
				  nt_errstr(status)));
			TALLOC_FREE(result);
			return NULL;
		}
		/* now its migrated, try again */
		goto again;
	}

	if (migrate_attempts > 10) {
		DEBUG(0, ("db_ctdb_fetch_locked for %s key %s needed %d "
			  "attempts\n", tdb_name(ctx->wtdb->tdb),
			  hex_encode_talloc(talloc_tos(),
					    (unsigned char *)key.dptr,
					    key.dsize),
			  migrate_attempts));
	}

	GetTimeOfDay(&crec->lock_time);

	memcpy(&crec->header, ctdb_data.dptr, sizeof(crec->header));

	result->value.dsize = ctdb_data.dsize - sizeof(crec->header);
	result->value.dptr = NULL;

	if ((result->value.dsize != 0)
	    && !(result->value.dptr = (uint8_t *)talloc_memdup(
			 result, ctdb_data.dptr + sizeof(crec->header),
			 result->value.dsize))) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
	}

	SAFE_FREE(ctdb_data.dptr);

	return result;
}

static struct db_record *db_ctdb_fetch_locked(struct db_context *db,
					      TALLOC_CTX *mem_ctx,
					      TDB_DATA key)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);

	if (ctx->transaction != NULL) {
		return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
	}

	if (db->persistent) {
		return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
	}

	return fetch_locked_internal(ctx, mem_ctx, key, false);
}

static struct db_record *db_ctdb_try_fetch_locked(struct db_context *db,
						  TALLOC_CTX *mem_ctx,
						  TDB_DATA key)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);

	if (ctx->transaction != NULL) {
		return db_ctdb_fetch_locked_transaction(ctx, mem_ctx, key);
	}

	if (db->persistent) {
		return db_ctdb_fetch_locked_persistent(ctx, mem_ctx, key);
	}

	return fetch_locked_internal(ctx, mem_ctx, key, true);
}

/*
  fetch (unlocked, no migration) operation on ctdb
 */
static NTSTATUS db_ctdb_fetch(struct db_context *db, TALLOC_CTX *mem_ctx,
			      TDB_DATA key, TDB_DATA *data)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
							struct db_ctdb_ctx);
	NTSTATUS status;
	TDB_DATA ctdb_data;

	if (ctx->transaction) {
		return db_ctdb_transaction_fetch(ctx, mem_ctx, key, data);
	}

	if (db->persistent) {
		return db_ctdb_fetch_persistent(ctx, mem_ctx, key, data);
	}

	/* try a direct fetch */
	ctdb_data = tdb_fetch_compat(ctx->wtdb->tdb, key);

	/*
	 * See if we have a valid record and we are the dmaster. If so, we can
	 * take the shortcut and just return it.
	 * we bypass the dmaster check for persistent databases
	 */
	if (db_ctdb_can_use_local_copy(ctdb_data, true)) {
		/*
		 * We have a valid local copy - avoid the ctdb protocol op
		 */
		data->dsize = ctdb_data.dsize - sizeof(struct ctdb_ltdb_header);

		data->dptr = (uint8_t *)talloc_memdup(
			mem_ctx, ctdb_data.dptr+sizeof(struct ctdb_ltdb_header),
			data->dsize);

		SAFE_FREE(ctdb_data.dptr);

		if (data->dptr == NULL) {
			return NT_STATUS_NO_MEMORY;
		}
		return NT_STATUS_OK;
	}

	SAFE_FREE(ctdb_data.dptr);

	/*
	 * We weren't able to get it locally - ask ctdb to fetch it for us.
	 * If we already had *something*, it's probably worth making a local
	 * read-only copy.
	 */
	status = ctdbd_fetch(messaging_ctdbd_connection(), ctx->db_id, key,
			     mem_ctx, data,
			     ctdb_data.dsize >= sizeof(struct ctdb_ltdb_header));
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(5, ("ctdbd_fetch failed: %s\n", nt_errstr(status)));
	}

	return status;
}

static NTSTATUS db_ctdb_parse_record(struct db_context *db, TDB_DATA key,
				     void (*parser)(TDB_DATA key,
						    TDB_DATA data,
						    void *private_data),
				     void *private_data)
{
	NTSTATUS status;
	TDB_DATA data;

	status = db_ctdb_fetch(db, talloc_tos(), key, &data);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}
	parser(key, data, private_data);
	TALLOC_FREE(data.dptr);
	return NT_STATUS_OK;
}

struct traverse_state {
	struct db_context *db;
	int (*fn)(struct db_record *rec, void *private_data);
	void *private_data;
	int count;
};

static void traverse_callback(TDB_DATA key, TDB_DATA data, void *private_data)
{
	struct traverse_state *state = (struct traverse_state *)private_data;
	struct db_record *rec;
	TALLOC_CTX *tmp_ctx = talloc_new(state->db);
	/* we have to give them a locked record to prevent races */
	rec = db_ctdb_fetch_locked(state->db, tmp_ctx, key);
	if (rec && rec->value.dsize > 0) {
		state->fn(rec, state->private_data);
	}
	talloc_free(tmp_ctx);
}

static int traverse_persistent_callback(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
					void *private_data)
{
	struct traverse_state *state = (struct traverse_state *)private_data;
	struct db_record *rec;
	TALLOC_CTX *tmp_ctx = talloc_new(state->db);
	int ret = 0;

	/*
	 * Skip the __db_sequence_number__ key:
	 * This is used for persistent transactions internally.
	 */
	if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
	    strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
	{
		goto done;
	}

	/* we have to give them a locked record to prevent races */
	rec = db_ctdb_fetch_locked(state->db, tmp_ctx, kbuf);
	if (rec && rec->value.dsize > 0) {
		ret = state->fn(rec, state->private_data);
	}

done:
	talloc_free(tmp_ctx);
	return ret;
}

/* wrapper to use traverse_persistent_callback with dbwrap */
static int traverse_persistent_callback_dbwrap(struct db_record *rec, void* data)
{
	return traverse_persistent_callback(NULL, rec->key, rec->value, data);
}


static int db_ctdb_traverse(struct db_context *db,
			    int (*fn)(struct db_record *rec,
				      void *private_data),
			    void *private_data)
{
	NTSTATUS status;
        struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
                                                        struct db_ctdb_ctx);
	struct traverse_state state;

	state.db = db;
	state.fn = fn;
	state.private_data = private_data;
	state.count = 0;

	if (db->persistent) {
		struct tdb_context *ltdb = ctx->wtdb->tdb;
		int ret;

		/* for persistent databases we don't need to do a ctdb traverse,
		   we can do a faster local traverse */
		ret = tdb_traverse(ltdb, traverse_persistent_callback, &state);
		if (ret < 0) {
			return ret;
		}
		if (ctx->transaction && ctx->transaction->m_write) {
			/*
			 * we now have to handle keys not yet
			 * present at transaction start
			 */
			struct db_context *newkeys = db_open_rbt(talloc_tos());
			struct ctdb_marshall_buffer *mbuf = ctx->transaction->m_write;
			struct ctdb_rec_data *rec=NULL;
			int i;
			int count = 0;

			if (newkeys == NULL) {
				return -1;
			}

			for (i=0; i<mbuf->count; i++) {
				TDB_DATA key;
				rec =db_ctdb_marshall_loop_next(mbuf, rec,
								NULL, NULL,
								&key, NULL);
				SMB_ASSERT(rec != NULL);

				if (!tdb_exists(ltdb, key)) {
					dbwrap_store(newkeys, key, tdb_null, 0);
				}
			}
			status = dbwrap_traverse(newkeys,
						 traverse_persistent_callback_dbwrap,
						 &state,
						 &count);
			talloc_free(newkeys);
			if (!NT_STATUS_IS_OK(status)) {
				return -1;
			}
			ret += count;
		}
		return ret;
	}

	status = ctdbd_traverse(ctx->db_id, traverse_callback, &state);
	if (!NT_STATUS_IS_OK(status)) {
		return -1;
	}
	return state.count;
}

static NTSTATUS db_ctdb_store_deny(struct db_record *rec, TDB_DATA data, int flag)
{
	return NT_STATUS_MEDIA_WRITE_PROTECTED;
}

static NTSTATUS db_ctdb_delete_deny(struct db_record *rec)
{
	return NT_STATUS_MEDIA_WRITE_PROTECTED;
}

static void traverse_read_callback(TDB_DATA key, TDB_DATA data, void *private_data)
{
	struct traverse_state *state = (struct traverse_state *)private_data;
	struct db_record rec;
	rec.key = key;
	rec.value = data;
	rec.store = db_ctdb_store_deny;
	rec.delete_rec = db_ctdb_delete_deny;
	rec.private_data = state->db;
	state->fn(&rec, state->private_data);
	state->count++;
}

static int traverse_persistent_callback_read(TDB_CONTEXT *tdb, TDB_DATA kbuf, TDB_DATA dbuf,
					void *private_data)
{
	struct traverse_state *state = (struct traverse_state *)private_data;
	struct db_record rec;

	/*
	 * Skip the __db_sequence_number__ key:
	 * This is used for persistent transactions internally.
	 */
	if (kbuf.dsize == strlen(CTDB_DB_SEQNUM_KEY) + 1 &&
	    strcmp((const char*)kbuf.dptr, CTDB_DB_SEQNUM_KEY) == 0)
	{
		return 0;
	}

	rec.key = kbuf;
	rec.value = dbuf;
	rec.store = db_ctdb_store_deny;
	rec.delete_rec = db_ctdb_delete_deny;
	rec.private_data = state->db;

	if (rec.value.dsize <= sizeof(struct ctdb_ltdb_header)) {
		/* a deleted record */
		return 0;
	}
	rec.value.dsize -= sizeof(struct ctdb_ltdb_header);
	rec.value.dptr += sizeof(struct ctdb_ltdb_header);

	state->count++;
	return state->fn(&rec, state->private_data);
}

static int db_ctdb_traverse_read(struct db_context *db,
				 int (*fn)(struct db_record *rec,
					   void *private_data),
				 void *private_data)
{
	NTSTATUS status;
        struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
                                                        struct db_ctdb_ctx);
	struct traverse_state state;

	state.db = db;
	state.fn = fn;
	state.private_data = private_data;
	state.count = 0;

	if (db->persistent) {
		/* for persistent databases we don't need to do a ctdb traverse,
		   we can do a faster local traverse */
		return tdb_traverse_read(ctx->wtdb->tdb, traverse_persistent_callback_read, &state);
	}

	status = ctdbd_traverse(ctx->db_id, traverse_read_callback, &state);
	if (!NT_STATUS_IS_OK(status)) {
		return -1;
	}
	return state.count;
}

static int db_ctdb_get_seqnum(struct db_context *db)
{
        struct db_ctdb_ctx *ctx = talloc_get_type_abort(db->private_data,
                                                        struct db_ctdb_ctx);
	return tdb_get_seqnum(ctx->wtdb->tdb);
}

static void db_ctdb_id(struct db_context *db, const uint8_t **id,
		       size_t *idlen)
{
	struct db_ctdb_ctx *ctx = talloc_get_type_abort(
		db->private_data, struct db_ctdb_ctx);

	*id = (uint8_t *)&ctx->db_id;
	*idlen = sizeof(ctx->db_id);
}

struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
				const char *name,
				int hash_size, int tdb_flags,
				int open_flags, mode_t mode,
				enum dbwrap_lock_order lock_order)
{
	struct db_context *result;
	struct db_ctdb_ctx *db_ctdb;
	char *db_path;
	struct ctdbd_connection *conn;
	struct loadparm_context *lp_ctx;
	struct ctdb_db_priority prio;
	NTSTATUS status;
	int cstatus;

	if (!lp_clustering()) {
		DEBUG(10, ("Clustering disabled -- no ctdb\n"));
		return NULL;
	}

	if (!(result = talloc_zero(mem_ctx, struct db_context))) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	if (!(db_ctdb = talloc(result, struct db_ctdb_ctx))) {
		DEBUG(0, ("talloc failed\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	db_ctdb->transaction = NULL;
	db_ctdb->db = result;

	conn = messaging_ctdbd_connection();
	if (conn == NULL) {
		DEBUG(1, ("Could not connect to ctdb\n"));
		TALLOC_FREE(result);
		return NULL;
	}

	if (!NT_STATUS_IS_OK(ctdbd_db_attach(conn, name, &db_ctdb->db_id, tdb_flags))) {
		DEBUG(0, ("ctdbd_db_attach failed for %s\n", name));
		TALLOC_FREE(result);
		return NULL;
	}

	db_path = ctdbd_dbpath(conn, db_ctdb, db_ctdb->db_id);

	result->persistent = ((tdb_flags & TDB_CLEAR_IF_FIRST) == 0);
	result->lock_order = lock_order;

	/* only pass through specific flags */
	tdb_flags &= TDB_SEQNUM;

	/* honor permissions if user has specified O_CREAT */
	if (open_flags & O_CREAT) {
		chmod(db_path, mode);
	}

	prio.db_id = db_ctdb->db_id;
	prio.priority = lock_order;

	status = ctdbd_control_local(
		conn, CTDB_CONTROL_SET_DB_PRIORITY, 0, 0,
		make_tdb_data((uint8_t *)&prio, sizeof(prio)),
		NULL, NULL, &cstatus);

	if (!NT_STATUS_IS_OK(status) || (cstatus != 0)) {
		DEBUG(1, ("CTDB_CONTROL_SET_DB_PRIORITY failed: %s, %d\n",
			  nt_errstr(status), cstatus));
		TALLOC_FREE(result);
		return NULL;
	}

	lp_ctx = loadparm_init_s3(db_path, loadparm_s3_helpers());

	db_ctdb->wtdb = tdb_wrap_open(db_ctdb, db_path, hash_size, tdb_flags,
				      O_RDWR, 0, lp_ctx);
	talloc_unlink(db_path, lp_ctx);
	if (db_ctdb->wtdb == NULL) {
		DEBUG(0, ("Could not open tdb %s: %s\n", db_path, strerror(errno)));
		TALLOC_FREE(result);
		return NULL;
	}
	talloc_free(db_path);

	if (result->persistent) {
		db_ctdb->lock_ctx = g_lock_ctx_init(db_ctdb,
						    ctdb_conn_msg_ctx(conn));
		if (db_ctdb->lock_ctx == NULL) {
			DEBUG(0, ("g_lock_ctx_init failed\n"));
			TALLOC_FREE(result);
			return NULL;
		}
	}

	result->private_data = (void *)db_ctdb;
	result->fetch_locked = db_ctdb_fetch_locked;
	result->try_fetch_locked = db_ctdb_try_fetch_locked;
	result->parse_record = db_ctdb_parse_record;
	result->traverse = db_ctdb_traverse;
	result->traverse_read = db_ctdb_traverse_read;
	result->get_seqnum = db_ctdb_get_seqnum;
	result->transaction_start = db_ctdb_transaction_start;
	result->transaction_commit = db_ctdb_transaction_commit;
	result->transaction_cancel = db_ctdb_transaction_cancel;
	result->id = db_ctdb_id;
	result->stored_callback = NULL;

	DEBUG(3,("db_open_ctdb: opened database '%s' with dbid 0x%x\n",
		 name, db_ctdb->db_id));

	return result;
}

#else /* CLUSTER_SUPPORT */

struct db_context *db_open_ctdb(TALLOC_CTX *mem_ctx,
				const char *name,
				int hash_size, int tdb_flags,
				int open_flags, mode_t mode,
				enum dbwrap_lock_order lock_order)
{
	DEBUG(3, ("db_open_ctdb: no cluster support!\n"));
	errno = ENOSYS;
	return NULL;
}

#endif