-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathbitcask.erl
3694 lines (3290 loc) · 140 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/6,
fold/3, fold/6,
iterator/3, iterator_next/1, iterator_release/1,
merge/1, merge/2, merge/3,
needs_merge/1,
needs_merge/2,
is_frozen/1,
is_empty_estimate/1,
status/1]).
-export([get_opt/2,
get_filestate/2,
is_tombstone/1]).
-export([has_pending_delete_bit/1]). % For EUnit tests
-include_lib("kernel/include/file.hrl").
-include("bitcask.hrl").
-ifdef(PULSE).
-compile({parse_transform, pulse_instrument}).
-compile(export_all).
-define(OPEN_FOLD_RETRIES, 100).
-else.
-define(OPEN_FOLD_RETRIES, 3).
-endif.
-ifdef(TEST).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include_lib("kernel/include/file.hrl").
-export([leak_t0/0, leak_t1/0]).
-endif.
%% In the real world, 1 or 2 retries is usually sufficient. In the
%% world of QuickCheck, however, QC can create some diabolical
%% races, so use a diabolical number.
-define(DIABOLIC_BIG_INT, 100).
%% In an EQC testing scenario, poll_for_merge_lock() may have failed
%% This atom is the signal that it failed but is harmless in this situation.
-define(POLL_FOR_MERGE_LOCK_PSEUDOFAILURE, pseudo_failure).
%% @type bc_state().
-record(bc_state, {dirname :: string(),
write_file :: 'fresh' | 'undefined' | #filestate{}, % File for writing
write_lock :: reference() | undefined, % Reference to write lock
read_files=[] :: [#filestate{}], % Files opened for reading
max_file_size :: integer(), % Max. size of a written file
opts :: list(), % Original options used to open the bitcask
key_transform=fun kt_id/1 :: fun((binary()) -> binary()),
keydir :: reference(), % Key directory
read_write_p :: integer(), % integer() avoids atom -> NIF
% What tombstone style to write, for testing purposes only.
% 0 = old style without file id, 2 = new style with file id
tombstone_version = 2 :: 0 | 2
}).
-ifdef(namespaced_types).
-type bitcask_set() :: sets:set().
-else.
-type bitcask_set() :: set().
-endif.
-record(mstate, { dirname :: string(),
merge_lock :: reference(),
max_file_size :: integer(),
input_files :: [#filestate{}],
input_file_ids :: bitcask_set(),
min_file_id :: non_neg_integer(),
tombstone_write_files :: [#filestate{}],
out_file :: 'fresh' | #filestate{},
merge_coverage :: prefix | partial | full,
live_keydir :: reference(),
del_keydir :: reference(),
expiry_time :: integer(),
expiry_grace_time :: integer(),
key_transform=fun kt_id/1 :: fun((binary()) -> binary()),
read_write_p :: integer(), % integer() avoids atom -> NIF
opts :: list(),
delete_files :: [#filestate{}]}).
%% 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 ->
%% If the lock file is not stale, we'll continue initializing
%% and loading anyway: if later someone tries to write
%% something, that someone will get a write_locked exception.
_ = 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)),
%% Set the key transform for this cask
KeyTransformFun = get_key_transform(get_opt(key_transform, Opts)),
%% Type of tombstone to write, for testing.
TombstoneVersion = get_opt(tombstone_version, Opts),
%% Loop and wait for the keydir to come available.
ReadWriteP = WritingFile /= undefined,
ReadWriteI = case ReadWriteP of true -> 1;
false -> 0
end,
case init_keydir(Dirname, WaitTime, ReadWriteP, KeyTransformFun) 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,
key_transform = KeyTransformFun,
tombstone_version = TombstoneVersion,
read_write_p = ReadWriteI}),
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),
%% 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,
%% 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
bitcask_fileops:close_all(State#bc_state.read_files),
ok.
%% @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
case bitcask_nifs:keydir_remove(State#bc_state.keydir, Key,
E#bitcask_entry.tstamp,
E#bitcask_entry.file_id,
E#bitcask_entry.offset) of
ok ->
not_found;
already_exists ->
% Updated since last read, try again.
get(Ref, Key, TryNum-1)
end;
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);
{error, _} = Else ->
Else;
{Filestate, S2} ->
put_state(Ref, S2),
case bitcask_fileops:read(Filestate,
E#bitcask_entry.offset,
E#bitcask_entry.total_sz) of
{ok, _Key, Value} ->
case is_tombstone(Value) of
true ->
not_found;
false ->
{ok, Value}
end;
{error, eof} ->
not_found;
{error, _} = Err ->
Err
end
end
end
end.
%% @doc Store a key and value in a bitcase datastore.
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,
try
{Ret, State1} = do_put(Key, Value, State,
?DIABOLIC_BIG_INT, undefined),
put_state(Ref, State1),
Ret
catch throw:{unrecoverable, Error, State2} ->
put_state(Ref, State2),
{error, Error}
end.
%% @doc Delete a key from a bitcask datastore.
-spec delete(reference(), Key::binary()) -> ok.
delete(Ref, Key) ->
put(Ref, Key, tombstone).
%% @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, false).
%% @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, boolean()) ->
term() | {error, any()}.
fold_keys(Ref, Fun, Acc0, MaxAge, MaxPut, SeeTombstonesP) ->
%% 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 ->
case BCEntry#bitcask_entry.total_sz -
(?HEADER_SIZE + size(Key)) of
Ss when ?IS_TOMBSTONE_SIZE(Ss) ->
%% might be a deleted record, so check
case ?MODULE:get(Ref, Key) of
not_found when not SeeTombstonesP ->
Acc;
not_found when SeeTombstonesP ->
Fun({tombstone, BCEntry}, 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() | tuple(),
fun((binary(), binary(), any()) -> any()),
any()) -> any() | {error, any()}.
fold(Ref, Fun, Acc0) when is_reference(Ref)->
State = get_state(Ref),
fold(State, Fun, Acc0);
fold(State, Fun, Acc0) ->
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),
SeeTombstonesP = get_opt(fold_tombstones, State#bc_state.opts) /= undefined,
fold(State, Fun, Acc0, MaxAge, MaxPuts, SeeTombstonesP).
%% @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() | tuple(), fun((binary(), binary(), any()) -> any()), any(),
non_neg_integer() | undefined, non_neg_integer() | undefined, boolean()) ->
any() | {error, any()}.
fold(Ref, Fun, Acc0, MaxAge, MaxPut, SeeTombstonesP) when is_reference(Ref)->
State = get_state(Ref),
fold(State, Fun, Acc0, MaxAge, MaxPut, SeeTombstonesP);
fold(State, Fun, Acc0, MaxAge, MaxPut, SeeTombstonesP) ->
KT = State#bc_state.key_transform,
FrozenFun =
fun() ->
case open_fold_files(State#bc_state.dirname,
State#bc_state.keydir,
?OPEN_FOLD_RETRIES) of
{ok, Files, FoldEpoch} ->
ExpiryTime = expiry_time(State#bc_state.opts),
SubFun = fun(K0,V,TStamp,{_FN,FTS,Offset,_Sz},Acc) ->
K = try
KT(K0)
catch
KeyTxErr ->
{key_tx_error, {K0, KeyTxErr}}
end,
case {K, (TStamp < ExpiryTime)} of
{{key_tx_error, TxErr}, _} ->
error_logger:error_msg("Error converting key ~p: ~p", [K0, TxErr]),
Acc;
{_, true} ->
Acc;
{_, false} ->
case bitcask_nifs:keydir_get(
State#bc_state.keydir, K,
FoldEpoch) 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 when SeeTombstonesP ->
Fun({tombstone, K},V,Acc);
true when not SeeTombstonesP ->
case is_tombstone(V) 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, _Keydir, 0) ->
{error, max_retries_exceeded_for_fold};
open_fold_files(Dirname, Keydir, Count) ->
try
{Epoch, CurrentFiles} = current_files(Dirname, Keydir),
Filenames = [F#file_status.filename || F <- CurrentFiles],
case open_files(Filenames, []) of
{ok, Files} ->
{ok, Files, Epoch};
{error, ErrFile, Err} ->
maybe_log_missing_file(Dirname, Keydir, ErrFile, Err),
open_fold_files(Dirname, Keydir, Count-1)
end
catch X:Y ->
{error, {X,Y, erlang:get_stacktrace()}}
end.
maybe_log_missing_file(Dirname, Keydir, ErrFile, enoent) ->
case is_current_file(Dirname, Keydir, ErrFile) of
true ->
error_logger:error_msg("Unexpectedly missing file ~s", [ErrFile]),
FileId = bitcask_fileops:file_tstamp(ErrFile),
%% Forget it to avoid retrying opening it
_ = bitcask_nifs:keydir_trim_fstats(Keydir, [FileId]),
ok;
false ->
ok
end;
maybe_log_missing_file(_, _, _, _) ->
ok.
is_current_file(Dirname, Keydir, Filename) ->
FileId = bitcask_fileops:file_tstamp(Filename),
{_Epoch, CurrentFiles} = current_files(Dirname, Keydir),
lists:any(fun(F) ->
bitcask_fileops:file_tstamp(F#file_status.filename) ==
FileId
end, CurrentFiles).
%%
%% 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) ->
interfere_with_pulse_test_only(),
case bitcask_fileops:open_file(Filename) of
{ok, Fd} ->
open_files(Rest, [Fd | Acc]);
{error, Err} ->
bitcask_fileops:close_all(Acc),
{error, Filename, Err}
end.
%%
%% Apply fold function to a single bitcask file; results are accumulated in
%% Acc
%%
subfold(_SubFun,[],Acc) ->
Acc;
subfold(SubFun,[FD | Rest],Acc0) ->
Acc2 = try bitcask_fileops:fold(FD, SubFun, Acc0) of
Acc1 ->
Acc1
catch
throw:{fold_error, Error, _PartialAcc} ->
error_logger:error_msg("subfold: skipping file ~s: ~p\n",
[FD#filestate.filename, Error]),
Acc0
after
bitcask_fileops:close(FD)
end,
subfold(SubFun, Rest, Acc2).
%% @doc Start entry iterator
-spec iterator(reference(), integer(), integer()) ->
ok | out_of_date | {error, iteration_in_process}.
iterator(Ref, MaxAge, MaxPuts) ->
KeyDir = (get_state(Ref))#bc_state.keydir,
bitcask_nifs:keydir_itr(KeyDir, MaxAge, MaxPuts).
%% @doc Get next entry from the iterator
-spec iterator_next(reference()) ->
#bitcask_entry{} |
{error, iteration_not_started} | allocation_error | not_found.
iterator_next(Ref) ->
KeyDir = (get_state(Ref))#bc_state.keydir,
bitcask_nifs:keydir_itr_next(KeyDir).
%% @doc Release iterator
-spec iterator_release(reference()) -> ok.
iterator_release(Ref) ->
KeyDir = (get_state(Ref))#bc_state.keydir,
bitcask_nifs:keydir_itr_release(KeyDir).
%% @doc Merge several data files within a bitcask datastore
%% into a more compact form.
-spec merge(Dirname::string()) -> ok | {error, any()}.
merge(Dirname) ->
merge(Dirname, []).
%% @doc Merge several data files within a bitcask datastore
%% into a more compact form.
-spec merge(Dirname::string(), Opts::[_]) -> ok | {error, any()}.
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()],FilesToDelete::[string()]})
-> ok | {error, any()}.
merge(_Dirname, _Opts, []) ->
ok;
merge(Dirname,Opts,FilesToMerge) when is_list(FilesToMerge) ->
merge(Dirname,Opts,{FilesToMerge,[]});
merge(_Dirname, _Opts, {[],_}) ->
ok;
merge(Dirname, Opts, {FilesToMerge0, ExpiredFiles0}) ->
try
%% 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,
bitcask_fileops:is_file(F)],
ExpiredFiles = [F || F <- ExpiredFiles0,
bitcask_fileops:is_file(F)],
merge1(Dirname, Opts, FilesToMerge, ExpiredFiles)
catch
throw:Reason ->
Reason;
X:Y ->
{error, {generic_failure, X, Y, erlang:get_stacktrace()}}
end.
%% Inner merge function, assumes that bitcask is running and all files exist.
merge1(_Dirname, _Opts, [], []) ->
ok;
merge1(Dirname, Opts, FilesToMerge0, ExpiredFiles) ->
KT = get_key_transform(get_opt(key_transform, Opts)),
%% 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:maybe_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
InFiles0 = [begin
%% Handle open errors gracefully. QuickCheck
%% plus PULSE showed that there are races where
%% the open below can fail.
case bitcask_fileops:open_file(F) of
{ok, Fstate} -> Fstate;
{error, _} -> skip
end
end
|| F <- FilesToMerge0],
InFiles1 = [F || F <- InFiles0, F /= skip];
{error, not_ready} ->
%% Someone else is loading the keydir, or this cask isn't open.
%% We'll bail here and try again later.
ok = bitcask_lockops:release(Lock),
% Make erlc happy w/ non-local exit
LiveKeyDir = undefined, InFiles1 = [],
throw({error, not_ready})
end,
{InFiles2,InExpiredFiles} = lists:foldl(fun(F, {InFilesAcc,InExpiredAcc}) ->
case lists:member(F#filestate.filename,
ExpiredFiles) of
false ->
{[F|InFilesAcc],InExpiredAcc};
true ->
{InFilesAcc,[F|InExpiredAcc]}
end
end, {[],[]}, InFiles1),
%% Test to see if this is a complete or partial merge
%% We perform this test now because our efforts to open the input files
%% in the InFiles0 list comprehension above may have had an open
%% failure. The open(2) shouldn't fail, except, of course, when it
%% does, e.g. EMFILE, ENFILE, the OS decides EINTR because "reasons", ...
ReadableFiles = lists:usort(readable_files(Dirname) -- ExpiredFiles),
FilesToMerge = lists:usort([F#filestate.filename || F <- InFiles2]),
MergeCoverage =
case FilesToMerge == ReadableFiles of
true ->
full;
false ->
case lists:prefix(FilesToMerge, ReadableFiles) of
true ->
prefix;
false ->
partial
end
end,
% This sort is very important. The merge expects to visit files in order
% to properly detect current values, and could resurrect old values if not.
InFiles = lists:sort(fun(#filestate{tstamp=FTL}, #filestate{tstamp=FTR}) ->
FTL =< FTR
end, InFiles2),
InFileIds = sets:from_list([bitcask_fileops:file_tstamp(InFile)
|| InFile <- InFiles]),
MinFileId = if ReadableFiles == [] ->
1;
true ->
lists:min([bitcask_fileops:file_tstamp(F) ||
F <- ReadableFiles])
end,
%% 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,
input_file_ids = InFileIds,
min_file_id = MinFileId,
tombstone_write_files = [],
out_file = fresh, % will be created when needed
merge_coverage = MergeCoverage,
live_keydir = LiveKeyDir,
del_keydir = DelKeyDir,
expiry_time = expiry_time(Opts),
expiry_grace_time = expiry_grace_time(Opts),
key_transform = KT,
read_write_p = 0,
opts = Opts,
delete_files = []},
%% Finally, start the merge process
ExpiredFilesFinished = expiry_merge(InExpiredFiles, LiveKeyDir, KT, []),
State1 = merge_files(State),
%% Make sure to close the final output file
case State1#mstate.out_file of
fresh ->
ok;
Outfile ->
ok = bitcask_fileops:sync(Outfile),
ok = bitcask_fileops:close(Outfile)
end,
_ = [begin
ok = bitcask_fileops:sync(TFile),
ok = bitcask_fileops:close(TFile)
end || TFile <- State1#mstate.tombstone_write_files],
%% Close the original input files, schedule them for deletion,
%% close keydirs, and release our lock
bitcask_fileops:close_all(State#mstate.input_files ++ ExpiredFilesFinished),
{_, _, _, {IterGeneration, _, _, _}, _} = bitcask_nifs:keydir_info(LiveKeyDir),
DelFiles = [F || F <- State1#mstate.delete_files ++ ExpiredFilesFinished],
FileNames = [F#filestate.filename || F <- DelFiles],
DelIds = [F#filestate.tstamp || F <- DelFiles],
_ = [bitcask_nifs:set_pending_delete(LiveKeyDir, DelId) || DelId <- DelIds],
_ = [catch set_pending_delete_bit(F) || F <- FileNames],
bitcask_merge_delete:defer_delete(Dirname, IterGeneration, FileNames),
%% Explicitly release our keydirs instead of waiting for GC
bitcask_nifs:keydir_release(LiveKeyDir),
bitcask_nifs:keydir_release(DelKeyDir),
ok = bitcask_lockops:release(Lock).
%% @doc Predicate which determines whether or not a file should be considered for a merge.
consider_for_merge(FragTrigger, DeadBytesTrigger, ExpirationGraceTime) ->
fun (F) ->
(F#file_status.fragmented >= FragTrigger)
orelse (F#file_status.dead_bytes >= DeadBytesTrigger)
orelse ((F#file_status.oldest_tstamp > 0) andalso %% means that the file has data
(F#file_status.newest_tstamp < ExpirationGraceTime)
)
end.
-spec needs_merge(reference()) -> {true, {[string()], [string()]}} | false.
needs_merge(Ref) ->
needs_merge(Ref, []).
-spec needs_merge(reference(), proplists:proplist()) -> {true, {[string()], [string()]}} | false.
needs_merge(Ref, Opts) ->
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) ->
bitcask_fileops:is_file(bitcask_fileops:filename(F))
end,
{LiveFiles, DeadFiles} = lists:partition(P, State#bc_state.read_files),
%% Close the dead files and accumulate a list for trimming their
%% fstats entries.
DeadIds0 =
[begin
bitcask_fileops:close(F),
bitcask_fileops:file_tstamp(F)
end
|| F <- DeadFiles],
DeadIds = lists:usort(DeadIds0),
case bitcask_nifs:keydir_trim_fstats(State#bc_state.keydir,
DeadIds) of
{ok, 0} ->
ok;
{ok, Warn} ->
error_logger:info_msg("Trimmed ~p non-existent fstat entries",
[Warn]);
Err ->
error_logger:error_msg("Error trimming fstats entries: ~p",
[Err])
end,
#bc_state{dirname=Dirname} = State,
%% Update state with live files
put_state(Ref, State#bc_state { read_files = LiveFiles }),
Result0 =
case explicit_merge_files(Dirname) of
[] ->
run_merge_triggers(State, Summary);
MergeFiles ->
{true, {MergeFiles, []}}
end,
MaxMergeSize = proplists:get_value(max_merge_size, Opts),
case Result0 of
false ->
false;
{true, {MergeFiles0, ExpiredFiles}} ->
{true, {cap_size(MergeFiles0, MaxMergeSize), ExpiredFiles}}
end.
-spec cap_size([string()], integer()) -> [string()].
cap_size(Files, MaxSize) ->
Result0 =
lists:foldl(fun(_, {finished, Acc}) ->
{finished, Acc};
(F, {AccSize, InFiles}) ->
case bitcask_fileops:read_file_info(F) of
{ok, #file_info{size=Size}}
when Size+AccSize > MaxSize ->
{finished, {AccSize, InFiles}};
{ok, #file_info{size=Size}} ->
{Size+AccSize, [F|InFiles]};
_ -> % Can't get size, assume zero (deleted)
{AccSize, [F|InFiles]}
end
end, {0, []}, Files),
Result1 =
case Result0 of
{finished, {_, List}} ->
List;
{_, List} ->
List
end,
lists:reverse(Result1).
%% Reads the list of files to merge from a text file if present.
%% The file will be deleted if it doesn't contain unmerged files.
-spec explicit_merge_files(Dir :: string()) -> list(string()).
explicit_merge_files(Dirname) ->
MergeListFile = filename:join(Dirname, "merge.txt"),
case read_lines(MergeListFile) of
{error, ReadErr} ->
case filelib:is_regular(MergeListFile) of
true ->
error_logger:error_msg("Invalid merge input file ~s,"
" deleting : ~p",
[MergeListFile, ReadErr]),
_ = file:delete(MergeListFile),
[];
false ->
[]
end;
{ok, MergeList} ->
case next_merge_batch(Dirname, MergeList) of
[] ->
_ = file:delete(MergeListFile),
[];
MergeBatch ->
MergeBatch
end
end.
-spec next_merge_batch(Dir::string(), Files::[binary()]) -> [string()].
next_merge_batch(Dir, Files) ->
AllFiles = sets:from_list(readable_files(Dir)),
Batch =
lists:foldl(fun(<<>>, []=Acc) ->
% Drop leading empty lines
Acc;
(<<>>, [_|_]=Acc) ->
% Stop at first empty line after some files
{batch, Acc};
(F0, Acc) when is_list(Acc) ->
% Collect existing files
F = filename:join(Dir, binary_to_list(F0)),
case sets:is_element(F, AllFiles) of
true ->
[F|Acc];
false ->
Acc
end;
(_, {batch, _}=Acc) ->
% Ignore the rest
Acc
end, [], Files),
BatchFiles =
case Batch of
{batch, List} ->
List;
List ->
List
end,
lists:reverse(BatchFiles).
-spec read_lines(string()) -> {ok, [binary()]} | {error, _}.
read_lines(Filename) ->
case file:read_file(Filename) of
{ok, Bin} ->
LineSeps = [<<"\n">>, <<"\r">>, <<"\r\n">>],
{ok, binary:split(Bin, LineSeps, [global])};
Err ->
Err
end.
run_merge_triggers(State, Summary) ->
%% 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_time - Any file has an expired key
%% expiry_grace_time - avoid expiring in the case of continuous writes
%%
FragTrigger = get_opt(frag_merge_trigger, State#bc_state.opts),
DeadBytesTrigger = get_opt(dead_bytes_merge_trigger, State#bc_state.opts),
ExpirationTime =
max(expiry_time(State#bc_state.opts), 0),
ExpirationGraceTime =
max(expiry_time(State#bc_state.opts) - expiry_grace_time(State#bc_state.opts), 0),
NeedsMerge = lists:any(consider_for_merge(FragTrigger, DeadBytesTrigger, ExpirationGraceTime),
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],
F = fun(X) ->
case X of
{data_expired,_,_} ->
true;
_ ->
false
end
end,
ExpiredFiles = [Filename || {Filename, Reasons} <- MergableFiles, lists:any(F,Reasons)],
{true, {FileNames, ExpiredFiles}};
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;