1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2012-2018. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20
21-module(ct_default_gl).
22-export([start_link/1, stop/0]).
23
24-export([init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2]).
25
26%% start_link()
27%% Start a new group leader process.
28start_link(ParentGL) ->
29    do_start(ParentGL, 3).
30
31do_start(_ParentGL, 0) ->
32    exit({?MODULE,startup});
33do_start(ParentGL, Retries) ->
34    case whereis(?MODULE) of
35	undefined ->
36	    case gen_server:start_link(?MODULE, [ParentGL], []) of
37		{ok,Pid} ->
38		    {ok,Pid};
39		Other ->
40		    Other
41	    end;
42	Pid ->
43	    exit(Pid, kill),
44	    timer:sleep(1000),
45	    do_start(ParentGL, Retries-1)
46    end.
47
48%% stop(Pid)
49%% Stop a group leader process.
50stop() ->
51    gen_server:cast(whereis(?MODULE), stop).
52
53
54%%% Internal functions.
55
56init([ParentGL]) ->
57    register(?MODULE, self()),
58    ct_util:mark_process(),
59    {ok,#{parent_gl_pid => ParentGL,
60	  parent_gl_monitor => erlang:monitor(process,ParentGL)}}.
61
62handle_cast(stop, St) ->
63    {stop,normal,St}.
64
65%% If the parent group leader dies, fall back on using the local user process
66handle_info({'DOWN',Ref,process,_,_Reason}, #{parent_gl_monitor := Ref} = St) ->
67    User = whereis(user),
68    {noreply,St#{parent_gl_pid => User,
69		 parent_gl_monitor => erlang:monitor(process,User)}};
70
71handle_info({io_request,_From,_ReplyAs,_Req} = IoReq,
72	    #{parent_gl_pid := ParentGL} = St) ->
73    ParentGL ! IoReq,
74    {noreply,St};
75
76handle_info(Msg, St) ->
77    io:format(user, "Common Test Group Leader process got: ~tp~n", [Msg]),
78    {noreply,St}.
79
80handle_call(_Req, _From, St) ->
81    {reply,ok,St}.
82
83terminate(_, _) ->
84    ok.
85