Major clean-ups. Migrating to C++11.
[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     std::thread th;
99
100     last_myvs.vid = 0;
101     last_myvs.seqno = 0;
102     myvs = last_myvs;
103     myvs.seqno = 1;
104
105     cfg = new config(_first, _me, this);
106
107     if (_first == _me) {
108         // Commit the first view here. We can not have acceptor::acceptor
109         // do the commit, since at that time this->cfg is not initialized
110         commit_change(1);
111     }
112     rsmrpc = cfg->get_rpcs();
113     rsmrpc->reg(rsm_client_protocol::invoke, this, &rsm::client_invoke);
114     rsmrpc->reg(rsm_client_protocol::members, this, &rsm::client_members);
115     rsmrpc->reg(rsm_protocol::invoke, this, &rsm::invoke);
116     rsmrpc->reg(rsm_protocol::transferreq, this, &rsm::transferreq);
117     rsmrpc->reg(rsm_protocol::transferdonereq, this, &rsm::transferdonereq);
118     rsmrpc->reg(rsm_protocol::joinreq, this, &rsm::joinreq);
119
120     // tester must be on different port, otherwise it may partition itself
121     testsvr = new rpcs(atoi(_me.c_str()) + 1);
122     testsvr->reg(rsm_test_protocol::net_repair, this, &rsm::test_net_repairreq);
123     testsvr->reg(rsm_test_protocol::breakpoint, this, &rsm::breakpointreq);
124
125     {
126         lock ml(rsm_mutex);
127         th = std::thread(&rsm::recovery, this);
128     }
129 }
130
131 void rsm::reg1(int proc, handler *h) {
132     lock ml(rsm_mutex);
133     procs[proc] = h;
134 }
135
136 // The recovery thread runs this function
137 void rsm::recovery() {
138     bool r = true;
139     lock ml(rsm_mutex);
140
141     while (1) {
142         while (!cfg->ismember(cfg->myaddr(), vid_commit)) {
143             // XXX iannucci 2013/09/15 -- I don't understand whether accessing
144             // cfg->view_id in this manner involves a race.  I suspect not.
145             if (join(primary)) {
146                 tprintf("recovery: joined\n");
147                 commit_change_wo(cfg->view_id());
148             } else {
149                 ml.unlock();
150                 std::this_thread::sleep_for(std::chrono::seconds(30)); // XXX make another node in cfg primary?
151                 ml.lock();
152             }
153         }
154         vid_insync = vid_commit;
155         tprintf("recovery: sync vid_insync %d\n", vid_insync);
156         if (primary == cfg->myaddr()) {
157             r = sync_with_backups();
158         } else {
159             r = sync_with_primary();
160         }
161         tprintf("recovery: sync done\n");
162
163         // If there was a commited viewchange during the synchronization, restart
164         // the recovery
165         if (vid_insync != vid_commit)
166             continue;
167
168         if (r) {
169             myvs.vid = vid_commit;
170             myvs.seqno = 1;
171             inviewchange = false;
172         }
173         tprintf("recovery: go to sleep %d %d\n", insync, inviewchange);
174         recovery_cond.wait(ml);
175     }
176 }
177
178 template <class A>
179 std::ostream & operator<<(std::ostream &o, const std::vector<A> &d) {
180     o << "[";
181     for (typename std::vector<A>::const_iterator i=d.begin(); i!=d.end(); i++) {
182         o << *i;
183         if (i+1 != d.end())
184             o << ", ";
185     }
186     o << "]";
187     return o;
188 }
189
190 bool rsm::sync_with_backups() {
191     adopt_lock ml(rsm_mutex);
192     ml.unlock();
193     {
194         // Make sure that the state of lock_server_cache_rsm is stable during
195         // synchronization; otherwise, the primary's state may be more recent
196         // than replicas after the synchronization.
197         lock ml(invoke_mutex);
198         // By acquiring and releasing the invoke_mutex once, we make sure that
199         // the state of lock_server_cache_rsm will not be changed until all
200         // replicas are synchronized. The reason is that client_invoke arrives
201         // after this point of time will see inviewchange == true, and returns
202         // BUSY.
203     }
204     ml.lock();
205     // Start accepting synchronization request (statetransferreq) now!
206     insync = true;
207     cfg->get_view(vid_insync, backups);
208     backups.erase(find(backups.begin(), backups.end(), cfg->myaddr()));
209     LOG("rsm::sync_with_backups " << backups);
210     sync_cond.wait(ml);
211     insync = false;
212     return true;
213 }
214
215
216 bool rsm::sync_with_primary() {
217     // Remember the primary of vid_insync
218     std::string m = primary;
219     while (vid_insync == vid_commit) {
220         if (statetransfer(m))
221             break;
222     }
223     return statetransferdone(m);
224 }
225
226
227 /**
228  * Call to transfer state from m to the local node.
229  * Assumes that rsm_mutex is already held.
230  */
231 bool rsm::statetransfer(std::string m)
232 {
233     rsm_protocol::transferres r;
234     handle h(m);
235     int ret;
236     tprintf("rsm::statetransfer: contact %s w. my last_myvs(%d,%d)\n",
237             m.c_str(), last_myvs.vid, last_myvs.seqno);
238     rpcc *cl;
239     {
240         adopt_lock ml(rsm_mutex);
241         ml.unlock();
242         cl = h.safebind();
243         if (cl) {
244             ret = cl->call(rsm_protocol::transferreq, cfg->myaddr(),
245                     last_myvs, vid_insync, r, rpcc::to(1000));
246         }
247         ml.lock();
248     }
249     if (cl == 0 || ret != rsm_protocol::OK) {
250         tprintf("rsm::statetransfer: couldn't reach %s %lx %d\n", m.c_str(),
251                 (long unsigned) cl, ret);
252         return false;
253     }
254     if (stf && last_myvs != r.last) {
255         stf->unmarshal_state(r.state);
256     }
257     last_myvs = r.last;
258     tprintf("rsm::statetransfer transfer from %s success, vs(%d,%d)\n",
259             m.c_str(), last_myvs.vid, last_myvs.seqno);
260     return true;
261 }
262
263 bool rsm::statetransferdone(std::string m) {
264     adopt_lock ml(rsm_mutex);
265     ml.unlock();
266     handle h(m);
267     rpcc *cl = h.safebind();
268     bool done = false;
269     if (cl) {
270         int r;
271         rsm_protocol::status ret = cl->call(rsm_protocol::transferdonereq, cfg->myaddr(), vid_insync, r);
272         done = (ret == rsm_protocol::OK);
273     }
274     ml.lock();
275     return done;
276 }
277
278
279 bool rsm::join(std::string m) {
280     handle h(m);
281     int ret;
282     rsm_protocol::joinres r;
283
284     tprintf("rsm::join: %s mylast (%d,%d)\n", m.c_str(), last_myvs.vid,
285             last_myvs.seqno);
286     rpcc *cl;
287     {
288         adopt_lock ml(rsm_mutex);
289         ml.unlock();
290         cl = h.safebind();
291         if (cl != 0) {
292             ret = cl->call(rsm_protocol::joinreq, cfg->myaddr(), last_myvs,
293                     r, rpcc::to(120000));
294         }
295         ml.lock();
296     }
297
298     if (cl == 0 || ret != rsm_protocol::OK) {
299         tprintf("rsm::join: couldn't reach %s %p %d\n", m.c_str(),
300                 cl, ret);
301         return false;
302     }
303     tprintf("rsm::join: succeeded %s\n", r.log.c_str());
304     cfg->restore(r.log);
305     return true;
306 }
307
308 /*
309  * Config informs rsm whenever it has successfully
310  * completed a view change
311  */
312 void rsm::commit_change(unsigned vid) {
313     lock ml(rsm_mutex);
314     commit_change_wo(vid);
315     if (cfg->ismember(cfg->myaddr(), vid_commit))
316         breakpoint2();
317 }
318
319 void rsm::commit_change_wo(unsigned vid) {
320     if (vid <= vid_commit)
321         return;
322     tprintf("commit_change: new view (%d)  last vs (%d,%d) %s insync %d\n",
323             vid, last_myvs.vid, last_myvs.seqno, primary.c_str(), insync);
324     vid_commit = vid;
325     inviewchange = true;
326     set_primary(vid);
327     recovery_cond.notify_one();
328     sync_cond.notify_one();
329     if (cfg->ismember(cfg->myaddr(), vid_commit))
330         breakpoint2();
331 }
332
333
334 void rsm::execute(int procno, std::string req, std::string &r) {
335     tprintf("execute\n");
336     handler *h = procs[procno];
337     VERIFY(h);
338     unmarshall args(req);
339     marshall rep;
340     std::string reps;
341     rsm_protocol::status ret = h->fn(args, rep);
342     marshall rep1;
343     rep1 << ret;
344     rep1 << rep.str();
345     r = rep1.str();
346 }
347
348 //
349 // Clients call client_invoke to invoke a procedure on the replicated state
350 // machine: the primary receives the request, assigns it a sequence
351 // number, and invokes it on all members of the replicated state
352 // machine.
353 //
354 rsm_client_protocol::status rsm::client_invoke(int procno, std::string req, std::string &r) {
355     LOG("rsm::client_invoke: procno 0x" << std::hex << procno);
356     lock ml(invoke_mutex);
357     std::vector<std::string> m;
358     std::string myaddr;
359     viewstamp vs;
360     {
361         lock ml(rsm_mutex);
362         LOG("Checking for inviewchange");
363         if (inviewchange)
364             return rsm_client_protocol::BUSY;
365         LOG("Checking for primacy");
366         myaddr = cfg->myaddr();
367         if (primary != myaddr)
368             return rsm_client_protocol::NOTPRIMARY;
369         LOG("Assigning a viewstamp");
370         cfg->get_view(vid_commit, m);
371         // assign the RPC the next viewstamp number
372         vs = myvs;
373         myvs++;
374     }
375
376     // send an invoke RPC to all slaves in the current view with a timeout of 1 second
377     LOG("Invoking slaves");
378     for (unsigned i  = 0; i < m.size(); i++) {
379         if (m[i] != myaddr) {
380             // if invoke on slave fails, return rsm_client_protocol::BUSY
381             handle h(m[i]);
382             LOG("Sending invoke to " << m[i]);
383             rpcc *cl = h.safebind();
384             if (!cl)
385                 return rsm_client_protocol::BUSY;
386             rsm_protocol::status ret;
387             int r;
388             ret = cl->call(rsm_protocol::invoke, procno, vs, req, r, rpcc::to(1000));
389             LOG("Invoke returned " << ret);
390             if (ret != rsm_protocol::OK)
391                 return rsm_client_protocol::BUSY;
392             breakpoint1();
393             partition1();
394         }
395     }
396     execute(procno, req, r);
397     last_myvs = vs;
398     return rsm_client_protocol::OK;
399 }
400
401 //
402 // The primary calls the internal invoke at each member of the
403 // replicated state machine
404 //
405 // the replica must execute requests in order (with no gaps)
406 // according to requests' seqno
407
408 rsm_protocol::status rsm::invoke(int proc, viewstamp vs, std::string req, int &dummy) {
409     LOG("rsm::invoke: procno 0x" << std::hex << proc);
410     lock ml(invoke_mutex);
411     std::vector<std::string> m;
412     std::string myaddr;
413     {
414         lock ml(rsm_mutex);
415         // check if !inviewchange
416         LOG("Checking for view change");
417         if (inviewchange)
418             return rsm_protocol::ERR;
419         // check if slave
420         LOG("Checking for slave status");
421         myaddr = cfg->myaddr();
422         if (primary == myaddr)
423             return rsm_protocol::ERR;
424         cfg->get_view(vid_commit, m);
425         if (find(m.begin(), m.end(), myaddr) == m.end())
426             return rsm_protocol::ERR;
427         // check sequence number
428         LOG("Checking sequence number");
429         if (vs != myvs)
430             return rsm_protocol::ERR;
431         myvs++;
432     }
433     std::string r;
434     execute(proc, req, r);
435     last_myvs = vs;
436     breakpoint1();
437     return rsm_protocol::OK;
438 }
439
440 /**
441  * RPC handler: Send back the local node's state to the caller
442  */
443 rsm_protocol::status rsm::transferreq(std::string src, viewstamp last, unsigned vid,
444         rsm_protocol::transferres &r) {
445     lock ml(rsm_mutex);
446     int ret = rsm_protocol::OK;
447     tprintf("transferreq from %s (%d,%d) vs (%d,%d)\n", src.c_str(),
448             last.vid, last.seqno, last_myvs.vid, last_myvs.seqno);
449     if (!insync || vid != vid_insync) {
450         return rsm_protocol::BUSY;
451     }
452     if (stf && last != last_myvs)
453         r.state = stf->marshal_state();
454     r.last = last_myvs;
455     return ret;
456 }
457
458 /**
459  * RPC handler: Inform the local node (the primary) that node m has synchronized
460  * for view vid
461  */
462 rsm_protocol::status rsm::transferdonereq(std::string m, unsigned vid, int &) {
463     lock ml(rsm_mutex);
464     if (!insync || vid != vid_insync)
465         return rsm_protocol::BUSY;
466     backups.erase(find(backups.begin(), backups.end(), m));
467     if (backups.empty())
468         sync_cond.notify_one();
469     return rsm_protocol::OK;
470 }
471
472 // a node that wants to join an RSM as a server sends a
473 // joinreq to the RSM's current primary; this is the
474 // handler for that RPC.
475 rsm_protocol::status rsm::joinreq(std::string m, viewstamp last, rsm_protocol::joinres &r) {
476     int ret = rsm_protocol::OK;
477
478     lock ml(rsm_mutex);
479     tprintf("joinreq: src %s last (%d,%d) mylast (%d,%d)\n", m.c_str(),
480             last.vid, last.seqno, last_myvs.vid, last_myvs.seqno);
481     if (cfg->ismember(m, vid_commit)) {
482         tprintf("joinreq: is still a member\n");
483         r.log = cfg->dump();
484     } else if (cfg->myaddr() != primary) {
485         tprintf("joinreq: busy\n");
486         ret = rsm_protocol::BUSY;
487     } else {
488         // We cache vid_commit to avoid adding m to a view which already contains
489         // m due to race condition
490         unsigned vid_cache = vid_commit;
491         bool succ;
492         {
493             ml.unlock();
494             succ = cfg->add(m, vid_cache);
495             ml.lock();
496         }
497         if (cfg->ismember(m, cfg->view_id())) {
498             r.log = cfg->dump();
499             tprintf("joinreq: ret %d log %s\n:", ret, r.log.c_str());
500         } else {
501             tprintf("joinreq: failed; proposer couldn't add %d\n", succ);
502             ret = rsm_protocol::BUSY;
503         }
504     }
505     return ret;
506 }
507
508 /*
509  * RPC handler: Send back all the nodes this local knows about to client
510  * so the client can switch to a different primary
511  * when it existing primary fails
512  */
513 rsm_client_protocol::status rsm::client_members(int i, std::vector<std::string> &r) {
514     std::vector<std::string> m;
515     lock ml(rsm_mutex);
516     cfg->get_view(vid_commit, m);
517     m.push_back(primary);
518     r = m;
519     tprintf("rsm::client_members return %s m %s\n", print_members(m).c_str(),
520             primary.c_str());
521     return rsm_client_protocol::OK;
522 }
523
524 // if primary is member of new view, that node is primary
525 // otherwise, the lowest number node of the previous view.
526 // caller should hold rsm_mutex
527 void rsm::set_primary(unsigned vid) {
528     std::vector<std::string> c, p;
529     cfg->get_view(vid, c);
530     cfg->get_view(vid - 1, p);
531     VERIFY (c.size() > 0);
532
533     if (isamember(primary,c)) {
534         tprintf("set_primary: primary stays %s\n", primary.c_str());
535         return;
536     }
537
538     VERIFY(p.size() > 0);
539     for (unsigned i = 0; i < p.size(); i++) {
540         if (isamember(p[i], c)) {
541             primary = p[i];
542             tprintf("set_primary: primary is %s\n", primary.c_str());
543             return;
544         }
545     }
546     VERIFY(0);
547 }
548
549 bool rsm::amiprimary() {
550     lock ml(rsm_mutex);
551     return primary == cfg->myaddr() && !inviewchange;
552 }
553
554
555 // Testing server
556
557 // Simulate partitions
558
559 // assumes caller holds rsm_mutex
560 void rsm::net_repair_wo(bool heal) {
561     std::vector<std::string> m;
562     cfg->get_view(vid_commit, m);
563     for (unsigned i  = 0; i < m.size(); i++) {
564         if (m[i] != cfg->myaddr()) {
565             handle h(m[i]);
566             tprintf("rsm::net_repair_wo: %s %d\n", m[i].c_str(), heal);
567             if (h.safebind()) h.safebind()->set_reachable(heal);
568         }
569     }
570     rsmrpc->set_reachable(heal);
571 }
572
573 rsm_test_protocol::status rsm::test_net_repairreq(int heal, int &r) {
574     lock ml(rsm_mutex);
575     tprintf("rsm::test_net_repairreq: %d (dopartition %d, partitioned %d)\n",
576             heal, dopartition, partitioned);
577     if (heal) {
578         net_repair_wo(heal);
579         partitioned = false;
580     } else {
581         dopartition = true;
582         partitioned = false;
583     }
584     r = rsm_test_protocol::OK;
585     return r;
586 }
587
588 // simulate failure at breakpoint 1 and 2
589
590 void rsm::breakpoint1() {
591     if (break1) {
592         tprintf("Dying at breakpoint 1 in rsm!\n");
593         exit(1);
594     }
595 }
596
597 void rsm::breakpoint2() {
598     if (break2) {
599         tprintf("Dying at breakpoint 2 in rsm!\n");
600         exit(1);
601     }
602 }
603
604 void rsm::partition1() {
605     if (dopartition) {
606         net_repair_wo(false);
607         dopartition = false;
608         partitioned = true;
609     }
610 }
611
612 rsm_test_protocol::status rsm::breakpointreq(int b, int &r) {
613     r = rsm_test_protocol::OK;
614     lock ml(rsm_mutex);
615     tprintf("rsm::breakpointreq: %d\n", b);
616     if (b == 1) break1 = true;
617     else if (b == 2) break2 = true;
618     else if (b == 3 || b == 4) cfg->breakpoint(b);
619     else r = rsm_test_protocol::ERR;
620     return r;
621 }