So many changes. Broken.
[invirt/third/libt4.git] / include / rpc / rpc.h
1 #ifndef rpc_h
2 #define rpc_h
3
4 #include "include/types.h"
5
6 #include "include/rpc/rpc_protocol.h"
7 #include "include/rpc/thread_pool.h"
8 #include "include/rpc/marshall.h"
9 #include "include/rpc/marshall_wrap.h"
10 #include "include/rpc/connection.h"
11 #include "include/debug.h"
12
13 using std::chrono::milliseconds;
14
15 namespace rpc {
16     static constexpr auto to_max = milliseconds(12000);
17     static constexpr auto to_min = milliseconds(100);
18 }
19
20 template<class P, class R, class ...Args>
21 struct is_valid_call : false_type {};
22
23 template<class S, class R, class ...Args>
24 struct is_valid_call<S(R &, Args...), R, Args...> : true_type {};
25
26 template<class P, class F>
27 struct is_valid_registration : false_type {};
28
29 template<class S, class R, class ...Args>
30 struct is_valid_registration<
31     S(R &, typename std::decay<Args>::type...),
32     S(R &, Args...)> : true_type {};
33
34 template<class P, class C, class S, class R, class ...Args>
35 struct is_valid_registration<
36     P,
37     S(C::*)(R &, Args...)> : is_valid_registration<P, S(R &, Args...)> {};
38
39 // rpc client endpoint.
40 // manages a xid space per destination socket
41 // threaded: multiple threads can be sending RPCs,
42 class rpcc : private connection_delegate {
43     private:
44         using proc_id_t = rpc_protocol::proc_id_t;
45         using nonce_t = rpc_protocol::nonce_t;
46         using xid_t = rpc_protocol::xid_t;
47
48         // manages per rpc info
49         struct caller {
50             caller(xid_t _xid, string *_rep) : xid(_xid), rep(_rep) {}
51
52             int xid;
53             string *rep;
54             int intret;
55             bool done = false;
56             std::mutex m;
57             cond c;
58         };
59
60         void get_latest_connection(shared_ptr<connection> & ch);
61         void update_xid_rep(xid_t xid, lock & m_lock);
62
63
64         sockaddr_in dst_;
65         nonce_t clt_nonce_;
66         nonce_t srv_nonce_ = 0;
67         bool bind_done_ = false;
68         int lossytest_ = 0;
69         bool reachable_ = true;
70
71         shared_ptr<connection> chan_;
72
73         std::mutex m_; // protect insert/delete to calls[]
74         std::mutex chan_m_;
75         std::mutex bind_m_; // protect bind operations
76
77         bool destroy_wait_ = false;
78         cond destroy_wait_c_;
79
80         std::map<int, caller *> calls_;
81
82         // xid starts with 1 and latest received reply starts with 0
83         xid_t xid_ = 1;
84         std::list<xid_t> xid_rep_window_ = {0};
85
86         struct request {
87             void clear() { buf.clear(); xid = -1; }
88             bool isvalid() { return xid != -1; }
89             string buf;
90             xid_t xid = -1;
91         };
92         request dup_req_;
93         int xid_rep_done_ = -1;
94
95         int call_marshalled(const rpc_protocol::proc_t & proc, milliseconds to, string & rep, const marshall & req);
96
97         bool got_pdu(const shared_ptr<connection> & c, const string & b);
98
99     public:
100
101         rpcc(const string & d);
102         ~rpcc();
103
104         int bind(milliseconds to = rpc::to_max);
105
106         // Manages a cache of RPC connections.  Usage:
107         //     if (auto cl = rpcc::bind_cached(dst))
108         //         ret = cl->call(...);
109         // where the string dst has the form "host:port".  Because bind_cached()
110         // may block, callers should probably not hold mutexes.
111         static shared_ptr<rpcc> bind_cached(const string & destination);
112         static void unbind_cached(const string & destination);
113
114         void set_reachable(bool r) { reachable_ = r; }
115
116         void cancel(lock & m_lock);
117
118         template<class P, class R, typename ...Args>
119         inline int call(const rpc_protocol::proc_checked_t<P> & proc, R & r, const Args & ... args) {
120             return call_timeout(proc, rpc::to_max, r, args...);
121         }
122
123         template<class P, class R, typename ...Args>
124         inline int call_timeout(const rpc_protocol::proc_checked_t<P> & proc, milliseconds to, R & r, const Args & ... args) {
125             static_assert(is_valid_call<P, R, Args...>::value, "RPC called with incorrect argument types");
126             string rep;
127             int intret = call_marshalled(proc, to, rep, marshall(args...));
128             if (intret >= 0) {
129                 rpc_protocol::reply_header rh;
130                 // guaranteed by static type checking?
131                 VERIFY(unmarshall::datagram(rep, rh, r).okdone());
132             }
133             return intret;
134         }
135 };
136
137 // rpc server endpoint.
138 class rpcs : private connection_delegate {
139     private:
140         using proc_id_t = rpc_protocol::proc_id_t;
141         using nonce_t = rpc_protocol::nonce_t;
142         using xid_t = rpc_protocol::xid_t;
143
144         typedef enum {
145             NEW,  // new RPC, not a duplicate
146             INPROGRESS, // duplicate of an RPC we're still processing
147             DONE, // duplicate of an RPC we already replied to (have reply)
148             FORGOTTEN,  // duplicate of an old RPC whose reply we've forgotten
149         } rpcstate_t;
150
151         // state about an in-progress or completed RPC, for at-most-once.
152         // if cb_present is true, then the RPC is complete and a reply
153         // has been sent; in that case buf points to a copy of the reply,
154         // and sz holds the size of the reply.
155         struct reply_t {
156             reply_t (xid_t _xid) : xid(_xid), cb_present(false) {}
157             reply_t (xid_t _xid, const string & _buf) : xid(_xid), cb_present(true), buf(_buf) {}
158             xid_t xid;
159             bool cb_present; // whether the reply buffer is valid
160             string buf;      // the reply buffer
161         };
162
163         in_port_t port_;
164         nonce_t nonce_;
165
166         // provide at most once semantics by maintaining a window of replies
167         // per client that that client hasn't acknowledged receiving yet.
168         // indexed by client nonce.
169         std::map<nonce_t, std::list<reply_t>> reply_window_;
170
171         void add_reply(nonce_t clt_nonce, xid_t xid, const string & b);
172
173         rpcstate_t check_duplicate_and_update(nonce_t clt_nonce, xid_t xid,
174                 xid_t rep_xid, string & b);
175
176         // latest connection to the client
177         std::map<nonce_t, shared_ptr<connection>> conns_;
178
179         bool reachable_ = true;
180
181         // map proc # to function
182         std::map<proc_id_t, handler *> procs_;
183
184         std::mutex procs_m_; // protect insert/delete to procs[]
185         std::mutex reply_window_m_; // protect reply window et al
186         std::mutex conns_m_; // protect conns_
187
188         void dispatch(shared_ptr<connection> c, const string & buf);
189
190         unique_ptr<thread_pool> dispatchpool_{new thread_pool(6)};
191         unique_ptr<connection_listener> listener_;
192
193         // RPC handler for clients binding
194         rpc_protocol::status rpcbind(nonce_t & r);
195
196         bool got_pdu(const shared_ptr<connection> & c, const string & b);
197
198     public:
199
200         rpcs(in_port_t port);
201         ~rpcs();
202
203         void set_reachable(bool r) { reachable_ = r; }
204
205         template<class P, class F, class C=void>
206         inline void reg(const rpc_protocol::proc_checked_t<P> & proc, F f, C *c=nullptr) {
207             static_assert(is_valid_registration<P, F>::value, "RPC handler registered with incorrect argument types");
208             struct ReturnOnFailure {
209                 static inline int unmarshall_args_failure() {
210                     return rpc_protocol::unmarshall_args_failure;
211                 }
212             };
213             lock pl(procs_m_);
214             VERIFY(procs_.count(proc.id) == 0);
215             procs_[proc.id] = marshalled_func<F, ReturnOnFailure>::wrap(f, c);
216             VERIFY(procs_.count(proc.id) >= 1);
217         }
218
219         void start();
220 };
221
222 #endif