Source file storage.ml
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
open Utils
open Lwt.Syntax
open Result_lwt.Syntax
module Int64 = Stdint.Int64
module B = Mmap.Buffer
type mode = Reader | Writer
type config =
{ head_string : string;
version : int;
bytes_per_cell : int;
max_index : Index.t;
}
let check_head_string head_string =
if String.length head_string <> 20 then
invalid_arg (Printf.sprintf "invalid head_string size: %S" head_string)
let check_config config =
check_head_string config.head_string;
if config.bytes_per_cell < 4 then invalid_arg "too small bytes_pre_cell";
if config.bytes_per_cell >= 0x10000 then invalid_arg "too large bytes_pre_cell";
if not (0 <= config.version
&& config.version <= Stdint.Uint32.(to_int max_int)) then
invalid_arg "invalid version";
if Index.to_int config.max_index <= 0 then invalid_arg "invalid max_index"
type writer_key = string
type storage = {
mutable array : Mmap.t ;
start_index : Index.t ;
mutable current_length : Index.t ;
mutable mapped_length : Index.t ;
mutable last_root_index : Index.t option ;
fd : Lwt_unix.file_descr ;
pos : int ;
mode : mode ;
version : int ;
head_string : string ;
bytes_per_cell : int ;
max_index : Index.t ;
resize_step : Index.t ;
fn : string ;
mutable closed : bool ;
mutable last_msynced_next_index : Index.t ;
mutable writer_key : writer_key option
}
type t = storage
let set_last_root_index t x = t.last_root_index <- x
let get_last_root_index t = t.last_root_index
let set_current_length t x = t.current_length <- x
let get_current_length t = t.current_length
let size t = Stdint.Int64.(Index.to_int64 (get_current_length t ) * of_int t.bytes_per_cell)
let filename t = t.fn
let mode t = t.mode
let version t = t.version
let start_index t = t.start_index
let writer_key t = t.writer_key
let msync t =
if t.mode = Writer then Mmap.msync_lwt t.array else Lwt.return_unit
let msync2 t ~off ~len =
if t.mode = Writer then begin
if len = 0 then Lwt.return_unit
else
let* () = Log.lwt_info "msync off:%a len:%d@." Index.pp off len in
let off = Index.to_int off * t.bytes_per_cell + t.pos in
let len = len * t.bytes_per_cell in
Mmap.msync2_lwt t.array ~off ~len
end
else Lwt.return_unit
let do_madvise_read_ahead =
let b = Envconf.madvise_read_ahead in
if b then Log.fatal "Configuration: madvise(READ_AHEAD)";
b
let make_array ~bytes_per_cell fd ~pos mapped_length =
let res = Mmap.make fd ~pos ~shared:true (bytes_per_cell * mapped_length) in
if not do_madvise_read_ahead then begin
let (), t = with_time (fun () -> Mmap.madvise_random res) in
Log.debug "madvise len=%d %a" mapped_length Mtime.Span.pp t
end;
res
type Error.t += Index_overflow of t
let () = Error.register_printer (function
| Index_overflow t -> Some ("Plebeia index overflow for " ^ t.fn)
| _ -> None)
let resize required t =
let open Index in
assert (t.mode = Writer);
assert (required > t.mapped_length);
let new_mapped_length =
((required - t.mapped_length) / t.resize_step + Index.one) * t.resize_step + t.mapped_length
in
if new_mapped_length < t.mapped_length || t.max_index < new_mapped_length
then begin
Log.notice "Storage: size overflow!";
Error (Index_overflow t)
end else begin
Log.notice "Storage: resizing to %Ld" (Index.to_int64 new_mapped_length);
let (), sec = with_time (fun () ->
let array =
make_array ~bytes_per_cell:t.bytes_per_cell
(Lwt_unix.unix_file_descr t.fd) ~pos:t.pos
(Index.to_int new_mapped_length)
in
t.array <- array;
t.mapped_length <- new_mapped_length)
in
Log.notice "Storage: resized to %Ld in %a" (Index.to_int64 new_mapped_length) Mtime.Span.pp sec;
Ok ()
end
let may_resize required t =
if t.mapped_length < required then
resize required t
else Ok ()
let get_bytes t i n =
let i = Index.to_int i in
Mmap.get_buffer ~off:(i * t.bytes_per_cell) ~len:n t.array
let get_cell t i = get_bytes t i t.bytes_per_cell
let get_cell2 t i = get_bytes t i (t.bytes_per_cell * 2)
let new_index c =
let i = c.current_length in
let i' = Index.succ i in
if i' < i || c.max_index < i' then Error (Index_overflow c)
else begin
c.current_length <- i';
match may_resize i' c with
| Ok () -> Ok i
| Error _ as e ->
c.current_length <- i;
e
end
let new_indices =
fun c n ->
let maximum_new_indices = 65536 + 6 / c.bytes_per_cell + 1 in
if not (0 < n && n <= maximum_new_indices) then invalid_arg "Plebeia: new_indices: invalid size";
let i = c.current_length in
let i' = Index.(i + Unsafe.of_int n) in
if i' < i || c.max_index < i' then Error (Index_overflow c)
else begin
c.current_length <- i';
match may_resize i' c with
| Ok () -> Ok i
| Error _ as e ->
c.current_length <- i;
e
end
let check_writer_key = Header.check_writer_key
let make_writer_key () =
let rng = Random.State.make_self_init () in
String.init 32 (fun _ -> Char.chr @@ Random.State.int rng 256)
let make_new_writer_key ts =
let rec loop () =
let key = make_writer_key () in
let rec check = function
| [] -> Lwt.return true
| t::ts ->
let* res = check_writer_key t key in
match res with
| Error _ -> check ts
| Ok `BadKey -> check ts
| Ok `GoodKey -> Lwt.return false
in
let* res = check ts in
if res then Lwt.return key
else loop ()
in
loop ()
let commit = Header.commit
let flush = Header.flush
let get_start_index bytes_per_cell =
let =
(256 + bytes_per_cell - 1) / bytes_per_cell
in
Index.Unsafe.of_int cells_for_header
let default_resize_step_bytes =
try
let n = int_of_string @@ Sys.getenv "PLEBEIA_RESIZE_STEP_BYTES" in
Log.fatal "Configuration: resize_step_bytes=%d" n;
n
with
| Not_found -> 1 lsl 30
| _ -> Stdlib.failwith "PLEBEIA_RESIZE_STEP_BYTES=<int>"
let create
?length
?(resize_step_bytes=default_resize_step_bytes)
~config
~key
fn =
let pos = 0 in
let writer_key = key in
check_config config;
let* fd = Lwt_unix.openfile fn [O_CREAT; O_EXCL; O_RDWR] 0o644 in
let resize_step = Index.Unsafe.of_int (resize_step_bytes / config.bytes_per_cell) in
let mapped_length =
match length with
| None -> resize_step
| Some i -> i
in
let array =
make_array
~bytes_per_cell:config.bytes_per_cell
(Lwt_unix.unix_file_descr fd)
~pos (Index.to_int mapped_length)
in
let start_index = get_start_index config.bytes_per_cell in
let t =
{ array ;
mapped_length ;
start_index ;
current_length = start_index ;
last_root_index = None ;
fd ;
pos ;
mode= Writer;
fn ;
closed = false ;
version = config.version;
head_string = config.head_string;
bytes_per_cell = config.bytes_per_cell;
max_index = config.max_index;
resize_step;
last_msynced_next_index = start_index ;
writer_key = Some writer_key;
}
in
Header.write_config t;
let+ () = Header.flush t in
t
let null =
let fd = Lwt_unix.stdin in
let array = Mmap.null in
{ array ;
mapped_length = Index.zero ;
start_index = Index.zero ;
current_length = Index.zero ;
last_root_index = None ;
fd ;
pos = 0;
mode= Reader ;
fn = "null";
closed = true ;
version = 0;
head_string = "DUMMY";
bytes_per_cell = 32;
max_index = Index.max_int;
resize_step = Index.one;
last_msynced_next_index = Index.zero ;
writer_key = None;
}
let is_null t = t == null
let override_version t version =
let t = { t with version } in
Header.write_config t
let truncate ?length t =
let* () = msync t in
let* () = Lwt_unix.ftruncate t.fd t.pos in
let mapped_length =
match length with
| None -> t.resize_step
| Some i ->
match Sys.int_size with
| 31 | 32 -> Index.Unsafe.of_int i
| 63 ->
if i > Index.(Unsafe.to_int max_int) then failwithf "create: too large: %d@." i
else Index.Unsafe.of_int i
| _ -> assert false
in
let array =
make_array ~bytes_per_cell:t.bytes_per_cell
(Lwt_unix.unix_file_descr t.fd) ~pos:t.pos
(Index.to_int mapped_length)
in
Header.write_config t;
t.array <- array;
t.mapped_length <- mapped_length;
t.current_length <- t.start_index;
t.last_root_index <- None ;
Header.flush t
let load_config ~pos fn =
let* fd = Lwt_unix.openfile fn [O_RDWR] 0o644 in
let array =
make_array ~bytes_per_cell:32 (Lwt_unix.unix_file_descr fd)
~pos:pos 1
in
let config = Header.read_config array in
let+ () = Lwt_unix.close fd in
config
type Error.t += No_such_file of string
let () = Error.register_printer (function
| No_such_file s -> Some ("no such file: " ^ s)
| _ -> None)
let open_existing_for_read fn =
let mode = Reader in
let writer_key = None in
let pos = 0 in
let* exists = Lwt_unix.file_exists fn in
if not exists then Lwt.return_error (No_such_file fn)
else
let* config = load_config ~pos fn in
check_config config;
let* fd = Lwt_unix.openfile fn [O_RDWR] 0o644 in
let* st = Lwt_unix.LargeFile.fstat fd in
let sz = Int64.sub st.Unix.LargeFile.st_size (Int64.of_int pos) in
assert (Int64.rem sz (Int64.of_int config.bytes_per_cell) = 0L);
let cells = Int64.(sz / Int64.of_int config.bytes_per_cell) in
if cells > Index.to_int64 config.max_index then assert false;
let mapped_length = Index.of_int64 cells in
let array =
make_array
~bytes_per_cell:config.bytes_per_cell
(Lwt_unix.unix_file_descr fd)
~pos (Index.to_int mapped_length)
in
let start_index = get_start_index config.bytes_per_cell in
let resize_step =
let resize_step_bytes = default_resize_step_bytes in
Index.Unsafe.of_int (resize_step_bytes / config.bytes_per_cell)
in
let* res_disk = Header.read_array_disk_sync fd array in
let*=? current_length, last_root_index =
match res_disk with
| None -> Lwt.return_error Header.Header_broken
| Some (`NoKey, h_disk_sync) ->
Lwt.return_ok (h_disk_sync.last_next_index, h_disk_sync.last_root_index)
| Some _ -> assert false
in
let t =
{ array ;
start_index ;
mapped_length ;
current_length;
last_root_index;
fd = fd ;
pos ;
mode ;
fn ;
version = config.version;
head_string = config.head_string;
bytes_per_cell = config.bytes_per_cell;
max_index = config.max_index;
resize_step ;
closed = false ;
last_msynced_next_index = current_length ;
writer_key
}
in
Lwt.return_ok (config, t)
let open_existing_for_write
?(resize_step_bytes=default_resize_step_bytes)
~key
fn
=
let pos = 0 in
let mode = Writer in
let writer_key = key in
let* exists = Lwt_unix.file_exists fn in
if not exists then Lwt.return_none
else
let* config = load_config ~pos fn in
check_config config;
let* fd = Lwt_unix.openfile fn [O_RDWR] 0o644 in
let* st = Lwt_unix.LargeFile.fstat fd in
let sz = Int64.sub st.Unix.LargeFile.st_size (Int64.of_int pos) in
assert (Int64.rem sz (Int64.of_int config.bytes_per_cell) = 0L);
let cells = Int64.(sz / Int64.of_int config.bytes_per_cell) in
if cells > Index.to_int64 config.max_index then assert false;
let mapped_length = Index.of_int64 cells in
let array =
make_array
~bytes_per_cell:config.bytes_per_cell
(Lwt_unix.unix_file_descr fd)
~pos (Index.to_int mapped_length)
in
let start_index = get_start_index config.bytes_per_cell in
let resize_step = Index.Unsafe.of_int (resize_step_bytes / config.bytes_per_cell) in
let* res_disk = Header.read_array_disk_sync fd array in
let* writer_key, current_length, last_root_index =
let+ res_process = Header.read_array_process_sync ~key:writer_key fd array in
match res_disk, res_process with
| None, _ ->
failwithf "Failed to load header: the disk sync header is broken"
| _, None ->
failwithf "Failed to load header: the process sync header is broken"
| Some ((`BadKey | `GoodKey), _), _ -> assert false
| Some (`NoKey, h_disk_sync), Some (_, h_process_sync) ->
match
compare h_disk_sync.Header.last_next_index h_process_sync.Header.last_next_index,
compare h_disk_sync.Header.last_root_index h_process_sync.Header.last_root_index
with
| 0, 0 -> Some writer_key, h_disk_sync.last_next_index, h_disk_sync.last_root_index
| 1, _ | _, 1 ->
failwithf "Header invariant is broken: the header for the process sync is older than the header for the disk sync"
| _ ->
let diff = Index.(-) h_process_sync.last_next_index h_disk_sync.last_next_index in
Log.warning "A Plebeia writer crash was detected. %a disk cells are skipped." Index.pp diff;
Some writer_key, h_process_sync.last_next_index, h_disk_sync.last_root_index
in
let t =
{ array ;
start_index ;
mapped_length ;
current_length;
last_root_index;
fd = fd ;
pos ;
mode ;
fn ;
version = config.version;
head_string = config.head_string;
bytes_per_cell = config.bytes_per_cell;
max_index = config.max_index;
resize_step ;
closed = false ;
last_msynced_next_index = current_length ;
writer_key
}
in
let+ () = Header.flush t in
Some (config, t)
let open_for_write
?resize_step_bytes
~config
~key
fn =
let* res = open_existing_for_write ?resize_step_bytes ~key fn in
match res with
| Some (config', storage) ->
if config <> config' then invalid_arg "Storage.open_for_write: config mismatch";
Lwt.return storage
| None ->
create ?resize_step_bytes ~config ~key fn
let close ({ fd ; mode ; closed ; _ } as t) =
if closed then Lwt.return_unit
else begin
let* () =
if mode <> Reader then Header.flush t
else Lwt.return_unit
in
let+ () = Lwt_unix.close fd in
t.closed <- true
end
let reopen_with t h =
if h.Header.last_next_index = t.current_length
&& h.last_root_index = t.last_root_index then begin
Lwt.return_unit
end else
let* st = Lwt_unix.LargeFile.fstat t.fd in
let sz = Int64.sub st.Unix.LargeFile.st_size (Int64.of_int t.pos) in
assert (Int64.rem sz (Int64.of_int t.bytes_per_cell) = 0L);
let cells = Int64.(sz / (Int64.of_int t.bytes_per_cell)) in
if cells > Index.to_int64 t.max_index then assert false;
let mapped_length = Index.of_int64 cells in
if mapped_length <> t.mapped_length then begin
t.array <- make_array
~bytes_per_cell:t.bytes_per_cell
(Lwt_unix.unix_file_descr t.fd)
~pos:t.pos (Index.to_int mapped_length);
t.mapped_length <- mapped_length;
end;
t.current_length <- h.Header.last_next_index;
t.last_root_index <- h.Header.last_root_index;
Lwt.return_unit
type Error.t += Invalid_writer_key
let () = Error.register_printer (function
| Invalid_writer_key -> Some "invalid writer key"
| _ -> None)
type Error.t += Not_reader
let () = Error.register_printer (function
| Not_reader -> Some "not reader"
| _ -> None)
let enable_process_sync t writer_key =
match t.mode with
| Reader ->
t.writer_key <- Some writer_key;
let+ res = Header.read_process_sync t in
(match res with
| Some (`GoodKey, _) -> Ok ()
| _ ->
t.writer_key <- None;
Error Invalid_writer_key)
| Writer -> Lwt.return_error Not_reader
let update_reader t =
match t.mode with
| Writer -> Lwt.return_unit
| Reader ->
match t.writer_key with
| None ->
let* res = Header.read_disk_sync t in
begin match res with
| None -> failwithf "Failed to load header"
| Some h -> reopen_with t h
end
| Some _ ->
let* res = Header.read_process_sync t in
match res with
| None -> failwithf "Failed to load header"
| Some (_, h) ->
reopen_with t h
module Chunk = struct
let max_bytes_per_chunk = 65535
let ncells bytes_per_cell size = (size + 6 + bytes_per_cell - 1) / bytes_per_cell
let storage last_index =
let buf =
Mmap.get_buffer
~off:((last_index + 1) * storage.bytes_per_cell - 6)
~len:6 storage.array
in
let cdr = B.get_index buf 2 in
let size = B.get_uint16 buf 0 in
(cdr, size)
let get_chunk storage last_index =
let cdr, size = get_footer_fields storage (Index.to_int last_index) in
let ncells = ncells storage.bytes_per_cell size in
let first_index = Index.(last_index - Unsafe.of_int ncells + one) in
(get_bytes storage first_index size, size, cdr)
let get_chunks storage last_index =
let rec aux (bufs, size) last_index =
let buf, bytes, cdr = get_chunk storage last_index in
let bufs = buf :: bufs in
let size = size + bytes in
if cdr = Index.zero then (bufs, size)
else aux (bufs, size) cdr
in
aux ([], 0) last_index
let string_of_cstructs bufs =
String.concat "" @@ List.map B.to_string bufs
let read t i = string_of_cstructs @@ fst @@ get_chunks t i
let write_to_chunk storage cdr s off len =
if mode storage = Reader then invalid_arg "Reader cannot write";
assert (String.length s >= off + len);
assert (len <= max_bytes_per_chunk);
let bytes_per_cell = storage.bytes_per_cell in
let ncells = ncells bytes_per_cell len in
let cdr_pos = ncells * bytes_per_cell - 4 in
let size_pos = cdr_pos - 2 in
let+? i = new_indices storage ncells in
let last_index = Index.(i + Unsafe.of_int ncells - one) in
let chunk = get_bytes storage i (bytes_per_cell * ncells) in
B.blit_from_string s off chunk 0 len;
B.set_uint16 chunk size_pos len;
B.set_index chunk cdr_pos cdr;
last_index
let write storage s =
if mode storage = Reader then invalid_arg "Reader cannot write";
let rec f off remain cdr =
let len = if remain > max_bytes_per_chunk then max_bytes_per_chunk else remain in
let*? cdr' = write_to_chunk storage cdr s off len in
let off' = off + len in
let remain' = remain - len in
if remain' > 0 then f off' remain' cdr'
else Ok cdr'
in
f 0 (String.length s) Index.zero
let test_write_read st storage =
let size = Random.State.int st (65536 * 5) in
let s = String.init size @@ fun i -> Char.chr (Char.code 'A' + i mod 20) in
let i = from_Ok @@ write storage s in
let s' = string_of_cstructs @@ fst @@ get_chunks storage i in
if (s <> s') then begin prerr_endline s; prerr_endline s' end;
assert (s = s')
end
module Internal = struct
let msync = msync
let set_current_length = set_current_length
end