update_appup.escript 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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] <previous_release_tag>
  19. Options:
  20. --check Don't update the appfile, 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. --src-dirs Directories where source code is found. Defaults to '{src,apps,lib-*}/**/'
  27. --binary-rel-url Binary release URL pattern. %TAG% variable is substituted with the release tag.
  28. E.g. \"https://github.com/emqx/emqx/releases/download/v%TAG%/emqx-centos7-%TAG%-amd64.zip\"
  29. ".
  30. -record(app,
  31. { modules :: #{module() => binary()}
  32. , version :: string()
  33. }).
  34. default_options() ->
  35. #{ clone_url => find_upstream_repo("origin")
  36. , make_command => "make emqx-rel"
  37. , beams_dir => "_build/emqx/rel/emqx/lib/"
  38. , check => false
  39. , prev_tag => undefined
  40. , src_dirs => "{src,apps,lib-*}/**/"
  41. , binary_rel_url => undefined
  42. }.
  43. %% App-specific actions that should be added unconditionally to any update/downgrade:
  44. app_specific_actions(_) ->
  45. [].
  46. ignored_apps() ->
  47. [emqx_dashboard, emqx_management] ++ otp_standard_apps().
  48. main(Args) ->
  49. #{prev_tag := Baseline} = Options = parse_args(Args, default_options()),
  50. init_globals(Options),
  51. main(Options, Baseline).
  52. parse_args([PrevTag = [A|_]], State) when A =/= $- ->
  53. State#{prev_tag => PrevTag};
  54. parse_args(["--check"|Rest], State) ->
  55. parse_args(Rest, State#{check => true});
  56. parse_args(["--skip-build"|Rest], State) ->
  57. parse_args(Rest, State#{make_command => "true"});
  58. parse_args(["--repo", Repo|Rest], State) ->
  59. parse_args(Rest, State#{clone_url => Repo});
  60. parse_args(["--remote", Remote|Rest], State) ->
  61. parse_args(Rest, State#{clone_url => find_upstream_repo(Remote)});
  62. parse_args(["--make-command", Command|Rest], State) ->
  63. parse_args(Rest, State#{make_command => Command});
  64. parse_args(["--release-dir", Dir|Rest], State) ->
  65. parse_args(Rest, State#{beams_dir => Dir});
  66. parse_args(["--src-dirs", Pattern|Rest], State) ->
  67. parse_args(Rest, State#{src_dirs => Pattern});
  68. parse_args(["--binary-rel-url", URL|Rest], State) ->
  69. parse_args(Rest, State#{binary_rel_url => {ok, URL}});
  70. parse_args(_, _) ->
  71. fail(usage()).
  72. main(Options, Baseline) ->
  73. {CurrRelDir, PrevRelDir} = prepare(Baseline, Options),
  74. log("~n===================================~n"
  75. "Processing changes..."
  76. "~n===================================~n"),
  77. CurrAppsIdx = index_apps(CurrRelDir),
  78. PrevAppsIdx = index_apps(PrevRelDir),
  79. %% log("Curr: ~p~nPrev: ~p~n", [CurrAppsIdx, PrevAppsIdx]),
  80. AppupChanges = find_appup_actions(CurrAppsIdx, PrevAppsIdx),
  81. case getopt(check) of
  82. true ->
  83. case AppupChanges of
  84. [] ->
  85. ok;
  86. _ ->
  87. set_invalid(),
  88. log("ERROR: The appup files are incomplete. Missing changes:~n ~p", [AppupChanges])
  89. end;
  90. false ->
  91. update_appups(AppupChanges)
  92. end,
  93. check_appup_files(),
  94. warn_and_exit(is_valid()).
  95. warn_and_exit(true) ->
  96. log("
  97. NOTE: Please review the changes manually. This script does not know about NIF
  98. changes, supervisor changes, process restarts and so on. Also the load order of
  99. the beam files might need updating.~n"),
  100. halt(0);
  101. warn_and_exit(false) ->
  102. log("~nERROR: Incomplete appups found. Please inspect the output for more details.~n"),
  103. halt(1).
  104. prepare(Baseline, Options = #{make_command := MakeCommand, beams_dir := BeamDir, binary_rel_url := BinRel}) ->
  105. log("~n===================================~n"
  106. "Baseline: ~s"
  107. "~n===================================~n", [Baseline]),
  108. log("Building the current version...~n"),
  109. bash(MakeCommand),
  110. log("Downloading and building the previous release...~n"),
  111. PrevRelDir =
  112. case BinRel of
  113. undefined ->
  114. {ok, PrevRootDir} = build_prev_release(Baseline, Options),
  115. filename:join(PrevRootDir, BeamDir);
  116. {ok, _URL} ->
  117. {ok, PrevRootDir} = download_prev_release(Baseline, Options),
  118. PrevRootDir
  119. end,
  120. {BeamDir, PrevRelDir}.
  121. build_prev_release(Baseline, #{clone_url := Repo, make_command := MakeCommand}) ->
  122. BaseDir = "/tmp/emqx-baseline/",
  123. Dir = filename:basename(Repo, ".git") ++ [$-|Baseline],
  124. %% TODO: shallow clone
  125. Script = "mkdir -p ${BASEDIR} &&
  126. cd ${BASEDIR} &&
  127. { [ -d ${DIR} ] || git clone --branch ${TAG} ${REPO} ${DIR}; } &&
  128. cd ${DIR} &&" ++ MakeCommand,
  129. Env = [{"REPO", Repo}, {"TAG", Baseline}, {"BASEDIR", BaseDir}, {"DIR", Dir}],
  130. bash(Script, Env),
  131. {ok, filename:join(BaseDir, Dir)}.
  132. download_prev_release(Tag, #{binary_rel_url := {ok, URL0}, clone_url := Repo}) ->
  133. URL = string:replace(URL0, "%TAG%", Tag, all),
  134. BaseDir = "/tmp/emqx-baseline-bin/",
  135. Dir = filename:basename(Repo, ".git") ++ [$-|Tag],
  136. Filename = filename:join(BaseDir, Dir),
  137. Script = "mkdir -p ${OUTFILE} &&
  138. wget -c -O ${OUTFILE}.zip ${URL} &&
  139. unzip -n -d ${OUTFILE} ${OUTFILE}.zip",
  140. Env = [{"TAG", Tag}, {"OUTFILE", Filename}, {"URL", URL}],
  141. bash(Script, Env),
  142. {ok, Filename}.
  143. find_upstream_repo(Remote) ->
  144. string:trim(os:cmd("git remote get-url " ++ Remote)).
  145. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  146. %% Appup action creation and updating
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. find_appup_actions(CurrApps, PrevApps) ->
  149. maps:fold(
  150. fun(App, CurrAppIdx, Acc) ->
  151. case PrevApps of
  152. #{App := PrevAppIdx} -> find_appup_actions(App, CurrAppIdx, PrevAppIdx) ++ Acc;
  153. _ -> Acc %% New app, nothing to upgrade here.
  154. end
  155. end,
  156. [],
  157. CurrApps).
  158. find_appup_actions(_App, AppIdx, AppIdx) ->
  159. %% No changes to the app, ignore:
  160. [];
  161. find_appup_actions(App, CurrAppIdx, PrevAppIdx = #app{version = PrevVersion}) ->
  162. {OldUpgrade, OldDowngrade} = find_old_appup_actions(App, PrevVersion),
  163. Upgrade = merge_update_actions(App, diff_app(App, CurrAppIdx, PrevAppIdx), OldUpgrade),
  164. Downgrade = merge_update_actions(App, diff_app(App, PrevAppIdx, CurrAppIdx), OldDowngrade),
  165. if OldUpgrade =:= Upgrade andalso OldDowngrade =:= Downgrade ->
  166. %% The appup file has been already updated:
  167. [];
  168. true ->
  169. [{App, {Upgrade, Downgrade}}]
  170. end.
  171. find_old_appup_actions(App, PrevVersion) ->
  172. {Upgrade0, Downgrade0} =
  173. case locate(ebin_current, App, ".appup") of
  174. {ok, AppupFile} ->
  175. log("Found the previous appup file: ~s~n", [AppupFile]),
  176. {_, U, D} = read_appup(AppupFile),
  177. {U, D};
  178. undefined ->
  179. %% Fallback to the app.src file, in case the
  180. %% application doesn't have a release (useful for the
  181. %% apps that live outside the EMQX monorepo):
  182. case locate(src, App, ".appup.src") of
  183. {ok, AppupSrcFile} ->
  184. log("Using ~s as a source of previous update actions~n", [AppupSrcFile]),
  185. {_, U, D} = read_appup(AppupSrcFile),
  186. {U, D};
  187. undefined ->
  188. {[], []}
  189. end
  190. end,
  191. {ensure_version(PrevVersion, Upgrade0), ensure_version(PrevVersion, Downgrade0)}.
  192. merge_update_actions(App, Changes, Vsns) ->
  193. lists:map(fun(Ret = {<<".*">>, _}) ->
  194. Ret;
  195. ({Vsn, Actions}) ->
  196. {Vsn, do_merge_update_actions(App, Changes, Actions)}
  197. end,
  198. Vsns).
  199. do_merge_update_actions(App, {New0, Changed0, Deleted0}, OldActions) ->
  200. AppSpecific = app_specific_actions(App) -- OldActions,
  201. AlreadyHandled = lists:flatten(lists:map(fun process_old_action/1, OldActions)),
  202. New = New0 -- AlreadyHandled,
  203. Changed = Changed0 -- AlreadyHandled,
  204. Deleted = Deleted0 -- AlreadyHandled,
  205. [{load_module, M, brutal_purge, soft_purge, []} || M <- Changed ++ New] ++
  206. OldActions ++
  207. [{delete_module, M} || M <- Deleted] ++
  208. AppSpecific.
  209. %% @doc Process the existing actions to exclude modules that are
  210. %% already handled
  211. process_old_action({purge, Modules}) ->
  212. Modules;
  213. process_old_action({delete_module, Module}) ->
  214. [Module];
  215. process_old_action(LoadModule) when is_tuple(LoadModule) andalso
  216. element(1, LoadModule) =:= load_module ->
  217. element(2, LoadModule);
  218. process_old_action(_) ->
  219. [].
  220. ensure_version(Version, OldInstructions) ->
  221. OldVersions = [ensure_string(element(1, I)) || I <- OldInstructions],
  222. case lists:member(Version, OldVersions) of
  223. false ->
  224. [{Version, []}|OldInstructions];
  225. _ ->
  226. OldInstructions
  227. end.
  228. read_appup(File) ->
  229. %% NOTE: appup file is a script, it may contain variables or functions.
  230. case file:script(File, [{'VSN', "VSN"}]) of
  231. {ok, Terms} ->
  232. Terms;
  233. Error ->
  234. fail("Failed to parse appup file ~s: ~p", [File, Error])
  235. end.
  236. check_appup_files() ->
  237. AppupFiles = filelib:wildcard(getopt(src_dirs) ++ "/*.appup.src"),
  238. lists:foreach(fun read_appup/1, AppupFiles).
  239. update_appups(Changes) ->
  240. lists:foreach(
  241. fun({App, {Upgrade, Downgrade}}) ->
  242. do_update_appup(App, Upgrade, Downgrade)
  243. end,
  244. Changes).
  245. do_update_appup(App, Upgrade, Downgrade) ->
  246. case locate(src, App, ".appup.src") of
  247. {ok, AppupFile} ->
  248. render_appfile(AppupFile, Upgrade, Downgrade);
  249. undefined ->
  250. case create_stub(App) of
  251. {ok, AppupFile} ->
  252. render_appfile(AppupFile, Upgrade, Downgrade);
  253. false ->
  254. set_invalid(),
  255. log("ERROR: Appup file for the external dependency '~p' is not complete.~n Missing changes: ~p~n", [App, Upgrade])
  256. end
  257. end.
  258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  259. %% Appup file creation
  260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  261. render_appfile(File, Upgrade, Downgrade) ->
  262. IOList = io_lib:format("%% -*- mode: erlang -*-\n{VSN,~n ~p,~n ~p}.~n", [Upgrade, Downgrade]),
  263. ok = file:write_file(File, IOList).
  264. create_stub(App) ->
  265. Ext = ".app.src",
  266. case locate(src, App, Ext) of
  267. {ok, AppSrc} ->
  268. DirName = filename:dirname(AppSrc),
  269. AppupFile = filename:basename(AppSrc, Ext) ++ ".appup.src",
  270. Default = {<<".*">>, []},
  271. AppupFileFullpath = filename:join(DirName, AppupFile),
  272. render_appfile(AppupFileFullpath, [Default], [Default]),
  273. {ok, AppupFileFullpath};
  274. undefined ->
  275. false
  276. end.
  277. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  278. %% application and release indexing
  279. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  280. index_apps(ReleaseDir) ->
  281. Apps0 = maps:from_list([index_app(filename:join(ReleaseDir, AppFile)) ||
  282. AppFile <- filelib:wildcard("**/ebin/*.app", ReleaseDir)]),
  283. maps:without(ignored_apps(), Apps0).
  284. index_app(AppFile) ->
  285. {ok, [{application, App, Properties}]} = file:consult(AppFile),
  286. Vsn = proplists:get_value(vsn, Properties),
  287. %% Note: assuming that beams are always located in the same directory where app file is:
  288. EbinDir = filename:dirname(AppFile),
  289. Modules = hashsums(EbinDir),
  290. {App, #app{ version = Vsn
  291. , modules = Modules
  292. }}.
  293. diff_app(App, #app{version = NewVersion, modules = NewModules}, #app{version = OldVersion, modules = OldModules}) ->
  294. {New, Changed} =
  295. maps:fold( fun(Mod, MD5, {New, Changed}) ->
  296. case OldModules of
  297. #{Mod := OldMD5} when MD5 =:= OldMD5 ->
  298. {New, Changed};
  299. #{Mod := _} ->
  300. {New, [Mod|Changed]};
  301. _ ->
  302. {[Mod|New], Changed}
  303. end
  304. end
  305. , {[], []}
  306. , NewModules
  307. ),
  308. Deleted = maps:keys(maps:without(maps:keys(NewModules), OldModules)),
  309. NChanges = length(New) + length(Changed) + length(Deleted),
  310. if NewVersion =:= OldVersion andalso NChanges > 0 ->
  311. set_invalid(),
  312. log("ERROR: Application '~p' contains changes, but its version is not updated~n", [App]);
  313. NewVersion > OldVersion ->
  314. log("INFO: Application '~p' has been updated: ~p -> ~p~n", [App, OldVersion, NewVersion]),
  315. ok;
  316. true ->
  317. ok
  318. end,
  319. {New, Changed, Deleted}.
  320. -spec hashsums(file:filename()) -> #{module() => binary()}.
  321. hashsums(EbinDir) ->
  322. maps:from_list(lists:map(
  323. fun(Beam) ->
  324. File = filename:join(EbinDir, Beam),
  325. {ok, Ret = {_Module, _MD5}} = beam_lib:md5(File),
  326. Ret
  327. end,
  328. filelib:wildcard("*.beam", EbinDir)
  329. )).
  330. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  331. %% Global state
  332. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  333. init_globals(Options) ->
  334. ets:new(globals, [named_table, set, public]),
  335. ets:insert(globals, {valid, true}),
  336. ets:insert(globals, {options, Options}).
  337. getopt(Option) ->
  338. maps:get(Option, ets:lookup_element(globals, options, 2)).
  339. %% Set a global flag that something about the appfiles is invalid
  340. set_invalid() ->
  341. ets:insert(globals, {valid, false}).
  342. is_valid() ->
  343. ets:lookup_element(globals, valid, 2).
  344. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  345. %% Utility functions
  346. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  347. %% Locate a file in a specified application
  348. locate(ebin_current, App, Suffix) ->
  349. ReleaseDir = getopt(beams_dir),
  350. AppStr = atom_to_list(App),
  351. case filelib:wildcard(ReleaseDir ++ "/**/ebin/" ++ AppStr ++ Suffix) of
  352. [File] ->
  353. {ok, File};
  354. [] ->
  355. undefined
  356. end;
  357. locate(src, App, Suffix) ->
  358. AppStr = atom_to_list(App),
  359. SrcDirs = getopt(src_dirs),
  360. case filelib:wildcard(SrcDirs ++ AppStr ++ Suffix) of
  361. [File] ->
  362. {ok, File};
  363. [] ->
  364. undefined
  365. end.
  366. bash(Script) ->
  367. bash(Script, []).
  368. bash(Script, Env) ->
  369. log("+ ~s~n+ Env: ~p~n", [Script, Env]),
  370. case cmd("bash", #{args => ["-c", Script], env => Env}) of
  371. 0 -> true;
  372. _ -> fail("Failed to run command: ~s", [Script])
  373. end.
  374. %% Spawn an executable and return the exit status
  375. cmd(Exec, Params) ->
  376. case os:find_executable(Exec) of
  377. false ->
  378. fail("Executable not found in $PATH: ~s", [Exec]);
  379. Path ->
  380. Params1 = maps:to_list(maps:with([env, args, cd], Params)),
  381. Port = erlang:open_port( {spawn_executable, Path}
  382. , [ exit_status
  383. , nouse_stdio
  384. | Params1
  385. ]
  386. ),
  387. receive
  388. {Port, {exit_status, Status}} ->
  389. Status
  390. end
  391. end.
  392. fail(Str) ->
  393. fail(Str, []).
  394. fail(Str, Args) ->
  395. log(Str ++ "~n", Args),
  396. halt(1).
  397. log(Msg) ->
  398. log(Msg, []).
  399. log(Msg, Args) ->
  400. io:format(standard_error, Msg, Args).
  401. ensure_string(Str) when is_binary(Str) ->
  402. binary_to_list(Str);
  403. ensure_string(Str) when is_list(Str) ->
  404. Str.
  405. otp_standard_apps() ->
  406. [ssl, mnesia, kernel, asn1, stdlib].