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