-
Notifications
You must be signed in to change notification settings - Fork 10
/
osiris_log.erl
2319 lines (2206 loc) · 92.2 KB
/
osiris_log.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
%% This Source Code Form is subject to the terms of the Mozilla Public
%% License, v. 2.0. If a copy of the MPL was not distributed with this
%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2007-2021 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(osiris_log).
-include("osiris.hrl").
-export([init/1,
init/2,
init_acceptor/3,
write/2,
write/3,
write/5,
recover_tracking/1,
accept_chunk/2,
next_offset/1,
first_offset/1,
first_timestamp/1,
tail_info/1,
is_open/1,
send_file/2,
send_file/3,
init_data_reader/2,
init_offset_reader/2,
read_header/1,
read_chunk/1,
read_chunk_parsed/1,
read_chunk_parsed/2,
committed_offset/1,
get_current_epoch/1,
get_directory/1,
get_name/1,
get_default_max_segment_size_bytes/0,
counters_ref/1,
close/1,
overview/1,
format_status/1,
update_retention/2,
evaluate_retention/2,
directory/1,
delete_directory/1]).
-define(IDX_VERSION, 1).
-define(LOG_VERSION, 1).
-define(IDX_HEADER, <<"OSII", ?IDX_VERSION:32/unsigned>>).
-define(LOG_HEADER, <<"OSIL", ?LOG_VERSION:32/unsigned>>).
-define(IDX_HEADER_SIZE, 8).
-define(LOG_HEADER_SIZE, 8).
% maximum size of a segment in bytes
-define(DEFAULT_MAX_SEGMENT_SIZE_B, 500 * 1000 * 1000).
% maximum number of chunks per segment
-define(DEFAULT_MAX_SEGMENT_SIZE_C, 256_000).
-define(INDEX_RECORD_SIZE_B, 29).
-define(C_OFFSET, 1).
-define(C_FIRST_OFFSET, 2).
-define(C_FIRST_TIMESTAMP, 3).
-define(C_CHUNKS, 4).
-define(C_SEGMENTS, 5).
-define(COUNTER_FIELDS,
[
{offset, ?C_OFFSET, counter, "The last offset (not chunk id) in the log for writers. The last offset read for readers"
},
{first_offset, ?C_FIRST_OFFSET, counter, "First offset, not updated for readers"},
{first_timestamp, ?C_FIRST_TIMESTAMP, counter, "First timestamp, not updated for readers"},
{chunks, ?C_CHUNKS, counter, "Number of chunks read or written, incremented even if a reader only reads the header"},
{segments, ?C_SEGMENTS, counter, "Number of segments"}
]
).
%% Specification of the Log format.
%%
%% Notes:
%% * All integers are in Big Endian order.
%% * Timestamps are expressed in milliseconds.
%% * Timestamps are stored in signed 64-bit integers.
%%
%% Log format
%% ==========
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +---------------+---------------+---------------+---------------+
%% | Log magic (0x4f53494c = "OSIL") |
%% +---------------------------------------------------------------+
%% | Log version (0x00000001) |
%% +---------------------------------------------------------------+
%% | Contiguous list of Chunks |
%% : (until EOF) :
%% : :
%% +---------------------------------------------------------------+
%%
%% Chunk format
%% ============
%%
%% A chunk is the unit of replication and read.
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +-------+-------+---------------+---------------+---------------+
%% | Mag | Ver | Chunk type | Number of entries |
%% +-------+-------+---------------+-------------------------------+
%% | Number of records |
%% +---------------------------------------------------------------+
%% | Timestamp |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | Epoch |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | ChunkId |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | Data CRC |
%% +---------------------------------------------------------------+
%% | Data length |
%% +---------------------------------------------------------------+
%% | Trailer length |
%% +---------------------------------------------------------------+
%% | Reserved |
%% +---------------------------------------------------------------+
%% | Contiguous list of Data entries |
%% : (<data length> bytes) :
%% : :
%% +---------------------------------------------------------------+
%% | Contiguous list of Trailer entries |
%% : (<trailer length> bytes) :
%% : :
%% +---------------------------------------------------------------+
%%
%% Mag = 0x5
%% Magic number to identify the beginning of a chunk
%%
%% Ver = 0x1
%% Version of the chunk format
%%
%% Chunk type = CHNK_USER (0x00) |
%% CHNK_TRK_DELTA (0x01) |
%% CHNK_TRK_SNAPSHOT (0x02)
%% Type which determines what to do with entries.
%%
%% Number of entries = unsigned 16-bit integer
%% Number of entries in the data section following the chunk header.
%%
%% Number of records = unsigned 32-bit integer
%%
%% Timestamp = signed 64-bit integer
%%
%% Epoch = unsigned 64-bit integer
%%
%% ChunkId = unsigned 64-bit integer, the first offset in the chunk
%%
%% Data CRC = unsigned 32-bit integer
%%
%% Data length = unsigned 32-bit integer
%%
%% Trailer length = unsigned 32-bit integer
%%
%% Reserved = 4 bytes reserved for future extensions
%%
%% Data Entry format
%% =================
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +---------------+---------------+---------------+---------------+
%% |T| Data entry header and body |
%% +-+ (format and length depends on the chunk and entry types) :
%% : :
%% : :
%% +---------------------------------------------------------------+
%%
%% T = SimpleEntry (0) |
%% SubBatchEntry (1)
%%
%% SimpleEntry (CHNK_USER)
%% -----------------------
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +---------------+---------------+---------------+---------------+
%% |0| Entry body length |
%% +-+-------------------------------------------------------------+
%% | Entry body :
%% : (<body length> bytes) :
%% : :
%% +---------------------------------------------------------------+
%%
%% Entry body length = unsigned 31-bit integer
%%
%% Entry body = arbitrary data
%%
%% SimpleEntry (CHNK_TRK_SNAPSHOT)
%% -------------------------------------------------
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +-+-------------+---------------+---------------+---------------+
%% |0| Entry body length |
%% +-+-------------------------------------------------------------+
%% | Entry Body |
%% : (<body length> bytes) :
%% : :
%% +---------------------------------------------------------------+
%%
%% The entry body is made of a contiguous list of the following block, until
%% the body length is reached.
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +---------------+---------------+---------------+---------------+
%% | Trk type | ID size | ID |
%% +---------------+---------------+ |
%% | |
%% : :
%% +---------------------------------------------------------------+
%% | Type specific data |
%% | |
%% +---------------------------------------------------------------+
%%
%% ID type = unsigned 8-bit integer 0 = sequence, 1 = offset
%%
%% ID size = unsigned 8-bit integer
%%
%% ID = arbitrary data
%%
%% Type specific data:
%% When ID type = 0: ChunkId, Sequence = unsigned 64-bit integers
%% When ID type = 1: Offset = unsigned 64-bit integer
%%
%%
%% SubBatchEntry (CHNK_USER)
%% -------------------------
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +-+-----+-------+---------------+---------------+---------------+
%% |1| Cmp | Rsvd | Number of records | Uncmp Length..|
%% +-+-----+-------+-------------------------------+---------------+
%% | Uncompressed Length | Length (...) |
%% +-+-----+-------+-------------------------------+---------------+
%% | Length | Body |
%% +-+---------------------------------------------+ +
%% | Body |
%% : :
%% +---------------------------------------------------------------+
%%
%% Cmp = unsigned 3-bit integer
%% Compression type
%%
%% Rsvd = 0x0
%% Reserved bits
%%
%% Number of records = unsigned 16-bit integer
%%
%% Uncompressed Length = unsigned 32-bit integer
%% Length = unsigned 32-bit integer
%%
%% Body = arbitrary data
%%
%% Tracking format
%% ==============
%%
%% Tracking is made of a contiguous list of the following block,
%% until the trailer length stated in the chunk header is reached.
%% The same format is used for the CHNK_TRK_DELTA chunk entry.
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +-+-------------+---------------+---------------+---------------+
%% | Tracking type |TrackingID size| TrackingID |
%% +---------------+---------------+ |
%% | |
%% : :
%% +---------------------------------------------------------------+
%% | Tracking data |
%% | |
%% +---------------------------------------------------------------+
%%
%%
%% Tracking type: 0 = sequence, 1 = offset, 2 = timestamp
%%
%% Tracking type 0 = sequence to track producers for msg deduplication
%% use case: producer sends msg -> osiris persists msg -> confirm doens't reach producer -> producer resends same msg
%%
%% Tracking type 1 = offset to track consumers
%% use case: consumer or server restarts -> osiris knows offset where consumer needs to resume
%%
%% Tracking data: 64 bit integer
%%
%% Index format
%% ============
%%
%% Each index record in the index file maps to a chunk in the segment file.
%%
%% Index record
%% ------------
%%
%% |0 |1 |2 |3 | Bytes
%% |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| Bits
%% +---------------+---------------+---------------+---------------+
%% | Offset |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | Timestamp |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | Epoch |
%% | (8 bytes) |
%% +---------------------------------------------------------------+
%% | File Offset |
%% +---------------+-----------------------------------------------+
%% | Chunk Type |
%% +---------------+
-type offset() :: osiris:offset().
-type epoch() :: osiris:epoch().
-type range() :: empty | {From :: offset(), To :: offset()}.
-type counter_spec() :: {Tag :: term(), Fields :: [atom()]}.
-type chunk_type() ::
?CHNK_USER |
?CHNK_TRK_DELTA |
?CHNK_TRK_SNAPSHOT.
-type config() ::
osiris:config() |
#{dir := file:filename(),
epoch => non_neg_integer(),
first_offset_fun => fun((integer()) -> ok),
max_segment_size_bytes => non_neg_integer(),
%% max number of writer ids to keep around
tracking_config => osiris_tracking:config(),
counter_spec => counter_spec(),
%% used when initialising a log from an offset other than 0
initial_offset => osiris:offset()}.
-type record() :: {offset(), osiris:data()}.
-type offset_spec() :: osiris:offset_spec().
-type retention_spec() :: osiris:retention_spec().
-type header_map() ::
#{chunk_id => offset(),
epoch => epoch(),
type => chunk_type(),
crc => integer(),
num_records => non_neg_integer(),
num_entries => non_neg_integer(),
timestamp => osiris:timestamp(),
data_size => non_neg_integer(),
trailer_size => non_neg_integer(),
header_data => binary(),
position => non_neg_integer()}.
-type transport() :: tcp | ssl.
%% holds static or rarely changing fields
-record(cfg,
{directory :: file:filename(),
name :: string(),
max_segment_size_bytes = ?DEFAULT_MAX_SEGMENT_SIZE_B :: non_neg_integer(),
max_segment_size_chunks = ?DEFAULT_MAX_SEGMENT_SIZE_C :: non_neg_integer(),
tracking_config = #{} :: osiris_tracking:config(),
retention = [] :: [osiris:retention_spec()],
counter :: counters:counters_ref(),
counter_id :: term(),
%% the maximum number of active writer deduplication sessions
%% that will be included in snapshots written to new segments
readers_counter_fun = fun(_) -> ok end :: function(),
first_offset_fun :: fun ((integer()) -> ok)}).
-record(read,
{type :: data | offset,
offset_ref :: undefined | atomics:atomics_ref(),
last_offset = 0 :: offset(),
next_offset = 0 :: offset(),
transport :: transport(),
chunk_selector :: all | user_data}).
-record(write,
{type = writer :: writer | acceptor,
segment_size = {0, 0} :: {non_neg_integer(), non_neg_integer()},
current_epoch :: non_neg_integer(),
tail_info = {0, empty} :: osiris:tail_info()
}).
-record(?MODULE,
{cfg :: #cfg{},
mode :: #read{} | #write{},
current_file :: undefined | file:filename(),
fd :: undefined | file:io_device(),
index_fd :: undefined | file:io_device()}).
%% record chunk_info does not map exactly to an index record (field 'num' differs)
-record(chunk_info,
{id :: offset(),
timestamp :: non_neg_integer(),
epoch :: epoch(),
num :: non_neg_integer(),
type :: chunk_type(),
%% size of data + trailer
size :: non_neg_integer(),
%% position in segment file
pos :: integer()
}).
-record(seg_info,
{file :: file:filename(),
size = 0 :: non_neg_integer(),
index :: file:filename(),
first :: undefined | #chunk_info{},
last :: undefined | #chunk_info{}}).
-opaque state() :: #?MODULE{}.
-export_type([state/0,
range/0,
config/0,
counter_spec/0]).
-spec directory(osiris:config() | list()) -> file:filename().
directory(#{name := Name, dir := Dir}) ->
filename:join(Dir, Name);
directory(#{name := Name}) ->
{ok, Dir} = application:get_env(osiris, data_dir),
filename:join(Dir, Name);
directory(Name) when is_list(Name) ->
{ok, Dir} = application:get_env(osiris, data_dir),
filename:join(Dir, Name).
-spec init(config()) -> state().
init(Config) ->
init(Config, writer).
-spec init(config(), writer | acceptor) -> state().
init(#{dir := Dir,
name := Name,
epoch := Epoch} =
Config,
WriterType) ->
%% scan directory for segments if in write mode
MaxSizeBytes =
maps:get(max_segment_size_bytes, Config, ?DEFAULT_MAX_SEGMENT_SIZE_B),
MaxSizeChunks = application:get_env(osiris, max_segment_size_chunks, ?DEFAULT_MAX_SEGMENT_SIZE_C),
Retention = maps:get(retention, Config, []),
?DEBUG("osiris_log:init/1 max_segment_size_bytes: ~b, max_segment_size_chunks ~b, retention ~w",
[MaxSizeBytes, MaxSizeChunks, Retention]),
ok = filelib:ensure_dir(Dir),
case file:make_dir(Dir) of
ok ->
ok;
{error, eexist} ->
ok;
Err ->
throw(Err)
end,
Cnt = make_counter(Config),
%% initialise offset counter to -1 as 0 is the first offset in the log and
%% it hasn't necessarily been written yet, for an empty log the first offset
%% is initialised to 0 however and will be updated after each retention run.
counters:put(Cnt, ?C_OFFSET, -1),
counters:put(Cnt, ?C_SEGMENTS, 0),
FirstOffsetFun = maps:get(first_offset_fun, Config, fun (_) -> ok end),
Cfg = #cfg{directory = Dir,
name = Name,
max_segment_size_bytes = MaxSizeBytes,
max_segment_size_chunks = MaxSizeChunks,
tracking_config = maps:get(tracking_config, Config, #{}),
retention = Retention,
counter = Cnt,
counter_id = counter_id(Config),
first_offset_fun = FirstOffsetFun},
case lists:reverse(build_log_overview(Dir)) of
[] ->
NextOffset = case Config of
#{initial_offset := IO}
when WriterType == acceptor ->
IO;
_ ->
0
end,
open_new_segment(#?MODULE{cfg = Cfg,
mode =
#write{type = WriterType,
tail_info = {NextOffset, empty},
current_epoch = Epoch}});
[#seg_info{file = Filename,
index = IdxFilename,
size = Size,
last =
#chunk_info{epoch = LastEpoch,
timestamp = LastTs,
id = LastChId,
num = LastNum}}
| _] = Infos ->
[#seg_info{first = #chunk_info{id = FstChId,
timestamp = FstTs}} | _] =
lists:reverse(Infos),
%% assert epoch is same or larger
%% than last known epoch
case LastEpoch > Epoch of
true ->
exit({invalid_epoch, LastEpoch, Epoch});
_ ->
ok
end,
TailInfo = {LastChId + LastNum,
{LastEpoch, LastChId, LastTs}},
counters:put(Cnt, ?C_FIRST_OFFSET, FstChId),
counters:put(Cnt, ?C_FIRST_TIMESTAMP, FstTs),
counters:put(Cnt, ?C_OFFSET, LastChId + LastNum - 1),
counters:put(Cnt, ?C_SEGMENTS, length(Infos)),
?DEBUG("~s:~s/~b: next offset ~b first offset ~b",
[?MODULE,
?FUNCTION_NAME,
?FUNCTION_ARITY,
element(1, TailInfo),
FstChId]),
{ok, Fd} = open(Filename, ?FILE_OPTS_WRITE),
{ok, IdxFd} = open(IdxFilename, ?FILE_OPTS_WRITE),
{ok, Size} = file:position(Fd, Size),
ok = file:truncate(Fd),
{ok, _} = file:position(IdxFd, eof),
{ok, Size} = file:position(Fd, Size),
%% truncate segment to size in case there is trailing data
#?MODULE{cfg = Cfg,
mode =
#write{type = WriterType,
tail_info = TailInfo,
current_epoch = Epoch},
fd = Fd,
index_fd = IdxFd};
[#seg_info{file = Filename,
index = IdxFilename,
last = undefined}
| _] ->
%% the empty log case
{ok, Fd} = open(Filename, ?FILE_OPTS_WRITE),
{ok, IdxFd} = open(IdxFilename, ?FILE_OPTS_WRITE),
%% TODO: do we potentially need to truncate the segment
%% here too?
{ok, _} = file:position(Fd, eof),
{ok, _} = file:position(IdxFd, eof),
#?MODULE{cfg = Cfg,
mode =
#write{type = WriterType,
tail_info = {0, empty},
current_epoch = Epoch},
fd = Fd,
index_fd = IdxFd}
end.
-spec write([osiris:data()], state()) -> state().
write(Entries, State) when is_list(Entries) ->
Timestamp = erlang:system_time(millisecond),
write(Entries, ?CHNK_USER, Timestamp, <<>>, State).
-spec write([osiris:data()], integer(), state()) -> state().
write(Entries, Now, #?MODULE{mode = #write{}} = State)
when is_integer(Now) ->
write(Entries, ?CHNK_USER, Now, <<>>, State).
-spec write([osiris:data()],
chunk_type(),
osiris:timestamp(),
iodata(),
state()) ->
state().
write([_ | _] = Entries,
ChType,
Now,
Trailer,
#?MODULE{cfg = #cfg{},
fd = undefined,
mode = #write{}} =
State0) ->
%% we need to open a new segment here to ensure tracking chunk
%% is made before the one that triggers the new segment to be created
trigger_retention_eval(
write(Entries, ChType, Now, Trailer, open_new_segment(State0)));
write([_ | _] = Entries,
ChType,
Now,
Trailer,
#?MODULE{cfg = #cfg{},
mode =
#write{current_epoch = Epoch, tail_info = {Next, _}} =
_Write0} =
State0)
when is_integer(Now)
andalso is_integer(ChType) ->
%% The osiris writer always pass Entries in the reversed order
%% in order to avoid unnecessary lists rev|trav|ersals
{ChunkData, NumRecords} =
make_chunk(Entries, Trailer, ChType, Now, Epoch, Next),
write_chunk(ChunkData, ChType, Now, Epoch, NumRecords, State0);
write([], _ChType, _Now, _Writers, State) ->
State.
-spec accept_chunk(iodata(), state()) -> state().
accept_chunk([<<?MAGIC:4/unsigned,
?VERSION:4/unsigned,
ChType:8/unsigned,
_NumEntries:16/unsigned,
NumRecords:32/unsigned,
Timestamp:64/signed,
Epoch:64/unsigned,
Next:64/unsigned,
Crc:32/integer,
DataSize:32/unsigned,
_TrailerSize:32/unsigned,
_Reserved:32,
Data/binary>>
| DataParts] =
Chunk,
#?MODULE{cfg = #cfg{}, mode = #write{tail_info = {Next, _}}} =
State0) ->
DataAndTrailer = [Data | DataParts],
validate_crc(Next, Crc, part(DataSize, DataAndTrailer)),
%% assertion
% true = iolist_size(DataAndTrailer) == (DataSize + TrailerSize),
%% acceptors do no need to maintain writer state in memory so we pass
%% the empty map here instead of parsing the trailer
case write_chunk(Chunk, ChType, Timestamp, Epoch, NumRecords, State0) of
full ->
trigger_retention_eval(
accept_chunk(Chunk, open_new_segment(State0)));
State ->
State
end;
accept_chunk(Binary, State) when is_binary(Binary) ->
accept_chunk([Binary], State);
accept_chunk([<<?MAGIC:4/unsigned,
?VERSION:4/unsigned,
_ChType:8/unsigned,
_NumEntries:16/unsigned,
_NumRecords:32/unsigned,
_Timestamp:64/signed,
_Epoch:64/unsigned,
Next:64/unsigned,
_Crc:32/integer,
_/binary>>
| _] =
_Chunk,
#?MODULE{cfg = #cfg{},
mode = #write{tail_info = {ExpectedNext, _}}}) ->
exit({accept_chunk_out_of_order, Next, ExpectedNext}).
-spec next_offset(state()) -> offset().
next_offset(#?MODULE{mode = #write{tail_info = {Next, _}}}) ->
Next;
next_offset(#?MODULE{mode = #read{next_offset = Next}}) ->
Next.
-spec first_offset(state()) -> offset().
first_offset(#?MODULE{cfg = #cfg{counter = Cnt}}) ->
counters:get(Cnt, ?C_FIRST_OFFSET).
-spec first_timestamp(state()) -> osiris:timestamp().
first_timestamp(#?MODULE{cfg = #cfg{counter = Cnt}}) ->
counters:get(Cnt, ?C_FIRST_TIMESTAMP).
-spec tail_info(state()) -> osiris:tail_info().
tail_info(#?MODULE{mode = #write{tail_info = TailInfo}}) ->
TailInfo.
-spec is_open(state()) -> boolean().
is_open(#?MODULE{mode = #write{}, fd = Fd}) ->
Fd =/= undefined.
% -spec
-spec init_acceptor(range(), list(), config()) ->
state().
init_acceptor(Range, EpochOffsets0,
#{name := Name, dir := Dir} = Conf) ->
%% truncate to first common last epoch offset
%% * if the last local chunk offset has the same epoch but is lower
%% than the last chunk offset then just attach at next offset.
%% * if it is higher - truncate to last epoch offset
%% * if it has a higher epoch than last provided - truncate to last offset
%% of previous
%% sort them so that the highest epochs go first
EpochOffsets =
lists:reverse(
lists:sort(EpochOffsets0)),
%% then truncate to
SegInfos = build_log_overview(Dir),
?DEBUG("~s: ~s from epoch offsets: ~w range ~w",
[?MODULE, ?FUNCTION_NAME, EpochOffsets, Range]),
ok = truncate_to(Name, Range, EpochOffsets, SegInfos),
%% after truncation we can do normal init
InitOffset = case Range of
empty -> 0;
{O, _} -> O
end,
init(Conf#{initial_offset => InitOffset}, acceptor).
chunk_id_index_scan(IdxFile, ChunkId) when is_list(IdxFile) ->
Fd = open_index_read(IdxFile),
chunk_id_index_scan0(Fd, ChunkId).
chunk_id_index_scan0(Fd, ChunkId) ->
{ok, IdxPos} = file:position(Fd, cur),
case file:read(Fd, ?INDEX_RECORD_SIZE_B) of
{ok,
<<ChunkId:64/unsigned,
_Timestamp:64/signed,
Epoch:64/unsigned,
FilePos:32/unsigned,
_ChType:8/unsigned>>} ->
ok = file:close(Fd),
{ChunkId, Epoch, FilePos, IdxPos};
{ok, _} ->
chunk_id_index_scan0(Fd, ChunkId);
eof ->
ok = file:close(Fd),
eof
end.
delete_segment(#seg_info{file = File, index = Index}) ->
?DEBUG("osiris_log: deleting segment ~s in ~s",
[filename:basename(File), filename:dirname(File)]),
ok = file:delete(File),
ok = file:delete(Index),
ok.
truncate_to(_Name, _Range, _EpochOffsets, []) ->
%% the target log is empty
ok;
truncate_to(_Name, _Range, [], SegInfos) ->
%% ????? this means the entire log is out
[begin ok = delete_segment(I) end || I <- SegInfos],
ok;
truncate_to(Name, Range, [{E, ChId} | NextEOs], SegInfos) ->
case find_segment_for_offset(ChId, SegInfos) of
not_found ->
case lists:last(SegInfos) of
#seg_info{last = #chunk_info{epoch = E,
id = LastChId,
num = Num}}
when ChId > LastChId + Num ->
%% the last available local chunk id is smaller than the
%% sources last chunk id but is in the same epoch
%% check if there is any overlap
LastOffsLocal = case offset_range_from_segment_infos(SegInfos) of
empty -> 0;
{_, L} -> L
end,
FstOffsetRemote = case Range of
empty -> 0;
{F, _} -> F
end,
case LastOffsLocal < FstOffsetRemote of
true ->
%% there is no overlap, need to delete all
%% local segments
[begin ok = delete_segment(I) end || I <- SegInfos],
ok;
false ->
%% there is overlap
%% no truncation needed
ok
end;
_ ->
truncate_to(Name, Range, NextEOs, SegInfos)
end;
{end_of_log, _Info} ->
ok;
{found, #seg_info{file = File, index = Idx}} ->
?DEBUG("osiris_log: ~s on node ~s truncating to chunk "
"id ~b in epoch ~b",
[Name, node(), ChId, E]),
%% this is the inclusive case
%% next offset needs to be a chunk offset
%% if it is not found we know the offset requested isn't a chunk
%% id and thus isn't valid
case chunk_id_index_scan(Idx, ChId) of
{ChId, E, Pos, IdxPos} when is_integer(Pos) ->
%% the Chunk id was found and has the right epoch
%% lets truncate to this point
%% FilePos could be eof here which means the next offset
{ok, Fd} = file:open(File, [read, write, binary, raw]),
{ok, IdxFd} = file:open(Idx, [read, write, binary, raw]),
{_ChType, ChId, E, _Num, Size, TSize} =
header_info(Fd, Pos),
%% position at end of chunk
{ok, _Pos} = file:position(Fd, {cur, Size + TSize}),
ok = file:truncate(Fd),
{ok, _} =
file:position(IdxFd, IdxPos + ?INDEX_RECORD_SIZE_B),
ok = file:truncate(IdxFd),
ok = file:close(Fd),
ok = file:close(IdxFd),
%% delete all segments with a first offset larger then ChId
[begin ok = delete_segment(I) end
|| I <- SegInfos, I#seg_info.first#chunk_info.id > ChId],
ok;
_ ->
truncate_to(Name, Range, NextEOs, SegInfos)
end
end.
-spec init_data_reader(osiris:tail_info(), config()) ->
{ok, state()} |
{error,
{offset_out_of_range,
empty | {offset(), offset()}}} |
{error,
{invalid_last_offset_epoch, offset(), offset()}}.
init_data_reader({StartChunkId, PrevEOT}, #{dir := Dir} = Config) ->
SegInfos = build_log_overview(Dir),
Range = offset_range_from_segment_infos(SegInfos),
?DEBUG("osiris_segment:init_data_reader/2 at ~b prev "
"~w local range: ~w",
[StartChunkId, PrevEOT, Range]),
%% Invariant: there is always at least one segment left on disk
case Range of
{FstOffs, LastOffs}
when StartChunkId < FstOffs
orelse StartChunkId > LastOffs + 1 ->
{error, {offset_out_of_range, Range}};
empty when StartChunkId > 0 ->
{error, {offset_out_of_range, Range}};
_ when PrevEOT == empty ->
%% this assumes the offset is in range
%% first we need to validate PrevEO
{ok, init_data_reader_from(
StartChunkId,
find_segment_for_offset(StartChunkId, SegInfos),
Config)};
_ ->
{PrevEpoch, PrevChunkId, _PrevTs} = PrevEOT,
case check_chunk_has_expected_epoch(PrevChunkId, PrevEpoch, SegInfos) of
ok ->
{ok, init_data_reader_from(
StartChunkId,
find_segment_for_offset(StartChunkId, SegInfos),
Config)};
{error, _} = Err ->
Err
end
end.
check_chunk_has_expected_epoch(ChunkId, Epoch, SegInfos) ->
case find_segment_for_offset(ChunkId, SegInfos) of
not_found ->
%% this is unexpected and thus an error
{error,
{invalid_last_offset_epoch, Epoch, unknown}};
{found, SegmentInfo = #seg_info{file = _PrevSeg}} ->
%% prev segment exists, does it have the correct
%% epoch?
case scan_idx(ChunkId, SegmentInfo) of
{ChunkId, Epoch, _PrevPos} ->
ok;
{ChunkId, OtherEpoch, _} ->
{error,
{invalid_last_offset_epoch, Epoch, OtherEpoch}}
end
end.
init_data_reader_at(ChunkId, FilePos, File,
#{dir := Dir, name := Name,
readers_counter_fun := CountersFun} = Config) ->
{ok, Fd} = file:open(File, [raw, binary, read]),
{ok, FilePos} = file:position(Fd, FilePos),
Cnt = make_counter(Config),
counters:put(Cnt, ?C_OFFSET, ChunkId - 1),
CountersFun(1),
#?MODULE{cfg =
#cfg{directory = Dir,
counter = Cnt,
name = Name,
readers_counter_fun = CountersFun,
first_offset_fun = fun (_) -> ok end},
mode =
#read{type = data,
offset_ref = maps:get(offset_ref, Config, undefined),
next_offset = ChunkId,
chunk_selector = all,
transport = maps:get(transport, Config, tcp)},
fd = Fd}.
init_data_reader_from(ChunkId,
{end_of_log, #seg_info{file = File,
last = LastChunk}},
Config) ->
{ChunkId, AttachPos} = next_location(LastChunk),
init_data_reader_at(ChunkId, AttachPos, File, Config);
init_data_reader_from(ChunkId,
{found, #seg_info{file = File} = SegInfo},
Config) ->
{ChunkId, _Epoch, FilePos} = scan_idx(ChunkId, SegInfo),
init_data_reader_at(ChunkId, FilePos, File, Config).
%% @doc Initialise a new offset reader
%% @param OffsetSpec specifies where in the log to attach the reader
%% `first': Attach at first available offset.
%% `last': Attach at the last available chunk offset or the next available offset
%% if the log is empty.
%% `next': Attach to the next chunk offset to be written.
%% `{abs, offset()}': Attach at the provided offset. If this offset does not exist
%% in the log it will error with `{error, {offset_out_of_range, Range}}'
%% `offset()': Like `{abs, offset()}' but instead of erroring it will fall back
%% to `first' (if lower than first offset in log) or `nextl if higher than
%% last offset in log.
%% @param Config The configuration. Requires the `dir' key.
%% @returns `{ok, state()} | {error, Error}' when error can be
%% `{offset_out_of_range, empty | {From :: offset(), To :: offset()}}'
%% @end
-spec init_offset_reader(OffsetSpec :: offset_spec(),
Config :: config()) ->
{ok, state()} |
{error,
{offset_out_of_range,
empty | {From :: offset(), To :: offset()}}} |
{error, {invalid_chunk_header, term()}}.
init_offset_reader(OffsetSpec, Conf) ->
try
init_offset_reader0(OffsetSpec, Conf)
catch
missing_file ->
init_offset_reader0(OffsetSpec, Conf)
end.
init_offset_reader0({abs, Offs}, #{dir := Dir} = Conf) ->
Range = offset_range_from_segment_infos(build_log_overview(Dir)),
case Range of
empty ->
{error, {offset_out_of_range, Range}};
{S, E} when Offs < S orelse Offs > E ->
{error, {offset_out_of_range, Range}};
_ ->
%% it is in range, convert to standard offset
init_offset_reader0(Offs, Conf)
end;
init_offset_reader0({timestamp, Ts}, #{dir := Dir} = Conf) ->
case build_log_overview(Dir) of
[] ->
init_offset_reader0(next, Conf);
[#seg_info{file = SegmentFile,
first = #chunk_info{timestamp = Fst,
pos = FilePos,
id = ChunkId}} | _]
when is_integer(Fst) andalso Fst > Ts ->
%% timestamp is lower than the first timestamp available
open_offset_reader_at(SegmentFile, ChunkId, FilePos, Conf);
SegInfos ->
case lists:search(fun (#seg_info{first = #chunk_info{timestamp = F},
last = #chunk_info{timestamp = L}})
when is_integer(F)
andalso is_integer(L) ->
Ts >= F andalso Ts =< L;
(_) ->
false
end,
SegInfos)
of
{value, #seg_info{file = SegmentFile} = Info} ->
%% segment was found, now we need to scan index to
%% find nearest offset
{ChunkId, FilePos} = chunk_location_for_timestamp(Info, Ts),
open_offset_reader_at(SegmentFile, ChunkId, FilePos, Conf);
false ->
%% segment was not found, attach next
%% this should be rare so no need to call the more optimal
%% open_offset_reader_at/4 function
init_offset_reader0(next, Conf)
end
end;
init_offset_reader0(first, #{dir := Dir} = Conf) ->
case build_log_overview(Dir) of
[#seg_info{file = File,
first = undefined}] ->
%% empty log, attach at 0
open_offset_reader_at(File, 0, ?LOG_HEADER_SIZE, Conf);
[#seg_info{file = File,
first = #chunk_info{id = FirstChunkId,
pos = FilePos}} | _] ->
open_offset_reader_at(File, FirstChunkId, FilePos, Conf);
_ ->
exit(no_segments_found)
end;
init_offset_reader0(next, #{dir := Dir} = Conf) ->
SegInfos = build_log_overview(Dir),
case lists:reverse(SegInfos) of
[#seg_info{file = File,
last = LastChunk} | _] ->
{NextChunkId, FilePos} = next_location(LastChunk),
open_offset_reader_at(File, NextChunkId, FilePos, Conf);
_ ->
exit(no_segments_found)
end;
init_offset_reader0(last, #{dir := Dir} = Conf) ->
SegInfos = build_log_overview(Dir),
case lists:reverse(SegInfos) of
[#seg_info{file = File,
last = undefined}] ->
%% empty log, attach at 0
open_offset_reader_at(File, 0, ?LOG_HEADER_SIZE, Conf);
[#seg_info{file = File,
last = #chunk_info{type = ?CHNK_USER,