df2b2fc83a469725f80bd214169f6a1606126417
[invirt/third/libt4.git] / rsm.cc
1 //
2 // Replicated state machine implementation with a primary and several
3 // backups. The primary receives requests, assigns each a view stamp (a
4 // vid, and a sequence number) in the order of reception, and forwards
5 // them to all backups. A backup executes requests in the order that
6 // the primary stamps them and replies with an OK to the primary. The
7 // primary executes the request after it receives OKs from all backups,
8 // and sends the reply back to the client.
9 //
10 // The config module will tell the RSM about a new view. If the
11 // primary in the previous view is a member of the new view, then it
12 // will stay the primary.  Otherwise, the smallest numbered node of
13 // the previous view will be the new primary.  In either case, the new
14 // primary will be a node from the previous view.  The configuration
15 // module constructs the sequence of views for the RSM and the RSM
16 // ensures there will be always one primary, who was a member of the
17 // last view.
18 //
19 // When a new node starts, the recovery thread is in charge of joining
20 // the RSM.  It will collect the internal RSM state from the primary;
21 // the primary asks the config module to add the new node and returns
22 // to the joining the internal RSM state (e.g., paxos log). Since
23 // there is only one primary, all joins happen in well-defined total
24 // order.
25 //
26 // The recovery thread also runs during a view change (e.g, when a node
27 // has failed).  After a failure some of the backups could have
28 // processed a request that the primary has not, but those results are
29 // not visible to clients (since the primary responds).  If the
30 // primary of the previous view is in the current view, then it will
31 // be the primary and its state is authoritive: the backups download
32 // from the primary the current state.  A primary waits until all
33 // backups have downloaded the state.  Once the RSM is in sync, the
34 // primary accepts requests again from clients.  If one of the backups
35 // is the new primary, then its state is authoritative.  In either
36 // scenario, the next view uses a node as primary that has the state
37 // resulting from processing all acknowledged client requests.
38 // Therefore, if the nodes sync up before processing the next request,
39 // the next view will have the correct state.
40 //
41 // While the RSM in a view change (i.e., a node has failed, a new view
42 // has been formed, but the sync hasn't completed), another failure
43 // could happen, which complicates a view change.  During syncing the
44 // primary or backups can timeout, and initiate another Paxos round.
45 // There are 2 variables that RSM uses to keep track in what state it
46 // is:
47 //    - inviewchange: a node has failed and the RSM is performing a view change
48 //    - insync: this node is syncing its state
49 //
50 // If inviewchange is false and a node is the primary, then it can
51 // process client requests. If it is true, clients are told to retry
52 // later again.  While inviewchange is true, the RSM may go through several
53 // member list changes, one by one.   After a member list
54 // change completes, the nodes tries to sync. If the sync complets,
55 // the view change completes (and inviewchange is set to false).  If
56 // the sync fails, the node may start another member list change
57 // (inviewchange = true and insync = false).
58 //
59 // The implementation should be used only with servers that run all
60 // requests run to completion; in particular, a request shouldn't
61 // block.  If a request blocks, the backup won't respond to the
62 // primary, and the primary won't execute the request.  A request may
63 // send an RPC to another host, but the RPC should be a one-way
64 // message to that host; the backup shouldn't do anything based on the
65 // response or execute after the response, because it is not
66 // guaranteed that all backup will receive the same response and
67 // execute in the same order.
68 //
69 // The implementation can be viewed as a layered system:
70 //       RSM module     ---- in charge of replication
71 //       config module  ---- in charge of view management
72 //       Paxos module   ---- in charge of running Paxos to agree on a value
73 //
74 // Each module has threads and internal locks. Furthermore, a thread
75 // may call down through the layers (e.g., to run Paxos's proposer).
76 // When Paxos's acceptor accepts a new value for an instance, a thread
77 // will invoke an upcall to inform higher layers of the new value.
78 // The rule is that a module releases its internal locks before it
79 // upcalls, but can keep its locks when calling down.
80
81 #include <fstream>
82 #include <iostream>
83 #include <algorithm>
84 #include <sys/types.h>
85 #include <unistd.h>
86
87 #include "handle.h"
88 #include "rsm.h"
89 #include "tprintf.h"
90 #include "lang/verify.h"
91 #include "rsm_client.h"
92 #include "lock.h"
93
94 rsm::rsm(std::string _first, std::string _me) :
95     stf(0), primary(_first), insync (false), inviewchange (true), vid_commit(0),
96     partitioned (false), dopartition(false), break1(false), break2(false)
97 {
98     last_myvs.vid = 0;
99     last_myvs.seqno = 0;
100     myvs = last_myvs;
101     myvs.seqno = 1;
102
103     cfg = new config(_first, _me, this);
104
105     if (_first == _me) {
106         // Commit the first view here. We can not have acceptor::acceptor
107         // do the commit, since at that time this->cfg is not initialized
108         commit_change(1);
109     }
110     rsmrpc = cfg->get_rpcs();
111     rsmrpc->reg(rsm_client_protocol::invoke, this, &rsm::client_invoke);
112     rsmrpc->reg(rsm_client_protocol::members, this, &rsm::client_members);
113     rsmrpc->reg(rsm_protocol::invoke, this, &rsm::invoke);
114     rsmrpc->reg(rsm_protocol::transferreq, this, &rsm::transferreq);
115     rsmrpc->reg(rsm_protocol::transferdonereq, this, &rsm::transferdonereq);
116     rsmrpc->reg(rsm_protocol::joinreq, this, &rsm::joinreq);
117
118     // tester must be on different port, otherwise it may partition itself
119     testsvr = new rpcs(atoi(_me.c_str()) + 1);
120     testsvr->reg(rsm_test_protocol::net_repair, this, &rsm::test_net_repairreq);
121     testsvr->reg(rsm_test_protocol::breakpoint, this, &rsm::breakpointreq);
122
123     {
124         lock ml(rsm_mutex);
125         std::thread(&rsm::recovery, this).detach();
126     }
127 }
128
129 void rsm::reg1(int proc, handler *h) {
130     lock ml(rsm_mutex);
131     procs[proc] = h;
132 }
133
134 // The recovery thread runs this function
135 void rsm::recovery() {
136     bool r = true;
137     lock ml(rsm_mutex);
138
139     while (1) {
140         while (!cfg->ismember(cfg->myaddr(), vid_commit)) {
141             // XXX iannucci 2013/09/15 -- I don't understand whether accessing
142             // cfg->view_id in this manner involves a race.  I suspect not.
143             if (join(primary)) {
144                 tprintf("recovery: joined\n");
145                 commit_change_wo(cfg->view_id());
146             } else {
147                 ml.unlock();
148                 std::this_thread::sleep_for(std::chrono::seconds(30)); // XXX make another node in cfg primary?
149                 ml.lock();
150             }
151         }
152         vid_insync = vid_commit;
153         tprintf("recovery: sync vid_insync %d\n", vid_insync);
154         if (primary == cfg->myaddr()) {
155             r = sync_with_backups();
156         } else {
157             r = sync_with_primary();
158         }
159         tprintf("recovery: sync done\n");
160
161         // If there was a commited viewchange during the synchronization, restart
162         // the recovery
163         if (vid_insync != vid_commit)
164             continue;
165
166         if (r) {
167             myvs.vid = vid_commit;
168             myvs.seqno = 1;
169             inviewchange = false;
170         }
171         tprintf("recovery: go to sleep %d %d\n", insync, inviewchange);
172         recovery_cond.wait(ml);
173     }
174 }
175
176 template <class A>
177 std::ostream & operator<<(std::ostream &o, const std::vector<A> &d) {
178     o << "[";
179     for (typename std::vector<A>::const_iterator i=d.begin(); i!=d.end(); i++) {
180         o << *i;
181         if (i+1 != d.end())
182             o << ", ";
183     }
184     o << "]";
185     return o;
186 }
187
188 bool rsm::sync_with_backups() {
189     adopt_lock ml(rsm_mutex);
190     ml.unlock();
191     {
192         // Make sure that the state of lock_server_cache_rsm is stable during
193         // synchronization; otherwise, the primary's state may be more recent
194         // than replicas after the synchronization.
195         lock ml(invoke_mutex);
196         // By acquiring and releasing the invoke_mutex once, we make sure that
197         // the state of lock_server_cache_rsm will not be changed until all
198         // replicas are synchronized. The reason is that client_invoke arrives
199         // after this point of time will see inviewchange == true, and returns
200         // BUSY.
201     }
202     ml.lock();
203     // Start accepting synchronization request (statetransferreq) now!
204     insync = true;
205     cfg->get_view(vid_insync, backups);
206     backups.erase(find(backups.begin(), backups.end(), cfg->myaddr()));
207     LOG("rsm::sync_with_backups " << backups);
208     sync_cond.wait(ml);
209     insync = false;
210     return true;
211 }
212
213
214 bool rsm::sync_with_primary() {
215     // Remember the primary of vid_insync
216     std::string m = primary;
217     while (vid_insync == vid_commit) {
218         if (statetransfer(m))
219             break;
220     }
221     return statetransferdone(m);
222 }
223
224
225 /**
226  * Call to transfer state from m to the local node.
227  * Assumes that rsm_mutex is already held.
228  */
229 bool rsm::statetransfer(std::string m)
230 {
231     rsm_protocol::transferres r;
232     handle h(m);
233     int ret = 0;
234     tprintf("rsm::statetransfer: contact %s w. my last_myvs(%d,%d)\n",
235             m.c_str(), last_myvs.vid, last_myvs.seqno);
236     rpcc *cl;
237     {
238         adopt_lock ml(rsm_mutex);
239         ml.unlock();
240         cl = h.safebind();
241         if (cl) {
242             ret = cl->call_timeout(rsm_protocol::transferreq, rpcc::to(1000),
243                     r, cfg->myaddr(), last_myvs, vid_insync);
244         }
245         ml.lock();
246     }
247     if (cl == 0 || ret != rsm_protocol::OK) {
248         tprintf("rsm::statetransfer: couldn't reach %s %lx %d\n", m.c_str(),
249                 (long unsigned) cl, ret);
250         return false;
251     }
252     if (stf && last_myvs != r.last) {
253         stf->unmarshal_state(r.state);
254     }
255     last_myvs = r.last;
256     tprintf("rsm::statetransfer transfer from %s success, vs(%d,%d)\n",
257             m.c_str(), last_myvs.vid, last_myvs.seqno);
258     return true;
259 }
260
261 bool rsm::statetransferdone(std::string m) {
262     adopt_lock ml(rsm_mutex);
263     ml.unlock();
264     handle h(m);
265     rpcc *cl = h.safebind();
266     bool done = false;
267     if (cl) {
268         int r;
269         rsm_protocol::status ret = cl->call(rsm_protocol::transferdonereq, r, cfg->myaddr(), vid_insync);
270         done = (ret == rsm_protocol::OK);
271     }
272     ml.lock();
273     return done;
274 }
275
276
277 bool rsm::join(std::string m) {
278     handle h(m);
279     int ret = 0;
280     rsm_protocol::joinres r;
281
282     tprintf("rsm::join: %s mylast (%d,%d)\n", m.c_str(), last_myvs.vid,
283             last_myvs.seqno);
284     rpcc *cl;
285     {
286         adopt_lock ml(rsm_mutex);
287         ml.unlock();
288         cl = h.safebind();
289         if (cl != 0) {
290             ret = cl->call_timeout(rsm_protocol::joinreq, rpcc::to(120000), r,
291                     cfg->myaddr(), last_myvs);
292         }
293         ml.lock();
294     }
295
296     if (cl == 0 || ret != rsm_protocol::OK) {
297         tprintf("rsm::join: couldn't reach %s %p %d\n", m.c_str(),
298                 cl, ret);
299         return false;
300     }
301     tprintf("rsm::join: succeeded %s\n", r.log.c_str());
302     cfg->restore(r.log);
303     return true;
304 }
305
306 /*
307  * Config informs rsm whenever it has successfully
308  * completed a view change
309  */
310 void rsm::commit_change(unsigned vid) {
311     lock ml(rsm_mutex);
312     commit_change_wo(vid);
313     if (cfg->ismember(cfg->myaddr(), vid_commit))
314         breakpoint2();
315 }
316
317 void rsm::commit_change_wo(unsigned vid) {
318     if (vid <= vid_commit)
319         return;
320     tprintf("commit_change: new view (%d)  last vs (%d,%d) %s insync %d\n",
321             vid, last_myvs.vid, last_myvs.seqno, primary.c_str(), insync);
322     vid_commit = vid;
323     inviewchange = true;
324     set_primary(vid);
325     recovery_cond.notify_one();
326     sync_cond.notify_one();
327     if (cfg->ismember(cfg->myaddr(), vid_commit))
328         breakpoint2();
329 }
330
331
332 void rsm::execute(int procno, std::string req, std::string &r) {
333     tprintf("execute\n");
334     handler *h = procs[procno];
335     VERIFY(h);
336     unmarshall args(req);
337     marshall rep;
338     std::string reps;
339     rsm_protocol::status ret = h->fn(args, rep);
340     marshall rep1;
341     rep1 << ret;
342     rep1 << rep.str();
343     r = rep1.str();
344 }
345
346 //
347 // Clients call client_invoke to invoke a procedure on the replicated state
348 // machine: the primary receives the request, assigns it a sequence
349 // number, and invokes it on all members of the replicated state
350 // machine.
351 //
352 rsm_client_protocol::status rsm::client_invoke(int procno, std::string req, std::string &r) {
353     LOG("rsm::client_invoke: procno 0x" << std::hex << procno);
354     lock ml(invoke_mutex);
355     std::vector<std::string> m;
356     std::string myaddr;
357     viewstamp vs;
358     {
359         lock ml(rsm_mutex);
360         LOG("Checking for inviewchange");
361         if (inviewchange)
362             return rsm_client_protocol::BUSY;
363         LOG("Checking for primacy");
364         myaddr = cfg->myaddr();
365         if (primary != myaddr)
366             return rsm_client_protocol::NOTPRIMARY;
367         LOG("Assigning a viewstamp");
368         cfg->get_view(vid_commit, m);
369         // assign the RPC the next viewstamp number
370         vs = myvs;
371         myvs++;
372     }
373
374     // send an invoke RPC to all slaves in the current view with a timeout of 1 second
375     LOG("Invoking slaves");
376     for (unsigned i  = 0; i < m.size(); i++) {
377         if (m[i] != myaddr) {
378             // if invoke on slave fails, return rsm_client_protocol::BUSY
379             handle h(m[i]);
380             LOG("Sending invoke to " << m[i]);
381             rpcc *cl = h.safebind();
382             if (!cl)
383                 return rsm_client_protocol::BUSY;
384             rsm_protocol::status ret;
385             int r;
386             ret = cl->call_timeout(rsm_protocol::invoke, rpcc::to(1000), r, procno, vs, req);
387             LOG("Invoke returned " << ret);
388             if (ret != rsm_protocol::OK)
389                 return rsm_client_protocol::BUSY;
390             breakpoint1();
391             partition1();
392         }
393     }
394     execute(procno, req, r);
395     last_myvs = vs;
396     return rsm_client_protocol::OK;
397 }
398
399 //
400 // The primary calls the internal invoke at each member of the
401 // replicated state machine
402 //
403 // the replica must execute requests in order (with no gaps)
404 // according to requests' seqno
405
406 rsm_protocol::status rsm::invoke(int proc, viewstamp vs, std::string req, int &dummy) {
407     LOG("rsm::invoke: procno 0x" << std::hex << proc);
408     lock ml(invoke_mutex);
409     std::vector<std::string> m;
410     std::string myaddr;
411     {
412         lock ml(rsm_mutex);
413         // check if !inviewchange
414         LOG("Checking for view change");
415         if (inviewchange)
416             return rsm_protocol::ERR;
417         // check if slave
418         LOG("Checking for slave status");
419         myaddr = cfg->myaddr();
420         if (primary == myaddr)
421             return rsm_protocol::ERR;
422         cfg->get_view(vid_commit, m);
423         if (find(m.begin(), m.end(), myaddr) == m.end())
424             return rsm_protocol::ERR;
425         // check sequence number
426         LOG("Checking sequence number");
427         if (vs != myvs)
428             return rsm_protocol::ERR;
429         myvs++;
430     }
431     std::string r;
432     execute(proc, req, r);
433     last_myvs = vs;
434     breakpoint1();
435     return rsm_protocol::OK;
436 }
437
438 /**
439  * RPC handler: Send back the local node's state to the caller
440  */
441 rsm_protocol::status rsm::transferreq(std::string src, viewstamp last, unsigned vid,
442         rsm_protocol::transferres &r) {
443     lock ml(rsm_mutex);
444     int ret = rsm_protocol::OK;
445     tprintf("transferreq from %s (%d,%d) vs (%d,%d)\n", src.c_str(),
446             last.vid, last.seqno, last_myvs.vid, last_myvs.seqno);
447     if (!insync || vid != vid_insync) {
448         return rsm_protocol::BUSY;
449     }
450     if (stf && last != last_myvs)
451         r.state = stf->marshal_state();
452     r.last = last_myvs;
453     return ret;
454 }
455
456 /**
457  * RPC handler: Inform the local node (the primary) that node m has synchronized
458  * for view vid
459  */
460 rsm_protocol::status rsm::transferdonereq(std::string m, unsigned vid, int &) {
461     lock ml(rsm_mutex);
462     if (!insync || vid != vid_insync)
463         return rsm_protocol::BUSY;
464     backups.erase(find(backups.begin(), backups.end(), m));
465     if (backups.empty())
466         sync_cond.notify_one();
467     return rsm_protocol::OK;
468 }
469
470 // a node that wants to join an RSM as a server sends a
471 // joinreq to the RSM's current primary; this is the
472 // handler for that RPC.
473 rsm_protocol::status rsm::joinreq(std::string m, viewstamp last, rsm_protocol::joinres &r) {
474     int ret = rsm_protocol::OK;
475
476     lock ml(rsm_mutex);
477     tprintf("joinreq: src %s last (%d,%d) mylast (%d,%d)\n", m.c_str(),
478             last.vid, last.seqno, last_myvs.vid, last_myvs.seqno);
479     if (cfg->ismember(m, vid_commit)) {
480         tprintf("joinreq: is still a member\n");
481         r.log = cfg->dump();
482     } else if (cfg->myaddr() != primary) {
483         tprintf("joinreq: busy\n");
484         ret = rsm_protocol::BUSY;
485     } else {
486         // We cache vid_commit to avoid adding m to a view which already contains
487         // m due to race condition
488         unsigned vid_cache = vid_commit;
489         bool succ;
490         {
491             ml.unlock();
492             succ = cfg->add(m, vid_cache);
493             ml.lock();
494         }
495         if (cfg->ismember(m, cfg->view_id())) {
496             r.log = cfg->dump();
497             tprintf("joinreq: ret %d log %s\n:", ret, r.log.c_str());
498         } else {
499             tprintf("joinreq: failed; proposer couldn't add %d\n", succ);
500             ret = rsm_protocol::BUSY;
501         }
502     }
503     return ret;
504 }
505
506 /*
507  * RPC handler: Send back all the nodes this local knows about to client
508  * so the client can switch to a different primary
509  * when it existing primary fails
510  */
511 rsm_client_protocol::status rsm::client_members(int i, std::vector<std::string> &r) {
512     std::vector<std::string> m;
513     lock ml(rsm_mutex);
514     cfg->get_view(vid_commit, m);
515     m.push_back(primary);
516     r = m;
517     tprintf("rsm::client_members return %s m %s\n", print_members(m).c_str(),
518             primary.c_str());
519     return rsm_client_protocol::OK;
520 }
521
522 // if primary is member of new view, that node is primary
523 // otherwise, the lowest number node of the previous view.
524 // caller should hold rsm_mutex
525 void rsm::set_primary(unsigned vid) {
526     std::vector<std::string> c, p;
527     cfg->get_view(vid, c);
528     cfg->get_view(vid - 1, p);
529     VERIFY (c.size() > 0);
530
531     if (isamember(primary,c)) {
532         tprintf("set_primary: primary stays %s\n", primary.c_str());
533         return;
534     }
535
536     VERIFY(p.size() > 0);
537     for (unsigned i = 0; i < p.size(); i++) {
538         if (isamember(p[i], c)) {
539             primary = p[i];
540             tprintf("set_primary: primary is %s\n", primary.c_str());
541             return;
542         }
543     }
544     VERIFY(0);
545 }
546
547 bool rsm::amiprimary() {
548     lock ml(rsm_mutex);
549     return primary == cfg->myaddr() && !inviewchange;
550 }
551
552
553 // Testing server
554
555 // Simulate partitions
556
557 // assumes caller holds rsm_mutex
558 void rsm::net_repair_wo(bool heal) {
559     std::vector<std::string> m;
560     cfg->get_view(vid_commit, m);
561     for (unsigned i  = 0; i < m.size(); i++) {
562         if (m[i] != cfg->myaddr()) {
563             handle h(m[i]);
564             tprintf("rsm::net_repair_wo: %s %d\n", m[i].c_str(), heal);
565             if (h.safebind()) h.safebind()->set_reachable(heal);
566         }
567     }
568     rsmrpc->set_reachable(heal);
569 }
570
571 rsm_test_protocol::status rsm::test_net_repairreq(int heal, int &r) {
572     lock ml(rsm_mutex);
573     tprintf("rsm::test_net_repairreq: %d (dopartition %d, partitioned %d)\n",
574             heal, dopartition, partitioned);
575     if (heal) {
576         net_repair_wo(heal);
577         partitioned = false;
578     } else {
579         dopartition = true;
580         partitioned = false;
581     }
582     r = rsm_test_protocol::OK;
583     return r;
584 }
585
586 // simulate failure at breakpoint 1 and 2
587
588 void rsm::breakpoint1() {
589     if (break1) {
590         tprintf("Dying at breakpoint 1 in rsm!\n");
591         exit(1);
592     }
593 }
594
595 void rsm::breakpoint2() {
596     if (break2) {
597         tprintf("Dying at breakpoint 2 in rsm!\n");
598         exit(1);
599     }
600 }
601
602 void rsm::partition1() {
603     if (dopartition) {
604         net_repair_wo(false);
605         dopartition = false;
606         partitioned = true;
607     }
608 }
609
610 rsm_test_protocol::status rsm::breakpointreq(int b, int &r) {
611     r = rsm_test_protocol::OK;
612     lock ml(rsm_mutex);
613     tprintf("rsm::breakpointreq: %d\n", b);
614     if (b == 1) break1 = true;
615     else if (b == 2) break2 = true;
616     else if (b == 3 || b == 4) cfg->breakpoint(b);
617     else r = rsm_test_protocol::ERR;
618     return r;
619 }