You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

340 line
13 KiB

  1. %%% @doc Runs a process that holds a rebar3 state and can be used
  2. %%% to statefully maintain loaded project state into a running VM.
  3. -module(rebar_agent).
  4. -export([start_link/1, do/1, do/2, async_do/1, async_do/2]).
  5. -export(['$handle_undefined_function'/2]).
  6. -export([init/1,
  7. handle_call/3, handle_cast/2, handle_info/2,
  8. code_change/3, terminate/2]).
  9. -include("rebar.hrl").
  10. -record(state, {state,
  11. cwd,
  12. show_warning=true}).
  13. %% @doc boots an agent server; requires a full rebar3 state already.
  14. %% By default (within rebar3), this isn't called; `rebar_prv_shell'
  15. %% enters and transforms into this module
  16. -spec start_link(rebar_state:t()) -> {ok, pid()}.
  17. start_link(State) ->
  18. gen_server:start_link({local, ?MODULE}, ?MODULE, State, []).
  19. %% @doc runs a given command in the agent's context.
  20. -spec do(atom()) -> ok | {error, term()}.
  21. do(Command) when is_atom(Command) ->
  22. gen_server:call(?MODULE, {cmd, Command}, infinity);
  23. do(Args) when is_list(Args) ->
  24. gen_server:call(?MODULE, {cmd, default, do, Args}, infinity).
  25. %% @doc runs a given command in the agent's context, under a given
  26. %% namespace.
  27. -spec do(atom(), atom()) -> ok | {error, term()}.
  28. do(Namespace, Command) when is_atom(Namespace), is_atom(Command) ->
  29. gen_server:call(?MODULE, {cmd, Namespace, Command}, infinity);
  30. do(Namespace, Args) when is_atom(Namespace), is_list(Args) ->
  31. gen_server:call(?MODULE, {cmd, Namespace, do, Args}, infinity).
  32. -spec async_do(atom()) -> ok | {error, term()}.
  33. async_do(Command) when is_atom(Command) ->
  34. gen_server:cast(?MODULE, {cmd, Command});
  35. async_do(Args) when is_list(Args) ->
  36. gen_server:cast(?MODULE, {cmd, default, do, Args}).
  37. -spec async_do(atom(), atom()) -> ok.
  38. async_do(Namespace, Command) when is_atom(Namespace), is_atom(Command) ->
  39. gen_server:cast(?MODULE, {cmd, Namespace, Command});
  40. async_do(Namespace, Args) when is_atom(Namespace), is_list(Args) ->
  41. gen_server:cast(?MODULE, {cmd, Namespace, do, Args}).
  42. '$handle_undefined_function'(Cmd, [Namespace, Args]) ->
  43. gen_server:call(?MODULE, {cmd, Namespace, Cmd, Args}, infinity);
  44. '$handle_undefined_function'(Cmd, [Args]) ->
  45. gen_server:call(?MODULE, {cmd, default, Cmd, Args}, infinity);
  46. '$handle_undefined_function'(Cmd, []) ->
  47. gen_server:call(?MODULE, {cmd, default, Cmd}, infinity).
  48. %%%%%%%%%%%%%%%%%
  49. %%% CALLBACKS %%%
  50. %%%%%%%%%%%%%%%%%
  51. %% @private
  52. init(State) ->
  53. Cwd = rebar_dir:get_cwd(),
  54. {ok, #state{state=State, cwd=Cwd}}.
  55. %% @private
  56. handle_call({cmd, Command}, _From, State=#state{state=RState, cwd=Cwd}) ->
  57. MidState = maybe_show_warning(State),
  58. put(cmd_type, sync),
  59. {Res, NewRState} = run(default, Command, "", RState, Cwd),
  60. put(cmd_type, undefined),
  61. {reply, Res, MidState#state{state=NewRState}, hibernate};
  62. handle_call({cmd, Namespace, Command}, _From, State = #state{state=RState, cwd=Cwd}) ->
  63. MidState = maybe_show_warning(State),
  64. put(cmd_type, sync),
  65. {Res, NewRState} = run(Namespace, Command, "", RState, Cwd),
  66. put(cmd_type, undefined),
  67. {reply, Res, MidState#state{state=NewRState}, hibernate};
  68. handle_call({cmd, Namespace, Command, Args}, _From, State = #state{state=RState, cwd=Cwd}) ->
  69. MidState = maybe_show_warning(State),
  70. put(cmd_type, sync),
  71. {Res, NewRState} = run(Namespace, Command, Args, RState, Cwd),
  72. put(cmd_type, undefined),
  73. {reply, Res, MidState#state{state=NewRState}, hibernate};
  74. handle_call(_Call, _From, State) ->
  75. {noreply, State}.
  76. %% @private
  77. handle_cast({cmd, Command}, State=#state{state=RState, cwd=Cwd}) ->
  78. MidState = maybe_show_warning(State),
  79. put(cmd_type, async),
  80. {_, NewRState} = run(default, Command, "", RState, Cwd),
  81. put(cmd_type, undefined),
  82. {noreply, MidState#state{state=NewRState}, hibernate};
  83. handle_cast({cmd, Namespace, Command}, State = #state{state=RState, cwd=Cwd}) ->
  84. MidState = maybe_show_warning(State),
  85. put(cmd_type, async),
  86. {_, NewRState} = run(Namespace, Command, "", RState, Cwd),
  87. put(cmd_type, undefined),
  88. {noreply, MidState#state{state=NewRState}, hibernate};
  89. handle_cast({cmd, Namespace, Command, Args}, State = #state{state=RState, cwd=Cwd}) ->
  90. MidState = maybe_show_warning(State),
  91. put(cmd_type, async),
  92. {_, NewRState} = run(Namespace, Command, Args, RState, Cwd),
  93. put(cmd_type, undefined),
  94. {noreply, MidState#state{state=NewRState}, hibernate};
  95. handle_cast(_Cast, State) ->
  96. {noreply, State}.
  97. %% @private
  98. handle_info(_Info, State) ->
  99. {noreply, State}.
  100. %% @private
  101. code_change(_OldVsn, State, _Extra) ->
  102. {ok, State}.
  103. %% @private
  104. terminate(_Reason, _State) ->
  105. ok.
  106. %%%%%%%%%%%%%%%
  107. %%% PRIVATE %%%
  108. %%%%%%%%%%%%%%%
  109. %% @private runs the actual command and maintains the state changes
  110. -spec run(atom(), atom(), string(), rebar_state:t(), file:filename()) ->
  111. {ok, rebar_state:t()} | {{error, term()}, rebar_state:t()}.
  112. run(Namespace, Command, StrArgs, RState, Cwd) ->
  113. try
  114. case rebar_dir:get_cwd() of
  115. Cwd ->
  116. PArgs = getopt:tokenize(StrArgs),
  117. Args = [atom_to_list(Namespace), atom_to_list(Command)] ++ PArgs,
  118. CmdState0 = refresh_state(RState, Cwd),
  119. CmdState1 = rebar_state:set(CmdState0, task, atom_to_list(Command)),
  120. CmdState = rebar_state:set(CmdState1, caller, api),
  121. case rebar3:run(CmdState, Args) of
  122. {ok, TmpState} ->
  123. refresh_paths(TmpState),
  124. {ok, CmdState};
  125. {error, Err} when is_list(Err) ->
  126. refresh_paths(CmdState),
  127. {{error, lists:flatten(Err)}, CmdState};
  128. {error, Err} ->
  129. refresh_paths(CmdState),
  130. {{error, Err}, CmdState}
  131. end;
  132. _ ->
  133. {{error, cwd_changed}, RState}
  134. end
  135. catch
  136. ?WITH_STACKTRACE(Type, Reason, Stacktrace)
  137. ?DEBUG("Agent Stacktrace: ~p", [Stacktrace]),
  138. {{error, {Type, Reason}}, RState}
  139. end.
  140. %% @private function to display a warning for the feature only once
  141. -spec maybe_show_warning(#state{}) -> #state{}.
  142. maybe_show_warning(S=#state{show_warning=true}) ->
  143. ?WARN("This feature is experimental and may be modified or removed at any time.", []),
  144. S#state{show_warning=false};
  145. maybe_show_warning(State) ->
  146. State.
  147. %% @private based on a rebar3 state term, reload paths in a way
  148. %% that makes sense.
  149. -spec refresh_paths(rebar_state:t()) -> ok.
  150. refresh_paths(RState) ->
  151. RefreshPaths = application:get_env(rebar, refresh_paths, [all_deps, test]),
  152. ToRefresh = parse_refresh_paths(RefreshPaths, RState, []),
  153. %% Modules from apps we can't reload without breaking functionality
  154. ShellOpts = rebar_state:get(RState, shell, []),
  155. ShellBlacklist = proplists:get_value(app_reload_blacklist, ShellOpts, []),
  156. Blacklist = lists:usort(
  157. application:get_env(rebar, refresh_paths_blacklist, ShellBlacklist)
  158. ++ [rebar, erlware_commons, providers, cf, cth_readable]),
  159. %% Similar to rebar_utils:update_code/1, but also forces a reload
  160. %% of used modules. Also forces to reload all of ebin/ instead
  161. %% of just the modules in the .app file, because 'extra_src_dirs'
  162. %% allows to load and compile files that are not to be kept
  163. %% in the app file.
  164. [refresh_path(Path, Blacklist) || Path <- ToRefresh],
  165. ok.
  166. refresh_path(Path, Blacklist) ->
  167. Name = filename:basename(Path, "/ebin"),
  168. App = list_to_atom(Name),
  169. case App of
  170. test -> % skip
  171. code:add_patha(Path),
  172. ok;
  173. _ ->
  174. application:load(App),
  175. case application:get_key(App, modules) of
  176. undefined ->
  177. code:add_patha(Path);
  178. {ok, _Mods} ->
  179. case lists:member(App, Blacklist) of
  180. false ->
  181. refresh_path_do(Path, App);
  182. true ->
  183. refresh_path_blacklisted(Path)
  184. end
  185. end
  186. end.
  187. refresh_path_do(Path, App) ->
  188. Modules = mods_in_path(Path),
  189. ?DEBUG("reloading ~p from ~ts", [Modules, Path]),
  190. code:replace_path(App, Path),
  191. reload_modules(Modules).
  192. %% @private blacklisted paths are not reloaded, but if they were not loaded
  193. %% already, we try and ensure they are loaded once. This is a soft operation
  194. %% that does not provoke crashes in existing processes, but hides issues
  195. %% as seen in issue #2013 comments where some loaded modules that are currently
  196. %% run by no processes get unloaded by rebar_paths, without being loaded back in.
  197. refresh_path_blacklisted(Path) ->
  198. Modules = [M || M <- mods_in_path(Path), not is_loaded(M)],
  199. ?DEBUG("ensure ~p loaded", [Modules]),
  200. code:add_pathz(Path), % in case the module is only in a new non-clashing path
  201. _ = [code:ensure_loaded(M) || M <- Modules],
  202. ok.
  203. %% @private fetch module names from a given directory that contains
  204. %% pre-build beam files.
  205. mods_in_path(Path) ->
  206. Files = filelib:wildcard(filename:join([Path, "*.beam"])),
  207. [list_to_atom(filename:basename(F, ".beam")) || F <- Files].
  208. %% @private check that a module is already loaded
  209. is_loaded(Mod) ->
  210. code:is_loaded(Mod) =/= false.
  211. %% @private parse refresh_paths option
  212. %% no_deps means only project_apps's ebin path
  213. %% no_test means no test path
  214. %% OtherPath.
  215. parse_refresh_paths([all_deps | RefreshPaths], RState, Acc) ->
  216. Paths = rebar_state:code_paths(RState, all_deps),
  217. parse_refresh_paths(RefreshPaths, RState, Paths ++ Acc);
  218. parse_refresh_paths([project_apps | RefreshPaths], RState, Acc) ->
  219. Paths = [filename:join([rebar_app_info:out_dir(App), "ebin"])
  220. || App <- rebar_state:project_apps(RState)],
  221. parse_refresh_paths(RefreshPaths, RState, Paths ++ Acc);
  222. parse_refresh_paths([test | RefreshPaths], RState, Acc) ->
  223. Paths = [filename:join([rebar_app_info:out_dir(App), "test"])
  224. || App <- rebar_state:project_apps(RState)],
  225. parse_refresh_paths(RefreshPaths, RState, Paths ++ Acc);
  226. parse_refresh_paths([RefreshPath0 | RefreshPaths], RState, Acc) when is_list(RefreshPath0) ->
  227. case filelib:is_dir(RefreshPath0) of
  228. true ->
  229. RefreshPath0 =
  230. case filename:basename(RefreshPath0) of
  231. "ebin" -> RefreshPath0;
  232. _ -> filename:join([RefreshPath0, "ebin"])
  233. end,
  234. parse_refresh_paths(RefreshPaths, RState, [RefreshPath0 | Acc]);
  235. false ->
  236. parse_refresh_paths(RefreshPaths, RState, Acc)
  237. end;
  238. parse_refresh_paths([_ | RefreshPaths], RState, Acc) ->
  239. parse_refresh_paths(RefreshPaths, RState, Acc);
  240. parse_refresh_paths([], _RState, Acc) ->
  241. lists:usort(Acc).
  242. %% @private from a disk config, reload and reapply with the current
  243. %% profiles; used to find changes in the config from a prior run.
  244. -spec refresh_state(rebar_state:t(), file:filename()) -> rebar_state:t().
  245. refresh_state(RState, _Dir) ->
  246. lists:foldl(
  247. fun(F, State) -> F(State) end,
  248. rebar3:init_config(),
  249. [fun(S) -> rebar_state:apply_profiles(S, rebar_state:current_profiles(RState)) end]
  250. ).
  251. %% @private takes a list of modules and reloads them
  252. -spec reload_modules([module()]) -> term().
  253. reload_modules([]) -> noop;
  254. reload_modules(Modules0) ->
  255. Modules = [M || M <- Modules0, is_changed(M)],
  256. reload_modules(Modules, erlang:function_exported(code, prepare_loading, 1)).
  257. %% @spec is_changed(atom()) -> boolean()
  258. %% @doc true if the loaded module is a beam with a vsn attribute
  259. %% and does not match the on-disk beam file, returns false otherwise.
  260. is_changed(M) ->
  261. try
  262. module_vsn(M:module_info(attributes)) =/= module_vsn(code:get_object_code(M))
  263. catch _:_ ->
  264. false
  265. end.
  266. module_vsn({M, Beam, _Fn}) ->
  267. % Because the vsn can set by -vsn(X) in module.
  268. % So didn't use beam_lib:version/1 to get the vsn.
  269. % So if set -vsn(X) in module, it will always reload the module.
  270. {ok, {M, <<Vsn:128>>}} = beam_lib:md5(Beam),
  271. Vsn;
  272. module_vsn(Attrs) when is_list(Attrs) ->
  273. {_, Vsn} = lists:keyfind(vsn, 1, Attrs),
  274. Vsn.
  275. %% @private reloading modules, when there are modules to actually reload
  276. reload_modules(Modules, true) ->
  277. %% OTP 19 and later -- use atomic loading and ignore unloadable mods
  278. case code:prepare_loading(Modules) of
  279. {ok, Prepared} ->
  280. [code:purge(M) || M <- Modules],
  281. code:finish_loading(Prepared);
  282. {error, ModRsns} ->
  283. Blacklist =
  284. lists:foldr(fun({ModError, Error}, Acc) ->
  285. case Error of
  286. % perhaps cover other cases of failure?
  287. on_load_not_allowed ->
  288. reload_modules([ModError], false),
  289. [ModError|Acc];
  290. _ ->
  291. ?DEBUG("Module ~p failed to atomic load because ~p", [ModError, Error]),
  292. [ModError|Acc]
  293. end
  294. end,
  295. [], ModRsns
  296. ),
  297. reload_modules(Modules -- Blacklist, true)
  298. end;
  299. reload_modules(Modules, false) ->
  300. %% Older versions, use a more ad-hoc mechanism.
  301. lists:foreach(fun(M) ->
  302. code:delete(M),
  303. code:purge(M),
  304. case code:load_file(M) of
  305. {module, M} -> ok;
  306. {error, Error} ->
  307. ?DEBUG("Module ~p failed to load because ~p", [M, Error])
  308. end
  309. end, Modules
  310. ).