raft理论与实践[4]-lab2b

2020-02-11  本文已影响0人  唯识相链2

准备工作

执行日志

func Make(peers []*labrpc.ClientEnd, me int,
    persister *Persister, applyCh chan ApplyMsg) *Raft {
    ...
    go rf.applyLogEntryDaemon() // start apply log
    DPrintf("[%d-%s]: newborn election(%s) heartbeat(%s) term(%d) voted(%d)\n",
        rf.me, rf, rf.electionTimeout, rf.heartbeatInterval, rf.CurrentTerm, rf.VotedFor)
    return rf
}

// applyLogEntryDaemon exit when shutdown channel is closed
func (rf *Raft) applyLogEntryDaemon() {
    for {
        var logs []LogEntry
        // wait
        rf.mu.Lock()
        for rf.lastApplied == rf.commitIndex {
            rf.commitCond.Wait()
            select {
            case <-rf.shutdownCh:
                rf.mu.Unlock()
                DPrintf("[%d-%s]: peer %d is shutting down apply log entry to client daemon.\n", rf.me, rf, rf.me)
                close(rf.applyCh)
                return
            default:
            }
        }
        last, cur := rf.lastApplied, rf.commitIndex
        if last < cur {
            rf.lastApplied = rf.commitIndex
            logs = make([]LogEntry, cur-last)
            copy(logs, rf.Logs[last+1:cur+1])
        }
        rf.mu.Unlock()
        for i := 0; i < cur-last; i++ {
            // current command is replicated, ignore nil command
            reply := ApplyMsg{
                CommandIndex: last + i + 1,
                Command:      logs[i].Command,
                CommandValid: true,
            }
            // reply to outer service
            // DPrintf("[%d-%s]: peer %d apply %v to client.\n", rf.me, rf, rf.me)
            DPrintf("[%d-%s]: peer %d apply to client.\n", rf.me, rf, rf.me)
            // Note: must in the same goroutine, or may result in out of order apply
            rf.applyCh <- reply
        }
    }
}

func (rf *Raft) Start(command interface{}) (int, int, bool) {
    index := -1
    term := 0
    isLeader := false

    // Your code here (2B).
    select {
    case <-rf.shutdownCh:
        return -1, 0, false
    default:
        rf.mu.Lock()
        defer rf.mu.Unlock()
        // Your code here (2B).
        if rf.state == Leader {
            log := LogEntry{rf.CurrentTerm, command}
            rf.Logs = append(rf.Logs, log)

            index = len(rf.Logs) - 1
            term = rf.CurrentTerm
            isLeader = true

            //DPrintf("[%d-%s]: client add new entry (%d-%v), logs: %v\n", rf.me, rf, index, command, rf.logs)
            DPrintf("[%d-%s]: client add new entry (%d)\n", rf.me, rf, index)
            //DPrintf("[%d-%s]: client add new entry (%d-%v)\n", rf.me, rf, index, command)

            // only update leader
            rf.nextIndex[rf.me] = index + 1
            rf.matchIndex[rf.me] = index
        }
    }

    return index, term, isLeader
}

func (rf *Raft) consistencyCheck(n int) {
    rf.mu.Lock()
    defer rf.mu.Unlock()
    pre := max(1,rf.nextIndex[n])
    var args = AppendEntriesArgs{
        Term:         rf.CurrentTerm,
        LeaderID:     rf.me,
        PrevLogIndex: pre - 1,
        PrevLogTerm:  rf.Logs[pre - 1].Term,
        Entries:      nil,
        LeaderCommit: rf.commitIndex,
    }

    if rf.nextIndex[n] < len(rf.Logs){
        args.Entries = append(args.Entries, rf.Logs[pre:]...)
    }

    go func() {
        DPrintf("[%d-%s]: consistency Check to peer %d.\n", rf.me, rf, n)
        var reply AppendEntriesReply
        if rf.sendAppendEntries(n, &args, &reply) {
            rf.consistencyCheckReplyHandler(n, &reply)
        }
    }()
}

type AppendEntriesReply struct {
    CurrentTerm int  // currentTerm, for leader to update itself
    Success     bool // true if follower contained entry matching prevLogIndex and prevLogTerm
    // extra info for heartbeat from follower
    ConflictTerm int // term of the conflicting entry
    FirstIndex   int // the first index it stores for ConflictTerm
}

// AppendEntries handler, including heartbeat, must backup quickly
func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) {
    ...
    preLogIdx, preLogTerm := 0, 0
    if args.PrevLogIndex < len(rf.Logs) {
        preLogIdx = args.PrevLogIndex
        preLogTerm = rf.Logs[preLogIdx].Term
    }

    // last log is match
    if preLogIdx == args.PrevLogIndex && preLogTerm == args.PrevLogTerm {
        reply.Success = true
        // truncate to known match
        rf.Logs = rf.Logs[:preLogIdx+1]
        rf.Logs = append(rf.Logs, args.Entries...)
        var last = len(rf.Logs) - 1

        // min(leaderCommit, index of last new entry)
        if args.LeaderCommit > rf.commitIndex {
            rf.commitIndex = min(args.LeaderCommit, last)
            // signal possible update commit index
            go func() { rf.commitCond.Broadcast() }()
        }
        // tell leader to update matched index
        reply.ConflictTerm = rf.Logs[last].Term
        reply.FirstIndex = last

        if len(args.Entries) > 0 {
            DPrintf("[%d-%s]: AE success from leader %d (%d cmd @ %d), commit index: l->%d, f->%d.\n",
                rf.me, rf, args.LeaderID, len(args.Entries), preLogIdx+1, args.LeaderCommit, rf.commitIndex)
        } else {
            DPrintf("[%d-%s]: <heartbeat> current logs: %v\n", rf.me, rf, rf.Logs)
        }
    } else {
        reply.Success = false

        // extra info for restore missing entries quickly: from original paper and lecture note
        // if follower rejects, includes this in reply:
        //
        // the follower's term in the conflicting entry
        // the index of follower's first entry with that term
        //
        // if leader knows about the conflicting term:
        //      move nextIndex[i] back to leader's last entry for the conflicting term
        // else:
        //      move nextIndex[i] back to follower's first index
        var first = 1
        reply.ConflictTerm = preLogTerm
        if reply.ConflictTerm == 0 {
            // which means leader has more logs or follower has no log at all
            first = len(rf.Logs)
            reply.ConflictTerm = rf.Logs[first-1].Term
        } else {
            i := preLogIdx
            // term的第一个log entry
            for ; i > 0; i-- {
                if rf.Logs[i].Term != preLogTerm {
                    first = i + 1
                    break
                }
            }
        }
        reply.FirstIndex = first
        if len(rf.Logs) <= args.PrevLogIndex {
            DPrintf("[%d-%s]: AE failed from leader %d, leader has more logs (%d > %d), reply: %d - %d.\n",
                rf.me, rf, args.LeaderID, args.PrevLogIndex, len(rf.Logs)-1, reply.ConflictTerm,
                reply.FirstIndex)
        } else {
            DPrintf("[%d-%s]: AE failed from leader %d, pre idx/term mismatch (%d != %d, %d != %d).\n",
                rf.me, rf, args.LeaderID, args.PrevLogIndex, preLogIdx, args.PrevLogTerm, preLogTerm)
        }
    }
}

func (rf *Raft) consistencyCheckReplyHandler(n int, reply *AppendEntriesReply) {
    rf.mu.Lock()
    defer rf.mu.Unlock()

    if rf.state != Leader {
        return
    }
    if reply.Success {
        // RPC and consistency check successful
        rf.matchIndex[n] = reply.FirstIndex
        rf.nextIndex[n] = rf.matchIndex[n] + 1
        rf.updateCommitIndex() // try to update commitIndex
    } else {
        // found a new leader? turn to follower
        if rf.state == Leader && reply.CurrentTerm > rf.CurrentTerm {
            rf.turnToFollow()
            rf.resetTimer <- struct{}{}
            DPrintf("[%d-%s]: leader %d found new term (heartbeat resp from peer %d), turn to follower.",
                rf.me, rf, rf.me, n)
            return
        }

        // Does leader know conflicting term?
        var know, lastIndex = false, 0
        if reply.ConflictTerm != 0 {
            for i := len(rf.Logs) - 1; i > 0; i-- {
                if rf.Logs[i].Term == reply.ConflictTerm {
                    know = true
                    lastIndex = i
                    DPrintf("[%d-%s]: leader %d have entry %d is the last entry in term %d.",
                        rf.me, rf, rf.me, i, reply.ConflictTerm)
                    break
                }
            }
            if know {
                rf.nextIndex[n] = min(lastIndex, reply.FirstIndex)
            } else {
                rf.nextIndex[n] = reply.FirstIndex
            }
        } else {
            rf.nextIndex[n] = reply.FirstIndex
        }
        rf.nextIndex[n] = min(rf.nextIndex[n], len(rf.Logs))
        DPrintf("[%d-%s]: nextIndex for peer %d  => %d.\n",
            rf.me, rf, n, rf.nextIndex[n])
    }
}

  S1: 1 2     1 2 4
  S2: 1 2     1 2
  S3: 1   --> 1 2
  S4: 1       1
  S5: 1       1 3

// updateCommitIndex find new commit id, must be called when hold lock
func (rf *Raft) updateCommitIndex() {
    match := make([]int, len(rf.matchIndex))
    copy(match, rf.matchIndex)
    sort.Ints(match)

    DPrintf("[%d-%s]: leader %d try to update commit index: %v @ term %d.\n",
        rf.me, rf, rf.me, rf.matchIndex, rf.CurrentTerm)

    target := match[len(rf.peers)/2]
    if rf.commitIndex < target {
        //fmt.Println("target:",target,match)
        if rf.Logs[target].Term == rf.CurrentTerm {
            //DPrintf("[%d-%s]: leader %d update commit index %d -> %d @ term %d command:%v\n",
            //  rf.me, rf, rf.me, rf.commitIndex, target, rf.CurrentTerm,rf.Logs[target].Command)

            DPrintf("[%d-%s]: leader %d update commit index %d -> %d @ term %d\n",
                rf.me, rf, rf.me, rf.commitIndex, target, rf.CurrentTerm)

            rf.commitIndex = target
            go func() { rf.commitCond.Broadcast() }()
        } else {
            DPrintf("[%d-%s]: leader %d update commit index %d failed (log term %d != current Term %d)\n",
                rf.me, rf, rf.me, rf.commitIndex, rf.Logs[target].Term, rf.CurrentTerm)
        }
    }
}

参考

上一篇下一篇

猜你喜欢

热点阅读