id
int32
0
167k
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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
143,100
uber/ringpop-go
swim/stats.go
Uptime
func (n *Node) Uptime() time.Duration { return time.Now().Sub(n.startTime) }
go
func (n *Node) Uptime() time.Duration { return time.Now().Sub(n.startTime) }
[ "func", "(", "n", "*", "Node", ")", "Uptime", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Now", "(", ")", ".", "Sub", "(", "n", ".", "startTime", ")", "\n", "}" ]
// Uptime returns the amount of time the node has been running for
[ "Uptime", "returns", "the", "amount", "of", "time", "the", "node", "has", "been", "running", "for" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/stats.go#L107-L109
143,101
uber/ringpop-go
router/router.go
New
func New(rp ringpop.Interface, f ClientFactory, ch *tchannel.Channel) Router { r := &router{ ringpop: rp, factory: f, channel: ch, clientCache: make(map[string]cacheEntry), } rp.AddListener(r) return r }
go
func New(rp ringpop.Interface, f ClientFactory, ch *tchannel.Channel) Router { r := &router{ ringpop: rp, factory: f, channel: ch, clientCache: make(map[string]cacheEntry), } rp.AddListener(r) return r }
[ "func", "New", "(", "rp", "ringpop", ".", "Interface", ",", "f", "ClientFactory", ",", "ch", "*", "tchannel", ".", "Channel", ")", "Router", "{", "r", ":=", "&", "router", "{", "ringpop", ":", "rp", ",", "factory", ":", "f", ",", "channel", ":", "ch", ",", "clientCache", ":", "make", "(", "map", "[", "string", "]", "cacheEntry", ")", ",", "}", "\n", "rp", ".", "AddListener", "(", "r", ")", "\n", "return", "r", "\n", "}" ]
// New creates an instance that validates the Router interface. A Router // will be used to get implementations of service interfaces that implement a // distributed microservice.
[ "New", "creates", "an", "instance", "that", "validates", "the", "Router", "interface", ".", "A", "Router", "will", "be", "used", "to", "get", "implementations", "of", "service", "interfaces", "that", "implement", "a", "distributed", "microservice", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/router/router.go#L73-L83
143,102
uber/ringpop-go
router/router.go
GetClient
func (r *router) GetClient(key string) (client interface{}, isRemote bool, err error) { dest, err := r.ringpop.Lookup(key) if err != nil { return nil, false, err } return r.getClientByHost(dest) }
go
func (r *router) GetClient(key string) (client interface{}, isRemote bool, err error) { dest, err := r.ringpop.Lookup(key) if err != nil { return nil, false, err } return r.getClientByHost(dest) }
[ "func", "(", "r", "*", "router", ")", "GetClient", "(", "key", "string", ")", "(", "client", "interface", "{", "}", ",", "isRemote", "bool", ",", "err", "error", ")", "{", "dest", ",", "err", ":=", "r", ".", "ringpop", ".", "Lookup", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n\n", "return", "r", ".", "getClientByHost", "(", "dest", ")", "\n", "}" ]
// Get the client for a certain destination from our internal cache, or // delegates the creation to the ClientFactory.
[ "Get", "the", "client", "for", "a", "certain", "destination", "from", "our", "internal", "cache", "or", "delegates", "the", "creation", "to", "the", "ClientFactory", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/router/router.go#L103-L110
143,103
uber/ringpop-go
swim/ping_request_sender.go
newPingRequestSender
func newPingRequestSender(node *Node, peer, target string, timeout time.Duration) *pingRequestSender { p := &pingRequestSender{ node: node, peer: peer, target: target, timeout: timeout, logger: logging.Logger("ping").WithField("local", node.Address()), } return p }
go
func newPingRequestSender(node *Node, peer, target string, timeout time.Duration) *pingRequestSender { p := &pingRequestSender{ node: node, peer: peer, target: target, timeout: timeout, logger: logging.Logger("ping").WithField("local", node.Address()), } return p }
[ "func", "newPingRequestSender", "(", "node", "*", "Node", ",", "peer", ",", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "*", "pingRequestSender", "{", "p", ":=", "&", "pingRequestSender", "{", "node", ":", "node", ",", "peer", ":", "peer", ",", "target", ":", "target", ",", "timeout", ":", "timeout", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "node", ".", "Address", "(", ")", ")", ",", "}", "\n\n", "return", "p", "\n", "}" ]
// NewPingRequestSender returns a new PingRequestSender
[ "NewPingRequestSender", "returns", "a", "new", "PingRequestSender" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/ping_request_sender.go#L53-L63
143,104
uber/ringpop-go
swim/ping_request_sender.go
indirectPing
func indirectPing(n *Node, target string, amount int, timeout time.Duration) (reached bool, errs []error) { resCh := sendPingRequests(n, target, amount, timeout) // wait for responses from the ping-reqs for result := range resCh { switch res := result.(type) { case *pingResponse: if res.Ok { return true, errs } // If the ping to the target was not-ok we want to wait for more results. case error: errs = append(errs, res) } } return false, errs }
go
func indirectPing(n *Node, target string, amount int, timeout time.Duration) (reached bool, errs []error) { resCh := sendPingRequests(n, target, amount, timeout) // wait for responses from the ping-reqs for result := range resCh { switch res := result.(type) { case *pingResponse: if res.Ok { return true, errs } // If the ping to the target was not-ok we want to wait for more results. case error: errs = append(errs, res) } } return false, errs }
[ "func", "indirectPing", "(", "n", "*", "Node", ",", "target", "string", ",", "amount", "int", ",", "timeout", "time", ".", "Duration", ")", "(", "reached", "bool", ",", "errs", "[", "]", "error", ")", "{", "resCh", ":=", "sendPingRequests", "(", "n", ",", "target", ",", "amount", ",", "timeout", ")", "\n\n", "// wait for responses from the ping-reqs", "for", "result", ":=", "range", "resCh", "{", "switch", "res", ":=", "result", ".", "(", "type", ")", "{", "case", "*", "pingResponse", ":", "if", "res", ".", "Ok", "{", "return", "true", ",", "errs", "\n", "}", "\n", "// If the ping to the target was not-ok we want to wait for more results.", "case", "error", ":", "errs", "=", "append", "(", "errs", ",", "res", ")", "\n", "}", "\n", "}", "\n\n", "return", "false", ",", "errs", "\n", "}" ]
// indirectPing is used to check if a target node can be reached indirectly. // The indirectPing is performed by sending a specifiable amount of ping // requests nodes in n's membership.
[ "indirectPing", "is", "used", "to", "check", "if", "a", "target", "node", "can", "be", "reached", "indirectly", ".", "The", "indirectPing", "is", "performed", "by", "sending", "a", "specifiable", "amount", "of", "ping", "requests", "nodes", "in", "n", "s", "membership", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/ping_request_sender.go#L120-L138
143,105
uber/ringpop-go
forward/forwarder.go
NewForwarder
func NewForwarder(s Sender, ch shared.SubChannel) *Forwarder { logger := logging.Logger("forwarder") if address, err := s.WhoAmI(); err == nil { logger = logger.WithField("local", address) } return &Forwarder{ sender: s, channel: ch, logger: logger, } }
go
func NewForwarder(s Sender, ch shared.SubChannel) *Forwarder { logger := logging.Logger("forwarder") if address, err := s.WhoAmI(); err == nil { logger = logger.WithField("local", address) } return &Forwarder{ sender: s, channel: ch, logger: logger, } }
[ "func", "NewForwarder", "(", "s", "Sender", ",", "ch", "shared", ".", "SubChannel", ")", "*", "Forwarder", "{", "logger", ":=", "logging", ".", "Logger", "(", "\"", "\"", ")", "\n", "if", "address", ",", "err", ":=", "s", ".", "WhoAmI", "(", ")", ";", "err", "==", "nil", "{", "logger", "=", "logger", ".", "WithField", "(", "\"", "\"", ",", "address", ")", "\n", "}", "\n\n", "return", "&", "Forwarder", "{", "sender", ":", "s", ",", "channel", ":", "ch", ",", "logger", ":", "logger", ",", "}", "\n", "}" ]
// NewForwarder returns a new forwarder
[ "NewForwarder", "returns", "a", "new", "forwarder" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/forward/forwarder.go#L102-L114
143,106
uber/ringpop-go
forward/forwarder.go
ForwardRequest
func (f *Forwarder) ForwardRequest(request []byte, destination, service, endpoint string, keys []string, format tchannel.Format, opts *Options) ([]byte, error) { f.EmitEvent(RequestForwardedEvent{}) f.incrementInflight() opts = f.mergeDefaultOptions(opts) rs := newRequestSender(f.sender, f, f.channel, request, keys, destination, service, endpoint, format, opts) b, err := rs.Send() f.decrementInflight() if err != nil { f.EmitEvent(FailedEvent{}) } else { f.EmitEvent(SuccessEvent{}) } return b, err }
go
func (f *Forwarder) ForwardRequest(request []byte, destination, service, endpoint string, keys []string, format tchannel.Format, opts *Options) ([]byte, error) { f.EmitEvent(RequestForwardedEvent{}) f.incrementInflight() opts = f.mergeDefaultOptions(opts) rs := newRequestSender(f.sender, f, f.channel, request, keys, destination, service, endpoint, format, opts) b, err := rs.Send() f.decrementInflight() if err != nil { f.EmitEvent(FailedEvent{}) } else { f.EmitEvent(SuccessEvent{}) } return b, err }
[ "func", "(", "f", "*", "Forwarder", ")", "ForwardRequest", "(", "request", "[", "]", "byte", ",", "destination", ",", "service", ",", "endpoint", "string", ",", "keys", "[", "]", "string", ",", "format", "tchannel", ".", "Format", ",", "opts", "*", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ".", "EmitEvent", "(", "RequestForwardedEvent", "{", "}", ")", "\n\n", "f", ".", "incrementInflight", "(", ")", "\n", "opts", "=", "f", ".", "mergeDefaultOptions", "(", "opts", ")", "\n", "rs", ":=", "newRequestSender", "(", "f", ".", "sender", ",", "f", ",", "f", ".", "channel", ",", "request", ",", "keys", ",", "destination", ",", "service", ",", "endpoint", ",", "format", ",", "opts", ")", "\n", "b", ",", "err", ":=", "rs", ".", "Send", "(", ")", "\n", "f", ".", "decrementInflight", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "f", ".", "EmitEvent", "(", "FailedEvent", "{", "}", ")", "\n", "}", "else", "{", "f", ".", "EmitEvent", "(", "SuccessEvent", "{", "}", ")", "\n", "}", "\n\n", "return", "b", ",", "err", "\n", "}" ]
// ForwardRequest forwards a request to the given service and endpoint returns the response. // Keys are used by the sender to lookup the destination on retry. If you have multiple keys // and their destinations diverge on a retry then the call is aborted.
[ "ForwardRequest", "forwards", "a", "request", "to", "the", "given", "service", "and", "endpoint", "returns", "the", "response", ".", "Keys", "are", "used", "by", "the", "sender", "to", "lookup", "the", "destination", "on", "retry", ".", "If", "you", "have", "multiple", "keys", "and", "their", "destinations", "diverge", "on", "a", "retry", "then", "the", "call", "is", "aborted", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/forward/forwarder.go#L147-L165
143,107
uber/ringpop-go
forward/forwarder.go
SetForwardedHeader
func SetForwardedHeader(ctx thrift.Context, keys []string) thrift.Context { // copy headers to make sure two calls do not leak headers to each other headers := make(map[string]string, len(ctx.Headers())+1) for key, value := range ctx.Headers() { headers[key] = value } if keys == nil { // prevent null serialization, but use an empty array instead keys = []string{} } keysBytes, _ := json.Marshal(keys) keysString := string(keysBytes) // set the header indicating the call is forwarded for the provided keys headers[ForwardedHeaderName] = keysString // return the ctx with new headrs return thrift.WithHeaders(ctx, headers) }
go
func SetForwardedHeader(ctx thrift.Context, keys []string) thrift.Context { // copy headers to make sure two calls do not leak headers to each other headers := make(map[string]string, len(ctx.Headers())+1) for key, value := range ctx.Headers() { headers[key] = value } if keys == nil { // prevent null serialization, but use an empty array instead keys = []string{} } keysBytes, _ := json.Marshal(keys) keysString := string(keysBytes) // set the header indicating the call is forwarded for the provided keys headers[ForwardedHeaderName] = keysString // return the ctx with new headrs return thrift.WithHeaders(ctx, headers) }
[ "func", "SetForwardedHeader", "(", "ctx", "thrift", ".", "Context", ",", "keys", "[", "]", "string", ")", "thrift", ".", "Context", "{", "// copy headers to make sure two calls do not leak headers to each other", "headers", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "ctx", ".", "Headers", "(", ")", ")", "+", "1", ")", "\n", "for", "key", ",", "value", ":=", "range", "ctx", ".", "Headers", "(", ")", "{", "headers", "[", "key", "]", "=", "value", "\n", "}", "\n\n", "if", "keys", "==", "nil", "{", "// prevent null serialization, but use an empty array instead", "keys", "=", "[", "]", "string", "{", "}", "\n", "}", "\n", "keysBytes", ",", "_", ":=", "json", ".", "Marshal", "(", "keys", ")", "\n", "keysString", ":=", "string", "(", "keysBytes", ")", "\n\n", "// set the header indicating the call is forwarded for the provided keys", "headers", "[", "ForwardedHeaderName", "]", "=", "keysString", "\n\n", "// return the ctx with new headrs", "return", "thrift", ".", "WithHeaders", "(", "ctx", ",", "headers", ")", "\n", "}" ]
// SetForwardedHeader adds a header to the current thrift context indicating // that the call has been forwarded by another node in the ringpop ring. This // header is used when a remote call is received to determine if forwarding // checks needs to be applied. By not forwarding already forwarded calls we // prevent unbound forwarding in the ring in case of memebership disagreement. // The keys provided will be serialized as the value of the key and can be used // in the future to check if key inconsistencies are found while forwarding. // Currently this is not checked
[ "SetForwardedHeader", "adds", "a", "header", "to", "the", "current", "thrift", "context", "indicating", "that", "the", "call", "has", "been", "forwarded", "by", "another", "node", "in", "the", "ringpop", "ring", ".", "This", "header", "is", "used", "when", "a", "remote", "call", "is", "received", "to", "determine", "if", "forwarding", "checks", "needs", "to", "be", "applied", ".", "By", "not", "forwarding", "already", "forwarded", "calls", "we", "prevent", "unbound", "forwarding", "in", "the", "ring", "in", "case", "of", "memebership", "disagreement", ".", "The", "keys", "provided", "will", "be", "serialized", "as", "the", "value", "of", "the", "key", "and", "can", "be", "used", "in", "the", "future", "to", "check", "if", "key", "inconsistencies", "are", "found", "while", "forwarding", ".", "Currently", "this", "is", "not", "checked" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/forward/forwarder.go#L181-L200
143,108
uber/ringpop-go
forward/forwarder.go
DeleteForwardedHeader
func DeleteForwardedHeader(ctx thrift.Context) bool { _, ok := ctx.Headers()[ForwardedHeaderName] if ok { delete(ctx.Headers(), ForwardedHeaderName) } return ok }
go
func DeleteForwardedHeader(ctx thrift.Context) bool { _, ok := ctx.Headers()[ForwardedHeaderName] if ok { delete(ctx.Headers(), ForwardedHeaderName) } return ok }
[ "func", "DeleteForwardedHeader", "(", "ctx", "thrift", ".", "Context", ")", "bool", "{", "_", ",", "ok", ":=", "ctx", ".", "Headers", "(", ")", "[", "ForwardedHeaderName", "]", "\n", "if", "ok", "{", "delete", "(", "ctx", ".", "Headers", "(", ")", ",", "ForwardedHeaderName", ")", "\n", "}", "\n", "return", "ok", "\n", "}" ]
// DeleteForwardedHeader takes the headers that came in via TChannel and looks // for the precense of a specific ringpop header to see if ringpop already // forwarded the message. If the header is present it will delete the header // from the context. The return value indicates if the header was present and // deleted
[ "DeleteForwardedHeader", "takes", "the", "headers", "that", "came", "in", "via", "TChannel", "and", "looks", "for", "the", "precense", "of", "a", "specific", "ringpop", "header", "to", "see", "if", "ringpop", "already", "forwarded", "the", "message", ".", "If", "the", "header", "is", "present", "it", "will", "delete", "the", "header", "from", "the", "context", ".", "The", "return", "value", "indicates", "if", "the", "header", "was", "present", "and", "deleted" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/forward/forwarder.go#L207-L213
143,109
uber/ringpop-go
swim/state_transitions.go
newStateTransitions
func newStateTransitions(n *Node, timeouts StateTimeouts) *stateTransitions { return &stateTransitions{ node: n, timeouts: timeouts, timers: make(map[string]*transitionTimer), enabled: true, logger: logging.Logger("stateTransitions").WithField("local", n.Address()), } }
go
func newStateTransitions(n *Node, timeouts StateTimeouts) *stateTransitions { return &stateTransitions{ node: n, timeouts: timeouts, timers: make(map[string]*transitionTimer), enabled: true, logger: logging.Logger("stateTransitions").WithField("local", n.Address()), } }
[ "func", "newStateTransitions", "(", "n", "*", "Node", ",", "timeouts", "StateTimeouts", ")", "*", "stateTransitions", "{", "return", "&", "stateTransitions", "{", "node", ":", "n", ",", "timeouts", ":", "timeouts", ",", "timers", ":", "make", "(", "map", "[", "string", "]", "*", "transitionTimer", ")", ",", "enabled", ":", "true", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "n", ".", "Address", "(", ")", ")", ",", "}", "\n", "}" ]
// newStateTransitions returns a new state transition controller that can be used to schedule state transitions for nodes
[ "newStateTransitions", "returns", "a", "new", "state", "transition", "controller", "that", "can", "be", "used", "to", "schedule", "state", "transitions", "for", "nodes" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L79-L87
143,110
uber/ringpop-go
swim/state_transitions.go
ScheduleSuspectToFaulty
func (s *stateTransitions) ScheduleSuspectToFaulty(subject subject) { s.Lock() s.schedule(subject, Suspect, s.timeouts.Suspect, func() { // transition the subject to faulty s.node.memberlist.MakeFaulty(subject.address(), subject.incarnation()) }) s.Unlock() }
go
func (s *stateTransitions) ScheduleSuspectToFaulty(subject subject) { s.Lock() s.schedule(subject, Suspect, s.timeouts.Suspect, func() { // transition the subject to faulty s.node.memberlist.MakeFaulty(subject.address(), subject.incarnation()) }) s.Unlock() }
[ "func", "(", "s", "*", "stateTransitions", ")", "ScheduleSuspectToFaulty", "(", "subject", "subject", ")", "{", "s", ".", "Lock", "(", ")", "\n", "s", ".", "schedule", "(", "subject", ",", "Suspect", ",", "s", ".", "timeouts", ".", "Suspect", ",", "func", "(", ")", "{", "// transition the subject to faulty", "s", ".", "node", ".", "memberlist", ".", "MakeFaulty", "(", "subject", ".", "address", "(", ")", ",", "subject", ".", "incarnation", "(", ")", ")", "\n", "}", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// ScheduleSuspectToFaulty starts the suspect timer. After the Suspect timeout the node will be declared faulty
[ "ScheduleSuspectToFaulty", "starts", "the", "suspect", "timer", ".", "After", "the", "Suspect", "timeout", "the", "node", "will", "be", "declared", "faulty" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L90-L97
143,111
uber/ringpop-go
swim/state_transitions.go
ScheduleFaultyToTombstone
func (s *stateTransitions) ScheduleFaultyToTombstone(subject subject) { s.Lock() s.schedule(subject, Faulty, s.timeouts.Faulty, func() { // transition the subject to tombstone s.node.memberlist.MakeTombstone(subject.address(), subject.incarnation()) }) s.Unlock() }
go
func (s *stateTransitions) ScheduleFaultyToTombstone(subject subject) { s.Lock() s.schedule(subject, Faulty, s.timeouts.Faulty, func() { // transition the subject to tombstone s.node.memberlist.MakeTombstone(subject.address(), subject.incarnation()) }) s.Unlock() }
[ "func", "(", "s", "*", "stateTransitions", ")", "ScheduleFaultyToTombstone", "(", "subject", "subject", ")", "{", "s", ".", "Lock", "(", ")", "\n", "s", ".", "schedule", "(", "subject", ",", "Faulty", ",", "s", ".", "timeouts", ".", "Faulty", ",", "func", "(", ")", "{", "// transition the subject to tombstone", "s", ".", "node", ".", "memberlist", ".", "MakeTombstone", "(", "subject", ".", "address", "(", ")", ",", "subject", ".", "incarnation", "(", ")", ")", "\n", "}", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// ScheduleFaultyToTombstone starts the faulty timer. After the Faulty timeout the node will be declared tombstone
[ "ScheduleFaultyToTombstone", "starts", "the", "faulty", "timer", ".", "After", "the", "Faulty", "timeout", "the", "node", "will", "be", "declared", "tombstone" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L100-L107
143,112
uber/ringpop-go
swim/state_transitions.go
ScheduleTombstoneToEvict
func (s *stateTransitions) ScheduleTombstoneToEvict(subject subject) { s.Lock() s.schedule(subject, Tombstone, s.timeouts.Tombstone, func() { // transition the subject to tombstone s.node.memberlist.Evict(subject.address()) }) s.Unlock() }
go
func (s *stateTransitions) ScheduleTombstoneToEvict(subject subject) { s.Lock() s.schedule(subject, Tombstone, s.timeouts.Tombstone, func() { // transition the subject to tombstone s.node.memberlist.Evict(subject.address()) }) s.Unlock() }
[ "func", "(", "s", "*", "stateTransitions", ")", "ScheduleTombstoneToEvict", "(", "subject", "subject", ")", "{", "s", ".", "Lock", "(", ")", "\n", "s", ".", "schedule", "(", "subject", ",", "Tombstone", ",", "s", ".", "timeouts", ".", "Tombstone", ",", "func", "(", ")", "{", "// transition the subject to tombstone", "s", ".", "node", ".", "memberlist", ".", "Evict", "(", "subject", ".", "address", "(", ")", ")", "\n", "}", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// ScheduleTombstoneToEvict starts the tombstone timer. After the Faulty timeout the node will be evicted
[ "ScheduleTombstoneToEvict", "starts", "the", "tombstone", "timer", ".", "After", "the", "Faulty", "timeout", "the", "node", "will", "be", "evicted" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L110-L117
143,113
uber/ringpop-go
swim/state_transitions.go
Cancel
func (s *stateTransitions) Cancel(subject subject) { s.Lock() if timer, ok := s.timers[subject.address()]; ok { timer.Stop() delete(s.timers, subject.address()) s.logger.WithFields(bark.Fields{ "member": subject.address(), "state": timer.state, }).Debug("stopped scheduled state transition for member") } s.Unlock() }
go
func (s *stateTransitions) Cancel(subject subject) { s.Lock() if timer, ok := s.timers[subject.address()]; ok { timer.Stop() delete(s.timers, subject.address()) s.logger.WithFields(bark.Fields{ "member": subject.address(), "state": timer.state, }).Debug("stopped scheduled state transition for member") } s.Unlock() }
[ "func", "(", "s", "*", "stateTransitions", ")", "Cancel", "(", "subject", "subject", ")", "{", "s", ".", "Lock", "(", ")", "\n\n", "if", "timer", ",", "ok", ":=", "s", ".", "timers", "[", "subject", ".", "address", "(", ")", "]", ";", "ok", "{", "timer", ".", "Stop", "(", ")", "\n", "delete", "(", "s", ".", "timers", ",", "subject", ".", "address", "(", ")", ")", "\n", "s", ".", "logger", ".", "WithFields", "(", "bark", ".", "Fields", "{", "\"", "\"", ":", "subject", ".", "address", "(", ")", ",", "\"", "\"", ":", "timer", ".", "state", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "s", ".", "Unlock", "(", ")", "\n", "}" ]
// Cancel cancels the scheduled transition for the subject
[ "Cancel", "cancels", "the", "scheduled", "transition", "for", "the", "subject" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L163-L176
143,114
uber/ringpop-go
swim/state_transitions.go
Enable
func (s *stateTransitions) Enable() { s.Lock() if s.enabled { s.logger.Warn("state transition controller already enabled") s.Unlock() return } s.enabled = true s.Unlock() s.logger.Info("enabled state transition controller") }
go
func (s *stateTransitions) Enable() { s.Lock() if s.enabled { s.logger.Warn("state transition controller already enabled") s.Unlock() return } s.enabled = true s.Unlock() s.logger.Info("enabled state transition controller") }
[ "func", "(", "s", "*", "stateTransitions", ")", "Enable", "(", ")", "{", "s", ".", "Lock", "(", ")", "\n\n", "if", "s", ".", "enabled", "{", "s", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "s", ".", "enabled", "=", "true", "\n", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "logger", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// Enable enables state transition controller. The transition controller needs to be in enabled state to allow transitions to be scheduled.
[ "Enable", "enables", "state", "transition", "controller", ".", "The", "transition", "controller", "needs", "to", "be", "in", "enabled", "state", "to", "allow", "transitions", "to", "be", "scheduled", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L179-L191
143,115
uber/ringpop-go
swim/state_transitions.go
Disable
func (s *stateTransitions) Disable() { s.Lock() if !s.enabled { s.logger.Warn("state transition controller already disabled") s.Unlock() return } s.enabled = false numTimers := len(s.timers) for address, timer := range s.timers { timer.Stop() delete(s.timers, address) } s.Unlock() s.logger.WithField("timersStopped", numTimers).Info("disabled state transition controller") }
go
func (s *stateTransitions) Disable() { s.Lock() if !s.enabled { s.logger.Warn("state transition controller already disabled") s.Unlock() return } s.enabled = false numTimers := len(s.timers) for address, timer := range s.timers { timer.Stop() delete(s.timers, address) } s.Unlock() s.logger.WithField("timersStopped", numTimers).Info("disabled state transition controller") }
[ "func", "(", "s", "*", "stateTransitions", ")", "Disable", "(", ")", "{", "s", ".", "Lock", "(", ")", "\n\n", "if", "!", "s", ".", "enabled", "{", "s", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "s", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "s", ".", "enabled", "=", "false", "\n\n", "numTimers", ":=", "len", "(", "s", ".", "timers", ")", "\n", "for", "address", ",", "timer", ":=", "range", "s", ".", "timers", "{", "timer", ".", "Stop", "(", ")", "\n", "delete", "(", "s", ".", "timers", ",", "address", ")", "\n", "}", "\n\n", "s", ".", "Unlock", "(", ")", "\n", "s", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "numTimers", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// Disable cancels all scheduled state transitions and disables the state transition controller for further use
[ "Disable", "cancels", "all", "scheduled", "state", "transitions", "and", "disables", "the", "state", "transition", "controller", "for", "further", "use" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L194-L213
143,116
uber/ringpop-go
swim/state_transitions.go
timer
func (s *stateTransitions) timer(address string) *clock.Timer { s.Lock() t, ok := s.timers[address] s.Unlock() if !ok { return nil } return t.Timer }
go
func (s *stateTransitions) timer(address string) *clock.Timer { s.Lock() t, ok := s.timers[address] s.Unlock() if !ok { return nil } return t.Timer }
[ "func", "(", "s", "*", "stateTransitions", ")", "timer", "(", "address", "string", ")", "*", "clock", ".", "Timer", "{", "s", ".", "Lock", "(", ")", "\n", "t", ",", "ok", ":=", "s", ".", "timers", "[", "address", "]", "\n", "s", ".", "Unlock", "(", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "t", ".", "Timer", "\n", "}" ]
// timer is a testing func to avoid data races
[ "timer", "is", "a", "testing", "func", "to", "avoid", "data", "races" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/state_transitions.go#L216-L224
143,117
uber/ringpop-go
swim/labels.go
Get
func (n *NodeLabels) Get(key string) (value string, has bool) { return n.node.memberlist.GetLocalLabel(key) }
go
func (n *NodeLabels) Get(key string) (value string, has bool) { return n.node.memberlist.GetLocalLabel(key) }
[ "func", "(", "n", "*", "NodeLabels", ")", "Get", "(", "key", "string", ")", "(", "value", "string", ",", "has", "bool", ")", "{", "return", "n", ".", "node", ".", "memberlist", ".", "GetLocalLabel", "(", "key", ")", "\n", "}" ]
// Get the value of a label for this node
[ "Get", "the", "value", "of", "a", "label", "for", "this", "node" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/labels.go#L164-L166
143,118
uber/ringpop-go
swim/labels.go
Remove
func (n *NodeLabels) Remove(key string) (removed bool, err error) { if isInternalLabel(key) { return false, ErrLabelInternalKey } return n.node.memberlist.RemoveLocalLabels(key), nil }
go
func (n *NodeLabels) Remove(key string) (removed bool, err error) { if isInternalLabel(key) { return false, ErrLabelInternalKey } return n.node.memberlist.RemoveLocalLabels(key), nil }
[ "func", "(", "n", "*", "NodeLabels", ")", "Remove", "(", "key", "string", ")", "(", "removed", "bool", ",", "err", "error", ")", "{", "if", "isInternalLabel", "(", "key", ")", "{", "return", "false", ",", "ErrLabelInternalKey", "\n", "}", "\n", "return", "n", ".", "node", ".", "memberlist", ".", "RemoveLocalLabels", "(", "key", ")", ",", "nil", "\n", "}" ]
// Remove a key from the labels
[ "Remove", "a", "key", "from", "the", "labels" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/labels.go#L179-L184
143,119
uber/ringpop-go
swim/heal_via_discover_provider.go
Start
func (h *discoverProviderHealer) Start() { // check if started channel is already filled // if not, we start a new loop select { case h.started <- struct{}{}: default: return } go func() { for { // loop or quit select { case <-h.node.clock.After(h.period): case <-h.quit: return } // attempt heal with the pro if h.rand.Float64() < h.Probability() { h.Heal() } } }() }
go
func (h *discoverProviderHealer) Start() { // check if started channel is already filled // if not, we start a new loop select { case h.started <- struct{}{}: default: return } go func() { for { // loop or quit select { case <-h.node.clock.After(h.period): case <-h.quit: return } // attempt heal with the pro if h.rand.Float64() < h.Probability() { h.Heal() } } }() }
[ "func", "(", "h", "*", "discoverProviderHealer", ")", "Start", "(", ")", "{", "// check if started channel is already filled", "// if not, we start a new loop", "select", "{", "case", "h", ".", "started", "<-", "struct", "{", "}", "{", "}", ":", "default", ":", "return", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "for", "{", "// loop or quit", "select", "{", "case", "<-", "h", ".", "node", ".", "clock", ".", "After", "(", "h", ".", "period", ")", ":", "case", "<-", "h", ".", "quit", ":", "return", "\n", "}", "\n\n", "// attempt heal with the pro", "if", "h", ".", "rand", ".", "Float64", "(", ")", "<", "h", ".", "Probability", "(", ")", "{", "h", ".", "Heal", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Start the partition healing loop
[ "Start", "the", "partition", "healing", "loop" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_via_discover_provider.go#L66-L90
143,120
uber/ringpop-go
swim/heal_via_discover_provider.go
Probability
func (h *discoverProviderHealer) Probability() float64 { // avoid division by zero. if h.previousHostListSize < h.node.CountReachableMembers() { h.previousHostListSize = h.node.CountReachableMembers() } if h.previousHostListSize < 1 { h.previousHostListSize = 1 } return h.baseProbabillity / float64(h.previousHostListSize) }
go
func (h *discoverProviderHealer) Probability() float64 { // avoid division by zero. if h.previousHostListSize < h.node.CountReachableMembers() { h.previousHostListSize = h.node.CountReachableMembers() } if h.previousHostListSize < 1 { h.previousHostListSize = 1 } return h.baseProbabillity / float64(h.previousHostListSize) }
[ "func", "(", "h", "*", "discoverProviderHealer", ")", "Probability", "(", ")", "float64", "{", "// avoid division by zero.", "if", "h", ".", "previousHostListSize", "<", "h", ".", "node", ".", "CountReachableMembers", "(", ")", "{", "h", ".", "previousHostListSize", "=", "h", ".", "node", ".", "CountReachableMembers", "(", ")", "\n", "}", "\n", "if", "h", ".", "previousHostListSize", "<", "1", "{", "h", ".", "previousHostListSize", "=", "1", "\n", "}", "\n", "return", "h", ".", "baseProbabillity", "/", "float64", "(", "h", ".", "previousHostListSize", ")", "\n", "}" ]
// Probability returns the probability when a heal should be attempted // we want to throttle the heal attempts to alleviate pressure on the // discover provider.
[ "Probability", "returns", "the", "probability", "when", "a", "heal", "should", "be", "attempted", "we", "want", "to", "throttle", "the", "heal", "attempts", "to", "alleviate", "pressure", "on", "the", "discover", "provider", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_via_discover_provider.go#L106-L115
143,121
uber/ringpop-go
swim/heal_via_discover_provider.go
Heal
func (h *discoverProviderHealer) Heal() ([]string, error) { h.node.EmitEvent(DiscoHealEvent{}) // get list from discovery provider if h.node.discoverProvider == nil { return []string{}, errors.New("discoverProvider not available to healer") } hostList, err := h.node.discoverProvider.Hosts() if err != nil { h.logger.Warn("healer unable to receive host list from discover provider") return []string{}, err } h.previousHostListSize = len(hostList) // collect the targets this node might want to heal with var targets []string for _, address := range hostList { m, ok := h.node.memberlist.Member(address) if !ok || statePrecedence(m.Status) >= statePrecedence(Faulty) { targets = append(targets, address) } } util.ShuffleStringsInPlace(targets) // filter hosts that we already know about and attempt to heal nodes that // are complementary to the membership of this node. var ret []string failures := 0 maxFailures := 10 for len(targets) != 0 && failures < maxFailures { target := targets[0] targets = del(targets, target) // try to heal partition hostsOnOtherSide, err := AttemptHeal(h.node, target) if err != nil { h.logger.WithFields(log.Fields{ "error": err.Error(), "failure": failures, }).Warn("heal attempt failed (10 in total)") failures++ continue } for _, host := range hostsOnOtherSide { targets = del(targets, host) } ret = append(ret, target) } if failures == maxFailures { h.logger.WithField("reachedNodes", len(ret)).Warn("healer reached max failures") } return ret, nil }
go
func (h *discoverProviderHealer) Heal() ([]string, error) { h.node.EmitEvent(DiscoHealEvent{}) // get list from discovery provider if h.node.discoverProvider == nil { return []string{}, errors.New("discoverProvider not available to healer") } hostList, err := h.node.discoverProvider.Hosts() if err != nil { h.logger.Warn("healer unable to receive host list from discover provider") return []string{}, err } h.previousHostListSize = len(hostList) // collect the targets this node might want to heal with var targets []string for _, address := range hostList { m, ok := h.node.memberlist.Member(address) if !ok || statePrecedence(m.Status) >= statePrecedence(Faulty) { targets = append(targets, address) } } util.ShuffleStringsInPlace(targets) // filter hosts that we already know about and attempt to heal nodes that // are complementary to the membership of this node. var ret []string failures := 0 maxFailures := 10 for len(targets) != 0 && failures < maxFailures { target := targets[0] targets = del(targets, target) // try to heal partition hostsOnOtherSide, err := AttemptHeal(h.node, target) if err != nil { h.logger.WithFields(log.Fields{ "error": err.Error(), "failure": failures, }).Warn("heal attempt failed (10 in total)") failures++ continue } for _, host := range hostsOnOtherSide { targets = del(targets, host) } ret = append(ret, target) } if failures == maxFailures { h.logger.WithField("reachedNodes", len(ret)).Warn("healer reached max failures") } return ret, nil }
[ "func", "(", "h", "*", "discoverProviderHealer", ")", "Heal", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "h", ".", "node", ".", "EmitEvent", "(", "DiscoHealEvent", "{", "}", ")", "\n", "// get list from discovery provider", "if", "h", ".", "node", ".", "discoverProvider", "==", "nil", "{", "return", "[", "]", "string", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hostList", ",", "err", ":=", "h", ".", "node", ".", "discoverProvider", ".", "Hosts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "[", "]", "string", "{", "}", ",", "err", "\n", "}", "\n\n", "h", ".", "previousHostListSize", "=", "len", "(", "hostList", ")", "\n\n", "// collect the targets this node might want to heal with", "var", "targets", "[", "]", "string", "\n", "for", "_", ",", "address", ":=", "range", "hostList", "{", "m", ",", "ok", ":=", "h", ".", "node", ".", "memberlist", ".", "Member", "(", "address", ")", "\n", "if", "!", "ok", "||", "statePrecedence", "(", "m", ".", "Status", ")", ">=", "statePrecedence", "(", "Faulty", ")", "{", "targets", "=", "append", "(", "targets", ",", "address", ")", "\n", "}", "\n", "}", "\n", "util", ".", "ShuffleStringsInPlace", "(", "targets", ")", "\n\n", "// filter hosts that we already know about and attempt to heal nodes that", "// are complementary to the membership of this node.", "var", "ret", "[", "]", "string", "\n", "failures", ":=", "0", "\n", "maxFailures", ":=", "10", "\n", "for", "len", "(", "targets", ")", "!=", "0", "&&", "failures", "<", "maxFailures", "{", "target", ":=", "targets", "[", "0", "]", "\n", "targets", "=", "del", "(", "targets", ",", "target", ")", "\n\n", "// try to heal partition", "hostsOnOtherSide", ",", "err", ":=", "AttemptHeal", "(", "h", ".", "node", ",", "target", ")", "\n\n", "if", "err", "!=", "nil", "{", "h", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "\"", "\"", ":", "failures", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "failures", "++", "\n", "continue", "\n", "}", "\n\n", "for", "_", ",", "host", ":=", "range", "hostsOnOtherSide", "{", "targets", "=", "del", "(", "targets", ",", "host", ")", "\n", "}", "\n\n", "ret", "=", "append", "(", "ret", ",", "target", ")", "\n", "}", "\n\n", "if", "failures", "==", "maxFailures", "{", "h", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "len", "(", "ret", ")", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// Heal iterates over the hostList that the discoverProvider provides. If the // node encounters a host that is faulty or not in the membership, we pick that // node as a target to perform a partition heal with. // // If heal was attempted, returns identities of the target nodes.
[ "Heal", "iterates", "over", "the", "hostList", "that", "the", "discoverProvider", "provides", ".", "If", "the", "node", "encounters", "a", "host", "that", "is", "faulty", "or", "not", "in", "the", "membership", "we", "pick", "that", "node", "as", "a", "target", "to", "perform", "a", "partition", "heal", "with", ".", "If", "heal", "was", "attempted", "returns", "identities", "of", "the", "target", "nodes", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_via_discover_provider.go#L122-L179
143,122
uber/ringpop-go
swim/heal_via_discover_provider.go
del
func del(strs []string, s string) []string { for i := 0; i < len(strs); i++ { if strs[i] != s { continue } strs[i] = strs[len(strs)-1] strs = strs[:len(strs)-1] i-- } return strs }
go
func del(strs []string, s string) []string { for i := 0; i < len(strs); i++ { if strs[i] != s { continue } strs[i] = strs[len(strs)-1] strs = strs[:len(strs)-1] i-- } return strs }
[ "func", "del", "(", "strs", "[", "]", "string", ",", "s", "string", ")", "[", "]", "string", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "strs", ")", ";", "i", "++", "{", "if", "strs", "[", "i", "]", "!=", "s", "{", "continue", "\n", "}", "\n", "strs", "[", "i", "]", "=", "strs", "[", "len", "(", "strs", ")", "-", "1", "]", "\n", "strs", "=", "strs", "[", ":", "len", "(", "strs", ")", "-", "1", "]", "\n", "i", "--", "\n", "}", "\n", "return", "strs", "\n", "}" ]
// del returns a slice where all ocurences of s are filtered out. This modifies // the original slice.
[ "del", "returns", "a", "slice", "where", "all", "ocurences", "of", "s", "are", "filtered", "out", ".", "This", "modifies", "the", "original", "slice", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_via_discover_provider.go#L183-L193
143,123
uber/ringpop-go
util/util.go
ShuffleStrings
func ShuffleStrings(strings []string) []string { newStrings := make([]string, len(strings)) newIndexes := rand.Perm(len(strings)) for o, n := range newIndexes { newStrings[n] = strings[o] } return newStrings }
go
func ShuffleStrings(strings []string) []string { newStrings := make([]string, len(strings)) newIndexes := rand.Perm(len(strings)) for o, n := range newIndexes { newStrings[n] = strings[o] } return newStrings }
[ "func", "ShuffleStrings", "(", "strings", "[", "]", "string", ")", "[", "]", "string", "{", "newStrings", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "strings", ")", ")", "\n", "newIndexes", ":=", "rand", ".", "Perm", "(", "len", "(", "strings", ")", ")", "\n\n", "for", "o", ",", "n", ":=", "range", "newIndexes", "{", "newStrings", "[", "n", "]", "=", "strings", "[", "o", "]", "\n", "}", "\n\n", "return", "newStrings", "\n", "}" ]
// ShuffleStrings takes a slice of strings and returns a new slice containing // the same strings in a random order.
[ "ShuffleStrings", "takes", "a", "slice", "of", "strings", "and", "returns", "a", "new", "slice", "containing", "the", "same", "strings", "in", "a", "random", "order", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/util/util.go#L176-L185
143,124
uber/ringpop-go
util/util.go
TakeNode
func TakeNode(nodes *[]string, index int) string { if len(*nodes) == 0 { return "" } var i int if index >= 0 { if index >= len(*nodes) { return "" } i = index } else { i = rand.Intn(len(*nodes)) } node := (*nodes)[i] *nodes = append((*nodes)[:i], (*nodes)[i+1:]...) return node }
go
func TakeNode(nodes *[]string, index int) string { if len(*nodes) == 0 { return "" } var i int if index >= 0 { if index >= len(*nodes) { return "" } i = index } else { i = rand.Intn(len(*nodes)) } node := (*nodes)[i] *nodes = append((*nodes)[:i], (*nodes)[i+1:]...) return node }
[ "func", "TakeNode", "(", "nodes", "*", "[", "]", "string", ",", "index", "int", ")", "string", "{", "if", "len", "(", "*", "nodes", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "var", "i", "int", "\n", "if", "index", ">=", "0", "{", "if", "index", ">=", "len", "(", "*", "nodes", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "i", "=", "index", "\n", "}", "else", "{", "i", "=", "rand", ".", "Intn", "(", "len", "(", "*", "nodes", ")", ")", "\n", "}", "\n\n", "node", ":=", "(", "*", "nodes", ")", "[", "i", "]", "\n\n", "*", "nodes", "=", "append", "(", "(", "*", "nodes", ")", "[", ":", "i", "]", ",", "(", "*", "nodes", ")", "[", "i", "+", "1", ":", "]", "...", ")", "\n\n", "return", "node", "\n", "}" ]
// TakeNode takes an element from nodes at the given index, or at a random index if // index < 0. Mutates nodes.
[ "TakeNode", "takes", "an", "element", "from", "nodes", "at", "the", "given", "index", "or", "at", "a", "random", "index", "if", "index", "<", "0", ".", "Mutates", "nodes", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/util/util.go#L198-L218
143,125
uber/ringpop-go
util/util.go
SelectDuration
func SelectDuration(opt, def time.Duration) time.Duration { if opt == time.Duration(0) { return def } return opt }
go
func SelectDuration(opt, def time.Duration) time.Duration { if opt == time.Duration(0) { return def } return opt }
[ "func", "SelectDuration", "(", "opt", ",", "def", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "if", "opt", "==", "time", ".", "Duration", "(", "0", ")", "{", "return", "def", "\n", "}", "\n", "return", "opt", "\n", "}" ]
// SelectDuration takes an option and a default value and returns the default value if // the option is equal to zero, and the option otherwise.
[ "SelectDuration", "takes", "an", "option", "and", "a", "default", "value", "and", "returns", "the", "default", "value", "if", "the", "option", "is", "equal", "to", "zero", "and", "the", "option", "otherwise", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/util/util.go#L240-L245
143,126
uber/ringpop-go
util/util.go
Min
func Min(first int, rest ...int) int { m := first for _, value := range rest { if value < m { m = value } } return m }
go
func Min(first int, rest ...int) int { m := first for _, value := range rest { if value < m { m = value } } return m }
[ "func", "Min", "(", "first", "int", ",", "rest", "...", "int", ")", "int", "{", "m", ":=", "first", "\n", "for", "_", ",", "value", ":=", "range", "rest", "{", "if", "value", "<", "m", "{", "m", "=", "value", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Min returns the lowest integer and is defined because golang only has a min // function for floats and not for ints.
[ "Min", "returns", "the", "lowest", "integer", "and", "is", "defined", "because", "golang", "only", "has", "a", "min", "function", "for", "floats", "and", "not", "for", "ints", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/util/util.go#L258-L266
143,127
uber/ringpop-go
util/util.go
UnmarshalJSON
func (t *Timestamp) UnmarshalJSON(b []byte) error { ts, err := strconv.Atoi(string(b)) if err != nil { return err } *t = Timestamp(time.Unix(int64(ts), 0)) return nil }
go
func (t *Timestamp) UnmarshalJSON(b []byte) error { ts, err := strconv.Atoi(string(b)) if err != nil { return err } *t = Timestamp(time.Unix(int64(ts), 0)) return nil }
[ "func", "(", "t", "*", "Timestamp", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "ts", ",", "err", ":=", "strconv", ".", "Atoi", "(", "string", "(", "b", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "t", "=", "Timestamp", "(", "time", ".", "Unix", "(", "int64", "(", "ts", ")", ",", "0", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON sets the timestamp to the value in the specified JSON.
[ "UnmarshalJSON", "sets", "the", "timestamp", "to", "the", "value", "in", "the", "specified", "JSON", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/util/util.go#L281-L290
143,128
uber/ringpop-go
swim/join_delayer.go
newDelayOpts
func newDelayOpts() *delayOpts { return &delayOpts{ initial: defaultInitial, max: defaultMax, randomizer: defaultRandomizer, sleeper: defaultSleeper, } }
go
func newDelayOpts() *delayOpts { return &delayOpts{ initial: defaultInitial, max: defaultMax, randomizer: defaultRandomizer, sleeper: defaultSleeper, } }
[ "func", "newDelayOpts", "(", ")", "*", "delayOpts", "{", "return", "&", "delayOpts", "{", "initial", ":", "defaultInitial", ",", "max", ":", "defaultMax", ",", "randomizer", ":", "defaultRandomizer", ",", "sleeper", ":", "defaultSleeper", ",", "}", "\n", "}" ]
// newDelayOpts creates a delayOpts struct with default values.
[ "newDelayOpts", "creates", "a", "delayOpts", "struct", "with", "default", "values", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_delayer.go#L66-L73
143,129
uber/ringpop-go
swim/join_delayer.go
newExponentialDelayer
func newExponentialDelayer(joiner string, opts *delayOpts) (*exponentialDelayer, error) { if opts == nil { opts = newDelayOpts() } randomizer := opts.randomizer if randomizer == nil { randomizer = defaultRandomizer } sleeper := opts.sleeper if sleeper == nil { sleeper = defaultSleeper } return &exponentialDelayer{ logger: logging.Logger("join").WithField("local", joiner), initialDelay: opts.initial, nextDelayMin: 0, maxDelayReached: false, maxDelay: opts.max, randomizer: randomizer, sleeper: sleeper, numDelays: 0, }, nil }
go
func newExponentialDelayer(joiner string, opts *delayOpts) (*exponentialDelayer, error) { if opts == nil { opts = newDelayOpts() } randomizer := opts.randomizer if randomizer == nil { randomizer = defaultRandomizer } sleeper := opts.sleeper if sleeper == nil { sleeper = defaultSleeper } return &exponentialDelayer{ logger: logging.Logger("join").WithField("local", joiner), initialDelay: opts.initial, nextDelayMin: 0, maxDelayReached: false, maxDelay: opts.max, randomizer: randomizer, sleeper: sleeper, numDelays: 0, }, nil }
[ "func", "newExponentialDelayer", "(", "joiner", "string", ",", "opts", "*", "delayOpts", ")", "(", "*", "exponentialDelayer", ",", "error", ")", "{", "if", "opts", "==", "nil", "{", "opts", "=", "newDelayOpts", "(", ")", "\n", "}", "\n\n", "randomizer", ":=", "opts", ".", "randomizer", "\n", "if", "randomizer", "==", "nil", "{", "randomizer", "=", "defaultRandomizer", "\n", "}", "\n\n", "sleeper", ":=", "opts", ".", "sleeper", "\n", "if", "sleeper", "==", "nil", "{", "sleeper", "=", "defaultSleeper", "\n", "}", "\n\n", "return", "&", "exponentialDelayer", "{", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "joiner", ")", ",", "initialDelay", ":", "opts", ".", "initial", ",", "nextDelayMin", ":", "0", ",", "maxDelayReached", ":", "false", ",", "maxDelay", ":", "opts", ".", "max", ",", "randomizer", ":", "randomizer", ",", "sleeper", ":", "sleeper", ",", "numDelays", ":", "0", ",", "}", ",", "nil", "\n", "}" ]
// newExponentialDelayer creates a new exponential delayer. joiner is required. // opts is optional.
[ "newExponentialDelayer", "creates", "a", "new", "exponential", "delayer", ".", "joiner", "is", "required", ".", "opts", "is", "optional", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_delayer.go#L112-L137
143,130
uber/ringpop-go
swim/join_delayer.go
delay
func (d *exponentialDelayer) delay() time.Duration { // Convert durations to time in millis initialDelayMs := float64(util.MS(d.initialDelay)) maxDelayMs := float64(util.MS(d.maxDelay)) // Compute uncapped exponential delay (exponent is the number of join // attempts so far). Then, make sure the computed delay is capped at its // max. Apply a random jitter to the actual sleep duration and finally, // sleep. uncappedDelay := initialDelayMs * math.Pow(2, float64(d.numDelays)) cappedDelay := math.Min(maxDelayMs, uncappedDelay) // If cappedDelay and nextDelayMin are equal, we have reached the point // at which the exponential backoff has reached its max; apply no more // jitter. var jitteredDelay int if cappedDelay == d.nextDelayMin { jitteredDelay = int(cappedDelay) } else { jitteredDelay = d.randomizer(int(cappedDelay-d.nextDelayMin)) + int(d.nextDelayMin) } // If this is the first time an uncapped delay reached or exceeded the // maximum allowable delay, log a message. if uncappedDelay >= maxDelayMs && d.maxDelayReached == false { d.logger.WithFields(bark.Fields{ "numDelays": d.numDelays, "initialDelay": d.initialDelay, "minDelay": d.nextDelayMin, "maxDelay": d.maxDelay, "uncappedDelay": uncappedDelay, "cappedDelay": cappedDelay, "jitteredDelay": jitteredDelay, }).Warn("ringpop join attempt delay reached max") d.maxDelayReached = true } // Set lower-bound for next attempt to maximum of current attempt. d.nextDelayMin = cappedDelay sleepDuration := time.Duration(jitteredDelay) * time.Millisecond d.sleeper(sleepDuration) // Increment the exponent used for backoff calculation. d.numDelays++ return sleepDuration }
go
func (d *exponentialDelayer) delay() time.Duration { // Convert durations to time in millis initialDelayMs := float64(util.MS(d.initialDelay)) maxDelayMs := float64(util.MS(d.maxDelay)) // Compute uncapped exponential delay (exponent is the number of join // attempts so far). Then, make sure the computed delay is capped at its // max. Apply a random jitter to the actual sleep duration and finally, // sleep. uncappedDelay := initialDelayMs * math.Pow(2, float64(d.numDelays)) cappedDelay := math.Min(maxDelayMs, uncappedDelay) // If cappedDelay and nextDelayMin are equal, we have reached the point // at which the exponential backoff has reached its max; apply no more // jitter. var jitteredDelay int if cappedDelay == d.nextDelayMin { jitteredDelay = int(cappedDelay) } else { jitteredDelay = d.randomizer(int(cappedDelay-d.nextDelayMin)) + int(d.nextDelayMin) } // If this is the first time an uncapped delay reached or exceeded the // maximum allowable delay, log a message. if uncappedDelay >= maxDelayMs && d.maxDelayReached == false { d.logger.WithFields(bark.Fields{ "numDelays": d.numDelays, "initialDelay": d.initialDelay, "minDelay": d.nextDelayMin, "maxDelay": d.maxDelay, "uncappedDelay": uncappedDelay, "cappedDelay": cappedDelay, "jitteredDelay": jitteredDelay, }).Warn("ringpop join attempt delay reached max") d.maxDelayReached = true } // Set lower-bound for next attempt to maximum of current attempt. d.nextDelayMin = cappedDelay sleepDuration := time.Duration(jitteredDelay) * time.Millisecond d.sleeper(sleepDuration) // Increment the exponent used for backoff calculation. d.numDelays++ return sleepDuration }
[ "func", "(", "d", "*", "exponentialDelayer", ")", "delay", "(", ")", "time", ".", "Duration", "{", "// Convert durations to time in millis", "initialDelayMs", ":=", "float64", "(", "util", ".", "MS", "(", "d", ".", "initialDelay", ")", ")", "\n", "maxDelayMs", ":=", "float64", "(", "util", ".", "MS", "(", "d", ".", "maxDelay", ")", ")", "\n\n", "// Compute uncapped exponential delay (exponent is the number of join", "// attempts so far). Then, make sure the computed delay is capped at its", "// max. Apply a random jitter to the actual sleep duration and finally,", "// sleep.", "uncappedDelay", ":=", "initialDelayMs", "*", "math", ".", "Pow", "(", "2", ",", "float64", "(", "d", ".", "numDelays", ")", ")", "\n", "cappedDelay", ":=", "math", ".", "Min", "(", "maxDelayMs", ",", "uncappedDelay", ")", "\n\n", "// If cappedDelay and nextDelayMin are equal, we have reached the point", "// at which the exponential backoff has reached its max; apply no more", "// jitter.", "var", "jitteredDelay", "int", "\n", "if", "cappedDelay", "==", "d", ".", "nextDelayMin", "{", "jitteredDelay", "=", "int", "(", "cappedDelay", ")", "\n", "}", "else", "{", "jitteredDelay", "=", "d", ".", "randomizer", "(", "int", "(", "cappedDelay", "-", "d", ".", "nextDelayMin", ")", ")", "+", "int", "(", "d", ".", "nextDelayMin", ")", "\n", "}", "\n\n", "// If this is the first time an uncapped delay reached or exceeded the", "// maximum allowable delay, log a message.", "if", "uncappedDelay", ">=", "maxDelayMs", "&&", "d", ".", "maxDelayReached", "==", "false", "{", "d", ".", "logger", ".", "WithFields", "(", "bark", ".", "Fields", "{", "\"", "\"", ":", "d", ".", "numDelays", ",", "\"", "\"", ":", "d", ".", "initialDelay", ",", "\"", "\"", ":", "d", ".", "nextDelayMin", ",", "\"", "\"", ":", "d", ".", "maxDelay", ",", "\"", "\"", ":", "uncappedDelay", ",", "\"", "\"", ":", "cappedDelay", ",", "\"", "\"", ":", "jitteredDelay", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "d", ".", "maxDelayReached", "=", "true", "\n", "}", "\n\n", "// Set lower-bound for next attempt to maximum of current attempt.", "d", ".", "nextDelayMin", "=", "cappedDelay", "\n\n", "sleepDuration", ":=", "time", ".", "Duration", "(", "jitteredDelay", ")", "*", "time", ".", "Millisecond", "\n", "d", ".", "sleeper", "(", "sleepDuration", ")", "\n\n", "// Increment the exponent used for backoff calculation.", "d", ".", "numDelays", "++", "\n\n", "return", "sleepDuration", "\n", "}" ]
// delay delays a join attempt by sleeping for an amount of time. The // amount of time is computed as an exponential backoff based on the number // of join attempts that have been made at the time of the function call; // the number of attempts is 0-based. It returns a time.Duration equal to the // amount of delay applied.
[ "delay", "delays", "a", "join", "attempt", "by", "sleeping", "for", "an", "amount", "of", "time", ".", "The", "amount", "of", "time", "is", "computed", "as", "an", "exponential", "backoff", "based", "on", "the", "number", "of", "join", "attempts", "that", "have", "been", "made", "at", "the", "time", "of", "the", "function", "call", ";", "the", "number", "of", "attempts", "is", "0", "-", "based", ".", "It", "returns", "a", "time", ".", "Duration", "equal", "to", "the", "amount", "of", "delay", "applied", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_delayer.go#L144-L191
143,131
uber/ringpop-go
examples/ping-thrift-gen/gen-go/ping/ringpop-ping.go
Ping
func (a *RingpopPingPongServiceAdapter) Ping(ctx thrift.Context, request *Ping) (r *Pong, err error) { // check if the function should be called locally if a.config.Ping == nil || forward.DeleteForwardedHeader(ctx) { return a.impl.Ping(ctx, request) } // find the key to shard on ringpopKey, err := a.config.Ping.Key(ctx, request) if err != nil { return r, fmt.Errorf("could not get key: %q", err) } clientInterface, isRemote, err := a.router.GetClient(ringpopKey) if err != nil { return r, err } client := clientInterface.(TChanPingPongService) if isRemote { ctx = forward.SetForwardedHeader(ctx, []string{ringpopKey}) } return client.Ping(ctx, request) }
go
func (a *RingpopPingPongServiceAdapter) Ping(ctx thrift.Context, request *Ping) (r *Pong, err error) { // check if the function should be called locally if a.config.Ping == nil || forward.DeleteForwardedHeader(ctx) { return a.impl.Ping(ctx, request) } // find the key to shard on ringpopKey, err := a.config.Ping.Key(ctx, request) if err != nil { return r, fmt.Errorf("could not get key: %q", err) } clientInterface, isRemote, err := a.router.GetClient(ringpopKey) if err != nil { return r, err } client := clientInterface.(TChanPingPongService) if isRemote { ctx = forward.SetForwardedHeader(ctx, []string{ringpopKey}) } return client.Ping(ctx, request) }
[ "func", "(", "a", "*", "RingpopPingPongServiceAdapter", ")", "Ping", "(", "ctx", "thrift", ".", "Context", ",", "request", "*", "Ping", ")", "(", "r", "*", "Pong", ",", "err", "error", ")", "{", "// check if the function should be called locally", "if", "a", ".", "config", ".", "Ping", "==", "nil", "||", "forward", ".", "DeleteForwardedHeader", "(", "ctx", ")", "{", "return", "a", ".", "impl", ".", "Ping", "(", "ctx", ",", "request", ")", "\n", "}", "\n\n", "// find the key to shard on", "ringpopKey", ",", "err", ":=", "a", ".", "config", ".", "Ping", ".", "Key", "(", "ctx", ",", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "clientInterface", ",", "isRemote", ",", "err", ":=", "a", ".", "router", ".", "GetClient", "(", "ringpopKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n\n", "client", ":=", "clientInterface", ".", "(", "TChanPingPongService", ")", "\n", "if", "isRemote", "{", "ctx", "=", "forward", ".", "SetForwardedHeader", "(", "ctx", ",", "[", "]", "string", "{", "ringpopKey", "}", ")", "\n", "}", "\n", "return", "client", ".", "Ping", "(", "ctx", ",", "request", ")", "\n", "}" ]
// Ping satisfies the TChanPingPongService interface. This function uses the configuration for Ping to determine the host to execute the call on. When it decides the call needs to be executed in the current process it will forward the invocation to its local implementation.
[ "Ping", "satisfies", "the", "TChanPingPongService", "interface", ".", "This", "function", "uses", "the", "configuration", "for", "Ping", "to", "determine", "the", "host", "to", "execute", "the", "call", "on", ".", "When", "it", "decides", "the", "call", "needs", "to", "be", "executed", "in", "the", "current", "process", "it", "will", "forward", "the", "invocation", "to", "its", "local", "implementation", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/examples/ping-thrift-gen/gen-go/ping/ringpop-ping.go#L100-L122
143,132
uber/ringpop-go
logging/named.go
WithField
func (l *namedLogger) WithField(key string, value interface{}) bark.Logger { newSize := len(l.fields) + 1 newFields := make(map[string]interface{}, newSize) // Hold the updated copy for k, v := range l.fields { newFields[k] = v } newFields[key] = value // Set the new key. return &namedLogger{ name: l.name, forwardTo: l.forwardTo, fields: newFields, } }
go
func (l *namedLogger) WithField(key string, value interface{}) bark.Logger { newSize := len(l.fields) + 1 newFields := make(map[string]interface{}, newSize) // Hold the updated copy for k, v := range l.fields { newFields[k] = v } newFields[key] = value // Set the new key. return &namedLogger{ name: l.name, forwardTo: l.forwardTo, fields: newFields, } }
[ "func", "(", "l", "*", "namedLogger", ")", "WithField", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "bark", ".", "Logger", "{", "newSize", ":=", "len", "(", "l", ".", "fields", ")", "+", "1", "\n", "newFields", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "newSize", ")", "// Hold the updated copy", "\n", "for", "k", ",", "v", ":=", "range", "l", ".", "fields", "{", "newFields", "[", "k", "]", "=", "v", "\n", "}", "\n", "newFields", "[", "key", "]", "=", "value", "// Set the new key.", "\n\n", "return", "&", "namedLogger", "{", "name", ":", "l", ".", "name", ",", "forwardTo", ":", "l", ".", "forwardTo", ",", "fields", ":", "newFields", ",", "}", "\n", "}" ]
// WithField creates a new namedLogger that retains the name but has an updated // copy of the fields.
[ "WithField", "creates", "a", "new", "namedLogger", "that", "retains", "the", "name", "but", "has", "an", "updated", "copy", "of", "the", "fields", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/named.go#L72-L85
143,133
uber/ringpop-go
logging/named.go
WithError
func (l *namedLogger) WithError(err error) bark.Logger { return &namedLogger{ name: l.name, forwardTo: l.forwardTo, err: err, fields: l.Fields(), } }
go
func (l *namedLogger) WithError(err error) bark.Logger { return &namedLogger{ name: l.name, forwardTo: l.forwardTo, err: err, fields: l.Fields(), } }
[ "func", "(", "l", "*", "namedLogger", ")", "WithError", "(", "err", "error", ")", "bark", ".", "Logger", "{", "return", "&", "namedLogger", "{", "name", ":", "l", ".", "name", ",", "forwardTo", ":", "l", ".", "forwardTo", ",", "err", ":", "err", ",", "fields", ":", "l", ".", "Fields", "(", ")", ",", "}", "\n", "}" ]
// Return a new named logger with the error set to be included in a subsequent // normal logging call
[ "Return", "a", "new", "named", "logger", "with", "the", "error", "set", "to", "be", "included", "in", "a", "subsequent", "normal", "logging", "call" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/named.go#L109-L116
143,134
uber/ringpop-go
swim/ping_sender.go
sendPing
func sendPing(node *Node, target string, timeout time.Duration) (*ping, error) { changes, bumpPiggybackCounters := node.disseminator.IssueAsSender() res, err := sendPingWithChanges(node, target, changes, timeout) if err != nil { return res, err } // when ping was successful bumpPiggybackCounters() return res, err }
go
func sendPing(node *Node, target string, timeout time.Duration) (*ping, error) { changes, bumpPiggybackCounters := node.disseminator.IssueAsSender() res, err := sendPingWithChanges(node, target, changes, timeout) if err != nil { return res, err } // when ping was successful bumpPiggybackCounters() return res, err }
[ "func", "sendPing", "(", "node", "*", "Node", ",", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "ping", ",", "error", ")", "{", "changes", ",", "bumpPiggybackCounters", ":=", "node", ".", "disseminator", ".", "IssueAsSender", "(", ")", "\n\n", "res", ",", "err", ":=", "sendPingWithChanges", "(", "node", ",", "target", ",", "changes", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "// when ping was successful", "bumpPiggybackCounters", "(", ")", "\n\n", "return", "res", ",", "err", "\n", "}" ]
// sendPing sends a ping to target node that times out after timeout
[ "sendPing", "sends", "a", "ping", "to", "target", "node", "that", "times", "out", "after", "timeout" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/ping_sender.go#L44-L56
143,135
uber/ringpop-go
swim/ping_sender.go
sendPingWithChanges
func sendPingWithChanges(node *Node, target string, changes []Change, timeout time.Duration) (*ping, error) { req := ping{ Checksum: node.memberlist.Checksum(), Changes: changes, Source: node.Address(), SourceIncarnation: node.Incarnation(), App: node.app, } node.EmitEvent(PingSendEvent{ Local: node.Address(), Remote: target, Changes: req.Changes, }) logging.Logger("ping").WithFields(log.Fields{ "local": node.Address(), "remote": target, "changes": req.Changes, }).Debug("ping send") ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) startTime := time.Now() // send the ping errC := make(chan error, 1) res := &ping{} go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/ping", req, res) }() // get result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errors.New("ping timed out") } if err != nil { // ping failed logging.Logger("ping").WithFields(log.Fields{ "local": node.Address(), "remote": target, "error": err, }).Debug("ping failed") return nil, err } node.EmitEvent(PingSendCompleteEvent{ Local: node.Address(), Remote: target, Changes: req.Changes, Duration: time.Now().Sub(startTime), }) return res, err }
go
func sendPingWithChanges(node *Node, target string, changes []Change, timeout time.Duration) (*ping, error) { req := ping{ Checksum: node.memberlist.Checksum(), Changes: changes, Source: node.Address(), SourceIncarnation: node.Incarnation(), App: node.app, } node.EmitEvent(PingSendEvent{ Local: node.Address(), Remote: target, Changes: req.Changes, }) logging.Logger("ping").WithFields(log.Fields{ "local": node.Address(), "remote": target, "changes": req.Changes, }).Debug("ping send") ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) startTime := time.Now() // send the ping errC := make(chan error, 1) res := &ping{} go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/ping", req, res) }() // get result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errors.New("ping timed out") } if err != nil { // ping failed logging.Logger("ping").WithFields(log.Fields{ "local": node.Address(), "remote": target, "error": err, }).Debug("ping failed") return nil, err } node.EmitEvent(PingSendCompleteEvent{ Local: node.Address(), Remote: target, Changes: req.Changes, Duration: time.Now().Sub(startTime), }) return res, err }
[ "func", "sendPingWithChanges", "(", "node", "*", "Node", ",", "target", "string", ",", "changes", "[", "]", "Change", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "ping", ",", "error", ")", "{", "req", ":=", "ping", "{", "Checksum", ":", "node", ".", "memberlist", ".", "Checksum", "(", ")", ",", "Changes", ":", "changes", ",", "Source", ":", "node", ".", "Address", "(", ")", ",", "SourceIncarnation", ":", "node", ".", "Incarnation", "(", ")", ",", "App", ":", "node", ".", "app", ",", "}", "\n\n", "node", ".", "EmitEvent", "(", "PingSendEvent", "{", "Local", ":", "node", ".", "Address", "(", ")", ",", "Remote", ":", "target", ",", "Changes", ":", "req", ".", "Changes", ",", "}", ")", "\n\n", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "Address", "(", ")", ",", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "req", ".", "Changes", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "ctx", ",", "cancel", ":=", "shared", ".", "NewTChannelContext", "(", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "peer", ":=", "node", ".", "channel", ".", "Peers", "(", ")", ".", "GetOrAdd", "(", "target", ")", "\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "// send the ping", "errC", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "res", ":=", "&", "ping", "{", "}", "\n", "go", "func", "(", ")", "{", "errC", "<-", "json", ".", "CallPeer", "(", "ctx", ",", "peer", ",", "node", ".", "service", ",", "\"", "\"", ",", "req", ",", "res", ")", "\n", "}", "(", ")", "\n\n", "// get result or timeout", "var", "err", "error", "\n", "select", "{", "case", "err", "=", "<-", "errC", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "// ping failed", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "Address", "(", ")", ",", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "node", ".", "EmitEvent", "(", "PingSendCompleteEvent", "{", "Local", ":", "node", ".", "Address", "(", ")", ",", "Remote", ":", "target", ",", "Changes", ":", "req", ".", "Changes", ",", "Duration", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ",", "}", ")", "\n\n", "return", "res", ",", "err", "\n", "}" ]
// sendPingWithChanges sends a special ping to the target with the given changes. // In normal pings the disseminator is consulted to create issue the changes, // this is not the case in this function. Only the given changes are transmitted.
[ "sendPingWithChanges", "sends", "a", "special", "ping", "to", "the", "target", "with", "the", "given", "changes", ".", "In", "normal", "pings", "the", "disseminator", "is", "consulted", "to", "create", "issue", "the", "changes", "this", "is", "not", "the", "case", "in", "this", "function", ".", "Only", "the", "given", "changes", "are", "transmitted", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/ping_sender.go#L61-L122
143,136
uber/ringpop-go
hashring/rbtree.go
Child
func (n *redBlackNode) Child(right bool) *redBlackNode { if right { return n.right } return n.left }
go
func (n *redBlackNode) Child(right bool) *redBlackNode { if right { return n.right } return n.left }
[ "func", "(", "n", "*", "redBlackNode", ")", "Child", "(", "right", "bool", ")", "*", "redBlackNode", "{", "if", "right", "{", "return", "n", ".", "right", "\n", "}", "\n", "return", "n", ".", "left", "\n", "}" ]
// Child returns the left or right node of the redBlackTree
[ "Child", "returns", "the", "left", "or", "right", "node", "of", "the", "redBlackTree" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L50-L55
143,137
uber/ringpop-go
hashring/rbtree.go
Insert
func (t *redBlackTree) Insert(key keytype, value valuetype) (ret bool) { if t.root == nil { t.root = &redBlackNode{ key: key, value: value, } ret = true } else { var head = &redBlackNode{} var dir = true var last = true var parent *redBlackNode // parent var gparent *redBlackNode // grandparent var ggparent = head // great grandparent var node = t.root ggparent.right = t.root for { if node == nil { // insert new node at bottom node = &redBlackNode{ key: key, value: value, red: true, } parent.setChild(dir, node) ret = true } else if isRed(node.left) && isRed(node.right) { // flip colors node.red = true node.left.red, node.right.red = false, false } // fix red violation if isRed(node) && isRed(parent) { dir2 := ggparent.right == gparent if node == parent.Child(last) { ggparent.setChild(dir2, singleRotate(gparent, !last)) } else { ggparent.setChild(dir2, doubleRotate(gparent, !last)) } } cmp := node.key.Compare(key) // stop if found if cmp == 0 { break } last = dir dir = cmp < 0 // update helpers if gparent != nil { ggparent = gparent } gparent = parent parent = node node = node.Child(dir) } t.root = head.right } // make root black t.root.red = false if ret { t.size++ } return ret }
go
func (t *redBlackTree) Insert(key keytype, value valuetype) (ret bool) { if t.root == nil { t.root = &redBlackNode{ key: key, value: value, } ret = true } else { var head = &redBlackNode{} var dir = true var last = true var parent *redBlackNode // parent var gparent *redBlackNode // grandparent var ggparent = head // great grandparent var node = t.root ggparent.right = t.root for { if node == nil { // insert new node at bottom node = &redBlackNode{ key: key, value: value, red: true, } parent.setChild(dir, node) ret = true } else if isRed(node.left) && isRed(node.right) { // flip colors node.red = true node.left.red, node.right.red = false, false } // fix red violation if isRed(node) && isRed(parent) { dir2 := ggparent.right == gparent if node == parent.Child(last) { ggparent.setChild(dir2, singleRotate(gparent, !last)) } else { ggparent.setChild(dir2, doubleRotate(gparent, !last)) } } cmp := node.key.Compare(key) // stop if found if cmp == 0 { break } last = dir dir = cmp < 0 // update helpers if gparent != nil { ggparent = gparent } gparent = parent parent = node node = node.Child(dir) } t.root = head.right } // make root black t.root.red = false if ret { t.size++ } return ret }
[ "func", "(", "t", "*", "redBlackTree", ")", "Insert", "(", "key", "keytype", ",", "value", "valuetype", ")", "(", "ret", "bool", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "t", ".", "root", "=", "&", "redBlackNode", "{", "key", ":", "key", ",", "value", ":", "value", ",", "}", "\n", "ret", "=", "true", "\n", "}", "else", "{", "var", "head", "=", "&", "redBlackNode", "{", "}", "\n\n", "var", "dir", "=", "true", "\n", "var", "last", "=", "true", "\n\n", "var", "parent", "*", "redBlackNode", "// parent", "\n", "var", "gparent", "*", "redBlackNode", "// grandparent", "\n", "var", "ggparent", "=", "head", "// great grandparent", "\n", "var", "node", "=", "t", ".", "root", "\n\n", "ggparent", ".", "right", "=", "t", ".", "root", "\n\n", "for", "{", "if", "node", "==", "nil", "{", "// insert new node at bottom", "node", "=", "&", "redBlackNode", "{", "key", ":", "key", ",", "value", ":", "value", ",", "red", ":", "true", ",", "}", "\n", "parent", ".", "setChild", "(", "dir", ",", "node", ")", "\n", "ret", "=", "true", "\n", "}", "else", "if", "isRed", "(", "node", ".", "left", ")", "&&", "isRed", "(", "node", ".", "right", ")", "{", "// flip colors", "node", ".", "red", "=", "true", "\n", "node", ".", "left", ".", "red", ",", "node", ".", "right", ".", "red", "=", "false", ",", "false", "\n", "}", "\n", "// fix red violation", "if", "isRed", "(", "node", ")", "&&", "isRed", "(", "parent", ")", "{", "dir2", ":=", "ggparent", ".", "right", "==", "gparent", "\n\n", "if", "node", "==", "parent", ".", "Child", "(", "last", ")", "{", "ggparent", ".", "setChild", "(", "dir2", ",", "singleRotate", "(", "gparent", ",", "!", "last", ")", ")", "\n", "}", "else", "{", "ggparent", ".", "setChild", "(", "dir2", ",", "doubleRotate", "(", "gparent", ",", "!", "last", ")", ")", "\n", "}", "\n", "}", "\n\n", "cmp", ":=", "node", ".", "key", ".", "Compare", "(", "key", ")", "\n\n", "// stop if found", "if", "cmp", "==", "0", "{", "break", "\n", "}", "\n\n", "last", "=", "dir", "\n", "dir", "=", "cmp", "<", "0", "\n\n", "// update helpers", "if", "gparent", "!=", "nil", "{", "ggparent", "=", "gparent", "\n", "}", "\n", "gparent", "=", "parent", "\n", "parent", "=", "node", "\n\n", "node", "=", "node", ".", "Child", "(", "dir", ")", "\n", "}", "\n\n", "t", ".", "root", "=", "head", ".", "right", "\n", "}", "\n\n", "// make root black", "t", ".", "root", ".", "red", "=", "false", "\n\n", "if", "ret", "{", "t", ".", "size", "++", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// Insert inserts a value and string into the tree // Returns true on succesful insertion, false if duplicate exists
[ "Insert", "inserts", "a", "value", "and", "string", "into", "the", "tree", "Returns", "true", "on", "succesful", "insertion", "false", "if", "duplicate", "exists" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L89-L166
143,138
uber/ringpop-go
hashring/rbtree.go
Delete
func (t *redBlackTree) Delete(key keytype) bool { if t.root == nil { return false } var head = &redBlackNode{red: true} // fake red node to push down var node = head var parent *redBlackNode //parent var gparent *redBlackNode //grandparent var found *redBlackNode var dir = true node.right = t.root for node.Child(dir) != nil { last := dir // update helpers gparent = parent parent = node node = node.Child(dir) cmp := node.key.Compare(key) dir = cmp < 0 // save node if found if cmp == 0 { found = node } // pretend to push red node down if !isRed(node) && !isRed(node.Child(dir)) { if isRed(node.Child(!dir)) { sr := singleRotate(node, dir) parent.setChild(last, sr) parent = sr } else { sibling := parent.Child(!last) if sibling != nil { if !isRed(sibling.Child(!last)) && !isRed(sibling.Child(last)) { // flip colors parent.red = false sibling.red, node.red = true, true } else { dir2 := gparent.right == parent if isRed(sibling.Child(last)) { gparent.setChild(dir2, doubleRotate(parent, last)) } else if isRed(sibling.Child(!last)) { gparent.setChild(dir2, singleRotate(parent, last)) } gpc := gparent.Child(dir2) gpc.red = true node.red = true gpc.left.red, gpc.right.red = false, false } } } } } // get rid of node if we've found one if found != nil { found.key = node.key found.value = node.value parent.setChild(parent.right == node, node.Child(node.left == nil)) t.size-- } t.root = head.right if t.root != nil { t.root.red = false } return found != nil }
go
func (t *redBlackTree) Delete(key keytype) bool { if t.root == nil { return false } var head = &redBlackNode{red: true} // fake red node to push down var node = head var parent *redBlackNode //parent var gparent *redBlackNode //grandparent var found *redBlackNode var dir = true node.right = t.root for node.Child(dir) != nil { last := dir // update helpers gparent = parent parent = node node = node.Child(dir) cmp := node.key.Compare(key) dir = cmp < 0 // save node if found if cmp == 0 { found = node } // pretend to push red node down if !isRed(node) && !isRed(node.Child(dir)) { if isRed(node.Child(!dir)) { sr := singleRotate(node, dir) parent.setChild(last, sr) parent = sr } else { sibling := parent.Child(!last) if sibling != nil { if !isRed(sibling.Child(!last)) && !isRed(sibling.Child(last)) { // flip colors parent.red = false sibling.red, node.red = true, true } else { dir2 := gparent.right == parent if isRed(sibling.Child(last)) { gparent.setChild(dir2, doubleRotate(parent, last)) } else if isRed(sibling.Child(!last)) { gparent.setChild(dir2, singleRotate(parent, last)) } gpc := gparent.Child(dir2) gpc.red = true node.red = true gpc.left.red, gpc.right.red = false, false } } } } } // get rid of node if we've found one if found != nil { found.key = node.key found.value = node.value parent.setChild(parent.right == node, node.Child(node.left == nil)) t.size-- } t.root = head.right if t.root != nil { t.root.red = false } return found != nil }
[ "func", "(", "t", "*", "redBlackTree", ")", "Delete", "(", "key", "keytype", ")", "bool", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "var", "head", "=", "&", "redBlackNode", "{", "red", ":", "true", "}", "// fake red node to push down", "\n", "var", "node", "=", "head", "\n", "var", "parent", "*", "redBlackNode", "//parent", "\n", "var", "gparent", "*", "redBlackNode", "//grandparent", "\n", "var", "found", "*", "redBlackNode", "\n\n", "var", "dir", "=", "true", "\n\n", "node", ".", "right", "=", "t", ".", "root", "\n\n", "for", "node", ".", "Child", "(", "dir", ")", "!=", "nil", "{", "last", ":=", "dir", "\n\n", "// update helpers", "gparent", "=", "parent", "\n", "parent", "=", "node", "\n", "node", "=", "node", ".", "Child", "(", "dir", ")", "\n\n", "cmp", ":=", "node", ".", "key", ".", "Compare", "(", "key", ")", "\n\n", "dir", "=", "cmp", "<", "0", "\n\n", "// save node if found", "if", "cmp", "==", "0", "{", "found", "=", "node", "\n", "}", "\n\n", "// pretend to push red node down", "if", "!", "isRed", "(", "node", ")", "&&", "!", "isRed", "(", "node", ".", "Child", "(", "dir", ")", ")", "{", "if", "isRed", "(", "node", ".", "Child", "(", "!", "dir", ")", ")", "{", "sr", ":=", "singleRotate", "(", "node", ",", "dir", ")", "\n", "parent", ".", "setChild", "(", "last", ",", "sr", ")", "\n", "parent", "=", "sr", "\n", "}", "else", "{", "sibling", ":=", "parent", ".", "Child", "(", "!", "last", ")", "\n", "if", "sibling", "!=", "nil", "{", "if", "!", "isRed", "(", "sibling", ".", "Child", "(", "!", "last", ")", ")", "&&", "!", "isRed", "(", "sibling", ".", "Child", "(", "last", ")", ")", "{", "// flip colors", "parent", ".", "red", "=", "false", "\n", "sibling", ".", "red", ",", "node", ".", "red", "=", "true", ",", "true", "\n", "}", "else", "{", "dir2", ":=", "gparent", ".", "right", "==", "parent", "\n\n", "if", "isRed", "(", "sibling", ".", "Child", "(", "last", ")", ")", "{", "gparent", ".", "setChild", "(", "dir2", ",", "doubleRotate", "(", "parent", ",", "last", ")", ")", "\n", "}", "else", "if", "isRed", "(", "sibling", ".", "Child", "(", "!", "last", ")", ")", "{", "gparent", ".", "setChild", "(", "dir2", ",", "singleRotate", "(", "parent", ",", "last", ")", ")", "\n", "}", "\n\n", "gpc", ":=", "gparent", ".", "Child", "(", "dir2", ")", "\n", "gpc", ".", "red", "=", "true", "\n", "node", ".", "red", "=", "true", "\n", "gpc", ".", "left", ".", "red", ",", "gpc", ".", "right", ".", "red", "=", "false", ",", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// get rid of node if we've found one", "if", "found", "!=", "nil", "{", "found", ".", "key", "=", "node", ".", "key", "\n", "found", ".", "value", "=", "node", ".", "value", "\n", "parent", ".", "setChild", "(", "parent", ".", "right", "==", "node", ",", "node", ".", "Child", "(", "node", ".", "left", "==", "nil", ")", ")", "\n", "t", ".", "size", "--", "\n", "}", "\n\n", "t", ".", "root", "=", "head", ".", "right", "\n", "if", "t", ".", "root", "!=", "nil", "{", "t", ".", "root", ".", "red", "=", "false", "\n", "}", "\n\n", "return", "found", "!=", "nil", "\n", "}" ]
// Delete removes the entry for key from the redBlackTree. Returns true on // succesful deletion, false if the key is not in tree
[ "Delete", "removes", "the", "entry", "for", "key", "from", "the", "redBlackTree", ".", "Returns", "true", "on", "succesful", "deletion", "false", "if", "the", "key", "is", "not", "in", "tree" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L170-L248
143,139
uber/ringpop-go
hashring/rbtree.go
traverseWhile
func (n *redBlackNode) traverseWhile(condition func(*redBlackNode) bool) bool { if n == nil { // the end of the tree does not signal the end of walking, but we can't // walk this node (nil) nor left or right anymore return true } // walk left first if !n.left.traverseWhile(condition) { // stop if walker indicated to break return false } // now visit this node if !condition(n) { // stop if walker indicated to break return false } // lastly visit right if !n.right.traverseWhile(condition) { // stop if walker indicated to break return false } // signal that we reached the end and walking should continue till we hit // end of tree return true }
go
func (n *redBlackNode) traverseWhile(condition func(*redBlackNode) bool) bool { if n == nil { // the end of the tree does not signal the end of walking, but we can't // walk this node (nil) nor left or right anymore return true } // walk left first if !n.left.traverseWhile(condition) { // stop if walker indicated to break return false } // now visit this node if !condition(n) { // stop if walker indicated to break return false } // lastly visit right if !n.right.traverseWhile(condition) { // stop if walker indicated to break return false } // signal that we reached the end and walking should continue till we hit // end of tree return true }
[ "func", "(", "n", "*", "redBlackNode", ")", "traverseWhile", "(", "condition", "func", "(", "*", "redBlackNode", ")", "bool", ")", "bool", "{", "if", "n", "==", "nil", "{", "// the end of the tree does not signal the end of walking, but we can't", "// walk this node (nil) nor left or right anymore", "return", "true", "\n", "}", "\n\n", "// walk left first", "if", "!", "n", ".", "left", ".", "traverseWhile", "(", "condition", ")", "{", "// stop if walker indicated to break", "return", "false", "\n", "}", "\n", "// now visit this node", "if", "!", "condition", "(", "n", ")", "{", "// stop if walker indicated to break", "return", "false", "\n", "}", "\n", "// lastly visit right", "if", "!", "n", ".", "right", ".", "traverseWhile", "(", "condition", ")", "{", "// stop if walker indicated to break", "return", "false", "\n", "}", "\n\n", "// signal that we reached the end and walking should continue till we hit", "// end of tree", "return", "true", "\n", "}" ]
// traverseWhile traverses the nodes in the tree in-order invoking the `condition`-function argument for each node. // If the condition-function returns `false` traversal is stopped and no more nodes will be // visited. Returns `true` if all nodes are visited; `false` if not.
[ "traverseWhile", "traverses", "the", "nodes", "in", "the", "tree", "in", "-", "order", "invoking", "the", "condition", "-", "function", "argument", "for", "each", "node", ".", "If", "the", "condition", "-", "function", "returns", "false", "traversal", "is", "stopped", "and", "no", "more", "nodes", "will", "be", "visited", ".", "Returns", "true", "if", "all", "nodes", "are", "visited", ";", "false", "if", "not", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L267-L293
143,140
uber/ringpop-go
hashring/rbtree.go
Search
func (t *redBlackTree) Search(key keytype) (valuetype, bool) { if t.root == nil { return nil, false } return t.root.search(key) }
go
func (t *redBlackTree) Search(key keytype) (valuetype, bool) { if t.root == nil { return nil, false } return t.root.search(key) }
[ "func", "(", "t", "*", "redBlackTree", ")", "Search", "(", "key", "keytype", ")", "(", "valuetype", ",", "bool", ")", "{", "if", "t", ".", "root", "==", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "return", "t", ".", "root", ".", "search", "(", "key", ")", "\n", "}" ]
// Search searches for the entry for key in the redBlackTree, returns the value // and true if found or nil and false if there is no entry for key in the tree.
[ "Search", "searches", "for", "the", "entry", "for", "key", "in", "the", "redBlackTree", "returns", "the", "value", "and", "true", "if", "found", "or", "nil", "and", "false", "if", "there", "is", "no", "entry", "for", "key", "in", "the", "tree", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L297-L302
143,141
uber/ringpop-go
hashring/rbtree.go
LookupNUniqueAt
func (t *redBlackTree) LookupNUniqueAt(n int, key keytype, result map[valuetype]struct{}) { findNUniqueAbove(t.root, n, key, result, nil) }
go
func (t *redBlackTree) LookupNUniqueAt(n int, key keytype, result map[valuetype]struct{}) { findNUniqueAbove(t.root, n, key, result, nil) }
[ "func", "(", "t", "*", "redBlackTree", ")", "LookupNUniqueAt", "(", "n", "int", ",", "key", "keytype", ",", "result", "map", "[", "valuetype", "]", "struct", "{", "}", ")", "{", "findNUniqueAbove", "(", "t", ".", "root", ",", "n", ",", "key", ",", "result", ",", "nil", ")", "\n", "}" ]
// LookupNUniqueAt iterates through the tree from the last node that is smaller // than key or equal, and returns the next n unique values. This function is not // guaranteed to return n values, less might be returned. Because this function // relies on writing the unique values to a golang map type, order cannot be // inferred. DEPRECATED, but maintained for backwards compatibility.
[ "LookupNUniqueAt", "iterates", "through", "the", "tree", "from", "the", "last", "node", "that", "is", "smaller", "than", "key", "or", "equal", "and", "returns", "the", "next", "n", "unique", "values", ".", "This", "function", "is", "not", "guaranteed", "to", "return", "n", "values", "less", "might", "be", "returned", ".", "Because", "this", "function", "relies", "on", "writing", "the", "unique", "values", "to", "a", "golang", "map", "type", "order", "cannot", "be", "inferred", ".", "DEPRECATED", "but", "maintained", "for", "backwards", "compatibility", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L309-L311
143,142
uber/ringpop-go
hashring/rbtree.go
LookupOrderedNUniqueAt
func (t *redBlackTree) LookupOrderedNUniqueAt(n int, key keytype, result map[valuetype]struct{}, orderedResult *[]valuetype) { findNUniqueAbove(t.root, n, key, result, orderedResult) }
go
func (t *redBlackTree) LookupOrderedNUniqueAt(n int, key keytype, result map[valuetype]struct{}, orderedResult *[]valuetype) { findNUniqueAbove(t.root, n, key, result, orderedResult) }
[ "func", "(", "t", "*", "redBlackTree", ")", "LookupOrderedNUniqueAt", "(", "n", "int", ",", "key", "keytype", ",", "result", "map", "[", "valuetype", "]", "struct", "{", "}", ",", "orderedResult", "*", "[", "]", "valuetype", ")", "{", "findNUniqueAbove", "(", "t", ".", "root", ",", "n", ",", "key", ",", "result", ",", "orderedResult", ")", "\n", "}" ]
// LookupOrderedNUniqueAt iterates through the tree from the last node that is // smaller than key or equal, and returns the next n unique values. This function // is not guaranteed to return n values, less might be returned. This method // replaces LookupNUniqueAt since it uses a slice to guarantee order.
[ "LookupOrderedNUniqueAt", "iterates", "through", "the", "tree", "from", "the", "last", "node", "that", "is", "smaller", "than", "key", "or", "equal", "and", "returns", "the", "next", "n", "unique", "values", ".", "This", "function", "is", "not", "guaranteed", "to", "return", "n", "values", "less", "might", "be", "returned", ".", "This", "method", "replaces", "LookupNUniqueAt", "since", "it", "uses", "a", "slice", "to", "guarantee", "order", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L317-L319
143,143
uber/ringpop-go
hashring/rbtree.go
findNUniqueAbove
func findNUniqueAbove(node *redBlackNode, n int, key keytype, result map[valuetype]struct{}, orderedResult *[]valuetype) { if len(result) >= n || node == nil { return } // skip left branch when all its keys are smaller than key cmp := node.key.Compare(key) if cmp >= 0 { findNUniqueAbove(node.left, n, key, result, orderedResult) } // Make sure to stop when we have n unique values if len(result) >= n { return } if cmp >= 0 { if _, ok := result[node.value]; !ok && orderedResult != nil { *orderedResult = append(*orderedResult, node.value) } result[node.value] = struct{}{} } findNUniqueAbove(node.right, n, key, result, orderedResult) }
go
func findNUniqueAbove(node *redBlackNode, n int, key keytype, result map[valuetype]struct{}, orderedResult *[]valuetype) { if len(result) >= n || node == nil { return } // skip left branch when all its keys are smaller than key cmp := node.key.Compare(key) if cmp >= 0 { findNUniqueAbove(node.left, n, key, result, orderedResult) } // Make sure to stop when we have n unique values if len(result) >= n { return } if cmp >= 0 { if _, ok := result[node.value]; !ok && orderedResult != nil { *orderedResult = append(*orderedResult, node.value) } result[node.value] = struct{}{} } findNUniqueAbove(node.right, n, key, result, orderedResult) }
[ "func", "findNUniqueAbove", "(", "node", "*", "redBlackNode", ",", "n", "int", ",", "key", "keytype", ",", "result", "map", "[", "valuetype", "]", "struct", "{", "}", ",", "orderedResult", "*", "[", "]", "valuetype", ")", "{", "if", "len", "(", "result", ")", ">=", "n", "||", "node", "==", "nil", "{", "return", "\n", "}", "\n\n", "// skip left branch when all its keys are smaller than key", "cmp", ":=", "node", ".", "key", ".", "Compare", "(", "key", ")", "\n", "if", "cmp", ">=", "0", "{", "findNUniqueAbove", "(", "node", ".", "left", ",", "n", ",", "key", ",", "result", ",", "orderedResult", ")", "\n", "}", "\n\n", "// Make sure to stop when we have n unique values", "if", "len", "(", "result", ")", ">=", "n", "{", "return", "\n", "}", "\n\n", "if", "cmp", ">=", "0", "{", "if", "_", ",", "ok", ":=", "result", "[", "node", ".", "value", "]", ";", "!", "ok", "&&", "orderedResult", "!=", "nil", "{", "*", "orderedResult", "=", "append", "(", "*", "orderedResult", ",", "node", ".", "value", ")", "\n", "}", "\n", "result", "[", "node", ".", "value", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "findNUniqueAbove", "(", "node", ".", "right", ",", "n", ",", "key", ",", "result", ",", "orderedResult", ")", "\n", "}" ]
// findNUniqueAbove is a recursive search that finds n unique values with a key // bigger or equal than key
[ "findNUniqueAbove", "is", "a", "recursive", "search", "that", "finds", "n", "unique", "values", "with", "a", "key", "bigger", "or", "equal", "than", "key" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/rbtree.go#L323-L347
143,144
uber/ringpop-go
examples/keyvalue/gen-go/keyvalue/ringpop-keyvalue.go
Get
func (a *RingpopKeyValueServiceAdapter) Get(ctx thrift.Context, key string) (r string, err error) { // check if the function should be called locally if a.config.Get == nil || forward.DeleteForwardedHeader(ctx) { return a.impl.Get(ctx, key) } // find the key to shard on ringpopKey, err := a.config.Get.Key(ctx, key) if err != nil { return r, fmt.Errorf("could not get key: %q", err) } clientInterface, isRemote, err := a.router.GetClient(ringpopKey) if err != nil { return r, err } client := clientInterface.(TChanKeyValueService) if isRemote { ctx = forward.SetForwardedHeader(ctx, []string{ringpopKey}) } return client.Get(ctx, key) }
go
func (a *RingpopKeyValueServiceAdapter) Get(ctx thrift.Context, key string) (r string, err error) { // check if the function should be called locally if a.config.Get == nil || forward.DeleteForwardedHeader(ctx) { return a.impl.Get(ctx, key) } // find the key to shard on ringpopKey, err := a.config.Get.Key(ctx, key) if err != nil { return r, fmt.Errorf("could not get key: %q", err) } clientInterface, isRemote, err := a.router.GetClient(ringpopKey) if err != nil { return r, err } client := clientInterface.(TChanKeyValueService) if isRemote { ctx = forward.SetForwardedHeader(ctx, []string{ringpopKey}) } return client.Get(ctx, key) }
[ "func", "(", "a", "*", "RingpopKeyValueServiceAdapter", ")", "Get", "(", "ctx", "thrift", ".", "Context", ",", "key", "string", ")", "(", "r", "string", ",", "err", "error", ")", "{", "// check if the function should be called locally", "if", "a", ".", "config", ".", "Get", "==", "nil", "||", "forward", ".", "DeleteForwardedHeader", "(", "ctx", ")", "{", "return", "a", ".", "impl", ".", "Get", "(", "ctx", ",", "key", ")", "\n", "}", "\n\n", "// find the key to shard on", "ringpopKey", ",", "err", ":=", "a", ".", "config", ".", "Get", ".", "Key", "(", "ctx", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "clientInterface", ",", "isRemote", ",", "err", ":=", "a", ".", "router", ".", "GetClient", "(", "ringpopKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n\n", "client", ":=", "clientInterface", ".", "(", "TChanKeyValueService", ")", "\n", "if", "isRemote", "{", "ctx", "=", "forward", ".", "SetForwardedHeader", "(", "ctx", ",", "[", "]", "string", "{", "ringpopKey", "}", ")", "\n", "}", "\n", "return", "client", ".", "Get", "(", "ctx", ",", "key", ")", "\n", "}" ]
// Get satisfies the TChanKeyValueService interface. This function uses the configuration for Get to determine the host to execute the call on. When it decides the call needs to be executed in the current process it will forward the invocation to its local implementation.
[ "Get", "satisfies", "the", "TChanKeyValueService", "interface", ".", "This", "function", "uses", "the", "configuration", "for", "Get", "to", "determine", "the", "host", "to", "execute", "the", "call", "on", ".", "When", "it", "decides", "the", "call", "needs", "to", "be", "executed", "in", "the", "current", "process", "it", "will", "forward", "the", "invocation", "to", "its", "local", "implementation", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/examples/keyvalue/gen-go/keyvalue/ringpop-keyvalue.go#L124-L146
143,145
uber/ringpop-go
hashring/hashring.go
New
func New(hashfunc func([]byte) uint32, replicaPoints int) *HashRing { r := &HashRing{ replicaPoints: replicaPoints, hashfunc: func(str string) int { return int(hashfunc([]byte(str))) }, logger: logging.Logger("ring"), checksummers: map[string]Checksummer{ "replica": &replicaPointChecksummer{}, }, } r.serverSet = make(map[string]struct{}) r.tree = &redBlackTree{} return r }
go
func New(hashfunc func([]byte) uint32, replicaPoints int) *HashRing { r := &HashRing{ replicaPoints: replicaPoints, hashfunc: func(str string) int { return int(hashfunc([]byte(str))) }, logger: logging.Logger("ring"), checksummers: map[string]Checksummer{ "replica": &replicaPointChecksummer{}, }, } r.serverSet = make(map[string]struct{}) r.tree = &redBlackTree{} return r }
[ "func", "New", "(", "hashfunc", "func", "(", "[", "]", "byte", ")", "uint32", ",", "replicaPoints", "int", ")", "*", "HashRing", "{", "r", ":=", "&", "HashRing", "{", "replicaPoints", ":", "replicaPoints", ",", "hashfunc", ":", "func", "(", "str", "string", ")", "int", "{", "return", "int", "(", "hashfunc", "(", "[", "]", "byte", "(", "str", ")", ")", ")", "\n", "}", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ",", "checksummers", ":", "map", "[", "string", "]", "Checksummer", "{", "\"", "\"", ":", "&", "replicaPointChecksummer", "{", "}", ",", "}", ",", "}", "\n\n", "r", ".", "serverSet", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "r", ".", "tree", "=", "&", "redBlackTree", "{", "}", "\n", "return", "r", "\n", "}" ]
// New instantiates and returns a new HashRing.
[ "New", "instantiates", "and", "returns", "a", "new", "HashRing", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L106-L122
143,146
uber/ringpop-go
hashring/hashring.go
Checksum
func (r *HashRing) Checksum() (checksum uint32) { r.RLock() checksum = r.legacyChecksum r.RUnlock() return }
go
func (r *HashRing) Checksum() (checksum uint32) { r.RLock() checksum = r.legacyChecksum r.RUnlock() return }
[ "func", "(", "r", "*", "HashRing", ")", "Checksum", "(", ")", "(", "checksum", "uint32", ")", "{", "r", ".", "RLock", "(", ")", "\n", "checksum", "=", "r", ".", "legacyChecksum", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}" ]
// Checksum returns the checksum of all stored servers in the HashRing // Use this value to find out if the HashRing is mutated.
[ "Checksum", "returns", "the", "checksum", "of", "all", "stored", "servers", "in", "the", "HashRing", "Use", "this", "value", "to", "find", "out", "if", "the", "HashRing", "is", "mutated", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L126-L131
143,147
uber/ringpop-go
hashring/hashring.go
Checksums
func (r *HashRing) Checksums() (checksums map[string]uint32) { r.RLock() // even though the map is immutable the pointer to it is not so it requires // a readlock checksums = r.checksums r.RUnlock() return }
go
func (r *HashRing) Checksums() (checksums map[string]uint32) { r.RLock() // even though the map is immutable the pointer to it is not so it requires // a readlock checksums = r.checksums r.RUnlock() return }
[ "func", "(", "r", "*", "HashRing", ")", "Checksums", "(", ")", "(", "checksums", "map", "[", "string", "]", "uint32", ")", "{", "r", ".", "RLock", "(", ")", "\n", "// even though the map is immutable the pointer to it is not so it requires", "// a readlock", "checksums", "=", "r", ".", "checksums", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}" ]
// Checksums returns a map of checksums named by the algorithm used to compute // the checksum.
[ "Checksums", "returns", "a", "map", "of", "checksums", "named", "by", "the", "algorithm", "used", "to", "compute", "the", "checksum", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L135-L142
143,148
uber/ringpop-go
hashring/hashring.go
computeChecksumsNoLock
func (r *HashRing) computeChecksumsNoLock() { oldChecksums := r.checksums r.checksums = make(map[string]uint32) changed := false // calculate all configured checksums for name, checksummer := range r.checksummers { oldChecksum := oldChecksums[name] newChecksum := checksummer.Checksum(r) r.checksums[name] = newChecksum if oldChecksum != newChecksum { changed = true } } // calculate the legacy identity only based checksum legacyChecksummer := identityChecksummer{} oldChecksum := r.legacyChecksum newChecksum := legacyChecksummer.Checksum(r) r.legacyChecksum = newChecksum if oldChecksum != newChecksum { changed = true } if changed { r.logger.WithFields(bark.Fields{ "checksum": r.legacyChecksum, "oldChecksum": oldChecksum, "checksums": r.checksums, }).Debug("ringpop ring computed new checksum") } r.EmitEvent(events.RingChecksumEvent{ OldChecksum: oldChecksum, NewChecksum: r.legacyChecksum, OldChecksums: oldChecksums, NewChecksums: r.checksums, }) }
go
func (r *HashRing) computeChecksumsNoLock() { oldChecksums := r.checksums r.checksums = make(map[string]uint32) changed := false // calculate all configured checksums for name, checksummer := range r.checksummers { oldChecksum := oldChecksums[name] newChecksum := checksummer.Checksum(r) r.checksums[name] = newChecksum if oldChecksum != newChecksum { changed = true } } // calculate the legacy identity only based checksum legacyChecksummer := identityChecksummer{} oldChecksum := r.legacyChecksum newChecksum := legacyChecksummer.Checksum(r) r.legacyChecksum = newChecksum if oldChecksum != newChecksum { changed = true } if changed { r.logger.WithFields(bark.Fields{ "checksum": r.legacyChecksum, "oldChecksum": oldChecksum, "checksums": r.checksums, }).Debug("ringpop ring computed new checksum") } r.EmitEvent(events.RingChecksumEvent{ OldChecksum: oldChecksum, NewChecksum: r.legacyChecksum, OldChecksums: oldChecksums, NewChecksums: r.checksums, }) }
[ "func", "(", "r", "*", "HashRing", ")", "computeChecksumsNoLock", "(", ")", "{", "oldChecksums", ":=", "r", ".", "checksums", "\n\n", "r", ".", "checksums", "=", "make", "(", "map", "[", "string", "]", "uint32", ")", "\n", "changed", ":=", "false", "\n", "// calculate all configured checksums", "for", "name", ",", "checksummer", ":=", "range", "r", ".", "checksummers", "{", "oldChecksum", ":=", "oldChecksums", "[", "name", "]", "\n", "newChecksum", ":=", "checksummer", ".", "Checksum", "(", "r", ")", "\n", "r", ".", "checksums", "[", "name", "]", "=", "newChecksum", "\n\n", "if", "oldChecksum", "!=", "newChecksum", "{", "changed", "=", "true", "\n", "}", "\n", "}", "\n\n", "// calculate the legacy identity only based checksum", "legacyChecksummer", ":=", "identityChecksummer", "{", "}", "\n", "oldChecksum", ":=", "r", ".", "legacyChecksum", "\n", "newChecksum", ":=", "legacyChecksummer", ".", "Checksum", "(", "r", ")", "\n", "r", ".", "legacyChecksum", "=", "newChecksum", "\n\n", "if", "oldChecksum", "!=", "newChecksum", "{", "changed", "=", "true", "\n", "}", "\n\n", "if", "changed", "{", "r", ".", "logger", ".", "WithFields", "(", "bark", ".", "Fields", "{", "\"", "\"", ":", "r", ".", "legacyChecksum", ",", "\"", "\"", ":", "oldChecksum", ",", "\"", "\"", ":", "r", ".", "checksums", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "r", ".", "EmitEvent", "(", "events", ".", "RingChecksumEvent", "{", "OldChecksum", ":", "oldChecksum", ",", "NewChecksum", ":", "r", ".", "legacyChecksum", ",", "OldChecksums", ":", "oldChecksums", ",", "NewChecksums", ":", "r", ".", "checksums", ",", "}", ")", "\n", "}" ]
// computeChecksumsNoLock re-computes all configured checksums for this hashring // and updates the in memory map with a new map containing the new checksums.
[ "computeChecksumsNoLock", "re", "-", "computes", "all", "configured", "checksums", "for", "this", "hashring", "and", "updates", "the", "in", "memory", "map", "with", "a", "new", "map", "containing", "the", "new", "checksums", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L146-L186
143,149
uber/ringpop-go
hashring/hashring.go
AddMembers
func (r *HashRing) AddMembers(members ...membership.Member) bool { r.Lock() changed := false var added []string for _, member := range members { if r.addMemberNoLock(member) { added = append(added, member.GetAddress()) changed = true } } if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersAdded: added, }) } r.Unlock() return changed }
go
func (r *HashRing) AddMembers(members ...membership.Member) bool { r.Lock() changed := false var added []string for _, member := range members { if r.addMemberNoLock(member) { added = append(added, member.GetAddress()) changed = true } } if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersAdded: added, }) } r.Unlock() return changed }
[ "func", "(", "r", "*", "HashRing", ")", "AddMembers", "(", "members", "...", "membership", ".", "Member", ")", "bool", "{", "r", ".", "Lock", "(", ")", "\n", "changed", ":=", "false", "\n", "var", "added", "[", "]", "string", "\n", "for", "_", ",", "member", ":=", "range", "members", "{", "if", "r", ".", "addMemberNoLock", "(", "member", ")", "{", "added", "=", "append", "(", "added", ",", "member", ".", "GetAddress", "(", ")", ")", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "changed", "{", "r", ".", "computeChecksumsNoLock", "(", ")", "\n", "r", ".", "EmitEvent", "(", "events", ".", "RingChangedEvent", "{", "ServersAdded", ":", "added", ",", "}", ")", "\n", "}", "\n", "r", ".", "Unlock", "(", ")", "\n", "return", "changed", "\n", "}" ]
// AddMembers adds multiple membership Member's and thus their replicas to the HashRing.
[ "AddMembers", "adds", "multiple", "membership", "Member", "s", "and", "thus", "their", "replicas", "to", "the", "HashRing", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L210-L229
143,150
uber/ringpop-go
hashring/hashring.go
RemoveMembers
func (r *HashRing) RemoveMembers(members ...membership.Member) bool { r.Lock() changed := false var removed []string for _, server := range members { if r.removeMemberNoLock(server) { removed = append(removed, server.GetAddress()) changed = true } } if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersRemoved: removed, }) } r.Unlock() return changed }
go
func (r *HashRing) RemoveMembers(members ...membership.Member) bool { r.Lock() changed := false var removed []string for _, server := range members { if r.removeMemberNoLock(server) { removed = append(removed, server.GetAddress()) changed = true } } if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersRemoved: removed, }) } r.Unlock() return changed }
[ "func", "(", "r", "*", "HashRing", ")", "RemoveMembers", "(", "members", "...", "membership", ".", "Member", ")", "bool", "{", "r", ".", "Lock", "(", ")", "\n", "changed", ":=", "false", "\n", "var", "removed", "[", "]", "string", "\n", "for", "_", ",", "server", ":=", "range", "members", "{", "if", "r", ".", "removeMemberNoLock", "(", "server", ")", "{", "removed", "=", "append", "(", "removed", ",", "server", ".", "GetAddress", "(", ")", ")", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "changed", "{", "r", ".", "computeChecksumsNoLock", "(", ")", "\n", "r", ".", "EmitEvent", "(", "events", ".", "RingChangedEvent", "{", "ServersRemoved", ":", "removed", ",", "}", ")", "\n", "}", "\n", "r", ".", "Unlock", "(", ")", "\n", "return", "changed", "\n", "}" ]
// RemoveMembers removes multiple membership Member's and thus their replicas from the HashRing.
[ "RemoveMembers", "removes", "multiple", "membership", "Member", "s", "and", "thus", "their", "replicas", "from", "the", "HashRing", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L250-L269
143,151
uber/ringpop-go
hashring/hashring.go
ProcessMembershipChanges
func (r *HashRing) ProcessMembershipChanges(changes []membership.MemberChange) { r.Lock() changed := false var added, updated, removed []string for _, change := range changes { if change.Before == nil && change.After != nil { // new member if r.addMemberNoLock(change.After) { added = append(added, change.After.GetAddress()) changed = true } } else if change.Before != nil && change.After == nil { // remove member if r.removeMemberNoLock(change.Before) { removed = append(removed, change.Before.GetAddress()) changed = true } } else { if change.Before.Identity() != change.After.Identity() { // identity has changed, member needs to be removed and readded r.removeMemberNoLock(change.Before) r.addMemberNoLock(change.After) updated = append(updated, change.After.GetAddress()) changed = true } } } // recompute checksums on changes if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersAdded: added, ServersUpdated: updated, ServersRemoved: removed, }) } r.Unlock() }
go
func (r *HashRing) ProcessMembershipChanges(changes []membership.MemberChange) { r.Lock() changed := false var added, updated, removed []string for _, change := range changes { if change.Before == nil && change.After != nil { // new member if r.addMemberNoLock(change.After) { added = append(added, change.After.GetAddress()) changed = true } } else if change.Before != nil && change.After == nil { // remove member if r.removeMemberNoLock(change.Before) { removed = append(removed, change.Before.GetAddress()) changed = true } } else { if change.Before.Identity() != change.After.Identity() { // identity has changed, member needs to be removed and readded r.removeMemberNoLock(change.Before) r.addMemberNoLock(change.After) updated = append(updated, change.After.GetAddress()) changed = true } } } // recompute checksums on changes if changed { r.computeChecksumsNoLock() r.EmitEvent(events.RingChangedEvent{ ServersAdded: added, ServersUpdated: updated, ServersRemoved: removed, }) } r.Unlock() }
[ "func", "(", "r", "*", "HashRing", ")", "ProcessMembershipChanges", "(", "changes", "[", "]", "membership", ".", "MemberChange", ")", "{", "r", ".", "Lock", "(", ")", "\n", "changed", ":=", "false", "\n", "var", "added", ",", "updated", ",", "removed", "[", "]", "string", "\n", "for", "_", ",", "change", ":=", "range", "changes", "{", "if", "change", ".", "Before", "==", "nil", "&&", "change", ".", "After", "!=", "nil", "{", "// new member", "if", "r", ".", "addMemberNoLock", "(", "change", ".", "After", ")", "{", "added", "=", "append", "(", "added", ",", "change", ".", "After", ".", "GetAddress", "(", ")", ")", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "else", "if", "change", ".", "Before", "!=", "nil", "&&", "change", ".", "After", "==", "nil", "{", "// remove member", "if", "r", ".", "removeMemberNoLock", "(", "change", ".", "Before", ")", "{", "removed", "=", "append", "(", "removed", ",", "change", ".", "Before", ".", "GetAddress", "(", ")", ")", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "else", "{", "if", "change", ".", "Before", ".", "Identity", "(", ")", "!=", "change", ".", "After", ".", "Identity", "(", ")", "{", "// identity has changed, member needs to be removed and readded", "r", ".", "removeMemberNoLock", "(", "change", ".", "Before", ")", "\n", "r", ".", "addMemberNoLock", "(", "change", ".", "After", ")", "\n", "updated", "=", "append", "(", "updated", ",", "change", ".", "After", ".", "GetAddress", "(", ")", ")", "\n", "changed", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// recompute checksums on changes", "if", "changed", "{", "r", ".", "computeChecksumsNoLock", "(", ")", "\n", "r", ".", "EmitEvent", "(", "events", ".", "RingChangedEvent", "{", "ServersAdded", ":", "added", ",", "ServersUpdated", ":", "updated", ",", "ServersRemoved", ":", "removed", ",", "}", ")", "\n", "}", "\n\n", "r", ".", "Unlock", "(", ")", "\n", "}" ]
// ProcessMembershipChanges takes a slice of membership.MemberChange's and // applies them to the hashring by adding and removing members accordingly to // the changes passed in.
[ "ProcessMembershipChanges", "takes", "a", "slice", "of", "membership", ".", "MemberChange", "s", "and", "applies", "them", "to", "the", "hashring", "by", "adding", "and", "removing", "members", "accordingly", "to", "the", "changes", "passed", "in", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L290-L329
143,152
uber/ringpop-go
hashring/hashring.go
HasServer
func (r *HashRing) HasServer(server string) bool { r.RLock() _, ok := r.serverSet[server] r.RUnlock() return ok }
go
func (r *HashRing) HasServer(server string) bool { r.RLock() _, ok := r.serverSet[server] r.RUnlock() return ok }
[ "func", "(", "r", "*", "HashRing", ")", "HasServer", "(", "server", "string", ")", "bool", "{", "r", ".", "RLock", "(", ")", "\n", "_", ",", "ok", ":=", "r", ".", "serverSet", "[", "server", "]", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "ok", "\n", "}" ]
// HasServer returns whether the HashRing contains the given server.
[ "HasServer", "returns", "whether", "the", "HashRing", "contains", "the", "given", "server", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L332-L337
143,153
uber/ringpop-go
hashring/hashring.go
Servers
func (r *HashRing) Servers() []string { r.RLock() servers := r.copyServersNoLock() r.RUnlock() return servers }
go
func (r *HashRing) Servers() []string { r.RLock() servers := r.copyServersNoLock() r.RUnlock() return servers }
[ "func", "(", "r", "*", "HashRing", ")", "Servers", "(", ")", "[", "]", "string", "{", "r", ".", "RLock", "(", ")", "\n", "servers", ":=", "r", ".", "copyServersNoLock", "(", ")", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "servers", "\n", "}" ]
// Servers returns all servers contained in the HashRing.
[ "Servers", "returns", "all", "servers", "contained", "in", "the", "HashRing", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L340-L345
143,154
uber/ringpop-go
hashring/hashring.go
ServerCount
func (r *HashRing) ServerCount() int { r.RLock() count := len(r.serverSet) r.RUnlock() return count }
go
func (r *HashRing) ServerCount() int { r.RLock() count := len(r.serverSet) r.RUnlock() return count }
[ "func", "(", "r", "*", "HashRing", ")", "ServerCount", "(", ")", "int", "{", "r", ".", "RLock", "(", ")", "\n", "count", ":=", "len", "(", "r", ".", "serverSet", ")", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "count", "\n", "}" ]
// ServerCount returns the number of servers contained in the HashRing.
[ "ServerCount", "returns", "the", "number", "of", "servers", "contained", "in", "the", "HashRing", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L357-L362
143,155
uber/ringpop-go
hashring/hashring.go
Lookup
func (r *HashRing) Lookup(key string) (string, bool) { strs := r.LookupN(key, 1) if len(strs) == 0 { return "", false } return strs[0], true }
go
func (r *HashRing) Lookup(key string) (string, bool) { strs := r.LookupN(key, 1) if len(strs) == 0 { return "", false } return strs[0], true }
[ "func", "(", "r", "*", "HashRing", ")", "Lookup", "(", "key", "string", ")", "(", "string", ",", "bool", ")", "{", "strs", ":=", "r", ".", "LookupN", "(", "key", ",", "1", ")", "\n", "if", "len", "(", "strs", ")", "==", "0", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "return", "strs", "[", "0", "]", ",", "true", "\n", "}" ]
// Lookup returns the owner of the given key and whether the HashRing contains // the key at all.
[ "Lookup", "returns", "the", "owner", "of", "the", "given", "key", "and", "whether", "the", "HashRing", "contains", "the", "key", "at", "all", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L366-L372
143,156
uber/ringpop-go
hashring/hashring.go
LookupN
func (r *HashRing) LookupN(key string, n int) []string { r.RLock() servers := r.lookupNNoLock(key, n) r.RUnlock() return servers }
go
func (r *HashRing) LookupN(key string, n int) []string { r.RLock() servers := r.lookupNNoLock(key, n) r.RUnlock() return servers }
[ "func", "(", "r", "*", "HashRing", ")", "LookupN", "(", "key", "string", ",", "n", "int", ")", "[", "]", "string", "{", "r", ".", "RLock", "(", ")", "\n", "servers", ":=", "r", ".", "lookupNNoLock", "(", "key", ",", "n", ")", "\n", "r", ".", "RUnlock", "(", ")", "\n", "return", "servers", "\n", "}" ]
// LookupN returns the N servers that own the given key. Duplicates in the form // of virtual nodes are skipped to maintain a list of unique servers. If there // are less servers than N, we simply return all existing servers.
[ "LookupN", "returns", "the", "N", "servers", "that", "own", "the", "given", "key", ".", "Duplicates", "in", "the", "form", "of", "virtual", "nodes", "are", "skipped", "to", "maintain", "a", "list", "of", "unique", "servers", ".", "If", "there", "are", "less", "servers", "than", "N", "we", "simply", "return", "all", "existing", "servers", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/hashring/hashring.go#L377-L382
143,157
uber/ringpop-go
options.go
applyOptions
func applyOptions(r *Ringpop, opts []Option) error { for _, option := range opts { err := option(r) if err != nil { return err } } return nil }
go
func applyOptions(r *Ringpop, opts []Option) error { for _, option := range opts { err := option(r) if err != nil { return err } } return nil }
[ "func", "applyOptions", "(", "r", "*", "Ringpop", ",", "opts", "[", "]", "Option", ")", "error", "{", "for", "_", ",", "option", ":=", "range", "opts", "{", "err", ":=", "option", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// applyOptions applies runtime configuration options to the specified Ringpop // instance.
[ "applyOptions", "applies", "runtime", "configuration", "options", "to", "the", "specified", "Ringpop", "instance", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L83-L91
143,158
uber/ringpop-go
options.go
checkOptions
func checkOptions(rp *Ringpop) []error { errs := []error{} if rp.channel == nil { errs = append(errs, errors.New("channel is required")) } if rp.addressResolver == nil { errs = append(errs, errors.New("address resolver is nil")) } return errs }
go
func checkOptions(rp *Ringpop) []error { errs := []error{} if rp.channel == nil { errs = append(errs, errors.New("channel is required")) } if rp.addressResolver == nil { errs = append(errs, errors.New("address resolver is nil")) } return errs }
[ "func", "checkOptions", "(", "rp", "*", "Ringpop", ")", "[", "]", "error", "{", "errs", ":=", "[", "]", "error", "{", "}", "\n", "if", "rp", ".", "channel", "==", "nil", "{", "errs", "=", "append", "(", "errs", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "rp", ".", "addressResolver", "==", "nil", "{", "errs", "=", "append", "(", "errs", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// checkOptions checks that the Ringpop instance has been properly configured // with all the required options.
[ "checkOptions", "checks", "that", "the", "Ringpop", "instance", "has", "been", "properly", "configured", "with", "all", "the", "required", "options", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L95-L104
143,159
uber/ringpop-go
options.go
Clock
func Clock(c clock.Clock) Option { return func(r *Ringpop) error { if c == nil { return errors.New("clock is required") } r.clock = c return nil } }
go
func Clock(c clock.Clock) Option { return func(r *Ringpop) error { if c == nil { return errors.New("clock is required") } r.clock = c return nil } }
[ "func", "Clock", "(", "c", "clock", ".", "Clock", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "r", ".", "clock", "=", "c", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Runtime options // Clock is used to set the Clock mechanism. Testing harnesses will typically // replace this with a mocked clock.
[ "Runtime", "options", "Clock", "is", "used", "to", "set", "the", "Clock", "mechanism", ".", "Testing", "harnesses", "will", "typically", "replace", "this", "with", "a", "mocked", "clock", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L110-L118
143,160
uber/ringpop-go
options.go
Logger
func Logger(l log.Logger) Option { return func(r *Ringpop) error { logging.SetLogger(l) return nil } }
go
func Logger(l log.Logger) Option { return func(r *Ringpop) error { logging.SetLogger(l) return nil } }
[ "func", "Logger", "(", "l", "log", ".", "Logger", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "logging", ".", "SetLogger", "(", "l", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Logger is used to specify a bark-compatible logger that will be used for // all Ringpop logging. If a logger is not provided, one will be created // automatically.
[ "Logger", "is", "used", "to", "specify", "a", "bark", "-", "compatible", "logger", "that", "will", "be", "used", "for", "all", "Ringpop", "logging", ".", "If", "a", "logger", "is", "not", "provided", "one", "will", "be", "created", "automatically", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L160-L165
143,161
uber/ringpop-go
options.go
LogLevels
func LogLevels(levels map[string]logging.Level) Option { return func(r *Ringpop) error { return logging.SetLevels(levels) } }
go
func LogLevels(levels map[string]logging.Level) Option { return func(r *Ringpop) error { return logging.SetLevels(levels) } }
[ "func", "LogLevels", "(", "levels", "map", "[", "string", "]", "logging", ".", "Level", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "return", "logging", ".", "SetLevels", "(", "levels", ")", "\n", "}", "\n", "}" ]
// LogLevels is used to set the severity log level for all Ringpop named // loggers.
[ "LogLevels", "is", "used", "to", "set", "the", "severity", "log", "level", "for", "all", "Ringpop", "named", "loggers", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L169-L173
143,162
uber/ringpop-go
options.go
SuspectPeriod
func SuspectPeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Suspect = period return nil } }
go
func SuspectPeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Suspect = period return nil } }
[ "func", "SuspectPeriod", "(", "period", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "StateTimeouts", ".", "Suspect", "=", "period", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SuspectPeriod configures the period it takes ringpop to declare a node faulty // after ringpop has first detected the node to be unresponsive to a healthcheck. // When a node is declared faulty it is removed from the consistent hashring and // stops forwarding traffic to that node. All keys previously routed to that node // will then be routed to the new owner of the key
[ "SuspectPeriod", "configures", "the", "period", "it", "takes", "ringpop", "to", "declare", "a", "node", "faulty", "after", "ringpop", "has", "first", "detected", "the", "node", "to", "be", "unresponsive", "to", "a", "healthcheck", ".", "When", "a", "node", "is", "declared", "faulty", "it", "is", "removed", "from", "the", "consistent", "hashring", "and", "stops", "forwarding", "traffic", "to", "that", "node", ".", "All", "keys", "previously", "routed", "to", "that", "node", "will", "then", "be", "routed", "to", "the", "new", "owner", "of", "the", "key" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L283-L288
143,163
uber/ringpop-go
options.go
FaultyPeriod
func FaultyPeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Faulty = period return nil } }
go
func FaultyPeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Faulty = period return nil } }
[ "func", "FaultyPeriod", "(", "period", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "StateTimeouts", ".", "Faulty", "=", "period", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// FaultyPeriod configures the period Ringpop keeps a faulty node in its memberlist. // Even though the node will not receive any traffic it is still present in the // list in case it will come back online later. After this timeout ringpop will // remove the node from its membership list permanently. If a node happens to come // back after it has been removed from the membership Ringpop still allows it to // join and take its old position in the hashring. To remove the node from the // distributed membership it will mark it as a tombstone which can be removed from // every members membership list independently.
[ "FaultyPeriod", "configures", "the", "period", "Ringpop", "keeps", "a", "faulty", "node", "in", "its", "memberlist", ".", "Even", "though", "the", "node", "will", "not", "receive", "any", "traffic", "it", "is", "still", "present", "in", "the", "list", "in", "case", "it", "will", "come", "back", "online", "later", ".", "After", "this", "timeout", "ringpop", "will", "remove", "the", "node", "from", "its", "membership", "list", "permanently", ".", "If", "a", "node", "happens", "to", "come", "back", "after", "it", "has", "been", "removed", "from", "the", "membership", "Ringpop", "still", "allows", "it", "to", "join", "and", "take", "its", "old", "position", "in", "the", "hashring", ".", "To", "remove", "the", "node", "from", "the", "distributed", "membership", "it", "will", "mark", "it", "as", "a", "tombstone", "which", "can", "be", "removed", "from", "every", "members", "membership", "list", "independently", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L298-L303
143,164
uber/ringpop-go
options.go
TombstonePeriod
func TombstonePeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Tombstone = period return nil } }
go
func TombstonePeriod(period time.Duration) Option { return func(r *Ringpop) error { r.config.StateTimeouts.Tombstone = period return nil } }
[ "func", "TombstonePeriod", "(", "period", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "StateTimeouts", ".", "Tombstone", "=", "period", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// TombstonePeriod configures the period of the last time of the lifecycle in of // a node in the membership list. This period should give the gossip protocol the // time it needs to disseminate this change. If configured too short the node in // question might show up again in faulty state in the distributed memberlist of // Ringpop.
[ "TombstonePeriod", "configures", "the", "period", "of", "the", "last", "time", "of", "the", "lifecycle", "in", "of", "a", "node", "in", "the", "membership", "list", ".", "This", "period", "should", "give", "the", "gossip", "protocol", "the", "time", "it", "needs", "to", "disseminate", "this", "change", ".", "If", "configured", "too", "short", "the", "node", "in", "question", "might", "show", "up", "again", "in", "faulty", "state", "in", "the", "distributed", "memberlist", "of", "Ringpop", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L310-L315
143,165
uber/ringpop-go
options.go
LabelLimitCount
func LabelLimitCount(count int) Option { return func(r *Ringpop) error { r.config.LabelLimits.Count = count return nil } }
go
func LabelLimitCount(count int) Option { return func(r *Ringpop) error { r.config.LabelLimits.Count = count return nil } }
[ "func", "LabelLimitCount", "(", "count", "int", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "LabelLimits", ".", "Count", "=", "count", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LabelLimitCount limits the number of labels an application can set on this // node.
[ "LabelLimitCount", "limits", "the", "number", "of", "labels", "an", "application", "can", "set", "on", "this", "node", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L319-L324
143,166
uber/ringpop-go
options.go
LabelLimitKeySize
func LabelLimitKeySize(size int) Option { return func(r *Ringpop) error { r.config.LabelLimits.KeySize = size return nil } }
go
func LabelLimitKeySize(size int) Option { return func(r *Ringpop) error { r.config.LabelLimits.KeySize = size return nil } }
[ "func", "LabelLimitKeySize", "(", "size", "int", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "LabelLimits", ".", "KeySize", "=", "size", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LabelLimitKeySize limits the size that a key of a label can be.
[ "LabelLimitKeySize", "limits", "the", "size", "that", "a", "key", "of", "a", "label", "can", "be", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L327-L332
143,167
uber/ringpop-go
options.go
LabelLimitValueSize
func LabelLimitValueSize(size int) Option { return func(r *Ringpop) error { r.config.LabelLimits.ValueSize = size return nil } }
go
func LabelLimitValueSize(size int) Option { return func(r *Ringpop) error { r.config.LabelLimits.ValueSize = size return nil } }
[ "func", "LabelLimitValueSize", "(", "size", "int", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "LabelLimits", ".", "ValueSize", "=", "size", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// LabelLimitValueSize limits the size that a value of a label can be.
[ "LabelLimitValueSize", "limits", "the", "size", "that", "a", "value", "of", "a", "label", "can", "be", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L335-L340
143,168
uber/ringpop-go
options.go
RequiresAppInPing
func RequiresAppInPing(requiresAppInPing bool) Option { return func(r *Ringpop) error { r.config.RequiresAppInPing = requiresAppInPing return nil } }
go
func RequiresAppInPing(requiresAppInPing bool) Option { return func(r *Ringpop) error { r.config.RequiresAppInPing = requiresAppInPing return nil } }
[ "func", "RequiresAppInPing", "(", "requiresAppInPing", "bool", ")", "Option", "{", "return", "func", "(", "r", "*", "Ringpop", ")", "error", "{", "r", ".", "config", ".", "RequiresAppInPing", "=", "requiresAppInPing", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RequiresAppInPing configures if ringpop node should reject pings // that don't contain app name
[ "RequiresAppInPing", "configures", "if", "ringpop", "node", "should", "reject", "pings", "that", "don", "t", "contain", "app", "name" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L364-L369
143,169
uber/ringpop-go
options.go
defaultLogLevels
func defaultLogLevels(r *Ringpop) error { return LogLevels(map[string]logging.Level{ "damping": logging.Error, "dissemination": logging.Error, "gossip": logging.Error, "join": logging.Warn, "membership": logging.Error, "ring": logging.Error, "suspicion": logging.Error, })(r) }
go
func defaultLogLevels(r *Ringpop) error { return LogLevels(map[string]logging.Level{ "damping": logging.Error, "dissemination": logging.Error, "gossip": logging.Error, "join": logging.Warn, "membership": logging.Error, "ring": logging.Error, "suspicion": logging.Error, })(r) }
[ "func", "defaultLogLevels", "(", "r", "*", "Ringpop", ")", "error", "{", "return", "LogLevels", "(", "map", "[", "string", "]", "logging", ".", "Level", "{", "\"", "\"", ":", "logging", ".", "Error", ",", "\"", "\"", ":", "logging", ".", "Error", ",", "\"", "\"", ":", "logging", ".", "Error", ",", "\"", "\"", ":", "logging", ".", "Warn", ",", "\"", "\"", ":", "logging", ".", "Error", ",", "\"", "\"", ":", "logging", ".", "Error", ",", "\"", "\"", ":", "logging", ".", "Error", ",", "}", ")", "(", "r", ")", "\n", "}" ]
// defaultLogLevels is the default configuration for all Ringpop named loggers.
[ "defaultLogLevels", "is", "the", "default", "configuration", "for", "all", "Ringpop", "named", "loggers", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/options.go#L385-L395
143,170
uber/ringpop-go
discovery/jsonfile/lib.go
Hosts
func (p *HostList) Hosts() ([]string, error) { var hosts []string data, err := ioutil.ReadFile(p.filePath) if err != nil { return nil, err } err = json.Unmarshal(data, &hosts) if err != nil { return nil, err } return hosts, nil }
go
func (p *HostList) Hosts() ([]string, error) { var hosts []string data, err := ioutil.ReadFile(p.filePath) if err != nil { return nil, err } err = json.Unmarshal(data, &hosts) if err != nil { return nil, err } return hosts, nil }
[ "func", "(", "p", "*", "HostList", ")", "Hosts", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "hosts", "[", "]", "string", "\n\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "p", ".", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "hosts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "hosts", ",", "nil", "\n", "}" ]
// Hosts reads hosts from a JSON file.
[ "Hosts", "reads", "hosts", "from", "a", "JSON", "file", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/discovery/jsonfile/lib.go#L34-L48
143,171
uber/ringpop-go
swim/handlers.go
notImplementedHandler
func notImplementedHandler(ctx json.Context, req *emptyArg) (*emptyArg, error) { return nil, errors.New("handler not implemented") }
go
func notImplementedHandler(ctx json.Context, req *emptyArg) (*emptyArg, error) { return nil, errors.New("handler not implemented") }
[ "func", "notImplementedHandler", "(", "ctx", "json", ".", "Context", ",", "req", "*", "emptyArg", ")", "(", "*", "emptyArg", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// notImplementedHandler is a dummy handler that returns an error explaining // this method is not implemented.
[ "notImplementedHandler", "is", "a", "dummy", "handler", "that", "returns", "an", "error", "explaining", "this", "method", "is", "not", "implemented", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/handlers.go#L59-L61
143,172
uber/ringpop-go
swim/handlers.go
reapFaultyMembersHandler
func (n *Node) reapFaultyMembersHandler(ctx json.Context, req *emptyArg) (*Status, error) { members := n.memberlist.GetMembers() for _, member := range members { if member.Status == Faulty { // declare all faulty members as tombstone n.memberlist.MakeTombstone(member.Address, member.Incarnation) } } return &Status{Status: "ok"}, nil }
go
func (n *Node) reapFaultyMembersHandler(ctx json.Context, req *emptyArg) (*Status, error) { members := n.memberlist.GetMembers() for _, member := range members { if member.Status == Faulty { // declare all faulty members as tombstone n.memberlist.MakeTombstone(member.Address, member.Incarnation) } } return &Status{Status: "ok"}, nil }
[ "func", "(", "n", "*", "Node", ")", "reapFaultyMembersHandler", "(", "ctx", "json", ".", "Context", ",", "req", "*", "emptyArg", ")", "(", "*", "Status", ",", "error", ")", "{", "members", ":=", "n", ".", "memberlist", ".", "GetMembers", "(", ")", "\n", "for", "_", ",", "member", ":=", "range", "members", "{", "if", "member", ".", "Status", "==", "Faulty", "{", "// declare all faulty members as tombstone", "n", ".", "memberlist", ".", "MakeTombstone", "(", "member", ".", "Address", ",", "member", ".", "Incarnation", ")", "\n", "}", "\n", "}", "\n", "return", "&", "Status", "{", "Status", ":", "\"", "\"", "}", ",", "nil", "\n", "}" ]
// reapFaultyMembersHandler iterates through the local members of this nodes and // declares all the members marked as faulty as a tombstone. This will clean all // these members from the membership in the complete cluster due to the gossipy // nature of swim
[ "reapFaultyMembersHandler", "iterates", "through", "the", "local", "members", "of", "this", "nodes", "and", "declares", "all", "the", "members", "marked", "as", "faulty", "as", "a", "tombstone", ".", "This", "will", "clean", "all", "these", "members", "from", "the", "membership", "in", "the", "complete", "cluster", "due", "to", "the", "gossipy", "nature", "of", "swim" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/handlers.go#L154-L163
143,173
uber/ringpop-go
swim/handlers.go
errorHandler
func (n *Node) errorHandler(ctx context.Context, err error) { n.logger.WithField("error", err).Info("error occurred") }
go
func (n *Node) errorHandler(ctx context.Context, err error) { n.logger.WithField("error", err).Info("error occurred") }
[ "func", "(", "n", "*", "Node", ")", "errorHandler", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "{", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "err", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// errorHandler is called when one of the handlers returns an error.
[ "errorHandler", "is", "called", "when", "one", "of", "the", "handlers", "returns", "an", "error", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/handlers.go#L166-L168
143,174
uber/ringpop-go
logging/level.go
String
func (lvl Level) String() string { switch lvl { case Panic: return "panic" case Fatal: return "fatal" case Error: return "error" case Warn: return "warn" case Info: return "info" case Debug: return "debug" } return strconv.Itoa(int(lvl)) }
go
func (lvl Level) String() string { switch lvl { case Panic: return "panic" case Fatal: return "fatal" case Error: return "error" case Warn: return "warn" case Info: return "info" case Debug: return "debug" } return strconv.Itoa(int(lvl)) }
[ "func", "(", "lvl", "Level", ")", "String", "(", ")", "string", "{", "switch", "lvl", "{", "case", "Panic", ":", "return", "\"", "\"", "\n", "case", "Fatal", ":", "return", "\"", "\"", "\n", "case", "Error", ":", "return", "\"", "\"", "\n", "case", "Warn", ":", "return", "\"", "\"", "\n", "case", "Info", ":", "return", "\"", "\"", "\n", "case", "Debug", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "strconv", ".", "Itoa", "(", "int", "(", "lvl", ")", ")", "\n", "}" ]
// String converts a log level to its string representation.
[ "String", "converts", "a", "log", "level", "to", "its", "string", "representation", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/level.go#L52-L68
143,175
uber/ringpop-go
logging/level.go
Parse
func Parse(lvl string) (Level, error) { switch lvl { case "fatal": return Fatal, nil case "panic": return Panic, nil case "error": return Error, nil case "warn": return Warn, nil case "info": return Info, nil case "debug": return Debug, nil } level, err := strconv.Atoi(lvl) if level > maxLevel { err = fmt.Errorf("invalid level value: %s", lvl) } return Level(level), err }
go
func Parse(lvl string) (Level, error) { switch lvl { case "fatal": return Fatal, nil case "panic": return Panic, nil case "error": return Error, nil case "warn": return Warn, nil case "info": return Info, nil case "debug": return Debug, nil } level, err := strconv.Atoi(lvl) if level > maxLevel { err = fmt.Errorf("invalid level value: %s", lvl) } return Level(level), err }
[ "func", "Parse", "(", "lvl", "string", ")", "(", "Level", ",", "error", ")", "{", "switch", "lvl", "{", "case", "\"", "\"", ":", "return", "Fatal", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Panic", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Error", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Warn", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Info", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "Debug", ",", "nil", "\n", "}", "\n\n", "level", ",", "err", ":=", "strconv", ".", "Atoi", "(", "lvl", ")", "\n", "if", "level", ">", "maxLevel", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "lvl", ")", "\n", "}", "\n", "return", "Level", "(", "level", ")", ",", "err", "\n", "}" ]
// Parse converts a string to a log level.
[ "Parse", "converts", "a", "string", "to", "a", "log", "level", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/level.go#L71-L92
143,176
uber/ringpop-go
swim/join_sender.go
newJoinSender
func newJoinSender(node *Node, opts *joinOpts) (*joinSender, error) { if opts == nil { opts = &joinOpts{} } if node.discoverProvider == nil { return nil, errors.New("no discover provider") } // Resolve/retrieve bootstrap hosts from the provider specified in the // join options. bootstrapHosts, err := node.discoverProvider.Hosts() if err != nil { return nil, err } // Check we're in the bootstrap host list and add ourselves if we're not // there. If the host list is empty, this will create a single-node // cluster. if !util.StringInSlice(bootstrapHosts, node.Address()) { bootstrapHosts = append(bootstrapHosts, node.Address()) } js := &joinSender{ node: node, logger: logging.Logger("join").WithField("local", node.Address()), } // Parse bootstrap hosts into a map js.parseHosts(bootstrapHosts) js.potentialNodes = js.CollectPotentialNodes(nil) js.timeout = util.SelectDuration(opts.timeout, defaultJoinTimeout) js.maxJoinDuration = util.SelectDuration(opts.maxJoinDuration, defaultMaxJoinDuration) js.parallelismFactor = util.SelectInt(opts.parallelismFactor, defaultParallelismFactor) js.size = util.SelectInt(opts.size, defaultJoinSize) js.size = util.Min(js.size, len(js.potentialNodes)) js.delayer = opts.delayer if js.delayer == nil { // Create and use exponential delayer as the delay mechanism. Create it // with nil opts which uses default delayOpts. js.delayer, err = newExponentialDelayer(js.node.address, nil) if err != nil { return nil, err } } return js, nil }
go
func newJoinSender(node *Node, opts *joinOpts) (*joinSender, error) { if opts == nil { opts = &joinOpts{} } if node.discoverProvider == nil { return nil, errors.New("no discover provider") } // Resolve/retrieve bootstrap hosts from the provider specified in the // join options. bootstrapHosts, err := node.discoverProvider.Hosts() if err != nil { return nil, err } // Check we're in the bootstrap host list and add ourselves if we're not // there. If the host list is empty, this will create a single-node // cluster. if !util.StringInSlice(bootstrapHosts, node.Address()) { bootstrapHosts = append(bootstrapHosts, node.Address()) } js := &joinSender{ node: node, logger: logging.Logger("join").WithField("local", node.Address()), } // Parse bootstrap hosts into a map js.parseHosts(bootstrapHosts) js.potentialNodes = js.CollectPotentialNodes(nil) js.timeout = util.SelectDuration(opts.timeout, defaultJoinTimeout) js.maxJoinDuration = util.SelectDuration(opts.maxJoinDuration, defaultMaxJoinDuration) js.parallelismFactor = util.SelectInt(opts.parallelismFactor, defaultParallelismFactor) js.size = util.SelectInt(opts.size, defaultJoinSize) js.size = util.Min(js.size, len(js.potentialNodes)) js.delayer = opts.delayer if js.delayer == nil { // Create and use exponential delayer as the delay mechanism. Create it // with nil opts which uses default delayOpts. js.delayer, err = newExponentialDelayer(js.node.address, nil) if err != nil { return nil, err } } return js, nil }
[ "func", "newJoinSender", "(", "node", "*", "Node", ",", "opts", "*", "joinOpts", ")", "(", "*", "joinSender", ",", "error", ")", "{", "if", "opts", "==", "nil", "{", "opts", "=", "&", "joinOpts", "{", "}", "\n", "}", "\n\n", "if", "node", ".", "discoverProvider", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Resolve/retrieve bootstrap hosts from the provider specified in the", "// join options.", "bootstrapHosts", ",", "err", ":=", "node", ".", "discoverProvider", ".", "Hosts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check we're in the bootstrap host list and add ourselves if we're not", "// there. If the host list is empty, this will create a single-node", "// cluster.", "if", "!", "util", ".", "StringInSlice", "(", "bootstrapHosts", ",", "node", ".", "Address", "(", ")", ")", "{", "bootstrapHosts", "=", "append", "(", "bootstrapHosts", ",", "node", ".", "Address", "(", ")", ")", "\n", "}", "\n\n", "js", ":=", "&", "joinSender", "{", "node", ":", "node", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "node", ".", "Address", "(", ")", ")", ",", "}", "\n\n", "// Parse bootstrap hosts into a map", "js", ".", "parseHosts", "(", "bootstrapHosts", ")", "\n\n", "js", ".", "potentialNodes", "=", "js", ".", "CollectPotentialNodes", "(", "nil", ")", "\n\n", "js", ".", "timeout", "=", "util", ".", "SelectDuration", "(", "opts", ".", "timeout", ",", "defaultJoinTimeout", ")", "\n", "js", ".", "maxJoinDuration", "=", "util", ".", "SelectDuration", "(", "opts", ".", "maxJoinDuration", ",", "defaultMaxJoinDuration", ")", "\n", "js", ".", "parallelismFactor", "=", "util", ".", "SelectInt", "(", "opts", ".", "parallelismFactor", ",", "defaultParallelismFactor", ")", "\n", "js", ".", "size", "=", "util", ".", "SelectInt", "(", "opts", ".", "size", ",", "defaultJoinSize", ")", "\n", "js", ".", "size", "=", "util", ".", "Min", "(", "js", ".", "size", ",", "len", "(", "js", ".", "potentialNodes", ")", ")", "\n", "js", ".", "delayer", "=", "opts", ".", "delayer", "\n\n", "if", "js", ".", "delayer", "==", "nil", "{", "// Create and use exponential delayer as the delay mechanism. Create it", "// with nil opts which uses default delayOpts.", "js", ".", "delayer", ",", "err", "=", "newExponentialDelayer", "(", "js", ".", "node", ".", "address", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "js", ",", "nil", "\n", "}" ]
// newJoinSender returns a new JoinSender to join a cluster with
[ "newJoinSender", "returns", "a", "new", "JoinSender", "to", "join", "a", "cluster", "with" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L118-L168
143,177
uber/ringpop-go
swim/join_sender.go
parseHosts
func (j *joinSender) parseHosts(hostports []string) { // Parse bootstrap hosts into a map j.bootstrapHostsMap = util.HostPortsByHost(hostports) // Perform some sanity checks on the bootstrap hosts err := util.CheckLocalMissing(j.node.address, j.bootstrapHostsMap[util.CaptureHost(j.node.address)]) if err != nil { j.logger.Warn(err.Error()) } mismatched, err := util.CheckHostnameIPMismatch(j.node.address, j.bootstrapHostsMap) if err != nil { j.logger.WithField("mismatched", mismatched).Warn(err.Error()) } }
go
func (j *joinSender) parseHosts(hostports []string) { // Parse bootstrap hosts into a map j.bootstrapHostsMap = util.HostPortsByHost(hostports) // Perform some sanity checks on the bootstrap hosts err := util.CheckLocalMissing(j.node.address, j.bootstrapHostsMap[util.CaptureHost(j.node.address)]) if err != nil { j.logger.Warn(err.Error()) } mismatched, err := util.CheckHostnameIPMismatch(j.node.address, j.bootstrapHostsMap) if err != nil { j.logger.WithField("mismatched", mismatched).Warn(err.Error()) } }
[ "func", "(", "j", "*", "joinSender", ")", "parseHosts", "(", "hostports", "[", "]", "string", ")", "{", "// Parse bootstrap hosts into a map", "j", ".", "bootstrapHostsMap", "=", "util", ".", "HostPortsByHost", "(", "hostports", ")", "\n\n", "// Perform some sanity checks on the bootstrap hosts", "err", ":=", "util", ".", "CheckLocalMissing", "(", "j", ".", "node", ".", "address", ",", "j", ".", "bootstrapHostsMap", "[", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "]", ")", "\n", "if", "err", "!=", "nil", "{", "j", ".", "logger", ".", "Warn", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "mismatched", ",", "err", ":=", "util", ".", "CheckHostnameIPMismatch", "(", "j", ".", "node", ".", "address", ",", "j", ".", "bootstrapHostsMap", ")", "\n", "if", "err", "!=", "nil", "{", "j", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "mismatched", ")", ".", "Warn", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// parseHosts populates the bootstrap hosts map from the provided slice of // hostports.
[ "parseHosts", "populates", "the", "bootstrap", "hosts", "map", "from", "the", "provided", "slice", "of", "hostports", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L172-L186
143,178
uber/ringpop-go
swim/join_sender.go
CollectPotentialNodes
func (j *joinSender) CollectPotentialNodes(nodesJoined []string) []string { if nodesJoined == nil { nodesJoined = make([]string, 0) } var potentialNodes []string for _, hostports := range j.bootstrapHostsMap { for _, hostport := range hostports { if j.node.address != hostport && !util.StringInSlice(nodesJoined, hostport) { potentialNodes = append(potentialNodes, hostport) } } } return potentialNodes }
go
func (j *joinSender) CollectPotentialNodes(nodesJoined []string) []string { if nodesJoined == nil { nodesJoined = make([]string, 0) } var potentialNodes []string for _, hostports := range j.bootstrapHostsMap { for _, hostport := range hostports { if j.node.address != hostport && !util.StringInSlice(nodesJoined, hostport) { potentialNodes = append(potentialNodes, hostport) } } } return potentialNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectPotentialNodes", "(", "nodesJoined", "[", "]", "string", ")", "[", "]", "string", "{", "if", "nodesJoined", "==", "nil", "{", "nodesJoined", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "}", "\n\n", "var", "potentialNodes", "[", "]", "string", "\n\n", "for", "_", ",", "hostports", ":=", "range", "j", ".", "bootstrapHostsMap", "{", "for", "_", ",", "hostport", ":=", "range", "hostports", "{", "if", "j", ".", "node", ".", "address", "!=", "hostport", "&&", "!", "util", ".", "StringInSlice", "(", "nodesJoined", ",", "hostport", ")", "{", "potentialNodes", "=", "append", "(", "potentialNodes", ",", "hostport", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "potentialNodes", "\n", "}" ]
// potential nodes are nodes that can be joined that are not the local node
[ "potential", "nodes", "are", "nodes", "that", "can", "be", "joined", "that", "are", "not", "the", "local", "node" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L189-L205
143,179
uber/ringpop-go
swim/join_sender.go
CollectPreferredNodes
func (j *joinSender) CollectPreferredNodes() []string { var preferredNodes []string for host, hostports := range j.bootstrapHostsMap { if host != util.CaptureHost(j.node.address) { preferredNodes = append(preferredNodes, hostports...) } } return preferredNodes }
go
func (j *joinSender) CollectPreferredNodes() []string { var preferredNodes []string for host, hostports := range j.bootstrapHostsMap { if host != util.CaptureHost(j.node.address) { preferredNodes = append(preferredNodes, hostports...) } } return preferredNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectPreferredNodes", "(", ")", "[", "]", "string", "{", "var", "preferredNodes", "[", "]", "string", "\n\n", "for", "host", ",", "hostports", ":=", "range", "j", ".", "bootstrapHostsMap", "{", "if", "host", "!=", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "{", "preferredNodes", "=", "append", "(", "preferredNodes", ",", "hostports", "...", ")", "\n", "}", "\n", "}", "\n\n", "return", "preferredNodes", "\n", "}" ]
// preferred nodes are nodes that are not on the same host as the local node
[ "preferred", "nodes", "are", "nodes", "that", "are", "not", "on", "the", "same", "host", "as", "the", "local", "node" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L208-L218
143,180
uber/ringpop-go
swim/join_sender.go
CollectNonPreferredNodes
func (j *joinSender) CollectNonPreferredNodes() []string { if len(j.preferredNodes) == 0 { return j.potentialNodes } var nonPreferredNodes []string for _, host := range j.bootstrapHostsMap[util.CaptureHost(j.node.address)] { if host != j.node.address { nonPreferredNodes = append(nonPreferredNodes, host) } } return nonPreferredNodes }
go
func (j *joinSender) CollectNonPreferredNodes() []string { if len(j.preferredNodes) == 0 { return j.potentialNodes } var nonPreferredNodes []string for _, host := range j.bootstrapHostsMap[util.CaptureHost(j.node.address)] { if host != j.node.address { nonPreferredNodes = append(nonPreferredNodes, host) } } return nonPreferredNodes }
[ "func", "(", "j", "*", "joinSender", ")", "CollectNonPreferredNodes", "(", ")", "[", "]", "string", "{", "if", "len", "(", "j", ".", "preferredNodes", ")", "==", "0", "{", "return", "j", ".", "potentialNodes", "\n", "}", "\n\n", "var", "nonPreferredNodes", "[", "]", "string", "\n\n", "for", "_", ",", "host", ":=", "range", "j", ".", "bootstrapHostsMap", "[", "util", ".", "CaptureHost", "(", "j", ".", "node", ".", "address", ")", "]", "{", "if", "host", "!=", "j", ".", "node", ".", "address", "{", "nonPreferredNodes", "=", "append", "(", "nonPreferredNodes", ",", "host", ")", "\n", "}", "\n", "}", "\n", "return", "nonPreferredNodes", "\n", "}" ]
// non-preferred nodes are everyone else
[ "non", "-", "preferred", "nodes", "are", "everyone", "else" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L221-L234
143,181
uber/ringpop-go
swim/join_sender.go
SelectGroup
func (j *joinSender) SelectGroup(nodesJoined []string) []string { var group []string // if fully exhausted or first round, initialize this round's nodes if len(j.roundPreferredNodes) == 0 && len(j.roundNonPreferredNodes) == 0 { j.Init(nodesJoined) } numNodesLeft := j.size - len(nodesJoined) cont := func() bool { if len(group) == numNodesLeft*j.parallelismFactor { return false } nodesAvailable := len(j.roundPreferredNodes) + len(j.roundNonPreferredNodes) if nodesAvailable == 0 { return false } return true } for cont() { if len(j.roundPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundPreferredNodes, -1)) } else if len(j.roundNonPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundNonPreferredNodes, -1)) } } return group }
go
func (j *joinSender) SelectGroup(nodesJoined []string) []string { var group []string // if fully exhausted or first round, initialize this round's nodes if len(j.roundPreferredNodes) == 0 && len(j.roundNonPreferredNodes) == 0 { j.Init(nodesJoined) } numNodesLeft := j.size - len(nodesJoined) cont := func() bool { if len(group) == numNodesLeft*j.parallelismFactor { return false } nodesAvailable := len(j.roundPreferredNodes) + len(j.roundNonPreferredNodes) if nodesAvailable == 0 { return false } return true } for cont() { if len(j.roundPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundPreferredNodes, -1)) } else if len(j.roundNonPreferredNodes) > 0 { group = append(group, util.TakeNode(&j.roundNonPreferredNodes, -1)) } } return group }
[ "func", "(", "j", "*", "joinSender", ")", "SelectGroup", "(", "nodesJoined", "[", "]", "string", ")", "[", "]", "string", "{", "var", "group", "[", "]", "string", "\n", "// if fully exhausted or first round, initialize this round's nodes", "if", "len", "(", "j", ".", "roundPreferredNodes", ")", "==", "0", "&&", "len", "(", "j", ".", "roundNonPreferredNodes", ")", "==", "0", "{", "j", ".", "Init", "(", "nodesJoined", ")", "\n", "}", "\n\n", "numNodesLeft", ":=", "j", ".", "size", "-", "len", "(", "nodesJoined", ")", "\n\n", "cont", ":=", "func", "(", ")", "bool", "{", "if", "len", "(", "group", ")", "==", "numNodesLeft", "*", "j", ".", "parallelismFactor", "{", "return", "false", "\n", "}", "\n\n", "nodesAvailable", ":=", "len", "(", "j", ".", "roundPreferredNodes", ")", "+", "len", "(", "j", ".", "roundNonPreferredNodes", ")", "\n", "if", "nodesAvailable", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n\n", "for", "cont", "(", ")", "{", "if", "len", "(", "j", ".", "roundPreferredNodes", ")", ">", "0", "{", "group", "=", "append", "(", "group", ",", "util", ".", "TakeNode", "(", "&", "j", ".", "roundPreferredNodes", ",", "-", "1", ")", ")", "\n", "}", "else", "if", "len", "(", "j", ".", "roundNonPreferredNodes", ")", ">", "0", "{", "group", "=", "append", "(", "group", ",", "util", ".", "TakeNode", "(", "&", "j", ".", "roundNonPreferredNodes", ",", "-", "1", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "group", "\n", "}" ]
// selects a group of nodes
[ "selects", "a", "group", "of", "nodes" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L249-L280
143,182
uber/ringpop-go
swim/join_sender.go
JoinGroup
func (j *joinSender) JoinGroup(nodesJoined []string) ([]string, []string) { group := j.SelectGroup(nodesJoined) var responses struct { successes []string failures []string sync.Mutex } var numNodesLeft = j.size - len(nodesJoined) var startTime = time.Now() var wg sync.WaitGroup j.numTries++ j.node.EmitEvent(JoinTriesUpdateEvent{j.numTries}) for _, target := range group { wg.Add(1) go func(target string) { defer wg.Done() res, err := sendJoinRequest(j.node, target, j.timeout) if err != nil { msg := "attempt to join node failed" if err == errJoinTimeout { msg = "attempt to join node timed out" } j.logger.WithFields(log.Fields{ "remote": target, "timeout": j.timeout, }).Debug(msg) responses.Lock() responses.failures = append(responses.failures, target) responses.Unlock() return } responses.Lock() responses.successes = append(responses.successes, target) responses.Unlock() start := time.Now() j.node.memberlist.AddJoinList(res.Membership) j.node.EmitEvent(AddJoinListEvent{ Duration: time.Now().Sub(start), }) }(target) } // wait for joins to complete wg.Wait() // don't need to lock successes/failures since we're finished writing to them j.logger.WithFields(log.Fields{ "groupSize": len(group), "joinSize": j.size, "joinTime": time.Now().Sub(startTime), "numNodesLeft": numNodesLeft, "numFailures": len(responses.failures), "failures": responses.failures, "numSuccesses": len(responses.successes), "successes": responses.successes, }).Debug("join group complete") return responses.successes, responses.failures }
go
func (j *joinSender) JoinGroup(nodesJoined []string) ([]string, []string) { group := j.SelectGroup(nodesJoined) var responses struct { successes []string failures []string sync.Mutex } var numNodesLeft = j.size - len(nodesJoined) var startTime = time.Now() var wg sync.WaitGroup j.numTries++ j.node.EmitEvent(JoinTriesUpdateEvent{j.numTries}) for _, target := range group { wg.Add(1) go func(target string) { defer wg.Done() res, err := sendJoinRequest(j.node, target, j.timeout) if err != nil { msg := "attempt to join node failed" if err == errJoinTimeout { msg = "attempt to join node timed out" } j.logger.WithFields(log.Fields{ "remote": target, "timeout": j.timeout, }).Debug(msg) responses.Lock() responses.failures = append(responses.failures, target) responses.Unlock() return } responses.Lock() responses.successes = append(responses.successes, target) responses.Unlock() start := time.Now() j.node.memberlist.AddJoinList(res.Membership) j.node.EmitEvent(AddJoinListEvent{ Duration: time.Now().Sub(start), }) }(target) } // wait for joins to complete wg.Wait() // don't need to lock successes/failures since we're finished writing to them j.logger.WithFields(log.Fields{ "groupSize": len(group), "joinSize": j.size, "joinTime": time.Now().Sub(startTime), "numNodesLeft": numNodesLeft, "numFailures": len(responses.failures), "failures": responses.failures, "numSuccesses": len(responses.successes), "successes": responses.successes, }).Debug("join group complete") return responses.successes, responses.failures }
[ "func", "(", "j", "*", "joinSender", ")", "JoinGroup", "(", "nodesJoined", "[", "]", "string", ")", "(", "[", "]", "string", ",", "[", "]", "string", ")", "{", "group", ":=", "j", ".", "SelectGroup", "(", "nodesJoined", ")", "\n\n", "var", "responses", "struct", "{", "successes", "[", "]", "string", "\n", "failures", "[", "]", "string", "\n", "sync", ".", "Mutex", "\n", "}", "\n\n", "var", "numNodesLeft", "=", "j", ".", "size", "-", "len", "(", "nodesJoined", ")", "\n", "var", "startTime", "=", "time", ".", "Now", "(", ")", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "j", ".", "numTries", "++", "\n", "j", ".", "node", ".", "EmitEvent", "(", "JoinTriesUpdateEvent", "{", "j", ".", "numTries", "}", ")", "\n\n", "for", "_", ",", "target", ":=", "range", "group", "{", "wg", ".", "Add", "(", "1", ")", "\n\n", "go", "func", "(", "target", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "res", ",", "err", ":=", "sendJoinRequest", "(", "j", ".", "node", ",", "target", ",", "j", ".", "timeout", ")", "\n\n", "if", "err", "!=", "nil", "{", "msg", ":=", "\"", "\"", "\n", "if", "err", "==", "errJoinTimeout", "{", "msg", "=", "\"", "\"", "\n", "}", "\n\n", "j", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "j", ".", "timeout", ",", "}", ")", ".", "Debug", "(", "msg", ")", "\n\n", "responses", ".", "Lock", "(", ")", "\n", "responses", ".", "failures", "=", "append", "(", "responses", ".", "failures", ",", "target", ")", "\n", "responses", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "responses", ".", "Lock", "(", ")", "\n", "responses", ".", "successes", "=", "append", "(", "responses", ".", "successes", ",", "target", ")", "\n", "responses", ".", "Unlock", "(", ")", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "j", ".", "node", ".", "memberlist", ".", "AddJoinList", "(", "res", ".", "Membership", ")", "\n\n", "j", ".", "node", ".", "EmitEvent", "(", "AddJoinListEvent", "{", "Duration", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ",", "}", ")", "\n", "}", "(", "target", ")", "\n", "}", "\n\n", "// wait for joins to complete", "wg", ".", "Wait", "(", ")", "\n\n", "// don't need to lock successes/failures since we're finished writing to them", "j", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "len", "(", "group", ")", ",", "\"", "\"", ":", "j", ".", "size", ",", "\"", "\"", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ",", "\"", "\"", ":", "numNodesLeft", ",", "\"", "\"", ":", "len", "(", "responses", ".", "failures", ")", ",", "\"", "\"", ":", "responses", ".", "failures", ",", "\"", "\"", ":", "len", "(", "responses", ".", "successes", ")", ",", "\"", "\"", ":", "responses", ".", "successes", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "responses", ".", "successes", ",", "responses", ".", "failures", "\n", "}" ]
// JoinGroup collects a number of nodes to join and sends join requests to them. // nodesJoined contains the nodes that are already joined. The method returns // the nodes that are succesfully joined, and the nodes that failed respond.
[ "JoinGroup", "collects", "a", "number", "of", "nodes", "to", "join", "and", "sends", "join", "requests", "to", "them", ".", "nodesJoined", "contains", "the", "nodes", "that", "are", "already", "joined", ".", "The", "method", "returns", "the", "nodes", "that", "are", "succesfully", "joined", "and", "the", "nodes", "that", "failed", "respond", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L365-L436
143,183
uber/ringpop-go
swim/join_sender.go
sendJoinRequest
func sendJoinRequest(node *Node, target string, timeout time.Duration) (*joinResponse, error) { ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) req := joinRequest{ App: node.app, Source: node.address, Incarnation: node.Incarnation(), Timeout: timeout, Labels: node.Labels().AsMap(), } res := &joinResponse{} // make request errC := make(chan error, 1) go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/join", req, res) }() // wait for result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errJoinTimeout } if err != nil { logging.Logger("join").WithFields(log.Fields{ "local": node.Address(), "error": err, }).Debug("could not complete join") return nil, err } return res, err }
go
func sendJoinRequest(node *Node, target string, timeout time.Duration) (*joinResponse, error) { ctx, cancel := shared.NewTChannelContext(timeout) defer cancel() peer := node.channel.Peers().GetOrAdd(target) req := joinRequest{ App: node.app, Source: node.address, Incarnation: node.Incarnation(), Timeout: timeout, Labels: node.Labels().AsMap(), } res := &joinResponse{} // make request errC := make(chan error, 1) go func() { errC <- json.CallPeer(ctx, peer, node.service, "/protocol/join", req, res) }() // wait for result or timeout var err error select { case err = <-errC: case <-ctx.Done(): err = errJoinTimeout } if err != nil { logging.Logger("join").WithFields(log.Fields{ "local": node.Address(), "error": err, }).Debug("could not complete join") return nil, err } return res, err }
[ "func", "sendJoinRequest", "(", "node", "*", "Node", ",", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "joinResponse", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "shared", ".", "NewTChannelContext", "(", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "peer", ":=", "node", ".", "channel", ".", "Peers", "(", ")", ".", "GetOrAdd", "(", "target", ")", "\n\n", "req", ":=", "joinRequest", "{", "App", ":", "node", ".", "app", ",", "Source", ":", "node", ".", "address", ",", "Incarnation", ":", "node", ".", "Incarnation", "(", ")", ",", "Timeout", ":", "timeout", ",", "Labels", ":", "node", ".", "Labels", "(", ")", ".", "AsMap", "(", ")", ",", "}", "\n", "res", ":=", "&", "joinResponse", "{", "}", "\n\n", "// make request", "errC", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "errC", "<-", "json", ".", "CallPeer", "(", "ctx", ",", "peer", ",", "node", ".", "service", ",", "\"", "\"", ",", "req", ",", "res", ")", "\n", "}", "(", ")", "\n\n", "// wait for result or timeout", "var", "err", "error", "\n", "select", "{", "case", "err", "=", "<-", "errC", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "err", "=", "errJoinTimeout", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "Address", "(", ")", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "res", ",", "err", "\n", "}" ]
// sendJoinRequest sends a join request to the specified target.
[ "sendJoinRequest", "sends", "a", "join", "request", "to", "the", "specified", "target", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L439-L478
143,184
uber/ringpop-go
swim/join_sender.go
sendJoin
func sendJoin(node *Node, opts *joinOpts) ([]string, error) { joiner, err := newJoinSender(node, opts) if err != nil { return nil, err } return joiner.JoinCluster() }
go
func sendJoin(node *Node, opts *joinOpts) ([]string, error) { joiner, err := newJoinSender(node, opts) if err != nil { return nil, err } return joiner.JoinCluster() }
[ "func", "sendJoin", "(", "node", "*", "Node", ",", "opts", "*", "joinOpts", ")", "(", "[", "]", "string", ",", "error", ")", "{", "joiner", ",", "err", ":=", "newJoinSender", "(", "node", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "joiner", ".", "JoinCluster", "(", ")", "\n", "}" ]
// SendJoin creates a new JoinSender and attempts to join the cluster defined by // the nodes bootstrap hosts
[ "SendJoin", "creates", "a", "new", "JoinSender", "and", "attempts", "to", "join", "the", "cluster", "defined", "by", "the", "nodes", "bootstrap", "hosts" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/join_sender.go#L482-L488
143,185
uber/ringpop-go
swim/node.go
NewNode
func NewNode(app, address string, channel shared.SubChannel, opts *Options) *Node { // use defaults for options that are unspecified opts = mergeDefaultOptions(opts) node := &Node{ address: address, app: app, channel: channel, logger: logging.Logger("node").WithField("local", address), joinTimeout: opts.JoinTimeout, pingTimeout: opts.PingTimeout, pingRequestTimeout: opts.PingRequestTimeout, pingRequestSize: opts.PingRequestSize, maxReverseFullSyncJobs: opts.MaxReverseFullSyncJobs, clientRate: metrics.NewMeter(), serverRate: metrics.NewMeter(), totalRate: metrics.NewMeter(), clock: opts.Clock, } node.selfEvict = newSelfEvict(node, opts.SelfEvict) node.requiresAppInPing = opts.RequiresAppInPing node.labelLimits = opts.LabelLimits node.memberlist = newMemberlist(node, opts.InitialLabels) node.memberiter = newMemberlistIter(node.memberlist) node.stateTransitions = newStateTransitions(node, opts.StateTimeouts) node.healer = newDiscoverProviderHealer( node, opts.PartitionHealBaseProbabillity, opts.PartitionHealPeriod, ) node.gossip = newGossip(node, opts.MinProtocolPeriod) node.disseminator = newDisseminator(node) for _, member := range node.memberlist.GetMembers() { change := Change{} change.populateSubject(&member) node.disseminator.RecordChange(change) } if node.channel != nil { node.registerHandlers() node.service = node.channel.ServiceName() } return node }
go
func NewNode(app, address string, channel shared.SubChannel, opts *Options) *Node { // use defaults for options that are unspecified opts = mergeDefaultOptions(opts) node := &Node{ address: address, app: app, channel: channel, logger: logging.Logger("node").WithField("local", address), joinTimeout: opts.JoinTimeout, pingTimeout: opts.PingTimeout, pingRequestTimeout: opts.PingRequestTimeout, pingRequestSize: opts.PingRequestSize, maxReverseFullSyncJobs: opts.MaxReverseFullSyncJobs, clientRate: metrics.NewMeter(), serverRate: metrics.NewMeter(), totalRate: metrics.NewMeter(), clock: opts.Clock, } node.selfEvict = newSelfEvict(node, opts.SelfEvict) node.requiresAppInPing = opts.RequiresAppInPing node.labelLimits = opts.LabelLimits node.memberlist = newMemberlist(node, opts.InitialLabels) node.memberiter = newMemberlistIter(node.memberlist) node.stateTransitions = newStateTransitions(node, opts.StateTimeouts) node.healer = newDiscoverProviderHealer( node, opts.PartitionHealBaseProbabillity, opts.PartitionHealPeriod, ) node.gossip = newGossip(node, opts.MinProtocolPeriod) node.disseminator = newDisseminator(node) for _, member := range node.memberlist.GetMembers() { change := Change{} change.populateSubject(&member) node.disseminator.RecordChange(change) } if node.channel != nil { node.registerHandlers() node.service = node.channel.ServiceName() } return node }
[ "func", "NewNode", "(", "app", ",", "address", "string", ",", "channel", "shared", ".", "SubChannel", ",", "opts", "*", "Options", ")", "*", "Node", "{", "// use defaults for options that are unspecified", "opts", "=", "mergeDefaultOptions", "(", "opts", ")", "\n\n", "node", ":=", "&", "Node", "{", "address", ":", "address", ",", "app", ":", "app", ",", "channel", ":", "channel", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "address", ")", ",", "joinTimeout", ":", "opts", ".", "JoinTimeout", ",", "pingTimeout", ":", "opts", ".", "PingTimeout", ",", "pingRequestTimeout", ":", "opts", ".", "PingRequestTimeout", ",", "pingRequestSize", ":", "opts", ".", "PingRequestSize", ",", "maxReverseFullSyncJobs", ":", "opts", ".", "MaxReverseFullSyncJobs", ",", "clientRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "serverRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "totalRate", ":", "metrics", ".", "NewMeter", "(", ")", ",", "clock", ":", "opts", ".", "Clock", ",", "}", "\n", "node", ".", "selfEvict", "=", "newSelfEvict", "(", "node", ",", "opts", ".", "SelfEvict", ")", "\n", "node", ".", "requiresAppInPing", "=", "opts", ".", "RequiresAppInPing", "\n\n", "node", ".", "labelLimits", "=", "opts", ".", "LabelLimits", "\n\n", "node", ".", "memberlist", "=", "newMemberlist", "(", "node", ",", "opts", ".", "InitialLabels", ")", "\n", "node", ".", "memberiter", "=", "newMemberlistIter", "(", "node", ".", "memberlist", ")", "\n", "node", ".", "stateTransitions", "=", "newStateTransitions", "(", "node", ",", "opts", ".", "StateTimeouts", ")", "\n\n", "node", ".", "healer", "=", "newDiscoverProviderHealer", "(", "node", ",", "opts", ".", "PartitionHealBaseProbabillity", ",", "opts", ".", "PartitionHealPeriod", ",", ")", "\n", "node", ".", "gossip", "=", "newGossip", "(", "node", ",", "opts", ".", "MinProtocolPeriod", ")", "\n", "node", ".", "disseminator", "=", "newDisseminator", "(", "node", ")", "\n\n", "for", "_", ",", "member", ":=", "range", "node", ".", "memberlist", ".", "GetMembers", "(", ")", "{", "change", ":=", "Change", "{", "}", "\n", "change", ".", "populateSubject", "(", "&", "member", ")", "\n", "node", ".", "disseminator", ".", "RecordChange", "(", "change", ")", "\n", "}", "\n\n", "if", "node", ".", "channel", "!=", "nil", "{", "node", ".", "registerHandlers", "(", ")", "\n", "node", ".", "service", "=", "node", ".", "channel", ".", "ServiceName", "(", ")", "\n", "}", "\n\n", "return", "node", "\n", "}" ]
// NewNode returns a new SWIM Node.
[ "NewNode", "returns", "a", "new", "SWIM", "Node", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L231-L283
143,186
uber/ringpop-go
swim/node.go
Incarnation
func (n *Node) Incarnation() int64 { if n.memberlist != nil && n.memberlist.local != nil { n.memberlist.members.RLock() incarnation := n.memberlist.local.Incarnation n.memberlist.members.RUnlock() return incarnation } return -1 }
go
func (n *Node) Incarnation() int64 { if n.memberlist != nil && n.memberlist.local != nil { n.memberlist.members.RLock() incarnation := n.memberlist.local.Incarnation n.memberlist.members.RUnlock() return incarnation } return -1 }
[ "func", "(", "n", "*", "Node", ")", "Incarnation", "(", ")", "int64", "{", "if", "n", ".", "memberlist", "!=", "nil", "&&", "n", ".", "memberlist", ".", "local", "!=", "nil", "{", "n", ".", "memberlist", ".", "members", ".", "RLock", "(", ")", "\n", "incarnation", ":=", "n", ".", "memberlist", ".", "local", ".", "Incarnation", "\n", "n", ".", "memberlist", ".", "members", ".", "RUnlock", "(", ")", "\n", "return", "incarnation", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Incarnation returns the incarnation number of the Node.
[ "Incarnation", "returns", "the", "incarnation", "number", "of", "the", "Node", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L301-L309
143,187
uber/ringpop-go
swim/node.go
Start
func (n *Node) Start() { n.gossip.Start() n.stateTransitions.Enable() n.healer.Start() n.state.Lock() n.state.stopped = false n.state.Unlock() }
go
func (n *Node) Start() { n.gossip.Start() n.stateTransitions.Enable() n.healer.Start() n.state.Lock() n.state.stopped = false n.state.Unlock() }
[ "func", "(", "n", "*", "Node", ")", "Start", "(", ")", "{", "n", ".", "gossip", ".", "Start", "(", ")", "\n", "n", ".", "stateTransitions", ".", "Enable", "(", ")", "\n", "n", ".", "healer", ".", "Start", "(", ")", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "stopped", "=", "false", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "}" ]
// Start starts the SWIM protocol and all sub-protocols.
[ "Start", "starts", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L312-L320
143,188
uber/ringpop-go
swim/node.go
Stop
func (n *Node) Stop() { n.gossip.Stop() n.stateTransitions.Disable() n.healer.Stop() n.state.Lock() n.state.stopped = true n.state.Unlock() }
go
func (n *Node) Stop() { n.gossip.Stop() n.stateTransitions.Disable() n.healer.Stop() n.state.Lock() n.state.stopped = true n.state.Unlock() }
[ "func", "(", "n", "*", "Node", ")", "Stop", "(", ")", "{", "n", ".", "gossip", ".", "Stop", "(", ")", "\n", "n", ".", "stateTransitions", ".", "Disable", "(", ")", "\n", "n", ".", "healer", ".", "Stop", "(", ")", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "stopped", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "}" ]
// Stop stops the SWIM protocol and all sub-protocols.
[ "Stop", "stops", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L323-L331
143,189
uber/ringpop-go
swim/node.go
Stopped
func (n *Node) Stopped() bool { n.state.RLock() stopped := n.state.stopped n.state.RUnlock() return stopped }
go
func (n *Node) Stopped() bool { n.state.RLock() stopped := n.state.stopped n.state.RUnlock() return stopped }
[ "func", "(", "n", "*", "Node", ")", "Stopped", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "stopped", ":=", "n", ".", "state", ".", "stopped", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "stopped", "\n", "}" ]
// Stopped returns whether or not the SWIM protocol is currently running.
[ "Stopped", "returns", "whether", "or", "not", "the", "SWIM", "protocol", "is", "currently", "running", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L334-L340
143,190
uber/ringpop-go
swim/node.go
Destroy
func (n *Node) Destroy() { n.state.Lock() if n.state.destroyed { n.state.Unlock() return } n.state.destroyed = true n.state.Unlock() n.Stop() }
go
func (n *Node) Destroy() { n.state.Lock() if n.state.destroyed { n.state.Unlock() return } n.state.destroyed = true n.state.Unlock() n.Stop() }
[ "func", "(", "n", "*", "Node", ")", "Destroy", "(", ")", "{", "n", ".", "state", ".", "Lock", "(", ")", "\n", "if", "n", ".", "state", ".", "destroyed", "{", "n", ".", "state", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "n", ".", "state", ".", "destroyed", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n\n", "n", ".", "Stop", "(", ")", "\n", "}" ]
// Destroy stops the SWIM protocol and all sub-protocols.
[ "Destroy", "stops", "the", "SWIM", "protocol", "and", "all", "sub", "-", "protocols", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L343-L353
143,191
uber/ringpop-go
swim/node.go
Destroyed
func (n *Node) Destroyed() bool { n.state.RLock() destroyed := n.state.destroyed n.state.RUnlock() return destroyed }
go
func (n *Node) Destroyed() bool { n.state.RLock() destroyed := n.state.destroyed n.state.RUnlock() return destroyed }
[ "func", "(", "n", "*", "Node", ")", "Destroyed", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "destroyed", ":=", "n", ".", "state", ".", "destroyed", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "destroyed", "\n", "}" ]
// Destroyed returns whether or not the node has been destroyed.
[ "Destroyed", "returns", "whether", "or", "not", "the", "node", "has", "been", "destroyed", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L356-L362
143,192
uber/ringpop-go
swim/node.go
Ready
func (n *Node) Ready() bool { n.state.RLock() ready := n.state.ready n.state.RUnlock() return ready }
go
func (n *Node) Ready() bool { n.state.RLock() ready := n.state.ready n.state.RUnlock() return ready }
[ "func", "(", "n", "*", "Node", ")", "Ready", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "ready", ":=", "n", ".", "state", ".", "ready", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "ready", "\n", "}" ]
// Ready returns whether or not the node has bootstrapped and is ready for use.
[ "Ready", "returns", "whether", "or", "not", "the", "node", "has", "bootstrapped", "and", "is", "ready", "for", "use", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L365-L371
143,193
uber/ringpop-go
swim/node.go
RegisterSelfEvictHook
func (n *Node) RegisterSelfEvictHook(hooks SelfEvictHook) error { return n.selfEvict.RegisterSelfEvictHook(hooks) }
go
func (n *Node) RegisterSelfEvictHook(hooks SelfEvictHook) error { return n.selfEvict.RegisterSelfEvictHook(hooks) }
[ "func", "(", "n", "*", "Node", ")", "RegisterSelfEvictHook", "(", "hooks", "SelfEvictHook", ")", "error", "{", "return", "n", ".", "selfEvict", ".", "RegisterSelfEvictHook", "(", "hooks", ")", "\n", "}" ]
// RegisterSelfEvictHook registers systems that want to hook into the eviction // sequence of the swim protocol.
[ "RegisterSelfEvictHook", "registers", "systems", "that", "want", "to", "hook", "into", "the", "eviction", "sequence", "of", "the", "swim", "protocol", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L375-L377
143,194
uber/ringpop-go
swim/node.go
Bootstrap
func (n *Node) Bootstrap(opts *BootstrapOptions) ([]string, error) { if n.channel == nil { return nil, errors.New("channel required") } if opts == nil { opts = &BootstrapOptions{} } n.discoverProvider = opts.DiscoverProvider joinOpts := &joinOpts{ timeout: opts.JoinTimeout, size: opts.JoinSize, maxJoinDuration: opts.MaxJoinDuration, parallelismFactor: opts.ParallelismFactor, } joined, err := sendJoin(n, joinOpts) if err != nil { n.logger.WithFields(log.Fields{ "err": err.Error(), }).Error("bootstrap failed") return nil, err } if !opts.Stopped { n.gossip.Start() n.healer.Start() } n.state.Lock() n.state.ready = true n.state.Unlock() n.startTime = time.Now() return joined, nil }
go
func (n *Node) Bootstrap(opts *BootstrapOptions) ([]string, error) { if n.channel == nil { return nil, errors.New("channel required") } if opts == nil { opts = &BootstrapOptions{} } n.discoverProvider = opts.DiscoverProvider joinOpts := &joinOpts{ timeout: opts.JoinTimeout, size: opts.JoinSize, maxJoinDuration: opts.MaxJoinDuration, parallelismFactor: opts.ParallelismFactor, } joined, err := sendJoin(n, joinOpts) if err != nil { n.logger.WithFields(log.Fields{ "err": err.Error(), }).Error("bootstrap failed") return nil, err } if !opts.Stopped { n.gossip.Start() n.healer.Start() } n.state.Lock() n.state.ready = true n.state.Unlock() n.startTime = time.Now() return joined, nil }
[ "func", "(", "n", "*", "Node", ")", "Bootstrap", "(", "opts", "*", "BootstrapOptions", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "n", ".", "channel", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "opts", "==", "nil", "{", "opts", "=", "&", "BootstrapOptions", "{", "}", "\n", "}", "\n\n", "n", ".", "discoverProvider", "=", "opts", ".", "DiscoverProvider", "\n", "joinOpts", ":=", "&", "joinOpts", "{", "timeout", ":", "opts", ".", "JoinTimeout", ",", "size", ":", "opts", ".", "JoinSize", ",", "maxJoinDuration", ":", "opts", ".", "MaxJoinDuration", ",", "parallelismFactor", ":", "opts", ".", "ParallelismFactor", ",", "}", "\n\n", "joined", ",", "err", ":=", "sendJoin", "(", "n", ",", "joinOpts", ")", "\n", "if", "err", "!=", "nil", "{", "n", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "opts", ".", "Stopped", "{", "n", ".", "gossip", ".", "Start", "(", ")", "\n", "n", ".", "healer", ".", "Start", "(", ")", "\n", "}", "\n\n", "n", ".", "state", ".", "Lock", "(", ")", "\n", "n", ".", "state", ".", "ready", "=", "true", "\n", "n", ".", "state", ".", "Unlock", "(", ")", "\n\n", "n", ".", "startTime", "=", "time", ".", "Now", "(", ")", "\n\n", "return", "joined", ",", "nil", "\n", "}" ]
// Bootstrap joins a node to a cluster. The channel provided to the node must be // listening for the bootstrap to complete.
[ "Bootstrap", "joins", "a", "node", "to", "a", "cluster", ".", "The", "channel", "provided", "to", "the", "node", "must", "be", "listening", "for", "the", "bootstrap", "to", "complete", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L420-L457
143,195
uber/ringpop-go
swim/node.go
handleChanges
func (n *Node) handleChanges(changes []Change) { n.disseminator.AdjustMaxPropagations() for _, change := range changes { n.disseminator.RecordChange(change) switch change.Status { case Alive: n.stateTransitions.Cancel(change) case Suspect: n.stateTransitions.ScheduleSuspectToFaulty(change) case Faulty: n.stateTransitions.ScheduleFaultyToTombstone(change) case Leave: // XXX: should this also reap? n.stateTransitions.Cancel(change) case Tombstone: n.stateTransitions.ScheduleTombstoneToEvict(change) } } }
go
func (n *Node) handleChanges(changes []Change) { n.disseminator.AdjustMaxPropagations() for _, change := range changes { n.disseminator.RecordChange(change) switch change.Status { case Alive: n.stateTransitions.Cancel(change) case Suspect: n.stateTransitions.ScheduleSuspectToFaulty(change) case Faulty: n.stateTransitions.ScheduleFaultyToTombstone(change) case Leave: // XXX: should this also reap? n.stateTransitions.Cancel(change) case Tombstone: n.stateTransitions.ScheduleTombstoneToEvict(change) } } }
[ "func", "(", "n", "*", "Node", ")", "handleChanges", "(", "changes", "[", "]", "Change", ")", "{", "n", ".", "disseminator", ".", "AdjustMaxPropagations", "(", ")", "\n", "for", "_", ",", "change", ":=", "range", "changes", "{", "n", ".", "disseminator", ".", "RecordChange", "(", "change", ")", "\n\n", "switch", "change", ".", "Status", "{", "case", "Alive", ":", "n", ".", "stateTransitions", ".", "Cancel", "(", "change", ")", "\n\n", "case", "Suspect", ":", "n", ".", "stateTransitions", ".", "ScheduleSuspectToFaulty", "(", "change", ")", "\n\n", "case", "Faulty", ":", "n", ".", "stateTransitions", ".", "ScheduleFaultyToTombstone", "(", "change", ")", "\n\n", "case", "Leave", ":", "// XXX: should this also reap?", "n", ".", "stateTransitions", ".", "Cancel", "(", "change", ")", "\n\n", "case", "Tombstone", ":", "n", ".", "stateTransitions", ".", "ScheduleTombstoneToEvict", "(", "change", ")", "\n", "}", "\n", "}", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Change Handling // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Change", "Handling", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L465-L488
143,196
uber/ringpop-go
swim/node.go
pinging
func (n *Node) pinging() bool { n.state.RLock() pinging := n.state.pinging n.state.RUnlock() return pinging }
go
func (n *Node) pinging() bool { n.state.RLock() pinging := n.state.pinging n.state.RUnlock() return pinging }
[ "func", "(", "n", "*", "Node", ")", "pinging", "(", ")", "bool", "{", "n", ".", "state", ".", "RLock", "(", ")", "\n", "pinging", ":=", "n", ".", "state", ".", "pinging", "\n", "n", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "pinging", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Gossip // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Gossip", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L496-L502
143,197
uber/ringpop-go
swim/node.go
pingNextMember
func (n *Node) pingNextMember() { member, ok := n.memberiter.Next() if !ok { n.logger.Warn("no pingable members") return } if n.pinging() { n.logger.Warn("node already pinging") return } n.setPinging(true) defer n.setPinging(false) // send ping res, err := sendPing(n, member.Address, n.pingTimeout) if err == nil { n.memberlist.Update(res.Changes) return } // ping failed, send ping requests target := member.Address targetReached, errs := indirectPing(n, target, n.pingRequestSize, n.pingRequestTimeout) // if all helper nodes are unreachable, the indirectPing is inconclusive if len(errs) == n.pingRequestSize { n.logger.WithFields(log.Fields{ "target": target, "errors": errs, "numErrors": len(errs), }).Warn("ping request inconclusive due to errors") return } if !targetReached { n.logger.WithField("target", target).Info("ping request target unreachable") n.memberlist.MakeSuspect(member.Address, member.Incarnation) return } n.logger.WithField("target", target).Info("ping request target reachable") }
go
func (n *Node) pingNextMember() { member, ok := n.memberiter.Next() if !ok { n.logger.Warn("no pingable members") return } if n.pinging() { n.logger.Warn("node already pinging") return } n.setPinging(true) defer n.setPinging(false) // send ping res, err := sendPing(n, member.Address, n.pingTimeout) if err == nil { n.memberlist.Update(res.Changes) return } // ping failed, send ping requests target := member.Address targetReached, errs := indirectPing(n, target, n.pingRequestSize, n.pingRequestTimeout) // if all helper nodes are unreachable, the indirectPing is inconclusive if len(errs) == n.pingRequestSize { n.logger.WithFields(log.Fields{ "target": target, "errors": errs, "numErrors": len(errs), }).Warn("ping request inconclusive due to errors") return } if !targetReached { n.logger.WithField("target", target).Info("ping request target unreachable") n.memberlist.MakeSuspect(member.Address, member.Incarnation) return } n.logger.WithField("target", target).Info("ping request target reachable") }
[ "func", "(", "n", "*", "Node", ")", "pingNextMember", "(", ")", "{", "member", ",", "ok", ":=", "n", ".", "memberiter", ".", "Next", "(", ")", "\n", "if", "!", "ok", "{", "n", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "n", ".", "pinging", "(", ")", "{", "n", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "n", ".", "setPinging", "(", "true", ")", "\n", "defer", "n", ".", "setPinging", "(", "false", ")", "\n\n", "// send ping", "res", ",", "err", ":=", "sendPing", "(", "n", ",", "member", ".", "Address", ",", "n", ".", "pingTimeout", ")", "\n", "if", "err", "==", "nil", "{", "n", ".", "memberlist", ".", "Update", "(", "res", ".", "Changes", ")", "\n", "return", "\n", "}", "\n\n", "// ping failed, send ping requests", "target", ":=", "member", ".", "Address", "\n", "targetReached", ",", "errs", ":=", "indirectPing", "(", "n", ",", "target", ",", "n", ".", "pingRequestSize", ",", "n", ".", "pingRequestTimeout", ")", "\n\n", "// if all helper nodes are unreachable, the indirectPing is inconclusive", "if", "len", "(", "errs", ")", "==", "n", ".", "pingRequestSize", "{", "n", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "errs", ",", "\"", "\"", ":", "len", "(", "errs", ")", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "!", "targetReached", "{", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "n", ".", "memberlist", ".", "MakeSuspect", "(", "member", ".", "Address", ",", "member", ".", "Incarnation", ")", "\n", "return", "\n", "}", "\n\n", "n", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}" ]
// pingNextMember pings the next member in the memberlist
[ "pingNextMember", "pings", "the", "next", "member", "in", "the", "memberlist" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L511-L554
143,198
uber/ringpop-go
swim/node.go
GetReachableMembers
func (n *Node) GetReachableMembers(predicates ...MemberPredicate) []Member { predicates = append(predicates, memberIsReachable) return n.memberlist.GetMembers(predicates...) }
go
func (n *Node) GetReachableMembers(predicates ...MemberPredicate) []Member { predicates = append(predicates, memberIsReachable) return n.memberlist.GetMembers(predicates...) }
[ "func", "(", "n", "*", "Node", ")", "GetReachableMembers", "(", "predicates", "...", "MemberPredicate", ")", "[", "]", "Member", "{", "predicates", "=", "append", "(", "predicates", ",", "memberIsReachable", ")", "\n", "return", "n", ".", "memberlist", ".", "GetMembers", "(", "predicates", "...", ")", "\n", "}" ]
// GetReachableMembers returns a slice of members containing only the reachable // members that satisfies the predicates passed in.
[ "GetReachableMembers", "returns", "a", "slice", "of", "members", "containing", "only", "the", "reachable", "members", "that", "satisfies", "the", "predicates", "passed", "in", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L558-L561
143,199
uber/ringpop-go
swim/node.go
CountReachableMembers
func (n *Node) CountReachableMembers(predicates ...MemberPredicate) int { predicates = append(predicates, memberIsReachable) return n.memberlist.CountMembers(predicates...) }
go
func (n *Node) CountReachableMembers(predicates ...MemberPredicate) int { predicates = append(predicates, memberIsReachable) return n.memberlist.CountMembers(predicates...) }
[ "func", "(", "n", "*", "Node", ")", "CountReachableMembers", "(", "predicates", "...", "MemberPredicate", ")", "int", "{", "predicates", "=", "append", "(", "predicates", ",", "memberIsReachable", ")", "\n", "return", "n", ".", "memberlist", ".", "CountMembers", "(", "predicates", "...", ")", "\n", "}" ]
// CountReachableMembers returns the number of reachable members currently in // this node's membership list that satisfies all predicates passed in.
[ "CountReachableMembers", "returns", "the", "number", "of", "reachable", "members", "currently", "in", "this", "node", "s", "membership", "list", "that", "satisfies", "all", "predicates", "passed", "in", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/node.go#L565-L568