_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q175500
handleStaleTerm
test
func (r *Raft) handleStaleTerm(s *followerReplication) { r.logger.Error(fmt.Sprintf("peer %v has newer term, stopping replication", s.peer)) s.notifyAll(false) // No longer leader asyncNotifyCh(s.stepDown) }
go
{ "resource": "" }
q175501
AppendEntries
test
func (t *transport) AppendEntries(id raft.ServerID, target raft.ServerAddress, args *raft.AppendEntriesRequest, resp *raft.AppendEntriesResponse) error { ae := appendEntries{ source: t.node, target: target, firstIndex: firstIndex(args), lastIndex: lastIndex(args), commitIndex: args.LeaderCommitI...
go
{ "resource": "" }
q175502
RequestVote
test
func (t *transport) RequestVote(id raft.ServerID, target raft.ServerAddress, args *raft.RequestVoteRequest, resp *raft.RequestVoteResponse) error { return t.sendRPC(string(target), args, resp) }
go
{ "resource": "" }
q175503
InstallSnapshot
test
func (t *transport) InstallSnapshot(id raft.ServerID, target raft.ServerAddress, args *raft.InstallSnapshotRequest, resp *raft.InstallSnapshotResponse, data io.Reader) error { t.log.Printf("INSTALL SNAPSHOT *************************************") return errors.New("huh") }
go
{ "resource": "" }
q175504
EncodePeer
test
func (t *transport) EncodePeer(id raft.ServerID, p raft.ServerAddress) []byte { return []byte(p) }
go
{ "resource": "" }
q175505
DecodePeer
test
func (t *transport) DecodePeer(p []byte) raft.ServerAddress { return raft.ServerAddress(p) }
go
{ "resource": "" }
q175506
AppendEntries
test
func (p *pipeline) AppendEntries(args *raft.AppendEntriesRequest, resp *raft.AppendEntriesResponse) (raft.AppendFuture, error) { e := &appendEntry{ req: args, res: resp, start: time.Now(), ready: make(chan error), consumer: p.consumer, } p.work <- e return e, nil }
go
{ "resource": "" }
q175507
ReadPeersJSON
test
func ReadPeersJSON(path string) (Configuration, error) { // Read in the file. buf, err := ioutil.ReadFile(path) if err != nil { return Configuration{}, err } // Parse it as JSON. var peers []string dec := json.NewDecoder(bytes.NewReader(buf)) if err := dec.Decode(&peers); err != nil { return Configuration{...
go
{ "resource": "" }
q175508
ReadConfigJSON
test
func ReadConfigJSON(path string) (Configuration, error) { // Read in the file. buf, err := ioutil.ReadFile(path) if err != nil { return Configuration{}, err } // Parse it as JSON. var peers []configEntry dec := json.NewDecoder(bytes.NewReader(buf)) if err := dec.Decode(&peers); err != nil { return Configur...
go
{ "resource": "" }
q175509
NewTCPTransport
test
func NewTCPTransport( bindAddr string, advertise net.Addr, maxPool int, timeout time.Duration, logOutput io.Writer, ) (*NetworkTransport, error) { return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport { return NewNetworkTransport(stream, maxPool, timeout, logOutput) }) }
go
{ "resource": "" }
q175510
NewTCPTransportWithLogger
test
func NewTCPTransportWithLogger( bindAddr string, advertise net.Addr, maxPool int, timeout time.Duration, logger *log.Logger, ) (*NetworkTransport, error) { return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport { return NewNetworkTransportWithLogger(stream, maxPool, timeout, logg...
go
{ "resource": "" }
q175511
NewTCPTransportWithConfig
test
func NewTCPTransportWithConfig( bindAddr string, advertise net.Addr, config *NetworkTransportConfig, ) (*NetworkTransport, error) { return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport { config.Stream = stream return NewNetworkTransportWithConfig(config) }) }
go
{ "resource": "" }
q175512
Dial
test
func (t *TCPStreamLayer) Dial(address ServerAddress, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("tcp", string(address), timeout) }
go
{ "resource": "" }
q175513
Accept
test
func (t *TCPStreamLayer) Accept() (c net.Conn, err error) { return t.listener.Accept() }
go
{ "resource": "" }
q175514
Addr
test
func (t *TCPStreamLayer) Addr() net.Addr { // Use an advertise addr if provided if t.advertise != nil { return t.advertise } return t.listener.Addr() }
go
{ "resource": "" }
q175515
restoreSnapshot
test
func (r *Raft) restoreSnapshot() error { snapshots, err := r.snapshots.List() if err != nil { r.logger.Error(fmt.Sprintf("Failed to list snapshots: %v", err)) return err } // Try to load in order of newest to oldest for _, snapshot := range snapshots { _, source, err := r.snapshots.Open(snapshot.ID) if er...
go
{ "resource": "" }
q175516
BootstrapCluster
test
func (r *Raft) BootstrapCluster(configuration Configuration) Future { bootstrapReq := &bootstrapFuture{} bootstrapReq.init() bootstrapReq.configuration = configuration select { case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.bootstrapCh <- bootstrapReq: return bootstrapReq } }
go
{ "resource": "" }
q175517
Leader
test
func (r *Raft) Leader() ServerAddress { r.leaderLock.RLock() leader := r.leader r.leaderLock.RUnlock() return leader }
go
{ "resource": "" }
q175518
Apply
test
func (r *Raft) Apply(cmd []byte, timeout time.Duration) ApplyFuture { metrics.IncrCounter([]string{"raft", "apply"}, 1) var timer <-chan time.Time if timeout > 0 { timer = time.After(timeout) } // Create a log future, no index or term yet logFuture := &logFuture{ log: Log{ Type: LogCommand, Data: cmd, ...
go
{ "resource": "" }
q175519
Barrier
test
func (r *Raft) Barrier(timeout time.Duration) Future { metrics.IncrCounter([]string{"raft", "barrier"}, 1) var timer <-chan time.Time if timeout > 0 { timer = time.After(timeout) } // Create a log future, no index or term yet logFuture := &logFuture{ log: Log{ Type: LogBarrier, }, } logFuture.init() ...
go
{ "resource": "" }
q175520
VerifyLeader
test
func (r *Raft) VerifyLeader() Future { metrics.IncrCounter([]string{"raft", "verify_leader"}, 1) verifyFuture := &verifyFuture{} verifyFuture.init() select { case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.verifyCh <- verifyFuture: return verifyFuture } }
go
{ "resource": "" }
q175521
AddVoter
test
func (r *Raft) AddVoter(id ServerID, address ServerAddress, prevIndex uint64, timeout time.Duration) IndexFuture { if r.protocolVersion < 2 { return errorFuture{ErrUnsupportedProtocol} } return r.requestConfigChange(configurationChangeRequest{ command: AddStaging, serverID: id, serverAddress: add...
go
{ "resource": "" }
q175522
RemoveServer
test
func (r *Raft) RemoveServer(id ServerID, prevIndex uint64, timeout time.Duration) IndexFuture { if r.protocolVersion < 2 { return errorFuture{ErrUnsupportedProtocol} } return r.requestConfigChange(configurationChangeRequest{ command: RemoveServer, serverID: id, prevIndex: prevIndex, }, timeout) }
go
{ "resource": "" }
q175523
Shutdown
test
func (r *Raft) Shutdown() Future { r.shutdownLock.Lock() defer r.shutdownLock.Unlock() if !r.shutdown { close(r.shutdownCh) r.shutdown = true r.setState(Shutdown) return &shutdownFuture{r} } // avoid closing transport twice return &shutdownFuture{nil} }
go
{ "resource": "" }
q175524
Snapshot
test
func (r *Raft) Snapshot() SnapshotFuture { future := &userSnapshotFuture{} future.init() select { case r.userSnapshotCh <- future: return future case <-r.shutdownCh: future.respond(ErrRaftShutdown) return future } }
go
{ "resource": "" }
q175525
Restore
test
func (r *Raft) Restore(meta *SnapshotMeta, reader io.Reader, timeout time.Duration) error { metrics.IncrCounter([]string{"raft", "restore"}, 1) var timer <-chan time.Time if timeout > 0 { timer = time.After(timeout) } // Perform the restore. restore := &userRestoreFuture{ meta: meta, reader: reader, } ...
go
{ "resource": "" }
q175526
String
test
func (r *Raft) String() string { return fmt.Sprintf("Node at %s [%v]", r.localAddr, r.getState()) }
go
{ "resource": "" }
q175527
LastContact
test
func (r *Raft) LastContact() time.Time { r.lastContactLock.RLock() last := r.lastContact r.lastContactLock.RUnlock() return last }
go
{ "resource": "" }
q175528
Logf
test
func (a *LoggerAdapter) Logf(s string, v ...interface{}) { a.log.Printf(s, v...) }
go
{ "resource": "" }
q175529
containsNode
test
func containsNode(nodes []*raftNode, n *raftNode) bool { for _, rn := range nodes { if rn == n { return true } } return false }
go
{ "resource": "" }
q175530
LeaderPlus
test
func (c *cluster) LeaderPlus(n int) []*raftNode { r := make([]*raftNode, 0, n+1) ldr := c.Leader(time.Second) if ldr != nil { r = append(r, ldr) } if len(r) >= n { return r } for _, node := range c.nodes { if !containsNode(r, node) { r = append(r, node) if len(r) >= n { return r } } } retu...
go
{ "resource": "" }
q175531
WaitTilUptoDate
test
func (c *cluster) WaitTilUptoDate(t *testing.T, maxWait time.Duration) { idx := c.lastApplySuccess.Index() start := time.Now() for true { allAtIdx := true for i := 0; i < len(c.nodes); i++ { nodeAppliedIdx := c.nodes[i].raft.AppliedIndex() if nodeAppliedIdx < idx { allAtIdx = false break } else ...
go
{ "resource": "" }
q175532
assertLogEntryEqual
test
func assertLogEntryEqual(t *testing.T, node string, exp *raft.Log, act *raft.Log) bool { res := true if exp.Term != act.Term { t.Errorf("Log Entry at Index %d for node %v has mismatched terms %d/%d", exp.Index, node, exp.Term, act.Term) res = false } if exp.Index != act.Index { t.Errorf("Node %v, Log Entry sh...
go
{ "resource": "" }
q175533
runFSM
test
func (r *Raft) runFSM() { var lastIndex, lastTerm uint64 commit := func(req *commitTuple) { // Apply the log if a command var resp interface{} if req.log.Type == LogCommand { start := time.Now() resp = r.fsm.Apply(req.log) metrics.MeasureSince([]string{"raft", "fsm", "apply"}, start) } // Update ...
go
{ "resource": "" }
q175534
Clone
test
func (c *Configuration) Clone() (copy Configuration) { copy.Servers = append(copy.Servers, c.Servers...) return }
go
{ "resource": "" }
q175535
Clone
test
func (c *configurations) Clone() (copy configurations) { copy.committed = c.committed.Clone() copy.committedIndex = c.committedIndex copy.latest = c.latest.Clone() copy.latestIndex = c.latestIndex return }
go
{ "resource": "" }
q175536
hasVote
test
func hasVote(configuration Configuration, id ServerID) bool { for _, server := range configuration.Servers { if server.ID == id { return server.Suffrage == Voter } } return false }
go
{ "resource": "" }
q175537
checkConfiguration
test
func checkConfiguration(configuration Configuration) error { idSet := make(map[ServerID]bool) addressSet := make(map[ServerAddress]bool) var voters int for _, server := range configuration.Servers { if server.ID == "" { return fmt.Errorf("Empty ID in configuration: %v", configuration) } if server.Address =...
go
{ "resource": "" }
q175538
nextConfiguration
test
func nextConfiguration(current Configuration, currentIndex uint64, change configurationChangeRequest) (Configuration, error) { if change.prevIndex > 0 && change.prevIndex != currentIndex { return Configuration{}, fmt.Errorf("Configuration changed since %v (latest is %v)", change.prevIndex, currentIndex) } configu...
go
{ "resource": "" }
q175539
encodePeers
test
func encodePeers(configuration Configuration, trans Transport) []byte { // Gather up all the voters, other suffrage types are not supported by // this data format. var encPeers [][]byte for _, server := range configuration.Servers { if server.Suffrage == Voter { encPeers = append(encPeers, trans.EncodePeer(ser...
go
{ "resource": "" }
q175540
decodePeers
test
func decodePeers(buf []byte, trans Transport) Configuration { // Decode the buffer first. var encPeers [][]byte if err := decodeMsgPack(buf, &encPeers); err != nil { panic(fmt.Errorf("failed to decode peers: %v", err)) } // Deserialize each peer. var servers []Server for _, enc := range encPeers { p := tran...
go
{ "resource": "" }
q175541
encodeConfiguration
test
func encodeConfiguration(configuration Configuration) []byte { buf, err := encodeMsgPack(configuration) if err != nil { panic(fmt.Errorf("failed to encode configuration: %v", err)) } return buf.Bytes() }
go
{ "resource": "" }
q175542
decodeConfiguration
test
func decodeConfiguration(buf []byte) Configuration { var configuration Configuration if err := decodeMsgPack(buf, &configuration); err != nil { panic(fmt.Errorf("failed to decode configuration: %v", err)) } return configuration }
go
{ "resource": "" }
q175543
goFunc
test
func (r *raftState) goFunc(f func()) { r.routinesGroup.Add(1) go func() { defer r.routinesGroup.Done() f() }() }
go
{ "resource": "" }
q175544
getLastIndex
test
func (r *raftState) getLastIndex() uint64 { r.lastLock.Lock() defer r.lastLock.Unlock() return max(r.lastLogIndex, r.lastSnapshotIndex) }
go
{ "resource": "" }
q175545
getLastEntry
test
func (r *raftState) getLastEntry() (uint64, uint64) { r.lastLock.Lock() defer r.lastLock.Unlock() if r.lastLogIndex >= r.lastSnapshotIndex { return r.lastLogIndex, r.lastLogTerm } return r.lastSnapshotIndex, r.lastSnapshotTerm }
go
{ "resource": "" }
q175546
checkRPCHeader
test
func (r *Raft) checkRPCHeader(rpc RPC) error { // Get the header off the RPC message. wh, ok := rpc.Command.(WithRPCHeader) if !ok { return fmt.Errorf("RPC does not have a header") } header := wh.GetRPCHeader() // First check is to just make sure the code can understand the // protocol at all. if header.Prot...
go
{ "resource": "" }
q175547
setLeader
test
func (r *Raft) setLeader(leader ServerAddress) { r.leaderLock.Lock() oldLeader := r.leader r.leader = leader r.leaderLock.Unlock() if oldLeader != leader { r.observe(LeaderObservation{leader: leader}) } }
go
{ "resource": "" }
q175548
requestConfigChange
test
func (r *Raft) requestConfigChange(req configurationChangeRequest, timeout time.Duration) IndexFuture { var timer <-chan time.Time if timeout > 0 { timer = time.After(timeout) } future := &configurationChangeFuture{ req: req, } future.init() select { case <-timer: return errorFuture{ErrEnqueueTimeout} ca...
go
{ "resource": "" }
q175549
run
test
func (r *Raft) run() { for { // Check if we are doing a shutdown select { case <-r.shutdownCh: // Clear the leader to prevent forwarding r.setLeader("") return default: } // Enter into a sub-FSM switch r.getState() { case Follower: r.runFollower() case Candidate: r.runCandidate() ca...
go
{ "resource": "" }
q175550
runFollower
test
func (r *Raft) runFollower() { didWarn := false r.logger.Info(fmt.Sprintf("%v entering Follower state (Leader: %q)", r, r.Leader())) metrics.IncrCounter([]string{"raft", "state", "follower"}, 1) heartbeatTimer := randomTimeout(r.conf.HeartbeatTimeout) for { select { case rpc := <-r.rpcCh: r.processRPC(rpc) ...
go
{ "resource": "" }
q175551
liveBootstrap
test
func (r *Raft) liveBootstrap(configuration Configuration) error { // Use the pre-init API to make the static updates. err := BootstrapCluster(&r.conf, r.logs, r.stable, r.snapshots, r.trans, configuration) if err != nil { return err } // Make the configuration live. var entry Log if err := r.logs.GetLog(1, ...
go
{ "resource": "" }
q175552
runCandidate
test
func (r *Raft) runCandidate() { r.logger.Info(fmt.Sprintf("%v entering Candidate state in term %v", r, r.getCurrentTerm()+1)) metrics.IncrCounter([]string{"raft", "state", "candidate"}, 1) // Start vote for us, and set a timeout voteCh := r.electSelf() electionTimer := randomTimeout(r.conf.ElectionTimeout) // T...
go
{ "resource": "" }
q175553
runLeader
test
func (r *Raft) runLeader() { r.logger.Info(fmt.Sprintf("%v entering Leader state", r)) metrics.IncrCounter([]string{"raft", "state", "leader"}, 1) // Notify that we are the leader asyncNotifyBool(r.leaderCh, true) // Push to the notify channel if given if notify := r.conf.NotifyCh; notify != nil { select { ...
go
{ "resource": "" }
q175554
startStopReplication
test
func (r *Raft) startStopReplication() { inConfig := make(map[ServerID]bool, len(r.configurations.latest.Servers)) lastIdx := r.getLastIndex() // Start replication goroutines that need starting for _, server := range r.configurations.latest.Servers { if server.ID == r.localID { continue } inConfig[server.I...
go
{ "resource": "" }
q175555
configurationChangeChIfStable
test
func (r *Raft) configurationChangeChIfStable() chan *configurationChangeFuture { // Have to wait until: // 1. The latest configuration is committed, and // 2. This leader has committed some entry (the noop) in this term // https://groups.google.com/forum/#!msg/raft-dev/t4xj6dJTP6E/d2D9LrWRza8J if r.configuratio...
go
{ "resource": "" }
q175556
verifyLeader
test
func (r *Raft) verifyLeader(v *verifyFuture) { // Current leader always votes for self v.votes = 1 // Set the quorum size, hot-path for single node v.quorumSize = r.quorumSize() if v.quorumSize == 1 { v.respond(nil) return } // Track this request v.notifyCh = r.verifyCh r.leaderState.notify[v] = struct{}...
go
{ "resource": "" }
q175557
checkLeaderLease
test
func (r *Raft) checkLeaderLease() time.Duration { // Track contacted nodes, we can always contact ourself contacted := 1 // Check each follower var maxDiff time.Duration now := time.Now() for peer, f := range r.leaderState.replState { diff := now.Sub(f.LastContact()) if diff <= r.conf.LeaderLeaseTimeout { ...
go
{ "resource": "" }
q175558
restoreUserSnapshot
test
func (r *Raft) restoreUserSnapshot(meta *SnapshotMeta, reader io.Reader) error { defer metrics.MeasureSince([]string{"raft", "restoreUserSnapshot"}, time.Now()) // Sanity check the version. version := meta.Version if version < SnapshotVersionMin || version > SnapshotVersionMax { return fmt.Errorf("unsupported sn...
go
{ "resource": "" }
q175559
appendConfigurationEntry
test
func (r *Raft) appendConfigurationEntry(future *configurationChangeFuture) { configuration, err := nextConfiguration(r.configurations.latest, r.configurations.latestIndex, future.req) if err != nil { future.respond(err) return } r.logger.Info(fmt.Sprintf("Updating configuration with %s (%v, %v) to %+v", futu...
go
{ "resource": "" }
q175560
dispatchLogs
test
func (r *Raft) dispatchLogs(applyLogs []*logFuture) { now := time.Now() defer metrics.MeasureSince([]string{"raft", "leader", "dispatchLog"}, now) term := r.getCurrentTerm() lastIndex := r.getLastIndex() n := len(applyLogs) logs := make([]*Log, n) metrics.SetGauge([]string{"raft", "leader", "dispatchNumLogs"},...
go
{ "resource": "" }
q175561
processLogs
test
func (r *Raft) processLogs(index uint64, future *logFuture) { // Reject logs we've applied already lastApplied := r.getLastApplied() if index <= lastApplied { r.logger.Warn(fmt.Sprintf("Skipping application of old log: %d", index)) return } // Apply all the preceding logs for idx := r.getLastApplied() + 1; i...
go
{ "resource": "" }
q175562
processLog
test
func (r *Raft) processLog(l *Log, future *logFuture) { switch l.Type { case LogBarrier: // Barrier is handled by the FSM fallthrough case LogCommand: // Forward to the fsm handler select { case r.fsmMutateCh <- &commitTuple{l, future}: case <-r.shutdownCh: if future != nil { future.respond(ErrRaf...
go
{ "resource": "" }
q175563
processRPC
test
func (r *Raft) processRPC(rpc RPC) { if err := r.checkRPCHeader(rpc); err != nil { rpc.Respond(nil, err) return } switch cmd := rpc.Command.(type) { case *AppendEntriesRequest: r.appendEntries(rpc, cmd) case *RequestVoteRequest: r.requestVote(rpc, cmd) case *InstallSnapshotRequest: r.installSnapshot(rp...
go
{ "resource": "" }
q175564
processHeartbeat
test
func (r *Raft) processHeartbeat(rpc RPC) { defer metrics.MeasureSince([]string{"raft", "rpc", "processHeartbeat"}, time.Now()) // Check if we are shutdown, just ignore the RPC select { case <-r.shutdownCh: return default: } // Ensure we are only handling a heartbeat switch cmd := rpc.Command.(type) { case ...
go
{ "resource": "" }
q175565
setLastContact
test
func (r *Raft) setLastContact() { r.lastContactLock.Lock() r.lastContact = time.Now() r.lastContactLock.Unlock() }
go
{ "resource": "" }
q175566
persistVote
test
func (r *Raft) persistVote(term uint64, candidate []byte) error { if err := r.stable.SetUint64(keyLastVoteTerm, term); err != nil { return err } if err := r.stable.Set(keyLastVoteCand, candidate); err != nil { return err } return nil }
go
{ "resource": "" }
q175567
setCurrentTerm
test
func (r *Raft) setCurrentTerm(t uint64) { // Persist to disk first if err := r.stable.SetUint64(keyCurrentTerm, t); err != nil { panic(fmt.Errorf("failed to save current term: %v", err)) } r.raftState.setCurrentTerm(t) }
go
{ "resource": "" }
q175568
setState
test
func (r *Raft) setState(state RaftState) { r.setLeader("") oldState := r.raftState.getState() r.raftState.setState(state) if oldState != state { r.observe(state) } }
go
{ "resource": "" }
q175569
getCommitIndex
test
func (c *commitment) getCommitIndex() uint64 { c.Lock() defer c.Unlock() return c.commitIndex }
go
{ "resource": "" }
q175570
recalculate
test
func (c *commitment) recalculate() { if len(c.matchIndexes) == 0 { return } matched := make([]uint64, 0, len(c.matchIndexes)) for _, idx := range c.matchIndexes { matched = append(matched, idx) } sort.Sort(uint64Slice(matched)) quorumMatchIndex := matched[(len(matched)-1)/2] if quorumMatchIndex > c.commit...
go
{ "resource": "" }
q175571
randomTimeout
test
func randomTimeout(minVal time.Duration) <-chan time.Time { if minVal == 0 { return nil } extra := (time.Duration(rand.Int63()) % minVal) return time.After(minVal + extra) }
go
{ "resource": "" }
q175572
generateUUID
test
func generateUUID() string { buf := make([]byte, 16) if _, err := crand.Read(buf); err != nil { panic(fmt.Errorf("failed to read random bytes: %v", err)) } return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", buf[0:4], buf[4:6], buf[6:8], buf[8:10], buf[10:16]) }
go
{ "resource": "" }
q175573
decodeMsgPack
test
func decodeMsgPack(buf []byte, out interface{}) error { r := bytes.NewBuffer(buf) hd := codec.MsgpackHandle{} dec := codec.NewDecoder(r, &hd) return dec.Decode(out) }
go
{ "resource": "" }
q175574
encodeMsgPack
test
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) { buf := bytes.NewBuffer(nil) hd := codec.MsgpackHandle{} enc := codec.NewEncoder(buf, &hd) err := enc.Encode(in) return buf, err }
go
{ "resource": "" }
q175575
backoff
test
func backoff(base time.Duration, round, limit uint64) time.Duration { power := min(round, limit) for power > 2 { base *= 2 power-- } return base }
go
{ "resource": "" }
q175576
newApplySource
test
func newApplySource(seed string) *applySource { h := fnv.New32() h.Write([]byte(seed)) s := &applySource{seed: int64(h.Sum32())} s.reset() return s }
go
{ "resource": "" }
q175577
reset
test
func (a *applySource) reset() { a.rnd = rand.New(rand.NewSource(a.seed)) }
go
{ "resource": "" }
q175578
DefaultConfig
test
func DefaultConfig() *Config { return &Config{ ProtocolVersion: ProtocolVersionMax, HeartbeatTimeout: 1000 * time.Millisecond, ElectionTimeout: 1000 * time.Millisecond, CommitTimeout: 50 * time.Millisecond, MaxAppendEntries: 64, ShutdownOnRemove: true, TrailingLogs: 10240, Snapsh...
go
{ "resource": "" }
q175579
ValidateConfig
test
func ValidateConfig(config *Config) error { // We don't actually support running as 0 in the library any more, but // we do understand it. protocolMin := ProtocolVersionMin if protocolMin == 0 { protocolMin = 1 } if config.ProtocolVersion < protocolMin || config.ProtocolVersion > ProtocolVersionMax { return...
go
{ "resource": "" }
q175580
runSnapshots
test
func (r *Raft) runSnapshots() { for { select { case <-randomTimeout(r.conf.SnapshotInterval): // Check if we should snapshot if !r.shouldSnapshot() { continue } // Trigger a snapshot if _, err := r.takeSnapshot(); err != nil { r.logger.Error(fmt.Sprintf("Failed to take snapshot: %v", err)) ...
go
{ "resource": "" }
q175581
shouldSnapshot
test
func (r *Raft) shouldSnapshot() bool { // Check the last snapshot index lastSnap, _ := r.getLastSnapshot() // Check the last log index lastIdx, err := r.logs.LastIndex() if err != nil { r.logger.Error(fmt.Sprintf("Failed to get last log index: %v", err)) return false } // Compare the delta to the threshold...
go
{ "resource": "" }
q175582
takeSnapshot
test
func (r *Raft) takeSnapshot() (string, error) { defer metrics.MeasureSince([]string{"raft", "snapshot", "takeSnapshot"}, time.Now()) // Create a request for the FSM to perform a snapshot. snapReq := &reqSnapshotFuture{} snapReq.init() // Wait for dispatch or shutdown. select { case r.fsmSnapshotCh <- snapReq: ...
go
{ "resource": "" }
q175583
compactLogs
test
func (r *Raft) compactLogs(snapIdx uint64) error { defer metrics.MeasureSince([]string{"raft", "compactLogs"}, time.Now()) // Determine log ranges to compact minLog, err := r.logs.FirstIndex() if err != nil { return fmt.Errorf("failed to get first log index: %v", err) } // Check if we have enough logs to trunc...
go
{ "resource": "" }
q175584
WebpackCheck
test
func WebpackCheck(r *Runner) error { fmt.Println("~~~ Checking webpack.config.js ~~~") if !r.App.WithWebpack { return nil } box := webpack.Templates f, err := box.FindString("webpack.config.js.tmpl") if err != nil { return err } tmpl, err := template.New("webpack").Parse(f) if err != nil { return err...
go
{ "resource": "" }
q175585
New
test
func New(opts *Options) (*genny.Generator, error) { g := genny.New() if err := opts.Validate(); err != nil { return g, err } if opts.Provider == "none" { return g, nil } box := packr.New("buffalo:genny:vcs", "../vcs/templates") s, err := box.FindString("ignore.tmpl") if err != nil { return g, err } ...
go
{ "resource": "" }
q175586
UnixSocket
test
func UnixSocket(addr string) (*Listener, error) { listener, err := net.Listen("unix", addr) if err != nil { return nil, err } return &Listener{ Server: &http.Server{}, Listener: listener, }, nil }
go
{ "resource": "" }
q175587
Get
test
func (e ErrorHandlers) Get(status int) ErrorHandler { if eh, ok := e[status]; ok { return eh } if eh, ok := e[0]; ok { return eh } return defaultErrorHandler }
go
{ "resource": "" }
q175588
PanicHandler
test
func (a *App) PanicHandler(next Handler) Handler { return func(c Context) error { defer func() { //catch or finally r := recover() var err error if r != nil { //catch switch t := r.(type) { case error: err = t case string: err = errors.New(t) default: err = errors.New(fmt.Spri...
go
{ "resource": "" }
q175589
partialFeeder
test
func (s templateRenderer) partialFeeder(name string) (string, error) { ct := strings.ToLower(s.contentType) d, f := filepath.Split(name) name = filepath.Join(d, "_"+f) name = fixExtension(name, ct) return s.TemplatesBox.FindString(name) }
go
{ "resource": "" }
q175590
New
test
func New(opts Options) *Engine { if opts.Helpers == nil { opts.Helpers = map[string]interface{}{} } if opts.TemplateEngines == nil { opts.TemplateEngines = map[string]TemplateEngine{} } if _, ok := opts.TemplateEngines["html"]; !ok { opts.TemplateEngines["html"] = plush.BuffaloRenderer } if _, ok := opts....
go
{ "resource": "" }
q175591
WriteTo
test
func (m *Message) WriteTo(w io.Writer) (int64, error) { mw := &messageWriter{w: w} mw.writeMessage(m) return mw.n, mw.err }
go
{ "resource": "" }
q175592
Send
test
func (sm SMTPSender) Send(message Message) error { gm := gomail.NewMessage() gm.SetHeader("From", message.From) gm.SetHeader("To", message.To...) gm.SetHeader("Subject", message.Subject) gm.SetHeader("Cc", message.CC...) gm.SetHeader("Bcc", message.Bcc...) sm.addBodies(message, gm) sm.addAttachments(message, ...
go
{ "resource": "" }
q175593
NewSMTPSender
test
func NewSMTPSender(host string, port string, user string, password string) (SMTPSender, error) { iport, err := strconv.Atoi(port) if err != nil { return SMTPSender{}, errors.New("invalid port for the SMTP mail") } dialer := &gomail.Dialer{ Host: host, Port: iport, } if user != "" { dialer.Username = us...
go
{ "resource": "" }
q175594
Param
test
func (d *DefaultContext) Param(key string) string { return d.Params().Get(key) }
go
{ "resource": "" }
q175595
Set
test
func (d *DefaultContext) Set(key string, value interface{}) { d.moot.Lock() d.data[key] = value d.moot.Unlock() }
go
{ "resource": "" }
q175596
Value
test
func (d *DefaultContext) Value(key interface{}) interface{} { if k, ok := key.(string); ok { d.moot.RLock() defer d.moot.RUnlock() if v, ok := d.data[k]; ok { return v } } return d.Context.Value(key) }
go
{ "resource": "" }
q175597
Redirect
test
func (d *DefaultContext) Redirect(status int, url string, args ...interface{}) error { d.Flash().persist(d.Session()) if strings.HasSuffix(url, "Path()") { if len(args) > 1 { return fmt.Errorf("you must pass only a map[string]interface{} to a route path: %T", args) } var m map[string]interface{} if len(ar...
go
{ "resource": "" }
q175598
File
test
func (d *DefaultContext) File(name string) (binding.File, error) { req := d.Request() if err := req.ParseMultipartForm(5 * 1024 * 1024); err != nil { return binding.File{}, err } f, h, err := req.FormFile(name) bf := binding.File{ File: f, FileHeader: h, } if err != nil { return bf, err } return ...
go
{ "resource": "" }
q175599
MarshalJSON
test
func (d *DefaultContext) MarshalJSON() ([]byte, error) { m := map[string]interface{}{} data := d.Data() for k, v := range data { // don't try and marshal ourself if _, ok := v.(*DefaultContext); ok { continue } if _, err := json.Marshal(v); err == nil { // it can be marshaled, so add it: m[k] = v ...
go
{ "resource": "" }