id
stringlengths
2
7
text
stringlengths
17
51.2k
title
stringclasses
1 value
c175500
%v has newer term, stopping replication", s.peer)) s.notifyAll(false) // No longer leader asyncNotifyCh(s.stepDown) }
c175501
source: t.node, target: target, firstIndex: firstIndex(args), lastIndex: lastIndex(args), commitIndex: args.LeaderCommitIndex, } if len(t.ae) < cap(t.ae) { t.ae = append(t.ae, ae) } return t.sendRPC(string(target), args, resp) }
c175502
*raft.RequestVoteResponse) error { return t.sendRPC(string(target), args, resp) }
c175503
resp *raft.InstallSnapshotResponse, data io.Reader) error { t.log.Printf("INSTALL SNAPSHOT *************************************") return errors.New("huh") }
c175504
p raft.ServerAddress) []byte { return []byte(p) }
c175505
raft.ServerAddress { return raft.ServerAddress(p) }
c175506
resp, start: time.Now(), ready: make(chan error), consumer: p.consumer, } p.work <- e return e, nil }
c175507
server := Server{ Suffrage: Voter, ID: ServerID(peer), Address: ServerAddress(peer), } configuration.Servers = append(configuration.Servers, server) } // We should only ingest valid configurations. if err := checkConfiguration(configuration); err != nil { return Configuration{}, err } return configuration, nil }
c175508
} server := Server{ Suffrage: suffrage, ID: peer.ID, Address: peer.Address, } configuration.Servers = append(configuration.Servers, server) } // We should only ingest valid configurations. if err := checkConfiguration(configuration); err != nil { return Configuration{}, err } return configuration, nil }
c175509
error) { return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport { return NewNetworkTransport(stream, maxPool, timeout, logOutput) }) }
c175510
*NetworkTransport { return NewNetworkTransportWithLogger(stream, maxPool, timeout, logger) }) }
c175511
error) { return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport { config.Stream = stream return NewNetworkTransportWithConfig(config) }) }
c175512
return net.DialTimeout("tcp", string(address), timeout) }
c175513
return t.listener.Accept() }
c175514
return t.advertise } return t.listener.Addr() }
c175515
// Update the lastApplied so we don't replay old logs r.setLastApplied(snapshot.Index) // Update the last stable snapshot info r.setLastSnapshot(snapshot.Index, snapshot.Term) // Update the configuration if snapshot.Version > 0 { r.configurations.committed = snapshot.Configuration r.configurations.committedIndex = snapshot.ConfigurationIndex r.configurations.latest = snapshot.Configuration r.configurations.latestIndex = snapshot.ConfigurationIndex } else { configuration := decodePeers(snapshot.Peers, r.trans) r.configurations.committed = configuration r.configurations.committedIndex = snapshot.Index r.configurations.latest = configuration r.configurations.latestIndex = snapshot.Index } // Success! return nil } // If we had snapshots and failed to load them, its an error if len(snapshots) > 0 { return fmt.Errorf("failed to load any existing snapshots") } return nil }
c175516
<-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.bootstrapCh <- bootstrapReq: return bootstrapReq } }
c175517
r.leaderLock.RUnlock() return leader }
c175518
{ case <-timer: return errorFuture{ErrEnqueueTimeout} case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.applyCh <- logFuture: return logFuture } }
c175519
return errorFuture{ErrEnqueueTimeout} case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.applyCh <- logFuture: return logFuture } }
c175520
return errorFuture{ErrRaftShutdown} case r.verifyCh <- verifyFuture: return verifyFuture } }
c175521
command: AddStaging, serverID: id, serverAddress: address, prevIndex: prevIndex, }, timeout) }
c175522
return errorFuture{ErrUnsupportedProtocol} } return r.requestConfigChange(configurationChangeRequest{ command: RemoveServer, serverID: id, prevIndex: prevIndex, }, timeout) }
c175523
r.setState(Shutdown) return &shutdownFuture{r} } // avoid closing transport twice return &shutdownFuture{nil} }
c175524
return future case <-r.shutdownCh: future.respond(ErrRaftShutdown) return future } }
c175525
restore: // If the restore is ingested then wait for it to complete. if err := restore.Error(); err != nil { return err } } // Apply a no-op log entry. Waiting for this allows us to wait until the // followers have gotten the restore and replicated at least this new // entry, which shows that we've also faulted and installed the // snapshot with the contents of the restore. noop := &logFuture{ log: Log{ Type: LogNoop, }, } noop.init() select { case <-timer: return ErrEnqueueTimeout case <-r.shutdownCh: return ErrRaftShutdown case r.applyCh <- noop: return noop.Error() } }
c175526
fmt.Sprintf("Node at %s [%v]", r.localAddr, r.getState()) }
c175527
r.lastContactLock.RUnlock() return last }
c175528
v ...interface{}) { a.log.Printf(s, v...) }
c175529
if rn == n { return true } } return false }
c175530
for _, node := range c.nodes { if !containsNode(r, node) { r = append(r, node) if len(r) >= n { return r } } } return r }
c175531
allAtIdx = false break } else if nodeAppliedIdx > idx { allAtIdx = false idx = nodeAppliedIdx break } } if allAtIdx { t.Logf("All nodes have appliedIndex=%d", idx) return } if time.Now().Sub(start) > maxWait { t.Fatalf("Gave up waiting for all nodes to reach raft Index %d, [currently at %v]", idx, c.appliedIndexes()) } time.Sleep(time.Millisecond * 10) } }
c175532
type %v but is %v", node, exp.Index, exp.Type, act.Type) res = false } if !bytes.Equal(exp.Data, act.Data) { t.Errorf("Node %v, Log Entry at Index %d should have data %v, but has %v", node, exp.Index, exp.Data, act.Data) res = false } return res }
c175533
:= func(req *reqSnapshotFuture) { // Is there something to snapshot? if lastIndex == 0 { req.respond(ErrNothingNewToSnapshot) return } // Start a snapshot start := time.Now() snap, err := r.fsm.Snapshot() metrics.MeasureSince([]string{"raft", "fsm", "snapshot"}, start) // Respond to the request req.index = lastIndex req.term = lastTerm req.snapshot = snap req.respond(err) } for { select { case ptr := <-r.fsmMutateCh: switch req := ptr.(type) { case *commitTuple: commit(req) case *restoreFuture: restore(req) default: panic(fmt.Errorf("bad type passed to fsmMutateCh: %#v", ptr)) } case req := <-r.fsmSnapshotCh: snapshot(req) case <-r.shutdownCh: return } } }
c175534
append(copy.Servers, c.Servers...) return }
c175535
copy.latest = c.latest.Clone() copy.latestIndex = c.latestIndex return }
c175536
id { return server.Suffrage == Voter } } return false }
c175537
{ return fmt.Errorf("Found duplicate address in configuration: %v", server.Address) } addressSet[server.Address] = true if server.Suffrage == Voter { voters++ } } if voters == 0 { return fmt.Errorf("Need at least one voter in configuration: %v", configuration) } return nil }
c175538
configuration.Servers[i] = newServer } found = true break } } if !found { configuration.Servers = append(configuration.Servers, newServer) } case DemoteVoter: for i, server := range configuration.Servers { if server.ID == change.serverID { configuration.Servers[i].Suffrage = Nonvoter break } } case RemoveServer: for i, server := range configuration.Servers { if server.ID == change.serverID { configuration.Servers = append(configuration.Servers[:i], configuration.Servers[i+1:]...) break } } case Promote: for i, server := range configuration.Servers { if server.ID == change.serverID && server.Suffrage == Staging { configuration.Servers[i].Suffrage = Voter break } } } // Make sure we didn't do something bad like remove the last voter if err := checkConfiguration(configuration); err != nil { return Configuration{}, err } return configuration, nil }
c175539
} } // Encode the entire array. buf, err := encodeMsgPack(encPeers) if err != nil { panic(fmt.Errorf("failed to encode peers: %v", err)) } return buf.Bytes() }
c175540
err)) } // Deserialize each peer. var servers []Server for _, enc := range encPeers { p := trans.DecodePeer(enc) servers = append(servers, Server{ Suffrage: Voter, ID: ServerID(p), Address: ServerAddress(p), }) } return Configuration{ Servers: servers, } }
c175541
if err != nil { panic(fmt.Errorf("failed to encode configuration: %v", err)) } return buf.Bytes() }
c175542
decodeMsgPack(buf, &configuration); err != nil { panic(fmt.Errorf("failed to decode configuration: %v", err)) } return configuration }
c175543
go func() { defer r.routinesGroup.Done() f() }() }
c175544
return max(r.lastLogIndex, r.lastSnapshotIndex) }
c175545
r.lastLogIndex, r.lastLogTerm } return r.lastSnapshotIndex, r.lastSnapshotTerm }
c175546
// for protocol version 0 starting at protocol version 2, which is // currently what we want, and in general support one version back. We // may need to revisit this policy depending on how future protocol // changes evolve. if header.ProtocolVersion < r.conf.ProtocolVersion-1 { return ErrUnsupportedProtocol } return nil }
c175547
!= leader { r.observe(LeaderObservation{leader: leader}) } }
c175548
case <-timer: return errorFuture{ErrEnqueueTimeout} case r.configurationChangeCh <- future: return future case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} } }
c175549
Enter into a sub-FSM switch r.getState() { case Follower: r.runFollower() case Candidate: r.runCandidate() case Leader: r.runLeader() } } }
c175550
} // Heartbeat failed! Transition to the candidate state lastLeader := r.Leader() r.setLeader("") if r.configurations.latestIndex == 0 { if !didWarn { r.logger.Warn("no known peers, aborting election") didWarn = true } } else if r.configurations.latestIndex == r.configurations.committedIndex && !hasVote(r.configurations.latest, r.localID) { if !didWarn { r.logger.Warn("not part of stable configuration, aborting election") didWarn = true } } else { r.logger.Warn(fmt.Sprintf("Heartbeat timeout from %q reached, starting election", lastLeader)) metrics.IncrCounter([]string{"raft", "transition", "heartbeat_timeout"}, 1) r.setState(Candidate) return } case <-r.shutdownCh: return } } }
c175551
configuration live. var entry Log if err := r.logs.GetLog(1, &entry); err != nil { panic(err) } r.setCurrentTerm(1) r.setLastLog(entry.Index, entry.Term) r.processConfigurationLogEntry(&entry) return nil }
c175552
grantedVotes++ r.logger.Debug(fmt.Sprintf("Vote granted from %s in term %v. Tally: %d", vote.voterID, vote.Term, grantedVotes)) } // Check if we've become the leader if grantedVotes >= votesNeeded { r.logger.Info(fmt.Sprintf("Election won. Tally: %d", grantedVotes)) r.setState(Leader) r.setLeader(r.localAddr) return } case c := <-r.configurationChangeCh: // Reject any operations since we are not the leader c.respond(ErrNotLeader) case a := <-r.applyCh: // Reject any operations since we are not the leader a.respond(ErrNotLeader) case v := <-r.verifyCh: // Reject any operations since we are not the leader v.respond(ErrNotLeader) case r := <-r.userRestoreCh: // Reject any restores since we are not the leader r.respond(ErrNotLeader) case c := <-r.configurationsCh: c.configurations = r.configurations.Clone() c.respond(nil) case b := <-r.bootstrapCh: b.respond(ErrCantBootstrap) case <-electionTimer: // Election failed! Restart the election. We simply return, // which will kick us back into runCandidate r.logger.Warn("Election timeout reached, restarting election") return case <-r.shutdownCh: return } } }
c175553
== r.localAddr { r.leader = "" } r.leaderLock.Unlock() // Notify that we are not the leader asyncNotifyBool(r.leaderCh, false) // Push to the notify channel if given if notify := r.conf.NotifyCh; notify != nil { select { case notify <- false: case <-r.shutdownCh: // On shutdown, make a best effort but do not block select { case notify <- false: default: } } } }() // Start a replication routine for each peer r.startStopReplication() // Dispatch a no-op log entry first. This gets this leader up to the latest // possible commit index, even in the absence of client commands. This used // to append a configuration entry instead of a noop. However, that permits // an unbounded number of uncommitted configurations in the log. We now // maintain that there exists at most one uncommitted configuration entry in // any log, so we have to do proper no-ops here. noop := &logFuture{ log: Log{ Type: LogNoop, }, } r.dispatchLogs([]*logFuture{noop}) // Sit in the leader loop until we step down r.leaderLoop() }
c175554
r.leaderState.stepDown, } r.leaderState.replState[server.ID] = s r.goFunc(func() { r.replicate(s) }) asyncNotifyCh(s.triggerCh) } } // Stop replication goroutines that need stopping for serverID, repl := range r.leaderState.replState { if inConfig[serverID] { continue } // Replicate up to lastIdx and stop r.logger.Info(fmt.Sprintf("Removed peer %v, stopping replication after %v", serverID, lastIdx)) repl.stopCh <- lastIdx close(repl.stopCh) delete(r.leaderState.replState, serverID) } }
c175555
noop) in this term // https://groups.google.com/forum/#!msg/raft-dev/t4xj6dJTP6E/d2D9LrWRza8J if r.configurations.latestIndex == r.configurations.committedIndex && r.getCommitIndex() >= r.leaderState.commitment.startIndex { return r.configurationChangeCh } return nil }
c175556
= struct{}{} // Trigger immediate heartbeats for _, repl := range r.leaderState.replState { repl.notifyLock.Lock() repl.notify[v] = struct{}{} repl.notifyLock.Unlock() asyncNotifyCh(repl.notifyCh) } }
c175557
r.logger.Debug(fmt.Sprintf("Failed to contact %v in %v", peer, diff)) } } metrics.AddSample([]string{"raft", "leader", "lastContact"}, float32(diff/time.Millisecond)) } // Verify we can contact a quorum quorum := r.quorumSize() if contacted < quorum { r.logger.Warn("Failed to contact quorum of nodes, stepping down") r.setState(Follower) metrics.IncrCounter([]string{"raft", "transition", "leader_lease_timeout"}, 1) } return maxDiff }
c175558
} if err := sink.Close(); err != nil { return fmt.Errorf("failed to close snapshot: %v", err) } r.logger.Info(fmt.Sprintf("Copied %d bytes to local snapshot", n)) // Restore the snapshot into the FSM. If this fails we are in a // bad state so we panic to take ourselves out. fsm := &restoreFuture{ID: sink.ID()} fsm.init() select { case r.fsmMutateCh <- fsm: case <-r.shutdownCh: return ErrRaftShutdown } if err := fsm.Error(); err != nil { panic(fmt.Errorf("failed to restore snapshot: %v", err)) } // We set the last log so it looks like we've stored the empty // index we burned. The last applied is set because we made the // FSM take the snapshot state, and we store the last snapshot // in the stable store since we created a snapshot as part of // this process. r.setLastLog(lastIndex, term) r.setLastApplied(lastIndex) r.setLastSnapshot(lastIndex, term) r.logger.Info(fmt.Sprintf("Restored user snapshot (index %d)", lastIndex)) return nil }
c175559
future.log = Log{ Type: LogRemovePeerDeprecated, Data: encodePeers(configuration, r.trans), } } else { future.log = Log{ Type: LogConfiguration, Data: encodeConfiguration(configuration), } } r.dispatchLogs([]*logFuture{&future.logFuture}) index := future.Index() r.configurations.latest = configuration r.configurations.latestIndex = index r.leaderState.commitment.setConfiguration(configuration) r.startStopReplication() }
c175560
r.logger.Error(fmt.Sprintf("Failed to commit logs: %v", err)) for _, applyLog := range applyLogs { applyLog.respond(err) } r.setState(Follower) return } r.leaderState.commitment.match(r.localID, lastIndex) // Update the last log since it's on disk now r.setLastLog(lastIndex, term) // Notify the replicators of the new log for _, f := range r.leaderState.replState { asyncNotifyCh(f.triggerCh) } }
c175561
r.processLog(&future.log, future) } else { l := new(Log) if err := r.logs.GetLog(idx, l); err != nil { r.logger.Error(fmt.Sprintf("Failed to get log at %d: %v", idx, err)) panic(err) } r.processLog(l, nil) } // Update the lastApplied index and term r.setLastApplied(idx) } }
c175562
application is done return case LogConfiguration: case LogAddPeerDeprecated: case LogRemovePeerDeprecated: case LogNoop: // Ignore the no-op default: panic(fmt.Errorf("unrecognized log type: %#v", l)) } // Invoke the future if given if future != nil { future.respond(nil) } }
c175563
cmd) case *RequestVoteRequest: r.requestVote(rpc, cmd) case *InstallSnapshotRequest: r.installSnapshot(rpc, cmd) default: r.logger.Error(fmt.Sprintf("Got unexpected command: %#v", rpc.Command)) rpc.Respond(nil, fmt.Errorf("unexpected command")) } }
c175564
switch cmd := rpc.Command.(type) { case *AppendEntriesRequest: r.appendEntries(rpc, cmd) default: r.logger.Error(fmt.Sprintf("Expected heartbeat, got command: %#v", rpc.Command)) rpc.Respond(nil, fmt.Errorf("unexpected command")) } }
c175565
r.lastContact = time.Now() r.lastContactLock.Unlock() }
c175566
err != nil { return err } if err := r.stable.Set(keyLastVoteCand, candidate); err != nil { return err } return nil }
c175567
t); err != nil { panic(fmt.Errorf("failed to save current term: %v", err)) } r.raftState.setCurrentTerm(t) }
c175568
:= r.raftState.getState() r.raftState.setState(state) if oldState != state { r.observe(state) } }
c175569
defer c.Unlock() return c.commitIndex }
c175570
:= matched[(len(matched)-1)/2] if quorumMatchIndex > c.commitIndex && quorumMatchIndex >= c.startIndex { c.commitIndex = quorumMatchIndex asyncNotifyCh(c.commitCh) } }
c175571
extra := (time.Duration(rand.Int63()) % minVal) return time.After(minVal + extra) }
c175572
return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", buf[0:4], buf[4:6], buf[6:8], buf[8:10], buf[10:16]) }
c175573
dec := codec.NewDecoder(r, &hd) return dec.Decode(out) }
c175574
hd := codec.MsgpackHandle{} enc := codec.NewEncoder(buf, &hd) err := enc.Encode(in) return buf, err }
c175575
{ power := min(round, limit) for power > 2 { base *= 2 power-- } return base }
c175576
:= &applySource{seed: int64(h.Sum32())} s.reset() return s }
c175577
a.rnd = rand.New(rand.NewSource(a.seed)) }
c175578
50 * time.Millisecond, MaxAppendEntries: 64, ShutdownOnRemove: true, TrailingLogs: 10240, SnapshotInterval: 120 * time.Second, SnapshotThreshold: 8192, LeaderLeaseTimeout: 500 * time.Millisecond, LogLevel: "DEBUG", } }
c175579
return fmt.Errorf("Snapshot interval is too low") } if config.LeaderLeaseTimeout < 5*time.Millisecond { return fmt.Errorf("Leader lease timeout is too low") } if config.LeaderLeaseTimeout > config.HeartbeatTimeout { return fmt.Errorf("Leader lease timeout cannot be larger than heartbeat timeout") } if config.ElectionTimeout < config.HeartbeatTimeout { return fmt.Errorf("Election timeout must be equal or greater than Heartbeat Timeout") } return nil }
c175580
nil { r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err)) } else { future.opener = func() (*SnapshotMeta, io.ReadCloser, error) { return r.snapshots.Open(id) } } future.respond(err) case <-r.shutdownCh: return } } }
c175581
return false } // Compare the delta to the threshold delta := lastIdx - lastSnap return delta >= r.conf.SnapshotThreshold }
c175582
:= r.snapshots.Create(version, snapReq.index, snapReq.term, committed, committedIndex, r.trans) if err != nil { return "", fmt.Errorf("failed to create snapshot: %v", err) } metrics.MeasureSince([]string{"raft", "snapshot", "create"}, start) // Try to persist the snapshot. start = time.Now() if err := snapReq.snapshot.Persist(sink); err != nil { sink.Cancel() return "", fmt.Errorf("failed to persist snapshot: %v", err) } metrics.MeasureSince([]string{"raft", "snapshot", "persist"}, start) // Close and check for error. if err := sink.Close(); err != nil { return "", fmt.Errorf("failed to close snapshot: %v", err) } // Update the last stable snapshot info. r.setLastSnapshot(snapReq.index, snapReq.term) // Compact the logs. if err := r.compactLogs(snapReq.index); err != nil { return "", err } r.logger.Info(fmt.Sprintf("Snapshot to %d complete", snapReq.index)) return sink.ID(), nil }
c175583
least `TrailingLogs` entries, but does not allow logs // after the snapshot to be removed. maxLog := min(snapIdx, lastLogIdx-r.conf.TrailingLogs) // Log this r.logger.Info(fmt.Sprintf("Compacting logs from %d to %d", minLog, maxLog)) // Compact the logs if err := r.logs.DeleteRange(minLog, maxLog); err != nil { return fmt.Errorf("log compaction failed: %v", err) } return nil }
c175584
App: r.App, }, }) if err != nil { return err } b, err := ioutil.ReadFile("webpack.config.js") if err != nil { return err } if string(b) == bb.String() { return nil } if !ask("Your webpack.config.js file is different from the latest Buffalo template.\nWould you like to replace yours with the latest template?") { fmt.Println("\tSkipping webpack.config.js") return nil } wf, err := os.Create("webpack.config.js") if err != nil { return err } _, err = wf.Write(bb.Bytes()) if err != nil { return err } return wf.Close() }
c175585
if p == "bzr" { // Ensure Bazaar is as quiet as Git args = append(args, "-q") } g.Command(exec.Command(p, args...)) g.Command(exec.Command(p, "commit", "-q", "-m", "Initial Commit")) return g, nil }
c175586
if err != nil { return nil, err } return &Listener{ Server: &http.Server{}, Listener: listener, }, nil }
c175587
if eh, ok := e[0]; ok { return eh } return defaultErrorHandler }
c175588
} err = err events.EmitError(events.ErrPanic, err, map[string]interface{}{ "context": c, "app": a, }, ) eh := a.ErrorHandlers.Get(500) eh(500, err, c) } }() return next(c) } }
c175589
filepath.Join(d, "_"+f) name = fixExtension(name, ct) return s.TemplatesBox.FindString(name) }
c175590
ok := opts.TemplateEngines["md"]; !ok { opts.TemplateEngines["md"] = MDTemplateEngine } if _, ok := opts.TemplateEngines["tmpl"]; !ok { opts.TemplateEngines["tmpl"] = GoTemplateEngine } if opts.DefaultContentType == "" { opts.DefaultContentType = "text/html; charset=utf-8" } e := &Engine{ Options: opts, } return e }
c175591
{ mw := &messageWriter{w: w} mw.writeMessage(m) return mw.n, mw.err }
c175592
gm.SetHeader("Bcc", message.Bcc...) sm.addBodies(message, gm) sm.addAttachments(message, gm) for field, value := range message.Headers { gm.SetHeader(field, value) } err := sm.Dialer.DialAndSend(gm) if err != nil { return err } return nil }
c175593
Port: iport, } if user != "" { dialer.Username = user dialer.Password = password } return SMTPSender{ Dialer: dialer, }, nil }
c175594
return d.Params().Get(key) }
c175595
d.data[key] = value d.moot.Unlock() }
c175596
{ d.moot.RLock() defer d.moot.RUnlock() if v, ok := d.data[k]; ok { return v } } return d.Context.Value(key) }
c175597
d.Value(strings.TrimSuffix(url, "()")).(RouteHelperFunc) if !ok { return fmt.Errorf("could not find a route helper named %s", url) } url, err := h(m) if err != nil { return err } http.Redirect(d.Response(), d.Request(), string(url), status) return nil } if len(args) > 0 { url = fmt.Sprintf(url, args...) } http.Redirect(d.Response(), d.Request(), url, status) return nil }
c175598
bf := binding.File{ File: f, FileHeader: h, } if err != nil { return bf, err } return bf, nil }
c175599
} if _, err := json.Marshal(v); err == nil { // it can be marshaled, so add it: m[k] = v } } return json.Marshal(m) }