repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
gravityblast/fresh
runner/runnerutils/utils.go
HasErrors
func HasErrors() bool { if _, err := os.Stat(logFilePath); err == nil { return true } return false }
go
func HasErrors() bool { if _, err := os.Stat(logFilePath); err == nil { return true } return false }
[ "func", "HasErrors", "(", ")", "bool", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "logFilePath", ")", ";", "err", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Returns true if a build error file exists in the tmp folder.
[ "Returns", "true", "if", "a", "build", "error", "file", "exists", "in", "the", "tmp", "folder", "." ]
9c0092493eff2825c3abf64e087b3383dec939c3
https://github.com/gravityblast/fresh/blob/9c0092493eff2825c3abf64e087b3383dec939c3/runner/runnerutils/utils.go#L22-L28
train
gravityblast/fresh
runner/runnerutils/utils.go
RenderError
func RenderError(w http.ResponseWriter) { data := map[string]interface{}{ "Output": readErrorFile(), } w.Header().Set("Content-Type", "text/html") tpl := template.Must(template.New("ErrorPage").Parse(buildPageTpl)) tpl.Execute(w, data) }
go
func RenderError(w http.ResponseWriter) { data := map[string]interface{}{ "Output": readErrorFile(), } w.Header().Set("Content-Type", "text/html") tpl := template.Must(template.New("ErrorPage").Parse(buildPageTpl)) tpl.Execute(w, data) }
[ "func", "RenderError", "(", "w", "http", ".", "ResponseWriter", ")", "{", "data", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "readErrorFile", "(", ")", ",", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", ...
// It renders an error page with the build error message.
[ "It", "renders", "an", "error", "page", "with", "the", "build", "error", "message", "." ]
9c0092493eff2825c3abf64e087b3383dec939c3
https://github.com/gravityblast/fresh/blob/9c0092493eff2825c3abf64e087b3383dec939c3/runner/runnerutils/utils.go#L31-L39
train
goraft/raft
log.go
currentIndex
func (l *Log) currentIndex() uint64 { l.mutex.RLock() defer l.mutex.RUnlock() return l.internalCurrentIndex() }
go
func (l *Log) currentIndex() uint64 { l.mutex.RLock() defer l.mutex.RUnlock() return l.internalCurrentIndex() }
[ "func", "(", "l", "*", "Log", ")", "currentIndex", "(", ")", "uint64", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "l", ".", "internalCurrentIndex", "(", ")", "\n", "...
// The current index in the log.
[ "The", "current", "index", "in", "the", "log", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L70-L74
train
goraft/raft
log.go
internalCurrentIndex
func (l *Log) internalCurrentIndex() uint64 { if len(l.entries) == 0 { return l.startIndex } return l.entries[len(l.entries)-1].Index() }
go
func (l *Log) internalCurrentIndex() uint64 { if len(l.entries) == 0 { return l.startIndex } return l.entries[len(l.entries)-1].Index() }
[ "func", "(", "l", "*", "Log", ")", "internalCurrentIndex", "(", ")", "uint64", "{", "if", "len", "(", "l", ".", "entries", ")", "==", "0", "{", "return", "l", ".", "startIndex", "\n", "}", "\n", "return", "l", ".", "entries", "[", "len", "(", "l"...
// The current index in the log without locking
[ "The", "current", "index", "in", "the", "log", "without", "locking" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L77-L82
train
goraft/raft
log.go
isEmpty
func (l *Log) isEmpty() bool { l.mutex.RLock() defer l.mutex.RUnlock() return (len(l.entries) == 0) && (l.startIndex == 0) }
go
func (l *Log) isEmpty() bool { l.mutex.RLock() defer l.mutex.RUnlock() return (len(l.entries) == 0) && (l.startIndex == 0) }
[ "func", "(", "l", "*", "Log", ")", "isEmpty", "(", ")", "bool", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "(", "len", "(", "l", ".", "entries", ")", "==", "0", ...
// Determines if the log contains zero entries.
[ "Determines", "if", "the", "log", "contains", "zero", "entries", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L90-L94
train
goraft/raft
log.go
lastCommandName
func (l *Log) lastCommandName() string { l.mutex.RLock() defer l.mutex.RUnlock() if len(l.entries) > 0 { if entry := l.entries[len(l.entries)-1]; entry != nil { return entry.CommandName() } } return "" }
go
func (l *Log) lastCommandName() string { l.mutex.RLock() defer l.mutex.RUnlock() if len(l.entries) > 0 { if entry := l.entries[len(l.entries)-1]; entry != nil { return entry.CommandName() } } return "" }
[ "func", "(", "l", "*", "Log", ")", "lastCommandName", "(", ")", "string", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "if", "len", "(", "l", ".", "entries", ")", ">", "0", ...
// The name of the last command in the log.
[ "The", "name", "of", "the", "last", "command", "in", "the", "log", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L97-L106
train
goraft/raft
log.go
close
func (l *Log) close() { l.mutex.Lock() defer l.mutex.Unlock() if l.file != nil { l.file.Close() l.file = nil } l.entries = make([]*LogEntry, 0) }
go
func (l *Log) close() { l.mutex.Lock() defer l.mutex.Unlock() if l.file != nil { l.file.Close() l.file = nil } l.entries = make([]*LogEntry, 0) }
[ "func", "(", "l", "*", "Log", ")", "close", "(", ")", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "file", "!=", "nil", "{", "l", ".", "file", ".", "Close"...
// Closes the log file.
[ "Closes", "the", "log", "file", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L198-L207
train
goraft/raft
log.go
getEntry
func (l *Log) getEntry(index uint64) *LogEntry { l.mutex.RLock() defer l.mutex.RUnlock() if index <= l.startIndex || index > (l.startIndex+uint64(len(l.entries))) { return nil } return l.entries[index-l.startIndex-1] }
go
func (l *Log) getEntry(index uint64) *LogEntry { l.mutex.RLock() defer l.mutex.RUnlock() if index <= l.startIndex || index > (l.startIndex+uint64(len(l.entries))) { return nil } return l.entries[index-l.startIndex-1] }
[ "func", "(", "l", "*", "Log", ")", "getEntry", "(", "index", "uint64", ")", "*", "LogEntry", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "if", "index", "<=", "l", ".", "sta...
// Retrieves an entry from the log. If the entry has been eliminated because // of a snapshot then nil is returned.
[ "Retrieves", "an", "entry", "from", "the", "log", ".", "If", "the", "entry", "has", "been", "eliminated", "because", "of", "a", "snapshot", "then", "nil", "is", "returned", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L225-L233
train
goraft/raft
log.go
getEntriesAfter
func (l *Log) getEntriesAfter(index uint64, maxLogEntriesPerRequest uint64) ([]*LogEntry, uint64) { l.mutex.RLock() defer l.mutex.RUnlock() // Return nil if index is before the start of the log. if index < l.startIndex { traceln("log.entriesAfter.before: ", index, " ", l.startIndex) return nil, 0 } // Return an error if the index doesn't exist. if index > (uint64(len(l.entries)) + l.startIndex) { panic(fmt.Sprintf("raft: Index is beyond end of log: %v %v", len(l.entries), index)) } // If we're going from the beginning of the log then return the whole log. if index == l.startIndex { traceln("log.entriesAfter.beginning: ", index, " ", l.startIndex) return l.entries, l.startTerm } traceln("log.entriesAfter.partial: ", index, " ", l.entries[len(l.entries)-1].Index) entries := l.entries[index-l.startIndex:] length := len(entries) traceln("log.entriesAfter: startIndex:", l.startIndex, " length", len(l.entries)) if uint64(length) < maxLogEntriesPerRequest { // Determine the term at the given entry and return a subslice. return entries, l.entries[index-1-l.startIndex].Term() } else { return entries[:maxLogEntriesPerRequest], l.entries[index-1-l.startIndex].Term() } }
go
func (l *Log) getEntriesAfter(index uint64, maxLogEntriesPerRequest uint64) ([]*LogEntry, uint64) { l.mutex.RLock() defer l.mutex.RUnlock() // Return nil if index is before the start of the log. if index < l.startIndex { traceln("log.entriesAfter.before: ", index, " ", l.startIndex) return nil, 0 } // Return an error if the index doesn't exist. if index > (uint64(len(l.entries)) + l.startIndex) { panic(fmt.Sprintf("raft: Index is beyond end of log: %v %v", len(l.entries), index)) } // If we're going from the beginning of the log then return the whole log. if index == l.startIndex { traceln("log.entriesAfter.beginning: ", index, " ", l.startIndex) return l.entries, l.startTerm } traceln("log.entriesAfter.partial: ", index, " ", l.entries[len(l.entries)-1].Index) entries := l.entries[index-l.startIndex:] length := len(entries) traceln("log.entriesAfter: startIndex:", l.startIndex, " length", len(l.entries)) if uint64(length) < maxLogEntriesPerRequest { // Determine the term at the given entry and return a subslice. return entries, l.entries[index-1-l.startIndex].Term() } else { return entries[:maxLogEntriesPerRequest], l.entries[index-1-l.startIndex].Term() } }
[ "func", "(", "l", "*", "Log", ")", "getEntriesAfter", "(", "index", "uint64", ",", "maxLogEntriesPerRequest", "uint64", ")", "(", "[", "]", "*", "LogEntry", ",", "uint64", ")", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", ...
// Retrieves a list of entries after a given index as well as the term of the // index provided. A nil list of entries is returned if the index no longer // exists because a snapshot was made.
[ "Retrieves", "a", "list", "of", "entries", "after", "a", "given", "index", "as", "well", "as", "the", "term", "of", "the", "index", "provided", ".", "A", "nil", "list", "of", "entries", "is", "returned", "if", "the", "index", "no", "longer", "exists", ...
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L244-L278
train
goraft/raft
log.go
lastInfo
func (l *Log) lastInfo() (index uint64, term uint64) { l.mutex.RLock() defer l.mutex.RUnlock() // If we don't have any entries then just return zeros. if len(l.entries) == 0 { return l.startIndex, l.startTerm } // Return the last index & term entry := l.entries[len(l.entries)-1] return entry.Index(), entry.Term() }
go
func (l *Log) lastInfo() (index uint64, term uint64) { l.mutex.RLock() defer l.mutex.RUnlock() // If we don't have any entries then just return zeros. if len(l.entries) == 0 { return l.startIndex, l.startTerm } // Return the last index & term entry := l.entries[len(l.entries)-1] return entry.Index(), entry.Term() }
[ "func", "(", "l", "*", "Log", ")", "lastInfo", "(", ")", "(", "index", "uint64", ",", "term", "uint64", ")", "{", "l", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "// If we don't have an...
// Retrieves the last index and term that has been appended to the log.
[ "Retrieves", "the", "last", "index", "and", "term", "that", "has", "been", "appended", "to", "the", "log", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L305-L317
train
goraft/raft
log.go
updateCommitIndex
func (l *Log) updateCommitIndex(index uint64) { l.mutex.Lock() defer l.mutex.Unlock() if index > l.commitIndex { l.commitIndex = index } debugln("update.commit.index ", index) }
go
func (l *Log) updateCommitIndex(index uint64) { l.mutex.Lock() defer l.mutex.Unlock() if index > l.commitIndex { l.commitIndex = index } debugln("update.commit.index ", index) }
[ "func", "(", "l", "*", "Log", ")", "updateCommitIndex", "(", "index", "uint64", ")", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "index", ">", "l", ".", "commitIndex", "{",...
// Updates the commit index
[ "Updates", "the", "commit", "index" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L320-L327
train
goraft/raft
log.go
setCommitIndex
func (l *Log) setCommitIndex(index uint64) error { l.mutex.Lock() defer l.mutex.Unlock() // this is not error any more after limited the number of sending entries // commit up to what we already have if index > l.startIndex+uint64(len(l.entries)) { debugln("raft.Log: Commit index", index, "set back to ", len(l.entries)) index = l.startIndex + uint64(len(l.entries)) } // Do not allow previous indices to be committed again. // This could happens, since the guarantee is that the new leader has up-to-dated // log entries rather than has most up-to-dated committed index // For example, Leader 1 send log 80 to follower 2 and follower 3 // follower 2 and follow 3 all got the new entries and reply // leader 1 committed entry 80 and send reply to follower 2 and follower3 // follower 2 receive the new committed index and update committed index to 80 // leader 1 fail to send the committed index to follower 3 // follower 3 promote to leader (server 1 and server 2 will vote, since leader 3 // has up-to-dated the entries) // when new leader 3 send heartbeat with committed index = 0 to follower 2, // follower 2 should reply success and let leader 3 update the committed index to 80 if index < l.commitIndex { return nil } // Find all entries whose index is between the previous index and the current index. for i := l.commitIndex + 1; i <= index; i++ { entryIndex := i - 1 - l.startIndex entry := l.entries[entryIndex] // Update commit index. l.commitIndex = entry.Index() // Decode the command. command, err := newCommand(entry.CommandName(), entry.Command()) if err != nil { return err } // Apply the changes to the state machine and store the error code. returnValue, err := l.ApplyFunc(entry, command) debugf("setCommitIndex.set.result index: %v, entries index: %v", i, entryIndex) if entry.event != nil { entry.event.returnValue = returnValue entry.event.c <- err } _, isJoinCommand := command.(JoinCommand) // we can only commit up to the most recent join command // if there is a join in this batch of commands. // after this commit, we need to recalculate the majority. if isJoinCommand { return nil } } return nil }
go
func (l *Log) setCommitIndex(index uint64) error { l.mutex.Lock() defer l.mutex.Unlock() // this is not error any more after limited the number of sending entries // commit up to what we already have if index > l.startIndex+uint64(len(l.entries)) { debugln("raft.Log: Commit index", index, "set back to ", len(l.entries)) index = l.startIndex + uint64(len(l.entries)) } // Do not allow previous indices to be committed again. // This could happens, since the guarantee is that the new leader has up-to-dated // log entries rather than has most up-to-dated committed index // For example, Leader 1 send log 80 to follower 2 and follower 3 // follower 2 and follow 3 all got the new entries and reply // leader 1 committed entry 80 and send reply to follower 2 and follower3 // follower 2 receive the new committed index and update committed index to 80 // leader 1 fail to send the committed index to follower 3 // follower 3 promote to leader (server 1 and server 2 will vote, since leader 3 // has up-to-dated the entries) // when new leader 3 send heartbeat with committed index = 0 to follower 2, // follower 2 should reply success and let leader 3 update the committed index to 80 if index < l.commitIndex { return nil } // Find all entries whose index is between the previous index and the current index. for i := l.commitIndex + 1; i <= index; i++ { entryIndex := i - 1 - l.startIndex entry := l.entries[entryIndex] // Update commit index. l.commitIndex = entry.Index() // Decode the command. command, err := newCommand(entry.CommandName(), entry.Command()) if err != nil { return err } // Apply the changes to the state machine and store the error code. returnValue, err := l.ApplyFunc(entry, command) debugf("setCommitIndex.set.result index: %v, entries index: %v", i, entryIndex) if entry.event != nil { entry.event.returnValue = returnValue entry.event.c <- err } _, isJoinCommand := command.(JoinCommand) // we can only commit up to the most recent join command // if there is a join in this batch of commands. // after this commit, we need to recalculate the majority. if isJoinCommand { return nil } } return nil }
[ "func", "(", "l", "*", "Log", ")", "setCommitIndex", "(", "index", "uint64", ")", "error", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// this is not error any more after limited the nu...
// Updates the commit index and writes entries after that index to the stable storage.
[ "Updates", "the", "commit", "index", "and", "writes", "entries", "after", "that", "index", "to", "the", "stable", "storage", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L330-L393
train
goraft/raft
log.go
flushCommitIndex
func (l *Log) flushCommitIndex() { l.file.Seek(0, os.SEEK_SET) fmt.Fprintf(l.file, "%8x\n", l.commitIndex) l.file.Seek(0, os.SEEK_END) }
go
func (l *Log) flushCommitIndex() { l.file.Seek(0, os.SEEK_SET) fmt.Fprintf(l.file, "%8x\n", l.commitIndex) l.file.Seek(0, os.SEEK_END) }
[ "func", "(", "l", "*", "Log", ")", "flushCommitIndex", "(", ")", "{", "l", ".", "file", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "fmt", ".", "Fprintf", "(", "l", ".", "file", ",", "\"", "\\n", "\"", ",", "l", ".", "commit...
// Set the commitIndex at the head of the log file to the current // commit Index. This should be called after obtained a log lock
[ "Set", "the", "commitIndex", "at", "the", "head", "of", "the", "log", "file", "to", "the", "current", "commit", "Index", ".", "This", "should", "be", "called", "after", "obtained", "a", "log", "lock" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L397-L401
train
goraft/raft
log.go
appendEntry
func (l *Log) appendEntry(entry *LogEntry) error { l.mutex.Lock() defer l.mutex.Unlock() if l.file == nil { return errors.New("raft.Log: Log is not open") } // Make sure the term and index are greater than the previous. if len(l.entries) > 0 { lastEntry := l.entries[len(l.entries)-1] if entry.Term() < lastEntry.Term() { return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } else if entry.Term() == lastEntry.Term() && entry.Index() <= lastEntry.Index() { return fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } } position, _ := l.file.Seek(0, os.SEEK_CUR) entry.Position = position // Write to storage. if _, err := entry.Encode(l.file); err != nil { return err } // Append to entries list if stored on disk. l.entries = append(l.entries, entry) return nil }
go
func (l *Log) appendEntry(entry *LogEntry) error { l.mutex.Lock() defer l.mutex.Unlock() if l.file == nil { return errors.New("raft.Log: Log is not open") } // Make sure the term and index are greater than the previous. if len(l.entries) > 0 { lastEntry := l.entries[len(l.entries)-1] if entry.Term() < lastEntry.Term() { return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } else if entry.Term() == lastEntry.Term() && entry.Index() <= lastEntry.Index() { return fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } } position, _ := l.file.Seek(0, os.SEEK_CUR) entry.Position = position // Write to storage. if _, err := entry.Encode(l.file); err != nil { return err } // Append to entries list if stored on disk. l.entries = append(l.entries, entry) return nil }
[ "func", "(", "l", "*", "Log", ")", "appendEntry", "(", "entry", "*", "LogEntry", ")", "error", "{", "l", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "file", "==", "nil"...
// Writes a single log entry to the end of the log.
[ "Writes", "a", "single", "log", "entry", "to", "the", "end", "of", "the", "log", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L510-L541
train
goraft/raft
log.go
writeEntry
func (l *Log) writeEntry(entry *LogEntry, w io.Writer) (int64, error) { if l.file == nil { return -1, errors.New("raft.Log: Log is not open") } // Make sure the term and index are greater than the previous. if len(l.entries) > 0 { lastEntry := l.entries[len(l.entries)-1] if entry.Term() < lastEntry.Term() { return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } else if entry.Term() == lastEntry.Term() && entry.Index() <= lastEntry.Index() { return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } } // Write to storage. size, err := entry.Encode(w) if err != nil { return -1, err } // Append to entries list if stored on disk. l.entries = append(l.entries, entry) return int64(size), nil }
go
func (l *Log) writeEntry(entry *LogEntry, w io.Writer) (int64, error) { if l.file == nil { return -1, errors.New("raft.Log: Log is not open") } // Make sure the term and index are greater than the previous. if len(l.entries) > 0 { lastEntry := l.entries[len(l.entries)-1] if entry.Term() < lastEntry.Term() { return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } else if entry.Term() == lastEntry.Term() && entry.Index() <= lastEntry.Index() { return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term(), entry.Index(), lastEntry.Term(), lastEntry.Index()) } } // Write to storage. size, err := entry.Encode(w) if err != nil { return -1, err } // Append to entries list if stored on disk. l.entries = append(l.entries, entry) return int64(size), nil }
[ "func", "(", "l", "*", "Log", ")", "writeEntry", "(", "entry", "*", "LogEntry", ",", "w", "io", ".", "Writer", ")", "(", "int64", ",", "error", ")", "{", "if", "l", ".", "file", "==", "nil", "{", "return", "-", "1", ",", "errors", ".", "New", ...
// appendEntry with Buffered io
[ "appendEntry", "with", "Buffered", "io" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log.go#L544-L569
train
goraft/raft
request_vote.go
newRequestVoteRequest
func newRequestVoteRequest(term uint64, candidateName string, lastLogIndex uint64, lastLogTerm uint64) *RequestVoteRequest { return &RequestVoteRequest{ Term: term, LastLogIndex: lastLogIndex, LastLogTerm: lastLogTerm, CandidateName: candidateName, } }
go
func newRequestVoteRequest(term uint64, candidateName string, lastLogIndex uint64, lastLogTerm uint64) *RequestVoteRequest { return &RequestVoteRequest{ Term: term, LastLogIndex: lastLogIndex, LastLogTerm: lastLogTerm, CandidateName: candidateName, } }
[ "func", "newRequestVoteRequest", "(", "term", "uint64", ",", "candidateName", "string", ",", "lastLogIndex", "uint64", ",", "lastLogTerm", "uint64", ")", "*", "RequestVoteRequest", "{", "return", "&", "RequestVoteRequest", "{", "Term", ":", "term", ",", "LastLogIn...
// Creates a new RequestVote request.
[ "Creates", "a", "new", "RequestVote", "request", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L28-L35
train
goraft/raft
request_vote.go
Encode
func (req *RequestVoteRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.RequestVoteRequest{ Term: proto.Uint64(req.Term), LastLogIndex: proto.Uint64(req.LastLogIndex), LastLogTerm: proto.Uint64(req.LastLogTerm), CandidateName: proto.String(req.CandidateName), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (req *RequestVoteRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.RequestVoteRequest{ Term: proto.Uint64(req.Term), LastLogIndex: proto.Uint64(req.LastLogIndex), LastLogTerm: proto.Uint64(req.LastLogTerm), CandidateName: proto.String(req.CandidateName), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "req", "*", "RequestVoteRequest", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "RequestVoteRequest", "{", "Term", ":", "proto", ".", "Uint64", "(", "req", ".", ...
// Encodes the RequestVoteRequest to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "RequestVoteRequest", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L39-L52
train
goraft/raft
request_vote.go
Decode
func (req *RequestVoteRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } totalBytes := len(data) pb := &protobuf.RequestVoteRequest{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.LastLogIndex = pb.GetLastLogIndex() req.LastLogTerm = pb.GetLastLogTerm() req.CandidateName = pb.GetCandidateName() return totalBytes, nil }
go
func (req *RequestVoteRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } totalBytes := len(data) pb := &protobuf.RequestVoteRequest{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.LastLogIndex = pb.GetLastLogIndex() req.LastLogTerm = pb.GetLastLogTerm() req.CandidateName = pb.GetCandidateName() return totalBytes, nil }
[ "func", "(", "req", "*", "RequestVoteRequest", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "retur...
// Decodes the RequestVoteRequest from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "RequestVoteRequest", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L56-L76
train
goraft/raft
request_vote.go
newRequestVoteResponse
func newRequestVoteResponse(term uint64, voteGranted bool) *RequestVoteResponse { return &RequestVoteResponse{ Term: term, VoteGranted: voteGranted, } }
go
func newRequestVoteResponse(term uint64, voteGranted bool) *RequestVoteResponse { return &RequestVoteResponse{ Term: term, VoteGranted: voteGranted, } }
[ "func", "newRequestVoteResponse", "(", "term", "uint64", ",", "voteGranted", "bool", ")", "*", "RequestVoteResponse", "{", "return", "&", "RequestVoteResponse", "{", "Term", ":", "term", ",", "VoteGranted", ":", "voteGranted", ",", "}", "\n", "}" ]
// Creates a new RequestVote response.
[ "Creates", "a", "new", "RequestVote", "response", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L79-L84
train
goraft/raft
request_vote.go
Encode
func (resp *RequestVoteResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.RequestVoteResponse{ Term: proto.Uint64(resp.Term), VoteGranted: proto.Bool(resp.VoteGranted), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (resp *RequestVoteResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.RequestVoteResponse{ Term: proto.Uint64(resp.Term), VoteGranted: proto.Bool(resp.VoteGranted), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "resp", "*", "RequestVoteResponse", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "RequestVoteResponse", "{", "Term", ":", "proto", ".", "Uint64", "(", "resp", "....
// Encodes the RequestVoteResponse to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "RequestVoteResponse", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L88-L100
train
goraft/raft
request_vote.go
Decode
func (resp *RequestVoteResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.RequestVoteResponse{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } resp.Term = pb.GetTerm() resp.VoteGranted = pb.GetVoteGranted() return totalBytes, nil }
go
func (resp *RequestVoteResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.RequestVoteResponse{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } resp.Term = pb.GetTerm() resp.VoteGranted = pb.GetVoteGranted() return totalBytes, nil }
[ "func", "(", "resp", "*", "RequestVoteResponse", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "ret...
// Decodes the RequestVoteResponse from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "RequestVoteResponse", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/request_vote.go#L104-L122
train
goraft/raft
event_dispatcher.go
newEventDispatcher
func newEventDispatcher(source interface{}) *eventDispatcher { return &eventDispatcher{ source: source, listeners: make(map[string]eventListeners), } }
go
func newEventDispatcher(source interface{}) *eventDispatcher { return &eventDispatcher{ source: source, listeners: make(map[string]eventListeners), } }
[ "func", "newEventDispatcher", "(", "source", "interface", "{", "}", ")", "*", "eventDispatcher", "{", "return", "&", "eventDispatcher", "{", "source", ":", "source", ",", "listeners", ":", "make", "(", "map", "[", "string", "]", "eventListeners", ")", ",", ...
// newEventDispatcher creates a new eventDispatcher instance.
[ "newEventDispatcher", "creates", "a", "new", "eventDispatcher", "instance", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event_dispatcher.go#L23-L28
train
goraft/raft
event_dispatcher.go
AddEventListener
func (d *eventDispatcher) AddEventListener(typ string, listener EventListener) { d.Lock() defer d.Unlock() d.listeners[typ] = append(d.listeners[typ], listener) }
go
func (d *eventDispatcher) AddEventListener(typ string, listener EventListener) { d.Lock() defer d.Unlock() d.listeners[typ] = append(d.listeners[typ], listener) }
[ "func", "(", "d", "*", "eventDispatcher", ")", "AddEventListener", "(", "typ", "string", ",", "listener", "EventListener", ")", "{", "d", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "Unlock", "(", ")", "\n", "d", ".", "listeners", "[", "typ", "]"...
// AddEventListener adds a listener function for a given event type.
[ "AddEventListener", "adds", "a", "listener", "function", "for", "a", "given", "event", "type", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event_dispatcher.go#L31-L35
train
goraft/raft
event_dispatcher.go
RemoveEventListener
func (d *eventDispatcher) RemoveEventListener(typ string, listener EventListener) { d.Lock() defer d.Unlock() // Grab a reference to the function pointer once. ptr := reflect.ValueOf(listener).Pointer() // Find listener by pointer and remove it. listeners := d.listeners[typ] for i, l := range listeners { if reflect.ValueOf(l).Pointer() == ptr { d.listeners[typ] = append(listeners[:i], listeners[i+1:]...) } } }
go
func (d *eventDispatcher) RemoveEventListener(typ string, listener EventListener) { d.Lock() defer d.Unlock() // Grab a reference to the function pointer once. ptr := reflect.ValueOf(listener).Pointer() // Find listener by pointer and remove it. listeners := d.listeners[typ] for i, l := range listeners { if reflect.ValueOf(l).Pointer() == ptr { d.listeners[typ] = append(listeners[:i], listeners[i+1:]...) } } }
[ "func", "(", "d", "*", "eventDispatcher", ")", "RemoveEventListener", "(", "typ", "string", ",", "listener", "EventListener", ")", "{", "d", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "Unlock", "(", ")", "\n\n", "// Grab a reference to the function pointe...
// RemoveEventListener removes a listener function for a given event type.
[ "RemoveEventListener", "removes", "a", "listener", "function", "for", "a", "given", "event", "type", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event_dispatcher.go#L38-L52
train
goraft/raft
event_dispatcher.go
DispatchEvent
func (d *eventDispatcher) DispatchEvent(e Event) { d.RLock() defer d.RUnlock() // Automatically set the event source. if e, ok := e.(*event); ok { e.source = d.source } // Dispatch the event to all listeners. for _, l := range d.listeners[e.Type()] { l(e) } }
go
func (d *eventDispatcher) DispatchEvent(e Event) { d.RLock() defer d.RUnlock() // Automatically set the event source. if e, ok := e.(*event); ok { e.source = d.source } // Dispatch the event to all listeners. for _, l := range d.listeners[e.Type()] { l(e) } }
[ "func", "(", "d", "*", "eventDispatcher", ")", "DispatchEvent", "(", "e", "Event", ")", "{", "d", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "RUnlock", "(", ")", "\n\n", "// Automatically set the event source.", "if", "e", ",", "ok", ":=", "e", "...
// DispatchEvent dispatches an event.
[ "DispatchEvent", "dispatches", "an", "event", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event_dispatcher.go#L55-L68
train
goraft/raft
snapshot.go
save
func (ss *Snapshot) save() error { // Open the file for writing. file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { return err } defer file.Close() // Serialize to JSON. b, err := json.Marshal(ss) if err != nil { return err } // Generate checksum and write it to disk. checksum := crc32.ChecksumIEEE(b) if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil { return err } // Write the snapshot to disk. if _, err = file.Write(b); err != nil { return err } // Ensure that the snapshot has been flushed to disk before continuing. if err := file.Sync(); err != nil { return err } return nil }
go
func (ss *Snapshot) save() error { // Open the file for writing. file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { return err } defer file.Close() // Serialize to JSON. b, err := json.Marshal(ss) if err != nil { return err } // Generate checksum and write it to disk. checksum := crc32.ChecksumIEEE(b) if _, err = fmt.Fprintf(file, "%08x\n", checksum); err != nil { return err } // Write the snapshot to disk. if _, err = file.Write(b); err != nil { return err } // Ensure that the snapshot has been flushed to disk before continuing. if err := file.Sync(); err != nil { return err } return nil }
[ "func", "(", "ss", "*", "Snapshot", ")", "save", "(", ")", "error", "{", "// Open the file for writing.", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "ss", ".", "Path", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_WRONLY", ",", "0600", ")...
// save writes the snapshot to file.
[ "save", "writes", "the", "snapshot", "to", "file", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L55-L86
train
goraft/raft
snapshot.go
remove
func (ss *Snapshot) remove() error { if err := os.Remove(ss.Path); err != nil { return err } return nil }
go
func (ss *Snapshot) remove() error { if err := os.Remove(ss.Path); err != nil { return err } return nil }
[ "func", "(", "ss", "*", "Snapshot", ")", "remove", "(", ")", "error", "{", "if", "err", ":=", "os", ".", "Remove", "(", "ss", ".", "Path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// remove deletes the snapshot file.
[ "remove", "deletes", "the", "snapshot", "file", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L89-L94
train
goraft/raft
snapshot.go
Encode
func (req *SnapshotRecoveryRequest) Encode(w io.Writer) (int, error) { protoPeers := make([]*protobuf.SnapshotRecoveryRequest_Peer, len(req.Peers)) for i, peer := range req.Peers { protoPeers[i] = &protobuf.SnapshotRecoveryRequest_Peer{ Name: proto.String(peer.Name), ConnectionString: proto.String(peer.ConnectionString), } } pb := &protobuf.SnapshotRecoveryRequest{ LeaderName: proto.String(req.LeaderName), LastIndex: proto.Uint64(req.LastIndex), LastTerm: proto.Uint64(req.LastTerm), Peers: protoPeers, State: req.State, } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (req *SnapshotRecoveryRequest) Encode(w io.Writer) (int, error) { protoPeers := make([]*protobuf.SnapshotRecoveryRequest_Peer, len(req.Peers)) for i, peer := range req.Peers { protoPeers[i] = &protobuf.SnapshotRecoveryRequest_Peer{ Name: proto.String(peer.Name), ConnectionString: proto.String(peer.ConnectionString), } } pb := &protobuf.SnapshotRecoveryRequest{ LeaderName: proto.String(req.LeaderName), LastIndex: proto.Uint64(req.LastIndex), LastTerm: proto.Uint64(req.LastTerm), Peers: protoPeers, State: req.State, } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "req", "*", "SnapshotRecoveryRequest", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "protoPeers", ":=", "make", "(", "[", "]", "*", "protobuf", ".", "SnapshotRecoveryRequest_Peer", ",", "len", "(", ...
// Encodes the SnapshotRecoveryRequest to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "SnapshotRecoveryRequest", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L109-L133
train
goraft/raft
snapshot.go
Decode
func (req *SnapshotRecoveryRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRecoveryRequest{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } req.LeaderName = pb.GetLeaderName() req.LastIndex = pb.GetLastIndex() req.LastTerm = pb.GetLastTerm() req.State = pb.GetState() req.Peers = make([]*Peer, len(pb.Peers)) for i, peer := range pb.Peers { req.Peers[i] = &Peer{ Name: peer.GetName(), ConnectionString: peer.GetConnectionString(), } } return totalBytes, nil }
go
func (req *SnapshotRecoveryRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRecoveryRequest{} if err = proto.Unmarshal(data, pb); err != nil { return -1, err } req.LeaderName = pb.GetLeaderName() req.LastIndex = pb.GetLastIndex() req.LastTerm = pb.GetLastTerm() req.State = pb.GetState() req.Peers = make([]*Peer, len(pb.Peers)) for i, peer := range pb.Peers { req.Peers[i] = &Peer{ Name: peer.GetName(), ConnectionString: peer.GetConnectionString(), } } return totalBytes, nil }
[ "func", "(", "req", "*", "SnapshotRecoveryRequest", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "...
// Decodes the SnapshotRecoveryRequest from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "SnapshotRecoveryRequest", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L137-L166
train
goraft/raft
snapshot.go
newSnapshotRecoveryResponse
func newSnapshotRecoveryResponse(term uint64, success bool, commitIndex uint64) *SnapshotRecoveryResponse { return &SnapshotRecoveryResponse{ Term: term, Success: success, CommitIndex: commitIndex, } }
go
func newSnapshotRecoveryResponse(term uint64, success bool, commitIndex uint64) *SnapshotRecoveryResponse { return &SnapshotRecoveryResponse{ Term: term, Success: success, CommitIndex: commitIndex, } }
[ "func", "newSnapshotRecoveryResponse", "(", "term", "uint64", ",", "success", "bool", ",", "commitIndex", "uint64", ")", "*", "SnapshotRecoveryResponse", "{", "return", "&", "SnapshotRecoveryResponse", "{", "Term", ":", "term", ",", "Success", ":", "success", ",",...
// Creates a new Snapshot response.
[ "Creates", "a", "new", "Snapshot", "response", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L169-L175
train
goraft/raft
snapshot.go
Encode
func (req *SnapshotRecoveryResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotRecoveryResponse{ Term: proto.Uint64(req.Term), Success: proto.Bool(req.Success), CommitIndex: proto.Uint64(req.CommitIndex), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (req *SnapshotRecoveryResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotRecoveryResponse{ Term: proto.Uint64(req.Term), Success: proto.Bool(req.Success), CommitIndex: proto.Uint64(req.CommitIndex), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "req", "*", "SnapshotRecoveryResponse", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "SnapshotRecoveryResponse", "{", "Term", ":", "proto", ".", "Uint64", "(", "re...
// Encode writes the response to a writer. // Returns the number of bytes written and any error that occurs.
[ "Encode", "writes", "the", "response", "to", "a", "writer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L179-L191
train
goraft/raft
snapshot.go
Decode
func (req *SnapshotRecoveryResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRecoveryResponse{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.Success = pb.GetSuccess() req.CommitIndex = pb.GetCommitIndex() return totalBytes, nil }
go
func (req *SnapshotRecoveryResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRecoveryResponse{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.Success = pb.GetSuccess() req.CommitIndex = pb.GetCommitIndex() return totalBytes, nil }
[ "func", "(", "req", "*", "SnapshotRecoveryResponse", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", ...
// Decodes the SnapshotRecoveryResponse from a buffer.
[ "Decodes", "the", "SnapshotRecoveryResponse", "from", "a", "buffer", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L194-L213
train
goraft/raft
snapshot.go
Encode
func (req *SnapshotRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotRequest{ LeaderName: proto.String(req.LeaderName), LastIndex: proto.Uint64(req.LastIndex), LastTerm: proto.Uint64(req.LastTerm), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (req *SnapshotRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotRequest{ LeaderName: proto.String(req.LeaderName), LastIndex: proto.Uint64(req.LastIndex), LastTerm: proto.Uint64(req.LastTerm), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "req", "*", "SnapshotRequest", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "SnapshotRequest", "{", "LeaderName", ":", "proto", ".", "String", "(", "req", ".", ...
// Encodes the SnapshotRequest to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "SnapshotRequest", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L226-L238
train
goraft/raft
snapshot.go
Decode
func (req *SnapshotRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRequest{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.LeaderName = pb.GetLeaderName() req.LastIndex = pb.GetLastIndex() req.LastTerm = pb.GetLastTerm() return totalBytes, nil }
go
func (req *SnapshotRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotRequest{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.LeaderName = pb.GetLeaderName() req.LastIndex = pb.GetLastIndex() req.LastTerm = pb.GetLastTerm() return totalBytes, nil }
[ "func", "(", "req", "*", "SnapshotRequest", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "return",...
// Decodes the SnapshotRequest from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "SnapshotRequest", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L242-L262
train
goraft/raft
snapshot.go
Encode
func (resp *SnapshotResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotResponse{ Success: proto.Bool(resp.Success), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (resp *SnapshotResponse) Encode(w io.Writer) (int, error) { pb := &protobuf.SnapshotResponse{ Success: proto.Bool(resp.Success), } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "resp", "*", "SnapshotResponse", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "SnapshotResponse", "{", "Success", ":", "proto", ".", "Bool", "(", "resp", ".", ...
// Encodes the SnapshotResponse to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "SnapshotResponse", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L273-L283
train
goraft/raft
snapshot.go
Decode
func (resp *SnapshotResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotResponse{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } resp.Success = pb.GetSuccess() return totalBytes, nil }
go
func (resp *SnapshotResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return 0, err } totalBytes := len(data) pb := &protobuf.SnapshotResponse{} if err := proto.Unmarshal(data, pb); err != nil { return -1, err } resp.Success = pb.GetSuccess() return totalBytes, nil }
[ "func", "(", "resp", "*", "SnapshotResponse", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "return...
// Decodes the SnapshotResponse from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "SnapshotResponse", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L287-L304
train
goraft/raft
log_entry.go
newLogEntry
func newLogEntry(log *Log, event *ev, index uint64, term uint64, command Command) (*LogEntry, error) { var buf bytes.Buffer var commandName string if command != nil { commandName = command.CommandName() if encoder, ok := command.(CommandEncoder); ok { if err := encoder.Encode(&buf); err != nil { return nil, err } } else { if err := json.NewEncoder(&buf).Encode(command); err != nil { return nil, err } } } pb := &protobuf.LogEntry{ Index: proto.Uint64(index), Term: proto.Uint64(term), CommandName: proto.String(commandName), Command: buf.Bytes(), } e := &LogEntry{ pb: pb, log: log, event: event, } return e, nil }
go
func newLogEntry(log *Log, event *ev, index uint64, term uint64, command Command) (*LogEntry, error) { var buf bytes.Buffer var commandName string if command != nil { commandName = command.CommandName() if encoder, ok := command.(CommandEncoder); ok { if err := encoder.Encode(&buf); err != nil { return nil, err } } else { if err := json.NewEncoder(&buf).Encode(command); err != nil { return nil, err } } } pb := &protobuf.LogEntry{ Index: proto.Uint64(index), Term: proto.Uint64(term), CommandName: proto.String(commandName), Command: buf.Bytes(), } e := &LogEntry{ pb: pb, log: log, event: event, } return e, nil }
[ "func", "newLogEntry", "(", "log", "*", "Log", ",", "event", "*", "ev", ",", "index", "uint64", ",", "term", "uint64", ",", "command", "Command", ")", "(", "*", "LogEntry", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "var", ...
// Creates a new log entry associated with a log.
[ "Creates", "a", "new", "log", "entry", "associated", "with", "a", "log", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L22-L52
train
goraft/raft
log_entry.go
Encode
func (e *LogEntry) Encode(w io.Writer) (int, error) { b, err := proto.Marshal(e.pb) if err != nil { return -1, err } if _, err = fmt.Fprintf(w, "%8x\n", len(b)); err != nil { return -1, err } return w.Write(b) }
go
func (e *LogEntry) Encode(w io.Writer) (int, error) { b, err := proto.Marshal(e.pb) if err != nil { return -1, err } if _, err = fmt.Fprintf(w, "%8x\n", len(b)); err != nil { return -1, err } return w.Write(b) }
[ "func", "(", "e", "*", "LogEntry", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "e", ".", "pb", ")", "\n", "if", "err", "!=", "nil", "{", "return",...
// Encodes the log entry to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "log", "entry", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L72-L83
train
goraft/raft
log_entry.go
Decode
func (e *LogEntry) Decode(r io.Reader) (int, error) { var length int _, err := fmt.Fscanf(r, "%8x\n", &length) if err != nil { return -1, err } data := make([]byte, length) _, err = io.ReadFull(r, data) if err != nil { return -1, err } if err = proto.Unmarshal(data, e.pb); err != nil { return -1, err } return length + 8 + 1, nil }
go
func (e *LogEntry) Decode(r io.Reader) (int, error) { var length int _, err := fmt.Fscanf(r, "%8x\n", &length) if err != nil { return -1, err } data := make([]byte, length) _, err = io.ReadFull(r, data) if err != nil { return -1, err } if err = proto.Unmarshal(data, e.pb); err != nil { return -1, err } return length + 8 + 1, nil }
[ "func", "(", "e", "*", "LogEntry", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "var", "length", "int", "\n", "_", ",", "err", ":=", "fmt", ".", "Fscanf", "(", "r", ",", "\"", "\\n", "\"", ",", "&", ...
// Decodes the log entry from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "log", "entry", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L87-L107
train
goraft/raft
util.go
afterBetween
func afterBetween(min time.Duration, max time.Duration) <-chan time.Time { rand := rand.New(rand.NewSource(time.Now().UnixNano())) d, delta := min, (max - min) if delta > 0 { d += time.Duration(rand.Int63n(int64(delta))) } return time.After(d) }
go
func afterBetween(min time.Duration, max time.Duration) <-chan time.Time { rand := rand.New(rand.NewSource(time.Now().UnixNano())) d, delta := min, (max - min) if delta > 0 { d += time.Duration(rand.Int63n(int64(delta))) } return time.After(d) }
[ "func", "afterBetween", "(", "min", "time", ".", "Duration", ",", "max", "time", ".", "Duration", ")", "<-", "chan", "time", ".", "Time", "{", "rand", ":=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", ...
// Waits for a random time between two durations and sends the current time on // the returned channel.
[ "Waits", "for", "a", "random", "time", "between", "two", "durations", "and", "sends", "the", "current", "time", "on", "the", "returned", "channel", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/util.go#L46-L53
train
goraft/raft
command.go
newCommand
func newCommand(name string, data []byte) (Command, error) { // Find the registered command. command := commandTypes[name] if command == nil { return nil, fmt.Errorf("raft.Command: Unregistered command type: %s", name) } // Make a copy of the command. v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface() copy, ok := v.(Command) if !ok { panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String())) } // If data for the command was passed in the decode it. if data != nil { if encoder, ok := copy.(CommandEncoder); ok { if err := encoder.Decode(bytes.NewReader(data)); err != nil { return nil, err } } else { if err := json.NewDecoder(bytes.NewReader(data)).Decode(copy); err != nil { return nil, err } } } return copy, nil }
go
func newCommand(name string, data []byte) (Command, error) { // Find the registered command. command := commandTypes[name] if command == nil { return nil, fmt.Errorf("raft.Command: Unregistered command type: %s", name) } // Make a copy of the command. v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface() copy, ok := v.(Command) if !ok { panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String())) } // If data for the command was passed in the decode it. if data != nil { if encoder, ok := copy.(CommandEncoder); ok { if err := encoder.Decode(bytes.NewReader(data)); err != nil { return nil, err } } else { if err := json.NewDecoder(bytes.NewReader(data)).Decode(copy); err != nil { return nil, err } } } return copy, nil }
[ "func", "newCommand", "(", "name", "string", ",", "data", "[", "]", "byte", ")", "(", "Command", ",", "error", ")", "{", "// Find the registered command.", "command", ":=", "commandTypes", "[", "name", "]", "\n", "if", "command", "==", "nil", "{", "return"...
// Creates a new instance of a command by name.
[ "Creates", "a", "new", "instance", "of", "a", "command", "by", "name", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/command.go#L38-L66
train
goraft/raft
command.go
RegisterCommand
func RegisterCommand(command Command) { if command == nil { panic(fmt.Sprintf("raft: Cannot register nil")) } else if commandTypes[command.CommandName()] != nil { panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName())) } commandTypes[command.CommandName()] = command }
go
func RegisterCommand(command Command) { if command == nil { panic(fmt.Sprintf("raft: Cannot register nil")) } else if commandTypes[command.CommandName()] != nil { panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName())) } commandTypes[command.CommandName()] = command }
[ "func", "RegisterCommand", "(", "command", "Command", ")", "{", "if", "command", "==", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ")", "\n", "}", "else", "if", "commandTypes", "[", "command", ".", "CommandName", "(", ")", ...
// Registers a command by storing a reference to an instance of it.
[ "Registers", "a", "command", "by", "storing", "a", "reference", "to", "an", "instance", "of", "it", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/command.go#L69-L76
train
goraft/raft
http_transporter.go
SendVoteRequest
func (t *HTTPTransporter) SendVoteRequest(server Server, peer *Peer, req *RequestVoteRequest) *RequestVoteResponse { var b bytes.Buffer if _, err := req.Encode(&b); err != nil { traceln("transporter.rv.encoding.error:", err) return nil } url := fmt.Sprintf("%s%s", peer.ConnectionString, t.RequestVotePath()) traceln(server.Name(), "POST", url) httpResp, err := t.httpClient.Post(url, "application/protobuf", &b) if httpResp == nil || err != nil { traceln("transporter.rv.response.error:", err) return nil } defer httpResp.Body.Close() resp := &RequestVoteResponse{} if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF { traceln("transporter.rv.decoding.error:", err) return nil } return resp }
go
func (t *HTTPTransporter) SendVoteRequest(server Server, peer *Peer, req *RequestVoteRequest) *RequestVoteResponse { var b bytes.Buffer if _, err := req.Encode(&b); err != nil { traceln("transporter.rv.encoding.error:", err) return nil } url := fmt.Sprintf("%s%s", peer.ConnectionString, t.RequestVotePath()) traceln(server.Name(), "POST", url) httpResp, err := t.httpClient.Post(url, "application/protobuf", &b) if httpResp == nil || err != nil { traceln("transporter.rv.response.error:", err) return nil } defer httpResp.Body.Close() resp := &RequestVoteResponse{} if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF { traceln("transporter.rv.decoding.error:", err) return nil } return resp }
[ "func", "(", "t", "*", "HTTPTransporter", ")", "SendVoteRequest", "(", "server", "Server", ",", "peer", "*", "Peer", ",", "req", "*", "RequestVoteRequest", ")", "*", "RequestVoteResponse", "{", "var", "b", "bytes", ".", "Buffer", "\n", "if", "_", ",", "e...
// Sends a RequestVote RPC to a peer.
[ "Sends", "a", "RequestVote", "RPC", "to", "a", "peer", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/http_transporter.go#L142-L166
train
goraft/raft
append_entries.go
newAppendEntriesRequest
func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64, commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest { pbEntries := make([]*protobuf.LogEntry, len(entries)) for i := range entries { pbEntries[i] = entries[i].pb } return &AppendEntriesRequest{ Term: term, PrevLogIndex: prevLogIndex, PrevLogTerm: prevLogTerm, CommitIndex: commitIndex, LeaderName: leaderName, Entries: pbEntries, } }
go
func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64, commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest { pbEntries := make([]*protobuf.LogEntry, len(entries)) for i := range entries { pbEntries[i] = entries[i].pb } return &AppendEntriesRequest{ Term: term, PrevLogIndex: prevLogIndex, PrevLogTerm: prevLogTerm, CommitIndex: commitIndex, LeaderName: leaderName, Entries: pbEntries, } }
[ "func", "newAppendEntriesRequest", "(", "term", "uint64", ",", "prevLogIndex", "uint64", ",", "prevLogTerm", "uint64", ",", "commitIndex", "uint64", ",", "leaderName", "string", ",", "entries", "[", "]", "*", "LogEntry", ")", "*", "AppendEntriesRequest", "{", "p...
// Creates a new AppendEntries request.
[ "Creates", "a", "new", "AppendEntries", "request", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L29-L45
train
goraft/raft
append_entries.go
Encode
func (req *AppendEntriesRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.AppendEntriesRequest{ Term: proto.Uint64(req.Term), PrevLogIndex: proto.Uint64(req.PrevLogIndex), PrevLogTerm: proto.Uint64(req.PrevLogTerm), CommitIndex: proto.Uint64(req.CommitIndex), LeaderName: proto.String(req.LeaderName), Entries: req.Entries, } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
go
func (req *AppendEntriesRequest) Encode(w io.Writer) (int, error) { pb := &protobuf.AppendEntriesRequest{ Term: proto.Uint64(req.Term), PrevLogIndex: proto.Uint64(req.PrevLogIndex), PrevLogTerm: proto.Uint64(req.PrevLogTerm), CommitIndex: proto.Uint64(req.CommitIndex), LeaderName: proto.String(req.LeaderName), Entries: req.Entries, } p, err := proto.Marshal(pb) if err != nil { return -1, err } return w.Write(p) }
[ "func", "(", "req", "*", "AppendEntriesRequest", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "pb", ":=", "&", "protobuf", ".", "AppendEntriesRequest", "{", "Term", ":", "proto", ".", "Uint64", "(", "req", "....
// Encodes the AppendEntriesRequest to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "AppendEntriesRequest", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L49-L65
train
goraft/raft
append_entries.go
Decode
func (req *AppendEntriesRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } pb := new(protobuf.AppendEntriesRequest) if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.PrevLogIndex = pb.GetPrevLogIndex() req.PrevLogTerm = pb.GetPrevLogTerm() req.CommitIndex = pb.GetCommitIndex() req.LeaderName = pb.GetLeaderName() req.Entries = pb.GetEntries() return len(data), nil }
go
func (req *AppendEntriesRequest) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } pb := new(protobuf.AppendEntriesRequest) if err := proto.Unmarshal(data, pb); err != nil { return -1, err } req.Term = pb.GetTerm() req.PrevLogIndex = pb.GetPrevLogIndex() req.PrevLogTerm = pb.GetPrevLogTerm() req.CommitIndex = pb.GetCommitIndex() req.LeaderName = pb.GetLeaderName() req.Entries = pb.GetEntries() return len(data), nil }
[ "func", "(", "req", "*", "AppendEntriesRequest", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "if", "err", "!=", "nil", "{", "ret...
// Decodes the AppendEntriesRequest from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "AppendEntriesRequest", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L69-L89
train
goraft/raft
append_entries.go
newAppendEntriesResponse
func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse { pb := &protobuf.AppendEntriesResponse{ Term: proto.Uint64(term), Index: proto.Uint64(index), Success: proto.Bool(success), CommitIndex: proto.Uint64(commitIndex), } return &AppendEntriesResponse{ pb: pb, } }
go
func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse { pb := &protobuf.AppendEntriesResponse{ Term: proto.Uint64(term), Index: proto.Uint64(index), Success: proto.Bool(success), CommitIndex: proto.Uint64(commitIndex), } return &AppendEntriesResponse{ pb: pb, } }
[ "func", "newAppendEntriesResponse", "(", "term", "uint64", ",", "success", "bool", ",", "index", "uint64", ",", "commitIndex", "uint64", ")", "*", "AppendEntriesResponse", "{", "pb", ":=", "&", "protobuf", ".", "AppendEntriesResponse", "{", "Term", ":", "proto",...
// Creates a new AppendEntries response.
[ "Creates", "a", "new", "AppendEntries", "response", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L92-L103
train
goraft/raft
append_entries.go
Encode
func (resp *AppendEntriesResponse) Encode(w io.Writer) (int, error) { b, err := proto.Marshal(resp.pb) if err != nil { return -1, err } return w.Write(b) }
go
func (resp *AppendEntriesResponse) Encode(w io.Writer) (int, error) { b, err := proto.Marshal(resp.pb) if err != nil { return -1, err } return w.Write(b) }
[ "func", "(", "resp", "*", "AppendEntriesResponse", ")", "Encode", "(", "w", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "resp", ".", "pb", ")", "\n", "if", "err", "!=", "nil",...
// Encodes the AppendEntriesResponse to a buffer. Returns the number of bytes // written and any error that may have occurred.
[ "Encodes", "the", "AppendEntriesResponse", "to", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "written", "and", "any", "error", "that", "may", "have", "occurred", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L123-L130
train
goraft/raft
append_entries.go
Decode
func (resp *AppendEntriesResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } resp.pb = new(protobuf.AppendEntriesResponse) if err := proto.Unmarshal(data, resp.pb); err != nil { return -1, err } return len(data), nil }
go
func (resp *AppendEntriesResponse) Decode(r io.Reader) (int, error) { data, err := ioutil.ReadAll(r) if err != nil { return -1, err } resp.pb = new(protobuf.AppendEntriesResponse) if err := proto.Unmarshal(data, resp.pb); err != nil { return -1, err } return len(data), nil }
[ "func", "(", "resp", "*", "AppendEntriesResponse", ")", "Decode", "(", "r", "io", ".", "Reader", ")", "(", "int", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "ret...
// Decodes the AppendEntriesResponse from a buffer. Returns the number of bytes read and // any error that occurs.
[ "Decodes", "the", "AppendEntriesResponse", "from", "a", "buffer", ".", "Returns", "the", "number", "of", "bytes", "read", "and", "any", "error", "that", "occurs", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L134-L146
train
goraft/raft
server.go
Peers
func (s *server) Peers() map[string]*Peer { s.mutex.Lock() defer s.mutex.Unlock() peers := make(map[string]*Peer) for name, peer := range s.peers { peers[name] = peer.clone() } return peers }
go
func (s *server) Peers() map[string]*Peer { s.mutex.Lock() defer s.mutex.Unlock() peers := make(map[string]*Peer) for name, peer := range s.peers { peers[name] = peer.clone() } return peers }
[ "func", "(", "s", "*", "server", ")", "Peers", "(", ")", "map", "[", "string", "]", "*", "Peer", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "peers", ":=", "make", "(", "ma...
// Retrieves a copy of the peer data.
[ "Retrieves", "a", "copy", "of", "the", "peer", "data", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L241-L250
train
goraft/raft
server.go
Transporter
func (s *server) Transporter() Transporter { s.mutex.RLock() defer s.mutex.RUnlock() return s.transporter }
go
func (s *server) Transporter() Transporter { s.mutex.RLock() defer s.mutex.RUnlock() return s.transporter }
[ "func", "(", "s", "*", "server", ")", "Transporter", "(", ")", "Transporter", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "transporter", "\n", "}" ]
// Retrieves the object that transports requests.
[ "Retrieves", "the", "object", "that", "transports", "requests", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L253-L257
train
goraft/raft
server.go
State
func (s *server) State() string { s.mutex.RLock() defer s.mutex.RUnlock() return s.state }
go
func (s *server) State() string { s.mutex.RLock() defer s.mutex.RUnlock() return s.state }
[ "func", "(", "s", "*", "server", ")", "State", "(", ")", "string", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "state", "\n", "}" ]
// Retrieves the current state of the server.
[ "Retrieves", "the", "current", "state", "of", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L281-L285
train
goraft/raft
server.go
setState
func (s *server) setState(state string) { s.mutex.Lock() defer s.mutex.Unlock() // Temporarily store previous values. prevState := s.state prevLeader := s.leader // Update state and leader. s.state = state if state == Leader { s.leader = s.Name() s.syncedPeer = make(map[string]bool) } // Dispatch state and leader change events. s.DispatchEvent(newEvent(StateChangeEventType, s.state, prevState)) if prevLeader != s.leader { s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader)) } }
go
func (s *server) setState(state string) { s.mutex.Lock() defer s.mutex.Unlock() // Temporarily store previous values. prevState := s.state prevLeader := s.leader // Update state and leader. s.state = state if state == Leader { s.leader = s.Name() s.syncedPeer = make(map[string]bool) } // Dispatch state and leader change events. s.DispatchEvent(newEvent(StateChangeEventType, s.state, prevState)) if prevLeader != s.leader { s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader)) } }
[ "func", "(", "s", "*", "server", ")", "setState", "(", "state", "string", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// Temporarily store previous values.", "prevState", ":=", ...
// Sets the state of the server.
[ "Sets", "the", "state", "of", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L288-L309
train
goraft/raft
server.go
Term
func (s *server) Term() uint64 { s.mutex.RLock() defer s.mutex.RUnlock() return s.currentTerm }
go
func (s *server) Term() uint64 { s.mutex.RLock() defer s.mutex.RUnlock() return s.currentTerm }
[ "func", "(", "s", "*", "server", ")", "Term", "(", ")", "uint64", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "currentTerm", "\n", "}" ]
// Retrieves the current term of the server.
[ "Retrieves", "the", "current", "term", "of", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L312-L316
train
goraft/raft
server.go
CommitIndex
func (s *server) CommitIndex() uint64 { s.log.mutex.RLock() defer s.log.mutex.RUnlock() return s.log.commitIndex }
go
func (s *server) CommitIndex() uint64 { s.log.mutex.RLock() defer s.log.mutex.RUnlock() return s.log.commitIndex }
[ "func", "(", "s", "*", "server", ")", "CommitIndex", "(", ")", "uint64", "{", "s", ".", "log", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "log", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "log", ".", ...
// Retrieves the current commit index of the server.
[ "Retrieves", "the", "current", "commit", "index", "of", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L319-L323
train
goraft/raft
server.go
LogEntries
func (s *server) LogEntries() []*LogEntry { s.log.mutex.RLock() defer s.log.mutex.RUnlock() return s.log.entries }
go
func (s *server) LogEntries() []*LogEntry { s.log.mutex.RLock() defer s.log.mutex.RUnlock() return s.log.entries }
[ "func", "(", "s", "*", "server", ")", "LogEntries", "(", ")", "[", "]", "*", "LogEntry", "{", "s", ".", "log", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "log", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ...
// A list of all the log entries. This should only be used for debugging purposes.
[ "A", "list", "of", "all", "the", "log", "entries", ".", "This", "should", "only", "be", "used", "for", "debugging", "purposes", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L336-L340
train
goraft/raft
server.go
GetState
func (s *server) GetState() string { s.mutex.RLock() defer s.mutex.RUnlock() return fmt.Sprintf("Name: %s, State: %s, Term: %v, CommitedIndex: %v ", s.name, s.state, s.currentTerm, s.log.commitIndex) }
go
func (s *server) GetState() string { s.mutex.RLock() defer s.mutex.RUnlock() return fmt.Sprintf("Name: %s, State: %s, Term: %v, CommitedIndex: %v ", s.name, s.state, s.currentTerm, s.log.commitIndex) }
[ "func", "(", "s", "*", "server", ")", "GetState", "(", ")", "string", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ...
// Get the state of the server for debugging
[ "Get", "the", "state", "of", "the", "server", "for", "debugging" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L348-L352
train
goraft/raft
server.go
SetElectionTimeout
func (s *server) SetElectionTimeout(duration time.Duration) { s.mutex.Lock() defer s.mutex.Unlock() s.electionTimeout = duration }
go
func (s *server) SetElectionTimeout(duration time.Duration) { s.mutex.Lock() defer s.mutex.Unlock() s.electionTimeout = duration }
[ "func", "(", "s", "*", "server", ")", "SetElectionTimeout", "(", "duration", "time", ".", "Duration", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n", "s", ".", "electionTimeout", ...
// Sets the election timeout.
[ "Sets", "the", "election", "timeout", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L387-L391
train
goraft/raft
server.go
SetHeartbeatInterval
func (s *server) SetHeartbeatInterval(duration time.Duration) { s.mutex.Lock() defer s.mutex.Unlock() s.heartbeatInterval = duration for _, peer := range s.peers { peer.setHeartbeatInterval(duration) } }
go
func (s *server) SetHeartbeatInterval(duration time.Duration) { s.mutex.Lock() defer s.mutex.Unlock() s.heartbeatInterval = duration for _, peer := range s.peers { peer.setHeartbeatInterval(duration) } }
[ "func", "(", "s", "*", "server", ")", "SetHeartbeatInterval", "(", "duration", "time", ".", "Duration", ")", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "s", ".", "heartbeatInterva...
// Sets the heartbeat timeout.
[ "Sets", "the", "heartbeat", "timeout", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L405-L413
train
goraft/raft
server.go
Start
func (s *server) Start() error { // Exit if the server is already running. if s.Running() { return fmt.Errorf("raft.Server: Server already running[%v]", s.state) } if err := s.Init(); err != nil { return err } // stopped needs to be allocated each time server starts // because it is closed at `Stop`. s.stopped = make(chan bool) s.setState(Follower) // If no log entries exist then // 1. wait for AEs from another node // 2. wait for self-join command // to set itself promotable if !s.promotable() { s.debugln("start as a new raft server") // If log entries exist then allow promotion to candidate // if no AEs received. } else { s.debugln("start from previous saved state") } debugln(s.GetState()) s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() s.loop() }() return nil }
go
func (s *server) Start() error { // Exit if the server is already running. if s.Running() { return fmt.Errorf("raft.Server: Server already running[%v]", s.state) } if err := s.Init(); err != nil { return err } // stopped needs to be allocated each time server starts // because it is closed at `Stop`. s.stopped = make(chan bool) s.setState(Follower) // If no log entries exist then // 1. wait for AEs from another node // 2. wait for self-join command // to set itself promotable if !s.promotable() { s.debugln("start as a new raft server") // If log entries exist then allow promotion to candidate // if no AEs received. } else { s.debugln("start from previous saved state") } debugln(s.GetState()) s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() s.loop() }() return nil }
[ "func", "(", "s", "*", "server", ")", "Start", "(", ")", "error", "{", "// Exit if the server is already running.", "if", "s", ".", "Running", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "state", ")", "\n", "}", "\n...
// Start the raft server // If log entries exist then allow promotion to candidate if no AEs received. // If no log entries exist then wait for AEs from another node. // If no log entries exist and a self-join command is issued then // immediately become leader and commit entry.
[ "Start", "the", "raft", "server", "If", "log", "entries", "exist", "then", "allow", "promotion", "to", "candidate", "if", "no", "AEs", "received", ".", "If", "no", "log", "entries", "exist", "then", "wait", "for", "AEs", "from", "another", "node", ".", "...
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L437-L474
train
goraft/raft
server.go
Stop
func (s *server) Stop() { if s.State() == Stopped { return } close(s.stopped) // make sure all goroutines have stopped before we close the log s.routineGroup.Wait() s.log.close() s.setState(Stopped) }
go
func (s *server) Stop() { if s.State() == Stopped { return } close(s.stopped) // make sure all goroutines have stopped before we close the log s.routineGroup.Wait() s.log.close() s.setState(Stopped) }
[ "func", "(", "s", "*", "server", ")", "Stop", "(", ")", "{", "if", "s", ".", "State", "(", ")", "==", "Stopped", "{", "return", "\n", "}", "\n\n", "close", "(", "s", ".", "stopped", ")", "\n\n", "// make sure all goroutines have stopped before we close the...
// Shuts down the server.
[ "Shuts", "down", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L518-L530
train
goraft/raft
server.go
Running
func (s *server) Running() bool { s.mutex.RLock() defer s.mutex.RUnlock() return (s.state != Stopped && s.state != Initialized) }
go
func (s *server) Running() bool { s.mutex.RLock() defer s.mutex.RUnlock() return (s.state != Stopped && s.state != Initialized) }
[ "func", "(", "s", "*", "server", ")", "Running", "(", ")", "bool", "{", "s", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "return", "(", "s", ".", "state", "!=", "Stopped", "&&", "s", ...
// Checks if the server is currently running.
[ "Checks", "if", "the", "server", "is", "currently", "running", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L533-L537
train
goraft/raft
server.go
send
func (s *server) send(value interface{}) (interface{}, error) { if !s.Running() { return nil, StopError } event := &ev{target: value, c: make(chan error, 1)} select { case s.c <- event: case <-s.stopped: return nil, StopError } select { case <-s.stopped: return nil, StopError case err := <-event.c: return event.returnValue, err } }
go
func (s *server) send(value interface{}) (interface{}, error) { if !s.Running() { return nil, StopError } event := &ev{target: value, c: make(chan error, 1)} select { case s.c <- event: case <-s.stopped: return nil, StopError } select { case <-s.stopped: return nil, StopError case err := <-event.c: return event.returnValue, err } }
[ "func", "(", "s", "*", "server", ")", "send", "(", "value", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "!", "s", ".", "Running", "(", ")", "{", "return", "nil", ",", "StopError", "\n", "}", "\n\n", "ev...
// Sends an event to the event loop to be processed. The function will wait // until the event is actually processed before returning.
[ "Sends", "an", "event", "to", "the", "event", "loop", "to", "be", "processed", ".", "The", "function", "will", "wait", "until", "the", "event", "is", "actually", "processed", "before", "returning", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L619-L636
train
goraft/raft
server.go
candidateLoop
func (s *server) candidateLoop() { // Clear leader value. prevLeader := s.leader s.leader = "" if prevLeader != s.leader { s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader)) } lastLogIndex, lastLogTerm := s.log.lastInfo() doVote := true votesGranted := 0 var timeoutChan <-chan time.Time var respChan chan *RequestVoteResponse for s.State() == Candidate { if doVote { // Increment current term, vote for self. s.currentTerm++ s.votedFor = s.name // Send RequestVote RPCs to all other servers. respChan = make(chan *RequestVoteResponse, len(s.peers)) for _, peer := range s.peers { s.routineGroup.Add(1) go func(peer *Peer) { defer s.routineGroup.Done() peer.sendVoteRequest(newRequestVoteRequest(s.currentTerm, s.name, lastLogIndex, lastLogTerm), respChan) }(peer) } // Wait for either: // * Votes received from majority of servers: become leader // * AppendEntries RPC received from new leader: step down. // * Election timeout elapses without election resolution: increment term, start new election // * Discover higher term: step down (§5.1) votesGranted = 1 timeoutChan = afterBetween(s.ElectionTimeout(), s.ElectionTimeout()*2) doVote = false } // If we received enough votes then stop waiting for more votes. // And return from the candidate loop if votesGranted == s.QuorumSize() { s.debugln("server.candidate.recv.enough.votes") s.setState(Leader) return } // Collect votes from peers. select { case <-s.stopped: s.setState(Stopped) return case resp := <-respChan: if success := s.processVoteResponse(resp); success { s.debugln("server.candidate.vote.granted: ", votesGranted) votesGranted++ } case e := <-s.c: var err error switch req := e.target.(type) { case Command: err = NotLeaderError case *AppendEntriesRequest: e.returnValue, _ = s.processAppendEntriesRequest(req) case *RequestVoteRequest: e.returnValue, _ = s.processRequestVoteRequest(req) } // Callback to event. e.c <- err case <-timeoutChan: doVote = true } } }
go
func (s *server) candidateLoop() { // Clear leader value. prevLeader := s.leader s.leader = "" if prevLeader != s.leader { s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader)) } lastLogIndex, lastLogTerm := s.log.lastInfo() doVote := true votesGranted := 0 var timeoutChan <-chan time.Time var respChan chan *RequestVoteResponse for s.State() == Candidate { if doVote { // Increment current term, vote for self. s.currentTerm++ s.votedFor = s.name // Send RequestVote RPCs to all other servers. respChan = make(chan *RequestVoteResponse, len(s.peers)) for _, peer := range s.peers { s.routineGroup.Add(1) go func(peer *Peer) { defer s.routineGroup.Done() peer.sendVoteRequest(newRequestVoteRequest(s.currentTerm, s.name, lastLogIndex, lastLogTerm), respChan) }(peer) } // Wait for either: // * Votes received from majority of servers: become leader // * AppendEntries RPC received from new leader: step down. // * Election timeout elapses without election resolution: increment term, start new election // * Discover higher term: step down (§5.1) votesGranted = 1 timeoutChan = afterBetween(s.ElectionTimeout(), s.ElectionTimeout()*2) doVote = false } // If we received enough votes then stop waiting for more votes. // And return from the candidate loop if votesGranted == s.QuorumSize() { s.debugln("server.candidate.recv.enough.votes") s.setState(Leader) return } // Collect votes from peers. select { case <-s.stopped: s.setState(Stopped) return case resp := <-respChan: if success := s.processVoteResponse(resp); success { s.debugln("server.candidate.vote.granted: ", votesGranted) votesGranted++ } case e := <-s.c: var err error switch req := e.target.(type) { case Command: err = NotLeaderError case *AppendEntriesRequest: e.returnValue, _ = s.processAppendEntriesRequest(req) case *RequestVoteRequest: e.returnValue, _ = s.processRequestVoteRequest(req) } // Callback to event. e.c <- err case <-timeoutChan: doVote = true } } }
[ "func", "(", "s", "*", "server", ")", "candidateLoop", "(", ")", "{", "// Clear leader value.", "prevLeader", ":=", "s", ".", "leader", "\n", "s", ".", "leader", "=", "\"", "\"", "\n", "if", "prevLeader", "!=", "s", ".", "leader", "{", "s", ".", "Dis...
// The event loop that is run when the server is in a Candidate state.
[ "The", "event", "loop", "that", "is", "run", "when", "the", "server", "is", "in", "a", "Candidate", "state", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L730-L808
train
goraft/raft
server.go
leaderLoop
func (s *server) leaderLoop() { logIndex, _ := s.log.lastInfo() // Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat. s.debugln("leaderLoop.set.PrevIndex to ", logIndex) for _, peer := range s.peers { peer.setPrevLogIndex(logIndex) peer.startHeartbeat() } // Commit a NOP after the server becomes leader. From the Raft paper: // "Upon election: send initial empty AppendEntries RPCs (heartbeat) to // each server; repeat during idle periods to prevent election timeouts // (§5.2)". The heartbeats started above do the "idle" period work. s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() s.Do(NOPCommand{}) }() // Begin to collect response from followers for s.State() == Leader { var err error select { case <-s.stopped: // Stop all peers before stop for _, peer := range s.peers { peer.stopHeartbeat(false) } s.setState(Stopped) return case e := <-s.c: switch req := e.target.(type) { case Command: s.processCommand(req, e) continue case *AppendEntriesRequest: e.returnValue, _ = s.processAppendEntriesRequest(req) case *AppendEntriesResponse: s.processAppendEntriesResponse(req) case *RequestVoteRequest: e.returnValue, _ = s.processRequestVoteRequest(req) } // Callback to event. e.c <- err } } s.syncedPeer = nil }
go
func (s *server) leaderLoop() { logIndex, _ := s.log.lastInfo() // Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat. s.debugln("leaderLoop.set.PrevIndex to ", logIndex) for _, peer := range s.peers { peer.setPrevLogIndex(logIndex) peer.startHeartbeat() } // Commit a NOP after the server becomes leader. From the Raft paper: // "Upon election: send initial empty AppendEntries RPCs (heartbeat) to // each server; repeat during idle periods to prevent election timeouts // (§5.2)". The heartbeats started above do the "idle" period work. s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() s.Do(NOPCommand{}) }() // Begin to collect response from followers for s.State() == Leader { var err error select { case <-s.stopped: // Stop all peers before stop for _, peer := range s.peers { peer.stopHeartbeat(false) } s.setState(Stopped) return case e := <-s.c: switch req := e.target.(type) { case Command: s.processCommand(req, e) continue case *AppendEntriesRequest: e.returnValue, _ = s.processAppendEntriesRequest(req) case *AppendEntriesResponse: s.processAppendEntriesResponse(req) case *RequestVoteRequest: e.returnValue, _ = s.processRequestVoteRequest(req) } // Callback to event. e.c <- err } } s.syncedPeer = nil }
[ "func", "(", "s", "*", "server", ")", "leaderLoop", "(", ")", "{", "logIndex", ",", "_", ":=", "s", ".", "log", ".", "lastInfo", "(", ")", "\n\n", "// Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat.", "s", ".", "debugln", "(", "\"", ...
// The event loop that is run when the server is in a Leader state.
[ "The", "event", "loop", "that", "is", "run", "when", "the", "server", "is", "in", "a", "Leader", "state", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L811-L862
train
goraft/raft
server.go
processCommand
func (s *server) processCommand(command Command, e *ev) { s.debugln("server.command.process") // Create an entry for the command in the log. entry, err := s.log.createEntry(s.currentTerm, command, e) if err != nil { s.debugln("server.command.log.entry.error:", err) e.c <- err return } if err := s.log.appendEntry(entry); err != nil { s.debugln("server.command.log.error:", err) e.c <- err return } s.syncedPeer[s.Name()] = true if len(s.peers) == 0 { commitIndex := s.log.currentIndex() s.log.setCommitIndex(commitIndex) s.debugln("commit index ", commitIndex) } }
go
func (s *server) processCommand(command Command, e *ev) { s.debugln("server.command.process") // Create an entry for the command in the log. entry, err := s.log.createEntry(s.currentTerm, command, e) if err != nil { s.debugln("server.command.log.entry.error:", err) e.c <- err return } if err := s.log.appendEntry(entry); err != nil { s.debugln("server.command.log.error:", err) e.c <- err return } s.syncedPeer[s.Name()] = true if len(s.peers) == 0 { commitIndex := s.log.currentIndex() s.log.setCommitIndex(commitIndex) s.debugln("commit index ", commitIndex) } }
[ "func", "(", "s", "*", "server", ")", "processCommand", "(", "command", "Command", ",", "e", "*", "ev", ")", "{", "s", ".", "debugln", "(", "\"", "\"", ")", "\n\n", "// Create an entry for the command in the log.", "entry", ",", "err", ":=", "s", ".", "l...
// Processes a command.
[ "Processes", "a", "command", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L901-L925
train
goraft/raft
server.go
processAppendEntriesRequest
func (s *server) processAppendEntriesRequest(req *AppendEntriesRequest) (*AppendEntriesResponse, bool) { s.traceln("server.ae.process") if req.Term < s.currentTerm { s.debugln("server.ae.error: stale term") return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), false } if req.Term == s.currentTerm { _assert(s.State() != Leader, "leader.elected.at.same.term.%d\n", s.currentTerm) // step-down to follower when it is a candidate if s.state == Candidate { // change state to follower s.setState(Follower) } // discover new leader when candidate // save leader name when follower s.leader = req.LeaderName } else { // Update term and leader. s.updateCurrentTerm(req.Term, req.LeaderName) } // Reject if log doesn't contain a matching previous entry. if err := s.log.truncate(req.PrevLogIndex, req.PrevLogTerm); err != nil { s.debugln("server.ae.truncate.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // Append entries to the log. if err := s.log.appendEntries(req.Entries); err != nil { s.debugln("server.ae.append.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // Commit up to the commit index. if err := s.log.setCommitIndex(req.CommitIndex); err != nil { s.debugln("server.ae.commit.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // once the server appended and committed all the log entries from the leader return newAppendEntriesResponse(s.currentTerm, true, s.log.currentIndex(), s.log.CommitIndex()), true }
go
func (s *server) processAppendEntriesRequest(req *AppendEntriesRequest) (*AppendEntriesResponse, bool) { s.traceln("server.ae.process") if req.Term < s.currentTerm { s.debugln("server.ae.error: stale term") return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), false } if req.Term == s.currentTerm { _assert(s.State() != Leader, "leader.elected.at.same.term.%d\n", s.currentTerm) // step-down to follower when it is a candidate if s.state == Candidate { // change state to follower s.setState(Follower) } // discover new leader when candidate // save leader name when follower s.leader = req.LeaderName } else { // Update term and leader. s.updateCurrentTerm(req.Term, req.LeaderName) } // Reject if log doesn't contain a matching previous entry. if err := s.log.truncate(req.PrevLogIndex, req.PrevLogTerm); err != nil { s.debugln("server.ae.truncate.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // Append entries to the log. if err := s.log.appendEntries(req.Entries); err != nil { s.debugln("server.ae.append.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // Commit up to the commit index. if err := s.log.setCommitIndex(req.CommitIndex); err != nil { s.debugln("server.ae.commit.error: ", err) return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true } // once the server appended and committed all the log entries from the leader return newAppendEntriesResponse(s.currentTerm, true, s.log.currentIndex(), s.log.CommitIndex()), true }
[ "func", "(", "s", "*", "server", ")", "processAppendEntriesRequest", "(", "req", "*", "AppendEntriesRequest", ")", "(", "*", "AppendEntriesResponse", ",", "bool", ")", "{", "s", ".", "traceln", "(", "\"", "\"", ")", "\n\n", "if", "req", ".", "Term", "<",...
// Processes the "append entries" request.
[ "Processes", "the", "append", "entries", "request", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L939-L985
train
goraft/raft
server.go
processAppendEntriesResponse
func (s *server) processAppendEntriesResponse(resp *AppendEntriesResponse) { // If we find a higher term then change to a follower and exit. if resp.Term() > s.Term() { s.updateCurrentTerm(resp.Term(), "") return } // panic response if it's not successful. if !resp.Success() { return } // if one peer successfully append a log from the leader term, // we add it to the synced list if resp.append == true { s.syncedPeer[resp.peer] = true } // Increment the commit count to make sure we have a quorum before committing. if len(s.syncedPeer) < s.QuorumSize() { return } // Determine the committed index that a majority has. var indices []uint64 indices = append(indices, s.log.currentIndex()) for _, peer := range s.peers { indices = append(indices, peer.getPrevLogIndex()) } sort.Sort(sort.Reverse(uint64Slice(indices))) // We can commit up to the index which the majority of the members have appended. commitIndex := indices[s.QuorumSize()-1] committedIndex := s.log.commitIndex if commitIndex > committedIndex { // leader needs to do a fsync before committing log entries s.log.sync() s.log.setCommitIndex(commitIndex) s.debugln("commit index ", commitIndex) } }
go
func (s *server) processAppendEntriesResponse(resp *AppendEntriesResponse) { // If we find a higher term then change to a follower and exit. if resp.Term() > s.Term() { s.updateCurrentTerm(resp.Term(), "") return } // panic response if it's not successful. if !resp.Success() { return } // if one peer successfully append a log from the leader term, // we add it to the synced list if resp.append == true { s.syncedPeer[resp.peer] = true } // Increment the commit count to make sure we have a quorum before committing. if len(s.syncedPeer) < s.QuorumSize() { return } // Determine the committed index that a majority has. var indices []uint64 indices = append(indices, s.log.currentIndex()) for _, peer := range s.peers { indices = append(indices, peer.getPrevLogIndex()) } sort.Sort(sort.Reverse(uint64Slice(indices))) // We can commit up to the index which the majority of the members have appended. commitIndex := indices[s.QuorumSize()-1] committedIndex := s.log.commitIndex if commitIndex > committedIndex { // leader needs to do a fsync before committing log entries s.log.sync() s.log.setCommitIndex(commitIndex) s.debugln("commit index ", commitIndex) } }
[ "func", "(", "s", "*", "server", ")", "processAppendEntriesResponse", "(", "resp", "*", "AppendEntriesResponse", ")", "{", "// If we find a higher term then change to a follower and exit.", "if", "resp", ".", "Term", "(", ")", ">", "s", ".", "Term", "(", ")", "{",...
// Processes the "append entries" response from the peer. This is only // processed when the server is a leader. Responses received during other // states are dropped.
[ "Processes", "the", "append", "entries", "response", "from", "the", "peer", ".", "This", "is", "only", "processed", "when", "the", "server", "is", "a", "leader", ".", "Responses", "received", "during", "other", "states", "are", "dropped", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L990-L1031
train
goraft/raft
server.go
processRequestVoteRequest
func (s *server) processRequestVoteRequest(req *RequestVoteRequest) (*RequestVoteResponse, bool) { // If the request is coming from an old term then reject it. if req.Term < s.Term() { s.debugln("server.rv.deny.vote: cause stale term") return newRequestVoteResponse(s.currentTerm, false), false } // If the term of the request peer is larger than this node, update the term // If the term is equal and we've already voted for a different candidate then // don't vote for this candidate. if req.Term > s.Term() { s.updateCurrentTerm(req.Term, "") } else if s.votedFor != "" && s.votedFor != req.CandidateName { s.debugln("server.deny.vote: cause duplicate vote: ", req.CandidateName, " already vote for ", s.votedFor) return newRequestVoteResponse(s.currentTerm, false), false } // If the candidate's log is not at least as up-to-date as our last log then don't vote. lastIndex, lastTerm := s.log.lastInfo() if lastIndex > req.LastLogIndex || lastTerm > req.LastLogTerm { s.debugln("server.deny.vote: cause out of date log: ", req.CandidateName, "Index :[", lastIndex, "]", " [", req.LastLogIndex, "]", "Term :[", lastTerm, "]", " [", req.LastLogTerm, "]") return newRequestVoteResponse(s.currentTerm, false), false } // If we made it this far then cast a vote and reset our election time out. s.debugln("server.rv.vote: ", s.name, " votes for", req.CandidateName, "at term", req.Term) s.votedFor = req.CandidateName return newRequestVoteResponse(s.currentTerm, true), true }
go
func (s *server) processRequestVoteRequest(req *RequestVoteRequest) (*RequestVoteResponse, bool) { // If the request is coming from an old term then reject it. if req.Term < s.Term() { s.debugln("server.rv.deny.vote: cause stale term") return newRequestVoteResponse(s.currentTerm, false), false } // If the term of the request peer is larger than this node, update the term // If the term is equal and we've already voted for a different candidate then // don't vote for this candidate. if req.Term > s.Term() { s.updateCurrentTerm(req.Term, "") } else if s.votedFor != "" && s.votedFor != req.CandidateName { s.debugln("server.deny.vote: cause duplicate vote: ", req.CandidateName, " already vote for ", s.votedFor) return newRequestVoteResponse(s.currentTerm, false), false } // If the candidate's log is not at least as up-to-date as our last log then don't vote. lastIndex, lastTerm := s.log.lastInfo() if lastIndex > req.LastLogIndex || lastTerm > req.LastLogTerm { s.debugln("server.deny.vote: cause out of date log: ", req.CandidateName, "Index :[", lastIndex, "]", " [", req.LastLogIndex, "]", "Term :[", lastTerm, "]", " [", req.LastLogTerm, "]") return newRequestVoteResponse(s.currentTerm, false), false } // If we made it this far then cast a vote and reset our election time out. s.debugln("server.rv.vote: ", s.name, " votes for", req.CandidateName, "at term", req.Term) s.votedFor = req.CandidateName return newRequestVoteResponse(s.currentTerm, true), true }
[ "func", "(", "s", "*", "server", ")", "processRequestVoteRequest", "(", "req", "*", "RequestVoteRequest", ")", "(", "*", "RequestVoteResponse", ",", "bool", ")", "{", "// If the request is coming from an old term then reject it.", "if", "req", ".", "Term", "<", "s",...
// Processes a "request vote" request.
[ "Processes", "a", "request", "vote", "request", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1066-L1099
train
goraft/raft
server.go
RemovePeer
func (s *server) RemovePeer(name string) error { s.debugln("server.peer.remove: ", name, len(s.peers)) // Skip the Peer if it has the same name as the Server if name != s.Name() { // Return error if peer doesn't exist. peer := s.peers[name] if peer == nil { return fmt.Errorf("raft: Peer not found: %s", name) } // Stop peer and remove it. if s.State() == Leader { // We create a go routine here to avoid potential deadlock. // We are holding log write lock when reach this line of code. // Peer.stopHeartbeat can be blocked without go routine, if the // target go routine (which we want to stop) is calling // log.getEntriesAfter and waiting for log read lock. // So we might be holding log lock and waiting for log lock, // which lead to a deadlock. // TODO(xiangli) refactor log lock s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() peer.stopHeartbeat(true) }() } delete(s.peers, name) s.DispatchEvent(newEvent(RemovePeerEventType, name, nil)) } // Write the configuration to file. s.writeConf() return nil }
go
func (s *server) RemovePeer(name string) error { s.debugln("server.peer.remove: ", name, len(s.peers)) // Skip the Peer if it has the same name as the Server if name != s.Name() { // Return error if peer doesn't exist. peer := s.peers[name] if peer == nil { return fmt.Errorf("raft: Peer not found: %s", name) } // Stop peer and remove it. if s.State() == Leader { // We create a go routine here to avoid potential deadlock. // We are holding log write lock when reach this line of code. // Peer.stopHeartbeat can be blocked without go routine, if the // target go routine (which we want to stop) is calling // log.getEntriesAfter and waiting for log read lock. // So we might be holding log lock and waiting for log lock, // which lead to a deadlock. // TODO(xiangli) refactor log lock s.routineGroup.Add(1) go func() { defer s.routineGroup.Done() peer.stopHeartbeat(true) }() } delete(s.peers, name) s.DispatchEvent(newEvent(RemovePeerEventType, name, nil)) } // Write the configuration to file. s.writeConf() return nil }
[ "func", "(", "s", "*", "server", ")", "RemovePeer", "(", "name", "string", ")", "error", "{", "s", ".", "debugln", "(", "\"", "\"", ",", "name", ",", "len", "(", "s", ".", "peers", ")", ")", "\n\n", "// Skip the Peer if it has the same name as the Server",...
// Removes a peer from the server.
[ "Removes", "a", "peer", "from", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1134-L1171
train
goraft/raft
server.go
LoadSnapshot
func (s *server) LoadSnapshot() error { // Open snapshot/ directory. dir, err := os.OpenFile(path.Join(s.path, "snapshot"), os.O_RDONLY, 0) if err != nil { s.debugln("cannot.open.snapshot: ", err) return err } // Retrieve a list of all snapshots. filenames, err := dir.Readdirnames(-1) if err != nil { dir.Close() panic(err) } dir.Close() if len(filenames) == 0 { s.debugln("no.snapshot.to.load") return nil } // Grab the latest snapshot. sort.Strings(filenames) snapshotPath := path.Join(s.path, "snapshot", filenames[len(filenames)-1]) // Read snapshot data. file, err := os.OpenFile(snapshotPath, os.O_RDONLY, 0) if err != nil { return err } defer file.Close() // Check checksum. var checksum uint32 n, err := fmt.Fscanf(file, "%08x\n", &checksum) if err != nil { return err } else if n != 1 { return errors.New("checksum.err: bad.snapshot.file") } // Load remaining snapshot contents. b, err := ioutil.ReadAll(file) if err != nil { return err } // Generate checksum. byteChecksum := crc32.ChecksumIEEE(b) if uint32(checksum) != byteChecksum { s.debugln(checksum, " ", byteChecksum) return errors.New("bad snapshot file") } // Decode snapshot. if err = json.Unmarshal(b, &s.snapshot); err != nil { s.debugln("unmarshal.snapshot.error: ", err) return err } // Recover snapshot into state machine. if err = s.stateMachine.Recovery(s.snapshot.State); err != nil { s.debugln("recovery.snapshot.error: ", err) return err } // Recover cluster configuration. for _, peer := range s.snapshot.Peers { s.AddPeer(peer.Name, peer.ConnectionString) } // Update log state. s.log.startTerm = s.snapshot.LastTerm s.log.startIndex = s.snapshot.LastIndex s.log.updateCommitIndex(s.snapshot.LastIndex) return err }
go
func (s *server) LoadSnapshot() error { // Open snapshot/ directory. dir, err := os.OpenFile(path.Join(s.path, "snapshot"), os.O_RDONLY, 0) if err != nil { s.debugln("cannot.open.snapshot: ", err) return err } // Retrieve a list of all snapshots. filenames, err := dir.Readdirnames(-1) if err != nil { dir.Close() panic(err) } dir.Close() if len(filenames) == 0 { s.debugln("no.snapshot.to.load") return nil } // Grab the latest snapshot. sort.Strings(filenames) snapshotPath := path.Join(s.path, "snapshot", filenames[len(filenames)-1]) // Read snapshot data. file, err := os.OpenFile(snapshotPath, os.O_RDONLY, 0) if err != nil { return err } defer file.Close() // Check checksum. var checksum uint32 n, err := fmt.Fscanf(file, "%08x\n", &checksum) if err != nil { return err } else if n != 1 { return errors.New("checksum.err: bad.snapshot.file") } // Load remaining snapshot contents. b, err := ioutil.ReadAll(file) if err != nil { return err } // Generate checksum. byteChecksum := crc32.ChecksumIEEE(b) if uint32(checksum) != byteChecksum { s.debugln(checksum, " ", byteChecksum) return errors.New("bad snapshot file") } // Decode snapshot. if err = json.Unmarshal(b, &s.snapshot); err != nil { s.debugln("unmarshal.snapshot.error: ", err) return err } // Recover snapshot into state machine. if err = s.stateMachine.Recovery(s.snapshot.State); err != nil { s.debugln("recovery.snapshot.error: ", err) return err } // Recover cluster configuration. for _, peer := range s.snapshot.Peers { s.AddPeer(peer.Name, peer.ConnectionString) } // Update log state. s.log.startTerm = s.snapshot.LastTerm s.log.startIndex = s.snapshot.LastIndex s.log.updateCommitIndex(s.snapshot.LastIndex) return err }
[ "func", "(", "s", "*", "server", ")", "LoadSnapshot", "(", ")", "error", "{", "// Open snapshot/ directory.", "dir", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ".", "Join", "(", "s", ".", "path", ",", "\"", "\"", ")", ",", "os", ".", "O_...
// Load a snapshot at restart
[ "Load", "a", "snapshot", "at", "restart" ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1316-L1393
train
goraft/raft
server.go
readConf
func (s *server) readConf() error { confPath := path.Join(s.path, "conf") s.debugln("readConf.open ", confPath) // open conf file b, err := ioutil.ReadFile(confPath) if err != nil { return nil } conf := &Config{} if err = json.Unmarshal(b, conf); err != nil { return err } s.log.updateCommitIndex(conf.CommitIndex) return nil }
go
func (s *server) readConf() error { confPath := path.Join(s.path, "conf") s.debugln("readConf.open ", confPath) // open conf file b, err := ioutil.ReadFile(confPath) if err != nil { return nil } conf := &Config{} if err = json.Unmarshal(b, conf); err != nil { return err } s.log.updateCommitIndex(conf.CommitIndex) return nil }
[ "func", "(", "s", "*", "server", ")", "readConf", "(", ")", "error", "{", "confPath", ":=", "path", ".", "Join", "(", "s", ".", "path", ",", "\"", "\"", ")", "\n", "s", ".", "debugln", "(", "\"", "\"", ",", "confPath", ")", "\n\n", "// open conf ...
// Read the configuration for the server.
[ "Read", "the", "configuration", "for", "the", "server", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1437-L1457
train
goraft/raft
event.go
newEvent
func newEvent(typ string, value interface{}, prevValue interface{}) *event { return &event{ typ: typ, value: value, prevValue: prevValue, } }
go
func newEvent(typ string, value interface{}, prevValue interface{}) *event { return &event{ typ: typ, value: value, prevValue: prevValue, } }
[ "func", "newEvent", "(", "typ", "string", ",", "value", "interface", "{", "}", ",", "prevValue", "interface", "{", "}", ")", "*", "event", "{", "return", "&", "event", "{", "typ", ":", "typ", ",", "value", ":", "value", ",", "prevValue", ":", "prevVa...
// newEvent creates a new event.
[ "newEvent", "creates", "a", "new", "event", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event.go#L35-L41
train
goraft/raft
peer.go
setPrevLogIndex
func (p *Peer) setPrevLogIndex(value uint64) { p.Lock() defer p.Unlock() p.prevLogIndex = value }
go
func (p *Peer) setPrevLogIndex(value uint64) { p.Lock() defer p.Unlock() p.prevLogIndex = value }
[ "func", "(", "p", "*", "Peer", ")", "setPrevLogIndex", "(", "value", "uint64", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "p", ".", "prevLogIndex", "=", "value", "\n", "}" ]
// Sets the previous log index.
[ "Sets", "the", "previous", "log", "index", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L65-L69
train
goraft/raft
peer.go
stopHeartbeat
func (p *Peer) stopHeartbeat(flush bool) { p.setLastActivity(time.Time{}) p.stopChan <- flush }
go
func (p *Peer) stopHeartbeat(flush bool) { p.setLastActivity(time.Time{}) p.stopChan <- flush }
[ "func", "(", "p", "*", "Peer", ")", "stopHeartbeat", "(", "flush", "bool", ")", "{", "p", ".", "setLastActivity", "(", "time", ".", "Time", "{", "}", ")", "\n\n", "p", ".", "stopChan", "<-", "flush", "\n", "}" ]
// Stops the peer heartbeat.
[ "Stops", "the", "peer", "heartbeat", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L103-L107
train
goraft/raft
peer.go
LastActivity
func (p *Peer) LastActivity() time.Time { p.RLock() defer p.RUnlock() return p.lastActivity }
go
func (p *Peer) LastActivity() time.Time { p.RLock() defer p.RUnlock() return p.lastActivity }
[ "func", "(", "p", "*", "Peer", ")", "LastActivity", "(", ")", "time", ".", "Time", "{", "p", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "lastActivity", "\n", "}" ]
// LastActivity returns the last time any response was received from the peer.
[ "LastActivity", "returns", "the", "last", "time", "any", "response", "was", "received", "from", "the", "peer", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L110-L114
train
goraft/raft
peer.go
sendSnapshotRequest
func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) { debugln("peer.snap.send: ", p.Name) resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req) if resp == nil { debugln("peer.snap.timeout: ", p.Name) return } debugln("peer.snap.recv: ", p.Name) // If successful, the peer should have been to snapshot state // Send it the snapshot! p.setLastActivity(time.Now()) if resp.Success { p.sendSnapshotRecoveryRequest() } else { debugln("peer.snap.failed: ", p.Name) return } }
go
func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) { debugln("peer.snap.send: ", p.Name) resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req) if resp == nil { debugln("peer.snap.timeout: ", p.Name) return } debugln("peer.snap.recv: ", p.Name) // If successful, the peer should have been to snapshot state // Send it the snapshot! p.setLastActivity(time.Now()) if resp.Success { p.sendSnapshotRecoveryRequest() } else { debugln("peer.snap.failed: ", p.Name) return } }
[ "func", "(", "p", "*", "Peer", ")", "sendSnapshotRequest", "(", "req", "*", "SnapshotRequest", ")", "{", "debugln", "(", "\"", "\"", ",", "p", ".", "Name", ")", "\n\n", "resp", ":=", "p", ".", "server", ".", "Transporter", "(", ")", ".", "SendSnapsho...
// Sends an Snapshot request to the peer through the transport.
[ "Sends", "an", "Snapshot", "request", "to", "the", "peer", "through", "the", "transport", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L258-L280
train
goraft/raft
peer.go
sendSnapshotRecoveryRequest
func (p *Peer) sendSnapshotRecoveryRequest() { req := newSnapshotRecoveryRequest(p.server.name, p.server.snapshot) debugln("peer.snap.recovery.send: ", p.Name) resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req) if resp == nil { debugln("peer.snap.recovery.timeout: ", p.Name) return } p.setLastActivity(time.Now()) if resp.Success { p.prevLogIndex = req.LastIndex } else { debugln("peer.snap.recovery.failed: ", p.Name) return } p.server.sendAsync(resp) }
go
func (p *Peer) sendSnapshotRecoveryRequest() { req := newSnapshotRecoveryRequest(p.server.name, p.server.snapshot) debugln("peer.snap.recovery.send: ", p.Name) resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req) if resp == nil { debugln("peer.snap.recovery.timeout: ", p.Name) return } p.setLastActivity(time.Now()) if resp.Success { p.prevLogIndex = req.LastIndex } else { debugln("peer.snap.recovery.failed: ", p.Name) return } p.server.sendAsync(resp) }
[ "func", "(", "p", "*", "Peer", ")", "sendSnapshotRecoveryRequest", "(", ")", "{", "req", ":=", "newSnapshotRecoveryRequest", "(", "p", ".", "server", ".", "name", ",", "p", ".", "server", ".", "snapshot", ")", "\n", "debugln", "(", "\"", "\"", ",", "p"...
// Sends an Snapshot Recovery request to the peer through the transport.
[ "Sends", "an", "Snapshot", "Recovery", "request", "to", "the", "peer", "through", "the", "transport", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L283-L302
train
goraft/raft
debug.go
debugf
func debugf(format string, v ...interface{}) { if logLevel >= Debug { logger.Printf(format, v...) } }
go
func debugf(format string, v ...interface{}) { if logLevel >= Debug { logger.Printf(format, v...) } }
[ "func", "debugf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "if", "logLevel", ">=", "Debug", "{", "logger", ".", "Printf", "(", "format", ",", "v", "...", ")", "\n", "}", "\n", "}" ]
// Prints to the standard logger if debug mode is enabled. Arguments // are handled in the manner of fmt.Printf.
[ "Prints", "to", "the", "standard", "logger", "if", "debug", "mode", "is", "enabled", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Printf", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/debug.go#L76-L80
train
goraft/raft
debug.go
tracef
func tracef(format string, v ...interface{}) { if logLevel >= Trace { logger.Printf(format, v...) } }
go
func tracef(format string, v ...interface{}) { if logLevel >= Trace { logger.Printf(format, v...) } }
[ "func", "tracef", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "if", "logLevel", ">=", "Trace", "{", "logger", ".", "Printf", "(", "format", ",", "v", "...", ")", "\n", "}", "\n", "}" ]
// Prints to the standard logger if trace debugging is enabled. Arguments // are handled in the manner of fmt.Printf.
[ "Prints", "to", "the", "standard", "logger", "if", "trace", "debugging", "is", "enabled", ".", "Arguments", "are", "handled", "in", "the", "manner", "of", "fmt", ".", "Printf", "." ]
0061b6c82526bd96292f41fa72358ec13ee3853c
https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/debug.go#L104-L108
train
tebeka/selenium
common.go
filteredURL
func filteredURL(u string) string { // Hide password if set in URL m, err := url.Parse(u) if err != nil { return "" } if m.User != nil { if _, ok := m.User.Password(); ok { m.User = url.UserPassword(m.User.Username(), "__password__") } } return m.String() }
go
func filteredURL(u string) string { // Hide password if set in URL m, err := url.Parse(u) if err != nil { return "" } if m.User != nil { if _, ok := m.User.Password(); ok { m.User = url.UserPassword(m.User.Username(), "__password__") } } return m.String() }
[ "func", "filteredURL", "(", "u", "string", ")", "string", "{", "// Hide password if set in URL", "m", ",", "err", ":=", "url", ".", "Parse", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "m", ".", ...
// filteredURL replaces existing password from the given URL.
[ "filteredURL", "replaces", "existing", "password", "from", "the", "given", "URL", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/common.go#L23-L35
train
tebeka/selenium
selenium.go
AddChrome
func (c Capabilities) AddChrome(f chrome.Capabilities) { c[chrome.CapabilitiesKey] = f c[chrome.DeprecatedCapabilitiesKey] = f }
go
func (c Capabilities) AddChrome(f chrome.Capabilities) { c[chrome.CapabilitiesKey] = f c[chrome.DeprecatedCapabilitiesKey] = f }
[ "func", "(", "c", "Capabilities", ")", "AddChrome", "(", "f", "chrome", ".", "Capabilities", ")", "{", "c", "[", "chrome", ".", "CapabilitiesKey", "]", "=", "f", "\n", "c", "[", "chrome", ".", "DeprecatedCapabilitiesKey", "]", "=", "f", "\n", "}" ]
// AddChrome adds Chrome-specific capabilities.
[ "AddChrome", "adds", "Chrome", "-", "specific", "capabilities", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L96-L99
train
tebeka/selenium
selenium.go
AddFirefox
func (c Capabilities) AddFirefox(f firefox.Capabilities) { c[firefox.CapabilitiesKey] = f }
go
func (c Capabilities) AddFirefox(f firefox.Capabilities) { c[firefox.CapabilitiesKey] = f }
[ "func", "(", "c", "Capabilities", ")", "AddFirefox", "(", "f", "firefox", ".", "Capabilities", ")", "{", "c", "[", "firefox", ".", "CapabilitiesKey", "]", "=", "f", "\n", "}" ]
// AddFirefox adds Firefox-specific capabilities.
[ "AddFirefox", "adds", "Firefox", "-", "specific", "capabilities", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L102-L104
train
tebeka/selenium
selenium.go
AddLogging
func (c Capabilities) AddLogging(l log.Capabilities) { c[log.CapabilitiesKey] = l }
go
func (c Capabilities) AddLogging(l log.Capabilities) { c[log.CapabilitiesKey] = l }
[ "func", "(", "c", "Capabilities", ")", "AddLogging", "(", "l", "log", ".", "Capabilities", ")", "{", "c", "[", "log", ".", "CapabilitiesKey", "]", "=", "l", "\n", "}" ]
// AddLogging adds logging configuration to the capabilities.
[ "AddLogging", "adds", "logging", "configuration", "to", "the", "capabilities", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L112-L114
train
tebeka/selenium
selenium.go
SetLogLevel
func (c Capabilities) SetLogLevel(typ log.Type, level log.Level) { if _, ok := c[log.CapabilitiesKey]; !ok { c[log.CapabilitiesKey] = make(log.Capabilities) } m := c[log.CapabilitiesKey].(log.Capabilities) m[typ] = level }
go
func (c Capabilities) SetLogLevel(typ log.Type, level log.Level) { if _, ok := c[log.CapabilitiesKey]; !ok { c[log.CapabilitiesKey] = make(log.Capabilities) } m := c[log.CapabilitiesKey].(log.Capabilities) m[typ] = level }
[ "func", "(", "c", "Capabilities", ")", "SetLogLevel", "(", "typ", "log", ".", "Type", ",", "level", "log", ".", "Level", ")", "{", "if", "_", ",", "ok", ":=", "c", "[", "log", ".", "CapabilitiesKey", "]", ";", "!", "ok", "{", "c", "[", "log", "...
// SetLogLevel sets the logging level of a component. It is a shortcut for // passing a log.Capabilities instance to AddLogging.
[ "SetLogLevel", "sets", "the", "logging", "level", "of", "a", "component", ".", "It", "is", "a", "shortcut", "for", "passing", "a", "log", ".", "Capabilities", "instance", "to", "AddLogging", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L118-L124
train
tebeka/selenium
service.go
Display
func Display(d, xauthPath string) ServiceOption { return func(s *Service) error { if s.display != "" { return fmt.Errorf("service display already set: %v", s.display) } if s.xauthPath != "" { return fmt.Errorf("service xauth path already set: %v", s.xauthPath) } if !isDisplay(d) { return fmt.Errorf("supplied display %q must be of the format 'x' or 'x.y' where x and y are integers", d) } s.display = d s.xauthPath = xauthPath return nil } }
go
func Display(d, xauthPath string) ServiceOption { return func(s *Service) error { if s.display != "" { return fmt.Errorf("service display already set: %v", s.display) } if s.xauthPath != "" { return fmt.Errorf("service xauth path already set: %v", s.xauthPath) } if !isDisplay(d) { return fmt.Errorf("supplied display %q must be of the format 'x' or 'x.y' where x and y are integers", d) } s.display = d s.xauthPath = xauthPath return nil } }
[ "func", "Display", "(", "d", ",", "xauthPath", "string", ")", "ServiceOption", "{", "return", "func", "(", "s", "*", "Service", ")", "error", "{", "if", "s", ".", "display", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",...
// Display specifies the value to which set the DISPLAY environment variable, // as well as the path to the Xauthority file containing credentials needed to // write to that X server.
[ "Display", "specifies", "the", "value", "to", "which", "set", "the", "DISPLAY", "environment", "variable", "as", "well", "as", "the", "path", "to", "the", "Xauthority", "file", "containing", "credentials", "needed", "to", "write", "to", "that", "X", "server", ...
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L24-L39
train
tebeka/selenium
service.go
isDisplay
func isDisplay(disp string) bool { ds := strings.Split(disp, ".") if len(ds) > 2 { return false } for _, d := range ds { if _, err := strconv.Atoi(d); err != nil { return false } } return true }
go
func isDisplay(disp string) bool { ds := strings.Split(disp, ".") if len(ds) > 2 { return false } for _, d := range ds { if _, err := strconv.Atoi(d); err != nil { return false } } return true }
[ "func", "isDisplay", "(", "disp", "string", ")", "bool", "{", "ds", ":=", "strings", ".", "Split", "(", "disp", ",", "\"", "\"", ")", "\n", "if", "len", "(", "ds", ")", ">", "2", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "d", ...
// isDisplay validates that the given disp is in the format "x" or "x.y", where // x and y are both integers.
[ "isDisplay", "validates", "that", "the", "given", "disp", "is", "in", "the", "format", "x", "or", "x", ".", "y", "where", "x", "and", "y", "are", "both", "integers", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L43-L55
train
tebeka/selenium
service.go
StartFrameBufferWithOptions
func StartFrameBufferWithOptions(options FrameBufferOptions) ServiceOption { return func(s *Service) error { if s.display != "" { return fmt.Errorf("service display already set: %v", s.display) } if s.xauthPath != "" { return fmt.Errorf("service xauth path already set: %v", s.xauthPath) } if s.xvfb != nil { return fmt.Errorf("service Xvfb instance already running") } fb, err := NewFrameBufferWithOptions(options) if err != nil { return fmt.Errorf("error starting frame buffer: %v", err) } s.xvfb = fb return Display(fb.Display, fb.AuthPath)(s) } }
go
func StartFrameBufferWithOptions(options FrameBufferOptions) ServiceOption { return func(s *Service) error { if s.display != "" { return fmt.Errorf("service display already set: %v", s.display) } if s.xauthPath != "" { return fmt.Errorf("service xauth path already set: %v", s.xauthPath) } if s.xvfb != nil { return fmt.Errorf("service Xvfb instance already running") } fb, err := NewFrameBufferWithOptions(options) if err != nil { return fmt.Errorf("error starting frame buffer: %v", err) } s.xvfb = fb return Display(fb.Display, fb.AuthPath)(s) } }
[ "func", "StartFrameBufferWithOptions", "(", "options", "FrameBufferOptions", ")", "ServiceOption", "{", "return", "func", "(", "s", "*", "Service", ")", "error", "{", "if", "s", ".", "display", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\...
// StartFrameBufferWithOptions causes an X virtual frame buffer to start before // the WebDriver service. The frame buffer process will be terminated when the // service itself is stopped.
[ "StartFrameBufferWithOptions", "causes", "an", "X", "virtual", "frame", "buffer", "to", "start", "before", "the", "WebDriver", "service", ".", "The", "frame", "buffer", "process", "will", "be", "terminated", "when", "the", "service", "itself", "is", "stopped", "...
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L77-L95
train
tebeka/selenium
service.go
Output
func Output(w io.Writer) ServiceOption { return func(s *Service) error { s.output = w return nil } }
go
func Output(w io.Writer) ServiceOption { return func(s *Service) error { s.output = w return nil } }
[ "func", "Output", "(", "w", "io", ".", "Writer", ")", "ServiceOption", "{", "return", "func", "(", "s", "*", "Service", ")", "error", "{", "s", ".", "output", "=", "w", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Output specifies that the WebDriver service should log to the provided // writer.
[ "Output", "specifies", "that", "the", "WebDriver", "service", "should", "log", "to", "the", "provided", "writer", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L99-L104
train
tebeka/selenium
service.go
GeckoDriver
func GeckoDriver(path string) ServiceOption { return func(s *Service) error { s.geckoDriverPath = path return nil } }
go
func GeckoDriver(path string) ServiceOption { return func(s *Service) error { s.geckoDriverPath = path return nil } }
[ "func", "GeckoDriver", "(", "path", "string", ")", "ServiceOption", "{", "return", "func", "(", "s", "*", "Service", ")", "error", "{", "s", ".", "geckoDriverPath", "=", "path", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// GeckoDriver sets the path to the geckodriver binary for the Selenium Server. // Unlike other drivers, Selenium Server does not support specifying the // geckodriver path at runtime. This ServiceOption is only useful when calling // NewSeleniumService.
[ "GeckoDriver", "sets", "the", "path", "to", "the", "geckodriver", "binary", "for", "the", "Selenium", "Server", ".", "Unlike", "other", "drivers", "Selenium", "Server", "does", "not", "support", "specifying", "the", "geckodriver", "path", "at", "runtime", ".", ...
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L110-L115
train
tebeka/selenium
service.go
JavaPath
func JavaPath(path string) ServiceOption { return func(s *Service) error { s.javaPath = path return nil } }
go
func JavaPath(path string) ServiceOption { return func(s *Service) error { s.javaPath = path return nil } }
[ "func", "JavaPath", "(", "path", "string", ")", "ServiceOption", "{", "return", "func", "(", "s", "*", "Service", ")", "error", "{", "s", ".", "javaPath", "=", "path", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// JavaPath specifies the path to the JRE for a Selenium service.
[ "JavaPath", "specifies", "the", "path", "to", "the", "JRE", "for", "a", "Selenium", "service", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L125-L130
train
tebeka/selenium
service.go
NewSeleniumService
func NewSeleniumService(jarPath string, port int, opts ...ServiceOption) (*Service, error) { cmd := exec.Command("java", "-jar", jarPath, "-port", strconv.Itoa(port)) s, err := newService(cmd, "/wd/hub", port, opts...) if err != nil { return nil, err } if s.javaPath != "" { s.cmd.Path = s.javaPath } if s.geckoDriverPath != "" { s.cmd.Args = append([]string{"java", "-Dwebdriver.gecko.driver=" + s.geckoDriverPath}, cmd.Args[1:]...) } if s.chromeDriverPath != "" { s.cmd.Args = append([]string{"java", "-Dwebdriver.chrome.driver=" + s.chromeDriverPath}, cmd.Args[1:]...) } if err := s.start(port); err != nil { return nil, err } return s, nil }
go
func NewSeleniumService(jarPath string, port int, opts ...ServiceOption) (*Service, error) { cmd := exec.Command("java", "-jar", jarPath, "-port", strconv.Itoa(port)) s, err := newService(cmd, "/wd/hub", port, opts...) if err != nil { return nil, err } if s.javaPath != "" { s.cmd.Path = s.javaPath } if s.geckoDriverPath != "" { s.cmd.Args = append([]string{"java", "-Dwebdriver.gecko.driver=" + s.geckoDriverPath}, cmd.Args[1:]...) } if s.chromeDriverPath != "" { s.cmd.Args = append([]string{"java", "-Dwebdriver.chrome.driver=" + s.chromeDriverPath}, cmd.Args[1:]...) } if err := s.start(port); err != nil { return nil, err } return s, nil }
[ "func", "NewSeleniumService", "(", "jarPath", "string", ",", "port", "int", ",", "opts", "...", "ServiceOption", ")", "(", "*", "Service", ",", "error", ")", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "jarPath", ...
// NewSeleniumService starts a Selenium instance in the background.
[ "NewSeleniumService", "starts", "a", "Selenium", "instance", "in", "the", "background", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L154-L173
train
tebeka/selenium
service.go
NewChromeDriverService
func NewChromeDriverService(path string, port int, opts ...ServiceOption) (*Service, error) { cmd := exec.Command(path, "--port="+strconv.Itoa(port), "--url-base=wd/hub", "--verbose") s, err := newService(cmd, "/wd/hub", port, opts...) if err != nil { return nil, err } s.shutdownURLPath = "/shutdown" if err := s.start(port); err != nil { return nil, err } return s, nil }
go
func NewChromeDriverService(path string, port int, opts ...ServiceOption) (*Service, error) { cmd := exec.Command(path, "--port="+strconv.Itoa(port), "--url-base=wd/hub", "--verbose") s, err := newService(cmd, "/wd/hub", port, opts...) if err != nil { return nil, err } s.shutdownURLPath = "/shutdown" if err := s.start(port); err != nil { return nil, err } return s, nil }
[ "func", "NewChromeDriverService", "(", "path", "string", ",", "port", "int", ",", "opts", "...", "ServiceOption", ")", "(", "*", "Service", ",", "error", ")", "{", "cmd", ":=", "exec", ".", "Command", "(", "path", ",", "\"", "\"", "+", "strconv", ".", ...
// NewChromeDriverService starts a ChromeDriver instance in the background.
[ "NewChromeDriverService", "starts", "a", "ChromeDriver", "instance", "in", "the", "background", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L176-L187
train
tebeka/selenium
service.go
Stop
func (s *Service) Stop() error { // Selenium 3 stopped supporting the shutdown URL by default. // https://github.com/SeleniumHQ/selenium/issues/2852 if s.shutdownURLPath == "" { if err := s.cmd.Process.Kill(); err != nil { return err } } else { resp, err := http.Get(s.addr + s.shutdownURLPath) if err != nil { return err } resp.Body.Close() } if err := s.cmd.Wait(); err != nil && err.Error() != "signal: killed" { return err } if s.xvfb != nil { return s.xvfb.Stop() } return nil }
go
func (s *Service) Stop() error { // Selenium 3 stopped supporting the shutdown URL by default. // https://github.com/SeleniumHQ/selenium/issues/2852 if s.shutdownURLPath == "" { if err := s.cmd.Process.Kill(); err != nil { return err } } else { resp, err := http.Get(s.addr + s.shutdownURLPath) if err != nil { return err } resp.Body.Close() } if err := s.cmd.Wait(); err != nil && err.Error() != "signal: killed" { return err } if s.xvfb != nil { return s.xvfb.Stop() } return nil }
[ "func", "(", "s", "*", "Service", ")", "Stop", "(", ")", "error", "{", "// Selenium 3 stopped supporting the shutdown URL by default.", "// https://github.com/SeleniumHQ/selenium/issues/2852", "if", "s", ".", "shutdownURLPath", "==", "\"", "\"", "{", "if", "err", ":=", ...
// Stop shuts down the WebDriver service, and the X virtual frame buffer // if one was started.
[ "Stop", "shuts", "down", "the", "WebDriver", "service", "and", "the", "X", "virtual", "frame", "buffer", "if", "one", "was", "started", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L250-L271
train
tebeka/selenium
service.go
NewFrameBufferWithOptions
func NewFrameBufferWithOptions(options FrameBufferOptions) (*FrameBuffer, error) { r, w, err := os.Pipe() if err != nil { return nil, err } defer r.Close() auth, err := ioutil.TempFile("", "selenium-xvfb") if err != nil { return nil, err } authPath := auth.Name() if err := auth.Close(); err != nil { return nil, err } // Xvfb will print the display on which it is listening to file descriptor 3, // for which we provide a pipe. arguments := []string{"-displayfd", "3", "-nolisten", "tcp"} if options.ScreenSize != "" { var screenSizeExpression = regexp.MustCompile(`^\d+x\d+(?:x\d+)$`) if !screenSizeExpression.MatchString(options.ScreenSize) { return nil, fmt.Errorf("invalid screen size: expected 'WxH[xD]', got %q", options.ScreenSize) } arguments = append(arguments, "-screen", "0", options.ScreenSize) } xvfb := exec.Command("Xvfb", arguments...) xvfb.ExtraFiles = []*os.File{w} // TODO(minusnine): plumb a way to set xvfb.Std{err,out} conditionally. // TODO(minusnine): Pdeathsig is only supported on Linux. Somehow, make sure // process cleanup happens as gracefully as possible. xvfb.Env = append(xvfb.Env, "XAUTHORITY="+authPath) if err := xvfb.Start(); err != nil { return nil, err } w.Close() type resp struct { display string err error } ch := make(chan resp) go func() { bufr := bufio.NewReader(r) s, err := bufr.ReadString('\n') ch <- resp{s, err} }() var display string select { case resp := <-ch: if resp.err != nil { return nil, resp.err } display = strings.TrimSpace(resp.display) if _, err := strconv.Atoi(display); err != nil { return nil, errors.New("Xvfb did not print the display number") } case <-time.After(3 * time.Second): return nil, errors.New("timeout waiting for Xvfb") } xauth := exec.Command("xauth", "generate", ":"+display, ".", "trusted") xauth.Stderr = os.Stderr xauth.Stdout = os.Stdout xauth.Env = append(xauth.Env, "XAUTHORITY="+authPath) if err := xauth.Run(); err != nil { return nil, err } return &FrameBuffer{display, authPath, xvfb}, nil }
go
func NewFrameBufferWithOptions(options FrameBufferOptions) (*FrameBuffer, error) { r, w, err := os.Pipe() if err != nil { return nil, err } defer r.Close() auth, err := ioutil.TempFile("", "selenium-xvfb") if err != nil { return nil, err } authPath := auth.Name() if err := auth.Close(); err != nil { return nil, err } // Xvfb will print the display on which it is listening to file descriptor 3, // for which we provide a pipe. arguments := []string{"-displayfd", "3", "-nolisten", "tcp"} if options.ScreenSize != "" { var screenSizeExpression = regexp.MustCompile(`^\d+x\d+(?:x\d+)$`) if !screenSizeExpression.MatchString(options.ScreenSize) { return nil, fmt.Errorf("invalid screen size: expected 'WxH[xD]', got %q", options.ScreenSize) } arguments = append(arguments, "-screen", "0", options.ScreenSize) } xvfb := exec.Command("Xvfb", arguments...) xvfb.ExtraFiles = []*os.File{w} // TODO(minusnine): plumb a way to set xvfb.Std{err,out} conditionally. // TODO(minusnine): Pdeathsig is only supported on Linux. Somehow, make sure // process cleanup happens as gracefully as possible. xvfb.Env = append(xvfb.Env, "XAUTHORITY="+authPath) if err := xvfb.Start(); err != nil { return nil, err } w.Close() type resp struct { display string err error } ch := make(chan resp) go func() { bufr := bufio.NewReader(r) s, err := bufr.ReadString('\n') ch <- resp{s, err} }() var display string select { case resp := <-ch: if resp.err != nil { return nil, resp.err } display = strings.TrimSpace(resp.display) if _, err := strconv.Atoi(display); err != nil { return nil, errors.New("Xvfb did not print the display number") } case <-time.After(3 * time.Second): return nil, errors.New("timeout waiting for Xvfb") } xauth := exec.Command("xauth", "generate", ":"+display, ".", "trusted") xauth.Stderr = os.Stderr xauth.Stdout = os.Stdout xauth.Env = append(xauth.Env, "XAUTHORITY="+authPath) if err := xauth.Run(); err != nil { return nil, err } return &FrameBuffer{display, authPath, xvfb}, nil }
[ "func", "NewFrameBufferWithOptions", "(", "options", "FrameBufferOptions", ")", "(", "*", "FrameBuffer", ",", "error", ")", "{", "r", ",", "w", ",", "err", ":=", "os", ".", "Pipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", ...
// NewFrameBufferWithOptions starts an X virtual frame buffer running in the background. // FrameBufferOptions may be populated to change the behavior of the frame buffer.
[ "NewFrameBufferWithOptions", "starts", "an", "X", "virtual", "frame", "buffer", "running", "in", "the", "background", ".", "FrameBufferOptions", "may", "be", "populated", "to", "change", "the", "behavior", "of", "the", "frame", "buffer", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L296-L369
train
tebeka/selenium
service.go
Stop
func (f FrameBuffer) Stop() error { if err := f.cmd.Process.Kill(); err != nil { return err } os.Remove(f.AuthPath) // best effort removal; ignore error if err := f.cmd.Wait(); err != nil && err.Error() != "signal: killed" { return err } return nil }
go
func (f FrameBuffer) Stop() error { if err := f.cmd.Process.Kill(); err != nil { return err } os.Remove(f.AuthPath) // best effort removal; ignore error if err := f.cmd.Wait(); err != nil && err.Error() != "signal: killed" { return err } return nil }
[ "func", "(", "f", "FrameBuffer", ")", "Stop", "(", ")", "error", "{", "if", "err", ":=", "f", ".", "cmd", ".", "Process", ".", "Kill", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "os", ".", "Remove", "(", "f", "....
// Stop kills the background frame buffer process and removes the X // authorization file.
[ "Stop", "kills", "the", "background", "frame", "buffer", "process", "and", "removes", "the", "X", "authorization", "file", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L373-L382
train
tebeka/selenium
sauce/connect.go
Start
func (c *Connect) Start() error { c.cmd = exec.Command(c.Path, c.Args...) if c.UserName != "" { c.cmd.Args = append(c.cmd.Args, "--user", c.UserName) } if c.AccessKey != "" { c.cmd.Args = append(c.cmd.Args, "--api-key", c.AccessKey) } if c.SeleniumPort > 0 { c.cmd.Args = append(c.cmd.Args, "--se-port", strconv.Itoa(c.SeleniumPort)) } if c.ExtraVerbose { c.cmd.Args = append(c.cmd.Args, "-vv") } else if c.Verbose { c.cmd.Args = append(c.cmd.Args, "-v") } if c.ExtraVerbose || c.Verbose { c.cmd.Stdout = os.Stdout c.cmd.Stderr = os.Stderr } if c.LogFile != "" { c.cmd.Args = append(c.cmd.Args, "--logfile", c.LogFile) } if c.QuitProcessUponExit && runtime.GOOS == "linux" { c.cmd.SysProcAttr = &syscall.SysProcAttr{ // Deliver SIGTERM to process when we die. Pdeathsig: syscall.SIGTERM, } } dir, err := ioutil.TempDir("", "selenium-sauce-connect") if err != nil { return err } defer func() { os.RemoveAll(dir) // ignore error. }() var pidFilePath string if c.PIDFile != "" { pidFilePath = c.PIDFile } else { f, err := ioutil.TempFile("", "selenium-sauce-connect-pid.") if err != nil { return err } pidFilePath = f.Name() f.Close() // ignore the error. } // The path specified here will be touched by the proxy process when it is // ready to accept connections. readyPath := filepath.Join(dir, "ready") c.cmd.Args = append(c.cmd.Args, "--readyfile", readyPath) c.cmd.Args = append(c.cmd.Args, "--pidfile", pidFilePath) if err := c.cmd.Start(); err != nil { return err } // Wait for the Proxy to accept connections. var started bool for i := 0; i < 60; i++ { time.Sleep(time.Second) if _, err := os.Stat(readyPath); err == nil { started = true break } } if !started { c.Stop() // ignore error. return fmt.Errorf("proxy process did not become ready before the timeout") } return nil }
go
func (c *Connect) Start() error { c.cmd = exec.Command(c.Path, c.Args...) if c.UserName != "" { c.cmd.Args = append(c.cmd.Args, "--user", c.UserName) } if c.AccessKey != "" { c.cmd.Args = append(c.cmd.Args, "--api-key", c.AccessKey) } if c.SeleniumPort > 0 { c.cmd.Args = append(c.cmd.Args, "--se-port", strconv.Itoa(c.SeleniumPort)) } if c.ExtraVerbose { c.cmd.Args = append(c.cmd.Args, "-vv") } else if c.Verbose { c.cmd.Args = append(c.cmd.Args, "-v") } if c.ExtraVerbose || c.Verbose { c.cmd.Stdout = os.Stdout c.cmd.Stderr = os.Stderr } if c.LogFile != "" { c.cmd.Args = append(c.cmd.Args, "--logfile", c.LogFile) } if c.QuitProcessUponExit && runtime.GOOS == "linux" { c.cmd.SysProcAttr = &syscall.SysProcAttr{ // Deliver SIGTERM to process when we die. Pdeathsig: syscall.SIGTERM, } } dir, err := ioutil.TempDir("", "selenium-sauce-connect") if err != nil { return err } defer func() { os.RemoveAll(dir) // ignore error. }() var pidFilePath string if c.PIDFile != "" { pidFilePath = c.PIDFile } else { f, err := ioutil.TempFile("", "selenium-sauce-connect-pid.") if err != nil { return err } pidFilePath = f.Name() f.Close() // ignore the error. } // The path specified here will be touched by the proxy process when it is // ready to accept connections. readyPath := filepath.Join(dir, "ready") c.cmd.Args = append(c.cmd.Args, "--readyfile", readyPath) c.cmd.Args = append(c.cmd.Args, "--pidfile", pidFilePath) if err := c.cmd.Start(); err != nil { return err } // Wait for the Proxy to accept connections. var started bool for i := 0; i < 60; i++ { time.Sleep(time.Second) if _, err := os.Stat(readyPath); err == nil { started = true break } } if !started { c.Stop() // ignore error. return fmt.Errorf("proxy process did not become ready before the timeout") } return nil }
[ "func", "(", "c", "*", "Connect", ")", "Start", "(", ")", "error", "{", "c", ".", "cmd", "=", "exec", ".", "Command", "(", "c", ".", "Path", ",", "c", ".", "Args", "...", ")", "\n", "if", "c", ".", "UserName", "!=", "\"", "\"", "{", "c", "....
// Start starts the Sauce Connect Proxy.
[ "Start", "starts", "the", "Sauce", "Connect", "Proxy", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/sauce/connect.go#L47-L121
train
tebeka/selenium
sauce/connect.go
Addr
func (c *Connect) Addr() string { return fmt.Sprintf("http://%s:%s@localhost:%d/wd/hub", c.UserName, c.AccessKey, c.SeleniumPort) }
go
func (c *Connect) Addr() string { return fmt.Sprintf("http://%s:%s@localhost:%d/wd/hub", c.UserName, c.AccessKey, c.SeleniumPort) }
[ "func", "(", "c", "*", "Connect", ")", "Addr", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "UserName", ",", "c", ".", "AccessKey", ",", "c", ".", "SeleniumPort", ")", "\n", "}" ]
// Addr returns the URL of the WebDriver endpoint to use for driving the // browser.
[ "Addr", "returns", "the", "URL", "of", "the", "WebDriver", "endpoint", "to", "use", "for", "driving", "the", "browser", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/sauce/connect.go#L125-L127
train
tebeka/selenium
chrome/capabilities.go
AddExtension
func (c *Capabilities) AddExtension(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return c.addExtension(f) }
go
func (c *Capabilities) AddExtension(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return c.addExtension(f) }
[ "func", "(", "c", "*", "Capabilities", ")", "AddExtension", "(", "path", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f",...
// AddExtension adds an extension for the browser to load at startup. The path // parameter should be a path to an extension file (which typically has a // `.crx` file extension. Note that the contents of the file will be loaded // into memory, as required by the protocol.
[ "AddExtension", "adds", "an", "extension", "for", "the", "browser", "to", "load", "at", "startup", ".", "The", "path", "parameter", "should", "be", "a", "path", "to", "an", "extension", "file", "(", "which", "typically", "has", "a", ".", "crx", "file", "...
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L128-L135
train
tebeka/selenium
chrome/capabilities.go
addExtension
func (c *Capabilities) addExtension(r io.Reader) error { var buf bytes.Buffer encoder := base64.NewEncoder(base64.StdEncoding, &buf) if _, err := io.Copy(encoder, bufio.NewReader(r)); err != nil { return err } encoder.Close() c.Extensions = append(c.Extensions, buf.String()) return nil }
go
func (c *Capabilities) addExtension(r io.Reader) error { var buf bytes.Buffer encoder := base64.NewEncoder(base64.StdEncoding, &buf) if _, err := io.Copy(encoder, bufio.NewReader(r)); err != nil { return err } encoder.Close() c.Extensions = append(c.Extensions, buf.String()) return nil }
[ "func", "(", "c", "*", "Capabilities", ")", "addExtension", "(", "r", "io", ".", "Reader", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "encoder", ":=", "base64", ".", "NewEncoder", "(", "base64", ".", "StdEncoding", ",", "&", "buf", ...
// addExtension reads a Chrome extension's data from r, base64-encodes it, and // attaches it to the Capabilities instance.
[ "addExtension", "reads", "a", "Chrome", "extension", "s", "data", "from", "r", "base64", "-", "encodes", "it", "and", "attaches", "it", "to", "the", "Capabilities", "instance", "." ]
edf31bb7fd715ad505d9190f8d65d13f39a7c825
https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L139-L148
train