-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
locks_agent.erl
executable file
·1420 lines (1268 loc) · 47.3 KB
/
locks_agent.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
%% -*- mode: erlang; indent-tabs-mode: nil; -*-
%%---- BEGIN COPYRIGHT -------------------------------------------------------
%%
%% Copyright (C) 2013 Ulf Wiger. All rights reserved.
%%
%% 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 http://mozilla.org/MPL/2.0/.
%%
%%---- END COPYRIGHT ---------------------------------------------------------
%% Key contributor: Thomas Arts <thomas.arts@quviq.com>
%%
%%=============================================================================
%% @doc Transaction agent for the locks system
%%
%% This module implements the recommended API for users of the `locks' system.
%% While the `locks_server' has a low-level API, the `locks_agent' is the
%% part that detects and resolves deadlocks.
%%
%% The agent runs as a separate process from the client, and monitors the
%% client, terminating immediately if it dies.
%% @end
-module(locks_agent).
%% -*- mode: erlang; indent-tabs-mode: nil; -*-
%%---- BEGIN COPYRIGHT -------------------------------------------------------
%%
%% Copyright (C) 2013 Ulf Wiger. All rights reserved.
%%
%% 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 http://mozilla.org/MPL/2.0/.
%%
%%---- END COPYRIGHT ---------------------------------------------------------
%% Key contributor: Thomas Arts <thomas.arts@quviq.com>
%%
%%=============================================================================
-behaviour(gen_server).
-compile({parse_transform, locks_watcher}).
-export([start_link/0, start_link/1, start/0, start/1]).
-export([spawn_agent/1]).
-export([begin_transaction/1,
begin_transaction/2,
%% acquire_all_or_none/2,
lock/2, lock/3, lock/4, lock/5,
lock_nowait/2, lock_nowait/3, lock_nowait/4, lock_nowait/5,
lock_objects/2,
surrender_nowait/4,
await_all_locks/1,
async_await_all_locks/1,
monitor_nodes/2,
change_flag/3,
lock_info/1,
transaction_status/1,
%% await_all_or_none/1,
end_transaction/1]).
%% gen_server callbacks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-export([record_fields/1]).
-import(lists,[foreach/2,any/2,map/2,member/2]).
-include("locks.hrl").
-define(costly_event(E),
case erlang:trace_info({?MODULE,event,3}, traced) of
{_, false} -> ok;
_ -> event(?LINE, E, none)
end).
-define(event(E), event(?LINE, E, none)).
-define(event(E, S), event(?LINE, E, S)).
-ifdef(DEBUG).
-define(dbg(Fmt, Args), io:fwrite(user, Fmt, Args)).
-else.
-define(dbg(F, A), ok).
-endif.
-type option() :: {client, pid()}
| {abort_on_deadlock, boolean()}
| {await_nodes, boolean()}
| {notify, boolean()}.
-type transaction_status() :: no_locks
| {have_all_locks, list()}
| waiting
| {cannot_serve, list()}.
-record(req, {object,
mode,
nodes,
claim_no = 0,
require = all}).
-type monitored_nodes() :: [{node(), reference()}].
-type down_nodes() :: [node()].
-record(state, {
locks :: ets:tab(),
agents :: ets:tab(),
interesting = [] :: [lock_id()],
claim_no = 0 :: integer(),
requests :: ets:tab(),
down = [] :: down_nodes(),
monitored = [] :: monitored_nodes(),
await_nodes = false :: boolean(),
monitor_nodes = false :: boolean(),
pending :: ets:tab(),
sync = [] :: [#lock{}],
client :: pid(),
client_mref :: reference(),
options = [] :: [option()],
notify = [] :: [pid()],
awaiting_all = []:: [{pid(), reference()}],
answer :: locking | waiting | done,
deadlocks = [] :: deadlocks(),
have_all = false :: boolean(),
status = no_locks :: transaction_status()
}).
-define(myclient,State#state.client).
record_fields(state ) -> record_info(fields, state);
record_fields(req ) -> record_info(fields, req);
record_fields(lock ) -> record_info(fields, lock);
record_fields(locks_info) -> record_info(fields, locks_info);
record_fields(w ) -> record_info(fields, w);
record_fields(r ) -> record_info(fields, r);
record_fields(entry ) -> record_info(fields, entry);
record_fields(_) ->
no.
%%% interface function
%% @spec start_link() -> {ok, pid()}
%% @equiv start_link([])
start_link() ->
start([{link, true}]).
-spec start_link([option()]) -> {ok, pid()}.
%% @doc Starts an agent with options, linking to the client.
%%
%% Note that even if `{link, false}' is specified in the Options, this will
%% be overridden by `{link, true}', implicit in the function name.
%%
%% Linking is normally not required, as the agent will always monitor the
%% client and terminate if the client dies.
%%
%% See also {@link start/1}.
%% @end
start_link(Options) when is_list(Options) ->
start(lists:keystore(link, 1, Options, {link, true})).
-spec start() -> {ok, pid()}.
%% @equiv start([])
start() ->
start([]).
-spec start([option()]) -> {ok, pid()}.
%% @doc Starts an agent with options.
%%
%% Options are:
%%
%% * `{client, pid()}' - defaults to `self()', indicating which process is
%% the client. The agent will monitor the client, and only accept lock
%% requests from it (this may be extended in future version).
%%
%% * `{link, boolean()}' - default: `false'. Whether to link the current
%% process to the agent. This is normally not required, but will have the
%% effect that the current process (normally the client) receives an 'EXIT'
%% signal if the agent aborts.
%%
%% * `{abort_on_deadlock, boolean()}' - default: `false'. Normally, when
%% deadlocks are detected, one agent will be picked to surrender a lock.
%% This can be problematic if the client has already been notified that the
%% lock has been granted. If `{abort_on_deadlock, true}', the agent will
%% abort if it would otherwise have had to surrender, <b>and</b> the client
%% has been told that the lock has been granted.
%%
%% * `{await_nodes, boolean()}' - default: `false'. If nodes 'disappear'
%% (i.e. the locks_server there goes away) and `{await_nodes, false}',
%% the agent will consider those nodes lost and may abort if the lock
%% request(s) cannot be granted without the lost nodes. If `{await_nodes,true}',
%% the agent will wait for the nodes to reappear, and reclaim the lock(s) when
%% they do.
%%
%% * `{monitor_nodes, boolean()}' - default: `false'. Works like
%% {@link net_kernel:monitor_nodes/1}, but `nodedown' and `nodeup' messages are
%% sent when the `locks' server on a given node either appears or disappears.
%% The messages (`{nodeup,Node}' and `{nodedown,Node}') are sent only to
%% the client. Can also be toggled using {@link monitor_nodes/2}.
%%
%% * `{notify, boolean()}' - default: `false'. If `{notify, true}', the client
%% will receive `{locks_agent, Agent, Info}' messages, where `Info' is either
%% a `#locks_info{}' record or `{have_all_locks, Deadlocks}'.
%% @end
start(Options0) when is_list(Options0) ->
spawn_agent(true, Options0).
spawn_agent(Options) ->
spawn_agent(false, Options).
spawn_agent(Wait, Options0) ->
Client = self(),
Options = prepare_spawn(Options0),
F = fun() -> agent_init(Wait, Client, Options) end,
Pid = case lists:keyfind(link, 1, Options) of
{_, true} -> spawn_link(F);
_ -> spawn(F)
end,
await_pid(Wait, Pid).
prepare_spawn(Options) ->
case whereis(locks_server) of
undefined -> error({not_running, locks_server});
_ -> ok
end,
case lists:keymember(client, 1, Options) of
true -> Options;
false -> [{client, self()}|Options]
end.
agent_init(Wait, Client, Options) ->
case init(Options) of
{ok, St} ->
ack(Wait, Client, {ok, self()}),
try loop(St)
catch
error:Error ->
error_logger:error_report(
[{?MODULE, aborted},
{reason, Error},
{trace, erlang:get_stacktrace()}]),
error(Error)
end;
Other ->
ack(Wait, Client, {error, Other}),
error(Other)
end.
await_pid(false, Pid) ->
{ok, Pid};
await_pid(true, Pid) ->
MRef = erlang:monitor(process, Pid),
receive
{Pid, Reply} ->
erlang:demonitor(MRef),
Reply;
{'DOWN', MRef, _, _, Reason} ->
error(Reason)
end.
ack(false, _, _) ->
ok;
ack(true, Pid, Reply) ->
Pid ! {self(), Reply}.
loop(#state{status = OldStatus} = St) ->
receive Msg ->
St1 = handle_msg(Msg, St),
loop(maybe_status_change(OldStatus, St1))
end.
handle_msg({'$gen_call', From, Req}, St) ->
case handle_call(Req, From, St) of
{reply, Reply, St1} ->
gen_server:reply(From, Reply),
St1;
{noreply, St1} ->
St1;
{stop, Reason, Reply, _} ->
gen_server:reply(From, Reply),
exit(Reason);
{stop, Reason, _} ->
exit(Reason)
end;
handle_msg({'$gen_cast', Msg}, St) ->
case handle_cast(Msg, St) of
{noreply, St1} ->
St1;
{stop, Reason, _} ->
exit(Reason)
end;
handle_msg(Msg, St) ->
case handle_info(Msg, St) of
{noreply, St1} -> St1;
{stop, Reason, _} ->
exit(Reason)
end.
-spec begin_transaction(objs()) -> {agent(), lock_result()}.
%% @equiv begin_transaction(Objects, [])
%%
begin_transaction(Objects) ->
begin_transaction(Objects, []).
-spec begin_transaction(objs(), options()) -> {agent(), lock_result()}.
%% @doc Starts an agent and requests a number of locks at the same time.
%%
%% For a description of valid options, see {@link start/1}.
%%
%% This function will return once the given lock requests have been granted,
%% or exit if they cannot be. If no initial lock requests are given, the
%% function will not wait at all, but return directly.
%% @end
begin_transaction(Objects, Opts) ->
{ok, Agent} = start(Opts),
case Objects of
[] -> {Agent, {ok,[]}};
[_|_] ->
_ = lock_objects(Agent, Objects),
{Agent, await_all_locks(Agent)}
end.
-spec await_all_locks(agent()) -> lock_result().
%% @doc Waits for all active lock requests to be granted.
%%
%% This function will return once all active lock requests have been granted.
%% If the agent determines that they cannot be granted, or if it has been
%% instructed to abort, this function will raise an exception.
%% @end
await_all_locks(Agent) ->
call(Agent, await_all_locks,infinity).
async_await_all_locks(Agent) ->
cast(Agent, {await_all_locks, self()}).
-spec monitor_nodes(agent(), boolean()) -> boolean().
%% @doc Toggles monitoring of nodes, like net_kernel:monitor_nodes/1.
%%
%% Works like {@link net_kernel:monitor_nodes/1}, but `nodedown' and `nodeup'
%% messages are sent when the `locks' server on a given node either appears
%% or disappears. In this sense, the monitoring will signal when a viable
%% `locks' node becomes operational (or inoperational).
%% The messages (`{nodeup,Node}' and `{nodedown,Node}') are sent only to
%% the client.
monitor_nodes(Agent, Bool) when is_boolean(Bool) ->
call(Agent, {monitor_nodes, Bool}).
-spec end_transaction(agent()) -> ok.
%% @doc Ends the transaction, terminating the agent.
%%
%% All lock requests issued via the agent will automatically be released.
%% @end
end_transaction(Agent) when is_pid(Agent) ->
call(Agent,stop).
-spec lock(pid(), oid()) -> {ok, list()}.
%%
lock(Agent, [_|_] = Obj) when is_pid(Agent) ->
lock_(Agent, Obj, write, [node()], all, wait).
-spec lock(pid(), oid(), mode()) -> {ok, list()}.
%% @equiv lock(Agent, Obj, Mode, [node()], all, wait)
lock(Agent, [_|_] = Obj, Mode)
when is_pid(Agent) andalso (Mode==read orelse Mode==write) ->
lock_(Agent, Obj, Mode, [node()], all, wait).
-spec lock(pid(), oid(), mode(), [node()]) -> {ok, list()}.
%%
lock(Agent, [_|_] = Obj, Mode, [_|_] = Where) ->
lock_(Agent, Obj, Mode, Where, all, wait).
-spec lock(pid(), oid(), mode(), [node()], req()) -> {ok, list()}.
%%
lock(Agent, [_|_] = Obj, Mode, [_|_] = Where, R)
when is_pid(Agent) andalso (Mode == read orelse Mode == write)
andalso (R == all orelse R == any orelse R == majority
orelse R == majority_alive orelse R == all_alive) ->
lock_(Agent, Obj, Mode, Where, R, wait).
lock_(Agent, Obj, Mode, [_|_] = Where, R, Wait) ->
Ref = case Wait of
wait -> erlang:monitor(process, Agent);
nowait -> nowait
end,
lock_return(
Wait,
cast(Agent, {lock, Obj, Mode, Where, R, Wait, self(), Ref}, Ref)).
change_flag(Agent, Option, Bool)
when is_boolean(Bool), Option == abort_on_deadlock;
is_boolean(Bool), Option == await_nodes;
is_boolean(Bool), Option == notify ->
gen_server:cast(Agent, {option, Option, Bool}).
cast(Agent, Msg) ->
gen_server:cast(Agent, Msg).
cast(Agent, Msg, Ref) ->
gen_server:cast(Agent, Msg),
await_reply(Ref).
await_reply(nowait) ->
ok;
await_reply(Ref) ->
receive
{'DOWN', Ref, _, _, Reason} ->
error(Reason);
{Ref, {abort, Reason}} ->
error(Reason);
{Ref, Reply} ->
Reply
end.
lock_return(wait, {have_all_locks, Deadlocks}) ->
{ok, Deadlocks};
lock_return(nowait, ok) ->
ok;
lock_return(_, Other) ->
Other.
lock_nowait(A, O) -> lock_(A, O, write, [node()], all, nowait).
lock_nowait(A, O, M) -> lock_(A, O, M, [node()], all, nowait).
lock_nowait(A, O, M, W) -> lock_(A, O, M, W, all, nowait).
lock_nowait(A, O, M, W, R) -> lock_(A, O, M, W, R, nowait).
surrender_nowait(A, O, OtherAgent, Nodes) ->
gen_server:cast(A, {surrender, O, OtherAgent, Nodes}).
-spec lock_objects(pid(), objs()) -> ok.
%%
lock_objects(Agent, Objects) ->
lists:foreach(fun({Obj, Mode}) when Mode == read; Mode == write ->
lock_nowait(Agent, Obj, Mode);
({Obj, Mode, Where}) when Mode == read; Mode == write ->
lock_nowait(Agent, Obj, Mode, Where);
({Obj, Mode, Where, Req})
when (Mode == read orelse Mode == write)
andalso (Req == all
orelse Req == any
orelse Req == majority
orelse Req == majority_alive
orelse Req == all_alive) ->
lock_nowait(Agent, Obj, Mode, Where);
(L) ->
error({illegal_lock_pattern, L})
end, Objects).
lock_info(Agent) ->
call(Agent, lock_info).
-spec transaction_status(agent()) -> transaction_status().
%% @doc Inquire about the current status of the transaction.
%% Return values:
%% <dl>
%% <dt>`no_locks'</dt>
%% <dd>No locks have been requested</dd>
%% <dt>`{have_all_locks, Deadlocks}'</dt>
%% <dd>All requested locks have been claimed, `Deadlocks' indicates whether
%% any deadlocks were resolved in the process.</dd>
%% <dt>`waiting'</dt>
%% <dd>Still waiting for some locks.</dd>
%% <dt>`{cannot_serve, Objs}'</dt>
%% <dd>Some lock requests cannot be served, e.g. because some nodes are
%% unavailable.</dd>
%% </dl>
%% @end
transaction_status(Agent) ->
call(Agent, transaction_status).
call(A, Req) ->
call(A, Req, 5000).
call(A, Req, Timeout) ->
case gen_server:call(A, Req, Timeout) of
{abort, Reason} ->
?event({abort, Reason, [A, Req, Timeout]}),
error(Reason);
Res ->
?event({result, Res, [A, Req, Timeout]}),
Res
end.
%% callback functions
%% @private
init(Opts) ->
Client = proplists:get_value(client, Opts),
ClientMRef = erlang:monitor(process, Client),
Notify = case proplists:get_value(notify, Opts, false) of
true -> [Client];
false -> []
end,
AwaitNodes = proplists:get_value(await_nodes, Opts, false),
MonNodes = proplists:get_value(monitor_nodes, Opts, false),
net_kernel:monitor_nodes(true),
{ok,#state{
locks = ets_new(locks, [ordered_set, {keypos, #lock.object}]),
agents = ets_new(agents, [ordered_set]),
requests = ets_new(reqs, [bag, {keypos, #req.object}]),
down = [],
monitored = orddict:new(),
await_nodes = AwaitNodes,
monitor_nodes = MonNodes,
pending = ets_new(pending, [bag, {keypos, #req.object}]),
sync = [],
client = Client,
client_mref = ClientMRef,
notify = Notify,
options = Opts,
answer = locking}}.
%% @private
handle_call(lock_info, _From, #state{locks = Locks,
pending = Pending} = State) ->
{reply, {ets:tab2list(Pending), ets:tab2list(Locks)}, State};
handle_call(transaction_status, _From, #state{status = Status} = State) ->
{reply, Status, State};
handle_call(await_all_locks, {Client, Tag},
#state{status = Status, awaiting_all = Aw} = State) ->
case Status of
{have_all_locks, _} ->
{noreply, notify_have_all(
State#state{awaiting_all = [{Client, Tag}|Aw]})};
_ ->
{noreply, check_if_done(add_waiter(wait, Client, Tag, State))}
end;
handle_call({monitor_nodes, Bool}, _From, St) when is_boolean(Bool) ->
{reply, St#state.monitor_nodes, St#state{monitor_nodes = Bool}};
handle_call(stop, {Client, _}, State) when Client==?myclient ->
{stop, normal, ok, State};
handle_call(R, _, State) ->
{reply, {unknown_request, R}, State}.
%% @private
handle_cast({lock, Object, Mode, Nodes, Require, Wait, Client, Tag} = _Req,
State) ->
%%
?event(_Req, State),
case matching_request(Object, Mode, Nodes, Require,
add_waiter(Wait, Client, Tag, State)) of
{false, S1} ->
?event({no_matching_request, Object}),
{noreply, check_if_done(
new_request(Object, Mode, Nodes, Require, S1))};
{true, S1} ->
{noreply, check_if_done(S1)}
end;
handle_cast({await_all_locks, Pid},
#state{status = Status, awaiting_all = Aw} = State) ->
case Status of
{have_all_locks, _} ->
{noreply, notify_have_all(
State#state{awaiting_all = [{Pid,async}|Aw]})};
_ ->
{noreply, check_if_done(add_waiter(wait, Pid, async, State))}
end;
handle_cast({surrender, O, ToAgent, Nodes} = _Req, S) ->
?event(_Req, S),
case lists:all(
fun(N) ->
#lock{queue = Q} = L = get_lock({O,N}, S),
lists:member(self(), lock_holders(L))
andalso in_tail(ToAgent, tl(Q))
end, Nodes) of
true ->
NewS = lists:foldl(
fun(OID, Sx) ->
do_surrender(self(), OID, [ToAgent], Sx)
end, S, [{O, N} || N <- Nodes]),
{noreply, check_if_done(NewS)};
false ->
{stop, {cannot_surrender, [O, ToAgent]}, S}
end;
handle_cast({option, O, Val}, #state{notify = Notify,
client = C, options = Opts} = S) ->
S1 = case O of
await_nodes ->
S#state{await_nodes = Val};
notify ->
case Val of
true ->
S1a = case Notify of
[] ->
Status = all_locks_status(S),
set_status(Status, S);
_ -> S
end,
%% always send an initial status notification
C ! {?MODULE, self(), S1a#state.status},
S1a#state{notify = list_store(C, Notify)};
false ->
S#state{notify = S#state.notify -- [C]}
end;
_ ->
S#state{options = lists:keystore(O, 1, Opts, {O, Val})}
end,
{noreply, S1};
handle_cast(_Msg, State) ->
{noreply, State}.
list_store(E, L) ->
case lists:member(E, L) of
true -> L;
false ->
[E|L]
end.
matching_request(Object, Mode, Nodes, Require,
#state{requests = Requests,
pending = Pending} = S) ->
case any_matching_request_(ets_lookup(Pending, Object), Pending,
Object, Mode, Nodes, Require, S) of
{false, S1} ->
any_matching_request_(ets_lookup(Requests, Object), Requests,
Object, Mode, Nodes, Require, S1);
True -> True
end.
any_matching_request_([R|Rs], Tab, Object, Mode, Nodes, Require, S) ->
case matching_request_(R, Tab, Object, Mode, Nodes, Require, S) of
{false, S1} ->
any_matching_request_(Rs, Tab, Object, Mode, Nodes, Require, S1);
True -> True
end;
any_matching_request_([], _, _, _, _, _, S) ->
{false, S}.
matching_request_(Req, Tab, Object, Mode, Nodes, Require, S) ->
case Req of
#req{nodes = Nodes1, require = Require, mode = Mode} ->
?event({repeated_request, Object}),
%% Repeated request
case Nodes -- Nodes1 of
[] ->
{true, S};
[_|_] = New ->
{true, add_nodes(New, Req, Tab, S)}
end;
#req{nodes = Nodes, require = Require, mode = write}
when Mode==read ->
?event({found_old_write_request, Object}),
%% The old request is sufficient
{true, S};
#req{nodes = Nodes, require = Require, mode = read} when Mode==write ->
?event({need_upgrade, Object}),
{false, remove_locks(Object, S)};
#req{nodes = PrevNodes} ->
%% Different conditions from last time
Reason = {conflicting_request,
[Object, Nodes, PrevNodes]},
error(Reason)
end.
remove_locks(Object, #state{locks = Locks, agents = As,
interesting = I} = S) ->
ets:match_delete(Locks, #lock{object = {Object,'_'}, _ = '_'}),
ets:match_delete(As, {{self(),{Object,'_'}}}),
S#state{interesting = prune_interesting(I, object, Object)}.
new_request(Object, Mode, Nodes, Require, #state{pending = Pending,
claim_no = Cl} = State) ->
Req = #req{object = Object,
mode = Mode,
nodes = Nodes,
claim_no = Cl,
require = Require},
ets_insert(Pending, Req),
lists:foldl(
fun(Node, Sx) ->
OID = {Object, Node},
request_lock(
OID, Mode, ensure_monitor(Node, Sx))
end, State, Nodes).
add_nodes(Nodes, #req{object = Object, mode = Mode, nodes = OldNodes} = Req,
Tab, #state{pending = Pending} = State) ->
AllNodes = union(Nodes, OldNodes),
Req1 = Req#req{nodes = AllNodes},
%% replace request
ets_delete_object(Tab, Req),
ets_insert(Pending, Req1),
lists:foldl(
fun(Node, Sx) ->
OID = {Object, Node},
request_lock(
OID, Mode, ensure_monitor(Node, Sx))
end, State, Nodes).
union(A, B) ->
A ++ (B -- A).
%% @private
handle_info(#locks_info{lock = Lock0, where = Node, note = Note} = I, S0) ->
?event({handle_info, I}, S0),
LockID = {Lock0#lock.object, Node},
Lock = Lock0#lock{object = LockID},
Prev = ets_lookup(S0#state.locks, LockID),
State = check_note(Note, LockID, S0),
case outdated(Prev, Lock) orelse waiting_for_ack(State, LockID) of
true ->
?event({outdated_or_waiting_for_ack, [LockID]}),
{noreply,State};
false ->
NewState = i_add_lock(State, Lock, Prev),
{noreply, handle_locks(check_if_done(NewState, [I]))}
end;
handle_info({surrendered, A, OID} = _Msg, State) ->
?event(_Msg),
{noreply, note_deadlock(A, OID, State)};
handle_info({'DOWN', Ref, _, _, _Rsn}, #state{client_mref = Ref} = State) ->
?event({client_DOWN, _Rsn}),
{stop, normal, State};
handle_info({'DOWN', _, process, {?LOCKER, Node}, _},
#state{down = Down} = S) ->
?event({locker_DOWN, Node}),
case lists:member(Node, Down) of
true -> {noreply, S};
false ->
handle_nodedown(Node, S)
end;
handle_info({'DOWN',_,_,_,_}, S) ->
%% most likely a watcher
{noreply, S};
handle_info({nodeup, N} = _Msg, #state{down = Down} = S) ->
?event(_Msg),
case S#state.monitor_nodes orelse lists:member(N, Down) of
true -> watch_node(N);
false -> ignore
end,
{noreply, S};
handle_info({nodedown,_}, S) ->
%% We react on 'DOWN' messages above instead
{noreply, S};
handle_info({locks_running,N} = Msg, #state{down=Down, pending=Pending,
requests = Reqs,
monitor_nodes = MonNodes,
client = C} = S) ->
?event(Msg),
if MonNodes ->
C ! {nodeup, N};
true ->
ignore
end,
case lists:member(N, Down) of
true ->
S1 = S#state{down = Down -- [N]},
{R, P} = Res = {requests_with_node(N, Reqs),
requests_with_node(N, Pending)},
?event({{reqs, pending}, Res}),
case R ++ P of
[] ->
{noreply, S1};
Reissue ->
move_requests(R, Reqs, Pending),
S2 = lists:foldl(
fun(#req{object = Obj, mode = Mode}, Sx) ->
request_lock({Obj,N}, Mode, Sx)
end, ensure_monitor(N, S1), Reissue),
{noreply, check_if_done(S2)}
end;
false ->
{noreply, S}
end;
handle_info({'EXIT', Client, Reason}, #state{client = Client} = S) ->
{stop, Reason, S};
handle_info(_Msg, S) ->
?event({unknown_msg, _Msg}),
{noreply, S}.
add_waiter(nowait, _, _, State) ->
State;
add_waiter(wait, Client, Tag, #state{awaiting_all = Aw} = State) ->
State#state{awaiting_all = [{Client, Tag} | Aw]}.
set_status(Status, #state{status = Status} = S) ->
S;
set_status({have_all_locks, _} = Status, S) ->
have_all(S#state{status = Status});
set_status(Status, S) ->
S#state{status = Status, have_all = false}.
maybe_status_change(Status, #state{status = Status} = State) ->
?event(no_status_change),
State;
maybe_status_change(OldStatus, #state{status = Status} = S) ->
?event({status_change, OldStatus, Status}),
notify(Status, S).
requests_for_obj_can_be_served(Obj, #state{pending = Pending} = S) ->
lists:all(
fun(R) ->
request_can_be_served(R, S)
end, ets:lookup(Pending, Obj)).
request_can_be_served(_, #state{await_nodes = true}) ->
true;
request_can_be_served(#req{nodes = Ns, require = R}, #state{down = Down}) ->
case R of
all -> intersection(Down, Ns) == [];
any -> Ns -- Down =/= [];
majority -> length(Ns -- Down) > (length(Ns) div 2);
majority_alive -> true;
all_alive -> true
end.
handle_nodedown(Node, #state{down = Down, requests = Reqs,
pending = Pending,
monitored = Mon, locks = Locks,
interesting = I,
agents = Agents,
monitor_nodes = MonNodes} = S) ->
?event({handle_nodedown, Node}, S),
handle_monitor_on_down(Node, S),
ets_match_delete(Locks, #lock{object = {'_',Node}, _ = '_'}),
ets_match_delete(Agents, {{'_',{'_',Node}}}),
Down1 = [Node|Down -- [Node]],
S1 = S#state{down = Down1, interesting = prune_interesting(I, node, Node),
monitored = lists:keydelete(Node, 1, Mon)},
Res = {requests_with_node(Node, Reqs),
requests_with_node(Node, Pending)},
?event({{reqs,pending}, Res}),
case Res of
{[], []} ->
{noreply, S1};
{Rs, PRs} ->
move_requests(Rs, Reqs, Pending),
case S1#state.await_nodes of
false ->
case [R || R <- Rs ++ PRs,
request_can_be_served(R, S1) =:= false] of
[] ->
{noreply, check_if_done(S1)};
Lost ->
{stop, {cannot_lock_objects, Lost}, S1}
end;
true ->
case MonNodes == false
andalso lists:member(Node, nodes()) of
true -> watch_node(Node);
false -> ignore
end,
if PRs =/= [] ->
{noreply, check_if_done(S1)};
true ->
{noreply, S1}
end
end
end.
handle_monitor_on_down(_, #state{monitor_nodes = false}) ->
ok;
handle_monitor_on_down(Node, #state{monitor_nodes = true,
client = C}) ->
C ! {nodedown, Node},
case lists:member(Node, nodes()) of
true ->
watch_node(Node);
false ->
ignore
end,
ok.
prune_interesting(I, node, Node) ->
[OID || {_, N} = OID <- I, N =/= Node];
prune_interesting(I, object, Object) ->
[OID || {O, _} = OID <- I, O =/= Object].
watch_node(N) ->
{M, F, A} =
locks_watcher(self()), % expanded through parse_transform
P = spawn(N, M, F, A),
erlang:monitor(process, P).
check_note([], _, State) ->
State;
check_note({surrender, A}, LockID, State) when A == self() ->
?event({surrender_ack, LockID}),
Sync = [L || #lock{object = Ox} = L <- State#state.sync,
Ox =/= LockID],
State#state{sync = Sync};
check_note({surrender, A}, LockID, State) ->
note_deadlock(A, LockID, State).
note_deadlock(A, LockID, #state{deadlocks = Deadlocks} = State) ->
Entry = {A, LockID},
case member(Entry, Deadlocks) of
false ->
State#state{deadlocks = [Entry|Deadlocks]};
true ->
State
end.
intersection(A, B) ->
A -- (A -- B).
ensure_monitor(Node, S) when Node == node() ->
S;
ensure_monitor(Node, #state{monitored = Mon} = S) ->
Mon1 = ensure_monitor_(?LOCKER, Node, Mon),
S#state{monitored = Mon1}.
ensure_monitor_(Locker, Node, Mon) ->
case orddict:is_key(Node, Mon) of
true ->
Mon;
false ->
Ref = erlang:monitor(process, {Locker, Node}),
orddict:store(Node, Ref, Mon)
end.
request_lock({OID, Node} = _LockID, Mode, #state{client = Client} = State) ->
?event({request_lock, _LockID}),
P = {?LOCKER, Node},
erlang:monitor(process, P),
locks_server:lock(OID, [Node], Client, Mode),
State.
request_surrender({OID, Node} = _LockID, #state{}) ->
?event({request_surrender, _LockID}),
locks_server:surrender(OID, Node).
check_if_done(S) ->
check_if_done(S, []).
check_if_done(#state{} = State, Msgs) ->
Status = all_locks_status(State),
notify_msgs(Msgs, set_status(Status, State)).
have_all(#state{have_all = Prev, claim_no = Cl} = State) ->
Cl1 = case Prev of
true -> Cl;
false -> Cl + 1
end,
notify_have_all(State#state{have_all = true, claim_no = Cl1}).
notify_have_all(#state{awaiting_all = Aw, status = Status} = S) ->
[reply_await_(W, Status) || W <- Aw],
S#state{awaiting_all = []}.
reply_await_({Pid, notify}, Status) ->
notify_(Pid, Status);
reply_await_({Pid, async}, Status) ->
notify_(Pid, Status);
reply_await_(From, Status) ->
gen_server:reply(From, Status).
abort_on_deadlock(OID, State) ->
notify({abort, Reason = {deadlock, OID}}, State),
error(Reason).
notify_msgs([M|Ms], S) ->
S1 = notify_msgs(Ms, S),
notify(M, S1);
notify_msgs([], S) ->
S.
notify(Msg, #state{notify = Notify} = State) ->
[notify_(P, Msg) || P <- Notify],
State.
notify_(P, Msg) ->
P ! {?MODULE, self(), Msg}.
handle_locks(#state{have_all = true} = State) ->
%% If we have all locks we've asked for, no need to search for potential
%% deadlocks - reasonably, we cannot be involved in one.
State;
handle_locks(#state{agents = As} = State) ->
InvolvedAgents = involved_agents(As),
case analyse(InvolvedAgents, State) of
ok ->
%% possible indirect deadlocks
%% inefficient computation, optimizes easily
Tell = send_indirects(State),
if Tell =/= [] ->
?event({tell, Tell});
true ->
ok
end,
State;
{deadlock,ShouldSurrender,ToObject} = _DL ->
?event(_DL),
case ShouldSurrender == self()
andalso
(proplists:get_value(
abort_on_deadlock, State#state.options, false)
andalso object_claimed(ToObject, State)) of
true -> abort_on_deadlock(ToObject, State);