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