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_shovel_dyn_worker_sup).
9-behaviour(supervisor2).
10
11-export([start_link/2, init/1]).
12
13-import(rabbit_misc, [pget/3]).
14
15-include_lib("rabbit_common/include/rabbit.hrl").
16-include("rabbit_shovel.hrl").
17-define(SUPERVISOR, ?MODULE).
18
19start_link(Name, Config) ->
20    ShovelParameter = rabbit_shovel_util:get_shovel_parameter(Name),
21    maybe_start_link(ShovelParameter, Name, Config).
22
23maybe_start_link(not_found, _Name, _Config) ->
24    %% See rabbitmq/rabbitmq-server#2655.
25    %% All dynamic shovels require that their associated parameter is present.
26    %% If not, this shovel has been deleted and stale child spec information
27    %% may still reside in the supervisor.
28    %%
29    %% We return 'ignore' to ensure that the child is not [re-]added in such case.
30    ignore;
31maybe_start_link(_, Name, Config) ->
32    supervisor2:start_link(?MODULE, [Name, Config]).
33
34%%----------------------------------------------------------------------------
35
36init([Name, Config0]) ->
37    Config  = rabbit_data_coercion:to_proplist(Config0),
38    Delay   = pget(<<"reconnect-delay">>, Config, ?DEFAULT_RECONNECT_DELAY),
39    case Name of
40      {VHost, ShovelName} -> rabbit_log:debug("Shovel '~s' in virtual host '~s' will use reconnection delay of ~p", [ShovelName, VHost, Delay]);
41      ShovelName          -> rabbit_log:debug("Shovel '~s' will use reconnection delay of ~s", [ShovelName, Delay])
42    end,
43    Restart = case Delay of
44        N when is_integer(N) andalso N > 0 ->
45          case pget(<<"src-delete-after">>, Config, pget(<<"delete-after">>, Config, <<"never">>)) of
46            %% always try to reconnect
47            <<"never">>                        -> {permanent, N};
48            %% this Shovel is an autodelete one
49              M when is_integer(M) andalso M > 0 -> {transient, N};
50              <<"queue-length">> -> {transient, N}
51          end;
52        %% reconnect-delay = 0 means "do not reconnect"
53        _                                  -> temporary
54    end,
55    {ok, {{one_for_one, 1, ?MAX_WAIT},
56          [{Name,
57            {rabbit_shovel_worker, start_link, [dynamic, Name, Config]},
58            Restart,
59            16#ffffffff, worker, [rabbit_shovel_worker]}]}}.
60