├── .gitignore ├── LICENSE ├── Makefile ├── README.org ├── ebin └── condor.app ├── src ├── condor.erl ├── condor_app.erl ├── condor_listener.erl ├── condor_listener_sup.erl ├── condor_packet.erl └── condor_sup.erl └── test └── condor_SUITE.erl /.gitignore: -------------------------------------------------------------------------------- 1 | ebin/*.beam 2 | logs 3 | *.beam 4 | *.plt 5 | .erlang.cookie 6 | erl_crash.dump 7 | -------------------------------------------------------------------------------- /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, Sina Samavati . 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all app shell test dialyze clean distclean 2 | 3 | PROJECT = condor 4 | 5 | EBIN = $(CURDIR)/ebin 6 | TEST_DIR = $(CURDIR)/test 7 | PLT_FILE = $(CURDIR)/.$(PROJECT).plt 8 | 9 | ERLC_OPTS += -Werror +debug_info +warn_export_all +warn_export_vars \ 10 | +warn_shadow_vars +warn_obsolete_guard 11 | 12 | V ?= 0 13 | 14 | erlc_verbose_0 = @echo " ERLC " $(?F); 15 | erlc_verbose = $(erlc_verbose_$(V)) 16 | 17 | gen_verbose_0 = @echo " GEN " $@; 18 | gen_verbose = $(gen_verbose_$(V)) 19 | 20 | CT_OPTS ?= 21 | CT_RUN = ct_run \ 22 | -no_auto_compile \ 23 | -noshell \ 24 | -pa $(EBIN) \ 25 | -dir $(TEST_DIR) \ 26 | -logdir logs \ 27 | $(CT_OPTS) 28 | 29 | PLT_APPS ?= 30 | DIALYZER_OPTS ?= -Werror_handling -Wrace_conditions 31 | 32 | BEAM_FILES = \ 33 | ebin/condor_app.beam \ 34 | ebin/condor.beam \ 35 | ebin/condor_listener.beam \ 36 | ebin/condor_listener_sup.beam \ 37 | ebin/condor_packet.beam \ 38 | ebin/condor_sup.beam 39 | 40 | CT_SUITES ?= condor 41 | 42 | all: compile 43 | 44 | # -------------------------------------------------------------------- 45 | # compile 46 | # -------------------------------------------------------------------- 47 | compile: $(BEAM_FILES) 48 | 49 | ebin/%.beam: src/%.erl 50 | $(erlc_verbose) erlc -v $(ERLC_OPTS) -o $(EBIN) $< 51 | 52 | # -------------------------------------------------------------------- 53 | # run erlang shell 54 | # -------------------------------------------------------------------- 55 | shell: 56 | erl -pa $(EBIN) 57 | 58 | # -------------------------------------------------------------------- 59 | # run tests 60 | # -------------------------------------------------------------------- 61 | test: ERLC_OPTS += -DTEST=1 +export_all 62 | test: clean compile 63 | $(gen_verbose) erlc -v -o test $(ERLC_OPTS) \ 64 | $(wildcard test/*.erl test/*/*.erl) -pa ebin 65 | @mkdir -p logs 66 | @$(CT_RUN) -suite $(addsuffix _SUITE,$(CT_SUITES)) 67 | @rm -f test/*.beam 68 | 69 | # -------------------------------------------------------------------- 70 | # dialyzer 71 | # -------------------------------------------------------------------- 72 | dialyze: $(PLT_FILE) 73 | @dialyzer +S 8 --src src --plt $(PLT_FILE) \ 74 | --no_native $(DIALYZER_OPTS) 75 | 76 | $(PLT_FILE): 77 | $(gen_verbose) dialyzer +S 8 --build_plt --output_plt $@ \ 78 | --apps erts kernel stdlib $(PLT_APPS) 79 | 80 | # -------------------------------------------------------------------- 81 | # clean compiled files 82 | # -------------------------------------------------------------------- 83 | clean: 84 | rm -rf $(EBIN)/*.beam $(CURDIR)/erl_crash.dump 85 | 86 | # -------------------------------------------------------------------- 87 | # clean project 88 | # -------------------------------------------------------------------- 89 | distclean: clean 90 | rm -rf $(CURDIR)/logs $(PLT_FILE) 91 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | * Condor 2 | 3 | Condor is a minimal library for building scalable TCP servers in Erlang. 4 | 5 | ** Quick Overview 6 | 7 | #+BEGIN_SRC erlang 8 | -module(ping_server). 9 | -behaviour(condor_listener). 10 | 11 | %% condor_listener callbacks 12 | -export([init/1]). 13 | -export([handle_packet/2]). 14 | -export([handle_info/2]). 15 | -export([terminate/2]). 16 | 17 | init([]) -> 18 | {ok, undefined}. 19 | 20 | handle_packet(<<"stop">>, State) -> 21 | {send_and_stop, <<"ok">>, normal, State}; 22 | handle_packet(<<"ping">>, State) -> 23 | {send, <<"pong">>, State}. 24 | 25 | handle_info(_Msg, State) -> 26 | {ok, State}. 27 | 28 | terminate(_Reason, _State) -> 29 | ok. 30 | #+END_SRC 31 | 32 | ** Features 33 | 34 | - Reusable supervised connection acceptors 35 | - Neat packet frames and buffers 36 | 37 | ** API 38 | 39 | *** Start a Listener 40 | 41 | #+BEGIN_SRC 42 | condor:start_listener(Name, Opts, Module, InitialState) -> 43 | {ok, Pid} | {error, Reason} 44 | 45 | Name = atom() 46 | Opts = #{ 47 | ip => inet:ip_address(), 48 | port => inet:port_number(), 49 | max_acceptors => non_neg_integer(), 50 | len => 1 | 2, 51 | timeout => non_neg_integer() 52 | } 53 | Module = atom() 54 | InitialState = any() 55 | Pid = pid() 56 | Reason = any() 57 | #+END_SRC 58 | 59 | ~Opts~: 60 | 61 | - ~ip~: to what IP Condor should bind. 62 | - ~port~: on what port Condor should listen. 63 | - ~max_acceptors~: maximum number of socket acceptors, or in other words, 64 | maximum number of concurrent connections. 65 | - ~len~: length of the indicator of a packet's size. 66 | - ~timeout~: the time limit, in milliseconds, for a packet to be buffered. 67 | 68 | Default ~Opts~: 69 | 70 | #+BEGIN_SRC 71 | #{ 72 | ip => {127, 0, 0, 1}, 73 | len => 2, 74 | timeout => 10000, 75 | max_acceptors => 100 76 | } 77 | #+END_SRC 78 | 79 | *** Stop a Listener 80 | 81 | #+BEGIN_SRC 82 | condor:stop_listener(Name) -> ok 83 | 84 | Name = atom() 85 | #+END_SRC 86 | 87 | *** Condor Listener Callbacks 88 | 89 | Behaviour: ~condor_listener~ 90 | 91 | #+BEGIN_SRC 92 | init(State) -> Result 93 | 94 | handle_packet(Packet, State) -> Result 95 | 96 | handle_info(Msg, State) -> Result 97 | 98 | terminate(Reason, State) -> ok 99 | 100 | Result = {ok, State} 101 | | {send, Packet, State} 102 | | {stop, Reason, State} 103 | | {send_and_stop, Packet, Reason, State} 104 | 105 | Packet = binary() 106 | State = any() 107 | Reason = atom() 108 | #+END_SRC 109 | 110 | Events that invoke callbacks: 111 | 112 | #+BEGIN_SRC 113 | event callback module 114 | ----- --------------- 115 | new connection ---> Module:init/1 116 | new packet ---> Module:handle_packet/2 117 | receiving a message ---> Module:handle_info/2 118 | packet timeout ---> Module:handle_info/2 119 | connection termination ---> Module:terminate/2 120 | #+END_SRC 121 | 122 | Condor takes care of framing packets. Each packet frame consists of two 123 | segments: ~Len | Packet~. 124 | 125 | ~Len~ indicates the length of ~Packet~ in big-endian order. 126 | 127 | The length of ~Len~ is two bytes by default, though it can be modified with 128 | the ~len~ option. 129 | 130 | Condor also takes care of buffering. So, ~Module:handle_packet/2~ is called 131 | only when an entire packet is received. That is, when ~Packet~ is buffered 132 | according to the value of ~Len~. ~Len~ will then be stripped off, and only 133 | ~Packet~ will be passed to ~Module:handle_packet/2~. However, if ~Packet~ is 134 | not received completely in ~Timeout~ milliseconds (which would be specified 135 | in ~Opts~), ~Module:handle_info/2~ will be invoked with ~Msg~ being 136 | ~{timeout, Buffer :: binary()}~. 137 | 138 | A callback's ~Result~: 139 | 140 | - ~{send, Packet, State}~ sends ~Packet~ (in the frame: ~Len | Packet~). 141 | - ~{stop, Reason, State}~ terminates the connection. 142 | - ~{send_and_stop, Packet, Reason, State}~ sends ~Packet~ (in the frame: 143 | ~Len | Packet~), and then terminates the connection. 144 | 145 | ** License 146 | 147 | Apache License, Version 2.0 148 | -------------------------------------------------------------------------------- /ebin/condor.app: -------------------------------------------------------------------------------- 1 | %% -*- mode: erlang -*- 2 | 3 | {application, condor, 4 | [{description, ""}, 5 | {vsn, "0.3.1"}, 6 | {licenses, ["Apache 2.0"]}, 7 | {applications, 8 | [kernel, 9 | stdlib 10 | ]}, 11 | {modules, [ 12 | condor, 13 | condor_app, 14 | condor_sup, 15 | condor_packet, 16 | condor_listener, 17 | condor_listener_sup 18 | ]}, 19 | {mod, {condor_app, []}}, 20 | {maintainers, []}, 21 | {registered, []}, 22 | {links, []}, 23 | {env,[]} 24 | ]}. 25 | -------------------------------------------------------------------------------- /src/condor.erl: -------------------------------------------------------------------------------- 1 | -module(condor). 2 | 3 | %% ----------------------------------------------------------------------------- 4 | %% API 5 | %% ----------------------------------------------------------------------------- 6 | -export([start_listener/4]). 7 | -export([stop_listener/1]). 8 | 9 | -type opts() :: #{ 10 | ip => inet:ip_address(), 11 | port => inet:port_number(), 12 | len => 1 | 2, 13 | timeout => non_neg_integer(), 14 | max_acceptors => non_neg_integer() 15 | }. 16 | -export_type([opts/0]). 17 | 18 | -spec start_listener(atom(), opts(), module(), term()) -> 19 | {ok, pid()} | {error, term()}. 20 | start_listener(Name, Opts0, Mod, InitialModState) -> 21 | SupName = listener_sup_name(Name), 22 | Opts = maps:merge(default_opts(), Opts0), 23 | ok = check_opts(Opts), 24 | Res = condor_sup:start_listener_sup(SupName, Opts, Mod, InitialModState), 25 | start_acceptors(Res, SupName, Opts). 26 | 27 | -spec stop_listener(atom()) -> ok. 28 | stop_listener(Name) -> 29 | SupName = listener_sup_name(Name), 30 | condor_sup:stop_listener_sup(SupName). 31 | 32 | %% ----------------------------------------------------------------------------- 33 | %% internal 34 | %% ----------------------------------------------------------------------------- 35 | -spec default_opts() -> opts(). 36 | default_opts() -> 37 | #{ 38 | ip => {127, 0, 0, 1}, 39 | len => 2, 40 | timeout => 10000, 41 | max_acceptors => 100 42 | }. 43 | 44 | -spec check_opts(opts()) -> ok | no_return(). 45 | check_opts(#{len:=Len}) when Len =< 0; Len > 2 -> 46 | exit(badlen); 47 | check_opts(_) -> 48 | ok. 49 | 50 | -spec start_acceptors(Res, atom(), opts()) -> 51 | Res when Res :: {ok, pid()} 52 | | {error, term()}. 53 | start_acceptors({ok, _}=Res, SupName, #{max_acceptors:=Max}) -> 54 | start_acceptor_n(SupName, Max), 55 | Res; 56 | start_acceptors(Else, _, _) -> 57 | Else. 58 | 59 | -spec start_acceptor_n(atom(), integer()) -> ok. 60 | start_acceptor_n(_, 0) -> 61 | ok; 62 | start_acceptor_n(SupName, N) -> 63 | {ok, _} = condor_listener_sup:start_child(SupName), 64 | start_acceptor_n(SupName, N - 1). 65 | 66 | -spec listener_sup_name(atom()) -> atom(). 67 | listener_sup_name(Name) -> 68 | list_to_atom("condor_listener_sup_" ++ atom_to_list(Name)). 69 | -------------------------------------------------------------------------------- /src/condor_app.erl: -------------------------------------------------------------------------------- 1 | -module(condor_app). 2 | -behaviour(application). 3 | 4 | -export([start/2]). 5 | -export([stop/1]). 6 | 7 | start(_StartType, _StartArgs) -> 8 | condor_sup:start_link(). 9 | 10 | stop(_State) -> 11 | ok. 12 | -------------------------------------------------------------------------------- /src/condor_listener.erl: -------------------------------------------------------------------------------- 1 | -module(condor_listener). 2 | -behaviour(gen_server). 3 | 4 | %% ----------------------------------------------------------------------------- 5 | %% API 6 | %% ----------------------------------------------------------------------------- 7 | -export([start_link/4]). 8 | -export([accept/1]). 9 | -export([stop/1]). 10 | 11 | %% ----------------------------------------------------------------------------- 12 | %% gen_server callbacks 13 | %% ----------------------------------------------------------------------------- 14 | -export([init/1]). 15 | -export([handle_call/3]). 16 | -export([handle_cast/2]). 17 | -export([handle_info/2]). 18 | -export([terminate/2]). 19 | -export([code_change/3]). 20 | 21 | %% ----------------------------------------------------------------------------- 22 | %% condor_listener behaviour 23 | %% ----------------------------------------------------------------------------- 24 | -type sock() :: inet:socket(). 25 | -type packet() :: binary(). 26 | -type msg() :: {timeout, binary()} | term(). 27 | -type state() :: term(). 28 | -type terminate_reason() :: term(). 29 | 30 | -type result() :: {ok, state()} 31 | | {send, packet(), state()} 32 | | {stop, terminate_reason(), state()} 33 | | {send_and_stop, packet(), terminate_reason(), state()}. 34 | 35 | -callback init(state()) -> 36 | result(). 37 | 38 | -callback handle_packet(packet(), state()) -> 39 | result(). 40 | 41 | -callback handle_info(msg(), state()) -> 42 | result(). 43 | 44 | -callback terminate(terminate_reason(), state()) -> 45 | ok. 46 | 47 | %% ----------------------------------------------------------------------------- 48 | 49 | -record(state, { 50 | mod :: module(), 51 | mod_init_state :: term(), 52 | mod_state :: term(), 53 | lsock :: undefined | sock(), 54 | sock :: undefined | sock(), 55 | len = 16 :: 8 | 16, 56 | buffer = <<>> :: binary(), 57 | timeout = 10000 :: integer(), 58 | timer_ref :: undefined | reference() 59 | }). 60 | 61 | %% ----------------------------------------------------------------------------- 62 | %% API 63 | %% ----------------------------------------------------------------------------- 64 | start_link(LSock, Mod, ModInitState, Opts) -> 65 | gen_server:start_link(?MODULE, [LSock, Mod, ModInitState, Opts], []). 66 | 67 | accept(Pid) -> 68 | {ok, _} = timer:apply_after(0, gen_server, cast, [Pid, accept]), 69 | ok. 70 | 71 | stop(Pid) -> 72 | gen_server:cast(Pid, stop). 73 | 74 | %% ----------------------------------------------------------------------------- 75 | %% gen_server callbacks 76 | %% ----------------------------------------------------------------------------- 77 | init([LSock, Mod, ModInitState, #{len:=Len, timeout:=Timeout}]) -> 78 | process_flag(trap_exit, true), 79 | accept(self()), 80 | State = #state{ 81 | mod = Mod, 82 | mod_init_state = ModInitState, 83 | lsock = LSock, 84 | len = Len * 8, 85 | timeout = Timeout 86 | }, 87 | {ok, State}. 88 | 89 | handle_call(_Msg, _From, State) -> 90 | {noreply, State}. 91 | 92 | handle_cast(accept, 93 | #state{mod=Mod, mod_init_state=ModInitState, lsock=LSock}=State) -> 94 | %% init/1 callback 95 | catch gen_tcp:shutdown(State#state.sock, read_write), 96 | {ok, Sock} = gen_tcp:accept(LSock), 97 | NewState = handle_callback(Mod, init, [ModInitState], State#state{sock=Sock}), 98 | {noreply, NewState}; 99 | handle_cast(stop, State) -> 100 | {stop, normal, State}. 101 | 102 | handle_info({tcp, Sock, Data}, 103 | #state{len=Len, buffer=Buf, 104 | sock=Sock, mod=Mod, mod_state=ModState}=State0) -> 105 | %% set a timeout for receiving the packet, if no timeout is set already 106 | State = maybe_set_timeout(State0), 107 | 108 | NewBuf = <>, 109 | NewState = 110 | case condor_packet:decode(Len, NewBuf) of 111 | {ok, Packet, RestBuf} -> 112 | State1 = cancel_timeout(State), 113 | %% handle_packet/3 callback 114 | handle_callback( 115 | Mod, 116 | handle_packet, 117 | [Packet, ModState], 118 | State1#state{buffer = RestBuf} 119 | ); 120 | {more, _} -> 121 | State#state{buffer = NewBuf} 122 | end, 123 | ok = inet:setopts(Sock, [{active, once}]), 124 | {noreply, NewState}; 125 | handle_info({tcp_error, Reason, Sock}, 126 | #state{sock=Sock, mod=Mod, mod_state=ModState}=State) -> 127 | %% terminate/2 callback and reuse the process 128 | accept(self()), 129 | NewState = handle_callback(Mod, terminate, [Reason, ModState], State), 130 | {noreply, NewState}; 131 | handle_info({tcp_closed, Sock}, 132 | #state{sock=Sock, mod=Mod, mod_state=ModState}=State) -> 133 | %% terminate/2 callback and reuse the process 134 | accept(self()), 135 | NewState = handle_callback(Mod, terminate, [tcp_closed, ModState], State), 136 | {noreply, NewState}; 137 | handle_info({timeout, _, packet_timeout}, 138 | #state{mod=Mod, mod_state=ModState, buffer=Buf}=State) -> 139 | NewState = 140 | handle_callback(Mod, handle_info, [{timeout, Buf}, ModState], State), 141 | {noreply, NewState#state{buffer = <<>>, timer_ref = undefined}}; 142 | handle_info(Msg, #state{mod=Mod, mod_state=ModState}=State) -> 143 | %% handle_info/2 callback 144 | NewState = handle_callback(Mod, handle_info, [Msg, ModState], State), 145 | {noreply, NewState}. 146 | 147 | terminate(_Reason, #state{lsock=LSock}) -> 148 | catch gen_tcp:shutdown(LSock, read_write), 149 | ok. 150 | 151 | code_change(_OldVsn, State, _Extra) -> 152 | {ok, State}. 153 | 154 | %% ----------------------------------------------------------------------------- 155 | %% internal 156 | %% ----------------------------------------------------------------------------- 157 | handle_callback(M, F, A, State) -> 158 | case (catch apply(M, F, A)) of 159 | {'EXIT', Trace} -> 160 | error_logger:error_msg("~p~n", [Trace]), 161 | State; 162 | ok -> 163 | State#state{mod_state = undefined, buffer = <<>>}; 164 | {ok, ModState} -> 165 | State#state{mod_state = ModState}; 166 | {send, Data, ModState} -> 167 | send(Data, State), 168 | State#state{mod_state = ModState}; 169 | {stop, Reason, ModState} -> 170 | %% terminate/2 callback and reuse the process 171 | accept(self()), 172 | handle_callback(M, terminate, [Reason, ModState], State); 173 | {send_and_stop, Data, Reason, ModState} -> 174 | %% send data, then terminate/2 callback and reuse the process 175 | send(Data, State), 176 | accept(self()), 177 | handle_callback(M, terminate, [Reason, ModState], State); 178 | Else -> 179 | error_logger:error_msg("** Bad return value == ~p~n", [Else]), 180 | State 181 | end. 182 | 183 | send(Data0, #state{len=L, sock=Sock}) -> 184 | Data = condor_packet:encode(L, Data0), 185 | gen_tcp:send(Sock, Data). 186 | 187 | maybe_set_timeout(#state{timer_ref=undefined, timeout=Timeout}=State) -> 188 | TimerRef = erlang:start_timer(Timeout, self(), packet_timeout), 189 | State#state{timer_ref = TimerRef}; 190 | maybe_set_timeout(State) -> 191 | State. 192 | 193 | cancel_timeout(#state{timer_ref=TimerRef}=State) -> 194 | catch erlang:cancel_timer(TimerRef), 195 | State#state{timer_ref = undefined}. 196 | -------------------------------------------------------------------------------- /src/condor_listener_sup.erl: -------------------------------------------------------------------------------- 1 | -module(condor_listener_sup). 2 | -behaviour(supervisor). 3 | 4 | -export([start_link/4]). 5 | -export([start_child/1]). 6 | -export([kill_children/1]). 7 | 8 | -export([init/1]). 9 | 10 | start_link(SupName, Opts, Mod, ModState) -> 11 | #{port := Port} = Opts, 12 | supervisor:start_link( 13 | {local, SupName}, ?MODULE, [Port, Opts, Mod, ModState] 14 | ). 15 | 16 | start_child(SupName) -> 17 | supervisor:start_child(SupName, []). 18 | 19 | kill_children(SupName) -> 20 | [exit(Pid, kill) || 21 | {_, Pid, _, _} <- supervisor:which_children(SupName)], 22 | ok. 23 | 24 | %% ----------------------------------------------------------------------------- 25 | %% supervisor callback 26 | %% ----------------------------------------------------------------------------- 27 | init([Port, Opts, Mod, ModState]) -> 28 | #{ip := IP} = Opts, 29 | {ok, LSock} = gen_tcp:listen(Port, [{ip, IP}, {active, once}, binary]), 30 | {ok, { 31 | {simple_one_for_one, 60, 120}, 32 | [{condor_listener, {condor_listener, start_link, [LSock, Mod, ModState, Opts]}, 33 | permanent, 1000, worker, [condor_listener]}] 34 | }}. 35 | -------------------------------------------------------------------------------- /src/condor_packet.erl: -------------------------------------------------------------------------------- 1 | -module(condor_packet). 2 | 3 | -export([encode/2]). 4 | -export([decode/2]). 5 | 6 | -spec encode(non_neg_integer(), iolist()) -> binary(). 7 | encode(L, Data) -> 8 | Bin = iolist_to_binary(Data), 9 | Len = byte_size(Bin), 10 | <>. 11 | 12 | -spec decode(non_neg_integer(), binary()) -> 13 | {ok, binary(), binary()} | 14 | {more, non_neg_integer()} | 15 | {error, term()}. 16 | decode(Len, Bin) -> 17 | erlang:decode_packet(trunc(Len / 8), Bin, []). 18 | -------------------------------------------------------------------------------- /src/condor_sup.erl: -------------------------------------------------------------------------------- 1 | -module(condor_sup). 2 | -behaviour(supervisor). 3 | 4 | -export([start_link/0]). 5 | -export([start_listener_sup/4]). 6 | -export([stop_listener_sup/1]). 7 | 8 | -export([init/1]). 9 | 10 | start_link() -> 11 | supervisor:start_link({local, ?MODULE}, ?MODULE, []). 12 | 13 | start_listener_sup(SupName, Opts, Mod, ModState) -> 14 | supervisor:start_child(?MODULE, [SupName, Opts, Mod, ModState]). 15 | 16 | stop_listener_sup(SupName) -> 17 | condor_listener_sup:kill_children(SupName), 18 | exit(whereis(SupName), kill), 19 | ok. 20 | 21 | %% ----------------------------------------------------------------------------- 22 | %% supervisor callback 23 | %% ----------------------------------------------------------------------------- 24 | init([]) -> 25 | {ok, { 26 | {simple_one_for_one, 60, 120}, 27 | [{condor_listener_sup, {condor_listener_sup, start_link, []}, 28 | temporary, 1000, supervisor, [condor_listener_sup]}] 29 | }}. 30 | -------------------------------------------------------------------------------- /test/condor_SUITE.erl: -------------------------------------------------------------------------------- 1 | -module(condor_SUITE). 2 | -behaviour(condor_listener). 3 | 4 | -export([init_per_suite/1]). 5 | -export([end_per_suite/1]). 6 | -export([all/0]). 7 | -export([echo_test/1]). 8 | -export([timeout_test/1]). 9 | 10 | -include_lib("common_test/include/ct.hrl"). 11 | 12 | init_per_suite(Config) -> 13 | ok = application:start(condor), 14 | Port = rand_port(), 15 | Opts = #{port => Port, max_acceptors => 5, len => 2}, 16 | {ok, _} = condor:start_listener(echo_server, Opts, ?MODULE, []), 17 | [{port, Port} | Config]. 18 | 19 | end_per_suite(_Config) -> 20 | ok = condor:stop_listener(echo_server), 21 | ok. 22 | 23 | all() -> 24 | [ 25 | condor_packet, 26 | echo_test, 27 | timeout_test 28 | ]. 29 | 30 | condor_packet(_) -> 31 | <<1, "a">> = condor_packet:encode(8, <<"a">>), 32 | <<0, 3, "aaa">> = condor_packet:encode(16, <<"aaa">>), 33 | {ok, <<"a">>, <<"aa">>} = condor_packet:decode(16, <<0, 1, "aaa">>), 34 | {ok, <<"aaa">>, <<>>} = condor_packet:decode(16, <<0, 3, "aaa">>), 35 | 36 | Data = binary:copy(<<"A">>, 1024), 37 | Packet = condor_packet:encode(16, Data), 38 | {ok, Data, <<>>} = condor_packet:decode(16, Packet), 39 | ok. 40 | 41 | echo_test(Config) -> 42 | Port = ?config(port, Config), 43 | 44 | {ok, Sock0} = gen_tcp:connect("localhost", Port, [binary]), 45 | Pkt0 = condor_packet:encode(16, binary:copy(<<"A">>, 1024)), 46 | ok = gen_tcp:send(Sock0, Pkt0), 47 | Pkt0 = loop_recv(Sock0), 48 | 49 | {ok, Sock1} = gen_tcp:connect("localhost", Port, [binary]), 50 | Pkt1 = condor_packet:encode(16, binary:copy(<<"ABC">>, 10240)), 51 | ok = gen_tcp:send(Sock1, Pkt1), 52 | Pkt1 = loop_recv(Sock1), 53 | 54 | {ok, Sock2} = gen_tcp:connect("localhost", Port, [binary]), 55 | Pkt2 = condor_packet:encode(16, <<"send_and_stop">>), 56 | ok = gen_tcp:send(Sock2, Pkt2), 57 | Pkt2 = loop_recv(Sock2), 58 | receive 59 | {tcp_closed, Sock2} -> 60 | ok 61 | after 10 -> 62 | exit(tcp_not_closed) 63 | end, 64 | 65 | ok = gen_tcp:close(Sock0), 66 | ok = gen_tcp:close(Sock1), 67 | ok. 68 | 69 | timeout_test(_Config) -> 70 | ok = application:ensure_started(condor), 71 | Port = rand_port(), 72 | Opts = #{port => Port, len => 2, timeout => 20, max_acceptors => 5}, 73 | {ok, _} = condor:start_listener(timeout_server, Opts, ?MODULE, []), 74 | 75 | %% let timeout trigger by not sending the entire packet 76 | {ok, Sock0} = gen_tcp:connect("localhost", Port, [binary]), 77 | <> = condor_packet:encode(16, binary:copy(<<"A">>, 128)), 78 | ok = gen_tcp:send(Sock0, Pkt0), 79 | receive 80 | {tcp, Sock0, <<_:16, Pkt0/binary>>} -> 81 | ok 82 | after 30 -> 83 | exit(not_received) 84 | end, 85 | 86 | %% send two chunks of packet, and let the timeout trigger 87 | {ok, Sock1} = gen_tcp:connect("localhost", Port, [binary]), 88 | <> = 89 | condor_packet:encode(16, binary:copy(<<"XYZ">>, 256)), 90 | ok = gen_tcp:send(Sock1, Pkt1), 91 | ok = timer:sleep(10), 92 | ok = gen_tcp:send(Sock1, Pkt2), 93 | receive 94 | {tcp, Sock1, <<_:16, Pkt1:64/binary, Pkt2:64/binary>>} -> 95 | ok 96 | after 30 -> 97 | exit(not_received) 98 | end, 99 | 100 | %% send the entire packet in three chunks, and do not trigger timeout 101 | {ok, Sock2} = gen_tcp:connect("localhost", Port, [binary]), 102 | Pkt3 = condor_packet:encode(16, binary:copy(<<"XYZ">>, 256)), 103 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 0, 64)), 104 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 64, 64)), 105 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 128, byte_size(Pkt3) - 128)), 106 | receive 107 | {tcp, Sock2, Pkt3} -> 108 | ok 109 | after 30 -> 110 | exit(not_received) 111 | end, 112 | 113 | %% send the entire packet in three chunks with a bit of pause in between. 114 | %% this will trigger timeout, because the packet won't be sent completely 115 | %% in 20 milliseconds 116 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 0, 64)), 117 | ok = timer:sleep(10), 118 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 64, 64)), 119 | ok = timer:sleep(10), 120 | ok = gen_tcp:send(Sock2, binary:part(Pkt3, 128, byte_size(Pkt3) - 128)), 121 | receive 122 | {tcp, Sock2, Pkt3} -> 123 | exit(should_not_receive_full_packet); 124 | {tcp, Sock2, _Buf} -> 125 | ok 126 | after 30 -> 127 | exit(not_received) 128 | end, 129 | 130 | ok = gen_tcp:close(Sock0), 131 | ok = gen_tcp:close(Sock1), 132 | ok = gen_tcp:close(Sock2), 133 | ok = condor:stop_listener(timeout_server), 134 | ok. 135 | 136 | %% ----------------------------------------------------------------------------- 137 | %% internal 138 | %% ----------------------------------------------------------------------------- 139 | rand_port() -> 140 | erlang:system_time() rem 10000. 141 | 142 | loop_recv(Sock) -> 143 | loop_recv(Sock, <<>>). 144 | 145 | loop_recv(Sock, Buffer) -> 146 | receive 147 | {tcp, Sock, Pkt} -> 148 | loop_recv(Sock, <>) 149 | after 10 -> 150 | Buffer 151 | end. 152 | 153 | %% ----------------------------------------------------------------------------- 154 | %% condor_listener callbacks 155 | %% ----------------------------------------------------------------------------- 156 | init([]) -> 157 | {ok, undefined}. 158 | 159 | handle_packet(<<"send_and_stop">> = Data, State) -> 160 | {send_and_stop, Data, normal, State}; 161 | handle_packet(Echo, State) -> 162 | {send, Echo, State}. 163 | 164 | handle_info({timeout, Buf}, State) -> 165 | {send, Buf, State}; 166 | handle_info(_MSg, State) -> 167 | {ok, State}. 168 | 169 | terminate(_Reason, _State) -> 170 | ok. 171 | --------------------------------------------------------------------------------