update_appup.escript 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. Diffs =
  88. lists:filtermap(
  89. fun({App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}) ->
  90. case parse_appup_diffs(Upgrade, OldUpgrade,
  91. Downgrade, OldDowngrade) of
  92. ok ->
  93. false;
  94. {diffs, Diffs} ->
  95. {true, {App, Diffs}}
  96. end
  97. end,
  98. AppupChanges),
  99. case Diffs =:= [] of
  100. true ->
  101. ok;
  102. false ->
  103. set_invalid(),
  104. log("ERROR: The appup files are incomplete. Missing changes:~n ~p",
  105. [Diffs])
  106. end
  107. end;
  108. false ->
  109. update_appups(AppupChanges)
  110. end,
  111. check_appup_files(),
  112. warn_and_exit(is_valid()).
  113. warn_and_exit(true) ->
  114. log("
  115. NOTE: Please review the changes manually. This script does not know about NIF
  116. changes, supervisor changes, process restarts and so on. Also the load order of
  117. the beam files might need updating.~n"),
  118. halt(0);
  119. warn_and_exit(false) ->
  120. log("~nERROR: Incomplete appups found. Please inspect the output for more details.~n"),
  121. halt(1).
  122. prepare(Baseline, Options = #{make_command := MakeCommand, beams_dir := BeamDir, binary_rel_url := BinRel}) ->
  123. log("~n===================================~n"
  124. "Baseline: ~s"
  125. "~n===================================~n", [Baseline]),
  126. log("Building the current version...~n"),
  127. bash(MakeCommand),
  128. log("Downloading and building the previous release...~n"),
  129. PrevRelDir =
  130. case BinRel of
  131. undefined ->
  132. {ok, PrevRootDir} = build_prev_release(Baseline, Options),
  133. filename:join(PrevRootDir, BeamDir);
  134. {ok, _URL} ->
  135. {ok, PrevRootDir} = download_prev_release(Baseline, Options),
  136. PrevRootDir
  137. end,
  138. {BeamDir, PrevRelDir}.
  139. build_prev_release(Baseline, #{clone_url := Repo, make_command := MakeCommand}) ->
  140. BaseDir = "/tmp/emqx-baseline/",
  141. Dir = filename:basename(Repo, ".git") ++ [$-|Baseline],
  142. %% TODO: shallow clone
  143. Script = "mkdir -p ${BASEDIR} &&
  144. cd ${BASEDIR} &&
  145. { [ -d ${DIR} ] || git clone --branch ${TAG} ${REPO} ${DIR}; } &&
  146. cd ${DIR} &&" ++ MakeCommand,
  147. Env = [{"REPO", Repo}, {"TAG", Baseline}, {"BASEDIR", BaseDir}, {"DIR", Dir}],
  148. bash(Script, Env),
  149. {ok, filename:join(BaseDir, Dir)}.
  150. download_prev_release(Tag, #{binary_rel_url := {ok, URL0}, clone_url := Repo}) ->
  151. URL = string:replace(URL0, "%TAG%", Tag, all),
  152. BaseDir = "/tmp/emqx-baseline-bin/",
  153. Dir = filename:basename(Repo, ".git") ++ [$-|Tag],
  154. Filename = filename:join(BaseDir, Dir),
  155. Script = "mkdir -p ${OUTFILE} &&
  156. wget -c -O ${OUTFILE}.zip ${URL} &&
  157. unzip -n -d ${OUTFILE} ${OUTFILE}.zip",
  158. Env = [{"TAG", Tag}, {"OUTFILE", Filename}, {"URL", URL}],
  159. bash(Script, Env),
  160. {ok, Filename}.
  161. find_upstream_repo(Remote) ->
  162. string:trim(os:cmd("git remote get-url " ++ Remote)).
  163. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  164. %% Appup action creation and updating
  165. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  166. find_appup_actions(CurrApps, PrevApps) ->
  167. maps:fold(
  168. fun(App, CurrAppIdx, Acc) ->
  169. case PrevApps of
  170. #{App := PrevAppIdx} -> find_appup_actions(App, CurrAppIdx, PrevAppIdx) ++ Acc;
  171. _ -> Acc %% New app, nothing to upgrade here.
  172. end
  173. end,
  174. [],
  175. CurrApps).
  176. find_appup_actions(_App, AppIdx, AppIdx) ->
  177. %% No changes to the app, ignore:
  178. [];
  179. find_appup_actions(App, CurrAppIdx, PrevAppIdx = #app{version = PrevVersion}) ->
  180. {OldUpgrade, OldDowngrade} = find_old_appup_actions(App, PrevVersion),
  181. Upgrade = merge_update_actions(App, diff_app(App, CurrAppIdx, PrevAppIdx), OldUpgrade),
  182. Downgrade = merge_update_actions(App, diff_app(App, PrevAppIdx, CurrAppIdx), OldDowngrade),
  183. if OldUpgrade =:= Upgrade andalso OldDowngrade =:= Downgrade ->
  184. %% The appup file has been already updated:
  185. [];
  186. true ->
  187. [{App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}]
  188. end.
  189. %% For external dependencies, show only the changes that are missing
  190. %% in their current appup.
  191. diff_appup_instructions(ComputedChanges, PresentChanges) ->
  192. lists:foldr(
  193. fun({Vsn, ComputedActions}, Acc) ->
  194. case find_matching_version(Vsn, PresentChanges) of
  195. undefined ->
  196. [{Vsn, ComputedActions} | Acc];
  197. PresentActions ->
  198. DiffActions = ComputedActions -- PresentActions,
  199. case DiffActions of
  200. [] ->
  201. %% no diff
  202. Acc;
  203. _ ->
  204. [{Vsn, DiffActions} | Acc]
  205. end
  206. end
  207. end,
  208. [],
  209. ComputedChanges).
  210. %% For external dependencies, checks if any missing diffs are present
  211. %% and groups them by `up' and `down' types.
  212. parse_appup_diffs(Upgrade, OldUpgrade, Downgrade, OldDowngrade) ->
  213. DiffUp = diff_appup_instructions(Upgrade, OldUpgrade),
  214. DiffDown = diff_appup_instructions(Downgrade, OldDowngrade),
  215. case {DiffUp, DiffDown} of
  216. {[], []} ->
  217. %% no diff for external dependency; ignore
  218. ok;
  219. _ ->
  220. set_invalid(),
  221. Diffs = #{ up => DiffUp
  222. , down => DiffDown
  223. },
  224. {diffs, Diffs}
  225. end.
  226. %% TODO: handle regexes
  227. find_matching_version(Vsn, PresentChanges) ->
  228. proplists:get_value(Vsn, PresentChanges).
  229. find_old_appup_actions(App, PrevVersion) ->
  230. {Upgrade0, Downgrade0} =
  231. case locate(ebin_current, App, ".appup") of
  232. {ok, AppupFile} ->
  233. log("Found the previous appup file: ~s~n", [AppupFile]),
  234. {_, U, D} = read_appup(AppupFile),
  235. {U, D};
  236. undefined ->
  237. %% Fallback to the app.src file, in case the
  238. %% application doesn't have a release (useful for the
  239. %% apps that live outside the EMQX monorepo):
  240. case locate(src, App, ".appup.src") of
  241. {ok, AppupSrcFile} ->
  242. log("Using ~s as a source of previous update actions~n", [AppupSrcFile]),
  243. {_, U, D} = read_appup(AppupSrcFile),
  244. {U, D};
  245. undefined ->
  246. {[], []}
  247. end
  248. end,
  249. {ensure_version(PrevVersion, Upgrade0), ensure_version(PrevVersion, Downgrade0)}.
  250. merge_update_actions(App, Changes, Vsns) ->
  251. lists:map(fun(Ret = {<<".*">>, _}) ->
  252. Ret;
  253. ({Vsn, Actions}) ->
  254. {Vsn, do_merge_update_actions(App, Changes, Actions)}
  255. end,
  256. Vsns).
  257. do_merge_update_actions(App, {New0, Changed0, Deleted0}, OldActions) ->
  258. AppSpecific = app_specific_actions(App) -- OldActions,
  259. AlreadyHandled = lists:flatten(lists:map(fun process_old_action/1, OldActions)),
  260. New = New0 -- AlreadyHandled,
  261. Changed = Changed0 -- AlreadyHandled,
  262. Deleted = Deleted0 -- AlreadyHandled,
  263. [{load_module, M, brutal_purge, soft_purge, []} || M <- Changed ++ New] ++
  264. OldActions ++
  265. [{delete_module, M} || M <- Deleted] ++
  266. AppSpecific.
  267. %% @doc Process the existing actions to exclude modules that are
  268. %% already handled
  269. process_old_action({purge, Modules}) ->
  270. Modules;
  271. process_old_action({delete_module, Module}) ->
  272. [Module];
  273. process_old_action(LoadModule) when is_tuple(LoadModule) andalso
  274. element(1, LoadModule) =:= load_module ->
  275. element(2, LoadModule);
  276. process_old_action(_) ->
  277. [].
  278. ensure_version(Version, OldInstructions) ->
  279. OldVersions = [ensure_string(element(1, I)) || I <- OldInstructions],
  280. case lists:member(Version, OldVersions) of
  281. false ->
  282. [{Version, []}|OldInstructions];
  283. _ ->
  284. OldInstructions
  285. end.
  286. read_appup(File) ->
  287. %% NOTE: appup file is a script, it may contain variables or functions.
  288. case file:script(File, [{'VSN', "VSN"}]) of
  289. {ok, Terms} ->
  290. Terms;
  291. Error ->
  292. fail("Failed to parse appup file ~s: ~p", [File, Error])
  293. end.
  294. check_appup_files() ->
  295. AppupFiles = filelib:wildcard(getopt(src_dirs) ++ "/*.appup.src"),
  296. lists:foreach(fun read_appup/1, AppupFiles).
  297. update_appups(Changes) ->
  298. lists:foreach(
  299. fun({App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}) ->
  300. do_update_appup(App, Upgrade, Downgrade, OldUpgrade, OldDowngrade)
  301. end,
  302. Changes).
  303. do_update_appup(App, Upgrade, Downgrade, OldUpgrade, OldDowngrade) ->
  304. case locate(src, App, ".appup.src") of
  305. {ok, AppupFile} ->
  306. render_appfile(AppupFile, Upgrade, Downgrade);
  307. undefined ->
  308. case create_stub(App) of
  309. {ok, AppupFile} ->
  310. render_appfile(AppupFile, Upgrade, Downgrade);
  311. false ->
  312. case parse_appup_diffs(Upgrade, OldUpgrade,
  313. Downgrade, OldDowngrade) of
  314. ok ->
  315. %% no diff for external dependency; ignore
  316. ok;
  317. {diffs, Diffs} ->
  318. set_invalid(),
  319. log("ERROR: Appup file for the external dependency '~p' is not complete.~n Missing changes: ~100p~n", [App, Diffs]),
  320. log("NOTE: Some changes above might be already covered by regexes.~n")
  321. end
  322. end
  323. end.
  324. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  325. %% Appup file creation
  326. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  327. render_appfile(File, Upgrade, Downgrade) ->
  328. IOList = io_lib:format("%% -*- mode: erlang -*-\n{VSN,~n ~p,~n ~p}.~n", [Upgrade, Downgrade]),
  329. ok = file:write_file(File, IOList).
  330. create_stub(App) ->
  331. Ext = ".app.src",
  332. case locate(src, App, Ext) of
  333. {ok, AppSrc} ->
  334. DirName = filename:dirname(AppSrc),
  335. AppupFile = filename:basename(AppSrc, Ext) ++ ".appup.src",
  336. Default = {<<".*">>, []},
  337. AppupFileFullpath = filename:join(DirName, AppupFile),
  338. render_appfile(AppupFileFullpath, [Default], [Default]),
  339. {ok, AppupFileFullpath};
  340. undefined ->
  341. false
  342. end.
  343. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  344. %% application and release indexing
  345. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  346. index_apps(ReleaseDir) ->
  347. Apps0 = maps:from_list([index_app(filename:join(ReleaseDir, AppFile)) ||
  348. AppFile <- filelib:wildcard("**/ebin/*.app", ReleaseDir)]),
  349. maps:without(ignored_apps(), Apps0).
  350. index_app(AppFile) ->
  351. {ok, [{application, App, Properties}]} = file:consult(AppFile),
  352. Vsn = proplists:get_value(vsn, Properties),
  353. %% Note: assuming that beams are always located in the same directory where app file is:
  354. EbinDir = filename:dirname(AppFile),
  355. Modules = hashsums(EbinDir),
  356. {App, #app{ version = Vsn
  357. , modules = Modules
  358. }}.
  359. diff_app(App, #app{version = NewVersion, modules = NewModules}, #app{version = OldVersion, modules = OldModules}) ->
  360. {New, Changed} =
  361. maps:fold( fun(Mod, MD5, {New, Changed}) ->
  362. case OldModules of
  363. #{Mod := OldMD5} when MD5 =:= OldMD5 ->
  364. {New, Changed};
  365. #{Mod := _} ->
  366. {New, [Mod|Changed]};
  367. _ ->
  368. {[Mod|New], Changed}
  369. end
  370. end
  371. , {[], []}
  372. , NewModules
  373. ),
  374. Deleted = maps:keys(maps:without(maps:keys(NewModules), OldModules)),
  375. NChanges = length(New) + length(Changed) + length(Deleted),
  376. if NewVersion =:= OldVersion andalso NChanges > 0 ->
  377. set_invalid(),
  378. log("ERROR: Application '~p' contains changes, but its version is not updated~n", [App]);
  379. NewVersion > OldVersion ->
  380. log("INFO: Application '~p' has been updated: ~p -> ~p~n", [App, OldVersion, NewVersion]),
  381. ok;
  382. true ->
  383. ok
  384. end,
  385. {New, Changed, Deleted}.
  386. -spec hashsums(file:filename()) -> #{module() => binary()}.
  387. hashsums(EbinDir) ->
  388. maps:from_list(lists:map(
  389. fun(Beam) ->
  390. File = filename:join(EbinDir, Beam),
  391. {ok, Ret = {_Module, _MD5}} = beam_lib:md5(File),
  392. Ret
  393. end,
  394. filelib:wildcard("*.beam", EbinDir)
  395. )).
  396. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  397. %% Global state
  398. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  399. init_globals(Options) ->
  400. ets:new(globals, [named_table, set, public]),
  401. ets:insert(globals, {valid, true}),
  402. ets:insert(globals, {options, Options}).
  403. getopt(Option) ->
  404. maps:get(Option, ets:lookup_element(globals, options, 2)).
  405. %% Set a global flag that something about the appfiles is invalid
  406. set_invalid() ->
  407. ets:insert(globals, {valid, false}).
  408. is_valid() ->
  409. ets:lookup_element(globals, valid, 2).
  410. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  411. %% Utility functions
  412. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  413. %% Locate a file in a specified application
  414. locate(ebin_current, App, Suffix) ->
  415. ReleaseDir = getopt(beams_dir),
  416. AppStr = atom_to_list(App),
  417. case filelib:wildcard(ReleaseDir ++ "/**/ebin/" ++ AppStr ++ Suffix) of
  418. [File] ->
  419. {ok, File};
  420. [] ->
  421. undefined
  422. end;
  423. locate(src, App, Suffix) ->
  424. AppStr = atom_to_list(App),
  425. SrcDirs = getopt(src_dirs),
  426. case filelib:wildcard(SrcDirs ++ AppStr ++ Suffix) of
  427. [File] ->
  428. {ok, File};
  429. [] ->
  430. undefined
  431. end.
  432. bash(Script) ->
  433. bash(Script, []).
  434. bash(Script, Env) ->
  435. log("+ ~s~n+ Env: ~p~n", [Script, Env]),
  436. case cmd("bash", #{args => ["-c", Script], env => Env}) of
  437. 0 -> true;
  438. _ -> fail("Failed to run command: ~s", [Script])
  439. end.
  440. %% Spawn an executable and return the exit status
  441. cmd(Exec, Params) ->
  442. case os:find_executable(Exec) of
  443. false ->
  444. fail("Executable not found in $PATH: ~s", [Exec]);
  445. Path ->
  446. Params1 = maps:to_list(maps:with([env, args, cd], Params)),
  447. Port = erlang:open_port( {spawn_executable, Path}
  448. , [ exit_status
  449. , nouse_stdio
  450. | Params1
  451. ]
  452. ),
  453. receive
  454. {Port, {exit_status, Status}} ->
  455. Status
  456. end
  457. end.
  458. fail(Str) ->
  459. fail(Str, []).
  460. fail(Str, Args) ->
  461. log(Str ++ "~n", Args),
  462. halt(1).
  463. log(Msg) ->
  464. log(Msg, []).
  465. log(Msg, Args) ->
  466. io:format(standard_error, Msg, Args).
  467. ensure_string(Str) when is_binary(Str) ->
  468. binary_to_list(Str);
  469. ensure_string(Str) when is_list(Str) ->
  470. Str.
  471. otp_standard_apps() ->
  472. [ssl, mnesia, kernel, asn1, stdlib].