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