1 |
|
-module(mongoose_shaper_sup). |
2 |
|
|
3 |
|
-behaviour(supervisor). |
4 |
|
|
5 |
|
%% API |
6 |
|
-export([start_link/0, get_workers/0, select_worker/1]). |
7 |
|
-ignore_xref([start_link/0]). |
8 |
|
|
9 |
|
%% Supervisor callbacks |
10 |
|
-export([init/1]). |
11 |
|
|
12 |
|
-spec start_link() -> {ok, pid()} | ignore | {error, term()}. |
13 |
|
start_link() -> |
14 |
104 |
supervisor:start_link({local, ?MODULE}, ?MODULE, []). |
15 |
|
|
16 |
|
-spec init([]) -> {ok, {#{strategy => one_for_one, intensity => 100, period => 5}, |
17 |
|
[supervisor:child_spec()]}}. |
18 |
|
init([]) -> |
19 |
104 |
SupFlags = #{strategy => one_for_one, intensity => 100, period => 5}, |
20 |
104 |
WorkerNames = worker_names(), |
21 |
104 |
TupleNames = list_to_tuple(WorkerNames), |
22 |
104 |
persistent_term:put(?MODULE, TupleNames), |
23 |
104 |
Shapers = [child_spec(Name) || Name <- WorkerNames], |
24 |
104 |
{ok, { SupFlags, Shapers }}. |
25 |
|
|
26 |
|
-spec child_spec(atom()) -> supervisor:child_spec(). |
27 |
|
child_spec(ProcName) -> |
28 |
1040 |
#{id => ProcName, |
29 |
|
start => {shaper_srv, start_link, [ProcName]}, |
30 |
|
restart => permanent, |
31 |
|
shutdown => 5000, |
32 |
|
type => worker, |
33 |
|
modules => [shaper_srv]}. |
34 |
|
|
35 |
|
-spec get_workers() -> [atom()]. |
36 |
|
get_workers() -> |
37 |
1 |
tuple_to_list(persistent_term:get(?MODULE)). |
38 |
|
|
39 |
|
-spec select_worker(term()) -> atom(). |
40 |
|
select_worker(Key) -> |
41 |
3488 |
N = 1 + erlang:phash2(Key, worker_count()), |
42 |
3488 |
Workers = persistent_term:get(?MODULE), |
43 |
3488 |
element(N, Workers). |
44 |
|
|
45 |
|
-spec worker_names() -> [atom()]. |
46 |
|
worker_names() -> |
47 |
104 |
[build_worker_name(N) || N <- lists:seq(1, worker_count())]. |
48 |
|
|
49 |
|
-spec build_worker_name(integer()) -> atom(). |
50 |
|
build_worker_name(N) -> |
51 |
1040 |
list_to_atom(worker_prefix() ++ integer_to_list(N)). |
52 |
|
|
53 |
|
-spec worker_prefix() -> string(). |
54 |
|
worker_prefix() -> |
55 |
1040 |
"mongoose_shaper_". |
56 |
|
|
57 |
|
worker_count() -> |
58 |
3592 |
10. |