├── rebar.lock ├── rebar.config ├── .gitignore ├── src ├── havoc.app.src ├── havoc_app.erl ├── havoc_sup.erl └── havoc.erl ├── README.md └── LICENSE /rebar.lock: -------------------------------------------------------------------------------- 1 | []. 2 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info]}. 2 | {deps, []}. 3 | 4 | {shell, [ 5 | % {config, [{config, "config/sys.config"}]}, 6 | {apps, [havoc]} 7 | ]}. 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .rebar3 2 | _* 3 | .eunit 4 | *.o 5 | *.beam 6 | *.plt 7 | *.swp 8 | *.swo 9 | .erlang.cookie 10 | ebin 11 | log 12 | erl_crash.dump 13 | .rebar 14 | logs 15 | _build 16 | .idea 17 | *.iml 18 | rebar3.crashdump 19 | -------------------------------------------------------------------------------- /src/havoc.app.src: -------------------------------------------------------------------------------- 1 | {application, havoc, 2 | [{description, "A ChaosMonkey style application to test the resiliency of your application"}, 3 | {vsn, "0.2.3"}, 4 | {registered, [havoc]}, 5 | {mod, { havoc_app, []}}, 6 | {applications, 7 | [kernel, 8 | stdlib 9 | ]}, 10 | {env,[]}, 11 | {modules, []}, 12 | {licenses, ["Apache 2.0"]}, 13 | {links, [{"Github", "https://github.com/ankhers/havoc"}]} 14 | ]}. 15 | -------------------------------------------------------------------------------- /src/havoc_app.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @private 3 | %%%------------------------------------------------------------------- 4 | 5 | -module(havoc_app). 6 | 7 | -behaviour(application). 8 | 9 | %% Application callbacks 10 | -export([start/2, stop/1]). 11 | 12 | %%==================================================================== 13 | %% API 14 | %%==================================================================== 15 | 16 | start(_StartType, _StartArgs) -> 17 | havoc_sup:start_link(). 18 | 19 | %%-------------------------------------------------------------------- 20 | stop(_State) -> 21 | ok. 22 | 23 | %%==================================================================== 24 | %% Internal functions 25 | %%==================================================================== 26 | -------------------------------------------------------------------------------- /src/havoc_sup.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @private 3 | %%%------------------------------------------------------------------- 4 | 5 | -module(havoc_sup). 6 | 7 | -behaviour(supervisor). 8 | 9 | %% API 10 | -export([start_link/0]). 11 | 12 | %% Supervisor callbacks 13 | -export([init/1]). 14 | 15 | -define(SERVER, ?MODULE). 16 | 17 | %%==================================================================== 18 | %% API functions 19 | %%==================================================================== 20 | 21 | start_link() -> 22 | supervisor:start_link({local, ?SERVER}, ?MODULE, []). 23 | 24 | %%==================================================================== 25 | %% Supervisor callbacks 26 | %%==================================================================== 27 | 28 | %% Child :: #{id => Id, start => {M, F, A}} 29 | %% Optional keys are restart, shutdown, type, modules. 30 | %% Before OTP 18 tuples must be used to specify a child. e.g. 31 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules} 32 | init([]) -> 33 | Havoc = #{id => havoc, start => {havoc, start_link, []}}, 34 | {ok, { {one_for_all, 0, 1}, [Havoc]} }. 35 | 36 | %%==================================================================== 37 | %% Internal functions 38 | %%==================================================================== 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Havoc 2 | ====== 3 | 4 | A ChaosMonkey style application that can randomly kill processes, as well as 5 | TCP and UDP connections. Inspired by [dLuna/chaos_monkey](https://github.com/dLuna/chaos_monkey). 6 | 7 | Basic Usage 8 | ----------- 9 | ``` erlang 10 | havoc:on(). 11 | ``` 12 | 13 | This will use the default options. The following is a list of currently 14 | allowed options 15 | 16 | * `avg_wait` - The average amount of time you would like to wait between kills. 17 | (default `5000`) 18 | * `deviation` - The deviation of time allowed between kills. (default `0.3`) 19 | * `supervisor` - Whether or not to kill supervisors. (default `false`) 20 | * `process` - Whether or not to kill processes. (default `true`) 21 | * `tcp` - Whether or not to kill TCP connections. (default `false`) 22 | * `udp` - Whether or not to kill UDP connections. (default `false`) 23 | * `nodes` - Either a list of atoms for node names, or any value that 24 | `erlang:nodes/1` accepts. (default `this`) 25 | * `applications` - A list of application names that you want to target. 26 | (defaults to all applications except `kernel` and `havoc`) 27 | * `otp_applications` - A list of OTP applications that you would like to target. 28 | (default `[]`) 29 | * `supervisors` - A list of supervisors that you want to target. Can be any 30 | valid supervisor reference. (defaults to all supervisors) 31 | * `killable_callback` - A `Fun` that gets called to decide if a `pid` or 32 | `port` may be killed or not by returning `true` or `false`. 33 | * `prekill_callback` - A `Fun` that gets called just before killing. 34 | 35 | You can specify options using `havoc:on/1`. 36 | 37 | ``` erlang 38 | havoc:on([{avg_wait, 3000}, {deviation, 0.5}, process, tcp]) 39 | ``` 40 | 41 | It is also possible to check if havoc is currently active. 42 | 43 | ``` erlang 44 | havoc:is_active() 45 | ``` 46 | 47 | Build 48 | ----- 49 | 50 | $ rebar3 compile 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2018, Justin Wood . 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | -------------------------------------------------------------------------------- /src/havoc.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %% @doc havoc 3 | %% @end 4 | %%%------------------------------------------------------------------- 5 | 6 | -module(havoc). 7 | 8 | -behaviour(gen_server). 9 | 10 | %% API 11 | -export([start_link/0]). 12 | -export([on/0, on/1, off/0, is_active/0]). 13 | 14 | %% GenServer callbacks 15 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). 16 | 17 | -define(SERVER, ?MODULE). 18 | 19 | -record(state, {is_active = false, 20 | avg_wait, 21 | deviation, 22 | supervisor, 23 | process, 24 | tcp, 25 | udp, 26 | nodes, 27 | applications, 28 | otp_applications, 29 | supervisors, 30 | killable_callback, 31 | prekill_callback 32 | }). 33 | 34 | -define(TCP_NAME, "tcp_inet"). 35 | -define(UDP_NAME, "udp_inet"). 36 | 37 | %%==================================================================== 38 | %% API functions 39 | %%==================================================================== 40 | %% @private 41 | start_link() -> 42 | gen_server:start_link({local, ?SERVER}, ?MODULE, ok, []). 43 | 44 | %% @doc Begin to wreak havoc on your system using the default options. 45 | %% @end 46 | -spec on() -> ok. 47 | on() -> 48 | gen_server:call(?SERVER, {on, []}). 49 | 50 | %% @doc Begin to wreak havoc on your system. 51 | %% @param Opts A proplist that accepts the following options. 52 | %% 73 | %% @end 74 | -spec on(list(term())) -> ok. 75 | on(Opts) -> 76 | gen_server:call(?SERVER, {on, Opts}). 77 | 78 | %% @doc Stops killing things within your system. 79 | -spec off() -> ok. 80 | off() -> 81 | gen_server:call(?SERVER, off). 82 | 83 | %% @doc Get the current status. 84 | -spec is_active() -> boolean(). 85 | is_active() -> 86 | gen_server:call(?SERVER, is_active). 87 | 88 | 89 | %%==================================================================== 90 | %% GenServer callbacks 91 | %%==================================================================== 92 | 93 | %% @private 94 | init(ok) -> 95 | {ok, #state{}}. 96 | 97 | %% @private 98 | handle_call({on, Opts}, _From, #state{is_active = false} = State) -> 99 | Wait = proplists:get_value(avg_wait, Opts, 5000), 100 | Deviation = proplists:get_value(deviation, Opts, 0.3), 101 | Supervisor = proplists:get_bool(supervisor, Opts), 102 | Process = 103 | case proplists:lookup(process, Opts) of 104 | {process, Val} -> Val; 105 | none -> true 106 | end, 107 | Tcp = proplists:get_bool(tcp, Opts), 108 | Udp = proplists:get_bool(udp, Opts), 109 | Nodes = proplists:get_value(nodes, Opts, this), 110 | Applications = proplists:get_value(applications, Opts), 111 | OTPApplications = proplists:get_value(otp_applications, Opts, []), 112 | Supervisors = proplists:get_value(supervisors, Opts), 113 | KillableCallback = proplists:get_value(killable_callback, Opts, default_killable_callback()), 114 | PrekillCallback = proplists:get_value(prekill_callback, Opts, default_prekill_callback()), 115 | NewState = State#state{is_active = true, avg_wait = Wait, 116 | deviation = Deviation, supervisor = Supervisor, 117 | process = Process, tcp = Tcp, 118 | udp = Udp, nodes = Nodes, 119 | applications = Applications, 120 | otp_applications = OTPApplications, 121 | supervisors = Supervisors, 122 | killable_callback = KillableCallback, 123 | prekill_callback = PrekillCallback}, 124 | self() ! kill_something, 125 | {reply, ok, NewState}; 126 | 127 | handle_call(off, _From, #state{is_active = true} = State) -> 128 | {reply, ok, State#state{is_active = false}}; 129 | 130 | handle_call(is_active, _From, #state{is_active = IsActive} = State) -> 131 | {reply, IsActive, State}; 132 | 133 | handle_call(_Msg, _From, State) -> 134 | {noreply, State}. 135 | 136 | %% @private 137 | handle_cast(_Msg, State) -> 138 | {noreply, State}. 139 | 140 | %% @private 141 | handle_info(kill_something, #state{is_active = true} = State) -> 142 | try_kill_one(State), 143 | schedule(State#state.avg_wait, State#state.deviation), 144 | {noreply, State}; 145 | 146 | handle_info(_Msg, State) -> 147 | {noreply, State}. 148 | 149 | %%==================================================================== 150 | %% Internal functions 151 | %%==================================================================== 152 | -spec schedule(non_neg_integer(), number()) -> ok. 153 | schedule(Wait, Deviation) -> 154 | case round(Wait * (1 + Deviation * (2 * rand:uniform() - 1))) of 155 | Delay when Delay > 0 -> erlang:send_after(Delay, self(), kill_something); 156 | _ -> self() ! kill_something 157 | end, 158 | ok. 159 | 160 | -spec try_kill_one(#state{}) -> {ok, term()} | {error, nothing_to_kill}. 161 | try_kill_one(State) -> 162 | case shuffle_nodes(State#state.nodes) of 163 | [] -> nil; % Nothing to do. 164 | [Node | _Rest] -> 165 | Processes = process_list(State#state.process, Node), 166 | Tcp = tcp_list(State#state.tcp, Node), 167 | Udp = udp_list(State#state.udp, Node), 168 | Shuffled = shuffle(Processes ++ Tcp ++ Udp), 169 | kill_one(Shuffled, State) 170 | end. 171 | 172 | -spec shuffle_nodes(list(node()) | atom()) -> [node()]. 173 | shuffle_nodes(L) when is_list(L) -> 174 | shuffle(L); 175 | shuffle_nodes(A) when is_atom(A) -> 176 | shuffle(nodes(A)). 177 | 178 | -spec process_list(boolean(), node()) -> list(pid()). 179 | process_list(true, Node) -> 180 | rpc:call(Node, erlang, processes, []); 181 | process_list(false, _Node) -> 182 | []. 183 | 184 | -spec tcp_list(boolean(), node()) -> list(port()). 185 | tcp_list(true, Node) -> 186 | Ports = rpc:call(Node, erlang, ports, []), 187 | lists:filter(fun (Port) -> erlang:port_info(Port, name) =:= {name, ?TCP_NAME} end, Ports); 188 | tcp_list(false, _Node) -> 189 | []. 190 | 191 | -spec udp_list(boolean(), node()) -> list(port()). 192 | udp_list(true, Node) -> 193 | Ports = rpc:call(Node, erlang, ports, []), 194 | lists:filter(fun (Port) -> erlang:port_info(Port, name) =:= {name, ?UDP_NAME} end, Ports); 195 | udp_list(false, _Node) -> 196 | []. 197 | 198 | 199 | -spec shuffle(list()) -> list(). 200 | shuffle(L) -> 201 | Shuffled = lists:sort([{rand:uniform(), X} || X <- L]), 202 | [X || {_, X} <- Shuffled]. 203 | 204 | -spec kill_one(list(pid()), #state{}) -> {ok, term()} | {error, nothing_to_kill}. 205 | kill_one([], _State) -> {error, nothing_to_kill}; 206 | kill_one([H | T], State) -> 207 | case 208 | is_killable(H, State) andalso 209 | killable_callback(State#state.killable_callback, H) 210 | of 211 | true -> 212 | prekill_callback(State#state.prekill_callback, H), 213 | kill(H); 214 | false -> 215 | kill_one(T, State) 216 | end. 217 | 218 | -spec killable_callback(fun((PidOrPort) -> Result), PidOrPort) -> Result 219 | when PidOrPort :: pid() | port(), 220 | Result :: boolean(). 221 | killable_callback(Fun, PidOrPort) when is_function(Fun, 1) -> 222 | Fun(PidOrPort). 223 | 224 | -spec default_killable_callback() -> fun((pid() | port()) -> true). 225 | default_killable_callback() -> fun(_X) -> true end. 226 | 227 | -spec prekill_callback(fun((PidOrPort) -> any()), PidOrPort) -> ok 228 | when PidOrPort :: pid() | port(). 229 | prekill_callback(Fun, PidOrPort) when is_function(Fun, 1) -> 230 | Fun(PidOrPort), 231 | ok. 232 | 233 | -spec default_prekill_callback() -> fun((pid() | port()) -> ok). 234 | default_prekill_callback() -> fun(_X) -> ok end. 235 | 236 | %% http://erlang.org/doc/apps/ 237 | -define(OTP_APPS, [asn1, common_test, compiler, crypto, debugger, dialyzer, 238 | diameter, edoc, eldap, erl_docgen, erl_interface, erts, et, 239 | eunit, ftp, hipe, inets, jinterface, kernel, megaco, mnesia, 240 | observer, odbc, os_mon, otp_mibs, parsetools, public_key, 241 | reltool, runtime_tools, sasl, snmp, ssh, ssl, stdlib, 242 | syntax_tools, tftp, tools, wx, xmerl]). 243 | 244 | -spec is_killable(pid() | port(), #state{}) -> boolean(). 245 | is_killable(Pid, State) when is_pid(Pid) -> 246 | App = case application:get_application(Pid) of 247 | {ok, A} -> A; 248 | undefined -> undefined 249 | end, 250 | 251 | Module = get_initial_call_module(Pid), 252 | 253 | not(erts_internal:is_system_process(Pid)) 254 | andalso not(is_application_controller(Pid)) 255 | andalso Module =/= application_master 256 | andalso not(lists:member(App, ?OTP_APPS -- State#state.otp_applications)) 257 | andalso not(lists:member(App, [kernel, havoc])) 258 | andalso not(is_shell(Pid)) 259 | andalso (Module =/= supervisor 260 | orelse State#state.supervisor 261 | andalso not(is_application_top_supervisor(Pid))) 262 | andalso (app_killable(App, State#state.applications) 263 | orelse supervisor_killable(Pid, State#state.supervisors)); 264 | is_killable(Port, _State) when is_port(Port) -> 265 | true. 266 | 267 | -spec app_killable(atom(), undefined | [atom()]) -> boolean(). 268 | app_killable(_App, undefined) -> 269 | true; 270 | app_killable(App, Applications) -> 271 | lists:member(App, Applications). 272 | 273 | -spec supervisor_killable(pid(), undefined | [supervisor:sup_ref()]) -> boolean(). 274 | supervisor_killable(_Pid, undefined) -> 275 | false; 276 | supervisor_killable(Pid, Supervisors) -> 277 | lists:any(fun(Sup) -> 278 | supervisor_killable1(Pid, supervisor:which_children(Sup)) 279 | end, Supervisors). 280 | 281 | supervisor_killable1(_, []) -> 282 | false; 283 | supervisor_killable1(Pid, [{_, Pid, _, _}|_]) -> 284 | true; 285 | supervisor_killable1(Pid, [{_, SupPid, supervisor, _}|Children]) -> 286 | SupChildren = try 287 | supervisor:which_children(SupPid) 288 | catch 289 | exit:{noproc, _} -> 290 | [] 291 | end, 292 | supervisor_killable1(Pid, Children ++ SupChildren); 293 | supervisor_killable1(Pid, [_|Children]) -> 294 | supervisor_killable1(Pid, Children). 295 | 296 | -spec kill(pid() | port()) -> term(). 297 | kill(Pid) when is_pid(Pid) -> 298 | erlang:monitor(process, Pid), 299 | exit(Pid, havoc), 300 | receive 301 | {'DOWN', _, process, Pid, Reason} -> 302 | {ok, Reason} 303 | after 500 -> 304 | exit(Pid, kill), 305 | receive 306 | {'DOWN', _, process, Pid, Reason} -> 307 | {ok, Reason} 308 | end 309 | end; 310 | kill(Port) when is_port(Port) -> 311 | {connected, Pid} = erlang:port_info(Port, connected), 312 | {ok, [{active, Active}]} = inet:getopts(Port, [active]), 313 | Msg = case erlang:port_info(Port, name) of 314 | {name, ?TCP_NAME} -> 315 | gen_tcp:close(Port), 316 | {tcp_closed, Port}; 317 | {name, ?UDP_NAME} -> 318 | gen_udp:close(Port), 319 | {udp_closed, Port} 320 | end, 321 | if Active /= false -> 322 | Pid ! Msg 323 | end, 324 | ok. 325 | 326 | -spec is_shell(pid()) -> boolean(). 327 | is_shell(Pid) -> 328 | case erlang:process_info(Pid, group_leader) of 329 | undefined -> false; 330 | {group_leader, Leader} -> 331 | case lists:keyfind(shell, 1, group:interfaces(Leader)) of 332 | {shell, Pid} -> true; 333 | {shell, Shell} -> 334 | case erlang:process_info(Shell, dictionary) of 335 | {dictionary, Dict} -> 336 | proplists:get_value(evaluator, Dict) =:= Pid; 337 | undefined -> false 338 | end; 339 | false -> false 340 | end 341 | end. 342 | 343 | -spec get_initial_call_module(pid()) -> module() | undefined. 344 | get_initial_call_module(Pid) -> 345 | case erlang:process_info(Pid, initial_call) of 346 | {initial_call, {proc_lib, init_p, 5}} -> 347 | {Module, _, _} = proc_lib:translate_initial_call(Pid), 348 | Module; 349 | {initial_call, {Module, _, _}} -> 350 | Module; 351 | _ -> 352 | undefined 353 | end. 354 | 355 | -spec is_application_top_supervisor(pid()) -> boolean(). 356 | is_application_top_supervisor(Pid) -> 357 | case erlang:process_info(Pid, dictionary) of 358 | {dictionary, Dict} -> 359 | case lists:keyfind('$ancestors', 1, Dict) of 360 | {'$ancestors', [Ancestor]} when is_pid(Ancestor) -> 361 | application_master =:= get_initial_call_module(Ancestor); 362 | _ -> 363 | false 364 | end; 365 | _ -> 366 | false 367 | end. 368 | 369 | -spec is_application_controller(pid()) -> boolean(). 370 | is_application_controller(Pid) -> 371 | Pid =:= whereis(application_controller). 372 | --------------------------------------------------------------------------------