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