File: bdb_lib.c

package info (click to toggle)
opensips 2.2.2-3.1
  • links: PTS
  • area: main
  • in suites: bullseye, sid
  • size: 31,160 kB
  • sloc: ansic: 334,348; xml: 91,231; perl: 6,659; sh: 5,148; sql: 4,175; makefile: 3,167; yacc: 2,499; python: 1,197; cpp: 611; php: 573
file content (1337 lines) | stat: -rw-r--r-- 26,266 bytes parent folder | download | duplicates (2)
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
/*
 * db_berkeley module, portions of this code were templated using
 * the dbtext and postgres modules.

 * Copyright (C) 2007 Cisco Systems
 *
 * This file is part of opensips, a free SIP server.
 *
 * opensips 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 2 of the License, or
 * (at your option) any later version
 *
 * opensips 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 * History:
 * --------
 * 2007-09-19  genesis (wiquan)
 */

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
#include "../../ut.h"
#include "../../mem/mem.h"
#include "../../dprint.h"

#include "bdb_util.h"
#include "bdb_lib.h"
#include "bdb_val.h"

static database_p *_cachedb = NULL;
static db_parms_p _db_parms = NULL;

/**
 *
 */
int bdblib_init(db_parms_p _p)
{
	if (!_cachedb)
	{
		_cachedb = pkg_malloc( sizeof(database_p) );
		if (!_cachedb)
		{	LM_CRIT("not enough private memory\n");
			return -1;
		}

		*_cachedb = NULL;

		/*create default parms*/
		db_parms_p dp = (db_parms_p) pkg_malloc( sizeof(db_parms_t) );
		if (!dp)
		{	LM_CRIT("not enough private memory\n");
			return -1;
		}

		if(_p)
		{
			dp->cache_size  = _p->cache_size;
			dp->auto_reload = _p->auto_reload;
			dp->log_enable  = _p->log_enable;
			dp->journal_roll_interval = _p->journal_roll_interval;
		}
		else
		{
			dp->cache_size = (4 * 1024 * 1024); //4Mb
			dp->auto_reload = 0;
			dp->log_enable = 0;
			dp->journal_roll_interval = 3600;
		}

		_db_parms = dp;
	}
	return 0;
}


/**
 * close all DBs and then the DBENV; free all memory
 */
int bdblib_destroy(void)
{
	if (_cachedb)	db_free(*_cachedb);
	if(_db_parms)	pkg_free(_db_parms);
	return 0;
}


/** closes the underlying Berkeley DB.
  assumes the lib data-structures are already initialzed;
  used to sync and reload the db file.
*/
int bdblib_close(char* _n)
{
	str s;
	int rc;
	tbl_cache_p _tbc;
	DB* _db = NULL;
	DB_ENV* _env = NULL;
	database_p _db_p = *_cachedb;

	if (!_cachedb || !_n)
		return -1;

	rc = 0;
	s.s = (char*)_n;
	s.len = strlen(_n);

	if (_db_p)
	{
		_env = _db_p->dbenv;
		_tbc = _db_p->tables;
LM_DBG("ENV %.*s \n"
	, _db_p->name.len
	, _db_p->name.s);
		if(s.len == _db_p->name.len &&
		!strncasecmp(s.s, _db_p->name.s, _db_p->name.len))
		{
			//close the whole dbenv
			LM_DBG("ENV %.*s \n", s.len, s.s);
			while(_tbc)
			{
				if(_tbc->dtp)
				{
					lock_get(&_tbc->dtp->sem);
					_db = _tbc->dtp->db;
					if(_db)
						rc = _db->close(_db, 0);
					if(rc != 0)
						LM_CRIT("error closing %s\n", _tbc->dtp->name.s);
					_tbc->dtp->db = NULL;

					lock_release(&_tbc->dtp->sem);
				}
				_tbc = _tbc->next;
			}
			_env->close(_env, 0);
			_db_p->dbenv = NULL;
			return 0;
		}

		//close a particular db
		while(_tbc)
		{
			if(_tbc->dtp)
			{
	LM_DBG("checking DB %.*s \n"
		, _tbc->dtp->name.len
		, _tbc->dtp->name.s);

				if(_tbc->dtp->name.len == s.len &&
				!strncasecmp(_tbc->dtp->name.s, s.s, s.len ))
				{
					LM_DBG("DB %.*s \n", s.len, s.s);
					lock_get(&_tbc->dtp->sem);
					_db = _tbc->dtp->db;
					if(_db)
						rc = _db->close(_db, 0);
					if(rc != 0)
						LM_CRIT("error closing %s\n", _tbc->dtp->name.s);
					_tbc->dtp->db = NULL;
					lock_release(&_tbc->dtp->sem);
					return 0;
				}
			}
			_tbc = _tbc->next;
		}
	}
	LM_DBG("DB not found %.*s \n", s.len, s.s);
	return 1; /*table not found*/
}

/** opens the underlying Berkeley DB.
  assumes the lib data-structures are already initialzed;
  used to sync and reload the db file.
*/
int bdblib_reopen(char* _n)
{
	str s;
	int rc, flags;
	tbl_cache_p _tbc;
	DB* _db = NULL;
	DB_ENV* _env = NULL;
	database_p _db_p = *_cachedb;
	rc = flags = 0;
	_tbc = NULL;

	if (!_cachedb || !_n)
		return -1;

	s.s = (char*)_n;
	s.len = strlen(_n);

	if (_db_p)
	{
		_env = _db_p->dbenv;
		_tbc = _db_p->tables;

		if(s.len ==_db_p->name.len &&
		!strncasecmp(s.s, _db_p->name.s,_db_p->name.len))
		{
			//open the whole dbenv
			LM_DBG("-- bdblib_reopen ENV %.*s \n", s.len, s.s);
			if(!_db_p->dbenv)
			{	rc = bdblib_create_dbenv(&_env, _n);
				_db_p->dbenv = _env;
			}

			if(rc!=0) return rc;
			_env = _db_p->dbenv;
			_tbc = _db_p->tables;

			while(_tbc)
			{
				if(_tbc->dtp)
				{
					lock_get(&_tbc->dtp->sem);
					if(!_tbc->dtp->db)
					{
						if ((rc = db_create(&_db, _env, 0)) != 0)
						{	_env->err(_env, rc, "db_create");
							LM_CRIT("error in db_create, db error: %s.\n",db_strerror(rc));
							bdblib_recover(_tbc->dtp, rc);
						}
					}

					if ((rc = _db->open(_db, NULL, _n, NULL, DB_HASH, DB_CREATE, 0664)) != 0)
					{	_db->dbenv->err(_env, rc, "DB->open: %s", _n);
						LM_CRIT("error in db_open: %s.\n",db_strerror(rc));
						bdblib_recover(_tbc->dtp, rc);
					}

					_tbc->dtp->db = _db;
					lock_release(&_tbc->dtp->sem);
				}
				_tbc = _tbc->next;
			}
			_env->close(_env, 0);
			return rc;
		}

		//open a particular db
		while(_tbc)
		{
			if(_tbc->dtp)
			{
	LM_DBG("checking DB %.*s \n"
		, _tbc->dtp->name.len
		, _tbc->dtp->name.s);

				if(_tbc->dtp->name.len == s.len &&
				!strncasecmp(_tbc->dtp->name.s, s.s, s.len ))
				{
					LM_DBG("DB %.*s \n", s.len, s.s);
					lock_get(&_tbc->dtp->sem);
					if(!_tbc->dtp->db)
					{
						if ((rc = db_create(&_db, _env, 0)) != 0)
						{	_env->err(_env, rc, "db_create");
							LM_CRIT("error in db_create, db error: %s.\n",db_strerror(rc));
							bdblib_recover(_tbc->dtp, rc);
						}
					}

					if ((rc = _db->open(_db, NULL, _n, NULL, DB_HASH, DB_CREATE, 0664)) != 0)
					{	_db->dbenv->err(_env, rc, "DB->open: %s", _n);
						LM_CRIT("bdb open: %s.\n",db_strerror(rc));
						bdblib_recover(_tbc->dtp, rc);
					}
					_tbc->dtp->db = _db;
					lock_release(&_tbc->dtp->sem);
					return rc;
				}
			}
			_tbc = _tbc->next;
		}

	}
	LM_DBG("DB not found %.*s \n", s.len, s.s);
	return 1; /*table not found*/
}


/**
 *
 */
int bdblib_create_dbenv(DB_ENV **_dbenv, char* _home)
{
	DB_ENV *env;
	char *progname;
	int rc, flags;

	progname = "opensips";

	/* Create an environment and initialize it for additional error * reporting. */
	if ((rc = db_env_create(&env, 0)) != 0)
	{
		LM_ERR("db_env_create failed! bdb error: %s.\n", db_strerror(rc));
		return (rc);
	}

	env->set_errpfx(env, progname);

	/*  Specify the shared memory buffer pool cachesize */
	if ((rc = env->set_cachesize(env, 0, _db_parms->cache_size, 0)) != 0)
	{
		LM_ERR("dbenv set_cachsize failed! bdb error: %s.\n", db_strerror(rc));
		env->err(env, rc, "set_cachesize");
		goto err;
	}

	/* Concurrent Data Store flags */
	flags = DB_CREATE |
		DB_INIT_CDB |
		DB_INIT_MPOOL |
		DB_THREAD;

	/* Transaction Data Store flags ; not supported yet */
	/*
	flags = DB_CREATE |
		DB_RECOVER |
		DB_INIT_LOG |
		DB_INIT_LOCK |
		DB_INIT_MPOOL |
		DB_THREAD |
		DB_INIT_TXN;
	*/

	/* Open the environment */
	if ((rc = env->open(env, _home, flags, 0)) != 0)
	{
		LM_ERR("dbenv is not initialized! bdb error: %s.\n",db_strerror(rc));
		env->err(env, rc, "environment open: %s", _home);
		goto err;
	}

	*_dbenv = env;
	return (0);

err: (void)env->close(env, 0);
	return (rc);
}


/**
 */
database_p bdblib_get_db(str *_s)
{
	int rc;
	database_p _db_p=NULL;
	char name[512];

	if(!_s || !_s->s || _s->len<=0 || _s->len > 512)
		return NULL;

	if( !_cachedb)
	{
		LM_ERR("db_berkeley cache is not initialized! Check if you loaded db_berkeley "
			"before any other module that uses it.\n");
		return NULL;
	}

	_db_p = *_cachedb;
	if(_db_p)
	{
		LM_DBG("db already cached!\n");
		return _db_p;
	}

	if(!bdb_is_database(_s))
	{
		LM_ERR("database [%.*s] does not exists!\n" ,_s->len , _s->s);
		return NULL;
	}

	_db_p = (database_p)pkg_malloc(sizeof(database_t));
	if(!_db_p)
	{
		LM_ERR("no private memory for dbenv_t.\n");
		pkg_free(_db_p);
		return NULL;
	}

	_db_p->name.s = (char*)pkg_malloc(_s->len*sizeof(char));
	memcpy(_db_p->name.s, _s->s, _s->len);
	_db_p->name.len = _s->len;

	strncpy(name, _s->s, _s->len);
	name[_s->len] = 0;

	if ((rc = bdblib_create_dbenv(&(_db_p->dbenv), name)) != 0)
	{
		LM_ERR("bdblib_create_dbenv failed");
		pkg_free(_db_p->name.s);
		pkg_free(_db_p);
		return NULL;
	}

	_db_p->tables=NULL;
	*_cachedb = _db_p;

	return _db_p;
}


/**
 * look thru a linked list for the table. if dne, create a new one
 * and add to the list
*/
tbl_cache_p bdblib_get_table(database_p _db, str *_s)
{
	tbl_cache_p _tbc = NULL;
	table_p _tp = NULL;

	if(!_db || !_s || !_s->s || _s->len<=0)
		return NULL;

	if(!_db->dbenv)
	{
		return NULL;
	}

	_tbc = _db->tables;
	while(_tbc)
	{
		if(_tbc->dtp)
		{

			if(_tbc->dtp->name.len == _s->len
				&& !strncasecmp(_tbc->dtp->name.s, _s->s, _s->len ))
			{
				return _tbc;
			}
		}
		_tbc = _tbc->next;
	}

	_tbc = (tbl_cache_p)pkg_malloc(sizeof(tbl_cache_t));
	if(!_tbc)
		return NULL;

	if(!lock_init(&_tbc->sem))
	{
		pkg_free(_tbc);
		return NULL;
	}

	_tp = bdblib_create_table(_db, _s);

#ifdef BDB_EXTRA_DEBUG
	LM_DBG("table: %.*s\n", _s->len, _s->s);
#endif

	if(!_tp)
	{
		LM_ERR("failed to create table.\n");
		pkg_free(_tbc);
		return NULL;
	}

	lock_get(&_tbc->sem);
	_tbc->dtp = _tp;

	if(_db->tables)
		(_db->tables)->prev = _tbc;

	_tbc->next = _db->tables;
	_db->tables = _tbc;
	lock_release(&_tbc->sem);

	return _tbc;
}


void bdblib_log(int op, table_p _tp, char* _msg, int len)
{
	if(!_tp || !len) 		return;
	if(! _db_parms->log_enable) 	return;
	if (_tp->logflags == JLOG_NONE)	return;

	if ((_tp->logflags & op) == op)
	{	int op_len=7;
		char buf[MAX_ROW_SIZE + op_len];
		char *c;
		time_t now = time(NULL);

		if( _db_parms->journal_roll_interval)
		{
			if((_tp->t) && (now - _tp->t) > _db_parms->journal_roll_interval)
			{	/*try to roll logfile*/
				if(bdblib_create_journal(_tp))
				{
					LM_ERR("Journaling has FAILED !\n");
					return;
				}
			}
		}

		c = buf;
		switch (op)
		{
		case JLOG_INSERT:
			strncpy(c, "INSERT|", op_len);
			break;
		case JLOG_UPDATE:
			strncpy(c, "UPDATE|", op_len);
			break;
		case JLOG_DELETE:
			strncpy(c, "DELETE|", op_len);
			break;
		}

		c += op_len;
		strncpy(c, _msg, len);
		c +=len;
		*c = '\n';
		c++;
		*c = '\0';

		if ((_tp->logflags & JLOG_STDOUT) == JLOG_STDOUT)
			puts(buf);

		if ((_tp->logflags & JLOG_SYSLOG) == JLOG_SYSLOG)
			syslog(LOG_LOCAL6, "%s", buf);

		if(_tp->fp)
		{
			if(!fputs(buf, _tp->fp) )
				fflush(_tp->fp);
		}
	}
}

/**
 * The function is called to create a handle to a db table.
 *
 * On startup, we do not create any of the db handles.
 * Instead it is done on first-use (lazy-initialized) to only create handles to
 * files (db) that we require.
 *
 * There is one db file per opensips table (eg. acc), and they should exist
 * in your DB_PATH (refer to opensipsctlrc) directory.
 *
 * This function does _not_ create the underlying binary db tables.
 * Creating the tables MUST be manually performed before
 * opensips startup by 'opensipsdbctl create'
 *
 * Function returns NULL on error, which will cause opensips to exit.
 *
 */
table_p bdblib_create_table(database_p _db, str *_s)
{

	int rc,i,flags;
	DB *bdb = NULL;
	table_p tp = NULL;
	char tblname[MAX_TABLENAME_SIZE];

	if(!_db || !_db->dbenv)
	{
		LM_ERR("no database_p or dbenv.\n");
		return NULL;
	}

	tp = (table_p)pkg_malloc(sizeof(table_t));
	if(!tp)
	{
		LM_ERR("no private memory for table_t.\n");
		return NULL;
	}

	if ((rc = db_create(&bdb, _db->dbenv, 0)) != 0)
	{
		_db->dbenv->err(_db->dbenv, rc, "database create");
		LM_ERR("error in db_create, bdb error: %s.\n",db_strerror(rc));
		pkg_free(tp);
		return NULL;
	}

	memset(tblname, 0, MAX_TABLENAME_SIZE);
	strncpy(tblname, _s->s, _s->len);

#ifdef BDB_EXTRA_DEBUG
	LM_DBG("CREATE TABLE = %s\n", tblname);
#endif

	flags = DB_THREAD;

	if ((rc = bdb->open(bdb, NULL, tblname, NULL, DB_HASH, flags, 0664)) != 0)
	{
		_db->dbenv->err(_db->dbenv, rc, "DB->open: %s", tblname);
		LM_ERR("bdb open failed: %s.\n",db_strerror(rc));
		pkg_free(tp);
		return NULL;
	}

	if(!lock_init(&tp->sem))
	{
		goto error;
	}

	tp->name.s = (char*)pkg_malloc(_s->len*sizeof(char));
	memcpy(tp->name.s, _s->s, _s->len);
	tp->name.len = _s->len;
	tp->db=bdb;
	tp->ncols=0;
	tp->nkeys=0;
	tp->ro=0;    /*0=ReadWrite ; 1=ReadOnly*/
	tp->ino=0;   /*inode*/
	tp->logflags=0; /*bitmap; 4=Delete, 2=Update, 1=Insert, 0=None*/
	tp->fp=0;
	tp->t=0;

	for(i=0;i<MAX_NUM_COLS;i++)
		tp->colp[i] = NULL;

	/*load metadata; seeded\db_loaded when database are created*/

	/*initialize columns with metadata*/
	rc = load_metadata_columns(tp);
	if(rc!=0)
	{
		LM_ERR("FAILED to load METADATA COLS in table: %s.\n", tblname);
		goto error;
	}

	/*initialize columns default values from metadata*/
	rc = load_metadata_defaults(tp);
	if(rc!=0)
	{
		LM_ERR("FAILED to load METADATA DEFAULTS in table: %s.\n", tblname);
		goto error;
	}

	rc = load_metadata_keys(tp);
	if(rc!=0)
	{
		LM_ERR("FAILED to load METADATA KEYS in table: %s.\n", tblname);
		/*will have problems later figuring column types*/
		goto error;
	}

	/*opened RW by default; Query to set the RO flag */
	rc = load_metadata_readonly(tp);
	if(rc!=0)
	{
		LM_INFO("No METADATA_READONLY in table: %s.\n", tblname);
		/*non-critical; table will default to READWRITE*/
	}

	if(tp->ro)
	{
		/*schema defines this table RO readonly*/
#ifdef BDB_EXTRA_DEBUG
		LM_DBG("TABLE %.*s is changing to READONLY mode\n"
			, tp->name.len, tp->name.s);
#endif

		if ((rc = bdb->close(bdb,0)) != 0)
		{
			_db->dbenv->err(_db->dbenv, rc, "DB->close: %s", tblname);
			LM_ERR("bdb close: %s.\n",db_strerror(rc));
			goto error;
		}

		bdb = NULL;
		if ((rc = db_create(&bdb, _db->dbenv, 0)) != 0)
		{
			_db->dbenv->err(_db->dbenv, rc, "database create");
			LM_ERR("error in db_create.\n");
			goto error;
		}

		flags = DB_THREAD | DB_RDONLY;
		if ((rc = bdb->open(bdb, NULL, tblname, NULL, DB_HASH, flags, 0664)) != 0)
		{
			_db->dbenv->err(_db->dbenv, rc, "DB->open: %s", tblname);
			LM_ERR("bdb open: %s.\n",db_strerror(rc));
			goto error;
		}
		tp->db=bdb;
	}

	/* set the journaling flags; flags indicate which operations
	   need to be journalled. (e.g possible to only journal INSERT.)
	*/
	rc = load_metadata_logflags(tp);
	if(rc!=0)
		LM_INFO("No METADATA_LOGFLAGS in table: %s.\n", tblname);

	if ((tp->logflags & JLOG_FILE) == JLOG_FILE)
		bdblib_create_journal(tp);

	return tp;

error:
	if(tp)
	{
		pkg_free(tp->name.s);
		pkg_free(tp);
	}
	return NULL;
}

int bdblib_create_journal(table_p _tp)
{
	char *s;
	char fn[1024];
	char d[64];
	FILE *fp = NULL;
	struct tm *t;
	int bl;
	database_p _db_p = *_cachedb;
	time_t tim = time(NULL);

	if(! _db_p || ! _tp) return -1;
	if(! _db_parms->log_enable) return 0;
	/* journal filename ; e.g. '/var/opensips/db/location-YYYYMMDDhhmmss.jnl' */
	s=fn;
	strncpy(s, _db_p->name.s, _db_p->name.len);
	s+=_db_p->name.len;

	*s = '/';
	s++;

	strncpy(s, _tp->name.s, _tp->name.len);
	s+=_tp->name.len;

	t = localtime( &tim );
	bl=strftime(d,128,"-%Y%m%d%H%M%S.jnl",t);
	strncpy(s, d, bl);
	s+= bl;
	*s = 0;

	if(_tp->fp)
	{	/* must be rolling. */
		if( fclose(_tp->fp) )
		{	LM_ERR("Failed to Close Log in table: %.*s .\n", _tp->name.len,
			 _tp->name.s);
			return -1;
		}
	}

	if( (fp = fopen(fn, "w")) != NULL )
	{
		_tp->fp = fp;
	}
	else
	{
		LM_ERR("Failed to Open Log in table: %.*s .\n",_tp->name.len, _tp->name.s);
		return -1;
	}

	_tp->t = tim;
	return 0;

}

int load_metadata_columns(table_p _tp)
{
	int ret,n,len;
	char dbuf[MAX_ROW_SIZE];
	char *tmp;
	char *s = NULL;
	char cn[64], ct[16];
	DB *db = NULL;
	DBT key, data;
	column_p col;
	ret = n = len = 0;

	if(!_tp || !_tp->db)
		return -1;

	if(_tp->ncols!=0)
		return 0;

	db = _tp->db;
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	memset(dbuf, 0, MAX_ROW_SIZE);

	key.data = METADATA_COLUMNS;
	key.size = strlen(METADATA_COLUMNS);

	/*memory for the result*/
	data.data = dbuf;
	data.ulen = MAX_ROW_SIZE;
	data.flags = DB_DBT_USERMEM;

	if ((ret = db->get(db, NULL, &key, &data, 0)) != 0)
	{
		db->err(db, ret, "load_metadata_columns DB->get failed");
		LM_ERR("FAILED to find METADATA_COLUMNS in DB \n");
		return -1;
	}


	/* eg: dbuf = "table_name(str) table_version(int)" */

	LM_DBG("Found: [%s]\n",dbuf);

	tmp = dbuf;
	s = strsep(&tmp, " ");
	while(s!=NULL && n<MAX_NUM_COLS)
	{
		/* eg: meta[0]=table_name  meta[1]=str */
		sscanf(s,"%20[^(](%10[^)])[^\n]", cn, ct);

		/* create column*/
		col = (column_p) pkg_malloc(sizeof(column_t));
		if(!col)
		{	LM_ERR("out of private memory \n");
			return -1;
		}

		/* set name*/
		len = strlen( cn );
		col->name.s = (char*)pkg_malloc(len * sizeof(char));
		memcpy(col->name.s, cn, len );
		col->name.len = len;

		/*set column type*/
		if(strncmp(ct, "str", 3)==0)
		{	col->type = DB_STRING;
		}
		else if(strncmp(ct, "int", 3)==0)
		{	col->type = DB_INT;
		}
		else if (strncmp(ct, "number", 6)==0)
		{	col->type = DB_BIGINT;
		}
		else if(strncmp(ct, "double", 6)==0)
		{	col->type = DB_DOUBLE;
		}
		else if(strncmp(ct, "datetime", 8)==0)
		{	col->type = DB_DATETIME;
		}
		else
		{	col->type = DB_STRING;
		}

		col->flag = 0;
		_tp->colp[n] = col;
		n++;
		_tp->ncols++;
		s = strsep(&tmp, " ");
	}

	return 0;
}

int load_metadata_keys(table_p _tp)
{
	int ret,n,ci;
	char dbuf[MAX_ROW_SIZE];
	char *tmp;
	char *s = NULL;
	DB *db = NULL;
	DBT key, data;
	ret = n = ci = 0;

	if(!_tp || !_tp->db)
		return -1;

	db = _tp->db;
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	memset(dbuf, 0, MAX_ROW_SIZE);
	key.data = METADATA_KEY;
	key.size = strlen(METADATA_KEY);
	data.data = dbuf;
	data.ulen = MAX_ROW_SIZE;
	data.flags = DB_DBT_USERMEM;

	if ((ret = db->get(db, NULL, &key, &data, 0)) != 0)
	{
		db->err(db, ret, "load_metadata_keys DB->get failed");
		LM_ERR("FAILED to find METADATA in table \n");
		return ret;
	}

	LM_DBG("Found: [%s]\n",dbuf);

	tmp = dbuf;
	s = strsep(&tmp, " ");
	while(s!=NULL && strlen(s) && n< _tp->ncols)
	{	ret = sscanf(s,"%i", &ci);
		if(ret != 1) return -1;
		if( _tp->colp[ci] )
		{	_tp->colp[ci]->flag = 1;
			_tp->nkeys++;
		}
		n++;
		s = strsep(&tmp, " ");
	}

	return 0;
}


int load_metadata_readonly(table_p _tp)
{
	int i, ret;
	char dbuf[MAX_ROW_SIZE];

	DB *db = NULL;
	DBT key, data;
	i = 0;

	if(!_tp || !_tp->db)
		return -1;

	db = _tp->db;
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	memset(dbuf, 0, MAX_ROW_SIZE);
	key.data = METADATA_READONLY;
	key.size = strlen(METADATA_READONLY);
	data.data = dbuf;
	data.ulen = MAX_ROW_SIZE;
	data.flags = DB_DBT_USERMEM;

	if ((ret = db->get(db, NULL, &key, &data, 0)) != 0)
	{	return ret;
	}

	if( 1 == sscanf(dbuf,"%i", &i) )
		_tp->ro=(i>0)?1:0;

	return 0;
}

int load_metadata_logflags(table_p _tp)
{
	int i, ret;
	char dbuf[MAX_ROW_SIZE];

	DB *db = NULL;
	DBT key, data;
	i = 0;

	if(!_tp || !_tp->db)
		return -1;

	db = _tp->db;
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	memset(dbuf, 0, MAX_ROW_SIZE);
	key.data = METADATA_LOGFLAGS;
	key.size = strlen(METADATA_LOGFLAGS);
	data.data = dbuf;
	data.ulen = MAX_ROW_SIZE;
	data.flags = DB_DBT_USERMEM;

	if ((ret = db->get(db, NULL, &key, &data, 0)) != 0)
	{	return ret;
	}

	if( 1 == sscanf(dbuf,"%i", &i) )
		_tp->logflags=i;

	return 0;
}

int load_metadata_defaults(table_p _tp)
{
	int ret,n,len;
	char dbuf[MAX_ROW_SIZE];
	char * tmp;
	char *s = NULL;
	char cv[512];
	DB *db = NULL;
	DBT key, data;
	column_p col;
	ret = n = len = 0;

	if(!_tp || !_tp->db)
		return -1;

	db = _tp->db;
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	memset(dbuf, 0, MAX_ROW_SIZE);

	key.data = METADATA_DEFAULTS;
	key.size = strlen(METADATA_DEFAULTS);

	/*memory for the result*/
	data.data = dbuf;
	data.ulen = MAX_ROW_SIZE;
	data.flags = DB_DBT_USERMEM;

	if ((ret = db->get(db, NULL, &key, &data, 0)) != 0)
	{
#ifdef BDB_EXTRA_DEBUG
		LM_DBG("NO DEFAULTS ; SETTING ALL columns to NULL! \n" );
#endif

		/*no defaults in DB; make some up.*/
		for(n=0; n<_tp->ncols; n++)
		{
			col = _tp->colp[n];
			if( col )
			{	/*set all columns default value to 'NULL' */
				len = strlen("NULL");
				col->dv.s = (char*)pkg_malloc(len * sizeof(char));
				memcpy(col->dv.s, "NULL", len);
				col->dv.len = len;
			}
		}
		return 0;
	}

	/* use the defaults provided*/

	LM_DBG("Found: [%s]\n",dbuf);

	tmp = dbuf;
	s = strsep(&tmp, DELIM);
	while(s!=NULL && n< _tp->ncols)
	{
		strcpy(cv,s);
		col = _tp->colp[n];
		if( col )
		{	/*set column default*/
			len = strlen(s);
			col->dv.s = (char*)pkg_malloc(len * sizeof(char));
			memcpy(col->dv.s, cv, len);
			col->dv.len = len;
#ifdef BDB_EXTRA_DEBUG
		LM_DBG("COLUMN DEFAULT is %.*s for column[%.*s] \n"
			, col->dv.len , ZSW(col->dv.s)
			, col->name.len , ZSW(col->name.s)
			);
#endif

		}
		n++;
		s = strsep( &tmp, DELIM);
	}

	return 0;
}


/*creates a composite key _k of length _klen from n values of _v;
  provide your own initialized memory for target _k and _klen;
  resulting value: _k = "KEY1 | KEY2"
  ko = key only
*/
int bdblib_valtochar(table_p _tp, int* _lres, char* _k, int* _klen, db_val_t* _v, int _n, int _ko)
{
	char *p;
	char sk[MAX_ROW_SIZE]; // subkey(sk) val
	char* delim = DELIM;
	char* cNULL = "NULL";
	int  len, total, sum;
	int i, j, k;
	p =  _k;
	len = sum = total = 0;
	i = j = k = 0;

	if(!_tp) return -1;
	if(!_v || (_n<1) ) return -1;
	if(!_k || !_klen ) return -1;
	if( *_klen < 1)    return -1;

	memset(sk, 0, MAX_ROW_SIZE);
	total = *_klen;
	*_klen = 0; //sum

	if(! _lres)
	{
#ifdef BDB_EXTRA_DEBUG
		LM_DBG("schema has NOT specified any keys! \n");
#endif

		/* schema has not specified keys
		   just use the provided data in order provided
		*/
		for(i=0;i<_n;i++)
		{	len = total - sum;
			if ( bdb_val2str(&_v[i], sk, &len) != 0 )
			{	LM_ERR("error building composite key \n");
				return -2;
			}

			sum += len;
			if(sum > total)
			{	LM_ERR("Destination buffer too short for subval %s\n",sk);
				return -2;
			}

			/* write sk */
			strncpy(p, sk, len);
			p += len;
			*_klen = sum;

			sum += DELIM_LEN;
			if(sum > total)
			{	LM_ERR("Destination buffer too short for delim \n");
				return -3;
			}

			/* write delim */
			strncpy(p, delim, DELIM_LEN);
			p += DELIM_LEN;
			*_klen = sum;;
		}
		return 0;
	}


	/*
	  schema has specified keys
	  verify all schema keys are provided
	  use 'NULL' for those that are missing.
	*/
	for(i=0; i<_tp->ncols; i++)
	{	/* i indexes columns in schema order */
		if( _ko)
		{	/* keymode; skip over non-key columns */
			if( ! _tp->colp[i]->flag)
				continue;
		}

		for(j=0; j<_n; j++)
		{
			/*
			  j indexes the columns provided in _k
			  which may be less than the total required by
			  the schema. the app does not know the order
			  of the columns in our schema!
			 */
			k = (_lres) ? _lres[j] : j;

			/*
			 * k index will remap back to our schema order; like i
			 */
			if(i == k)
			{
				/*
				 KEY was provided; append to buffer;
				 _k[j] contains a key, but its a key that
				 corresponds to column k of our schema.
				 now we know its a match, and we don't need
				 index k for anything else
				*/
#ifdef BDB_EXTRA_DEBUG
				LM_DBG("KEY PROVIDED[%i]: %.*s.%.*s \n", i
					, _tp->name.len , ZSW(_tp->name.s)
					, _tp->colp[i]->name.len, ZSW(_tp->colp[i]->name.s)
				   );
#endif

				len = total - sum;
				if ( bdb_val2str(&_v[j], sk, &len) != 0)
				{	LM_ERR("Error while converting to str %s\n",sk);
					return -4;
				}

				sum += len;
				if(sum > total)
				{	LM_ERR("Destination buffer too short for subval %s\n",sk);
					return -5;
				}

				strncpy(p, sk, len);
				p += len;
				*_klen = sum;

				sum += DELIM_LEN;
				if(sum > total)
				{	LM_ERR("Destination buffer too short for delim \n");
					return -5;
				}

				/* append delim */
				strncpy(p, delim, DELIM_LEN);
				p += DELIM_LEN;
				*_klen = sum;


				/* take us out of inner for loop
				   and at the end of the outer loop
				   to look for our next schema key
				*/
				goto next;
			}

		}

		/*
		 NO KEY provided; use the column default value (dv)
		     i.e _tp->colp[i]->dv
		*/
#ifdef BDB_EXTRA_DEBUG
		LM_DBG("Missing KEY[%i]: %.*s.%.*s using default [%.*s] \n", i
			, _tp->name.len , ZSW(_tp->name.s)
			, _tp->colp[i]->name.len, ZSW(_tp->colp[i]->name.s)
			, _tp->colp[i]->dv.len , ZSW(_tp->colp[i]->dv.s)
		   );
#endif
		len = _tp->colp[i]->dv.len;
		sum += len;
		if(sum > total)
		{	LM_ERR("Destination buffer too short for subval %s\n",cNULL);
			return -5;
		}

		strncpy(p, _tp->colp[i]->dv.s, len);
		p += len;
		*_klen = sum;

		sum += DELIM_LEN;
		if(sum > total)
		{	LM_ERR("Destination buffer too short for delim \n");
			return -5;
		}

		strncpy(p, delim, DELIM_LEN);
		p += DELIM_LEN;
		*_klen = sum;
next:
		continue;
	}



	return 0;
}


/**
 *
 */
int db_free(database_p _dbp)
{
	tbl_cache_p _tbc = NULL, _tbc0=NULL;
	if(!_dbp)
		return -1;

	_tbc = _dbp->tables;

	while(_tbc)
	{
		_tbc0 = _tbc->next;
		tbl_cache_free(_tbc);
		_tbc = _tbc0;
	}

	if(_dbp->dbenv)
		_dbp->dbenv->close(_dbp->dbenv, 0);

	if(_dbp->name.s)
		pkg_free(_dbp->name.s);

	pkg_free(_dbp);

	return 0;
}


/**
 *
 */
int tbl_cache_free(tbl_cache_p _tbc)
{
	if(!_tbc)
		return -1;

	lock_get(&_tbc->sem);

	if(_tbc->dtp)
		tbl_free(_tbc->dtp);

	lock_destroy(&_tbc->sem);
	pkg_free(_tbc);

	return 0;
}


/**
 * close DB (sync data to disk) and free mem
 */
int tbl_free(table_p _tp)
{	int i;
	if(!_tp)
		return -1;

	if(_tp->db)
		_tp->db->close(_tp->db, 0);

	if(_tp->fp)
		fclose(_tp->fp);

	if(_tp->name.s)
		pkg_free(_tp->name.s);

	for(i=0;i<_tp->ncols;i++)
	{	if(_tp->colp[i])
		{	pkg_free(_tp->colp[i]->name.s);
			pkg_free(_tp->colp[i]->dv.s);
			pkg_free(_tp->colp[i]);
		}
	}

	pkg_free(_tp);
	return 0;
}

int bdblib_recover(table_p _tp, int _rc)
{
	switch(_rc)
	{
		case DB_LOCK_DEADLOCK:
		LM_ERR("DB_LOCK_DEADLOCK detected !!\n");

		case DB_RUNRECOVERY:
		LM_ERR("DB_RUNRECOVERY detected !! \n");
		bdblib_destroy();
		exit(1);
		break;
	}

	return 0;
}