All random numbers generated via one PRNG seeded in one place.
[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 static sockaddr_in make_sockaddr(const string & hostandport);
67
68 rpcc::rpcc(const string & d) : dst_(make_sockaddr(d))
69 {
70     clt_nonce_ = (nonce_t)global->random_generator();
71
72     char *loss_env = getenv("RPC_LOSSY");
73     if (loss_env)
74         lossytest_ = atoi(loss_env);
75
76     IF_LEVEL(2) LOG << "cltn_nonce is " << clt_nonce_ << " lossy " << lossytest_;
77 }
78
79 // IMPORTANT: destruction should happen only when no external threads
80 // are blocked inside rpcc or will use rpcc in the future
81 rpcc::~rpcc() {
82     lock ml(m_);
83     cancel(ml);
84     IF_LEVEL(2) LOG << "delete nonce " << clt_nonce_ << " chan " << (chan_?(int)chan_->fd:-1);
85     chan_.reset();
86     VERIFY(calls_.size() == 0);
87 }
88
89 int rpcc::bind(milliseconds to) {
90     nonce_t r = 0;
91     rpc_protocol::status ret = call_timeout(rpc_protocol::bind, to, r);
92     if (ret == 0) {
93         lock ml(m_);
94         bind_done_ = true;
95         srv_nonce_ = r;
96     } else {
97         IF_LEVEL(2) LOG << "bind " << inet_ntoa(dst_.sin_addr) << " failed " << ret;
98     }
99     return ret;
100 }
101
102 shared_ptr<rpcc> rpcc::bind_cached(const string & destination) {
103     auto client = global->get_handle(destination);
104     lock cl = lock(client->bind_m_);
105     if (!client->bind_done_) {
106         LOG_NONMEMBER << "bind(\"" << destination << "\")";
107         int ret = client->bind(milliseconds(1000));
108         if (ret < 0) {
109             LOG_NONMEMBER << "bind failure! " << destination << " " << ret;
110             client.reset();
111         } else {
112             LOG_NONMEMBER << "bind succeeded " << destination;
113         }
114     }
115     return client;
116 }
117
118 void rpcc::unbind_cached(const string & destination) {
119     global->erase_handle(destination);
120 }
121
122 // Cancel all outstanding calls
123 void rpcc::cancel(lock & m_lock) {
124     VERIFY(m_lock);
125     if (calls_.size()) {
126         LOG << "force callers to fail";
127         for (auto & p : calls_) {
128             caller *ca = p.second;
129
130             IF_LEVEL(2) LOG << "force caller to fail";
131
132             lock cl(ca->m);
133             ca->done = true;
134             ca->intret = rpc_protocol::cancel_failure;
135             ca->c.notify_one();
136         }
137
138         destroy_wait_ = true;
139         while (calls_.size () > 0)
140             destroy_wait_c_.wait(m_lock);
141
142         LOG << "done";
143     }
144 }
145
146 int rpcc::call1(proc_id_t proc, milliseconds to, string & rep, marshall & req) {
147
148     caller ca(0, &rep);
149     xid_t xid_rep;
150     {
151         lock ml(m_);
152
153         if ((proc != rpc_protocol::bind.id && !bind_done_) || (proc == rpc_protocol::bind.id && bind_done_)) {
154             IF_LEVEL(1) LOG << "rpcc has not been bound to dst or binding twice";
155             return rpc_protocol::bind_failure;
156         }
157
158         if (destroy_wait_)
159             return rpc_protocol::cancel_failure;
160
161         ca.xid = xid_++;
162         calls_[ca.xid] = &ca;
163
164         req.write_header(rpc_protocol::request_header{
165                 ca.xid, proc, clt_nonce_, srv_nonce_, xid_rep_window_.front()
166                 });
167         xid_rep = xid_rep_window_.front();
168     }
169
170     milliseconds curr_to = rpc::to_min;
171     auto finaldeadline = steady_clock::now() + to;
172
173     bool transmit = true;
174     shared_ptr<connection> ch;
175
176     while (1) {
177         if (transmit) {
178             get_latest_connection(ch);
179             if (ch) {
180                 if (reachable_) {
181                     request forgot;
182                     {
183                         lock ml(m_);
184                         if (dup_req_.isvalid() && xid_rep_done_ > dup_req_.xid) {
185                             forgot = dup_req_;
186                             dup_req_.clear();
187                         }
188                     }
189                     if (forgot.isvalid())
190                         ch->send(forgot.buf);
191                     ch->send(req);
192                 }
193                 else IF_LEVEL(1) LOG << "not reachable";
194                 IF_LEVEL(2) LOG << clt_nonce_ << " just sent req proc " << std::hex << proc
195                                 << " xid " << std::dec << ca.xid << " clt_nonce " << clt_nonce_;
196             }
197             transmit = false; // only send once on a given channel
198         }
199
200         auto nextdeadline = std::min(steady_clock::now() + curr_to, finaldeadline);
201         curr_to *= 2;
202
203         {
204             lock cal(ca.m);
205             while (!ca.done) {
206                 IF_LEVEL(2) LOG << "wait";
207                 if (ca.c.wait_until(cal, nextdeadline) == std::cv_status::timeout) {
208                     IF_LEVEL(2) LOG << "timeout";
209                     break;
210                 }
211             }
212             if (ca.done) {
213                 IF_LEVEL(2) LOG << "reply received";
214                 break;
215             }
216         }
217
218         if (nextdeadline >= finaldeadline)
219             break;
220
221         // retransmit on new connection if connection is dead
222         if (!ch || ch->isdead())
223             transmit = true;
224     }
225
226     {
227         // no locking of ca.m since only this thread changes ca.xid
228         lock ml(m_);
229         calls_.erase(ca.xid);
230         // may need to update the xid again here, in case the
231         // packet times out before it's even sent by the channel.
232         // I don't think there's any harm in maybe doing it twice
233         update_xid_rep(ca.xid, ml);
234
235         if (destroy_wait_)
236             destroy_wait_c_.notify_one();
237     }
238
239     if (ca.done && lossytest_)
240     {
241         lock ml(m_);
242         if (!dup_req_.isvalid()) {
243             dup_req_.buf = req;
244             dup_req_.xid = ca.xid;
245         }
246         if (xid_rep > xid_rep_done_)
247             xid_rep_done_ = xid_rep;
248     }
249
250     lock cal(ca.m);
251
252     IF_LEVEL(2) LOG << clt_nonce_ << " call done for req proc " << std::hex << proc
253                     << " xid " << std::dec << ca.xid << " " << inet_ntoa(dst_.sin_addr) << ":"
254                     << ntoh(dst_.sin_port) << " done? " << ca.done << " ret " << ca.intret;
255
256     // destruction of req automatically frees its buffer
257     return (ca.done? ca.intret : rpc_protocol::timeout_failure);
258 }
259
260 void rpcc::get_latest_connection(shared_ptr<connection> & ch) {
261     lock ml(chan_m_);
262     if (!chan_ || chan_->isdead())
263         chan_ = connection::to_dst(dst_, this, lossytest_);
264
265     if (chan_)
266         ch = chan_;
267 }
268
269 // PollMgr's thread is being used to
270 // make this upcall from connection object to rpcc.
271 // this funtion must not block.
272 //
273 // this function keeps no reference for connection *c
274 bool
275 rpcc::got_pdu(const shared_ptr<connection> &, const string & b)
276 {
277     unmarshall rep(b, true);
278     rpc_protocol::reply_header h;
279     rep.read_header(h);
280
281     if (!rep.ok()) {
282         IF_LEVEL(1) LOG << "unmarshall header failed!!!";
283         return true;
284     }
285
286     lock ml(m_);
287
288     update_xid_rep(h.xid, ml);
289
290     if (calls_.find(h.xid) == calls_.end()) {
291         IF_LEVEL(2) LOG << "xid " << h.xid << " no pending request";
292         return true;
293     }
294     caller *ca = calls_[h.xid];
295
296     lock cl(ca->m);
297     if (!ca->done) {
298         *ca->rep = b;
299         ca->intret = h.ret;
300         if (ca->intret < 0) {
301             IF_LEVEL(2) LOG << "RPC reply error for xid " << h.xid << " intret " << ca->intret;
302         }
303         ca->done = 1;
304     }
305     ca->c.notify_all();
306     return true;
307 }
308
309 void rpcc::update_xid_rep(xid_t xid, lock & m_lock) {
310     VERIFY(m_lock);
311     if (xid <= xid_rep_window_.front())
312         return;
313
314     for (auto it = xid_rep_window_.begin(); it != xid_rep_window_.end(); it++) {
315         if (*it > xid) {
316             xid_rep_window_.insert(it, xid);
317             goto compress;
318         }
319     }
320     xid_rep_window_.push_back(xid);
321
322 compress:
323     auto it = xid_rep_window_.begin();
324     for (it++; it != xid_rep_window_.end(); it++) {
325         while (xid_rep_window_.front() + 1 == *it)
326             xid_rep_window_.pop_front();
327     }
328 }
329
330 rpcs::rpcs(in_port_t p1) : port_(p1)
331 {
332     nonce_ = (nonce_t)global->random_generator();
333     IF_LEVEL(2) LOG << "created with nonce " << nonce_;
334
335     reg(rpc_protocol::bind, &rpcs::rpcbind, this);
336 }
337
338 void rpcs::start() {
339     char *loss_env = getenv("RPC_LOSSY");
340     listener_.reset(new connection_listener(this, port_, loss_env ? atoi(loss_env) : 0));
341 }
342
343 rpcs::~rpcs() {
344     // must delete listener before dispatchpool
345     listener_ = nullptr;
346     dispatchpool_ = nullptr;
347 }
348
349 bool rpcs::got_pdu(const shared_ptr<connection> & c, const string & b) {
350     if (!reachable_) {
351         IF_LEVEL(1) LOG << "not reachable";
352         return true;
353     }
354
355     return dispatchpool_->addJob(std::bind(&rpcs::dispatch, this, c, b));
356 }
357
358 void rpcs::dispatch(shared_ptr<connection> c, const string & buf) {
359     unmarshall req(buf, true);
360
361     rpc_protocol::request_header h;
362     req.read_header(h);
363     proc_id_t proc = h.proc;
364
365     if (!req.ok()) {
366         IF_LEVEL(1) LOG << "unmarshall header failed";
367         return;
368     }
369
370     IF_LEVEL(2) LOG << "rpc " << h.xid << " (proc " << std::hex << proc << ", last_rep "
371                     << std::dec << h.xid_rep << ") from clt " << h.clt_nonce << " for srv instance " << h.srv_nonce;
372
373     marshall rep;
374     rpc_protocol::reply_header rh{h.xid,0};
375
376     // is client sending to an old instance of server?
377     if (h.srv_nonce != 0 && h.srv_nonce != nonce_) {
378         IF_LEVEL(2) LOG << "rpc for an old server instance " << h.srv_nonce
379                         << " (current " << nonce_ << ") proc " << std::hex << h.proc;
380         rh.ret = rpc_protocol::oldsrv_failure;
381         rep.write_header(rh);
382         c->send(rep);
383         return;
384     }
385
386     handler *f;
387     // is RPC proc a registered procedure?
388     {
389         lock pl(procs_m_);
390         if (procs_.count(proc) < 1) {
391             LOG << "unknown proc 0x" << std::hex << proc << " with h.srv_nonce=" << h.srv_nonce << ", my srv_nonce=" << nonce_;
392             VERIFY(0);
393             return;
394         }
395
396         f = procs_[proc];
397     }
398
399     // have i seen this client before?
400     {
401         lock rwl(reply_window_m_);
402         // if we don't know about this clt_nonce, create a cleanup object
403         if (reply_window_.find(h.clt_nonce) == reply_window_.end()) {
404             VERIFY (reply_window_[h.clt_nonce].size() == 0); // create
405             reply_window_[h.clt_nonce].push_back(reply_t(-1)); // store starting reply xid
406             IF_LEVEL(2) LOG << "new client " << h.clt_nonce << " xid " << h.xid
407                             << " chan " << c->fd << ", total clients " << (reply_window_.size()-1);
408         }
409     }
410
411     // save the latest good connection to the client
412     {
413         lock rwl(conns_m_);
414         if (conns_.find(h.clt_nonce) == conns_.end())
415             conns_[h.clt_nonce] = c;
416         else if (conns_[h.clt_nonce]->create_time < c->create_time)
417             conns_[h.clt_nonce] = c;
418     }
419
420     string b1;
421
422     switch (check_duplicate_and_update(h.clt_nonce, h.xid, h.xid_rep, b1)) {
423         case NEW: // new request
424             rh.ret = (*f)(std::forward<unmarshall>(req), rep);
425             if (rh.ret == rpc_protocol::unmarshall_args_failure) {
426                 LOG << "failed to unmarshall the arguments. You are "
427                     << "probably calling RPC 0x" << std::hex << proc << " with the wrong "
428                     << "types of arguments.";
429                 VERIFY(0);
430             }
431             VERIFY(rh.ret >= 0);
432
433             rep.write_header(rh);
434             b1 = rep;
435
436             IF_LEVEL(2) LOG << "sending and saving reply of size " << b1.size() << " for rpc "
437                             << h.xid << ", proc " << std::hex << proc << " ret " << std::dec
438                             << rh.ret << ", clt " << h.clt_nonce;
439
440             add_reply(h.clt_nonce, h.xid, b1);
441
442             // get the latest connection to the client
443             {
444                 lock rwl(conns_m_);
445                 if (c->isdead())
446                     c = conns_[h.clt_nonce];
447             }
448
449             c->send(rep);
450             break;
451         case INPROGRESS: // server is working on this request
452             break;
453         case DONE: // duplicate and we still have the response
454             c->send(b1);
455             break;
456         case FORGOTTEN: // very old request and we don't have the response anymore
457             IF_LEVEL(2) LOG << "very old request " << h.xid << " from " << h.clt_nonce;
458             rh.ret = rpc_protocol::atmostonce_failure;
459             rep.write_header(rh);
460             c->send(rep);
461             break;
462     }
463 }
464
465 // rpcs::dispatch calls this when an RPC request arrives.
466 //
467 // checks to see if an RPC with xid from clt_nonce has already been received.
468 // if not, remembers the request in reply_window_.
469 //
470 // deletes remembered requests with XIDs <= xid_rep; the client
471 // says it has received a reply for every RPC up through xid_rep.
472 // frees the reply_t::buf of each such request.
473 //
474 // returns one of:
475 //   NEW: never seen this xid before.
476 //   INPROGRESS: seen this xid, and still processing it.
477 //   DONE: seen this xid, previous reply returned in b.
478 //   FORGOTTEN: might have seen this xid, but deleted previous reply.
479 rpcs::rpcstate_t
480 rpcs::check_duplicate_and_update(nonce_t clt_nonce, xid_t xid,
481         xid_t xid_rep, string & b)
482 {
483     lock rwl(reply_window_m_);
484
485     list<reply_t> & l = reply_window_[clt_nonce];
486
487     VERIFY(l.size() > 0);
488     VERIFY(xid >= xid_rep);
489
490     xid_t past_xid_rep = l.begin()->xid;
491
492     list<reply_t>::iterator start = l.begin(), it = ++start;
493
494     if (past_xid_rep < xid_rep || past_xid_rep == -1) {
495         // scan for deletion candidates
496         while (it != l.end() && it->xid < xid_rep)
497             it++;
498         l.erase(start, it);
499         l.begin()->xid = xid_rep;
500     }
501
502     if (xid < past_xid_rep && past_xid_rep != -1)
503         return FORGOTTEN;
504
505     // skip non-deletion candidates
506     while (it != l.end() && it->xid < xid)
507         it++;
508
509     // if it's in the list it must be right here
510     if (it != l.end() && it->xid == xid) {
511         if (it->cb_present) {
512             // return information about the remembered reply
513             b = it->buf;
514             return DONE;
515         }
516         return INPROGRESS;
517     } else {
518         // remember that a new request has arrived
519         l.insert(it, reply_t(xid));
520         return NEW;
521     }
522 }
523
524 // rpcs::dispatch calls add_reply when it is sending a reply to an RPC,
525 // and passes the return value in b.
526 // add_reply() should remember b.
527 void rpcs::add_reply(nonce_t clt_nonce, xid_t xid, const string & b) {
528     lock rwl(reply_window_m_);
529     // remember the RPC reply value
530     list<reply_t> & l = reply_window_[clt_nonce];
531     list<reply_t>::iterator it = l.begin();
532     // skip to our place in the list
533     for (it++; it != l.end() && it->xid < xid; it++);
534     // there should already be an entry, so whine if there isn't
535     if (it == l.end() || it->xid != xid) {
536         LOG << "Could not find reply struct in add_reply";
537         l.insert(it, reply_t(xid, b));
538     } else {
539         *it = reply_t(xid, b);
540     }
541 }
542
543 rpc_protocol::status rpcs::rpcbind(nonce_t & r) {
544     IF_LEVEL(2) LOG << "called return nonce " << nonce_;
545     r = nonce_;
546     return 0;
547 }
548
549 static sockaddr_in make_sockaddr(const string & hostandport) {
550     string host = "127.0.0.1";
551     string port = hostandport;
552     auto colon = hostandport.find(':');
553     if (colon != string::npos) {
554         host = hostandport.substr(0, colon);
555         port = hostandport.substr(colon+1);
556     }
557
558     sockaddr_in dst = sockaddr_in(); // zero initialize
559     dst.sin_family = AF_INET;
560
561     struct in_addr a{inet_addr(host.c_str())};
562
563     if (a.s_addr != INADDR_NONE)
564         dst.sin_addr.s_addr = a.s_addr;
565     else {
566         struct hostent *hp = gethostbyname(host.c_str());
567
568         if (!hp || hp->h_length != 4 || hp->h_addrtype != AF_INET) {
569             LOG_NONMEMBER << "cannot find host name " << host;
570             exit(1);
571         }
572         memcpy(&a, hp->h_addr_list[0], sizeof(in_addr_t));
573         dst.sin_addr.s_addr = a.s_addr;
574     }
575     dst.sin_port = hton((in_port_t)std::stoi(port));
576     return dst;
577 }