xref: /6.0.3/ns_server/src/async.erl (revision 4205289b)
1%% @author Couchbase <info@couchbase.com>
2%% @copyright 2017-2018 Couchbase, Inc.
3%%
4%% Licensed under the Apache License, Version 2.0 (the "License");
5%% you may not use this file except in compliance with the License.
6%% You may obtain a copy of the License at
7%%
8%%      http://www.apache.org/licenses/LICENSE-2.0
9%%
10%% Unless required by applicable law or agreed to in writing, software
11%% distributed under the License is distributed on an "AS IS" BASIS,
12%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13%% See the License for the specific language governing permissions and
14%% limitations under the License.
15
16-module(async).
17
18-include("cut.hrl").
19-include("ns_common.hrl").
20-include_lib("eunit/include/eunit.hrl").
21
22-export([start/1, start/2,
23         start_many/2, start_many/3,
24         perform/1, perform/2,
25         abort/1, abort/2,
26         abort_many/1, abort_many/2,
27         send/2,
28         with/2, with/3,
29         with_many/3, with_many/4,
30         wait/1, wait/2,
31         wait_many/1, wait_many/2,
32         wait_any/1, wait_any/2,
33         race/2, map/2, foreach/2,
34         run_with_timeout/2,
35         get_identity/0]).
36
37start(Fun) ->
38    start(Fun, []).
39
40start(Fun, Opts) ->
41    SpawnFun =
42        case proplists:get_value(monitor, Opts, false) of
43            true ->
44                fun misc:spawn_monitor/1;
45            false ->
46                fun proc_lib:spawn/1
47        end,
48
49    Parent           = self(),
50    ParentController = get_controller(),
51
52    SpawnFun(
53      fun () ->
54              async_init(Parent, ParentController, Opts, Fun)
55      end).
56
57perform(Fun) ->
58    perform(Fun, [monitor]).
59
60perform(Fun, Opts) ->
61    start(Fun, Opts ++ [{type, perform}]).
62
63start_many(Fun, Args) ->
64    start_many(Fun, Args, []).
65
66start_many(Fun, Args, Opts) ->
67    [start(fun () ->
68                   Fun(A)
69           end, Opts) || A <- Args].
70
71abort(Pid) ->
72    abort_many([Pid]).
73
74abort(Pid, Reason) ->
75    abort_many([Pid], Reason).
76
77abort_many(Pids) ->
78    abort_many(Pids, shutdown).
79
80abort_many(Pids, Reason) ->
81    misc:terminate_and_wait(Pids, Reason).
82
83send(Async, Msg) ->
84    Async ! {'$async_msg', Msg},
85    Msg.
86
87with(AsyncBody, Fun) ->
88    with(AsyncBody, [], Fun).
89
90with(AsyncBody, Opts, Fun) ->
91    Async = start(AsyncBody, Opts),
92    try
93        Fun(Async)
94    after
95        abort(Async)
96    end.
97
98with_many(AsyncBody, Args, Fun) ->
99    with_many(AsyncBody, Args, [], Fun).
100
101with_many(AsyncBody, Args, Opts, Fun) ->
102    Asyncs = start_many(AsyncBody, Args, Opts),
103    try
104        Fun(Asyncs)
105    after
106        abort_many(Asyncs)
107    end.
108
109wait(Pid) ->
110    wait(Pid, []).
111
112wait(Pid, Flags) ->
113    call(Pid, get_result, Flags).
114
115wait_many(Pids) ->
116    wait_many(Pids, []).
117
118wait_many(Pids, Flags) ->
119    call_many(Pids, get_result, Flags).
120
121wait_any(Pids) ->
122    wait_any(Pids, []).
123
124wait_any(Pids, Flags) ->
125    call_any(Pids, get_result, Flags).
126
127race(Fun1, Fun2) ->
128    with(
129      Fun1,
130      fun (Async1) ->
131              with(
132                Fun2,
133                fun (Async2) ->
134                        case wait_any([Async1, Async2]) of
135                            {Async1, R} ->
136                                {left, R};
137                            {Async2, R} ->
138                                {right, R}
139                        end
140                end)
141      end).
142
143map(Fun, List) ->
144    with_many(
145      Fun, List,
146      fun (Asyncs) ->
147              Results = wait_many(Asyncs),
148              [R || {_, R} <- Results]
149      end).
150
151foreach(Fun, List) ->
152    with_many(
153      Fun, List,
154      fun (Asyncs) ->
155              _ = wait_many(Asyncs),
156              ok
157      end).
158
159run_with_timeout(Fun, Timeout) ->
160    case race(Fun, fun () -> receive after Timeout -> timeout end end) of
161        {left, R} ->
162            {ok, R};
163        {right, timeout} ->
164            {error, timeout}
165    end.
166
167get_identity() ->
168    case get_role() of
169        executor ->
170            Controller = get_controller(),
171            true = is_pid(Controller),
172
173            {ok, Controller};
174        _ ->
175            not_async
176    end.
177
178%% internal
179async_init(Parent, ParentController, Opts, Fun) ->
180    erlang:monitor(process, Parent),
181
182    set_role(controller),
183    maybe_register_with_parent_async(ParentController),
184
185    MonitorPids = proplists:get_value(monitor_pids, Opts, []),
186    lists:foreach(erlang:monitor(process, _), MonitorPids),
187
188    Adopters = proplists:get_value(adopters, Opts, []),
189    lists:foreach(register_for_adoption(_), Adopters),
190
191    process_flag(trap_exit, true),
192
193    Reply      = make_ref(),
194    Controller = self(),
195
196    Child =
197        spawn_link(
198          fun () ->
199                  set_role(executor),
200                  set_controller(Controller),
201
202                  To = {Controller, Reply},
203
204                  try Fun() of
205                      R ->
206                          reply(To, {ok, R})
207                  catch
208                      T:E ->
209                          Stack = erlang:get_stacktrace(),
210                          reply(To, {raised, {T, E, Stack}}),
211                          erlang:raise(T, E, Stack)
212                  end
213          end),
214
215    case proplists:get_value(abort_after, Opts) of
216        undefined ->
217            ok;
218        AbortAfter when is_integer(AbortAfter) ->
219            erlang:send_after(AbortAfter, self(), abort_after_expired)
220    end,
221
222    Type = proplists:get_value(type, Opts, wait),
223    async_loop_wait_result(Type, Child, Reply, []).
224
225maybe_register_with_parent_async(undefined) ->
226    ok;
227maybe_register_with_parent_async(Pid) ->
228    {ok, _} = register_with_async(Pid).
229
230register_with_async(Pid) ->
231    controller = get_role(),
232    {ok, _} = call(Pid, {register_child_async, self()}).
233
234async_loop_wait_result(Type, Child, Reply, ChildAsyncs) ->
235    receive
236        {'DOWN', _MRef, process, _Pid, Reason} = Down ->
237            maybe_log_down_message(Down),
238            terminate_now(Child, ChildAsyncs, Reason);
239        {'EXIT', Child, Reason} ->
240            terminate_on_query(Type,
241                               undefined, ChildAsyncs, {child_died, Reason});
242        %% note, we don't assume that this comes from the parent, because we
243        %% can be terminated by parent async, for example, which is not the
244        %% actual parent of our process
245        {'EXIT', _, Reason} ->
246            terminate_now(Child, ChildAsyncs, Reason);
247        {'$async_req', From, {register_child_async, Pid}} ->
248            reply(From, {ok, Child}),
249            async_loop_wait_result(Type, Child, Reply, [Pid | ChildAsyncs]);
250        {Reply, Result} ->
251            async_loop_handle_result(Type, Child, ChildAsyncs, Result);
252        {'$async_msg', Msg} ->
253            Child ! Msg,
254            async_loop_wait_result(Type, Child, Reply, ChildAsyncs);
255        abort_after_expired ->
256            terminate_on_query(Type, Child, ChildAsyncs, timeout)
257    end.
258
259maybe_terminate_child(undefined, _Reason) ->
260    ok;
261maybe_terminate_child(Child, Reason)
262  when is_pid(Child) ->
263    misc:unlink_terminate_and_wait(Child, Reason).
264
265terminate_children(Child, ChildAsyncs, Reason) ->
266    maybe_terminate_child(Child, Reason),
267    misc:terminate_and_wait(ChildAsyncs, Reason).
268
269terminate_now(Child, ChildAsyncs, Reason) ->
270    terminate_children(Child, ChildAsyncs, Reason),
271    exit(Reason).
272
273terminate_on_query(perform, Child, ChildAsyncs, Reason) ->
274    terminate_now(Child, ChildAsyncs, Reason);
275terminate_on_query(wait, Child, ChildAsyncs, Reason) ->
276    terminate_children(Child, ChildAsyncs, Reason),
277    async_loop_with_result({die, Reason}).
278
279async_loop_handle_result(Type, Child, ChildAsyncs, Result) ->
280    unlink(Child),
281    ?flush({'EXIT', Child, _}),
282
283    misc:terminate_and_wait(ChildAsyncs, shutdown),
284
285    case Type of
286        perform ->
287            case Result of
288                {raised, {T, E, Stack}} ->
289                    erlang:raise(T, E, Stack);
290                {ok, _} ->
291                    exit(normal)
292            end;
293        wait ->
294            case Result of
295                {ok, Success} ->
296                    async_loop_with_result({reply, Success});
297                {raised, _} = Raised ->
298                    async_loop_with_result({die, Raised})
299            end
300    end.
301
302async_loop_with_result(Result) ->
303    receive
304        {'DOWN', _MRef, process, _Pid, Reason} = Down ->
305            maybe_log_down_message(Down),
306            exit(Reason);
307        {'EXIT', _, Reason} ->
308            exit(Reason);
309        {'$async_req', From, get_result} ->
310            handle_get_result(From, Result);
311        {'$async_req', From, {register_child_async, _Pid}} ->
312            %% We don't expect register requests at this point, but it's
313            %% possible to write a correct async that has such behavior. If we
314            %% don't reply, the requesting process will have to wait till we
315            %% die, which is unnecessary. So we just respond with nack to kill
316            %% it quickly.
317            reply(From, nack);
318        {'$async_req', From, _} ->
319            %% Similar logic applies to all the other requests (that actually
320            %% don't exist at the moment).
321            reply(From, nack);
322        _ ->
323            async_loop_with_result(Result)
324    end.
325
326handle_get_result(From, {reply, Result}) ->
327    reply(From, Result);
328handle_get_result(_From, {die, Reason}) ->
329    exit(Reason).
330
331call(Pid, Req) ->
332    call(Pid, Req, []).
333
334call(Pid, Req, Flags) ->
335    [{Pid, R}] = call_many([Pid], Req, Flags),
336    R.
337
338call_many(Pids, Req, Flags) ->
339    PidMRefs = monitor_asyncs(Pids),
340    try
341        send_req_many(PidMRefs, Req),
342        recv_many(PidMRefs, Flags)
343    after
344        demonitor_asyncs(PidMRefs)
345    end.
346
347call_any(Pids, Req, Flags) ->
348    PidMRefs = monitor_asyncs(Pids),
349    try
350        send_req_many(PidMRefs, Req),
351        recv_any(PidMRefs, Flags)
352    after
353        Pids = demonitor_asyncs(PidMRefs),
354        abort_many(Pids),
355        drop_extra_resps(PidMRefs)
356    end.
357
358drop_extra_resps(PidMRefs) ->
359    lists:foreach(
360      fun ({_, MRef}) ->
361              ?flush({MRef, _})
362      end, PidMRefs).
363
364reply({Pid, Tag}, Reply) ->
365    Pid ! {Tag, Reply}.
366
367monitor_asyncs(Pids) ->
368    [{Pid, erlang:monitor(process, Pid)} || Pid <- Pids].
369
370demonitor_asyncs(PidMRefs) ->
371    lists:map(
372      fun ({Pid, MRef}) ->
373              erlang:demonitor(MRef, [flush]),
374              Pid
375      end, PidMRefs).
376
377send_req(Pid, MRef, Req) ->
378    Pid ! {'$async_req', {self(), MRef}, Req}.
379
380send_req_many(PidMRefs, Req) ->
381    lists:foreach(
382      fun ({Pid, MRef}) ->
383              send_req(Pid, MRef, Req)
384      end, PidMRefs).
385
386recv_resp(MRef, Interruptible) ->
387    receive
388        {MRef, R} ->
389            R;
390        {'DOWN', MRef, _, _, Reason} ->
391            recv_resp_handle_down(Reason);
392        {'EXIT', _Pid, _Reason} = Exit when Interruptible ->
393            throw({interrupted, Exit})
394    end.
395
396recv_resp_handle_down({raised, {T, E, Stack}}) ->
397    erlang:raise(T, E, Stack);
398recv_resp_handle_down(Reason) ->
399    exit(Reason).
400
401recv_many(PidMRefs, Flags) ->
402    Interruptible = proplists:get_bool(interruptible, Flags),
403    [{Pid, recv_resp(MRef, Interruptible)} || {Pid, MRef} <- PidMRefs].
404
405recv_any(PidMRefs, Flags) ->
406    Interruptible = proplists:get_bool(interruptible, Flags),
407    recv_any_loop(PidMRefs, Interruptible, []).
408
409recv_any_loop(PidMRefs, Interruptible, PendingMsgs) ->
410    receive
411        {Ref, R} = Msg when is_reference(Ref) ->
412            case lists:keyfind(Ref, 2, PidMRefs) of
413                {Pid, Ref} ->
414                    recv_any_loop_resend_pending(PendingMsgs),
415                    {Pid, R};
416                false ->
417                    recv_any_loop(PidMRefs,
418                                  Interruptible,
419                                  [Msg | PendingMsgs])
420            end;
421        {'DOWN', Ref, _, _, Reason} = Msg ->
422            case lists:keymember(Ref, 2, PidMRefs) of
423                true ->
424                    recv_any_loop_resend_pending(PendingMsgs),
425                    recv_resp_handle_down(Reason);
426                false ->
427                    recv_any_loop(PidMRefs,
428                                  Interruptible,
429                                  [Msg | PendingMsgs])
430            end;
431        {'EXIT', _Pid, _Reason} = Exit when Interruptible ->
432            throw({interrupted, Exit})
433    end.
434
435recv_any_loop_resend_pending(PendingMsgs) ->
436    lists:foreach(
437      fun (Msg) ->
438              self() ! Msg
439      end, lists:reverse(PendingMsgs)).
440
441set_role(Role) ->
442    erlang:put('$async_role', Role).
443
444get_role() ->
445    erlang:get('$async_role').
446
447set_controller(Pid) when is_pid(Pid) ->
448    executor = get_role(),
449    erlang:put('$async_controller', Pid).
450
451get_controller() ->
452    erlang:get('$async_controller').
453
454register_for_adoption(Controller) ->
455    {ok, Executor} = register_with_async(Controller),
456    erlang:monitor(process, Executor).
457
458maybe_log_down_message({'DOWN', _MRef, process, Pid, Reason}) ->
459    case misc:is_normal_termination(Reason) of
460        true ->
461            ok;
462        false ->
463            ?log_warning("Monitored process ~p "
464                         "terminated abnormally (reason = ~p)", [Pid, Reason])
465    end.
466
467-ifdef(EUNIT).
468abort_after_test() ->
469    A1 = async:start(?cut(timer:sleep(10000)), [{abort_after, 100}]),
470    ?assertExit(timeout, async:wait(A1)),
471
472    A2 = async:start(?cut(timer:sleep(10000)), [{abort_after, 100}]),
473    timer:sleep(200),
474    ?assertExit(timeout, async:wait(A2)),
475
476    ok = async:with(?cut(timer:sleep(100)),
477                    [{abort_after, 200}], async:wait(_)),
478
479
480    {A3, MRef} = async:perform(?cut(timer:sleep(1000)),
481                               [monitor, {abort_after, 100}]),
482    ?must_flush({'DOWN', MRef, process, A3, timeout}).
483-endif.
484