%%%------------------------------------------------------------------- %%% @author anlicheng %%% @copyright (C) 2025, %%% @doc %%% %%% @end %%% Created : 18. 4月 2025 16:42 %%%------------------------------------------------------------------- -module(efka_micro_service_sup). -author("anlicheng"). -include("efka_tables.hrl"). -behaviour(supervisor). %% API -export([start_link/0]). -export([start_service/1, delete_service/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== %% @doc Starts the supervisor -spec(start_link() -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private %% @doc Whenever a supervisor is started using supervisor:start_link/[2,3], %% this function is called by the new process to find out about %% restart strategy, maximum restart frequency and child %% specifications. -spec(init(Args :: term()) -> {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(), MaxR :: non_neg_integer(), MaxT :: non_neg_integer()}, [ChildSpec :: supervisor:child_spec()]}} | ignore | {error, Reason :: term()}). init([]) -> SupFlags = #{strategy => one_for_one, intensity => 1000, period => 3600}, MicroServices = micro_service_model:get_all_services(), Specs = lists:map(fun(Service) -> child_spec(Service) end, MicroServices), Spec1 = child_spec(#micro_service{ service_id = <<"test1234">>, service_name = <<"测试服务">>, from = <<"master">>, %% 工作目录 work_dir = <<"/usr/local/code/tmp/test/">>, params = <<"">>, metrics = <<"">>, %% 状态: 0: 停止, 1: 运行中 status = 1 }), {ok, {SupFlags, [Spec1|Specs]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== -spec start_service(Service :: #micro_service{}) -> {ok, Pid :: pid()} | {error, Reason :: any()}. start_service(Service) -> case supervisor:start_child(?MODULE, child_spec(Service)) of {ok, Pid} when is_pid(Pid) -> {ok, Pid}; {error, {'already_started', Pid}} when is_pid(Pid) -> {ok, Pid}; {error, Error} -> {error, Error} end. -spec delete_service(ServiceId :: binary()) -> ok. delete_service(ServiceId) when is_binary(ServiceId) -> ChildId = efka_micro_service:get_name(ServiceId), ok = supervisor:terminate_child(?MODULE, ChildId), supervisor:delete_child(?MODULE, ChildId). child_spec(S = #micro_service{service_id = ServiceId}) when is_binary(ServiceId) -> Name = efka_micro_service:get_name(ServiceId), #{ id => Name, start => {efka_micro_service, start_link, [Name, S]}, restart => permanent, shutdown => 2000, type => worker, modules => ['efka_micro_service'] }.