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