forked from sky-big/RabbitMQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_handle_cache.erl
1832 lines (1591 loc) · 71.9 KB
/
file_handle_cache.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
%% The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (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.mozilla.org/MPL/
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
%% The Original Code is RabbitMQ.
%%
%% The Initial Developer of the Original Code is GoPivotal, Inc.
%% Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved.
%%
-module(file_handle_cache).
%% 主要作用是管理每个进程拥有的文件描述符数量,确保当前RabbitMQ系统的文件描述符不超过上限
%% A File Handle Cache
%%
%% This extends a subset of the functionality of the Erlang file
%% module. In the below, we use "file handle" to specifically refer to
%% file handles, and "file descriptor" to refer to descriptors which
%% are not file handles, e.g. sockets.
%%
%% Some constraints
%% 1) This supports one writer, multiple readers per file. Nothing
%% else.
%% 2) Do not open the same file from different processes. Bad things
%% may happen, especially for writes.
%% 3) Writes are all appends. You cannot write to the middle of a
%% file, although you can truncate and then append if you want.
%% 4) There are read and write buffers. Feel free to use the read_ahead
%% mode, but beware of the interaction between that buffer and the write
%% buffer.
%%
%% Some benefits
%% 1) You do not have to remember to call sync before close
%% 2) Buffering is much more flexible than with the plain file module,
%% and you can control when the buffer gets flushed out. This means
%% that you can rely on reads-after-writes working, without having to
%% call the expensive sync.
%% 3) Unnecessary calls to position and sync get optimised out.
%% 4) You can find out what your 'real' offset is, and what your
%% 'virtual' offset is (i.e. where the hdl really is, and where it
%% would be after the write buffer is written out).
%%
%% There is also a server component which serves to limit the number
%% of open file descriptors. This is a hard limit: the server
%% component will ensure that clients do not have more file
%% descriptors open than it's configured to allow.
%%
%% On open, the client requests permission from the server to open the
%% required number of file handles. The server may ask the client to
%% close other file handles that it has open, or it may queue the
%% request and ask other clients to close file handles they have open
%% in order to satisfy the request. Requests are always satisfied in
%% the order they arrive, even if a latter request (for a small number
%% of file handles) can be satisfied before an earlier request (for a
%% larger number of file handles). On close, the client sends a
%% message to the server. These messages allow the server to keep
%% track of the number of open handles. The client also keeps a
%% gb_tree which is updated on every use of a file handle, mapping the
%% time at which the file handle was last used (timestamp) to the
%% handle. Thus the smallest key in this tree maps to the file handle
%% that has not been used for the longest amount of time. This
%% smallest key is included in the messages to the server. As such,
%% the server keeps track of when the least recently used file handle
%% was used *at the point of the most recent open or close* by each
%% client.
%%
%% Note that this data can go very out of date, by the client using
%% the least recently used handle.
%%
%% When the limit is exceeded (i.e. the number of open file handles is
%% at the limit and there are pending 'open' requests), the server
%% calculates the average age of the last reported least recently used
%% file handle of all the clients. It then tells all the clients to
%% close any handles not used for longer than this average, by
%% invoking the callback the client registered. The client should
%% receive this message and pass it into
%% set_maximum_since_use/1. However, it is highly possible this age
%% will be greater than the ages of all the handles the client knows
%% of because the client has used its file handles in the mean
%% time. Thus at this point the client reports to the server the
%% current timestamp at which its least recently used file handle was
%% last used. The server will check two seconds later that either it
%% is back under the limit, in which case all is well again, or if
%% not, it will calculate a new average age. Its data will be much
%% more recent now, and so it is very likely that when this is
%% communicated to the clients, the clients will close file handles.
%% (In extreme cases, where it's very likely that all clients have
%% used their open handles since they last sent in an update, which
%% would mean that the average will never cause any file handles to
%% be closed, the server can send out an average age of 0, resulting
%% in all available clients closing all their file handles.)
%%
%% Care is taken to ensure that (a) processes which are blocked
%% waiting for file descriptors to become available are not sent
%% requests to close file handles; and (b) given it is known how many
%% file handles a process has open, when the average age is forced to
%% 0, close messages are only sent to enough processes to release the
%% correct number of file handles and the list of processes is
%% randomly shuffled. This ensures we don't cause processes to
%% needlessly close file handles, and ensures that we don't always
%% make such requests of the same processes.
%%
%% The advantage of this scheme is that there is only communication
%% from the client to the server on open, close, and when in the
%% process of trying to reduce file handle usage. There is no
%% communication from the client to the server on normal file handle
%% operations. This scheme forms a feed-back loop - the server does
%% not care which file handles are closed, just that some are, and it
%% checks this repeatedly when over the limit.
%%
%% Handles which are closed as a result of the server are put into a
%% "soft-closed" state in which the handle is closed (data flushed out
%% and sync'd first) but the state is maintained. The handle will be
%% fully reopened again as soon as needed, thus users of this library
%% do not need to worry about their handles being closed by the server
%% - reopening them when necessary is handled transparently.
%%
%% The server also supports obtain, release and transfer. obtain/{0,1}
%% blocks until a file descriptor is available, at which point the
%% requesting process is considered to 'own' more descriptor(s).
%% release/{0,1} is the inverse operation and releases previously obtained
%% descriptor(s). transfer/{1,2} transfers ownership of file descriptor(s)
%% between processes. It is non-blocking. Obtain has a
%% lower limit, set by the ?OBTAIN_LIMIT/1 macro. File handles can use
%% the entire limit, but will be evicted by obtain calls up to the
%% point at which no more obtain calls can be satisfied by the obtains
%% limit. Thus there will always be some capacity available for file
%% handles. Processes that use obtain are never asked to return them,
%% and they are not managed in any way by the server. It is simply a
%% mechanism to ensure that processes that need file descriptors such
%% as sockets can do so in such a way that the overall number of open
%% file descriptors is managed.
%%
%% The callers of register_callback/3, obtain, and the argument of
%% transfer are monitored, reducing the count of handles in use
%% appropriately when the processes terminate.
-behaviour(gen_server2).
-export([register_callback/3]).
-export([open/3, close/1, read/2, append/2, needs_sync/1, sync/1, position/2,
truncate/1, current_virtual_offset/1, current_raw_offset/1, flush/1,
copy/3, set_maximum_since_use/1, delete/1, clear/1]).
-export([obtain/0, obtain/1, release/0, release/1, transfer/1, transfer/2,
set_limit/1, get_limit/0, info_keys/0, with_handle/1, with_handle/2,
info/0, info/1]).
-export([ulimit/0]).
-export([start_link/0, start_link/2, init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3, prioritise_cast/3]).
-define(SERVER, ?MODULE).
-define(RESERVED_FOR_OTHERS, 100).
-define(FILE_HANDLES_LIMIT_OTHER, 1024).
-define(FILE_HANDLES_CHECK_INTERVAL, 2000).
-define(OBTAIN_LIMIT(LIMIT), trunc((LIMIT * 0.9) - 2)). %% 根据LIMIT个能够打开的文件句柄上限得到当前RabbitMQ系统中能够obtain上限
-define(CLIENT_ETS_TABLE, file_handle_cache_client). %% 保存客户端状态的ETS表名
-define(ELDERS_ETS_TABLE, file_handle_cache_elders).
%%----------------------------------------------------------------------------
%% 一个文件的读写状态数据结构
-record(file,
{ reader_count, %% 文件的读者数量
has_writer %% 判断是否有写数据者
}).
%% 一个文件的处理句柄数据结构
-record(handle,
{ hdl, %% prim_file打开文件返回的文件句柄
offset, %% 当前实际的读取到文件的字符偏移量,实际就是当前读取到的文件字符位置
is_dirty,
write_buffer_size, %%
write_buffer_size_limit, %% 当前句柄写缓存的最大限制
write_buffer, %% 当前句柄要写的缓存
read_buffer, %% 上次读取的字符串缓存
read_buffer_pos, %% 上次读取的时候实际读取到的字符串pos位置
read_buffer_rem, %% Num of bytes from pos to end(保存的是num个字节从pos到文件结束)(上次读取的字符串数量 - read_buffer_pos,即上次读取的数据还剩余的数据大小)
read_buffer_size, %% Next size of read buffer to use(下一个要读取的缓存大小)
read_buffer_size_limit, %% Max size of read buffer to use(最大读取缓存的大小,根据参数设置的)
read_buffer_usage, %% Bytes we have read from it, for tuning(上次读取的数据中已经读取的数据大小)
at_eof, %% 是否达到文件最后
path, %% 当前操作文件的绝对路径
mode, %% 当前操作文件的操作类型列表
options, %% 当前句柄操作配置的参数
is_write, %% 当前句柄是否是写操作
is_read, %% 当前句柄是否是读操作
last_used_at %% 最后一次使用句柄的时间
}).
%% file_handle_cache进程的状态数据结构
-record(fhc_state,
{ elders, %% 记录客户端对应最老的句柄最后一次的使用时间的ETS表名
limit, %% 总体文件描述符的上限
open_count, %% 当前RabbitMQ系统文件句柄打开的个数
open_pending, %% 当前RabbitMQ系统等待打开文件句柄的等待队列
obtain_limit, %%socket %% obtain类型的描述符上限
obtain_count_socket, %% 当前RabbitMQ系统打开的Socket的数量
obtain_count_file, %% 当前RabbitMQ系统操作文件的数量
obtain_pending_socket, %% 当前RabbitMQ系统等待打开socket的等待队列
obtain_pending_file, %% 当前RabbitMQ等待打开文件的等待队列
clients, %% 存储客户端信息的ETS表名
timer_ref, %% 较少文件描述符后下次检查的定时器,用来判断是否还需要减少
alarm_set, %% 文件描述符超过上限的报警函数
alarm_clear %% 文件描述符从超过上限到为超过上限的警报清除函数
}).
%% client客户端状态数据结构
-record(cstate,
{ pid, %% 客户端进程Pid
callback, %% 客户端进程注册的回调函数
opened, %% 客户端打开的文件句柄数量
obtained_socket, %% 客户端打开的socket数量
obtained_file, %% 客户端操作文件的数量
blocked, %% 客户端当前是否阻塞的字段
pending_closes %% 客户端在等待关闭的数量
}).
%% 等待的状态数据结构
-record(pending,
{ kind, %% 操作类型(open,file,socket)
pid, %% 客户端进程Pid
requested, %% 当前请求要打开的数量
from %% 接收返回结果的进程Pid
}).
%%----------------------------------------------------------------------------
%% Specs
%%----------------------------------------------------------------------------
-ifdef(use_specs).
-type(ref() :: any()).
-type(ok_or_error() :: 'ok' | {'error', any()}).
-type(val_or_error(T) :: {'ok', T} | {'error', any()}).
-type(position() :: ('bof' | 'eof' | non_neg_integer() |
{('bof' |'eof'), non_neg_integer()} |
{'cur', integer()})).
-type(offset() :: non_neg_integer()).
-spec(register_callback/3 :: (atom(), atom(), [any()]) -> 'ok').
-spec(open/3 ::
(file:filename(), [any()],
[{'write_buffer', (non_neg_integer() | 'infinity' | 'unbuffered')} |
{'read_buffer', (non_neg_integer() | 'unbuffered')}])
-> val_or_error(ref())).
-spec(close/1 :: (ref()) -> ok_or_error()).
-spec(read/2 :: (ref(), non_neg_integer()) ->
val_or_error([char()] | binary()) | 'eof').
-spec(append/2 :: (ref(), iodata()) -> ok_or_error()).
-spec(sync/1 :: (ref()) -> ok_or_error()).
-spec(position/2 :: (ref(), position()) -> val_or_error(offset())).
-spec(truncate/1 :: (ref()) -> ok_or_error()).
-spec(current_virtual_offset/1 :: (ref()) -> val_or_error(offset())).
-spec(current_raw_offset/1 :: (ref()) -> val_or_error(offset())).
-spec(flush/1 :: (ref()) -> ok_or_error()).
-spec(copy/3 :: (ref(), ref(), non_neg_integer()) ->
val_or_error(non_neg_integer())).
-spec(delete/1 :: (ref()) -> ok_or_error()).
-spec(clear/1 :: (ref()) -> ok_or_error()).
-spec(set_maximum_since_use/1 :: (non_neg_integer()) -> 'ok').
-spec(obtain/0 :: () -> 'ok').
-spec(obtain/1 :: (non_neg_integer()) -> 'ok').
-spec(release/0 :: () -> 'ok').
-spec(release/1 :: (non_neg_integer()) -> 'ok').
-spec(transfer/1 :: (pid()) -> 'ok').
-spec(transfer/2 :: (pid(), non_neg_integer()) -> 'ok').
-spec(with_handle/1 :: (fun(() -> A)) -> A).
-spec(with_handle/2 :: (non_neg_integer(), fun(() -> A)) -> A).
-spec(set_limit/1 :: (non_neg_integer()) -> 'ok').
-spec(get_limit/0 :: () -> non_neg_integer()).
-spec(info_keys/0 :: () -> rabbit_types:info_keys()).
-spec(info/0 :: () -> rabbit_types:infos()).
-spec(info/1 :: ([atom()]) -> rabbit_types:infos()).
-spec(ulimit/0 :: () -> 'unknown' | non_neg_integer()).
-endif.
%%----------------------------------------------------------------------------
-define(INFO_KEYS, [total_limit, total_used, sockets_limit, sockets_used]).
%%----------------------------------------------------------------------------
%% Public(公共) API
%%----------------------------------------------------------------------------
%% file_handle_cache进程的启动API接口
start_link() ->
start_link(fun alarm_handler:set_alarm/1, fun alarm_handler:clear_alarm/1).
%% file_handle_cache进程的启动API接口
start_link(AlarmSet, AlarmClear) ->
gen_server2:start_link({local, ?SERVER}, ?MODULE, [AlarmSet, AlarmClear],
[{timeout, infinity}]).
%% 打开文件的客户端进程注册的回调清理函数的接口
register_callback(M, F, A)
when is_atom(M) andalso is_atom(F) andalso is_list(A) ->
gen_server2:cast(?SERVER, {register_callback, self(), {M, F, A}}).
%% 打开一个文件的API接口
open(Path, Mode, Options) ->
%% 得到文件名字对应的绝对路径(如果传入的是单个文件名字则返回当前工作目录加上文件名,如果传入的是绝对路径则直接返回绝对路径)
Path1 = filename:absname(Path),
%% 得到当前文件的file文件数据结构
File1 = #file { reader_count = RCount, has_writer = HasWriter } =
case get({Path1, fhc_file}) of
File = #file {} -> File;
undefined -> #file { reader_count = 0,
has_writer = false }
end,
%% 将打开文件的append mode直接转化为write
Mode1 = append_to_write(Mode),
%% 判断当前文件操作模式是否是写模式
IsWriter = is_writer(Mode1),
case IsWriter andalso HasWriter of
true -> {error, writer_exists};
false -> %% 新增当前文件关闭的句柄数据结构
{ok, Ref} = new_closed_handle(Path1, Mode1, Options),
case get_or_reopen([{Ref, new}]) of
{ok, [_Handle1]} ->
RCount1 = case is_reader(Mode1) of
true -> RCount + 1;
false -> RCount
end,
HasWriter1 = HasWriter orelse IsWriter,
%% 更新打开的磁盘文件的file结构到调用该接口的进程中的进程字典中
put({Path1, fhc_file},
File1 #file { reader_count = RCount1,
has_writer = HasWriter1 }),
{ok, Ref};
Error ->
erase({Ref, fhc_handle}),
Error
end
end.
%% 关闭一个文件的接口
close(Ref) ->
case erase({Ref, fhc_handle}) of
undefined -> ok;
Handle -> case hard_close(Handle) of
ok -> ok;
{Error, Handle1} -> put_handle(Ref, Handle1),
Error
end
end.
%% 读取文件的接口
read(Ref, Count) ->
%% 先将Ref句柄的写缓存清空,然后对Ref句柄进行Fun函数的操作,操作成功后更新Ref句柄最后使用时间
with_flushed_handles(
[Ref], keep,
fun ([#handle { is_read = false }]) ->
{error, not_open_for_reading};
([Handle = #handle{read_buffer = Buf,
read_buffer_pos = BufPos,
read_buffer_rem = BufRem,
read_buffer_usage = BufUsg,
offset = Offset}])
when BufRem >= Count ->
%% 当前读取过还未引用的数据大于等于需要阅读的字符数量Count则直接从缓存中读取
<<_:BufPos/binary, Res:Count/binary, _/binary>> = Buf,
{{ok, Res}, [Handle#handle{offset = Offset + Count,
read_buffer_pos = BufPos + Count,
read_buffer_rem = BufRem - Count,
read_buffer_usage = BufUsg + Count }]};
([Handle0]) ->
%% 当内存的使用量超过上限有可能需要减少读取的缓存
maybe_reduce_read_cache([Ref]),
Handle = #handle{read_buffer = Buf,
read_buffer_pos = BufPos,
read_buffer_rem = BufRem,
read_buffer_size = BufSz,
hdl = Hdl,
offset = Offset}
= tune_read_buffer_limit(Handle0, Count),
%% 读缓存中上次读中剩余的字符串数量小于本次需要读取的字符数量
WantedCount = Count - BufRem,
%% 实际读取文件的地方(WantedCount:实际要从磁盘读取的数据大小)
case prim_file_read(Hdl, lists:max([BufSz, WantedCount])) of
{ok, Data} ->
<<_:BufPos/binary, BufTl/binary>> = Buf,
ReadCount = size(Data),
case ReadCount < WantedCount of
%% 到这种情况是要读取的数据大于读到的数据,此时读取已经到达磁盘文件的末尾
true ->
OffSet1 = Offset + BufRem + ReadCount,
{{ok, <<BufTl/binary, Data/binary>>},
%% 则重置句柄的读缓存,然后更新文件句柄的最新偏移位置
[reset_read_buffer(
Handle#handle{offset = OffSet1})]};
false ->
<<Hd:WantedCount/binary, _/binary>> = Data,
OffSet1 = Offset + BufRem + WantedCount,
BufRem1 = ReadCount - WantedCount,
{{ok, <<BufTl/binary, Hd/binary>>},
[Handle#handle{offset = OffSet1,
read_buffer = Data,
read_buffer_pos = WantedCount,
read_buffer_rem = BufRem1,
read_buffer_usage = WantedCount}]}
end;
%% 已经读到文件的尾部
eof ->
{eof, [Handle #handle { at_eof = true }]};
%% 读取数据出现错误,则将该句柄的读缓存清空
Error ->
{Error, [reset_read_buffer(Handle)]}
end
end).
%% file_handle_cache中的文件写操作只能是写在文件的后面
append(Ref, Data) ->
%% 对Refs所有的句柄执行Fun函数,在执行Fun函数之前reset表示会将Refs所有句柄的读缓存清除掉
with_handles(
[Ref],
fun ([#handle { is_write = false }]) ->
{error, not_open_for_writing};
([Handle]) ->
case maybe_seek(eof, Handle) of
%% 没有写缓存的设置,则直接将数据写入文件
{{ok, _Offset}, #handle { hdl = Hdl, offset = Offset,
write_buffer_size_limit = 0,
at_eof = true } = Handle1} ->
Offset1 = Offset + iolist_size(Data),
%% prim_file模块写Hdl句柄Bytes长度的数据,然后更新io_write字段对应的count,size,time信息
{prim_file_write(Hdl, Data),
%% 将is_dirty字段设置为true,然后更新最新的文件偏移量
[Handle1 #handle { is_dirty = true, offset = Offset1 }]};
{{ok, _Offset}, #handle { write_buffer = WriteBuffer,
write_buffer_size = Size,
write_buffer_size_limit = Limit,
at_eof = true } = Handle1} ->
WriteBuffer1 = [Data | WriteBuffer],
Size1 = Size + iolist_size(Data),
Handle2 = Handle1 #handle { write_buffer = WriteBuffer1,
write_buffer_size = Size1 },
%% 如果不是永久缓存且当前缓存的大小超过写缓存的大小限制则将当前的写缓存写入文件
case Limit =/= infinity andalso Size1 > Limit of
%% 将句柄中缓存的数据写入磁盘文件
true -> {Result, Handle3} = write_buffer(Handle2),
{Result, [Handle3]};
false -> {ok, [Handle2]}
end;
{{error, _} = Error, Handle1} ->
{Error, [Handle1]}
end
end).
%% 文件的同步
sync(Ref) ->
%% 先将Refs所有句柄的写缓存清空,然后对Refs列表中的句柄进行Fun函数的操作,操作成功后更新Refs列表中的所有最后使用时间
with_flushed_handles(
[Ref], keep,
fun ([#handle { is_dirty = false, write_buffer = [] }]) ->
ok;
([Handle = #handle { hdl = Hdl,
is_dirty = true, write_buffer = [] }]) ->
%% prim_file模块同步磁盘文件,然后更新io_sync字段的数量和同步花费的时间
case prim_file_sync(Hdl) of
ok -> {ok, [Handle #handle { is_dirty = false }]};
Error -> {Error, [Handle]}
end
end).
%% 判断是否需要同步
needs_sync(Ref) ->
%% This must *not* use with_handles/2; see bug 25052
case get({Ref, fhc_handle}) of
#handle { is_dirty = false, write_buffer = [] } -> false;
#handle {} -> true
end.
position(Ref, NewOffset) ->
%% 先将Refs所有句柄的写缓存清空,然后对Refs列表中的句柄进行Fun函数的操作,操作成功后更新Refs列表中的所有最后使用时间
with_flushed_handles(
[Ref], keep,
%% 判断当前文件句柄是否需要重新设置偏移位置,如果需要,则立刻对文件句柄重新设置偏移位置
fun ([Handle]) -> {Result, Handle1} = maybe_seek(NewOffset, Handle),
{Result, [Handle1]}
end).
%% truncate:截短
%% 截断Ref对应的磁盘文件
truncate(Ref) ->
%% 先将Refs所有句柄的写缓存清空,然后对Refs列表中的句柄进行Fun函数的操作,操作成功后更新Refs列表中的所有最后使用时间
with_flushed_handles(
[Ref],
fun ([Handle1 = #handle { hdl = Hdl }]) ->
case prim_file:truncate(Hdl) of
%% 更新句柄已经处于磁盘文件尾部
ok -> {ok, [Handle1 #handle { at_eof = true }]};
Error -> {Error, [Handle1]}
end
end).
%% 拿到Ref句柄对应的最新偏移量
current_virtual_offset(Ref) ->
with_handles([Ref], fun ([#handle { at_eof = true, is_write = true,
offset = Offset,
write_buffer_size = Size }]) ->
{ok, Offset + Size};
([#handle { offset = Offset }]) ->
{ok, Offset}
end).
%% 拿到Ref句柄对应的偏移量,直接获取offset字段,不需用加上write_buffer_size字段的偏移量
current_raw_offset(Ref) ->
with_handles([Ref], fun ([Handle]) -> {ok, Handle #handle.offset} end).
%% 将Ref对应的句柄中的写数据缓存写入到磁盘中
flush(Ref) ->
with_flushed_handles([Ref], fun ([Handle]) -> {ok, [Handle]} end).
%% 将Src句柄中Count大小的数据拷贝到Dest句柄对应的磁盘文件
copy(Src, Dest, Count) ->
%% 对Refs所有的句柄执行Fun函数,在执行Fun函数之前reset表示会将Refs所有句柄的读缓存清除掉,同时将Refs所有句柄的写缓存清空
with_flushed_handles(
[Src, Dest],
fun ([SHandle = #handle { is_read = true, hdl = SHdl, offset = SOffset },
DHandle = #handle { is_write = true, hdl = DHdl, offset = DOffset }]
) ->
case prim_file:copy(SHdl, DHdl, Count) of
{ok, Count1} = Result1 ->
{Result1,
%% 调整目的和源句柄对应的磁盘文件的最新偏移量
[SHandle #handle { offset = SOffset + Count1 },
DHandle #handle { offset = DOffset + Count1,
is_dirty = true }]};
Error ->
{Error, [SHandle, DHandle]}
end;
(_Handles) ->
{error, incorrect_handle_modes}
end).
%% 强制删除句柄,写缓存数据会丢失
delete(Ref) ->
%% 先清除句柄进程字典
case erase({Ref, fhc_handle}) of
undefined ->
ok;
Handle = #handle { path = Path } ->
%% 硬关闭(先进行软关闭,先将写缓存中的数据写入磁盘,然后关闭句柄,然后如果当前读个数不为0或者是写操作则更新文件最新的读取者数量和has_writer字段,否则直接将文件信息全部清除掉)
case hard_close(Handle #handle { is_dirty = false,
write_buffer = [] }) of
ok -> prim_file:delete(Path);
{Error, Handle1} -> put_handle(Ref, Handle1),
Error
end
end.
%% 清理Ref对应的句柄
clear(Ref) ->
with_handles(
[Ref],
fun ([#handle { at_eof = true, write_buffer_size = 0, offset = 0 }]) ->
ok;
([Handle]) ->
case maybe_seek(bof, Handle#handle{write_buffer = [],
write_buffer_size = 0}) of
{{ok, 0}, Handle1 = #handle { hdl = Hdl }} ->
%% 直接将句柄对应的磁盘文件截断
case prim_file:truncate(Hdl) of
ok -> {ok, [Handle1 #handle { at_eof = true }]};
Error -> {Error, [Handle1]}
end;
{{error, _} = Error, Handle1} ->
{Error, [Handle1]}
end
end).
%% 将当前进程客户端中文件句柄打开时间超过MaximumAge的句柄软关闭
set_maximum_since_use(MaximumAge) ->
Now = now(),
case lists:foldl(
fun ({{Ref, fhc_handle},
Handle = #handle { hdl = Hdl, last_used_at = Then }}, Rep) ->
case Hdl =/= closed andalso
timer:now_diff(Now, Then) >= MaximumAge of
true -> soft_close(Ref, Handle) orelse Rep;
false -> Rep
end;
(_KeyValuePair, Rep) ->
Rep
end, false, get()) of
false -> age_tree_change(), ok;
true -> ok
end.
%% obtain/0方法增加拥有的文件描述符数量
obtain() -> obtain(1).
%% release/0方法减少拥有的文件描述符数量
release() -> release(1).
%% transfer/1将文件描述符的拥有权转移到另外一个进程(原进程拥有的打开描述符数量减1,转移目标进程拥有的文件描述符数量加1)
transfer(Pid) -> transfer(Pid, 1).
%% obtain/0方法增加拥有的文件描述符数量
obtain(Count) -> obtain(Count, socket).
%% release/0方法减少拥有的文件描述符数量
release(Count) -> release(Count, socket).
%% 操作单个整体文件的接口
with_handle(Fun) ->
with_handle(1, Fun).
%% 操作单个整体文件的接口
with_handle(N, Fun) ->
%% 将当前客户端进程在file_handle_cache进程中file对应的数量增加N
ok = obtain(N, file),
try Fun()
%% 执行完Fun函数后,再将当前客户端进程在file_handle_cache进程中file对应的数量减去N
after ok = release(N, file)
end.
%% 增加Type对应obtain的数量
obtain(Count, Type) when Count > 0 ->
%% If the FHC isn't running, obtains succeed immediately.
case whereis(?SERVER) of
undefined -> ok;
_ -> gen_server2:call(
?SERVER, {obtain, Count, Type, self()}, infinity)
end.
%% release/0方法减少拥有的文件描述符数量
release(Count, Type) when Count > 0 ->
gen_server2:cast(?SERVER, {release, Count, Type, self()}).
%% transfer/1将文件描述符的拥有权转移到另外一个进程(原进程拥有的打开描述符数量减Count,转移目标进程拥有的文件描述符数量加Count)
transfer(Pid, Count) when Count > 0 ->
gen_server2:cast(?SERVER, {transfer, Count, self(), Pid}).
%% 设置file_handle_cache进程中文件描述符的上限
set_limit(Limit) ->
gen_server2:call(?SERVER, {set_limit, Limit}, infinity).
%% 获取file_handle_cache进程上的文件描述符上限
get_limit() ->
gen_server2:call(?SERVER, get_limit, infinity).
%% 获得file_handle_cache关键信息key列表
info_keys() -> ?INFO_KEYS.
%% 获取file_handle_cache进程INFO_KEYS对应的所有关键信息
info() -> info(?INFO_KEYS).
%% 获取file_handle_cache进程Items对应的所有关键信息
info(Items) -> gen_server2:call(?SERVER, {info, Items}, infinity).
%%----------------------------------------------------------------------------
%% Internal(内部) functions
%%----------------------------------------------------------------------------
%% prim_file模块读Hdl句柄Size大小的磁盘数据,然后更新io_read字段对应的count,size,time信息
prim_file_read(Hdl, Size) ->
file_handle_cache_stats:update(
io_read, Size, fun() -> prim_file:read(Hdl, Size) end).
%% prim_file模块写Hdl句柄Bytes长度的数据,然后更新io_write字段对应的count,size,time信息
prim_file_write(Hdl, Bytes) ->
file_handle_cache_stats:update(
io_write, iolist_size(Bytes), fun() -> prim_file:write(Hdl, Bytes) end).
%% prim_file模块同步磁盘文件,然后更新io_sync字段的数量和同步花费的时间
prim_file_sync(Hdl) ->
file_handle_cache_stats:update(io_sync, fun() -> prim_file:sync(Hdl) end).
%% prim_file模块更新文件句柄最新的偏移位置,然后更新io_seek字段的数量和确定位置的执行时间
prim_file_position(Hdl, NewOffset) ->
file_handle_cache_stats:update(
io_seek, fun() -> prim_file:position(Hdl, NewOffset) end).
%% 判断Mode模式是否是读模式
is_reader(Mode) -> lists:member(read, Mode).
%% 判断Mode模式是否是写模式
is_writer(Mode) -> lists:member(write, Mode).
%% 将打开文件的append mode直接转化为write
append_to_write(Mode) ->
case lists:member(append, Mode) of
true -> [write | Mode -- [append, write]];
false -> Mode
end.
%% 对Refs所有的句柄执行Fun函数,在执行Fun函数之前reset表示会将Refs所有句柄的读缓存清除掉
with_handles(Refs, Fun) ->
with_handles(Refs, reset, Fun).
%% 对Refs列表中的句柄进行Fun函数的操作,操作成功后更新Refs列表中的所有最后使用时间
with_handles(Refs, ReadBuffer, Fun) ->
%% 如果Refs列表中的句柄没有打开则重新打开
case get_or_reopen([{Ref, reopen} || Ref <- Refs]) of
{ok, Handles0} ->
Handles = case ReadBuffer of
%% 重置句柄的读缓存
reset -> [reset_read_buffer(H) || H <- Handles0];
%% keep表示保持读缓存
keep -> Handles0
end,
case Fun(Handles) of
{Result, Handles1} when is_list(Handles1) ->
%% 更新Refs的最后使用时间
lists:zipwith(fun put_handle/2, Refs, Handles1),
Result;
Result ->
Result
end;
Error ->
Error
end.
%% 对Refs所有的句柄执行Fun函数,在执行Fun函数之前reset表示会将Refs所有句柄的读缓存清除掉,同时将Refs所有句柄的写缓存清空
with_flushed_handles(Refs, Fun) ->
with_flushed_handles(Refs, reset, Fun).
%% 先将Refs所有句柄的写缓存清空,然后对Refs列表中的句柄进行Fun函数的操作,操作成功后更新Refs列表中的所有最后使用时间
with_flushed_handles(Refs, ReadBuffer, Fun) ->
with_handles(
Refs, ReadBuffer,
fun (Handles) ->
%% 如果有写缓存,则先将写缓存数据写入文件
case lists:foldl(
fun (Handle, {ok, HandlesAcc}) ->
%% 将句柄的缓存写入磁盘
{Res, Handle1} = write_buffer(Handle),
{Res, [Handle1 | HandlesAcc]};
(Handle, {Error, HandlesAcc}) ->
{Error, [Handle | HandlesAcc]}
end, {ok, []}, Handles) of
{ok, Handles1} ->
Fun(lists:reverse(Handles1));
{Error, Handles1} ->
{Error, lists:reverse(Handles1)}
end
end).
%% 根据标志拿到对应的handle或者重新打开该文件
get_or_reopen(RefNewOrReopens) ->
%% 将已经打开的句柄和关闭的句柄分开
case partition_handles(RefNewOrReopens) of
{OpenHdls, []} ->
{ok, [Handle || {_Ref, Handle} <- OpenHdls]};
{OpenHdls, ClosedHdls} ->
%% 得到年龄最老的句柄创建时间
Oldest = oldest(get_age_tree(), fun () -> now() end),
case gen_server2:call(?SERVER, {open, self(), length(ClosedHdls),
Oldest}, infinity) of
ok ->
case reopen(ClosedHdls) of
{ok, RefHdls} -> sort_handles(RefNewOrReopens,
OpenHdls, RefHdls, []);
Error -> Error
end;
%% file_handle_cache进程中的文件描述符已经超过上限,且当前客户端有打开的文件句柄,则将当前客户端的所有文件句柄进行软关闭
close ->
%% 将当前客户端所有没有关闭的句柄执行软关闭
[soft_close(Ref, Handle) ||
{{Ref, fhc_handle}, Handle = #handle { hdl = Hdl }} <-
get(),
Hdl =/= closed],
%% 将当前客户端的所有句柄关闭后,再重新打开要打开的句柄
get_or_reopen(RefNewOrReopens)
end
end.
%% 重新打开文件句柄的函数接口
reopen(ClosedHdls) -> reopen(ClosedHdls, get_age_tree(), []).
reopen([], Tree, RefHdls) ->
%% 更新最新的时间平衡二叉树
put_age_tree(Tree),
{ok, lists:reverse(RefHdls)};
reopen([{Ref, NewOrReopen, Handle = #handle { hdl = closed,
path = Path,
mode = Mode0,
offset = Offset,
last_used_at = undefined }} |
RefNewOrReopenHdls] = ToOpen, Tree, RefHdls) ->
Mode = case NewOrReopen of
%% new表示当前文件是要新打开的文件句柄
new -> Mode0;
%% reopen表示当前文件是重新打开句柄,同时更新IO中重新打开文件的数量
reopen -> file_handle_cache_stats:update(io_reopen),
[read | Mode0]
end,
%% 调用prim_file:open()接口打开文件句柄
case prim_file:open(Path, Mode) of
{ok, Hdl} ->
Now = now(),
{{ok, _Offset}, Handle1} =
maybe_seek(Offset, reset_read_buffer(
Handle#handle{hdl = Hdl,
offset = 0,
last_used_at = Now})),
%% 将当前文件句柄数据结构存入进程字典
put({Ref, fhc_handle}, Handle1),
%% 将当前句柄的打开时间写入时间二叉树,然后继续处理重新打开的剩余列表
reopen(RefNewOrReopenHdls, gb_trees:insert(Now, Ref, Tree),
[{Ref, Handle1} | RefHdls]);
Error ->
%% NB: none of the handles in ToOpen are in the age tree
Oldest = oldest(Tree, fun () -> undefined end),
[gen_server2:cast(?SERVER, {close, self(), Oldest}) || _ <- ToOpen],
%% 更新最新的时间平衡二叉树
put_age_tree(Tree),
Error
end.
%% 将已经打开的句柄和关闭的句柄分开
partition_handles(RefNewOrReopens) ->
lists:foldr(
fun ({Ref, NewOrReopen}, {Open, Closed}) ->
case get({Ref, fhc_handle}) of
#handle { hdl = closed } = Handle ->
{Open, [{Ref, NewOrReopen, Handle} | Closed]};
#handle {} = Handle ->
{[{Ref, Handle} | Open], Closed}
end
end, {[], []}, RefNewOrReopens).
%% 给句柄排序
sort_handles([], [], [], Acc) ->
{ok, lists:reverse(Acc)};
sort_handles([{Ref, _} | RefHdls], [{Ref, Handle} | RefHdlsA], RefHdlsB, Acc) ->
sort_handles(RefHdls, RefHdlsA, RefHdlsB, [Handle | Acc]);
sort_handles([{Ref, _} | RefHdls], RefHdlsA, [{Ref, Handle} | RefHdlsB], Acc) ->
sort_handles(RefHdls, RefHdlsA, RefHdlsB, [Handle | Acc]).
%% 更新文件句柄最新的使用时间
put_handle(Ref, Handle = #handle { last_used_at = Then }) ->
Now = now(),
age_tree_update(Then, Now, Ref),
put({Ref, fhc_handle}, Handle #handle { last_used_at = Now }).
%% 对时间二叉树执行Fun函数
with_age_tree(Fun) -> put_age_tree(Fun(get_age_tree())).
%% 得到当前年龄二叉树的数据结构
get_age_tree() ->
case get(fhc_age_tree) of
undefined -> gb_trees:empty();
AgeTree -> AgeTree
end.
%% 更新最新的时间平衡二叉树
put_age_tree(Tree) -> put(fhc_age_tree, Tree).
%% 将Then老的时间对应的数据删除掉,然后插入Now对应Ref的数据
age_tree_update(Then, Now, Ref) ->
with_age_tree(
fun (Tree) ->
gb_trees:insert(Now, Ref, gb_trees:delete_any(Then, Tree))
end).
%% 将Then这个时间点对应的打开句柄数据从时间二叉树中删除
age_tree_delete(Then) ->
with_age_tree(
fun (Tree) ->
%% 将Then时间对应的数据删除
Tree1 = gb_trees:delete_any(Then, Tree),
Oldest = oldest(Tree1, fun () -> undefined end),
%% 通知file_handle_cache进程关闭一个句柄
gen_server2:cast(?SERVER, {close, self(), Oldest}),
Tree1
end).
%% 年龄数的改变接口
age_tree_change() ->
with_age_tree(
fun (Tree) ->
case gb_trees:is_empty(Tree) of
true -> Tree;
false -> {Oldest, _Ref} = gb_trees:smallest(Tree),
%% 通知file_handle_cache进程更新
gen_server2:cast(?SERVER, {update, self(), Oldest})
end,
Tree
end).
%% 拿到年龄二叉树中年龄最先的数据
oldest(Tree, DefaultFun) ->
case gb_trees:is_empty(Tree) of
true -> DefaultFun();
false -> {Oldest, _Ref} = gb_trees:smallest(Tree),
Oldest
end.
%% 新增一个文件handle
new_closed_handle(Path, Mode, Options) ->
%% 拿到当前文件写的缓存大小
WriteBufferSize =
case proplists:get_value(write_buffer, Options, unbuffered) of
unbuffered -> 0;
infinity -> infinity;
N when is_integer(N) -> N
end,
%% 拿到当前文件读的缓存大小
ReadBufferSize =
case proplists:get_value(read_buffer, Options, unbuffered) of
unbuffered -> 0;
N2 when is_integer(N2) -> N2
end,
%% 给当前文件生成一个唯一的标识
Ref = make_ref(),
%% 将文件句柄信息放入到自己进程的进程字典中
put({Ref, fhc_handle}, #handle { hdl = closed,
offset = 0,
is_dirty = false,
write_buffer_size = 0,
write_buffer_size_limit = WriteBufferSize,
write_buffer = [],
read_buffer = <<>>,
read_buffer_pos = 0,
read_buffer_rem = 0,
read_buffer_size = ReadBufferSize,
read_buffer_size_limit = ReadBufferSize,
read_buffer_usage = 0,
at_eof = false,
path = Path,
mode = Mode,
options = Options,
is_write = is_writer(Mode),
is_read = is_reader(Mode),
last_used_at = undefined }),
{ok, Ref}.
%% 软关闭文件句柄Handle(所谓软关闭,就是将Handle对应文件buffer写完,sync后再关闭)
soft_close(Ref, Handle) ->
{Res, Handle1} = soft_close(Handle),
case Res of
%% 删除句柄成功,则将最新的句柄写入到进程字典
ok -> put({Ref, fhc_handle}, Handle1),
true;
%% 更新文件句柄最新的使用时间