update_appup.escript 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #!/usr/bin/env -S escript -c
  2. %% -*- erlang-indent-level:4 -*-
  3. usage() ->
  4. "A script that fills in boilerplate for appup files.
  5. Algorithm: this script compares md5s of beam files of each
  6. application, and creates a `{load_module, Module, brutal_purge,
  7. soft_purge, []}` action for the changed and new modules. For deleted
  8. modules it creates `{delete_module, M}` action. These entries are
  9. added to each patch release preceding the current release. If an entry
  10. for a module already exists, this module is ignored. The existing
  11. actions are kept.
  12. Please note that it only compares the current release with its
  13. predecessor, assuming that the upgrade actions for the older releases
  14. are correct.
  15. Note: The defaults are set up for emqx, but they can be tuned to
  16. support other repos too.
  17. Usage:
  18. update_appup.escript [--check] [--repo URL] [--remote NAME] [--skip-build] [--make-commad SCRIPT] [--release-dir DIR] <current_release_tag>
  19. Options:
  20. --check Don't update the appup files, just check that they are complete
  21. --repo Upsteam git repo URL
  22. --remote Get upstream repo URL from the specified git remote
  23. --skip-build Don't rebuild the releases. May produce wrong results
  24. --make-command A command used to assemble the release
  25. --release-dir Release directory
  26. ".
  27. default_options() ->
  28. #{ check => false
  29. , clone_url => find_upstream_repo("origin")
  30. , make_command => "make emqx-rel"
  31. , beams_dir => "_build/emqx/rel/emqx/lib/"
  32. }.
  33. main(Args) ->
  34. #{current_release := CurrentRelease} = Options = parse_args(Args, default_options()),
  35. case find_pred_tag(CurrentRelease) of
  36. {ok, Baseline} ->
  37. main(Options, Baseline);
  38. undefined ->
  39. log("No appup update is needed for this release, nothing to be done~n", []),
  40. ok
  41. end.
  42. parse_args([CurrentRelease = [A|_]], State) when A =/= $- ->
  43. State#{current_release => CurrentRelease};
  44. parse_args(["--check"|Rest], State) ->
  45. parse_args(Rest, State#{check => true});
  46. parse_args(["--skip-build"|Rest], State) ->
  47. parse_args(Rest, State#{make_command => "true"});
  48. parse_args(["--repo", Repo|Rest], State) ->
  49. parse_args(Rest, State#{clone_url => Repo});
  50. parse_args(["--remote", Remote|Rest], State) ->
  51. parse_args(Rest, State#{clone_url => find_upstream_repo(Remote)});
  52. parse_args(["--make-command", Command|Rest], State) ->
  53. parse_args(Rest, State#{make_command => Command});
  54. parse_args(["--release-dir", Dir|Rest], State) ->
  55. parse_args(Rest, State#{beams_dir => Dir});
  56. parse_args(_, _) ->
  57. fail(usage()).
  58. main(Options = #{check := Check}, Baseline) ->
  59. {CurrDir, PredDir} = prepare(Baseline, Options),
  60. CurrBeams = hashsums(find_beams(CurrDir)),
  61. PredBeams = hashsums(find_beams(PredDir)),
  62. Upgrade = diff_releases(CurrBeams, PredBeams),
  63. Downgrade = diff_releases(PredBeams, CurrBeams),
  64. Apps = maps:keys(Upgrade),
  65. lists:foreach( fun(App) ->
  66. #{App := AppUpgrade} = Upgrade,
  67. #{App := AppDowngrade} = Downgrade,
  68. process_app(Baseline, Check, App, AppUpgrade, AppDowngrade)
  69. end
  70. , Apps
  71. ),
  72. log("
  73. NOTE: Please review the changes manually. This script does not know about NIF
  74. changes, supervisor changes, process restarts and so on. Also the load order of
  75. the beam files might need updating.
  76. ").
  77. process_app(_, _, App, {[], [], []}, {[], [], []}) ->
  78. %% No changes, just check the appup file if present:
  79. case locate(App, ".appup.src") of
  80. {ok, AppupFile} ->
  81. _ = read_appup(AppupFile),
  82. ok;
  83. undefined ->
  84. ok
  85. end;
  86. process_app(PredVersion, Check, App, Upgrade, Downgrade) ->
  87. case locate(App, ".appup.src") of
  88. {ok, AppupFile} ->
  89. update_appup(Check, PredVersion, AppupFile, Upgrade, Downgrade);
  90. undefined ->
  91. case create_stub(App) of
  92. false ->
  93. %% External dependency, skip
  94. ok;
  95. AppupFile ->
  96. update_appup(Check, PredVersion, AppupFile, Upgrade, Downgrade)
  97. end
  98. end.
  99. create_stub(App) ->
  100. case locate(App, ".app.src") of
  101. {ok, AppSrc} ->
  102. AppupFile = filename:basename(AppSrc) ++ ".appup.src",
  103. Default = {<<".*">>, []},
  104. render_appfile(AppupFile, [Default], [Default]),
  105. AppupFile;
  106. undefined ->
  107. false
  108. end.
  109. update_appup(Check, PredVersion, File, UpgradeChanges, DowngradeChanges) ->
  110. log("Updating appup: ~p~n", [File]),
  111. {_, Upgrade0, Downgrade0} = read_appup(File),
  112. Upgrade = update_actions(PredVersion, UpgradeChanges, Upgrade0),
  113. Downgrade = update_actions(PredVersion, DowngradeChanges, Downgrade0),
  114. render_appfile(File, Upgrade, Downgrade),
  115. %% Check appup syntax:
  116. _ = read_appup(File).
  117. render_appfile(File, Upgrade, Downgrade) ->
  118. IOList = io_lib:format("%% -*- mode: erlang -*-\n{VSN,~n ~p,~n ~p}.~n", [Upgrade, Downgrade]),
  119. ok = file:write_file(File, IOList).
  120. update_actions(PredVersion, Changes, Actions) ->
  121. lists:map( fun(L) -> do_update_actions(Changes, L) end
  122. , ensure_pred_versions(PredVersion, Actions)
  123. ).
  124. do_update_actions(_, Ret = {<<".*">>, _}) ->
  125. Ret;
  126. do_update_actions(Changes, {Vsn, Actions}) ->
  127. {Vsn, process_changes(Changes, Actions)}.
  128. process_changes({New0, Changed0, Deleted0}, OldActions) ->
  129. AlreadyHandled = lists:flatten(lists:map(fun process_old_action/1, OldActions)),
  130. New = New0 -- AlreadyHandled,
  131. Changed = Changed0 -- AlreadyHandled,
  132. Deleted = Deleted0 -- AlreadyHandled,
  133. [{load_module, M, brutal_purge, soft_purge, []} || M <- Changed ++ New] ++
  134. OldActions ++
  135. [{delete_module, M} || M <- Deleted].
  136. %% @doc Process the existing actions to exclude modules that are
  137. %% already handled
  138. process_old_action({purge, Modules}) ->
  139. Modules;
  140. process_old_action({delete_module, Module}) ->
  141. [Module];
  142. process_old_action(LoadModule) when is_tuple(LoadModule) andalso
  143. element(1, LoadModule) =:= load_module ->
  144. element(2, LoadModule);
  145. process_old_action(_) ->
  146. [].
  147. ensure_pred_versions(PredVersion, Versions) ->
  148. {Maj, Min, Patch} = parse_semver(PredVersion),
  149. PredVersions = [semver(Maj, Min, P) || P <- lists:seq(0, Patch)],
  150. lists:foldl(fun ensure_version/2, Versions, PredVersions).
  151. ensure_version(Version, Versions) ->
  152. case lists:keyfind(Version, 1, Versions) of
  153. false ->
  154. [{Version, []}|Versions];
  155. _ ->
  156. Versions
  157. end.
  158. read_appup(File) ->
  159. case file:script(File, [{'VSN', "VSN"}]) of
  160. {ok, Terms} ->
  161. Terms;
  162. Error ->
  163. fail("Failed to parse appup file ~s: ~p", [File, Error])
  164. end.
  165. diff_releases(Curr, Old) ->
  166. Fun = fun(App, Modules, Acc) ->
  167. OldModules = maps:get(App, Old, #{}),
  168. Acc#{App => diff_app_modules(Modules, OldModules)}
  169. end,
  170. maps:fold(Fun, #{}, Curr).
  171. diff_app_modules(Modules, OldModules) ->
  172. {New, Changed} =
  173. maps:fold( fun(Mod, MD5, {New, Changed}) ->
  174. case OldModules of
  175. #{Mod := OldMD5} when MD5 =:= OldMD5 ->
  176. {New, Changed};
  177. #{Mod := _} ->
  178. {New, [Mod|Changed]};
  179. _ -> {[Mod|New], Changed}
  180. end
  181. end
  182. , {[], []}
  183. , Modules
  184. ),
  185. Deleted = maps:keys(maps:without(maps:keys(Modules), OldModules)),
  186. {New, Changed, Deleted}.
  187. find_beams(Dir) ->
  188. [filename:join(Dir, I) || I <- filelib:wildcard("**/ebin/*.beam", Dir)].
  189. prepare(Baseline, Options = #{make_command := MakeCommand, beams_dir := BeamDir}) ->
  190. log("~n===================================~n"
  191. "Baseline: ~s"
  192. "~n===================================~n", [Baseline]),
  193. log("Building the current version...~n"),
  194. bash(MakeCommand),
  195. log("Downloading and building the previous release...~n"),
  196. {ok, PredRootDir} = build_pred_release(Baseline, Options),
  197. {BeamDir, filename:join(PredRootDir, BeamDir)}.
  198. build_pred_release(Baseline, #{clone_url := Repo, make_command := MakeCommand}) ->
  199. BaseDir = "/tmp/emqx-baseline/",
  200. Dir = filename:basename(Repo, ".git") ++ [$-|Baseline],
  201. %% TODO: shallow clone
  202. Script = "mkdir -p ${BASEDIR} &&
  203. cd ${BASEDIR} &&
  204. { git clone --branch ${TAG} ${REPO} ${DIR} || true; } &&
  205. cd ${DIR} &&" ++ MakeCommand,
  206. Env = [{"REPO", Repo}, {"TAG", Baseline}, {"BASEDIR", BaseDir}, {"DIR", Dir}],
  207. bash(Script, Env),
  208. {ok, filename:join(BaseDir, Dir)}.
  209. find_upstream_repo(Remote) ->
  210. string:trim(os:cmd("git remote get-url " ++ Remote)).
  211. find_pred_tag(CurrentRelease) ->
  212. {Maj, Min, Patch} = parse_semver(CurrentRelease),
  213. case Patch of
  214. 0 -> undefined;
  215. _ -> {ok, semver(Maj, Min, Patch - 1)}
  216. end.
  217. -spec hashsums(file:filename()) -> #{App => #{module() => binary()}}
  218. when App :: atom().
  219. hashsums(Files) ->
  220. hashsums(Files, #{}).
  221. hashsums([], Acc) ->
  222. Acc;
  223. hashsums([File|Rest], Acc0) ->
  224. [_, "ebin", Dir|_] = lists:reverse(filename:split(File)),
  225. {match, [AppStr]} = re(Dir, "^(.*)-[^-]+$"),
  226. App = list_to_atom(AppStr),
  227. {ok, {Module, MD5}} = beam_lib:md5(File),
  228. Acc = maps:update_with( App
  229. , fun(Old) -> Old #{Module => MD5} end
  230. , #{Module => MD5}
  231. , Acc0
  232. ),
  233. hashsums(Rest, Acc).
  234. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  235. %% Utility functions
  236. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  237. parse_semver(Version) ->
  238. case re(Version, "^([0-9]+)\\.([0-9]+)\\.([0-9]+)(\\.[0-9]+)?$") of
  239. {match, [Maj, Min, Patch|_]} ->
  240. {list_to_integer(Maj), list_to_integer(Min), list_to_integer(Patch)};
  241. _ ->
  242. error({not_a_semver, Version})
  243. end.
  244. semver(Maj, Min, Patch) ->
  245. lists:flatten(io_lib:format("~p.~p.~p", [Maj, Min, Patch])).
  246. %% Locate a file in a specified application
  247. locate(App, Suffix) ->
  248. AppStr = atom_to_list(App),
  249. case filelib:wildcard("{src,apps,lib-*}/**/" ++ AppStr ++ Suffix) of
  250. [File] ->
  251. {ok, File};
  252. [] ->
  253. undefined
  254. end.
  255. bash(Script) ->
  256. bash(Script, []).
  257. bash(Script, Env) ->
  258. case cmd("bash", #{args => ["-c", Script], env => Env}) of
  259. 0 -> true;
  260. _ -> fail("Failed to run command: ~s", [Script])
  261. end.
  262. %% Spawn an executable and return the exit status
  263. cmd(Exec, Params) ->
  264. case os:find_executable(Exec) of
  265. false ->
  266. fail("Executable not found in $PATH: ~s", [Exec]);
  267. Path ->
  268. Params1 = maps:to_list(maps:with([env, args, cd], Params)),
  269. Port = erlang:open_port( {spawn_executable, Path}
  270. , [ exit_status
  271. , nouse_stdio
  272. | Params1
  273. ]
  274. ),
  275. receive
  276. {Port, {exit_status, Status}} ->
  277. Status
  278. end
  279. end.
  280. fail(Str) ->
  281. fail(Str, []).
  282. fail(Str, Args) ->
  283. log(Str ++ "~n", Args),
  284. halt(1).
  285. re(Subject, RE) ->
  286. re:run(Subject, RE, [{capture, all_but_first, list}]).
  287. log(Msg) ->
  288. log(Msg, []).
  289. log(Msg, Args) ->
  290. io:format(standard_error, Msg, Args).