1%% This Source Code Form is subject to the terms of the Mozilla Public
2%% License, v. 2.0. If a copy of the MPL was not distributed with this
3%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
4%%
5%% Copyright (c) 2007-2021 VMware, Inc. or its affiliates.  All rights reserved.
6%%
7
8-module(rabbit_prelaunch_enabled_plugins_file).
9
10-include_lib("kernel/include/logger.hrl").
11
12-include_lib("rabbit_common/include/rabbit.hrl").
13-include_lib("rabbit_common/include/logging.hrl").
14
15-export([setup/1]).
16
17setup(Context) ->
18    ?LOG_DEBUG(
19       "~n== Enabled plugins file ==", [],
20       #{domain => ?RMQLOG_DOMAIN_PRELAUNCH}),
21    update_enabled_plugins_file(Context).
22
23%% -------------------------------------------------------------------
24%% `enabled_plugins` file content initialization.
25%% -------------------------------------------------------------------
26
27update_enabled_plugins_file(#{enabled_plugins := undefined}) ->
28    ok;
29update_enabled_plugins_file(#{enabled_plugins := all,
30                              plugins_path := Path} = Context) ->
31    List = [P#plugin.name || P <- rabbit_plugins:list(Path)],
32    do_update_enabled_plugins_file(Context, List);
33update_enabled_plugins_file(#{enabled_plugins := List} = Context) ->
34    do_update_enabled_plugins_file(Context, List).
35
36do_update_enabled_plugins_file(#{enabled_plugins_file := File}, List) ->
37    SortedList = lists:usort(List),
38    case SortedList of
39        [] ->
40            ?LOG_DEBUG(
41               "Marking all plugins as disabled", [],
42               #{domain => ?RMQLOG_DOMAIN_PRELAUNCH});
43        _ ->
44            ?LOG_DEBUG(
45              lists:flatten(["Marking the following plugins as enabled:",
46                             ["~n  - ~s" || _ <- SortedList]]),
47              SortedList,
48              #{domain => ?RMQLOG_DOMAIN_PRELAUNCH})
49    end,
50    Content = io_lib:format("~p.~n", [SortedList]),
51    case file:write_file(File, Content) of
52        ok ->
53            ?LOG_DEBUG(
54               "Wrote plugins file: ~ts", [File],
55               #{domain => ?RMQLOG_DOMAIN_PRELAUNCH}),
56            ok;
57        {error, Reason} ->
58            ?LOG_ERROR(
59              "Failed to update enabled plugins file \"~ts\" "
60              "from $RABBITMQ_ENABLED_PLUGINS: ~ts",
61              [File, file:format_error(Reason)],
62              #{domain => ?RMQLOG_DOMAIN_PRELAUNCH}),
63            throw({error, failed_to_update_enabled_plugins_file})
64    end.
65