/
bitcask.erl
1642 lines (1409 loc) · 60.8 KB
/
bitcask.erl
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
%% -------------------------------------------------------------------
%%
%% bitcask: Eric Brewer-inspired key/value store
%%
%% Copyright (c) 2010 Basho Technologies, Inc. All Rights Reserved.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(bitcask).
-export([open/1, open/2,
close/1,
close_write_file/1,
get/2,
put/3,
delete/2,
sync/1,
list_keys/1,
fold_keys/3, fold_keys/5,
fold/3, fold/5,
merge/1, merge/2, merge/3,
needs_merge/1,
status/1]).
-export([get_opt/2,
get_filestate/2]).
-include("bitcask.hrl").
-ifdef(PULSE).
-compile({parse_transform, pulse_instrument}).
-compile(export_all).
-endif.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include_lib("kernel/include/file.hrl").
-endif.
%% @type bc_state().
-record(bc_state, {dirname,
write_file, % File for writing
write_lock, % Reference to write lock
read_files, % Files opened for reading
max_file_size, % Max. size of a written file
opts, % Original options used to open the bitcask
keydir}). % Key directory
-record(mstate, { dirname,
merge_lock,
max_file_size,
input_files,
out_file,
merged_files,
partial,
live_keydir :: reference(),
hint_keydir,
del_keydir,
expiry_time,
opts }).
%% A bitcask is a directory containing:
%% * One or more data files - {integer_timestamp}.bitcask.data
%% * A write lock - bitcask.write.lock (Optional)
%% * A merge lock - bitcask.merge.lock (Optional)
%% @doc Open a new or existing bitcask datastore for read-only access.
-spec open(Dirname::string()) -> reference() | {error, timeout}.
open(Dirname) ->
open(Dirname, []).
%% @doc Open a new or existing bitcask datastore with additional options.
-spec open(Dirname::string(), Opts::[_]) -> reference() | {error, timeout}.
open(Dirname, Opts) ->
%% Make sure bitcask app is started so we can pull defaults from env
ok = start_app(),
%% Make sure the directory exists
ok = filelib:ensure_dir(filename:join(Dirname, "bitcask")),
%% If the read_write option is set, attempt to release any stale write lock.
%% Do this first to avoid unnecessary processing of files for reading.
WritingFile = case proplists:get_bool(read_write, Opts) of
true ->
bitcask_lockops:delete_stale_lock(write, Dirname),
fresh;
false -> undefined
end,
%% Get the max file size parameter from opts
MaxFileSize = get_opt(max_file_size, Opts),
%% Get the number of seconds we are willing to wait for the keydir init to timeout
WaitTime = timer:seconds(get_opt(open_timeout, Opts)),
%% Loop and wait for the keydir to come available.
case init_keydir(Dirname, WaitTime) of
{ok, KeyDir, ReadFiles} ->
%% Ensure that expiry_secs is in Opts and not just application env
ExpOpts = [{expiry_secs,get_opt(expiry_secs,Opts)}|Opts],
Ref = make_ref(),
erlang:put(Ref, #bc_state {dirname = Dirname,
read_files = ReadFiles,
write_file = WritingFile, % <fd>|undefined|fresh
write_lock = undefined,
max_file_size = MaxFileSize,
opts = ExpOpts,
keydir = KeyDir}),
Ref;
{error, Reason} ->
{error, Reason}
end.
%% @doc Close a bitcask data store and flush any pending writes to disk.
-spec close(reference()) -> ok.
close(Ref) ->
State = get_state(Ref),
erlang:erase(Ref),
%% Manually release the keydir. If, for some reason, this failed GC would
%% still get the job done.
bitcask_nifs:keydir_release(State#bc_state.keydir),
%% Clean up all the reading files
[ok = bitcask_fileops:close(F) || F <- State#bc_state.read_files],
%% Cleanup the write file and associated lock
case State#bc_state.write_file of
undefined ->
ok;
fresh ->
ok;
WriteFile ->
bitcask_fileops:close_for_writing(WriteFile),
ok = bitcask_lockops:release(State#bc_state.write_lock)
end.
%% @doc Close the currently active writing file; mostly for testing purposes
close_write_file(Ref) ->
#bc_state { write_file = WriteFile} = State = get_state(Ref),
case WriteFile of
undefined ->
ok;
fresh ->
ok;
_ ->
LastWriteFile = bitcask_fileops:close_for_writing(WriteFile),
ok = bitcask_lockops:release(State#bc_state.write_lock),
S2 = State#bc_state { write_file = fresh,
read_files = [LastWriteFile | State#bc_state.read_files]},
put_state(Ref, S2)
end.
%% @doc Retrieve a value by key from a bitcask datastore.
-spec get(reference(), binary()) ->
not_found | {ok, Value::binary()} | {error, Err::term()}.
get(Ref, Key) ->
get(Ref, Key, 2).
-spec get(reference(), binary(), integer()) ->
not_found | {ok, Value::binary()} | {error, Err::term()}.
get(_Ref, _Key, 0) -> {error, nofile};
get(Ref, Key, TryNum) ->
State = get_state(Ref),
case bitcask_nifs:keydir_get(State#bc_state.keydir, Key) of
not_found ->
not_found;
E when is_record(E, bitcask_entry) ->
case E#bitcask_entry.tstamp < expiry_time(State#bc_state.opts) of
true ->
%% Expired entry; remove from keydir and free up memory
ok = bitcask_nifs:keydir_remove(State#bc_state.keydir, Key),
not_found;
false ->
%% HACK: Use a fully-qualified call to get_filestate/2 so that
%% we can intercept calls w/ Pulse tests.
case ?MODULE:get_filestate(E#bitcask_entry.file_id, State) of
{error, enoent} ->
%% merging deleted file between keydir_get and here
get(Ref, Key, TryNum-1);
{Filestate, S2} ->
put_state(Ref, S2),
case bitcask_fileops:read(Filestate,
E#bitcask_entry.offset,
E#bitcask_entry.total_sz) of
{ok, _Key, ?TOMBSTONE} ->
not_found;
{ok, _Key, Value} ->
{ok, Value};
{error, eof} ->
not_found;
{error, _} = Err ->
Err
end
end
end
end.
%% @doc Store a key and value in a bitcase datastore.
-spec put(reference(), Key::binary(), Value::binary()) -> ok.
put(Ref, Key, Value) ->
#bc_state { write_file = WriteFile } = State = get_state(Ref),
%% Make sure we have a file open to write
case WriteFile of
undefined ->
throw({error, read_only});
_ ->
ok
end,
{Ret, State1} = do_put(Key, Value, State, 2, undefined),
put_state(Ref, State1),
Ret.
%% @doc Delete a key from a bitcask datastore.
-spec delete(reference(), Key::binary()) -> ok.
delete(Ref, Key) ->
put(Ref, Key, ?TOMBSTONE),
ok = bitcask_nifs:keydir_remove((get_state(Ref))#bc_state.keydir, Key).
%% @doc Force any writes to sync to disk.
-spec sync(reference()) -> ok.
sync(Ref) ->
State = get_state(Ref),
case (State#bc_state.write_file) of
undefined ->
ok;
fresh ->
ok;
File ->
ok = bitcask_fileops:sync(File)
end.
%% @doc List all keys in a bitcask datastore.
-spec list_keys(reference()) -> [Key::binary()] | {error, any()}.
list_keys(Ref) ->
fold_keys(Ref, fun(#bitcask_entry{key=K},Acc) -> [K|Acc] end, []).
%% @doc Fold over all keys in a bitcask datastore.
%% Must be able to understand the bitcask_entry record form.
-spec fold_keys(reference(), Fun::fun(), Acc::term()) ->
term() | {error, any()}.
fold_keys(Ref, Fun, Acc0) ->
State = get_state(Ref),
MaxAge = get_opt(max_fold_age, State#bc_state.opts) * 1000, % convert from ms to us
MaxPuts = get_opt(max_fold_puts, State#bc_state.opts),
fold_keys(Ref, Fun, Acc0, MaxAge, MaxPuts).
%% @doc Fold over all keys in a bitcask datastore with limits on how out of date
%% the keydir is allowed to be.
%% Must be able to understand the bitcask_entry record form.
-spec fold_keys(reference(), Fun::fun(), Acc::term(), non_neg_integer() | undefined,
non_neg_integer() | undefined) ->
term() | {error, any()}.
fold_keys(Ref, Fun, Acc0, MaxAge, MaxPut) ->
%% Fun should be of the form F(#bitcask_entry, A) -> A
ExpiryTime = expiry_time((get_state(Ref))#bc_state.opts),
RealFun = fun(BCEntry, Acc) ->
Key = BCEntry#bitcask_entry.key,
case BCEntry#bitcask_entry.tstamp < ExpiryTime of
true ->
Acc;
false ->
TSize = size(?TOMBSTONE),
case BCEntry#bitcask_entry.total_sz -
(?HEADER_SIZE + size(Key)) of
TSize -> % might be a deleted record, so check
case ?MODULE:get(Ref, Key) of
not_found -> Acc;
_ -> Fun(BCEntry, Acc)
end;
_ ->
Fun(BCEntry, Acc)
end
end
end,
bitcask_nifs:keydir_fold((get_state(Ref))#bc_state.keydir, RealFun, Acc0, MaxAge, MaxPut).
%% @doc fold over all K/V pairs in a bitcask datastore.
%% Fun is expected to take F(K,V,Acc0) -> Acc
-spec fold(reference(), fun((binary(), binary(), any()) -> any()), any()) -> any() | {error, any()}.
fold(Ref, Fun, Acc0) ->
State = get_state(Ref),
MaxAge = get_opt(max_fold_age, State#bc_state.opts) * 1000, % convert from ms to us
MaxPuts = get_opt(max_fold_puts, State#bc_state.opts),
fold(Ref, Fun, Acc0, MaxAge, MaxPuts).
%% @doc fold over all K/V pairs in a bitcask datastore specifying max age/updates of
%% the frozen keystore.
%% Fun is expected to take F(K,V,Acc0) -> Acc
-spec fold(reference(), fun((binary(), binary(), any()) -> any()), any(),
non_neg_integer() | undefined, non_neg_integer() | undefined) ->
any() | {error, any()}.
fold(Ref, Fun, Acc0, MaxAge, MaxPut) ->
State = get_state(Ref),
FrozenFun =
fun() ->
case open_fold_files(State#bc_state.dirname, 3) of
{ok, Files} ->
ExpiryTime = expiry_time(State#bc_state.opts),
SubFun = fun(K,V,TStamp,{_FN,FTS,Offset,_Sz},Acc) ->
case (TStamp < ExpiryTime) of
true ->
Acc;
false ->
case bitcask_nifs:keydir_get(
State#bc_state.keydir, K) of
not_found ->
Acc;
E when is_record(E, bitcask_entry) ->
case
Offset =:= E#bitcask_entry.offset
andalso
TStamp =:= E#bitcask_entry.tstamp
andalso
FTS =:= E#bitcask_entry.file_id of
false ->
Acc;
true ->
case V =:= ?TOMBSTONE of
true ->
Acc;
false ->
Fun(K,V,Acc)
end
end
end
end
end,
subfold(SubFun,Files,Acc0);
{error, Reason} ->
{error, Reason}
end
end,
KeyDir = State#bc_state.keydir,
bitcask_nifs:keydir_frozen(KeyDir, FrozenFun, MaxAge, MaxPut).
%%
%% Get a list of readable files and attempt to open them for a fold. If we can't
%% open any one of the files, get a fresh list of files and try again.
%%
open_fold_files(_Dirname, 0) ->
{error, max_retries_exceeded_for_fold};
open_fold_files(Dirname, Count) ->
Filenames = list_data_files(Dirname, undefined, undefined),
case open_files(Filenames, []) of
{ok, Files} ->
{ok, Files};
error ->
open_fold_files(Dirname, Count-1)
end.
%%
%% Open a list of filenames; if any one of them fails to open, error out.
%%
open_files([], Acc) ->
{ok, lists:reverse(Acc)};
open_files([Filename | Rest], Acc) ->
case bitcask_fileops:open_file(Filename) of
{ok, Fd} ->
open_files(Rest, [Fd | Acc]);
{error, _} ->
[bitcask_fileops:close(Fd) || Fd <- Acc],
error
end.
%%
%% Apply fold function to a single bitcask file; results are accumulated in
%% Acc
%%
subfold(_SubFun,[],Acc) ->
Acc;
subfold(SubFun,[FD | Rest],Acc0) ->
Acc = bitcask_fileops:fold(FD, SubFun, Acc0),
bitcask_fileops:close(FD),
subfold(SubFun,Rest,Acc).
%% @doc Merge several data files within a bitcask datastore
%% into a more compact form.
-spec merge(Dirname::string()) -> ok.
merge(Dirname) ->
merge(Dirname, [], readable_files(Dirname)).
%% @doc Merge several data files within a bitcask datastore
%% into a more compact form.
-spec merge(Dirname::string(), Opts::[_]) -> ok.
merge(Dirname, Opts) ->
merge(Dirname, Opts, readable_files(Dirname)).
%% @doc Merge several data files within a bitcask datastore
%% into a more compact form.
-spec merge(Dirname::string(), Opts::[_], FilesToMerge::[string()]) -> ok.
merge(_Dirname, _Opts, []) ->
ok;
merge(Dirname, Opts, FilesToMerge0) ->
%% Make sure bitcask app is started so we can pull defaults from env
ok = start_app(),
%% Filter the files to merge and ensure that they all exist. It's
%% possible in some circumstances that we'll get an out-of-date
%% list of files.
FilesToMerge = [F || F <- FilesToMerge0,
filelib:is_file(F)],
merge1(Dirname, Opts, FilesToMerge).
%% Inner merge function, assumes that bitcask is running and all files exist.
merge1(_Dirname, _Opts, []) ->
ok;
merge1(Dirname, Opts, FilesToMerge) ->
%% Test to see if this is a complete or partial merge
Partial = not(lists:usort(readable_files(Dirname)) ==
lists:usort(FilesToMerge)),
%% Try to lock for merging
case bitcask_lockops:acquire(merge, Dirname) of
{ok, Lock} ->
ok;
{error, Reason} ->
Lock = undefined,
throw({error, {merge_locked, Reason, Dirname}})
end,
%% Get the live keydir
case bitcask_nifs:keydir_new(Dirname) of
{ready, LiveKeyDir} ->
%% Simplest case; a key dir is already available and
%% loaded. Go ahead and open just the files we wish to
%% merge
InFiles = [begin
{ok, Fstate} = bitcask_fileops:open_file(F),
Fstate
end
|| F <- FilesToMerge];
{not_ready, LiveKeyDir} ->
%% Live keydir is newly created. We need to go ahead and
%% load all available data into the keydir in case another
%% reader/writer comes along in the same VM. Note that we
%% won't necessarily merge all these files.
AllFiles = scan_key_files(readable_files(Dirname), LiveKeyDir, []),
%% Partition all files to files we'll merge and files we
%% won't (so that we can close those extra files once
%% they've been loaded into the keydir)
P = fun(F) ->
lists:member(bitcask_fileops:filename(F), FilesToMerge)
end,
{InFiles, UnusedFiles} = lists:partition(P, AllFiles),
%% Close the unused files
[bitcask_fileops:close(U) || U <- UnusedFiles],
bitcask_nifs:keydir_mark_ready(LiveKeyDir);
{error, not_ready} ->
%% Someone else is loading the keydir. We'll bail here and
%% try again later.
% Make erlc happy w/ non-local exit
LiveKeyDir = undefined, InFiles = [],
throw({error, not_ready})
end,
%% Setup our first output merge file and update the merge lock accordingly
{ok, Outfile} = bitcask_fileops:create_file(Dirname, Opts),
ok = bitcask_lockops:write_activefile(
Lock, bitcask_fileops:filename(Outfile)),
%% Initialize the other keydirs we need.
{ok, DelKeyDir} = bitcask_nifs:keydir_new(),
%% Initialize our state for the merge
State = #mstate { dirname = Dirname,
merge_lock = Lock,
max_file_size = get_opt(max_file_size, Opts),
input_files = InFiles,
out_file = Outfile,
merged_files = [],
partial = Partial,
live_keydir = LiveKeyDir,
del_keydir = DelKeyDir,
expiry_time = expiry_time(Opts),
opts = Opts },
%% Finally, start the merge process
State1 = merge_files(State),
%% Make sure to close the final output file
ok = bitcask_fileops:sync(State1#mstate.out_file),
ok = bitcask_fileops:close(State1#mstate.out_file),
%% Explicitly release our keydirs instead of waiting for GC
bitcask_nifs:keydir_release(LiveKeyDir),
bitcask_nifs:keydir_release(DelKeyDir),
%% Cleanup the original input files and release our lock
[begin
bitcask_fileops:delete(F),
bitcask_fileops:close(F)
end || F <- State#mstate.input_files],
ok = bitcask_lockops:release(Lock).
-spec needs_merge(reference()) -> {true, [string()]} | false.
needs_merge(Ref) ->
State = get_state(Ref),
{_KeyCount, Summary} = summary_info(Ref),
%% Review all the files we currently have open in read_files and
%% see if any no longer exist by name (i.e. have been deleted by
%% previous merges). Close these files so that we don't leak
%% file descriptors.
P = fun(F) ->
filelib:is_file(bitcask_fileops:filename(F))
end,
{LiveFiles, DeadFiles} = lists:partition(P, State#bc_state.read_files),
%% Close the dead files
[bitcask_fileops:close(F) || F <- DeadFiles],
%% Update state with live files
put_state(Ref, State#bc_state { read_files = LiveFiles }),
%% Triggers that would require a merge:
%%
%% frag_merge_trigger - Any file exceeds this % fragmentation
%% dead_bytes_merge_trigger - Any file has more than this # of dead bytes
%% expiry_secs - Any file has an expired key
%%
FragTrigger = get_opt(frag_merge_trigger, State#bc_state.opts),
DeadBytesTrigger = get_opt(dead_bytes_merge_trigger, State#bc_state.opts),
ExpirationTime = expiry_time(State#bc_state.opts),
NeedsMerge = lists:any(fun(F) ->
(F#file_status.fragmented >= FragTrigger)
or (F#file_status.dead_bytes >= DeadBytesTrigger)
or (F#file_status.oldest_tstamp < ExpirationTime)
end, Summary),
case NeedsMerge of
true ->
%% Build a list of threshold checks; a file which meets ANY
%% of these will be merged
%%
%% frag_threshold - At least this % fragmented
%% dead_bytes_threshold - At least this # of dead bytes
%% small_file_threshold - Any file < this # of bytes
%% expiry_secs - Any file has a expired key
%%
Thresholds = [frag_threshold(State#bc_state.opts),
dead_bytes_threshold(State#bc_state.opts),
small_file_threshold(State#bc_state.opts),
expired_threshold(ExpirationTime)],
%% For each file, apply the threshold checks and return a list
%% of failed threshold checks
CheckFile = fun(F) ->
{F#file_status.filename, lists:flatten([T(F) || T <- Thresholds])}
end,
MergableFiles = [{N, R} || {N, R} <- [CheckFile(F) || F <- Summary],
R /= []],
%% Log the reasons for needing a merge, if so configured
%% TODO: At some point we may want to change this API to let the caller
%% recv this information and decide if they want it
case get_opt(log_needs_merge, State#bc_state.opts) of
true ->
error_logger:info_msg("~p needs_merge: ~p\n",
[State#bc_state.dirname, MergableFiles]);
_ ->
ok
end,
FileNames = [Filename || {Filename, _Reasons} <- MergableFiles],
{true, FileNames};
false ->
false
end.
frag_threshold(Opts) ->
FragThreshold = get_opt(frag_threshold, Opts),
fun(F) ->
if F#file_status.fragmented >= FragThreshold ->
[{fragmented, F#file_status.fragmented}];
true ->
[]
end
end.
dead_bytes_threshold(Opts) ->
DeadBytesThreshold = get_opt(dead_bytes_threshold, Opts),
fun(F) ->
if F#file_status.dead_bytes >= DeadBytesThreshold ->
[{dead_bytes, F#file_status.dead_bytes}];
true ->
[]
end
end.
small_file_threshold(Opts) ->
%% We need to do a special check on small_file_threshold for non-integer
%% values since it is using a less-than check. Other thresholds typically
%% do a greater-than check and can take advantage of fact that integers
%% are always greater than an atom.
case get_opt(small_file_threshold, Opts) of
Threshold when is_integer(Threshold) ->
fun(F) ->
if F#file_status.total_bytes < Threshold ->
[{small_file, F#file_status.total_bytes}];
true ->
[]
end
end;
disabled ->
fun(_F) -> [] end
end.
expired_threshold(Cutoff) ->
fun(F) ->
if F#file_status.oldest_tstamp < Cutoff ->
[{oldest_tstamp, F#file_status.oldest_tstamp, Cutoff}];
true ->
[]
end
end.
-spec status(reference()) -> {integer(), [{string(), integer(), integer(), integer()}]}.
status(Ref) ->
%% Rewrite the new, record-style status from status_info into a backwards-compatible
%% call.
%% TODO: Next major revision should remove this variation on status
{KeyCount, Summary} = summary_info(Ref),
{KeyCount, [{F#file_status.filename, F#file_status.fragmented,
F#file_status.dead_bytes, F#file_status.total_bytes} || F <- Summary]}.
-spec summary_info(reference()) -> {integer(), [#file_status{}]}.
summary_info(Ref) ->
State = get_state(Ref),
%% Pull current info for the bitcask. In particular, we want
%% the file stats so we can determine how much fragmentation
%% is present
%%
%% Fstat has form: [{FileId, LiveCount, TotalCount, LiveBytes, TotalBytes, OldestTstamp}]
%% and is only an estimate/snapshot.
{KeyCount, _KeyBytes, Fstats} = bitcask_nifs:keydir_info(
State#bc_state.keydir),
%% We want to ignore the file currently being written when
%% considering status!
case bitcask_lockops:read_activefile(write, State#bc_state.dirname) of
undefined ->
WritingFileId = undefined;
Filename ->
WritingFileId = bitcask_fileops:file_tstamp(Filename)
end,
%% Convert fstats list into a list of #file_status
%%
%% Note that we also, filter the WritingFileId from any further
%% consideration.
Summary0 = [summarize(State#bc_state.dirname, S) ||
S <- Fstats, element(1, S) /= WritingFileId],
%% Remove any files that don't exist from the initial summary
Summary = lists:keysort(1, [S || S <- Summary0,
filelib:is_file(element(2, S))]),
{KeyCount, Summary}.
%% ===================================================================
%% Internal functions
%% ===================================================================
summarize(Dirname, {FileId, LiveCount, TotalCount, LiveBytes, TotalBytes, OldestTstamp}) ->
#file_status { filename = bitcask_fileops:mk_filename(Dirname, FileId),
fragmented = trunc((1 - LiveCount/TotalCount) * 100),
dead_bytes = TotalBytes - LiveBytes,
total_bytes = TotalBytes,
oldest_tstamp = OldestTstamp }.
expiry_time(Opts) ->
ExpirySecs = get_opt(expiry_secs, Opts),
case ExpirySecs > 0 of
true -> bitcask_time:tstamp() - ExpirySecs;
false -> 0
end.
start_app() ->
case application:start(?MODULE) of
ok ->
ok;
{error, {already_started, ?MODULE}} ->
ok;
{error, Reason} ->
{error, Reason}
end.
get_state(Ref) ->
case erlang:get(Ref) of
S when is_record(S, bc_state) ->
S;
undefined ->
throw({error, {invalid_ref, Ref}})
end.
get_opt(Key, Opts) ->
case proplists:get_value(Key, Opts) of
undefined ->
case application:get_env(?MODULE, Key) of
{ok, Value} -> Value;
undefined -> undefined
end;
Value ->
Value
end.
put_state(Ref, State) ->
erlang:put(Ref, State).
reverse_sort(L) ->
lists:reverse(lists:sort(L)).
scan_key_files([], _KeyDir, Acc) ->
Acc;
scan_key_files([Filename | Rest], KeyDir, Acc) ->
{ok, File} = bitcask_fileops:open_file(Filename),
F = fun(K, Tstamp, {Offset, TotalSz}, _) ->
bitcask_nifs:keydir_put(KeyDir,
K,
bitcask_fileops:file_tstamp(File),
TotalSz,
Offset,
Tstamp)
end,
bitcask_fileops:fold_keys(File, F, undefined, recovery),
scan_key_files(Rest, KeyDir, [File | Acc]).
%%
%% Initialize a keydir for a given directory.
%%
init_keydir(Dirname, WaitTime) ->
%% Get the named keydir for this directory. If we get it and it's already
%% marked as ready, that indicates another caller has already loaded
%% all the data from disk and we can short-circuit scanning all the files.
case bitcask_nifs:keydir_new(Dirname) of
{ready, KeyDir} ->
%% A keydir already exists, nothing more to do here. We'll lazy
%% open files as needed.
{ok, KeyDir, []};
{not_ready, KeyDir} ->
%% We've just created a new named keydir, so we need to load up all
%% the data from disk. Build a list of all the bitcask data files
%% and sort it in descending order (newest->oldest).
SortedFiles = readable_files(Dirname),
ReadFiles = scan_key_files(SortedFiles, KeyDir, []),
%% Now that we loaded all the data, mark the keydir as ready
%% so other callers can use it
ok = bitcask_nifs:keydir_mark_ready(KeyDir),
{ok, KeyDir, ReadFiles};
{error, not_ready} ->
timer:sleep(100),
case WaitTime of
Value when is_integer(Value), Value =< 0 -> %% avoids 'infinity'!
{error, timeout};
_ ->
init_keydir(Dirname, WaitTime - 100)
end
end.
get_filestate(FileId,
State=#bc_state{ dirname = Dirname, read_files = ReadFiles }) ->
case lists:keysearch(FileId, #filestate.tstamp, ReadFiles) of
{value, Filestate} ->
{Filestate, State};
false ->
Fname = bitcask_fileops:mk_filename(Dirname, FileId),
case bitcask_fileops:open_file(Fname) of
{error,enoent} ->
%% merge removed the file since the keydir_get
{error, enoent};
{ok, Filestate} ->
{Filestate, State#bc_state{read_files =
[Filestate | State#bc_state.read_files]}}
end
end.
list_data_files(Dirname, WritingFile, Mergingfile) ->
%% Get list of {tstamp, filename} for all files in the directory then
%% reverse sort that list and extract the fully-qualified filename.
Files = bitcask_fileops:data_file_tstamps(Dirname),
[F || {_Tstamp, F} <- reverse_sort(Files),
F /= WritingFile,
F /= Mergingfile].
merge_files(#mstate { input_files = [] } = State) ->
State;
merge_files(#mstate { input_files = [File | Rest]} = State) ->
FileId = bitcask_fileops:file_tstamp(File),
F = fun(K, V, Tstamp, Pos, State0) ->
merge_single_entry(K, V, Tstamp, FileId, Pos, State0)
end,
State1 = bitcask_fileops:fold(File, F, State),
ok = bitcask_fileops:close(File),
merge_files(State1#mstate { input_files = Rest }).
merge_single_entry(K, V, Tstamp, FileId, {_, _, Offset, _} = Pos, State) ->
case out_of_date(K, Tstamp, FileId, Pos, State#mstate.expiry_time, false,
[State#mstate.live_keydir, State#mstate.del_keydir]) of
true ->
bitcask_nifs:keydir_remove(State#mstate.live_keydir, K,
Tstamp, FileId, Offset),
State;
false ->
case (V =:= ?TOMBSTONE) of
true ->
ok = bitcask_nifs:keydir_put(State#mstate.del_keydir, K,
FileId, 0, Offset, Tstamp),
%% Use the conditional remove on the live
%% keydir. We only want to actually remove
%% whatever is in the live keydir IIF the
%% tstamp/fileid we have matches the current
%% entry.
bitcask_nifs:keydir_remove(State#mstate.live_keydir, K,
Tstamp, FileId, Offset),
case State#mstate.partial of
true -> inner_merge_write(K, V, Tstamp, State);
false -> State
end;
false ->
ok = bitcask_nifs:keydir_remove(State#mstate.del_keydir, K),
inner_merge_write(K, V, Tstamp, State)
end
end.
-spec inner_merge_write(binary(), binary(), integer(), #mstate{}) -> #mstate{}.
inner_merge_write(K, V, Tstamp, State) ->
%% write a single item while inside the merge process
%% See if it's time to rotate to the next file
State1 =
case bitcask_fileops:check_write(State#mstate.out_file,
K, V, State#mstate.max_file_size) of
wrap ->
%% Close the current output file
ok = bitcask_fileops:sync(State#mstate.out_file),
ok = bitcask_fileops:close(State#mstate.out_file),
%% Start our next file and update state
{ok, NewFile} = bitcask_fileops:create_file(
State#mstate.dirname,
State#mstate.opts),
NewFileName = bitcask_fileops:filename(NewFile),
ok = bitcask_lockops:write_activefile(
State#mstate.merge_lock,
NewFileName),
State#mstate { out_file = NewFile };
ok ->
State
end,
{ok, Outfile, Offset, Size} =
bitcask_fileops:write(State1#mstate.out_file,
K, V, Tstamp),
%% Update live keydir for the current out
%% file. It's possible that this is a noop, as
%% someone else may have written a newer value
%% whilst we were processing.
bitcask_nifs:keydir_put(
State#mstate.live_keydir, K,
bitcask_fileops:file_tstamp(Outfile),
Size, Offset, Tstamp),
State1#mstate { out_file = Outfile }.
out_of_date(_Key, _Tstamp, _FileId, _Pos, _ExpiryTime, EverFound, []) ->
%% if we ever found it, and non of the entries were out of date,
%% then it's not out of date
EverFound == false;
out_of_date(_Key, Tstamp, _FileId, _Pos, ExpiryTime, _EverFound, _KeyDirs)
when Tstamp < ExpiryTime ->
true;
out_of_date(Key, Tstamp, FileId, {_,_,Offset,_} = Pos, ExpiryTime, EverFound,
[KeyDir|Rest]) ->
case bitcask_nifs:keydir_get(KeyDir, Key) of
not_found ->
out_of_date(Key, Tstamp, FileId, Pos, ExpiryTime, EverFound, Rest);
E when is_record(E, bitcask_entry) ->
if
E#bitcask_entry.tstamp == Tstamp ->
%% Exact match. In this situation, we use the file
%% id and offset as a tie breaker. The assumption
%% is that the merge starts with the newest files
%% first, thus we want data from the highest
%% file_id and the highest offset in that file.
if
E#bitcask_entry.file_id > FileId ->
true;
E#bitcask_entry.file_id == FileId ->
case E#bitcask_entry.offset > Offset of
true ->
true;
false ->
out_of_date(
Key, Tstamp, FileId, Pos,
ExpiryTime, true, Rest)
end;
true ->
%% At this point the following conditions are true:
%% The file_id in the keydir is older (<) the file
%% id we're currently merging...
%%
%% OR:
%%
%% The file_id in the keydir is the same (==) as the
%% file we're merging BUT the offset the keydir has
%% is older (<=) the offset we are currently
%% processing.
%%
%% Thus, we are NOT out of date. Check the
%% rest of the keydirs to ensure this
%% holds true.
out_of_date(Key, Tstamp, FileId, Pos,
ExpiryTime, true, Rest)
end;
E#bitcask_entry.tstamp < Tstamp ->
%% Not out of date -- check rest of the keydirs
out_of_date(Key, Tstamp, FileId, Pos,
ExpiryTime, true, Rest);
true ->
%% Out of date!
true
end
end.
readable_files(Dirname) ->
%% Check the write and/or merge locks to see what files are currently
%% being written to. Generate our list excepting those.
WritingFile = bitcask_lockops:read_activefile(write, Dirname),
MergingFile = bitcask_lockops:read_activefile(merge, Dirname),
list_data_files(Dirname, WritingFile, MergingFile).
%% Internal put - have validated that the file is opened for write
%% and looked up the state at this point
do_put(_Key, _Value, State, 0, LastErr) ->
{{error, LastErr}, State};
do_put(Key, Value, #bc_state{write_file = WriteFile} = State, Retries, _LastErr) ->
case bitcask_fileops:check_write(WriteFile, Key, Value,
State#bc_state.max_file_size) of
wrap ->
%% Time to start a new write file. Note that we do not close the old
%% one, just transition it. The thinking is that closing/reopening
%% for read only access would flush the O/S cache for the file,
%% which may be undesirable.
State2 = wrap_write_file(State);
fresh ->
%% Time to start our first write file.
case bitcask_lockops:acquire(write, State#bc_state.dirname) of
{ok, WriteLock} ->
{ok, NewWriteFile} = bitcask_fileops:create_file(
State#bc_state.dirname,
State#bc_state.opts),