de3367566cfab109ecc2e5a35b104debe5f5b60d
[invirt/third/libt4.git] / rpc / rpc.cc
1 //
2 // The rpcc class handles client-side RPC.  Each rpcc is bound to a single RPC
3 // server.  The jobs of rpcc include maintaining a connection to server, sending
4 // RPC requests and waiting for responses, retransmissions, at-most-once delivery
5 // etc.
6 //
7 // The rpcs class handles the server side of RPC.  Each rpcs handles multiple
8 // connections from different rpcc objects.  The jobs of rpcs include accepting
9 // connections, dispatching requests to registered RPC handlers, at-most-once
10 // delivery etc.
11 //
12 // Both rpcc and rpcs use the connection class as an abstraction for the
13 // underlying communication channel.  To send an RPC request/reply, one calls
14 // connection::send() which blocks until data is sent or the connection has
15 // failed (thus the caller can free the buffer when send() returns).  When a
16 // request/reply is received, connection makes a callback into the corresponding
17 // rpcc or rpcs (see rpcc::got_pdu() and rpcs::got_pdu()).
18 //
19 // Thread organization:
20 // rpcc uses application threads to send RPC requests and blocks to receive the
21 // reply or error. All connections use a single PollMgr object to perform async
22 // socket IO.  PollMgr creates a single thread to examine the readiness of socket
23 // file descriptors and informs the corresponding connection whenever a socket is
24 // ready to be read or written.  (We use asynchronous socket IO to reduce the
25 // number of threads needed to manage these connections; without async IO, at
26 // least one thread is needed per connection to read data without blocking other
27 // activities.)  Each rpcs object creates one thread for listening on the server
28 // port and a pool of threads for executing RPC requests.  The thread pool allows
29 // us to control the number of threads spawned at the server (spawning one thread
30 // per request will hurt when the server faces thousands of requests).
31 //
32 // In order to delete a connection object, we must maintain a reference count.
33 // For rpcc, multiple client threads might be invoking the rpcc::call() functions
34 // and thus holding multiple references to the underlying connection object. For
35 // rpcs, multiple dispatch threads might be holding references to the same
36 // connection object.  A connection object is deleted only when the underlying
37 // connection is dead and the reference count reaches zero.
38 //
39 // This version of the RPC library explicitly joins exited threads to make sure
40 // no outstanding references exist before deleting objects.
41 //
42 // To delete a rpcc object safely, the users of the library must ensure that
43 // there are no outstanding calls on the rpcc object.
44 //
45 // To delete a rpcs object safely, we do the following in sequence: 1. stop
46 // accepting new incoming connections. 2. close existing active connections.  3.
47 // delete the dispatch thread pool which involves waiting for current active RPC
48 // handlers to finish.  It is interesting how a thread pool can be deleted
49 // without using thread cancellation. The trick is to inject x "poison pills" for
50 // a thread pool of x threads. Upon getting a poison pill instead of a normal
51 // task, a worker thread will exit (and thread pool destructor waits to join all
52 // x exited worker threads).
53 //
54
55 #include "rpc.h"
56
57 #include <arpa/inet.h>
58 #include <netinet/tcp.h>
59 #include <netdb.h>
60 #include <unistd.h>
61 #include <string.h>
62
63 using std::list;
64 using namespace std::chrono;
65
66 inline void set_rand_seed() {
67     auto now = time_point_cast<nanoseconds>(steady_clock::now());
68     srandom((uint32_t)now.time_since_epoch().count()^(uint32_t)getpid());
69 }
70
71 static sockaddr_in make_sockaddr(const string & hostandport);
72
73 rpcc::rpcc(const string & d) : dst_(make_sockaddr(d))
74 {
75     set_rand_seed();
76     clt_nonce_ = (nonce_t)random();
77
78     char *loss_env = getenv("RPC_LOSSY");
79     if (loss_env)
80         lossytest_ = atoi(loss_env);
81
82     IF_LEVEL(2) LOG << "cltn_nonce is " << clt_nonce_ << " lossy " << lossytest_;
83 }
84
85 // IMPORTANT: destruction should happen only when no external threads
86 // are blocked inside rpcc or will use rpcc in the future
87 rpcc::~rpcc() {
88     cancel();
89     IF_LEVEL(2) LOG << "delete nonce " << clt_nonce_ << " chan " << (chan_?(int)chan_->fd:-1);
90     chan_.reset();
91     VERIFY(calls_.size() == 0);
92 }
93
94 int rpcc::bind(milliseconds to) {
95     nonce_t r = 0;
96     rpc_protocol::status ret = call_timeout(rpc_protocol::bind, to, r);
97     if (ret == 0) {
98         lock ml(m_);
99         bind_done_ = true;
100         srv_nonce_ = r;
101     } else {
102         IF_LEVEL(2) LOG << "bind " << inet_ntoa(dst_.sin_addr) << " failed " << ret;
103     }
104     return ret;
105 }
106
107 // Cancel all outstanding calls
108 void rpcc::cancel(void) {
109     lock ml(m_);
110     if (calls_.size()) {
111         LOG << "force callers to fail";
112         for (auto & p : calls_) {
113             caller *ca = p.second;
114
115             IF_LEVEL(2) LOG << "force caller to fail";
116
117             lock cl(ca->m);
118             ca->done = true;
119             ca->intret = rpc_protocol::cancel_failure;
120             ca->c.notify_one();
121         }
122
123         destroy_wait_ = true;
124         while (calls_.size () > 0)
125             destroy_wait_c_.wait(ml);
126
127         LOG << "done";
128     }
129 }
130
131 int rpcc::call1(proc_id_t proc, milliseconds to, string & rep, marshall & req) {
132
133     caller ca(0, &rep);
134     xid_t xid_rep;
135     {
136         lock ml(m_);
137
138         if ((proc != rpc_protocol::bind.id && !bind_done_) || (proc == rpc_protocol::bind.id && bind_done_)) {
139             IF_LEVEL(1) LOG << "rpcc has not been bound to dst or binding twice";
140             return rpc_protocol::bind_failure;
141         }
142
143         if (destroy_wait_)
144             return rpc_protocol::cancel_failure;
145
146         ca.xid = xid_++;
147         calls_[ca.xid] = &ca;
148
149         req.write_header(rpc_protocol::request_header{
150                 ca.xid, proc, clt_nonce_, srv_nonce_, xid_rep_window_.front()
151                 });
152         xid_rep = xid_rep_window_.front();
153     }
154
155     milliseconds curr_to = rpc::to_min;
156     auto finaldeadline = steady_clock::now() + to;
157
158     bool transmit = true;
159     shared_ptr<connection> ch;
160
161     while (1) {
162         if (transmit) {
163             get_latest_connection(ch);
164             if (ch) {
165                 if (reachable_) {
166                     request forgot;
167                     {
168                         lock ml(m_);
169                         if (dup_req_.isvalid() && xid_rep_done_ > dup_req_.xid) {
170                             forgot = dup_req_;
171                             dup_req_.clear();
172                         }
173                     }
174                     if (forgot.isvalid())
175                         ch->send(forgot.buf);
176                     ch->send(req);
177                 }
178                 else IF_LEVEL(1) LOG << "not reachable";
179                 IF_LEVEL(2) LOG << clt_nonce_ << " just sent req proc " << std::hex << proc
180                                 << " xid " << std::dec << ca.xid << " clt_nonce " << clt_nonce_;
181             }
182             transmit = false; // only send once on a given channel
183         }
184
185         auto nextdeadline = std::min(steady_clock::now() + curr_to, finaldeadline);
186         curr_to *= 2;
187
188         {
189             lock cal(ca.m);
190             while (!ca.done) {
191                 IF_LEVEL(2) LOG << "wait";
192                 if (ca.c.wait_until(cal, nextdeadline) == std::cv_status::timeout) {
193                     IF_LEVEL(2) LOG << "timeout";
194                     break;
195                 }
196             }
197             if (ca.done) {
198                 IF_LEVEL(2) LOG << "reply received";
199                 break;
200             }
201         }
202
203         if (nextdeadline >= finaldeadline)
204             break;
205
206         // retransmit on new connection if connection is dead
207         if (!ch || ch->isdead())
208             transmit = true;
209     }
210
211     {
212         // no locking of ca.m since only this thread changes ca.xid
213         lock ml(m_);
214         calls_.erase(ca.xid);
215         // may need to update the xid again here, in case the
216         // packet times out before it's even sent by the channel.
217         // I don't think there's any harm in maybe doing it twice
218         update_xid_rep(ca.xid, ml);
219
220         if (destroy_wait_)
221             destroy_wait_c_.notify_one();
222     }
223
224     if (ca.done && lossytest_)
225     {
226         lock ml(m_);
227         if (!dup_req_.isvalid()) {
228             dup_req_.buf = req;
229             dup_req_.xid = ca.xid;
230         }
231         if (xid_rep > xid_rep_done_)
232             xid_rep_done_ = xid_rep;
233     }
234
235     lock cal(ca.m);
236
237     IF_LEVEL(2) LOG << clt_nonce_ << " call done for req proc " << std::hex << proc
238                     << " xid " << std::dec << ca.xid << " " << inet_ntoa(dst_.sin_addr) << ":"
239                     << ntoh(dst_.sin_port) << " done? " << ca.done << " ret " << ca.intret;
240
241     // destruction of req automatically frees its buffer
242     return (ca.done? ca.intret : rpc_protocol::timeout_failure);
243 }
244
245 void rpcc::get_latest_connection(shared_ptr<connection> & ch) {
246     lock ml(chan_m_);
247     if (!chan_ || chan_->isdead())
248         chan_ = connection::to_dst(dst_, this, lossytest_);
249
250     if (chan_)
251         ch = chan_;
252 }
253
254 // PollMgr's thread is being used to
255 // make this upcall from connection object to rpcc.
256 // this funtion must not block.
257 //
258 // this function keeps no reference for connection *c
259 bool
260 rpcc::got_pdu(const shared_ptr<connection> &, const string & b)
261 {
262     unmarshall rep(b, true);
263     rpc_protocol::reply_header h;
264     rep.read_header(h);
265
266     if (!rep.ok()) {
267         IF_LEVEL(1) LOG << "unmarshall header failed!!!";
268         return true;
269     }
270
271     lock ml(m_);
272
273     update_xid_rep(h.xid, ml);
274
275     if (calls_.find(h.xid) == calls_.end()) {
276         IF_LEVEL(2) LOG << "xid " << h.xid << " no pending request";
277         return true;
278     }
279     caller *ca = calls_[h.xid];
280
281     lock cl(ca->m);
282     if (!ca->done) {
283         *ca->rep = b;
284         ca->intret = h.ret;
285         if (ca->intret < 0) {
286             IF_LEVEL(2) LOG << "RPC reply error for xid " << h.xid << " intret " << ca->intret;
287         }
288         ca->done = 1;
289     }
290     ca->c.notify_all();
291     return true;
292 }
293
294 void rpcc::update_xid_rep(xid_t xid, lock & m_lock) {
295     VERIFY(m_lock);
296     if (xid <= xid_rep_window_.front())
297         return;
298
299     for (auto it = xid_rep_window_.begin(); it != xid_rep_window_.end(); it++) {
300         if (*it > xid) {
301             xid_rep_window_.insert(it, xid);
302             goto compress;
303         }
304     }
305     xid_rep_window_.push_back(xid);
306
307 compress:
308     auto it = xid_rep_window_.begin();
309     for (it++; it != xid_rep_window_.end(); it++) {
310         while (xid_rep_window_.front() + 1 == *it)
311             xid_rep_window_.pop_front();
312     }
313 }
314
315 rpcs::rpcs(in_port_t p1) : port_(p1)
316 {
317     set_rand_seed();
318     nonce_ = (nonce_t)random();
319     IF_LEVEL(2) LOG << "created with nonce " << nonce_;
320
321     reg(rpc_protocol::bind, &rpcs::rpcbind, this);
322 }
323
324 void rpcs::start() {
325     char *loss_env = getenv("RPC_LOSSY");
326     listener_.reset(new connection_listener(this, port_, loss_env ? atoi(loss_env) : 0));
327 }
328
329 rpcs::~rpcs() {
330     // must delete listener before dispatchpool
331     listener_ = nullptr;
332     dispatchpool_ = nullptr;
333 }
334
335 bool rpcs::got_pdu(const shared_ptr<connection> & c, const string & b) {
336     if (!reachable_) {
337         IF_LEVEL(1) LOG << "not reachable";
338         return true;
339     }
340
341     return dispatchpool_->addJob(std::bind(&rpcs::dispatch, this, c, b));
342 }
343
344 void rpcs::dispatch(shared_ptr<connection> c, const string & buf) {
345     unmarshall req(buf, true);
346
347     rpc_protocol::request_header h;
348     req.read_header(h);
349     proc_id_t proc = h.proc;
350
351     if (!req.ok()) {
352         IF_LEVEL(1) LOG << "unmarshall header failed";
353         return;
354     }
355
356     IF_LEVEL(2) LOG << "rpc " << h.xid << " (proc " << std::hex << proc << ", last_rep "
357                     << std::dec << h.xid_rep << ") from clt " << h.clt_nonce << " for srv instance " << h.srv_nonce;
358
359     marshall rep;
360     rpc_protocol::reply_header rh{h.xid,0};
361
362     // is client sending to an old instance of server?
363     if (h.srv_nonce != 0 && h.srv_nonce != nonce_) {
364         IF_LEVEL(2) LOG << "rpc for an old server instance " << h.srv_nonce
365                         << " (current " << nonce_ << ") proc " << std::hex << h.proc;
366         rh.ret = rpc_protocol::oldsrv_failure;
367         rep.write_header(rh);
368         c->send(rep);
369         return;
370     }
371
372     handler *f;
373     // is RPC proc a registered procedure?
374     {
375         lock pl(procs_m_);
376         if (procs_.count(proc) < 1) {
377             LOG << "unknown proc 0x" << std::hex << proc << " with h.srv_nonce=" << h.srv_nonce << ", my srv_nonce=" << nonce_;
378             VERIFY(0);
379             return;
380         }
381
382         f = procs_[proc];
383     }
384
385     // have i seen this client before?
386     {
387         lock rwl(reply_window_m_);
388         // if we don't know about this clt_nonce, create a cleanup object
389         if (reply_window_.find(h.clt_nonce) == reply_window_.end()) {
390             VERIFY (reply_window_[h.clt_nonce].size() == 0); // create
391             reply_window_[h.clt_nonce].push_back(reply_t(-1)); // store starting reply xid
392             IF_LEVEL(2) LOG << "new client " << h.clt_nonce << " xid " << h.xid
393                             << " chan " << c->fd << ", total clients " << (reply_window_.size()-1);
394         }
395     }
396
397     // save the latest good connection to the client
398     {
399         lock rwl(conns_m_);
400         if (conns_.find(h.clt_nonce) == conns_.end())
401             conns_[h.clt_nonce] = c;
402         else if (conns_[h.clt_nonce]->create_time < c->create_time)
403             conns_[h.clt_nonce] = c;
404     }
405
406     string b1;
407
408     switch (check_duplicate_and_update(h.clt_nonce, h.xid, h.xid_rep, b1)) {
409         case NEW: // new request
410             rh.ret = (*f)(std::forward<unmarshall>(req), rep);
411             if (rh.ret == rpc_protocol::unmarshall_args_failure) {
412                 LOG << "failed to unmarshall the arguments. You are "
413                     << "probably calling RPC 0x" << std::hex << proc << " with the wrong "
414                     << "types of arguments.";
415                 VERIFY(0);
416             }
417             VERIFY(rh.ret >= 0);
418
419             rep.write_header(rh);
420             b1 = rep;
421
422             IF_LEVEL(2) LOG << "sending and saving reply of size " << b1.size() << " for rpc "
423                             << h.xid << ", proc " << std::hex << proc << " ret " << std::dec
424                             << rh.ret << ", clt " << h.clt_nonce;
425
426             add_reply(h.clt_nonce, h.xid, b1);
427
428             // get the latest connection to the client
429             {
430                 lock rwl(conns_m_);
431                 if (c->isdead())
432                     c = conns_[h.clt_nonce];
433             }
434
435             c->send(rep);
436             break;
437         case INPROGRESS: // server is working on this request
438             break;
439         case DONE: // duplicate and we still have the response
440             c->send(b1);
441             break;
442         case FORGOTTEN: // very old request and we don't have the response anymore
443             IF_LEVEL(2) LOG << "very old request " << h.xid << " from " << h.clt_nonce;
444             rh.ret = rpc_protocol::atmostonce_failure;
445             rep.write_header(rh);
446             c->send(rep);
447             break;
448     }
449 }
450
451 // rpcs::dispatch calls this when an RPC request arrives.
452 //
453 // checks to see if an RPC with xid from clt_nonce has already been received.
454 // if not, remembers the request in reply_window_.
455 //
456 // deletes remembered requests with XIDs <= xid_rep; the client
457 // says it has received a reply for every RPC up through xid_rep.
458 // frees the reply_t::buf of each such request.
459 //
460 // returns one of:
461 //   NEW: never seen this xid before.
462 //   INPROGRESS: seen this xid, and still processing it.
463 //   DONE: seen this xid, previous reply returned in b.
464 //   FORGOTTEN: might have seen this xid, but deleted previous reply.
465 rpcs::rpcstate_t
466 rpcs::check_duplicate_and_update(nonce_t clt_nonce, xid_t xid,
467         xid_t xid_rep, string & b)
468 {
469     lock rwl(reply_window_m_);
470
471     list<reply_t> & l = reply_window_[clt_nonce];
472
473     VERIFY(l.size() > 0);
474     VERIFY(xid >= xid_rep);
475
476     xid_t past_xid_rep = l.begin()->xid;
477
478     list<reply_t>::iterator start = l.begin(), it = ++start;
479
480     if (past_xid_rep < xid_rep || past_xid_rep == -1) {
481         // scan for deletion candidates
482         while (it != l.end() && it->xid < xid_rep)
483             it++;
484         l.erase(start, it);
485         l.begin()->xid = xid_rep;
486     }
487
488     if (xid < past_xid_rep && past_xid_rep != -1)
489         return FORGOTTEN;
490
491     // skip non-deletion candidates
492     while (it != l.end() && it->xid < xid)
493         it++;
494
495     // if it's in the list it must be right here
496     if (it != l.end() && it->xid == xid) {
497         if (it->cb_present) {
498             // return information about the remembered reply
499             b = it->buf;
500             return DONE;
501         }
502         return INPROGRESS;
503     } else {
504         // remember that a new request has arrived
505         l.insert(it, reply_t(xid));
506         return NEW;
507     }
508 }
509
510 // rpcs::dispatch calls add_reply when it is sending a reply to an RPC,
511 // and passes the return value in b.
512 // add_reply() should remember b.
513 void rpcs::add_reply(nonce_t clt_nonce, xid_t xid, const string & b) {
514     lock rwl(reply_window_m_);
515     // remember the RPC reply value
516     list<reply_t> & l = reply_window_[clt_nonce];
517     list<reply_t>::iterator it = l.begin();
518     // skip to our place in the list
519     for (it++; it != l.end() && it->xid < xid; it++);
520     // there should already be an entry, so whine if there isn't
521     if (it == l.end() || it->xid != xid) {
522         LOG << "Could not find reply struct in add_reply";
523         l.insert(it, reply_t(xid, b));
524     } else {
525         *it = reply_t(xid, b);
526     }
527 }
528
529 rpc_protocol::status rpcs::rpcbind(nonce_t & r) {
530     IF_LEVEL(2) LOG << "called return nonce " << nonce_;
531     r = nonce_;
532     return 0;
533 }
534
535 static sockaddr_in make_sockaddr(const string & hostandport) {
536     string host = "127.0.0.1";
537     string port = hostandport;
538     auto colon = hostandport.find(':');
539     if (colon != string::npos) {
540         host = hostandport.substr(0, colon);
541         port = hostandport.substr(colon+1);
542     }
543
544     sockaddr_in dst = sockaddr_in(); // zero initialize
545     dst.sin_family = AF_INET;
546
547     struct in_addr a{inet_addr(host.c_str())};
548
549     if (a.s_addr != INADDR_NONE)
550         dst.sin_addr.s_addr = a.s_addr;
551     else {
552         struct hostent *hp = gethostbyname(host.c_str());
553
554         if (!hp || hp->h_length != 4 || hp->h_addrtype != AF_INET) {
555             LOG_NONMEMBER << "cannot find host name " << host;
556             exit(1);
557         }
558         memcpy(&a, hp->h_addr_list[0], sizeof(in_addr_t));
559         dst.sin_addr.s_addr = a.s_addr;
560     }
561     dst.sin_port = hton((in_port_t)std::stoi(port));
562     return dst;
563 }