r1519@opsdev009 (orig r80499): mcslee | 2008-01-30 17:49:16 -0800
[amiethrift.git] / lib / erl / src / server / tErlServer.erl
blob10ac2b2536c4578275987081c298ed24570851ab
1 %%% Copyright (c) 2007- Facebook
2 %%% Distributed under the Thrift Software License
3 %%%
4 %%% See accompanying file LICENSE or visit the Thrift site at:
5 %%% http://developers.facebook.com/thrift/
7 -module(tErlServer).
9 -include("oop.hrl").
11 -include("thrift.hrl").
12 -include("transport/tTransportException.hrl").
13 -include("server/tErlServer.hrl").
15 -behavior(oop).
17 -export([attr/4, super/0, inspect/1]).
19 -export([new/6, new/5, new/4, effectful_serve/1, effectful_new_acceptor/1]).
21 %%%
22 %%% define attributes
23 %%% 'super' is required unless ?MODULE is a base class
24 %%%
26 ?DEFINE_ATTR(super);
27 ?DEFINE_ATTR(acceptor);
28 ?DEFINE_ATTR(listenSocket);
29 ?DEFINE_ATTR(port).
31 %%%
32 %%% behavior callbacks
33 %%%
35 %%% super() -> SuperModule = atom()
36 %%% | none
38 super() ->
39 tServer.
41 %%% inspect(This) -> string()
43 inspect(This) ->
44 ?FORMAT_ATTR(acceptor) ++ ", " ++
45 ?FORMAT_ATTR(listenSocket) ++ ", " ++
46 ?FORMAT_ATTR(port).
48 %%%
49 %%% class methods
50 %%%
52 new(Port, Handler, Processor, ServerTransport, TransportFactory, ProtocolFactory) ->
53 Super = (super()):new(Handler, Processor, ServerTransport, TransportFactory, ProtocolFactory),
54 #?MODULE{super=Super, port=Port, listenSocket=nil, acceptor=nil}.
56 new(Port, Handler, Processor, ServerTransport) ->
57 new(Port, Handler, Processor, ServerTransport, nil, nil).
59 new(Port, Handler, Processor, ServerTransport, TransportFactory) ->
60 new(Port, Handler, Processor, ServerTransport, TransportFactory, nil).
62 % listenSocket, acceptor, port
64 effectful_serve(This) ->
65 Port = oop:get(This, port),
67 Options = [binary, {packet, 0}, {active, false}],
69 %% listen
70 case gen_tcp:listen(Port, Options) of
71 {ok, ListenSocket} ->
72 ?INFO("thrift server listening on port ~p", [Port]),
74 This1 = oop:set(This, listenSocket, ListenSocket),
76 %% spawn acceptor
77 {_Acceptor, This2} = effectful_new_acceptor(This1),
79 {ok, This2};
81 {error, eaddrinuse} ->
82 ?ERROR("thrift couldn't bind port ~p, address in use", [Port]),
83 {{error, eaddrinuse}, This} %% state before the accept
84 end.
86 effectful_new_acceptor(This) ->
87 ListenSocket = oop:get(This, listenSocket),
88 Processor = oop:get(This, processor), %% cpiro: generated processor, not the "actual" processor
89 Handler = oop:get(This, handler),
91 TF = oop:get(This, transportFactory),
92 PF = oop:get(This, protocolFactory),
94 tErlAcceptor = oop:get(This, serverTransport), %% cpiro: only supported ServerTransport
96 ServerPid = self(),
97 Acceptor = oop:start_new(tErlAcceptor, [ServerPid, TF, PF]),
98 ?C3(Acceptor, accept, ListenSocket, Processor, Handler),
100 This1 = oop:set(This, acceptor, Acceptor),
102 {Acceptor, This1}.