59 lines
1.8 KiB
Erlang
59 lines
1.8 KiB
Erlang
%%%-------------------------------------------------------------------
|
|
%%% @author aresei
|
|
%%% @copyright (C) 2023, <COMPANY>
|
|
%%% @doc
|
|
%%% @end
|
|
%%%-------------------------------------------------------------------
|
|
-module(iot_host_sup).
|
|
-include("iot.hrl").
|
|
|
|
-behaviour(supervisor).
|
|
|
|
-export([start_link/0, init/1, delete_host/1, ensured_host_started/1]).
|
|
|
|
start_link() ->
|
|
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
|
|
|
|
init([]) ->
|
|
Specs = lists:map(fun child_spec/1, iot_api:get_all_hosts()),
|
|
|
|
{ok, {#{strategy => one_for_one, intensity => 1000, period => 3600}, Specs}}.
|
|
|
|
-spec ensured_host_started(UUID :: binary()) -> {ok, Pid :: pid()} | {error, Reason :: any()}.
|
|
ensured_host_started(UUID) when is_binary(UUID) ->
|
|
case iot_host:get_pid(UUID) of
|
|
undefined ->
|
|
%% 尝试删除下host对应的信息
|
|
delete_host(UUID),
|
|
case supervisor:start_child(?MODULE, child_spec(UUID)) of
|
|
{ok, Pid} when is_pid(Pid) ->
|
|
{ok, Pid};
|
|
{error, {'already_started', Pid}} when is_pid(Pid) ->
|
|
{ok, Pid};
|
|
{error, Error} ->
|
|
{error, Error}
|
|
end;
|
|
Pid when is_pid(Pid) ->
|
|
{ok, Pid}
|
|
end.
|
|
|
|
delete_host(UUID) ->
|
|
Id = iot_host:get_name(UUID),
|
|
ok = supervisor:terminate_child(?MODULE, Id),
|
|
case supervisor:delete_child(?MODULE, Id) of
|
|
{error, running} ->
|
|
%% ensure killed then delete again
|
|
iot_host:kill(UUID),
|
|
supervisor:delete_child(?MODULE, Id);
|
|
_ ->
|
|
ok
|
|
end.
|
|
|
|
child_spec(UUID) ->
|
|
Id = iot_host:get_name(UUID),
|
|
#{id => Id,
|
|
start => {iot_host, start_link, [Id, UUID]},
|
|
restart => permanent,
|
|
shutdown => 2000,
|
|
type => worker,
|
|
modules => ['iot_host']}. |