forked from cloudflarearchive/kyotocabinet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kccachedb.h
2514 lines (2502 loc) · 107 KB
/
kccachedb.h
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
/*************************************************************************************************
* Cache hash database
* Copyright (C) 2009-2012 FAL Labs
* Copyright (C) 2013-2017 Cloudflare Inc.
* Copyright (C) 2018-2019 TrustYou GmbH
* This file is part of Kyoto Cabinet.
* 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 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/>.
*************************************************************************************************/
#ifndef _KCCACHEDB_H // duplication check
#define _KCCACHEDB_H
#include <kccommon.h>
#include <kcutil.h>
#include <kcthread.h>
#include <kcfile.h>
#include <kccompress.h>
#include <kccompare.h>
#include <kcmap.h>
#include <kcregex.h>
#include <kcdb.h>
#include <kcplantdb.h>
namespace kyotocabinet // common namespace
{
/**
* On-memory hash database with LRU deletion.
* @note This class is a concrete class to operate a hash database on memory. This class can be
* inherited but overwriting methods is forbidden. Before every database operation, it is
* necessary to call the CacheDB::open method in order to open a database file and connect the
* database object to it. To avoid data missing or corruption, it is important to close every
* database file by the CacheDB::close method when the database is no longer in use. It is
* forbidden for multible database objects in a process to open the same database at the same
* time. It is forbidden to share a database object with child processes.
*/
class CacheDB : public BasicDB
{
friend class PlantDB<CacheDB, BasicDB::TYPEGRASS>;
public:
class Cursor;
private:
struct Record;
struct TranLog;
struct Slot;
class Repeater;
class Setter;
class Remover;
class ScopedVisitor;
/** An alias of list of cursors. */
typedef std::list<Cursor *> CursorList;
/** An alias of list of transaction logs. */
typedef std::list<TranLog> TranLogList;
/** The number of slot tables. */
static const int32_t SLOTNUM = 16;
/** The default bucket number. */
static const size_t DEFBNUM = 1048583LL;
/** The mininum number of buckets to use mmap. */
static const size_t ZMAPBNUM = 32768;
/** The maximum size of each key. */
static const uint32_t KSIZMAX = 0xfffff;
/** The size of the record buffer. */
static const size_t RECBUFSIZ = 48;
/** The size of the opaque buffer. */
static const size_t OPAQUESIZ = 16;
/** The threshold of busy loop and sleep for locking. */
static const uint32_t LOCKBUSYLOOP = 8192;
public:
/**
* Cursor to indicate a record.
*/
class Cursor : public BasicDB::Cursor
{
friend class CacheDB;
public:
/**
* Constructor.
* @param db the container database object.
*/
explicit Cursor ( CacheDB *db ) : db_ ( db ), sidx_ ( -1 ), rec_ ( NULL )
{
_assert_ ( db );
ScopedRWLock lock ( &db_->mlock_, true );
db_->curs_.push_back ( this );
}
/**
* Destructor.
*/
virtual ~Cursor()
{
_assert_ ( true );
if ( !db_ )
{
return;
}
ScopedRWLock lock ( &db_->mlock_, true );
db_->curs_.remove ( this );
}
/**
* Accept a visitor to the current record.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param step true to move the cursor to the next record, or false for no move.
* @return true on success, or false on failure.
* @note The operation for each record is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool accept ( Visitor *visitor, bool writable = true, bool step = false )
{
_assert_ ( visitor );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( writable && ! ( db_->omode_ & OWRITER ) )
{
db_->set_error ( _KCCODELINE_, Error::NOPERM, "permission denied" );
return false;
}
if ( sidx_ < 0 || !rec_ )
{
db_->set_error ( _KCCODELINE_, Error::NOREC, "no record" );
return false;
}
uint32_t rksiz = rec_->ksiz & KSIZMAX;
char *dbuf = ( char * ) rec_ + sizeof ( *rec_ );
const char *rvbuf = dbuf + rksiz;
size_t rvsiz = rec_->vsiz;
char *zbuf = NULL;
size_t zsiz = 0;
if ( db_->comp_ )
{
zbuf = db_->comp_->decompress ( rvbuf, rvsiz, &zsiz );
if ( zbuf )
{
rvbuf = zbuf;
rvsiz = zsiz;
}
}
size_t vsiz;
const char *vbuf = visitor->visit_full ( dbuf, rksiz, rvbuf, rvsiz, &vsiz );
delete[] zbuf;
if ( vbuf == Visitor::REMOVE )
{
uint64_t hash = db_->hash_record ( dbuf, rksiz ) / SLOTNUM;
Slot *slot = db_->slots_ + sidx_;
Repeater repeater ( Visitor::REMOVE, 0 );
db_->accept_impl ( slot, hash, dbuf, rksiz, &repeater, db_->comp_, false );
}
else
if ( vbuf == Visitor::NOP )
{
if ( step )
{
step_impl();
}
}
else
{
uint64_t hash = db_->hash_record ( dbuf, rksiz ) / SLOTNUM;
Slot *slot = db_->slots_ + sidx_;
Repeater repeater ( vbuf, vsiz );
db_->accept_impl ( slot, hash, dbuf, rksiz, &repeater, db_->comp_, false );
if ( step )
{
step_impl();
}
}
return true;
}
/**
* Jump the cursor to the first record for forward scan.
* @return true on success, or false on failure.
*/
bool jump()
{
_assert_ ( true );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
for ( int32_t i = 0; i < SLOTNUM; i++ )
{
Slot *slot = db_->slots_ + i;
if ( slot->first )
{
sidx_ = i;
rec_ = slot->first;
return true;
}
}
db_->set_error ( _KCCODELINE_, Error::NOREC, "no record" );
sidx_ = -1;
rec_ = NULL;
return false;
}
/**
* Jump the cursor to a record for forward scan.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
*/
bool jump ( const char *kbuf, size_t ksiz )
{
_assert_ ( kbuf && ksiz <= MEMMAXSIZ );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( ksiz > KSIZMAX )
{
ksiz = KSIZMAX;
}
uint64_t hash = db_->hash_record ( kbuf, ksiz );
int32_t sidx = hash % SLOTNUM;
hash /= SLOTNUM;
Slot *slot = db_->slots_ + sidx;
size_t bidx = hash % slot->bnum;
Record *rec = slot->buckets[bidx];
Record **entp = slot->buckets + bidx;
uint32_t fhash = db_->fold_hash ( hash ) & ~KSIZMAX;
while ( rec )
{
uint32_t rhash = rec->ksiz & ~KSIZMAX;
uint32_t rksiz = rec->ksiz & KSIZMAX;
if ( fhash > rhash )
{
entp = &rec->left;
rec = rec->left;
}
else
if ( fhash < rhash )
{
entp = &rec->right;
rec = rec->right;
}
else
{
char *dbuf = ( char * ) rec + sizeof ( *rec );
int32_t kcmp = db_->compare_keys ( kbuf, ksiz, dbuf, rksiz );
if ( kcmp < 0 )
{
entp = &rec->left;
rec = rec->left;
}
else
if ( kcmp > 0 )
{
entp = &rec->right;
rec = rec->right;
}
else
{
sidx_ = sidx;
rec_ = rec;
return true;
}
}
}
db_->set_error ( _KCCODELINE_, Error::NOREC, "no record" );
sidx_ = -1;
rec_ = NULL;
return false;
}
/**
* Jump the cursor to a record for forward scan.
* @note Equal to the original Cursor::jump method except that the parameter is std::string.
*/
bool jump ( const std::string &key )
{
_assert_ ( true );
return jump ( key.c_str(), key.size() );
}
/**
* Jump the cursor to the last record for backward scan.
* @note This is a dummy implementation for compatibility.
*/
bool jump_back()
{
_assert_ ( true );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
db_->set_error ( _KCCODELINE_, Error::NOIMPL, "not implemented" );
return false;
}
/**
* Jump the cursor to a record for backward scan.
* @note This is a dummy implementation for compatibility.
*/
bool jump_back ( const char *kbuf, size_t ksiz )
{
_assert_ ( kbuf && ksiz <= MEMMAXSIZ );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
db_->set_error ( _KCCODELINE_, Error::NOIMPL, "not implemented" );
return false;
}
/**
* Jump the cursor to a record for backward scan.
* @note This is a dummy implementation for compatibility.
*/
bool jump_back ( const std::string &key )
{
_assert_ ( true );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
db_->set_error ( _KCCODELINE_, Error::NOIMPL, "not implemented" );
return false;
}
/**
* Step the cursor to the next record.
* @return true on success, or false on failure.
*/
bool step()
{
_assert_ ( true );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( sidx_ < 0 || !rec_ )
{
db_->set_error ( _KCCODELINE_, Error::NOREC, "no record" );
return false;
}
bool err = false;
if ( !step_impl() )
{
err = true;
}
return !err;
}
/**
* Step the cursor to the previous record.
* @note This is a dummy implementation for compatibility.
*/
bool step_back()
{
_assert_ ( true );
ScopedRWLock lock ( &db_->mlock_, true );
if ( db_->omode_ == 0 )
{
db_->set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
db_->set_error ( _KCCODELINE_, Error::NOIMPL, "not implemented" );
return false;
}
/**
* Get the database object.
* @return the database object.
*/
CacheDB *db()
{
_assert_ ( true );
return db_;
}
private:
/**
* Step the cursor to the next record.
* @return true on success, or false on failure.
*/
bool step_impl()
{
_assert_ ( true );
rec_ = rec_->next;
if ( !rec_ )
{
for ( int32_t i = sidx_ + 1; i < SLOTNUM; i++ )
{
Slot *slot = db_->slots_ + i;
if ( slot->first )
{
sidx_ = i;
rec_ = slot->first;
return true;
}
}
db_->set_error ( _KCCODELINE_, Error::NOREC, "no record" );
sidx_ = -1;
rec_ = NULL;
return false;
}
return true;
}
/** Dummy constructor to forbid the use. */
Cursor ( const Cursor & );
/** Dummy Operator to forbid the use. */
Cursor &operator = ( const Cursor & );
/** The inner database. */
CacheDB *db_;
/** The index of the current slot. */
int32_t sidx_;
/** The current record. */
Record *rec_;
};
/**
* Tuning options.
*/
enum Option
{
TSMALL = 1 << 0, ///< dummy for compatibility
TLINEAR = 1 << 1, ///< dummy for compatibility
TCOMPRESS = 1 << 2 ///< compress each record
};
/**
* Status flags.
*/
enum Flag
{
FOPEN = 1 << 0, ///< dummy for compatibility
FFATAL = 1 << 1 ///< dummy for compatibility
};
/**
* Default constructor.
*/
explicit CacheDB() :
mlock_(), flock_(), error_(), logger_ ( NULL ), logkinds_ ( 0 ), mtrigger_ ( NULL ),
omode_ ( 0 ), curs_(), path_ ( "" ), type_ ( TYPECACHE ),
opts_ ( 0 ), bnum_ ( DEFBNUM ), capcnt_ ( -1 ), capsiz_ ( -1 ),
opaque_(), embcomp_ ( ZLIBRAWCOMP ), comp_ ( NULL ), slots_(), rttmode_ ( true ), tran_ ( false )
{
_assert_ ( true );
}
/**
* Destructor.
* @note If the database is not closed, it is closed implicitly.
*/
virtual ~CacheDB()
{
_assert_ ( true );
if ( omode_ != 0 )
{
close();
}
if ( !curs_.empty() )
{
CursorList::const_iterator cit = curs_.begin();
CursorList::const_iterator citend = curs_.end();
while ( cit != citend )
{
Cursor *cur = *cit;
cur->db_ = NULL;
++cit;
}
}
}
/**
* Accept a visitor to a record.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @return true on success, or false on failure.
* @note The operation for each record is performed atomically and other threads accessing the
* same record are blocked. To avoid deadlock, any explicit database operation must not be
* performed in this function.
*/
bool accept ( const char *kbuf, size_t ksiz, Visitor *visitor, bool writable = true )
{
_assert_ ( kbuf && ksiz <= MEMMAXSIZ && visitor );
ScopedRWLock lock ( &mlock_, false );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( writable && ! ( omode_ & OWRITER ) )
{
set_error ( _KCCODELINE_, Error::NOPERM, "permission denied" );
return false;
}
if ( ksiz > KSIZMAX )
{
ksiz = KSIZMAX;
}
uint64_t hash = hash_record ( kbuf, ksiz );
int32_t sidx = hash % SLOTNUM;
hash /= SLOTNUM;
Slot *slot = slots_ + sidx;
slot->lock.lock();
accept_impl ( slot, hash, kbuf, ksiz, visitor, comp_, rttmode_ );
slot->lock.unlock();
return true;
}
/**
* Accept a visitor to multiple records at once.
* @param keys specifies a string vector of the keys.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @return true on success, or false on failure.
* @note The operations for specified records are performed atomically and other threads
* accessing the same records are blocked. To avoid deadlock, any explicit database operation
* must not be performed in this function.
*/
bool accept_bulk ( const std::vector<std::string> &keys, Visitor *visitor,
bool writable = true )
{
_assert_ ( visitor );
ScopedRWLock lock ( &mlock_, false );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( writable && ! ( omode_ & OWRITER ) )
{
set_error ( _KCCODELINE_, Error::NOPERM, "permission denied" );
return false;
}
ScopedVisitor svis ( visitor );
size_t knum = keys.size();
if ( knum < 1 )
{
return true;
}
struct RecordKey
{
const char *kbuf;
size_t ksiz;
uint64_t hash;
int32_t sidx;
};
RecordKey *rkeys = new RecordKey[knum];
std::set<int32_t> sidxs;
for ( size_t i = 0; i < knum; i++ )
{
const std::string &key = keys[i];
RecordKey *rkey = rkeys + i;
rkey->kbuf = key.data();
rkey->ksiz = key.size();
if ( rkey->ksiz > KSIZMAX )
{
rkey->ksiz = KSIZMAX;
}
rkey->hash = hash_record ( rkey->kbuf, rkey->ksiz );
rkey->sidx = rkey->hash % SLOTNUM;
sidxs.insert ( rkey->sidx );
rkey->hash /= SLOTNUM;
}
std::set<int32_t>::iterator sit = sidxs.begin();
std::set<int32_t>::iterator sitend = sidxs.end();
while ( sit != sitend )
{
Slot *slot = slots_ + *sit;
slot->lock.lock();
++sit;
}
for ( size_t i = 0; i < knum; i++ )
{
RecordKey *rkey = rkeys + i;
Slot *slot = slots_ + rkey->sidx;
accept_impl ( slot, rkey->hash, rkey->kbuf, rkey->ksiz, visitor, comp_, rttmode_ );
}
sit = sidxs.begin();
sitend = sidxs.end();
while ( sit != sitend )
{
Slot *slot = slots_ + *sit;
slot->lock.unlock();
++sit;
}
delete[] rkeys;
return true;
}
/**
* Iterate to accept a visitor for each record.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note The whole iteration is performed atomically and other threads are blocked. To avoid
* deadlock, any explicit database operation must not be performed in this function.
*/
bool iterate ( Visitor *visitor, bool writable = true, ProgressChecker *checker = NULL )
{
_assert_ ( visitor );
ScopedRWLock lock ( &mlock_, true );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( writable && ! ( omode_ & OWRITER ) )
{
set_error ( _KCCODELINE_, Error::NOPERM, "permission denied" );
return false;
}
ScopedVisitor svis ( visitor );
int64_t allcnt = count_impl();
if ( checker && !checker->check ( "iterate", "beginning", 0, allcnt ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
int64_t curcnt = 0;
for ( int32_t i = 0; i < SLOTNUM; i++ )
{
Slot *slot = slots_ + i;
Record *rec = slot->first;
while ( rec )
{
Record *next = rec->next;
uint32_t rksiz = rec->ksiz & KSIZMAX;
char *dbuf = ( char * ) rec + sizeof ( *rec );
const char *rvbuf = dbuf + rksiz;
size_t rvsiz = rec->vsiz;
char *zbuf = NULL;
size_t zsiz = 0;
if ( comp_ )
{
zbuf = comp_->decompress ( rvbuf, rvsiz, &zsiz );
if ( zbuf )
{
rvbuf = zbuf;
rvsiz = zsiz;
}
}
size_t vsiz;
const char *vbuf = visitor->visit_full ( dbuf, rksiz, rvbuf, rvsiz, &vsiz );
delete[] zbuf;
if ( vbuf == Visitor::REMOVE )
{
uint64_t hash = hash_record ( dbuf, rksiz ) / SLOTNUM;
Repeater repeater ( Visitor::REMOVE, 0 );
accept_impl ( slot, hash, dbuf, rksiz, &repeater, comp_, false );
}
else
if ( vbuf != Visitor::NOP )
{
uint64_t hash = hash_record ( dbuf, rksiz ) / SLOTNUM;
Repeater repeater ( vbuf, vsiz );
accept_impl ( slot, hash, dbuf, rksiz, &repeater, comp_, false );
}
rec = next;
curcnt++;
if ( checker && !checker->check ( "iterate", "processing", curcnt, allcnt ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
}
}
if ( checker && !checker->check ( "iterate", "ending", -1, allcnt ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
trigger_meta ( MetaTrigger::ITERATE, "iterate" );
return true;
}
/**
* Scan each record in parallel.
* @param visitor a visitor object.
* @param thnum the number of worker threads.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note This function is for reading records and not for updating ones. The return value of
* the visitor is just ignored. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool scan_parallel ( Visitor *visitor, size_t thnum, ProgressChecker *checker = NULL )
{
_assert_ ( visitor && thnum <= MEMMAXSIZ );
ScopedRWLock lock ( &mlock_, false );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
if ( thnum < 1 )
{
thnum = 1;
}
thnum = std::pow ( 2.0, ( int32_t ) ( std::log ( thnum * std::sqrt ( 2.0 ) ) / std::log ( 2.0 ) ) );
if ( thnum > ( size_t ) SLOTNUM )
{
thnum = SLOTNUM;
}
ScopedVisitor svis ( visitor );
int64_t allcnt = count_impl();
if ( checker && !checker->check ( "scan_parallel", "beginning", -1, allcnt ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
class ThreadImpl : public Thread
{
public:
explicit ThreadImpl() :
db_ ( NULL ), visitor_ ( NULL ), checker_ ( NULL ), allcnt_ ( 0 ), slots_(), error_() {}
void init ( CacheDB *db, Visitor *visitor, ProgressChecker *checker, int64_t allcnt )
{
db_ = db;
visitor_ = visitor;
checker_ = checker;
allcnt_ = allcnt;
}
void add_slot ( Slot *slot )
{
slots_.push_back ( slot );
}
const Error &error()
{
return error_;
}
private:
void run()
{
CacheDB *db = db_;
Visitor *visitor = visitor_;
ProgressChecker *checker = checker_;
int64_t allcnt = allcnt_;
Compressor *comp = db->comp_;
std::vector<Slot *>::iterator sit = slots_.begin();
std::vector<Slot *>::iterator sitend = slots_.end();
while ( sit != sitend )
{
Slot *slot = *sit;
Record *rec = slot->first;
while ( rec )
{
Record *next = rec->next;
uint32_t rksiz = rec->ksiz & KSIZMAX;
char *dbuf = ( char * ) rec + sizeof ( *rec );
const char *rvbuf = dbuf + rksiz;
size_t rvsiz = rec->vsiz;
char *zbuf = NULL;
size_t zsiz = 0;
if ( comp )
{
zbuf = comp->decompress ( rvbuf, rvsiz, &zsiz );
if ( zbuf )
{
rvbuf = zbuf;
rvsiz = zsiz;
}
}
size_t vsiz;
visitor->visit_full ( dbuf, rksiz, rvbuf, rvsiz, &vsiz );
delete[] zbuf;
rec = next;
if ( checker && !checker->check ( "scan_parallel", "processing", -1, allcnt ) )
{
db->set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
error_ = db->error();
break;
}
}
++sit;
}
}
CacheDB *db_;
Visitor *visitor_;
ProgressChecker *checker_;
int64_t allcnt_;
std::vector<Slot *> slots_;
Error error_;
};
bool err = false;
bool orttmode = rttmode_;
rttmode_ = false;
ThreadImpl *threads = new ThreadImpl[thnum];
for ( int32_t i = 0; i < SLOTNUM; i++ )
{
ThreadImpl *thread = threads + ( i % thnum );
thread->add_slot ( slots_ + i );
}
for ( size_t i = 0; i < thnum; i++ )
{
ThreadImpl *thread = threads + i;
thread->init ( this, visitor, checker, allcnt );
thread->start();
}
for ( size_t i = 0; i < thnum; i++ )
{
ThreadImpl *thread = threads + i;
thread->join();
if ( thread->error() != Error::SUCCESS )
{
*error_ = thread->error();
err = true;
}
}
delete[] threads;
rttmode_ = orttmode;
if ( err )
{
return false;
}
if ( checker && !checker->check ( "scan_parallel", "ending", -1, allcnt ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
trigger_meta ( MetaTrigger::ITERATE, "scan_parallel" );
return true;
}
/**
* Get the last happened error.
* @return the last happened error.
*/
Error error() const
{
_assert_ ( true );
return error_;
}
/**
* Set the error information.
* @param file the file name of the program source code.
* @param line the line number of the program source code.
* @param func the function name of the program source code.
* @param code an error code.
* @param message a supplement message.
*/
void set_error ( const char *file, int32_t line, const char *func,
Error::Code code, const char *message )
{
_assert_ ( file && line > 0 && func && message );
error_->set ( code, message );
if ( logger_ )
{
Logger::Kind kind = code == Error::BROKEN || code == Error::SYSTEM ?
Logger::ERROR : Logger::INFO;
if ( kind & logkinds_ )
{
report ( file, line, func, kind, "%d: %s: %s", code, Error::codename ( code ), message );
}
}
}
/**
* Open a database file.
* @param path the path of a database file.
* @param mode the connection mode. CacheDB::OWRITER as a writer, CacheDB::OREADER as a
* reader. The following may be added to the writer mode by bitwise-or: CacheDB::OCREATE,
* which means it creates a new database if the file does not exist, CacheDB::OTRUNCATE, which
* means it creates a new database regardless if the file exists, CacheDB::OAUTOTRAN, which
* means each updating operation is performed in implicit transaction, CacheDB::OAUTOSYNC,
* which means each updating operation is followed by implicit synchronization with the file
* system. The following may be added to both of the reader mode and the writer mode by
* bitwise-or: CacheDB::ONOLOCK, which means it opens the database file without file locking,
* CacheDB::OTRYLOCK, which means locking is performed without blocking, CacheDB::ONOREPAIR,
* which means the database file is not repaired implicitly even if file destruction is
* detected.
* @return true on success, or false on failure.
* @note Every opened database must be closed by the CacheDB::close method when it is no
* longer in use. It is not allowed for two or more database objects in the same process to
* keep their connections to the same database file at the same time.
*/
bool open ( const std::string &path, uint32_t mode = OWRITER | OCREATE )
{
_assert_ ( true );
ScopedRWLock lock ( &mlock_, true );
if ( omode_ != 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "already opened" );
return false;
}
report ( _KCCODELINE_, Logger::DEBUG, "opening the database (path=%s)", path.c_str() );
omode_ = mode;
path_.append ( path );
size_t bnum = nearbyprime ( bnum_ / SLOTNUM );
size_t capcnt = capcnt_ > 0 ? capcnt_ / SLOTNUM + 1 : ( 1ULL << ( sizeof ( capcnt ) * 8 - 1 ) );
size_t capsiz = capsiz_ > 0 ? capsiz_ / SLOTNUM + 1 : ( 1ULL << ( sizeof ( capsiz ) * 8 - 1 ) );
if ( capsiz > sizeof ( *this ) / SLOTNUM )
{
capsiz -= sizeof ( *this ) / SLOTNUM;
}
if ( capsiz > bnum * sizeof ( Record * ) )
{
capsiz -= bnum * sizeof ( Record * );
}
for ( int32_t i = 0; i < SLOTNUM; i++ )
{
initialize_slot ( slots_ + i, bnum, capcnt, capsiz );
}
comp_ = ( opts_ & TCOMPRESS ) ? embcomp_ : NULL;
std::memset ( opaque_, 0, sizeof ( opaque_ ) );
trigger_meta ( MetaTrigger::OPEN, "open" );
return true;
}
/**
* Close the database file.
* @return true on success, or false on failure.
*/
bool close()
{
_assert_ ( true );
ScopedRWLock lock ( &mlock_, true );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
report ( _KCCODELINE_, Logger::DEBUG, "closing the database (path=%s)", path_.c_str() );
tran_ = false;
for ( int32_t i = SLOTNUM - 1; i >= 0; i-- )
{
destroy_slot ( slots_ + i );
}
path_.clear();
omode_ = 0;
trigger_meta ( MetaTrigger::CLOSE, "close" );
return true;
}
/**
* Synchronize updated contents with the file and the device.
* @param hard true for physical synchronization with the device, or false for logical
* synchronization with the file system.
* @param proc a postprocessor object. If it is NULL, no postprocessing is performed.
* @param checker a progress checker object. If it is NULL, no checking is performed.
* @return true on success, or false on failure.
* @note The operation of the postprocessor is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool synchronize ( bool hard = false, FileProcessor *proc = NULL,
ProgressChecker *checker = NULL )
{
_assert_ ( true );
ScopedRWLock lock ( &mlock_, false );
if ( omode_ == 0 )
{
set_error ( _KCCODELINE_, Error::INVALID, "not opened" );
return false;
}
bool err = false;
if ( ( omode_ & OWRITER ) && checker &&
!checker->check ( "synchronize", "nothing to be synchronized", -1, -1 ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
if ( proc )
{
if ( checker && !checker->check ( "synchronize", "running the post processor", -1, -1 ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "checker failed" );
return false;
}
if ( !proc->process ( path_, count_impl(), size_impl() ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "postprocessing failed" );
err = true;
}
}
trigger_meta ( MetaTrigger::SYNCHRONIZE, "synchronize" );
return !err;
}
/**
* Occupy database by locking and do something meanwhile.
* @param writable true to use writer lock, or false to use reader lock.
* @param proc a processor object. If it is NULL, no processing is performed.
* @return true on success, or false on failure.
* @note The operation of the processor is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool occupy ( bool writable = true, FileProcessor *proc = NULL )
{
_assert_ ( true );
ScopedRWLock lock ( &mlock_, writable );
bool err = false;
if ( proc && !proc->process ( path_, count_impl(), size_impl() ) )
{
set_error ( _KCCODELINE_, Error::LOGIC, "processing failed" );
err = true;
}
trigger_meta ( MetaTrigger::OCCUPY, "occupy" );
return !err;