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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
166,100
hashicorp/serf
cmd/serf/command/agent/agent.go
loadTagsFile
func (a *Agent) loadTagsFile(tagsFile string) error { // Avoid passing tags and using a tags file at the same time if len(a.agentConf.Tags) > 0 { return fmt.Errorf("Tags config not allowed while using tag files") } if _, err := os.Stat(tagsFile); err == nil { tagData, err := ioutil.ReadFile(tagsFile) if err != nil { return fmt.Errorf("Failed to read tags file: %s", err) } if err := json.Unmarshal(tagData, &a.conf.Tags); err != nil { return fmt.Errorf("Failed to decode tags file: %s", err) } a.logger.Printf("[INFO] agent: Restored %d tag(s) from %s", len(a.conf.Tags), tagsFile) } // Success! return nil }
go
func (a *Agent) loadTagsFile(tagsFile string) error { // Avoid passing tags and using a tags file at the same time if len(a.agentConf.Tags) > 0 { return fmt.Errorf("Tags config not allowed while using tag files") } if _, err := os.Stat(tagsFile); err == nil { tagData, err := ioutil.ReadFile(tagsFile) if err != nil { return fmt.Errorf("Failed to read tags file: %s", err) } if err := json.Unmarshal(tagData, &a.conf.Tags); err != nil { return fmt.Errorf("Failed to decode tags file: %s", err) } a.logger.Printf("[INFO] agent: Restored %d tag(s) from %s", len(a.conf.Tags), tagsFile) } // Success! return nil }
[ "func", "(", "a", "*", "Agent", ")", "loadTagsFile", "(", "tagsFile", "string", ")", "error", "{", "// Avoid passing tags and using a tags file at the same time", "if", "len", "(", "a", ".", "agentConf", ".", "Tags", ")", ">", "0", "{", "return", "fmt", ".", ...
// loadTagsFile will load agent tags out of a file and set them in the // current serf configuration.
[ "loadTagsFile", "will", "load", "agent", "tags", "out", "of", "a", "file", "and", "set", "them", "in", "the", "current", "serf", "configuration", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L308-L328
166,101
hashicorp/serf
cmd/serf/command/agent/agent.go
writeTagsFile
func (a *Agent) writeTagsFile(tags map[string]string) error { encoded, err := json.MarshalIndent(tags, "", " ") if err != nil { return fmt.Errorf("Failed to encode tags: %s", err) } // Use 0600 for permissions, in case tag data is sensitive if err = ioutil.WriteFile(a.agentConf.TagsFile, encoded, 0600); err != nil { return fmt.Errorf("Failed to write tags file: %s", err) } // Success! return nil }
go
func (a *Agent) writeTagsFile(tags map[string]string) error { encoded, err := json.MarshalIndent(tags, "", " ") if err != nil { return fmt.Errorf("Failed to encode tags: %s", err) } // Use 0600 for permissions, in case tag data is sensitive if err = ioutil.WriteFile(a.agentConf.TagsFile, encoded, 0600); err != nil { return fmt.Errorf("Failed to write tags file: %s", err) } // Success! return nil }
[ "func", "(", "a", "*", "Agent", ")", "writeTagsFile", "(", "tags", "map", "[", "string", "]", "string", ")", "error", "{", "encoded", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "tags", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", ...
// writeTagsFile will write the current tags to the configured tags file.
[ "writeTagsFile", "will", "write", "the", "current", "tags", "to", "the", "configured", "tags", "file", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L331-L344
166,102
hashicorp/serf
cmd/serf/command/agent/agent.go
UnmarshalTags
func UnmarshalTags(tags []string) (map[string]string, error) { result := make(map[string]string) for _, tag := range tags { parts := strings.SplitN(tag, "=", 2) if len(parts) != 2 || len(parts[0]) == 0 { return nil, fmt.Errorf("Invalid tag: '%s'", tag) } result[parts[0]] = parts[1] } return result, nil }
go
func UnmarshalTags(tags []string) (map[string]string, error) { result := make(map[string]string) for _, tag := range tags { parts := strings.SplitN(tag, "=", 2) if len(parts) != 2 || len(parts[0]) == 0 { return nil, fmt.Errorf("Invalid tag: '%s'", tag) } result[parts[0]] = parts[1] } return result, nil }
[ "func", "UnmarshalTags", "(", "tags", "[", "]", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "tag", ":=", "range", "...
// UnmarshalTags is a utility function which takes a slice of strings in // key=value format and returns them as a tag mapping.
[ "UnmarshalTags", "is", "a", "utility", "function", "which", "takes", "a", "slice", "of", "strings", "in", "key", "=", "value", "format", "and", "returns", "them", "as", "a", "tag", "mapping", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L358-L368
166,103
hashicorp/serf
cmd/serf/command/agent/agent.go
loadKeyringFile
func (a *Agent) loadKeyringFile(keyringFile string) error { // Avoid passing an encryption key and a keyring file at the same time if len(a.agentConf.EncryptKey) > 0 { return fmt.Errorf("Encryption key not allowed while using a keyring") } if _, err := os.Stat(keyringFile); err != nil { return err } // Read in the keyring file data keyringData, err := ioutil.ReadFile(keyringFile) if err != nil { return fmt.Errorf("Failed to read keyring file: %s", err) } // Decode keyring JSON keys := make([]string, 0) if err := json.Unmarshal(keyringData, &keys); err != nil { return fmt.Errorf("Failed to decode keyring file: %s", err) } // Decode base64 values keysDecoded := make([][]byte, len(keys)) for i, key := range keys { keyBytes, err := base64.StdEncoding.DecodeString(key) if err != nil { return fmt.Errorf("Failed to decode key from keyring: %s", err) } keysDecoded[i] = keyBytes } // Guard against empty keyring file if len(keysDecoded) == 0 { return fmt.Errorf("Keyring file contains no keys") } // Create the keyring keyring, err := memberlist.NewKeyring(keysDecoded, keysDecoded[0]) if err != nil { return fmt.Errorf("Failed to restore keyring: %s", err) } a.conf.MemberlistConfig.Keyring = keyring a.logger.Printf("[INFO] agent: Restored keyring with %d keys from %s", len(keys), keyringFile) // Success! return nil }
go
func (a *Agent) loadKeyringFile(keyringFile string) error { // Avoid passing an encryption key and a keyring file at the same time if len(a.agentConf.EncryptKey) > 0 { return fmt.Errorf("Encryption key not allowed while using a keyring") } if _, err := os.Stat(keyringFile); err != nil { return err } // Read in the keyring file data keyringData, err := ioutil.ReadFile(keyringFile) if err != nil { return fmt.Errorf("Failed to read keyring file: %s", err) } // Decode keyring JSON keys := make([]string, 0) if err := json.Unmarshal(keyringData, &keys); err != nil { return fmt.Errorf("Failed to decode keyring file: %s", err) } // Decode base64 values keysDecoded := make([][]byte, len(keys)) for i, key := range keys { keyBytes, err := base64.StdEncoding.DecodeString(key) if err != nil { return fmt.Errorf("Failed to decode key from keyring: %s", err) } keysDecoded[i] = keyBytes } // Guard against empty keyring file if len(keysDecoded) == 0 { return fmt.Errorf("Keyring file contains no keys") } // Create the keyring keyring, err := memberlist.NewKeyring(keysDecoded, keysDecoded[0]) if err != nil { return fmt.Errorf("Failed to restore keyring: %s", err) } a.conf.MemberlistConfig.Keyring = keyring a.logger.Printf("[INFO] agent: Restored keyring with %d keys from %s", len(keys), keyringFile) // Success! return nil }
[ "func", "(", "a", "*", "Agent", ")", "loadKeyringFile", "(", "keyringFile", "string", ")", "error", "{", "// Avoid passing an encryption key and a keyring file at the same time", "if", "len", "(", "a", ".", "agentConf", ".", "EncryptKey", ")", ">", "0", "{", "retu...
// loadKeyringFile will load a keyring out of a file
[ "loadKeyringFile", "will", "load", "a", "keyring", "out", "of", "a", "file" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L371-L419
166,104
hashicorp/serf
cmd/serf/command/agent/agent.go
Stats
func (a *Agent) Stats() map[string]map[string]string { local := a.serf.LocalMember() event_handlers := make(map[string]string) // Convert event handlers from a string slice to a string map for _, script := range a.agentConf.EventScripts() { script_filter := fmt.Sprintf("%s:%s", script.EventFilter.Event, script.EventFilter.Name) event_handlers[script_filter] = script.Script } output := map[string]map[string]string{ "agent": map[string]string{ "name": local.Name, }, "runtime": runtimeStats(), "serf": a.serf.Stats(), "tags": local.Tags, "event_handlers": event_handlers, } return output }
go
func (a *Agent) Stats() map[string]map[string]string { local := a.serf.LocalMember() event_handlers := make(map[string]string) // Convert event handlers from a string slice to a string map for _, script := range a.agentConf.EventScripts() { script_filter := fmt.Sprintf("%s:%s", script.EventFilter.Event, script.EventFilter.Name) event_handlers[script_filter] = script.Script } output := map[string]map[string]string{ "agent": map[string]string{ "name": local.Name, }, "runtime": runtimeStats(), "serf": a.serf.Stats(), "tags": local.Tags, "event_handlers": event_handlers, } return output }
[ "func", "(", "a", "*", "Agent", ")", "Stats", "(", ")", "map", "[", "string", "]", "map", "[", "string", "]", "string", "{", "local", ":=", "a", ".", "serf", ".", "LocalMember", "(", ")", "\n", "event_handlers", ":=", "make", "(", "map", "[", "st...
// Stats is used to get various runtime information and stats
[ "Stats", "is", "used", "to", "get", "various", "runtime", "information", "and", "stats" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L422-L442
166,105
hashicorp/serf
serf/ping_delegate.go
AckPayload
func (p *pingDelegate) AckPayload() []byte { var buf bytes.Buffer // The first byte is the version number, forming a simple header. version := []byte{PingVersion} buf.Write(version) // The rest of the message is the serialized coordinate. enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{}) if err := enc.Encode(p.serf.coordClient.GetCoordinate()); err != nil { p.serf.logger.Printf("[ERR] serf: Failed to encode coordinate: %v\n", err) } return buf.Bytes() }
go
func (p *pingDelegate) AckPayload() []byte { var buf bytes.Buffer // The first byte is the version number, forming a simple header. version := []byte{PingVersion} buf.Write(version) // The rest of the message is the serialized coordinate. enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{}) if err := enc.Encode(p.serf.coordClient.GetCoordinate()); err != nil { p.serf.logger.Printf("[ERR] serf: Failed to encode coordinate: %v\n", err) } return buf.Bytes() }
[ "func", "(", "p", "*", "pingDelegate", ")", "AckPayload", "(", ")", "[", "]", "byte", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "// The first byte is the version number, forming a simple header.", "version", ":=", "[", "]", "byte", "{", "PingVersion", "...
// AckPayload is called to produce a payload to send back in response to a ping // request.
[ "AckPayload", "is", "called", "to", "produce", "a", "payload", "to", "send", "back", "in", "response", "to", "a", "ping", "request", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/ping_delegate.go#L29-L42
166,106
hashicorp/serf
serf/ping_delegate.go
NotifyPingComplete
func (p *pingDelegate) NotifyPingComplete(other *memberlist.Node, rtt time.Duration, payload []byte) { if payload == nil || len(payload) == 0 { return } // Verify ping version in the header. version := payload[0] if version != PingVersion { p.serf.logger.Printf("[ERR] serf: Unsupported ping version: %v", version) return } // Process the remainder of the message as a coordinate. r := bytes.NewReader(payload[1:]) dec := codec.NewDecoder(r, &codec.MsgpackHandle{}) var coord coordinate.Coordinate if err := dec.Decode(&coord); err != nil { p.serf.logger.Printf("[ERR] serf: Failed to decode coordinate from ping: %v", err) return } // Apply the update. before := p.serf.coordClient.GetCoordinate() after, err := p.serf.coordClient.Update(other.Name, &coord, rtt) if err != nil { metrics.IncrCounter([]string{"serf", "coordinate", "rejected"}, 1) p.serf.logger.Printf("[TRACE] serf: Rejected coordinate from %s: %v\n", other.Name, err) return } // Publish some metrics to give us an idea of how much we are // adjusting each time we update. d := float32(before.DistanceTo(after).Seconds() * 1.0e3) metrics.AddSample([]string{"serf", "coordinate", "adjustment-ms"}, d) // Cache the coordinate for the other node, and add our own // to the cache as well since it just got updated. This lets // users call GetCachedCoordinate with our node name, which is // more friendly. p.serf.coordCacheLock.Lock() p.serf.coordCache[other.Name] = &coord p.serf.coordCache[p.serf.config.NodeName] = p.serf.coordClient.GetCoordinate() p.serf.coordCacheLock.Unlock() }
go
func (p *pingDelegate) NotifyPingComplete(other *memberlist.Node, rtt time.Duration, payload []byte) { if payload == nil || len(payload) == 0 { return } // Verify ping version in the header. version := payload[0] if version != PingVersion { p.serf.logger.Printf("[ERR] serf: Unsupported ping version: %v", version) return } // Process the remainder of the message as a coordinate. r := bytes.NewReader(payload[1:]) dec := codec.NewDecoder(r, &codec.MsgpackHandle{}) var coord coordinate.Coordinate if err := dec.Decode(&coord); err != nil { p.serf.logger.Printf("[ERR] serf: Failed to decode coordinate from ping: %v", err) return } // Apply the update. before := p.serf.coordClient.GetCoordinate() after, err := p.serf.coordClient.Update(other.Name, &coord, rtt) if err != nil { metrics.IncrCounter([]string{"serf", "coordinate", "rejected"}, 1) p.serf.logger.Printf("[TRACE] serf: Rejected coordinate from %s: %v\n", other.Name, err) return } // Publish some metrics to give us an idea of how much we are // adjusting each time we update. d := float32(before.DistanceTo(after).Seconds() * 1.0e3) metrics.AddSample([]string{"serf", "coordinate", "adjustment-ms"}, d) // Cache the coordinate for the other node, and add our own // to the cache as well since it just got updated. This lets // users call GetCachedCoordinate with our node name, which is // more friendly. p.serf.coordCacheLock.Lock() p.serf.coordCache[other.Name] = &coord p.serf.coordCache[p.serf.config.NodeName] = p.serf.coordClient.GetCoordinate() p.serf.coordCacheLock.Unlock() }
[ "func", "(", "p", "*", "pingDelegate", ")", "NotifyPingComplete", "(", "other", "*", "memberlist", ".", "Node", ",", "rtt", "time", ".", "Duration", ",", "payload", "[", "]", "byte", ")", "{", "if", "payload", "==", "nil", "||", "len", "(", "payload", ...
// NotifyPingComplete is called when this node successfully completes a direct ping // of a peer node.
[ "NotifyPingComplete", "is", "called", "when", "this", "node", "successfully", "completes", "a", "direct", "ping", "of", "a", "peer", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/ping_delegate.go#L46-L90
166,107
hashicorp/serf
cmd/serf/command/agent/ipc.go
RegisterQuery
func (c *IPCClient) RegisterQuery(q *serf.Query) uint64 { // Generate a unique-per-client ID id := c.nextQueryID() // Ensure the query deadline is in the future timeout := q.Deadline().Sub(time.Now()) if timeout < 0 { return id } // Register the query c.queryLock.Lock() c.pendingQueries[id] = q c.queryLock.Unlock() // Setup a timer to deregister after the timeout time.AfterFunc(timeout, func() { c.queryLock.Lock() delete(c.pendingQueries, id) c.queryLock.Unlock() }) return id }
go
func (c *IPCClient) RegisterQuery(q *serf.Query) uint64 { // Generate a unique-per-client ID id := c.nextQueryID() // Ensure the query deadline is in the future timeout := q.Deadline().Sub(time.Now()) if timeout < 0 { return id } // Register the query c.queryLock.Lock() c.pendingQueries[id] = q c.queryLock.Unlock() // Setup a timer to deregister after the timeout time.AfterFunc(timeout, func() { c.queryLock.Lock() delete(c.pendingQueries, id) c.queryLock.Unlock() }) return id }
[ "func", "(", "c", "*", "IPCClient", ")", "RegisterQuery", "(", "q", "*", "serf", ".", "Query", ")", "uint64", "{", "// Generate a unique-per-client ID", "id", ":=", "c", ".", "nextQueryID", "(", ")", "\n\n", "// Ensure the query deadline is in the future", "timeou...
// RegisterQuery is used to register a pending query that may // get a response. The ID of the query is returned
[ "RegisterQuery", "is", "used", "to", "register", "a", "pending", "query", "that", "may", "get", "a", "response", ".", "The", "ID", "of", "the", "query", "is", "returned" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L303-L325
166,108
hashicorp/serf
cmd/serf/command/agent/ipc.go
NewAgentIPC
func NewAgentIPC(agent *Agent, authKey string, listener net.Listener, logOutput io.Writer, logWriter *logWriter) *AgentIPC { if logOutput == nil { logOutput = os.Stderr } ipc := &AgentIPC{ agent: agent, authKey: authKey, clients: make(map[string]*IPCClient), listener: listener, logger: log.New(logOutput, "", log.LstdFlags), logWriter: logWriter, stopCh: make(chan struct{}), } go ipc.listen() return ipc }
go
func NewAgentIPC(agent *Agent, authKey string, listener net.Listener, logOutput io.Writer, logWriter *logWriter) *AgentIPC { if logOutput == nil { logOutput = os.Stderr } ipc := &AgentIPC{ agent: agent, authKey: authKey, clients: make(map[string]*IPCClient), listener: listener, logger: log.New(logOutput, "", log.LstdFlags), logWriter: logWriter, stopCh: make(chan struct{}), } go ipc.listen() return ipc }
[ "func", "NewAgentIPC", "(", "agent", "*", "Agent", ",", "authKey", "string", ",", "listener", "net", ".", "Listener", ",", "logOutput", "io", ".", "Writer", ",", "logWriter", "*", "logWriter", ")", "*", "AgentIPC", "{", "if", "logOutput", "==", "nil", "{...
// NewAgentIPC is used to create a new Agent IPC handler
[ "NewAgentIPC", "is", "used", "to", "create", "a", "new", "Agent", "IPC", "handler" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L328-L344
166,109
hashicorp/serf
cmd/serf/command/agent/ipc.go
Shutdown
func (i *AgentIPC) Shutdown() { i.Lock() defer i.Unlock() if i.stop { return } i.stop = true close(i.stopCh) i.listener.Close() // Close the existing connections for _, client := range i.clients { client.conn.Close() } }
go
func (i *AgentIPC) Shutdown() { i.Lock() defer i.Unlock() if i.stop { return } i.stop = true close(i.stopCh) i.listener.Close() // Close the existing connections for _, client := range i.clients { client.conn.Close() } }
[ "func", "(", "i", "*", "AgentIPC", ")", "Shutdown", "(", ")", "{", "i", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "Unlock", "(", ")", "\n\n", "if", "i", ".", "stop", "{", "return", "\n", "}", "\n\n", "i", ".", "stop", "=", "true", "\n",...
// Shutdown is used to shutdown the IPC layer
[ "Shutdown", "is", "used", "to", "shutdown", "the", "IPC", "layer" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L347-L363
166,110
hashicorp/serf
cmd/serf/command/agent/ipc.go
listen
func (i *AgentIPC) listen() { for { conn, err := i.listener.Accept() if err != nil { if i.stop { return } i.logger.Printf("[ERR] agent.ipc: Failed to accept client: %v", err) continue } i.logger.Printf("[INFO] agent.ipc: Accepted client: %v", conn.RemoteAddr()) metrics.IncrCounter([]string{"agent", "ipc", "accept"}, 1) // Wrap the connection in a client client := &IPCClient{ name: conn.RemoteAddr().String(), conn: conn, reader: bufio.NewReader(conn), writer: bufio.NewWriter(conn), eventStreams: make(map[uint64]*eventStream), pendingQueries: make(map[uint64]*serf.Query), } client.dec = codec.NewDecoder(client.reader, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) client.enc = codec.NewEncoder(client.writer, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) // Register the client i.Lock() if !i.stop { i.clients[client.name] = client go i.handleClient(client) } else { conn.Close() } i.Unlock() } }
go
func (i *AgentIPC) listen() { for { conn, err := i.listener.Accept() if err != nil { if i.stop { return } i.logger.Printf("[ERR] agent.ipc: Failed to accept client: %v", err) continue } i.logger.Printf("[INFO] agent.ipc: Accepted client: %v", conn.RemoteAddr()) metrics.IncrCounter([]string{"agent", "ipc", "accept"}, 1) // Wrap the connection in a client client := &IPCClient{ name: conn.RemoteAddr().String(), conn: conn, reader: bufio.NewReader(conn), writer: bufio.NewWriter(conn), eventStreams: make(map[uint64]*eventStream), pendingQueries: make(map[uint64]*serf.Query), } client.dec = codec.NewDecoder(client.reader, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) client.enc = codec.NewEncoder(client.writer, &codec.MsgpackHandle{RawToString: true, WriteExt: true}) // Register the client i.Lock() if !i.stop { i.clients[client.name] = client go i.handleClient(client) } else { conn.Close() } i.Unlock() } }
[ "func", "(", "i", "*", "AgentIPC", ")", "listen", "(", ")", "{", "for", "{", "conn", ",", "err", ":=", "i", ".", "listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "i", ".", "stop", "{", "return", "\n", "}", "\n",...
// listen is a long running routine that listens for new clients
[ "listen", "is", "a", "long", "running", "routine", "that", "listens", "for", "new", "clients" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L366-L403
166,111
hashicorp/serf
cmd/serf/command/agent/ipc.go
deregisterClient
func (i *AgentIPC) deregisterClient(client *IPCClient) { // Close the socket client.conn.Close() // Remove from the clients list i.Lock() delete(i.clients, client.name) i.Unlock() // Remove from the log writer if client.logStreamer != nil { i.logWriter.DeregisterHandler(client.logStreamer) client.logStreamer.Stop() } // Remove from event handlers for _, es := range client.eventStreams { i.agent.DeregisterEventHandler(es) es.Stop() } }
go
func (i *AgentIPC) deregisterClient(client *IPCClient) { // Close the socket client.conn.Close() // Remove from the clients list i.Lock() delete(i.clients, client.name) i.Unlock() // Remove from the log writer if client.logStreamer != nil { i.logWriter.DeregisterHandler(client.logStreamer) client.logStreamer.Stop() } // Remove from event handlers for _, es := range client.eventStreams { i.agent.DeregisterEventHandler(es) es.Stop() } }
[ "func", "(", "i", "*", "AgentIPC", ")", "deregisterClient", "(", "client", "*", "IPCClient", ")", "{", "// Close the socket", "client", ".", "conn", ".", "Close", "(", ")", "\n\n", "// Remove from the clients list", "i", ".", "Lock", "(", ")", "\n", "delete"...
// deregisterClient is called to cleanup after a client disconnects
[ "deregisterClient", "is", "called", "to", "cleanup", "after", "a", "client", "disconnects" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L406-L426
166,112
hashicorp/serf
cmd/serf/command/agent/ipc.go
handleClient
func (i *AgentIPC) handleClient(client *IPCClient) { defer i.deregisterClient(client) var reqHeader requestHeader for { // Decode the header if err := client.dec.Decode(&reqHeader); err != nil { if !i.stop { // The second part of this if is to block socket // errors from Windows which appear to happen every // time there is an EOF. if err != io.EOF && !strings.Contains(strings.ToLower(err.Error()), "wsarecv") { i.logger.Printf("[ERR] agent.ipc: failed to decode request header: %v", err) } } return } // Evaluate the command if err := i.handleRequest(client, &reqHeader); err != nil { i.logger.Printf("[ERR] agent.ipc: Failed to evaluate request: %v", err) return } } }
go
func (i *AgentIPC) handleClient(client *IPCClient) { defer i.deregisterClient(client) var reqHeader requestHeader for { // Decode the header if err := client.dec.Decode(&reqHeader); err != nil { if !i.stop { // The second part of this if is to block socket // errors from Windows which appear to happen every // time there is an EOF. if err != io.EOF && !strings.Contains(strings.ToLower(err.Error()), "wsarecv") { i.logger.Printf("[ERR] agent.ipc: failed to decode request header: %v", err) } } return } // Evaluate the command if err := i.handleRequest(client, &reqHeader); err != nil { i.logger.Printf("[ERR] agent.ipc: Failed to evaluate request: %v", err) return } } }
[ "func", "(", "i", "*", "AgentIPC", ")", "handleClient", "(", "client", "*", "IPCClient", ")", "{", "defer", "i", ".", "deregisterClient", "(", "client", ")", "\n", "var", "reqHeader", "requestHeader", "\n", "for", "{", "// Decode the header", "if", "err", ...
// handleClient is a long running routine that handles a single client
[ "handleClient", "is", "a", "long", "running", "routine", "that", "handles", "a", "single", "client" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L429-L452
166,113
hashicorp/serf
cmd/serf/command/agent/ipc.go
handleRequest
func (i *AgentIPC) handleRequest(client *IPCClient, reqHeader *requestHeader) error { // Look for a command field command := reqHeader.Command seq := reqHeader.Seq // Ensure the handshake is performed before other commands if command != handshakeCommand && client.version == 0 { respHeader := responseHeader{Seq: seq, Error: handshakeRequired} client.Send(&respHeader, nil) return fmt.Errorf(handshakeRequired) } metrics.IncrCounter([]string{"agent", "ipc", "command"}, 1) // Ensure the client has authenticated after the handshake if necessary if i.authKey != "" && !client.didAuth && command != authCommand && command != handshakeCommand { i.logger.Printf("[WARN] agent.ipc: Client sending commands before auth") respHeader := responseHeader{Seq: seq, Error: authRequired} client.Send(&respHeader, nil) return nil } // Dispatch command specific handlers switch command { case handshakeCommand: return i.handleHandshake(client, seq) case authCommand: return i.handleAuth(client, seq) case eventCommand: return i.handleEvent(client, seq) case membersCommand, membersFilteredCommand: return i.handleMembers(client, command, seq) case streamCommand: return i.handleStream(client, seq) case monitorCommand: return i.handleMonitor(client, seq) case stopCommand: return i.handleStop(client, seq) case forceLeaveCommand: return i.handleForceLeave(client, seq) case joinCommand: return i.handleJoin(client, seq) case leaveCommand: return i.handleLeave(client, seq) case installKeyCommand: return i.handleInstallKey(client, seq) case useKeyCommand: return i.handleUseKey(client, seq) case removeKeyCommand: return i.handleRemoveKey(client, seq) case listKeysCommand: return i.handleListKeys(client, seq) case tagsCommand: return i.handleTags(client, seq) case queryCommand: return i.handleQuery(client, seq) case respondCommand: return i.handleRespond(client, seq) case statsCommand: return i.handleStats(client, seq) case getCoordinateCommand: return i.handleGetCoordinate(client, seq) default: respHeader := responseHeader{Seq: seq, Error: unsupportedCommand} client.Send(&respHeader, nil) return fmt.Errorf("command '%s' not recognized", command) } }
go
func (i *AgentIPC) handleRequest(client *IPCClient, reqHeader *requestHeader) error { // Look for a command field command := reqHeader.Command seq := reqHeader.Seq // Ensure the handshake is performed before other commands if command != handshakeCommand && client.version == 0 { respHeader := responseHeader{Seq: seq, Error: handshakeRequired} client.Send(&respHeader, nil) return fmt.Errorf(handshakeRequired) } metrics.IncrCounter([]string{"agent", "ipc", "command"}, 1) // Ensure the client has authenticated after the handshake if necessary if i.authKey != "" && !client.didAuth && command != authCommand && command != handshakeCommand { i.logger.Printf("[WARN] agent.ipc: Client sending commands before auth") respHeader := responseHeader{Seq: seq, Error: authRequired} client.Send(&respHeader, nil) return nil } // Dispatch command specific handlers switch command { case handshakeCommand: return i.handleHandshake(client, seq) case authCommand: return i.handleAuth(client, seq) case eventCommand: return i.handleEvent(client, seq) case membersCommand, membersFilteredCommand: return i.handleMembers(client, command, seq) case streamCommand: return i.handleStream(client, seq) case monitorCommand: return i.handleMonitor(client, seq) case stopCommand: return i.handleStop(client, seq) case forceLeaveCommand: return i.handleForceLeave(client, seq) case joinCommand: return i.handleJoin(client, seq) case leaveCommand: return i.handleLeave(client, seq) case installKeyCommand: return i.handleInstallKey(client, seq) case useKeyCommand: return i.handleUseKey(client, seq) case removeKeyCommand: return i.handleRemoveKey(client, seq) case listKeysCommand: return i.handleListKeys(client, seq) case tagsCommand: return i.handleTags(client, seq) case queryCommand: return i.handleQuery(client, seq) case respondCommand: return i.handleRespond(client, seq) case statsCommand: return i.handleStats(client, seq) case getCoordinateCommand: return i.handleGetCoordinate(client, seq) default: respHeader := responseHeader{Seq: seq, Error: unsupportedCommand} client.Send(&respHeader, nil) return fmt.Errorf("command '%s' not recognized", command) } }
[ "func", "(", "i", "*", "AgentIPC", ")", "handleRequest", "(", "client", "*", "IPCClient", ",", "reqHeader", "*", "requestHeader", ")", "error", "{", "// Look for a command field", "command", ":=", "reqHeader", ".", "Command", "\n", "seq", ":=", "reqHeader", "....
// handleRequest is used to evaluate a single client command
[ "handleRequest", "is", "used", "to", "evaluate", "a", "single", "client", "command" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L455-L540
166,114
hashicorp/serf
cmd/serf/command/agent/ipc.go
handleStats
func (i *AgentIPC) handleStats(client *IPCClient, seq uint64) error { header := responseHeader{ Seq: seq, Error: "", } resp := i.agent.Stats() return client.Send(&header, resp) }
go
func (i *AgentIPC) handleStats(client *IPCClient, seq uint64) error { header := responseHeader{ Seq: seq, Error: "", } resp := i.agent.Stats() return client.Send(&header, resp) }
[ "func", "(", "i", "*", "AgentIPC", ")", "handleStats", "(", "client", "*", "IPCClient", ",", "seq", "uint64", ")", "error", "{", "header", ":=", "responseHeader", "{", "Seq", ":", "seq", ",", "Error", ":", "\"", "\"", ",", "}", "\n", "resp", ":=", ...
// handleStats is used to get various statistics
[ "handleStats", "is", "used", "to", "get", "various", "statistics" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L1030-L1037
166,115
hashicorp/serf
cmd/serf/command/agent/ipc.go
handleGetCoordinate
func (i *AgentIPC) handleGetCoordinate(client *IPCClient, seq uint64) error { var req coordinateRequest if err := client.dec.Decode(&req); err != nil { return fmt.Errorf("decode failed: %v", err) } // Fetch the coordinate. var result coordinate.Coordinate coord, ok := i.agent.Serf().GetCachedCoordinate(req.Node) if ok { result = *coord } // Respond header := responseHeader{ Seq: seq, Error: errToString(nil), } resp := coordinateResponse{ Coord: result, Ok: ok, } return client.Send(&header, &resp) }
go
func (i *AgentIPC) handleGetCoordinate(client *IPCClient, seq uint64) error { var req coordinateRequest if err := client.dec.Decode(&req); err != nil { return fmt.Errorf("decode failed: %v", err) } // Fetch the coordinate. var result coordinate.Coordinate coord, ok := i.agent.Serf().GetCachedCoordinate(req.Node) if ok { result = *coord } // Respond header := responseHeader{ Seq: seq, Error: errToString(nil), } resp := coordinateResponse{ Coord: result, Ok: ok, } return client.Send(&header, &resp) }
[ "func", "(", "i", "*", "AgentIPC", ")", "handleGetCoordinate", "(", "client", "*", "IPCClient", ",", "seq", "uint64", ")", "error", "{", "var", "req", "coordinateRequest", "\n", "if", "err", ":=", "client", ".", "dec", ".", "Decode", "(", "&", "req", "...
// handleGetCoordinate is used to get the cached coordinate for a node.
[ "handleGetCoordinate", "is", "used", "to", "get", "the", "cached", "coordinate", "for", "a", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc.go#L1040-L1063
166,116
hashicorp/serf
cmd/serf/command/agent/event_handler.go
UpdateScripts
func (h *ScriptEventHandler) UpdateScripts(scripts []EventScript) { h.scriptLock.Lock() defer h.scriptLock.Unlock() h.newScripts = scripts }
go
func (h *ScriptEventHandler) UpdateScripts(scripts []EventScript) { h.scriptLock.Lock() defer h.scriptLock.Unlock() h.newScripts = scripts }
[ "func", "(", "h", "*", "ScriptEventHandler", ")", "UpdateScripts", "(", "scripts", "[", "]", "EventScript", ")", "{", "h", ".", "scriptLock", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "scriptLock", ".", "Unlock", "(", ")", "\n", "h", ".", "newS...
// UpdateScripts is used to safely update the scripts we invoke in // a thread safe manner
[ "UpdateScripts", "is", "used", "to", "safely", "update", "the", "scripts", "we", "invoke", "in", "a", "thread", "safe", "manner" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/event_handler.go#L57-L61
166,117
hashicorp/serf
cmd/serf/command/agent/event_handler.go
Invoke
func (s *EventFilter) Invoke(e serf.Event) bool { if s.Event == "*" { return true } if e.EventType().String() != s.Event { return false } if s.Event == "user" && s.Name != "" { userE, ok := e.(serf.UserEvent) if !ok { return false } if userE.Name != s.Name { return false } } if s.Event == "query" && s.Name != "" { query, ok := e.(*serf.Query) if !ok { return false } if query.Name != s.Name { return false } } return true }
go
func (s *EventFilter) Invoke(e serf.Event) bool { if s.Event == "*" { return true } if e.EventType().String() != s.Event { return false } if s.Event == "user" && s.Name != "" { userE, ok := e.(serf.UserEvent) if !ok { return false } if userE.Name != s.Name { return false } } if s.Event == "query" && s.Name != "" { query, ok := e.(*serf.Query) if !ok { return false } if query.Name != s.Name { return false } } return true }
[ "func", "(", "s", "*", "EventFilter", ")", "Invoke", "(", "e", "serf", ".", "Event", ")", "bool", "{", "if", "s", ".", "Event", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n\n", "if", "e", ".", "EventType", "(", ")", ".", "String", "(...
// Invoke tests whether or not this event script should be invoked // for the given Serf event.
[ "Invoke", "tests", "whether", "or", "not", "this", "event", "script", "should", "be", "invoked", "for", "the", "given", "Serf", "event", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/event_handler.go#L71-L103
166,118
hashicorp/serf
cmd/serf/command/agent/event_handler.go
ParseEventScript
func ParseEventScript(v string) []EventScript { var filter, script string parts := strings.SplitN(v, "=", 2) if len(parts) == 1 { script = parts[0] } else { filter = parts[0] script = parts[1] } filters := ParseEventFilter(filter) results := make([]EventScript, 0, len(filters)) for _, filt := range filters { result := EventScript{ EventFilter: filt, Script: script, } results = append(results, result) } return results }
go
func ParseEventScript(v string) []EventScript { var filter, script string parts := strings.SplitN(v, "=", 2) if len(parts) == 1 { script = parts[0] } else { filter = parts[0] script = parts[1] } filters := ParseEventFilter(filter) results := make([]EventScript, 0, len(filters)) for _, filt := range filters { result := EventScript{ EventFilter: filt, Script: script, } results = append(results, result) } return results }
[ "func", "ParseEventScript", "(", "v", "string", ")", "[", "]", "EventScript", "{", "var", "filter", ",", "script", "string", "\n", "parts", ":=", "strings", ".", "SplitN", "(", "v", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parts", "...
// ParseEventScript takes a string in the format of "type=script" and // parses it into an EventScript struct, if it can.
[ "ParseEventScript", "takes", "a", "string", "in", "the", "format", "of", "type", "=", "script", "and", "parses", "it", "into", "an", "EventScript", "struct", "if", "it", "can", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/event_handler.go#L139-L159
166,119
hashicorp/serf
cmd/serf/command/agent/event_handler.go
ParseEventFilter
func ParseEventFilter(v string) []EventFilter { // No filter translates to stream all if v == "" { v = "*" } events := strings.Split(v, ",") results := make([]EventFilter, 0, len(events)) for _, event := range events { var result EventFilter var name string if strings.HasPrefix(event, "user:") { name = event[len("user:"):] event = "user" } else if strings.HasPrefix(event, "query:") { name = event[len("query:"):] event = "query" } result.Event = event result.Name = name results = append(results, result) } return results }
go
func ParseEventFilter(v string) []EventFilter { // No filter translates to stream all if v == "" { v = "*" } events := strings.Split(v, ",") results := make([]EventFilter, 0, len(events)) for _, event := range events { var result EventFilter var name string if strings.HasPrefix(event, "user:") { name = event[len("user:"):] event = "user" } else if strings.HasPrefix(event, "query:") { name = event[len("query:"):] event = "query" } result.Event = event result.Name = name results = append(results, result) } return results }
[ "func", "ParseEventFilter", "(", "v", "string", ")", "[", "]", "EventFilter", "{", "// No filter translates to stream all", "if", "v", "==", "\"", "\"", "{", "v", "=", "\"", "\"", "\n", "}", "\n\n", "events", ":=", "strings", ".", "Split", "(", "v", ",",...
// ParseEventFilter a string with the event type filters and // parses it into a series of EventFilters if it can.
[ "ParseEventFilter", "a", "string", "with", "the", "event", "type", "filters", "and", "parses", "it", "into", "a", "series", "of", "EventFilters", "if", "it", "can", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/event_handler.go#L163-L189
166,120
hashicorp/serf
cmd/serf/command/rpc.go
RPCAddrFlag
func RPCAddrFlag(f *flag.FlagSet) *string { defaultRpcAddr := os.Getenv("SERF_RPC_ADDR") if defaultRpcAddr == "" { defaultRpcAddr = "127.0.0.1:7373" } return f.String("rpc-addr", defaultRpcAddr, "RPC address of the Serf agent") }
go
func RPCAddrFlag(f *flag.FlagSet) *string { defaultRpcAddr := os.Getenv("SERF_RPC_ADDR") if defaultRpcAddr == "" { defaultRpcAddr = "127.0.0.1:7373" } return f.String("rpc-addr", defaultRpcAddr, "RPC address of the Serf agent") }
[ "func", "RPCAddrFlag", "(", "f", "*", "flag", ".", "FlagSet", ")", "*", "string", "{", "defaultRpcAddr", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "defaultRpcAddr", "==", "\"", "\"", "{", "defaultRpcAddr", "=", "\"", "\"", "\n", "}...
// RPCAddrFlag returns a pointer to a string that will be populated // when the given flagset is parsed with the RPC address of the Serf.
[ "RPCAddrFlag", "returns", "a", "pointer", "to", "a", "string", "that", "will", "be", "populated", "when", "the", "given", "flagset", "is", "parsed", "with", "the", "RPC", "address", "of", "the", "Serf", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/rpc.go#L12-L20
166,121
hashicorp/serf
cmd/serf/command/rpc.go
RPCAuthFlag
func RPCAuthFlag(f *flag.FlagSet) *string { rpcAuth := os.Getenv("SERF_RPC_AUTH") return f.String("rpc-auth", rpcAuth, "RPC auth token of the Serf agent") }
go
func RPCAuthFlag(f *flag.FlagSet) *string { rpcAuth := os.Getenv("SERF_RPC_AUTH") return f.String("rpc-auth", rpcAuth, "RPC auth token of the Serf agent") }
[ "func", "RPCAuthFlag", "(", "f", "*", "flag", ".", "FlagSet", ")", "*", "string", "{", "rpcAuth", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "return", "f", ".", "String", "(", "\"", "\"", ",", "rpcAuth", ",", "\"", "\"", ")", "\n", ...
// RPCAuthFlag returns a pointer to a string that will be populated // when the given flagset is parsed with the RPC auth token of the Serf.
[ "RPCAuthFlag", "returns", "a", "pointer", "to", "a", "string", "that", "will", "be", "populated", "when", "the", "given", "flagset", "is", "parsed", "with", "the", "RPC", "auth", "token", "of", "the", "Serf", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/rpc.go#L24-L28
166,122
hashicorp/serf
cmd/serf/command/rpc.go
RPCClient
func RPCClient(addr, auth string) (*client.RPCClient, error) { config := client.Config{Addr: addr, AuthKey: auth} return client.ClientFromConfig(&config) }
go
func RPCClient(addr, auth string) (*client.RPCClient, error) { config := client.Config{Addr: addr, AuthKey: auth} return client.ClientFromConfig(&config) }
[ "func", "RPCClient", "(", "addr", ",", "auth", "string", ")", "(", "*", "client", ".", "RPCClient", ",", "error", ")", "{", "config", ":=", "client", ".", "Config", "{", "Addr", ":", "addr", ",", "AuthKey", ":", "auth", "}", "\n", "return", "client",...
// RPCClient returns a new Serf RPC client with the given address.
[ "RPCClient", "returns", "a", "new", "Serf", "RPC", "client", "with", "the", "given", "address", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/rpc.go#L31-L34
166,123
hashicorp/serf
serf/keymanager.go
handleKeyRequest
func (k *KeyManager) handleKeyRequest(key, query string, opts *KeyRequestOptions) (*KeyResponse, error) { resp := &KeyResponse{ Messages: make(map[string]string), Keys: make(map[string]int), } qName := internalQueryName(query) // Decode the new key into raw bytes rawKey, err := base64.StdEncoding.DecodeString(key) if err != nil { return resp, err } // Encode the query request req, err := encodeMessage(messageKeyRequestType, keyRequest{Key: rawKey}) if err != nil { return resp, err } qParam := k.serf.DefaultQueryParams() if opts != nil { qParam.RelayFactor = opts.RelayFactor } queryResp, err := k.serf.Query(qName, req, qParam) if err != nil { return resp, err } // Handle the response stream and populate the KeyResponse resp.NumNodes = k.serf.memberlist.NumMembers() k.streamKeyResp(resp, queryResp.respCh) // Check the response for any reported failure conditions if resp.NumErr != 0 { return resp, fmt.Errorf("%d/%d nodes reported failure", resp.NumErr, resp.NumNodes) } if resp.NumResp != resp.NumNodes { return resp, fmt.Errorf("%d/%d nodes reported success", resp.NumResp, resp.NumNodes) } return resp, nil }
go
func (k *KeyManager) handleKeyRequest(key, query string, opts *KeyRequestOptions) (*KeyResponse, error) { resp := &KeyResponse{ Messages: make(map[string]string), Keys: make(map[string]int), } qName := internalQueryName(query) // Decode the new key into raw bytes rawKey, err := base64.StdEncoding.DecodeString(key) if err != nil { return resp, err } // Encode the query request req, err := encodeMessage(messageKeyRequestType, keyRequest{Key: rawKey}) if err != nil { return resp, err } qParam := k.serf.DefaultQueryParams() if opts != nil { qParam.RelayFactor = opts.RelayFactor } queryResp, err := k.serf.Query(qName, req, qParam) if err != nil { return resp, err } // Handle the response stream and populate the KeyResponse resp.NumNodes = k.serf.memberlist.NumMembers() k.streamKeyResp(resp, queryResp.respCh) // Check the response for any reported failure conditions if resp.NumErr != 0 { return resp, fmt.Errorf("%d/%d nodes reported failure", resp.NumErr, resp.NumNodes) } if resp.NumResp != resp.NumNodes { return resp, fmt.Errorf("%d/%d nodes reported success", resp.NumResp, resp.NumNodes) } return resp, nil }
[ "func", "(", "k", "*", "KeyManager", ")", "handleKeyRequest", "(", "key", ",", "query", "string", ",", "opts", "*", "KeyRequestOptions", ")", "(", "*", "KeyResponse", ",", "error", ")", "{", "resp", ":=", "&", "KeyResponse", "{", "Messages", ":", "make",...
// handleKeyRequest performs query broadcasting to all members for any type of // key operation and manages gathering responses and packing them up into a // KeyResponse for uniform response handling.
[ "handleKeyRequest", "performs", "query", "broadcasting", "to", "all", "members", "for", "any", "type", "of", "key", "operation", "and", "manages", "gathering", "responses", "and", "packing", "them", "up", "into", "a", "KeyResponse", "for", "uniform", "response", ...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/keymanager.go#L98-L139
166,124
hashicorp/serf
serf/keymanager.go
InstallKey
func (k *KeyManager) InstallKey(key string) (*KeyResponse, error) { return k.InstallKeyWithOptions(key, nil) }
go
func (k *KeyManager) InstallKey(key string) (*KeyResponse, error) { return k.InstallKeyWithOptions(key, nil) }
[ "func", "(", "k", "*", "KeyManager", ")", "InstallKey", "(", "key", "string", ")", "(", "*", "KeyResponse", ",", "error", ")", "{", "return", "k", ".", "InstallKeyWithOptions", "(", "key", ",", "nil", ")", "\n", "}" ]
// InstallKey handles broadcasting a query to all members and gathering // responses from each of them, returning a list of messages from each node // and any applicable error conditions.
[ "InstallKey", "handles", "broadcasting", "a", "query", "to", "all", "members", "and", "gathering", "responses", "from", "each", "of", "them", "returning", "a", "list", "of", "messages", "from", "each", "node", "and", "any", "applicable", "error", "conditions", ...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/keymanager.go#L144-L146
166,125
hashicorp/serf
serf/keymanager.go
UseKey
func (k *KeyManager) UseKey(key string) (*KeyResponse, error) { return k.UseKeyWithOptions(key, nil) }
go
func (k *KeyManager) UseKey(key string) (*KeyResponse, error) { return k.UseKeyWithOptions(key, nil) }
[ "func", "(", "k", "*", "KeyManager", ")", "UseKey", "(", "key", "string", ")", "(", "*", "KeyResponse", ",", "error", ")", "{", "return", "k", ".", "UseKeyWithOptions", "(", "key", ",", "nil", ")", "\n", "}" ]
// UseKey handles broadcasting a primary key change to all members in the // cluster, and gathering any response messages. If successful, there should // be an empty KeyResponse returned.
[ "UseKey", "handles", "broadcasting", "a", "primary", "key", "change", "to", "all", "members", "in", "the", "cluster", "and", "gathering", "any", "response", "messages", ".", "If", "successful", "there", "should", "be", "an", "empty", "KeyResponse", "returned", ...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/keymanager.go#L158-L160
166,126
hashicorp/serf
serf/keymanager.go
RemoveKey
func (k *KeyManager) RemoveKey(key string) (*KeyResponse, error) { return k.RemoveKeyWithOptions(key, nil) }
go
func (k *KeyManager) RemoveKey(key string) (*KeyResponse, error) { return k.RemoveKeyWithOptions(key, nil) }
[ "func", "(", "k", "*", "KeyManager", ")", "RemoveKey", "(", "key", "string", ")", "(", "*", "KeyResponse", ",", "error", ")", "{", "return", "k", ".", "RemoveKeyWithOptions", "(", "key", ",", "nil", ")", "\n", "}" ]
// RemoveKey handles broadcasting a key to the cluster for removal. Each member // will receive this event, and if they have the key in their keyring, remove // it. If any errors are encountered, RemoveKey will collect and relay them.
[ "RemoveKey", "handles", "broadcasting", "a", "key", "to", "the", "cluster", "for", "removal", ".", "Each", "member", "will", "receive", "this", "event", "and", "if", "they", "have", "the", "key", "in", "their", "keyring", "remove", "it", ".", "If", "any", ...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/keymanager.go#L172-L174
166,127
hashicorp/serf
cmd/serf/command/agent/command.go
setupLoggers
func (c *Command) setupLoggers(config *Config) (*GatedWriter, *logWriter, io.Writer) { // Setup logging. First create the gated log writer, which will // store logs until we're ready to show them. Then create the level // filter, filtering logs of the specified level. logGate := &GatedWriter{ Writer: &cli.UiWriter{Ui: c.Ui}, } c.logFilter = LevelFilter() c.logFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.LogLevel)) c.logFilter.Writer = logGate if !ValidateLevelFilter(c.logFilter.MinLevel, c.logFilter) { c.Ui.Error(fmt.Sprintf( "Invalid log level: %s. Valid log levels are: %v", c.logFilter.MinLevel, c.logFilter.Levels)) return nil, nil, nil } // Check if syslog is enabled var syslog io.Writer if config.EnableSyslog { l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, "serf") if err != nil { c.Ui.Error(fmt.Sprintf("Syslog setup failed: %v", err)) return nil, nil, nil } syslog = &SyslogWrapper{l, c.logFilter} } // Create a log writer, and wrap a logOutput around it logWriter := NewLogWriter(512) var logOutput io.Writer if syslog != nil { logOutput = io.MultiWriter(c.logFilter, logWriter, syslog) } else { logOutput = io.MultiWriter(c.logFilter, logWriter) } // Create a logger c.logger = log.New(logOutput, "", log.LstdFlags) return logGate, logWriter, logOutput }
go
func (c *Command) setupLoggers(config *Config) (*GatedWriter, *logWriter, io.Writer) { // Setup logging. First create the gated log writer, which will // store logs until we're ready to show them. Then create the level // filter, filtering logs of the specified level. logGate := &GatedWriter{ Writer: &cli.UiWriter{Ui: c.Ui}, } c.logFilter = LevelFilter() c.logFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.LogLevel)) c.logFilter.Writer = logGate if !ValidateLevelFilter(c.logFilter.MinLevel, c.logFilter) { c.Ui.Error(fmt.Sprintf( "Invalid log level: %s. Valid log levels are: %v", c.logFilter.MinLevel, c.logFilter.Levels)) return nil, nil, nil } // Check if syslog is enabled var syslog io.Writer if config.EnableSyslog { l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, "serf") if err != nil { c.Ui.Error(fmt.Sprintf("Syslog setup failed: %v", err)) return nil, nil, nil } syslog = &SyslogWrapper{l, c.logFilter} } // Create a log writer, and wrap a logOutput around it logWriter := NewLogWriter(512) var logOutput io.Writer if syslog != nil { logOutput = io.MultiWriter(c.logFilter, logWriter, syslog) } else { logOutput = io.MultiWriter(c.logFilter, logWriter) } // Create a logger c.logger = log.New(logOutput, "", log.LstdFlags) return logGate, logWriter, logOutput }
[ "func", "(", "c", "*", "Command", ")", "setupLoggers", "(", "config", "*", "Config", ")", "(", "*", "GatedWriter", ",", "*", "logWriter", ",", "io", ".", "Writer", ")", "{", "// Setup logging. First create the gated log writer, which will", "// store logs until we'r...
// setupLoggers is used to setup the logGate, logWriter, and our logOutput
[ "setupLoggers", "is", "used", "to", "setup", "the", "logGate", "logWriter", "and", "our", "logOutput" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/command.go#L362-L403
166,128
hashicorp/serf
cmd/serf/command/agent/command.go
retryJoin
func (c *Command) retryJoin(config *Config, agent *Agent, errCh chan struct{}) { // Quit fast if there is no nodes to join if len(config.RetryJoin) == 0 { return } // Track the number of join attempts attempt := 0 for { // Try to perform the join c.logger.Printf("[INFO] agent: Joining cluster...(replay: %v)", config.ReplayOnJoin) n, err := agent.Join(config.RetryJoin, config.ReplayOnJoin) if err == nil { c.logger.Printf("[INFO] agent: Join completed. Synced with %d initial agents", n) return } // Check if the maximum attempts has been exceeded attempt++ if config.RetryMaxAttempts > 0 && attempt > config.RetryMaxAttempts { c.logger.Printf("[ERR] agent: maximum retry join attempts made, exiting") close(errCh) return } // Log the failure and sleep c.logger.Printf("[WARN] agent: Join failed: %v, retrying in %v", err, config.RetryInterval) time.Sleep(config.RetryInterval) } }
go
func (c *Command) retryJoin(config *Config, agent *Agent, errCh chan struct{}) { // Quit fast if there is no nodes to join if len(config.RetryJoin) == 0 { return } // Track the number of join attempts attempt := 0 for { // Try to perform the join c.logger.Printf("[INFO] agent: Joining cluster...(replay: %v)", config.ReplayOnJoin) n, err := agent.Join(config.RetryJoin, config.ReplayOnJoin) if err == nil { c.logger.Printf("[INFO] agent: Join completed. Synced with %d initial agents", n) return } // Check if the maximum attempts has been exceeded attempt++ if config.RetryMaxAttempts > 0 && attempt > config.RetryMaxAttempts { c.logger.Printf("[ERR] agent: maximum retry join attempts made, exiting") close(errCh) return } // Log the failure and sleep c.logger.Printf("[WARN] agent: Join failed: %v, retrying in %v", err, config.RetryInterval) time.Sleep(config.RetryInterval) } }
[ "func", "(", "c", "*", "Command", ")", "retryJoin", "(", "config", "*", "Config", ",", "agent", "*", "Agent", ",", "errCh", "chan", "struct", "{", "}", ")", "{", "// Quit fast if there is no nodes to join", "if", "len", "(", "config", ".", "RetryJoin", ")"...
// retryJoin is invoked to handle joins with retries. This runs until at least a // single successful join or RetryMaxAttempts is reached
[ "retryJoin", "is", "invoked", "to", "handle", "joins", "with", "retries", ".", "This", "runs", "until", "at", "least", "a", "single", "successful", "join", "or", "RetryMaxAttempts", "is", "reached" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/command.go#L494-L523
166,129
hashicorp/serf
cmd/serf/command/agent/config.go
DefaultConfig
func DefaultConfig() *Config { return &Config{ DisableCoordinates: false, Tags: make(map[string]string), BindAddr: "0.0.0.0", AdvertiseAddr: "", LogLevel: "INFO", RPCAddr: "127.0.0.1:7373", Protocol: serf.ProtocolVersionMax, ReplayOnJoin: false, Profile: "lan", RetryInterval: 30 * time.Second, SyslogFacility: "LOCAL0", QueryResponseSizeLimit: 1024, QuerySizeLimit: 1024, UserEventSizeLimit: 512, BroadcastTimeout: 5 * time.Second, } }
go
func DefaultConfig() *Config { return &Config{ DisableCoordinates: false, Tags: make(map[string]string), BindAddr: "0.0.0.0", AdvertiseAddr: "", LogLevel: "INFO", RPCAddr: "127.0.0.1:7373", Protocol: serf.ProtocolVersionMax, ReplayOnJoin: false, Profile: "lan", RetryInterval: 30 * time.Second, SyslogFacility: "LOCAL0", QueryResponseSizeLimit: 1024, QuerySizeLimit: 1024, UserEventSizeLimit: 512, BroadcastTimeout: 5 * time.Second, } }
[ "func", "DefaultConfig", "(", ")", "*", "Config", "{", "return", "&", "Config", "{", "DisableCoordinates", ":", "false", ",", "Tags", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "BindAddr", ":", "\"", "\"", ",", "AdvertiseAddr", ":...
// DefaultConfig contains the defaults for configurations.
[ "DefaultConfig", "contains", "the", "defaults", "for", "configurations", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L23-L41
166,130
hashicorp/serf
cmd/serf/command/agent/config.go
AddrParts
func (c *Config) AddrParts(address string) (string, int, error) { checkAddr := address START: _, _, err := net.SplitHostPort(checkAddr) if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" { checkAddr = fmt.Sprintf("%s:%d", checkAddr, DefaultBindPort) goto START } if err != nil { return "", 0, err } // Get the address addr, err := net.ResolveTCPAddr("tcp", checkAddr) if err != nil { return "", 0, err } return addr.IP.String(), addr.Port, nil }
go
func (c *Config) AddrParts(address string) (string, int, error) { checkAddr := address START: _, _, err := net.SplitHostPort(checkAddr) if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" { checkAddr = fmt.Sprintf("%s:%d", checkAddr, DefaultBindPort) goto START } if err != nil { return "", 0, err } // Get the address addr, err := net.ResolveTCPAddr("tcp", checkAddr) if err != nil { return "", 0, err } return addr.IP.String(), addr.Port, nil }
[ "func", "(", "c", "*", "Config", ")", "AddrParts", "(", "address", "string", ")", "(", "string", ",", "int", ",", "error", ")", "{", "checkAddr", ":=", "address", "\n\n", "START", ":", "_", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "...
// BindAddrParts returns the parts of the BindAddr that should be // used to configure Serf.
[ "BindAddrParts", "returns", "the", "parts", "of", "the", "BindAddr", "that", "should", "be", "used", "to", "configure", "Serf", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L234-L254
166,131
hashicorp/serf
cmd/serf/command/agent/config.go
EventScripts
func (c *Config) EventScripts() []EventScript { result := make([]EventScript, 0, len(c.EventHandlers)) for _, v := range c.EventHandlers { part := ParseEventScript(v) result = append(result, part...) } return result }
go
func (c *Config) EventScripts() []EventScript { result := make([]EventScript, 0, len(c.EventHandlers)) for _, v := range c.EventHandlers { part := ParseEventScript(v) result = append(result, part...) } return result }
[ "func", "(", "c", "*", "Config", ")", "EventScripts", "(", ")", "[", "]", "EventScript", "{", "result", ":=", "make", "(", "[", "]", "EventScript", ",", "0", ",", "len", "(", "c", ".", "EventHandlers", ")", ")", "\n", "for", "_", ",", "v", ":=", ...
// EventScripts returns the list of EventScripts associated with this // configuration and specified by the "event_handlers" configuration.
[ "EventScripts", "returns", "the", "list", "of", "EventScripts", "associated", "with", "this", "configuration", "and", "specified", "by", "the", "event_handlers", "configuration", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L263-L270
166,132
hashicorp/serf
cmd/serf/command/agent/config.go
NetworkInterface
func (c *Config) NetworkInterface() (*net.Interface, error) { if c.Interface == "" { return nil, nil } return net.InterfaceByName(c.Interface) }
go
func (c *Config) NetworkInterface() (*net.Interface, error) { if c.Interface == "" { return nil, nil } return net.InterfaceByName(c.Interface) }
[ "func", "(", "c", "*", "Config", ")", "NetworkInterface", "(", ")", "(", "*", "net", ".", "Interface", ",", "error", ")", "{", "if", "c", ".", "Interface", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "net", ".",...
// Networkinterface is used to get the associated network // interface from the configured value
[ "Networkinterface", "is", "used", "to", "get", "the", "associated", "network", "interface", "from", "the", "configured", "value" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L274-L279
166,133
hashicorp/serf
cmd/serf/command/agent/config.go
DecodeConfig
func DecodeConfig(r io.Reader) (*Config, error) { var raw interface{} dec := json.NewDecoder(r) if err := dec.Decode(&raw); err != nil { return nil, err } // Decode var md mapstructure.Metadata var result Config msdec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Metadata: &md, Result: &result, ErrorUnused: true, }) if err != nil { return nil, err } if err := msdec.Decode(raw); err != nil { return nil, err } // Decode the time values if result.ReconnectIntervalRaw != "" { dur, err := time.ParseDuration(result.ReconnectIntervalRaw) if err != nil { return nil, err } result.ReconnectInterval = dur } if result.ReconnectTimeoutRaw != "" { dur, err := time.ParseDuration(result.ReconnectTimeoutRaw) if err != nil { return nil, err } result.ReconnectTimeout = dur } if result.TombstoneTimeoutRaw != "" { dur, err := time.ParseDuration(result.TombstoneTimeoutRaw) if err != nil { return nil, err } result.TombstoneTimeout = dur } if result.RetryIntervalRaw != "" { dur, err := time.ParseDuration(result.RetryIntervalRaw) if err != nil { return nil, err } result.RetryInterval = dur } if result.BroadcastTimeoutRaw != "" { dur, err := time.ParseDuration(result.BroadcastTimeoutRaw) if err != nil { return nil, err } result.BroadcastTimeout = dur } return &result, nil }
go
func DecodeConfig(r io.Reader) (*Config, error) { var raw interface{} dec := json.NewDecoder(r) if err := dec.Decode(&raw); err != nil { return nil, err } // Decode var md mapstructure.Metadata var result Config msdec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Metadata: &md, Result: &result, ErrorUnused: true, }) if err != nil { return nil, err } if err := msdec.Decode(raw); err != nil { return nil, err } // Decode the time values if result.ReconnectIntervalRaw != "" { dur, err := time.ParseDuration(result.ReconnectIntervalRaw) if err != nil { return nil, err } result.ReconnectInterval = dur } if result.ReconnectTimeoutRaw != "" { dur, err := time.ParseDuration(result.ReconnectTimeoutRaw) if err != nil { return nil, err } result.ReconnectTimeout = dur } if result.TombstoneTimeoutRaw != "" { dur, err := time.ParseDuration(result.TombstoneTimeoutRaw) if err != nil { return nil, err } result.TombstoneTimeout = dur } if result.RetryIntervalRaw != "" { dur, err := time.ParseDuration(result.RetryIntervalRaw) if err != nil { return nil, err } result.RetryInterval = dur } if result.BroadcastTimeoutRaw != "" { dur, err := time.ParseDuration(result.BroadcastTimeoutRaw) if err != nil { return nil, err } result.BroadcastTimeout = dur } return &result, nil }
[ "func", "DecodeConfig", "(", "r", "io", ".", "Reader", ")", "(", "*", "Config", ",", "error", ")", "{", "var", "raw", "interface", "{", "}", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "r", ")", "\n", "if", "err", ":=", "dec", ".", "Decode...
// DecodeConfig reads the configuration from the given reader in JSON // format and decodes it into a proper Config structure.
[ "DecodeConfig", "reads", "the", "configuration", "from", "the", "given", "reader", "in", "JSON", "format", "and", "decodes", "it", "into", "a", "proper", "Config", "structure", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L283-L348
166,134
hashicorp/serf
cmd/serf/command/agent/config.go
containsKey
func containsKey(keys []string, key string) bool { for _, k := range keys { if k == key { return true } } return false }
go
func containsKey(keys []string, key string) bool { for _, k := range keys { if k == key { return true } } return false }
[ "func", "containsKey", "(", "keys", "[", "]", "string", ",", "key", "string", ")", "bool", "{", "for", "_", ",", "k", ":=", "range", "keys", "{", "if", "k", "==", "key", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", ...
// containsKey is used to check if a slice of string keys contains // another key
[ "containsKey", "is", "used", "to", "check", "if", "a", "slice", "of", "string", "keys", "contains", "another", "key" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L352-L359
166,135
hashicorp/serf
cmd/serf/command/agent/config.go
ReadConfigPaths
func ReadConfigPaths(paths []string) (*Config, error) { result := new(Config) for _, path := range paths { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", path, err) } fi, err := f.Stat() if err != nil { f.Close() return nil, fmt.Errorf("Error reading '%s': %s", path, err) } if !fi.IsDir() { config, err := DecodeConfig(f) f.Close() if err != nil { return nil, fmt.Errorf("Error decoding '%s': %s", path, err) } result = MergeConfig(result, config) continue } contents, err := f.Readdir(-1) f.Close() if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", path, err) } // Sort the contents, ensures lexical order sort.Sort(dirEnts(contents)) for _, fi := range contents { // Don't recursively read contents if fi.IsDir() { continue } // If it isn't a JSON file, ignore it if !strings.HasSuffix(fi.Name(), ".json") { continue } subpath := filepath.Join(path, fi.Name()) f, err := os.Open(subpath) if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", subpath, err) } config, err := DecodeConfig(f) f.Close() if err != nil { return nil, fmt.Errorf("Error decoding '%s': %s", subpath, err) } result = MergeConfig(result, config) } } return result, nil }
go
func ReadConfigPaths(paths []string) (*Config, error) { result := new(Config) for _, path := range paths { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", path, err) } fi, err := f.Stat() if err != nil { f.Close() return nil, fmt.Errorf("Error reading '%s': %s", path, err) } if !fi.IsDir() { config, err := DecodeConfig(f) f.Close() if err != nil { return nil, fmt.Errorf("Error decoding '%s': %s", path, err) } result = MergeConfig(result, config) continue } contents, err := f.Readdir(-1) f.Close() if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", path, err) } // Sort the contents, ensures lexical order sort.Sort(dirEnts(contents)) for _, fi := range contents { // Don't recursively read contents if fi.IsDir() { continue } // If it isn't a JSON file, ignore it if !strings.HasSuffix(fi.Name(), ".json") { continue } subpath := filepath.Join(path, fi.Name()) f, err := os.Open(subpath) if err != nil { return nil, fmt.Errorf("Error reading '%s': %s", subpath, err) } config, err := DecodeConfig(f) f.Close() if err != nil { return nil, fmt.Errorf("Error decoding '%s': %s", subpath, err) } result = MergeConfig(result, config) } } return result, nil }
[ "func", "ReadConfigPaths", "(", "paths", "[", "]", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "result", ":=", "new", "(", "Config", ")", "\n", "for", "_", ",", "path", ":=", "range", "paths", "{", "f", ",", "err", ":=", "os", ".",...
// ReadConfigPaths reads the paths in the given order to load configurations. // The paths can be to files or directories. If the path is a directory, // we read one directory deep and read any files ending in ".json" as // configuration files.
[ "ReadConfigPaths", "reads", "the", "paths", "in", "the", "given", "order", "to", "load", "configurations", ".", "The", "paths", "can", "be", "to", "files", "or", "directories", ".", "If", "the", "path", "is", "a", "directory", "we", "read", "one", "directo...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/config.go#L501-L565
166,136
hashicorp/serf
coordinate/phantom.go
GenerateClients
func GenerateClients(nodes int, config *Config) ([]*Client, error) { clients := make([]*Client, nodes) for i, _ := range clients { client, err := NewClient(config) if err != nil { return nil, err } clients[i] = client } return clients, nil }
go
func GenerateClients(nodes int, config *Config) ([]*Client, error) { clients := make([]*Client, nodes) for i, _ := range clients { client, err := NewClient(config) if err != nil { return nil, err } clients[i] = client } return clients, nil }
[ "func", "GenerateClients", "(", "nodes", "int", ",", "config", "*", "Config", ")", "(", "[", "]", "*", "Client", ",", "error", ")", "{", "clients", ":=", "make", "(", "[", "]", "*", "Client", ",", "nodes", ")", "\n", "for", "i", ",", "_", ":=", ...
// GenerateClients returns a slice with nodes number of clients, all with the // given config.
[ "GenerateClients", "returns", "a", "slice", "with", "nodes", "number", "of", "clients", "all", "with", "the", "given", "config", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L12-L23
166,137
hashicorp/serf
coordinate/phantom.go
GenerateLine
func GenerateLine(nodes int, spacing time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rtt := time.Duration(j-i) * spacing truth[i][j], truth[j][i] = rtt, rtt } } return truth }
go
func GenerateLine(nodes int, spacing time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rtt := time.Duration(j-i) * spacing truth[i][j], truth[j][i] = rtt, rtt } } return truth }
[ "func", "GenerateLine", "(", "nodes", "int", ",", "spacing", "time", ".", "Duration", ")", "[", "]", "[", "]", "time", ".", "Duration", "{", "truth", ":=", "make", "(", "[", "]", "[", "]", "time", ".", "Duration", ",", "nodes", ")", "\n", "for", ...
// GenerateLine returns a truth matrix as if all the nodes are in a straight linke // with the given spacing between them.
[ "GenerateLine", "returns", "a", "truth", "matrix", "as", "if", "all", "the", "nodes", "are", "in", "a", "straight", "linke", "with", "the", "given", "spacing", "between", "them", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L27-L40
166,138
hashicorp/serf
coordinate/phantom.go
GenerateGrid
func GenerateGrid(nodes int, spacing time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } n := int(math.Sqrt(float64(nodes))) for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { x1, y1 := float64(i%n), float64(i/n) x2, y2 := float64(j%n), float64(j/n) dx, dy := x2-x1, y2-y1 dist := math.Sqrt(dx*dx + dy*dy) rtt := time.Duration(dist * float64(spacing)) truth[i][j], truth[j][i] = rtt, rtt } } return truth }
go
func GenerateGrid(nodes int, spacing time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } n := int(math.Sqrt(float64(nodes))) for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { x1, y1 := float64(i%n), float64(i/n) x2, y2 := float64(j%n), float64(j/n) dx, dy := x2-x1, y2-y1 dist := math.Sqrt(dx*dx + dy*dy) rtt := time.Duration(dist * float64(spacing)) truth[i][j], truth[j][i] = rtt, rtt } } return truth }
[ "func", "GenerateGrid", "(", "nodes", "int", ",", "spacing", "time", ".", "Duration", ")", "[", "]", "[", "]", "time", ".", "Duration", "{", "truth", ":=", "make", "(", "[", "]", "[", "]", "time", ".", "Duration", ",", "nodes", ")", "\n", "for", ...
// GenerateGrid returns a truth matrix as if all the nodes are in a two dimensional // grid with the given spacing between them.
[ "GenerateGrid", "returns", "a", "truth", "matrix", "as", "if", "all", "the", "nodes", "are", "in", "a", "two", "dimensional", "grid", "with", "the", "given", "spacing", "between", "them", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L44-L62
166,139
hashicorp/serf
coordinate/phantom.go
GenerateSplit
func GenerateSplit(nodes int, lan time.Duration, wan time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } split := nodes / 2 for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rtt := lan if (i <= split && j > split) || (i > split && j <= split) { rtt += wan } truth[i][j], truth[j][i] = rtt, rtt } } return truth }
go
func GenerateSplit(nodes int, lan time.Duration, wan time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } split := nodes / 2 for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rtt := lan if (i <= split && j > split) || (i > split && j <= split) { rtt += wan } truth[i][j], truth[j][i] = rtt, rtt } } return truth }
[ "func", "GenerateSplit", "(", "nodes", "int", ",", "lan", "time", ".", "Duration", ",", "wan", "time", ".", "Duration", ")", "[", "]", "[", "]", "time", ".", "Duration", "{", "truth", ":=", "make", "(", "[", "]", "[", "]", "time", ".", "Duration", ...
// GenerateSplit returns a truth matrix as if half the nodes are close together in // one location and half the nodes are close together in another. The lan factor // is used to separate the nodes locally and the wan factor represents the split // between the two sides.
[ "GenerateSplit", "returns", "a", "truth", "matrix", "as", "if", "half", "the", "nodes", "are", "close", "together", "in", "one", "location", "and", "half", "the", "nodes", "are", "close", "together", "in", "another", ".", "The", "lan", "factor", "is", "use...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L68-L85
166,140
hashicorp/serf
coordinate/phantom.go
GenerateCircle
func GenerateCircle(nodes int, radius time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { var rtt time.Duration if i == 0 { rtt = 2 * radius } else { t1 := 2.0 * math.Pi * float64(i) / float64(nodes) x1, y1 := math.Cos(t1), math.Sin(t1) t2 := 2.0 * math.Pi * float64(j) / float64(nodes) x2, y2 := math.Cos(t2), math.Sin(t2) dx, dy := x2-x1, y2-y1 dist := math.Sqrt(dx*dx + dy*dy) rtt = time.Duration(dist * float64(radius)) } truth[i][j], truth[j][i] = rtt, rtt } } return truth }
go
func GenerateCircle(nodes int, radius time.Duration) [][]time.Duration { truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { var rtt time.Duration if i == 0 { rtt = 2 * radius } else { t1 := 2.0 * math.Pi * float64(i) / float64(nodes) x1, y1 := math.Cos(t1), math.Sin(t1) t2 := 2.0 * math.Pi * float64(j) / float64(nodes) x2, y2 := math.Cos(t2), math.Sin(t2) dx, dy := x2-x1, y2-y1 dist := math.Sqrt(dx*dx + dy*dy) rtt = time.Duration(dist * float64(radius)) } truth[i][j], truth[j][i] = rtt, rtt } } return truth }
[ "func", "GenerateCircle", "(", "nodes", "int", ",", "radius", "time", ".", "Duration", ")", "[", "]", "[", "]", "time", ".", "Duration", "{", "truth", ":=", "make", "(", "[", "]", "[", "]", "time", ".", "Duration", ",", "nodes", ")", "\n", "for", ...
// GenerateCircle returns a truth matrix for a set of nodes, evenly distributed // around a circle with the given radius. The first node is at the "center" of the // circle because it's equidistant from all the other nodes, but we place it at // double the radius, so it should show up above all the other nodes in height.
[ "GenerateCircle", "returns", "a", "truth", "matrix", "for", "a", "set", "of", "nodes", "evenly", "distributed", "around", "a", "circle", "with", "the", "given", "radius", ".", "The", "first", "node", "is", "at", "the", "center", "of", "the", "circle", "bec...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L91-L115
166,141
hashicorp/serf
coordinate/phantom.go
GenerateRandom
func GenerateRandom(nodes int, mean time.Duration, deviation time.Duration) [][]time.Duration { rand.Seed(1) truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rttSeconds := rand.NormFloat64()*deviation.Seconds() + mean.Seconds() rtt := time.Duration(rttSeconds * secondsToNanoseconds) truth[i][j], truth[j][i] = rtt, rtt } } return truth }
go
func GenerateRandom(nodes int, mean time.Duration, deviation time.Duration) [][]time.Duration { rand.Seed(1) truth := make([][]time.Duration, nodes) for i := range truth { truth[i] = make([]time.Duration, nodes) } for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { rttSeconds := rand.NormFloat64()*deviation.Seconds() + mean.Seconds() rtt := time.Duration(rttSeconds * secondsToNanoseconds) truth[i][j], truth[j][i] = rtt, rtt } } return truth }
[ "func", "GenerateRandom", "(", "nodes", "int", ",", "mean", "time", ".", "Duration", ",", "deviation", "time", ".", "Duration", ")", "[", "]", "[", "]", "time", ".", "Duration", "{", "rand", ".", "Seed", "(", "1", ")", "\n\n", "truth", ":=", "make", ...
// GenerateRandom returns a truth matrix for a set of nodes with normally // distributed delays, with the given mean and deviation. The RNG is re-seeded // so you always get the same matrix for a given size.
[ "GenerateRandom", "returns", "a", "truth", "matrix", "for", "a", "set", "of", "nodes", "with", "normally", "distributed", "delays", "with", "the", "given", "mean", "and", "deviation", ".", "The", "RNG", "is", "re", "-", "seeded", "so", "you", "always", "ge...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L120-L136
166,142
hashicorp/serf
coordinate/phantom.go
Evaluate
func Evaluate(clients []*Client, truth [][]time.Duration) (stats Stats) { nodes := len(clients) count := 0 for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { est := clients[i].DistanceTo(clients[j].GetCoordinate()).Seconds() actual := truth[i][j].Seconds() error := math.Abs(est-actual) / actual stats.ErrorMax = math.Max(stats.ErrorMax, error) stats.ErrorAvg += error count += 1 } } stats.ErrorAvg /= float64(count) fmt.Printf("Error avg=%9.6f max=%9.6f\n", stats.ErrorAvg, stats.ErrorMax) return }
go
func Evaluate(clients []*Client, truth [][]time.Duration) (stats Stats) { nodes := len(clients) count := 0 for i := 0; i < nodes; i++ { for j := i + 1; j < nodes; j++ { est := clients[i].DistanceTo(clients[j].GetCoordinate()).Seconds() actual := truth[i][j].Seconds() error := math.Abs(est-actual) / actual stats.ErrorMax = math.Max(stats.ErrorMax, error) stats.ErrorAvg += error count += 1 } } stats.ErrorAvg /= float64(count) fmt.Printf("Error avg=%9.6f max=%9.6f\n", stats.ErrorAvg, stats.ErrorMax) return }
[ "func", "Evaluate", "(", "clients", "[", "]", "*", "Client", ",", "truth", "[", "]", "[", "]", "time", ".", "Duration", ")", "(", "stats", "Stats", ")", "{", "nodes", ":=", "len", "(", "clients", ")", "\n", "count", ":=", "0", "\n", "for", "i", ...
// Evaluate uses the coordinates of the given clients to calculate estimated // distances and compares them with the given truth matrix, returning summary // stats.
[ "Evaluate", "uses", "the", "coordinates", "of", "the", "given", "clients", "to", "calculate", "estimated", "distances", "and", "compares", "them", "with", "the", "given", "truth", "matrix", "returning", "summary", "stats", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/phantom.go#L170-L187
166,143
hashicorp/serf
serf/snapshot.go
NewSnapshotter
func NewSnapshotter(path string, minCompactSize int, rejoinAfterLeave bool, logger *log.Logger, clock *LamportClock, outCh chan<- Event, shutdownCh <-chan struct{}) (chan<- Event, *Snapshotter, error) { inCh := make(chan Event, eventChSize) streamCh := make(chan Event, eventChSize) // Try to open the file fh, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644) if err != nil { return nil, nil, fmt.Errorf("failed to open snapshot: %v", err) } // Determine the offset info, err := fh.Stat() if err != nil { fh.Close() return nil, nil, fmt.Errorf("failed to stat snapshot: %v", err) } offset := info.Size() // Create the snapshotter snap := &Snapshotter{ aliveNodes: make(map[string]string), clock: clock, fh: fh, buffered: bufio.NewWriter(fh), inCh: inCh, streamCh: streamCh, lastClock: 0, lastEventClock: 0, lastQueryClock: 0, leaveCh: make(chan struct{}), logger: logger, minCompactSize: int64(minCompactSize), path: path, offset: offset, outCh: outCh, rejoinAfterLeave: rejoinAfterLeave, shutdownCh: shutdownCh, waitCh: make(chan struct{}), } // Recover the last known state if err := snap.replay(); err != nil { fh.Close() return nil, nil, err } // Start handling new commands go snap.teeStream() go snap.stream() return inCh, snap, nil }
go
func NewSnapshotter(path string, minCompactSize int, rejoinAfterLeave bool, logger *log.Logger, clock *LamportClock, outCh chan<- Event, shutdownCh <-chan struct{}) (chan<- Event, *Snapshotter, error) { inCh := make(chan Event, eventChSize) streamCh := make(chan Event, eventChSize) // Try to open the file fh, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644) if err != nil { return nil, nil, fmt.Errorf("failed to open snapshot: %v", err) } // Determine the offset info, err := fh.Stat() if err != nil { fh.Close() return nil, nil, fmt.Errorf("failed to stat snapshot: %v", err) } offset := info.Size() // Create the snapshotter snap := &Snapshotter{ aliveNodes: make(map[string]string), clock: clock, fh: fh, buffered: bufio.NewWriter(fh), inCh: inCh, streamCh: streamCh, lastClock: 0, lastEventClock: 0, lastQueryClock: 0, leaveCh: make(chan struct{}), logger: logger, minCompactSize: int64(minCompactSize), path: path, offset: offset, outCh: outCh, rejoinAfterLeave: rejoinAfterLeave, shutdownCh: shutdownCh, waitCh: make(chan struct{}), } // Recover the last known state if err := snap.replay(); err != nil { fh.Close() return nil, nil, err } // Start handling new commands go snap.teeStream() go snap.stream() return inCh, snap, nil }
[ "func", "NewSnapshotter", "(", "path", "string", ",", "minCompactSize", "int", ",", "rejoinAfterLeave", "bool", ",", "logger", "*", "log", ".", "Logger", ",", "clock", "*", "LamportClock", ",", "outCh", "chan", "<-", "Event", ",", "shutdownCh", "<-", "chan",...
// NewSnapshotter creates a new Snapshotter that records events up to a // max byte size before rotating the file. It can also be used to // recover old state. Snapshotter works by reading an event channel it returns, // passing through to an output channel, and persisting relevant events to disk. // Setting rejoinAfterLeave makes leave not clear the state, and can be used // if you intend to rejoin the same cluster after a leave.
[ "NewSnapshotter", "creates", "a", "new", "Snapshotter", "that", "records", "events", "up", "to", "a", "max", "byte", "size", "before", "rotating", "the", "file", ".", "It", "can", "also", "be", "used", "to", "recover", "old", "state", ".", "Snapshotter", "...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L99-L155
166,144
hashicorp/serf
serf/snapshot.go
AliveNodes
func (s *Snapshotter) AliveNodes() []*PreviousNode { // Copy the previously known previous := make([]*PreviousNode, 0, len(s.aliveNodes)) for name, addr := range s.aliveNodes { previous = append(previous, &PreviousNode{name, addr}) } // Randomize the order, prevents hot shards for i := range previous { j := rand.Intn(i + 1) previous[i], previous[j] = previous[j], previous[i] } return previous }
go
func (s *Snapshotter) AliveNodes() []*PreviousNode { // Copy the previously known previous := make([]*PreviousNode, 0, len(s.aliveNodes)) for name, addr := range s.aliveNodes { previous = append(previous, &PreviousNode{name, addr}) } // Randomize the order, prevents hot shards for i := range previous { j := rand.Intn(i + 1) previous[i], previous[j] = previous[j], previous[i] } return previous }
[ "func", "(", "s", "*", "Snapshotter", ")", "AliveNodes", "(", ")", "[", "]", "*", "PreviousNode", "{", "// Copy the previously known", "previous", ":=", "make", "(", "[", "]", "*", "PreviousNode", ",", "0", ",", "len", "(", "s", ".", "aliveNodes", ")", ...
// AliveNodes returns the last known alive nodes
[ "AliveNodes", "returns", "the", "last", "known", "alive", "nodes" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L173-L186
166,145
hashicorp/serf
serf/snapshot.go
teeStream
func (s *Snapshotter) teeStream() { flushEvent := func(e Event) { // Forward to the internal stream, do not block select { case s.streamCh <- e: default: } // Forward the event immediately, do not block if s.outCh != nil { select { case s.outCh <- e: default: } } } OUTER: for { select { case e := <-s.inCh: flushEvent(e) case <-s.shutdownCh: break OUTER } } // Drain any remaining events before exiting for { select { case e := <-s.inCh: flushEvent(e) default: return } } }
go
func (s *Snapshotter) teeStream() { flushEvent := func(e Event) { // Forward to the internal stream, do not block select { case s.streamCh <- e: default: } // Forward the event immediately, do not block if s.outCh != nil { select { case s.outCh <- e: default: } } } OUTER: for { select { case e := <-s.inCh: flushEvent(e) case <-s.shutdownCh: break OUTER } } // Drain any remaining events before exiting for { select { case e := <-s.inCh: flushEvent(e) default: return } } }
[ "func", "(", "s", "*", "Snapshotter", ")", "teeStream", "(", ")", "{", "flushEvent", ":=", "func", "(", "e", "Event", ")", "{", "// Forward to the internal stream, do not block", "select", "{", "case", "s", ".", "streamCh", "<-", "e", ":", "default", ":", ...
// teeStream is a long running routine that is used to copy events // to the output channel and the internal event handler.
[ "teeStream", "is", "a", "long", "running", "routine", "that", "is", "used", "to", "copy", "events", "to", "the", "output", "channel", "and", "the", "internal", "event", "handler", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L204-L240
166,146
hashicorp/serf
serf/snapshot.go
stream
func (s *Snapshotter) stream() { clockTicker := time.NewTicker(clockUpdateInterval) defer clockTicker.Stop() // flushEvent is used to handle writing out an event flushEvent := func(e Event) { // Stop recording events after a leave is issued if s.leaving { return } switch typed := e.(type) { case MemberEvent: s.processMemberEvent(typed) case UserEvent: s.processUserEvent(typed) case *Query: s.processQuery(typed) default: s.logger.Printf("[ERR] serf: Unknown event to snapshot: %#v", e) } } for { select { case <-s.leaveCh: s.leaving = true // If we plan to re-join, keep our state if !s.rejoinAfterLeave { s.aliveNodes = make(map[string]string) } s.tryAppend("leave\n") if err := s.buffered.Flush(); err != nil { s.logger.Printf("[ERR] serf: failed to flush leave to snapshot: %v", err) } if err := s.fh.Sync(); err != nil { s.logger.Printf("[ERR] serf: failed to sync leave to snapshot: %v", err) } case e := <-s.streamCh: flushEvent(e) case <-clockTicker.C: s.updateClock() case <-s.shutdownCh: // Setup a timeout flushTimeout := time.After(shutdownFlushTimeout) // Snapshot the clock s.updateClock() // Clear out the buffers FLUSH: for { select { case e := <-s.streamCh: flushEvent(e) case <-flushTimeout: break FLUSH default: break FLUSH } } if err := s.buffered.Flush(); err != nil { s.logger.Printf("[ERR] serf: failed to flush snapshot: %v", err) } if err := s.fh.Sync(); err != nil { s.logger.Printf("[ERR] serf: failed to sync snapshot: %v", err) } s.fh.Close() close(s.waitCh) return } } }
go
func (s *Snapshotter) stream() { clockTicker := time.NewTicker(clockUpdateInterval) defer clockTicker.Stop() // flushEvent is used to handle writing out an event flushEvent := func(e Event) { // Stop recording events after a leave is issued if s.leaving { return } switch typed := e.(type) { case MemberEvent: s.processMemberEvent(typed) case UserEvent: s.processUserEvent(typed) case *Query: s.processQuery(typed) default: s.logger.Printf("[ERR] serf: Unknown event to snapshot: %#v", e) } } for { select { case <-s.leaveCh: s.leaving = true // If we plan to re-join, keep our state if !s.rejoinAfterLeave { s.aliveNodes = make(map[string]string) } s.tryAppend("leave\n") if err := s.buffered.Flush(); err != nil { s.logger.Printf("[ERR] serf: failed to flush leave to snapshot: %v", err) } if err := s.fh.Sync(); err != nil { s.logger.Printf("[ERR] serf: failed to sync leave to snapshot: %v", err) } case e := <-s.streamCh: flushEvent(e) case <-clockTicker.C: s.updateClock() case <-s.shutdownCh: // Setup a timeout flushTimeout := time.After(shutdownFlushTimeout) // Snapshot the clock s.updateClock() // Clear out the buffers FLUSH: for { select { case e := <-s.streamCh: flushEvent(e) case <-flushTimeout: break FLUSH default: break FLUSH } } if err := s.buffered.Flush(); err != nil { s.logger.Printf("[ERR] serf: failed to flush snapshot: %v", err) } if err := s.fh.Sync(); err != nil { s.logger.Printf("[ERR] serf: failed to sync snapshot: %v", err) } s.fh.Close() close(s.waitCh) return } } }
[ "func", "(", "s", "*", "Snapshotter", ")", "stream", "(", ")", "{", "clockTicker", ":=", "time", ".", "NewTicker", "(", "clockUpdateInterval", ")", "\n", "defer", "clockTicker", ".", "Stop", "(", ")", "\n\n", "// flushEvent is used to handle writing out an event",...
// stream is a long running routine that is used to handle events
[ "stream", "is", "a", "long", "running", "routine", "that", "is", "used", "to", "handle", "events" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L243-L319
166,147
hashicorp/serf
serf/snapshot.go
processMemberEvent
func (s *Snapshotter) processMemberEvent(e MemberEvent) { switch e.Type { case EventMemberJoin: for _, mem := range e.Members { addr := net.TCPAddr{IP: mem.Addr, Port: int(mem.Port)} s.aliveNodes[mem.Name] = addr.String() s.tryAppend(fmt.Sprintf("alive: %s %s\n", mem.Name, addr.String())) } case EventMemberLeave: fallthrough case EventMemberFailed: for _, mem := range e.Members { delete(s.aliveNodes, mem.Name) s.tryAppend(fmt.Sprintf("not-alive: %s\n", mem.Name)) } } s.updateClock() }
go
func (s *Snapshotter) processMemberEvent(e MemberEvent) { switch e.Type { case EventMemberJoin: for _, mem := range e.Members { addr := net.TCPAddr{IP: mem.Addr, Port: int(mem.Port)} s.aliveNodes[mem.Name] = addr.String() s.tryAppend(fmt.Sprintf("alive: %s %s\n", mem.Name, addr.String())) } case EventMemberLeave: fallthrough case EventMemberFailed: for _, mem := range e.Members { delete(s.aliveNodes, mem.Name) s.tryAppend(fmt.Sprintf("not-alive: %s\n", mem.Name)) } } s.updateClock() }
[ "func", "(", "s", "*", "Snapshotter", ")", "processMemberEvent", "(", "e", "MemberEvent", ")", "{", "switch", "e", ".", "Type", "{", "case", "EventMemberJoin", ":", "for", "_", ",", "mem", ":=", "range", "e", ".", "Members", "{", "addr", ":=", "net", ...
// processMemberEvent is used to handle a single member event
[ "processMemberEvent", "is", "used", "to", "handle", "a", "single", "member", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L322-L340
166,148
hashicorp/serf
serf/snapshot.go
updateClock
func (s *Snapshotter) updateClock() { lastSeen := s.clock.Time() - 1 if lastSeen > s.lastClock { s.lastClock = lastSeen s.tryAppend(fmt.Sprintf("clock: %d\n", s.lastClock)) } }
go
func (s *Snapshotter) updateClock() { lastSeen := s.clock.Time() - 1 if lastSeen > s.lastClock { s.lastClock = lastSeen s.tryAppend(fmt.Sprintf("clock: %d\n", s.lastClock)) } }
[ "func", "(", "s", "*", "Snapshotter", ")", "updateClock", "(", ")", "{", "lastSeen", ":=", "s", ".", "clock", ".", "Time", "(", ")", "-", "1", "\n", "if", "lastSeen", ">", "s", ".", "lastClock", "{", "s", ".", "lastClock", "=", "lastSeen", "\n", ...
// updateClock is called periodically to check if we should udpate our // clock value. This is done after member events but should also be done // periodically due to race conditions with join and leave intents
[ "updateClock", "is", "called", "periodically", "to", "check", "if", "we", "should", "udpate", "our", "clock", "value", ".", "This", "is", "done", "after", "member", "events", "but", "should", "also", "be", "done", "periodically", "due", "to", "race", "condit...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L345-L351
166,149
hashicorp/serf
serf/snapshot.go
processUserEvent
func (s *Snapshotter) processUserEvent(e UserEvent) { // Ignore old clocks if e.LTime <= s.lastEventClock { return } s.lastEventClock = e.LTime s.tryAppend(fmt.Sprintf("event-clock: %d\n", e.LTime)) }
go
func (s *Snapshotter) processUserEvent(e UserEvent) { // Ignore old clocks if e.LTime <= s.lastEventClock { return } s.lastEventClock = e.LTime s.tryAppend(fmt.Sprintf("event-clock: %d\n", e.LTime)) }
[ "func", "(", "s", "*", "Snapshotter", ")", "processUserEvent", "(", "e", "UserEvent", ")", "{", "// Ignore old clocks", "if", "e", ".", "LTime", "<=", "s", ".", "lastEventClock", "{", "return", "\n", "}", "\n", "s", ".", "lastEventClock", "=", "e", ".", ...
// processUserEvent is used to handle a single user event
[ "processUserEvent", "is", "used", "to", "handle", "a", "single", "user", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L354-L361
166,150
hashicorp/serf
serf/snapshot.go
processQuery
func (s *Snapshotter) processQuery(q *Query) { // Ignore old clocks if q.LTime <= s.lastQueryClock { return } s.lastQueryClock = q.LTime s.tryAppend(fmt.Sprintf("query-clock: %d\n", q.LTime)) }
go
func (s *Snapshotter) processQuery(q *Query) { // Ignore old clocks if q.LTime <= s.lastQueryClock { return } s.lastQueryClock = q.LTime s.tryAppend(fmt.Sprintf("query-clock: %d\n", q.LTime)) }
[ "func", "(", "s", "*", "Snapshotter", ")", "processQuery", "(", "q", "*", "Query", ")", "{", "// Ignore old clocks", "if", "q", ".", "LTime", "<=", "s", ".", "lastQueryClock", "{", "return", "\n", "}", "\n", "s", ".", "lastQueryClock", "=", "q", ".", ...
// processQuery is used to handle a single query event
[ "processQuery", "is", "used", "to", "handle", "a", "single", "query", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L364-L371
166,151
hashicorp/serf
serf/snapshot.go
tryAppend
func (s *Snapshotter) tryAppend(l string) { if err := s.appendLine(l); err != nil { s.logger.Printf("[ERR] serf: Failed to update snapshot: %v", err) now := time.Now() if now.Sub(s.lastAttemptedCompaction) > snapshotErrorRecoveryInterval { s.lastAttemptedCompaction = now s.logger.Printf("[INFO] serf: Attempting compaction to recover from error...") err = s.compact() if err != nil { s.logger.Printf("[ERR] serf: Compaction failed, will reattempt after %v: %v", snapshotErrorRecoveryInterval, err) } else { s.logger.Printf("[INFO] serf: Finished compaction, successfully recovered from error state") } } } }
go
func (s *Snapshotter) tryAppend(l string) { if err := s.appendLine(l); err != nil { s.logger.Printf("[ERR] serf: Failed to update snapshot: %v", err) now := time.Now() if now.Sub(s.lastAttemptedCompaction) > snapshotErrorRecoveryInterval { s.lastAttemptedCompaction = now s.logger.Printf("[INFO] serf: Attempting compaction to recover from error...") err = s.compact() if err != nil { s.logger.Printf("[ERR] serf: Compaction failed, will reattempt after %v: %v", snapshotErrorRecoveryInterval, err) } else { s.logger.Printf("[INFO] serf: Finished compaction, successfully recovered from error state") } } } }
[ "func", "(", "s", "*", "Snapshotter", ")", "tryAppend", "(", "l", "string", ")", "{", "if", "err", ":=", "s", ".", "appendLine", "(", "l", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", ...
// tryAppend will invoke append line but will not return an error
[ "tryAppend", "will", "invoke", "append", "line", "but", "will", "not", "return", "an", "error" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L374-L389
166,152
hashicorp/serf
serf/snapshot.go
appendLine
func (s *Snapshotter) appendLine(l string) error { defer metrics.MeasureSince([]string{"serf", "snapshot", "appendLine"}, time.Now()) n, err := s.buffered.WriteString(l) if err != nil { return err } // Check if we should flush now := time.Now() if now.Sub(s.lastFlush) > flushInterval { s.lastFlush = now if err := s.buffered.Flush(); err != nil { return err } } // Check if a compaction is necessary s.offset += int64(n) if s.offset > s.snapshotMaxSize() { return s.compact() } return nil }
go
func (s *Snapshotter) appendLine(l string) error { defer metrics.MeasureSince([]string{"serf", "snapshot", "appendLine"}, time.Now()) n, err := s.buffered.WriteString(l) if err != nil { return err } // Check if we should flush now := time.Now() if now.Sub(s.lastFlush) > flushInterval { s.lastFlush = now if err := s.buffered.Flush(); err != nil { return err } } // Check if a compaction is necessary s.offset += int64(n) if s.offset > s.snapshotMaxSize() { return s.compact() } return nil }
[ "func", "(", "s", "*", "Snapshotter", ")", "appendLine", "(", "l", "string", ")", "error", "{", "defer", "metrics", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "time", ".", "Now", "("...
// appendLine is used to append a line to the existing log
[ "appendLine", "is", "used", "to", "append", "a", "line", "to", "the", "existing", "log" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L392-L415
166,153
hashicorp/serf
serf/snapshot.go
snapshotMaxSize
func (s *Snapshotter) snapshotMaxSize() int64 { nodes := int64(len(s.aliveNodes)) estSize := nodes * snapshotBytesPerNode threshold := estSize * snapshotCompactionThreshold // Apply a minimum threshold to avoid frequent compaction if threshold < s.minCompactSize { threshold = s.minCompactSize } return threshold }
go
func (s *Snapshotter) snapshotMaxSize() int64 { nodes := int64(len(s.aliveNodes)) estSize := nodes * snapshotBytesPerNode threshold := estSize * snapshotCompactionThreshold // Apply a minimum threshold to avoid frequent compaction if threshold < s.minCompactSize { threshold = s.minCompactSize } return threshold }
[ "func", "(", "s", "*", "Snapshotter", ")", "snapshotMaxSize", "(", ")", "int64", "{", "nodes", ":=", "int64", "(", "len", "(", "s", ".", "aliveNodes", ")", ")", "\n", "estSize", ":=", "nodes", "*", "snapshotBytesPerNode", "\n", "threshold", ":=", "estSiz...
// snapshotMaxSize computes the maximum size and is used to force periodic compaction.
[ "snapshotMaxSize", "computes", "the", "maximum", "size", "and", "is", "used", "to", "force", "periodic", "compaction", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/snapshot.go#L418-L428
166,154
hashicorp/serf
cmd/serf/command/agent/invoke.go
eventClean
func eventClean(v string) string { v = strings.Replace(v, "\t", "\\t", -1) v = strings.Replace(v, "\n", "\\n", -1) return v }
go
func eventClean(v string) string { v = strings.Replace(v, "\t", "\\t", -1) v = strings.Replace(v, "\n", "\\n", -1) return v }
[ "func", "eventClean", "(", "v", "string", ")", "string", "{", "v", "=", "strings", ".", "Replace", "(", "v", ",", "\"", "\\t", "\"", ",", "\"", "\\\\", "\"", ",", "-", "1", ")", "\n", "v", "=", "strings", ".", "Replace", "(", "v", ",", "\"", ...
// eventClean cleans a value to be a parameter in an event line.
[ "eventClean", "cleans", "a", "value", "to", "be", "a", "parameter", "in", "an", "event", "line", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/invoke.go#L132-L136
166,155
hashicorp/serf
cmd/serf/command/agent/ipc_event_stream.go
sendMemberEvent
func (es *eventStream) sendMemberEvent(me serf.MemberEvent) error { members := make([]Member, 0, len(me.Members)) for _, m := range me.Members { sm := Member{ Name: m.Name, Addr: m.Addr, Port: m.Port, Tags: m.Tags, Status: m.Status.String(), ProtocolMin: m.ProtocolMin, ProtocolMax: m.ProtocolMax, ProtocolCur: m.ProtocolCur, DelegateMin: m.DelegateMin, DelegateMax: m.DelegateMax, DelegateCur: m.DelegateCur, } members = append(members, sm) } header := responseHeader{ Seq: es.seq, Error: "", } rec := memberEventRecord{ Event: me.String(), Members: members, } return es.client.Send(&header, &rec) }
go
func (es *eventStream) sendMemberEvent(me serf.MemberEvent) error { members := make([]Member, 0, len(me.Members)) for _, m := range me.Members { sm := Member{ Name: m.Name, Addr: m.Addr, Port: m.Port, Tags: m.Tags, Status: m.Status.String(), ProtocolMin: m.ProtocolMin, ProtocolMax: m.ProtocolMax, ProtocolCur: m.ProtocolCur, DelegateMin: m.DelegateMin, DelegateMax: m.DelegateMax, DelegateCur: m.DelegateCur, } members = append(members, sm) } header := responseHeader{ Seq: es.seq, Error: "", } rec := memberEventRecord{ Event: me.String(), Members: members, } return es.client.Send(&header, &rec) }
[ "func", "(", "es", "*", "eventStream", ")", "sendMemberEvent", "(", "me", "serf", ".", "MemberEvent", ")", "error", "{", "members", ":=", "make", "(", "[", "]", "Member", ",", "0", ",", "len", "(", "me", ".", "Members", ")", ")", "\n", "for", "_", ...
// sendMemberEvent is used to send a single member event
[ "sendMemberEvent", "is", "used", "to", "send", "a", "single", "member", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_event_stream.go#L80-L108
166,156
hashicorp/serf
cmd/serf/command/agent/ipc_event_stream.go
sendUserEvent
func (es *eventStream) sendUserEvent(ue serf.UserEvent) error { header := responseHeader{ Seq: es.seq, Error: "", } rec := userEventRecord{ Event: ue.EventType().String(), LTime: ue.LTime, Name: ue.Name, Payload: ue.Payload, Coalesce: ue.Coalesce, } return es.client.Send(&header, &rec) }
go
func (es *eventStream) sendUserEvent(ue serf.UserEvent) error { header := responseHeader{ Seq: es.seq, Error: "", } rec := userEventRecord{ Event: ue.EventType().String(), LTime: ue.LTime, Name: ue.Name, Payload: ue.Payload, Coalesce: ue.Coalesce, } return es.client.Send(&header, &rec) }
[ "func", "(", "es", "*", "eventStream", ")", "sendUserEvent", "(", "ue", "serf", ".", "UserEvent", ")", "error", "{", "header", ":=", "responseHeader", "{", "Seq", ":", "es", ".", "seq", ",", "Error", ":", "\"", "\"", ",", "}", "\n", "rec", ":=", "u...
// sendUserEvent is used to send a single user event
[ "sendUserEvent", "is", "used", "to", "send", "a", "single", "user", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_event_stream.go#L111-L124
166,157
hashicorp/serf
cmd/serf/command/agent/ipc_event_stream.go
sendQuery
func (es *eventStream) sendQuery(q *serf.Query) error { id := es.client.RegisterQuery(q) header := responseHeader{ Seq: es.seq, Error: "", } rec := queryEventRecord{ Event: q.EventType().String(), ID: id, LTime: q.LTime, Name: q.Name, Payload: q.Payload, } return es.client.Send(&header, &rec) }
go
func (es *eventStream) sendQuery(q *serf.Query) error { id := es.client.RegisterQuery(q) header := responseHeader{ Seq: es.seq, Error: "", } rec := queryEventRecord{ Event: q.EventType().String(), ID: id, LTime: q.LTime, Name: q.Name, Payload: q.Payload, } return es.client.Send(&header, &rec) }
[ "func", "(", "es", "*", "eventStream", ")", "sendQuery", "(", "q", "*", "serf", ".", "Query", ")", "error", "{", "id", ":=", "es", ".", "client", ".", "RegisterQuery", "(", "q", ")", "\n\n", "header", ":=", "responseHeader", "{", "Seq", ":", "es", ...
// sendQuery is used to send a single query event
[ "sendQuery", "is", "used", "to", "send", "a", "single", "query", "event" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/ipc_event_stream.go#L127-L142
166,158
hashicorp/serf
serf/event.go
checkResponseSize
func (q *Query) checkResponseSize(resp []byte) error { if len(resp) > q.serf.config.QueryResponseSizeLimit { return fmt.Errorf("response exceeds limit of %d bytes", q.serf.config.QueryResponseSizeLimit) } return nil }
go
func (q *Query) checkResponseSize(resp []byte) error { if len(resp) > q.serf.config.QueryResponseSizeLimit { return fmt.Errorf("response exceeds limit of %d bytes", q.serf.config.QueryResponseSizeLimit) } return nil }
[ "func", "(", "q", "*", "Query", ")", "checkResponseSize", "(", "resp", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "resp", ")", ">", "q", ".", "serf", ".", "config", ".", "QueryResponseSizeLimit", "{", "return", "fmt", ".", "Errorf", "(", ...
// Check response size
[ "Check", "response", "size" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/event.go#L137-L142
166,159
hashicorp/serf
serf/event.go
Respond
func (q *Query) Respond(buf []byte) error { // Create response resp := q.createResponse(buf) // Encode response raw, err := encodeMessage(messageQueryResponseType, resp) if err != nil { return fmt.Errorf("failed to format response: %v", err) } if err := q.respondWithMessageAndResponse(raw, resp); err != nil { return fmt.Errorf("failed to respond to key query: %v", err) } return nil }
go
func (q *Query) Respond(buf []byte) error { // Create response resp := q.createResponse(buf) // Encode response raw, err := encodeMessage(messageQueryResponseType, resp) if err != nil { return fmt.Errorf("failed to format response: %v", err) } if err := q.respondWithMessageAndResponse(raw, resp); err != nil { return fmt.Errorf("failed to respond to key query: %v", err) } return nil }
[ "func", "(", "q", "*", "Query", ")", "Respond", "(", "buf", "[", "]", "byte", ")", "error", "{", "// Create response", "resp", ":=", "q", ".", "createResponse", "(", "buf", ")", "\n\n", "// Encode response", "raw", ",", "err", ":=", "encodeMessage", "(",...
// Respond is used to send a response to the user query
[ "Respond", "is", "used", "to", "send", "a", "response", "to", "the", "user", "query" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/event.go#L181-L196
166,160
hashicorp/serf
serf/messages.go
encodeRelayMessage
func encodeRelayMessage(t messageType, addr net.UDPAddr, msg interface{}) ([]byte, error) { buf := bytes.NewBuffer(nil) handle := codec.MsgpackHandle{} encoder := codec.NewEncoder(buf, &handle) buf.WriteByte(uint8(messageRelayType)) if err := encoder.Encode(relayHeader{DestAddr: addr}); err != nil { return nil, err } buf.WriteByte(uint8(t)) err := encoder.Encode(msg) return buf.Bytes(), err }
go
func encodeRelayMessage(t messageType, addr net.UDPAddr, msg interface{}) ([]byte, error) { buf := bytes.NewBuffer(nil) handle := codec.MsgpackHandle{} encoder := codec.NewEncoder(buf, &handle) buf.WriteByte(uint8(messageRelayType)) if err := encoder.Encode(relayHeader{DestAddr: addr}); err != nil { return nil, err } buf.WriteByte(uint8(t)) err := encoder.Encode(msg) return buf.Bytes(), err }
[ "func", "encodeRelayMessage", "(", "t", "messageType", ",", "addr", "net", ".", "UDPAddr", ",", "msg", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "handle",...
// encodeRelayMessage wraps a message in the messageRelayType, adding the length and // address of the end recipient to the front of the message
[ "encodeRelayMessage", "wraps", "a", "message", "in", "the", "messageRelayType", "adding", "the", "length", "and", "address", "of", "the", "end", "recipient", "to", "the", "front", "of", "the", "message" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/messages.go#L150-L163
166,161
hashicorp/serf
coordinate/client.go
NewClient
func NewClient(config *Config) (*Client, error) { if !(config.Dimensionality > 0) { return nil, fmt.Errorf("dimensionality must be >0") } return &Client{ coord: NewCoordinate(config), origin: NewCoordinate(config), config: config, adjustmentIndex: 0, adjustmentSamples: make([]float64, config.AdjustmentWindowSize), latencyFilterSamples: make(map[string][]float64), }, nil }
go
func NewClient(config *Config) (*Client, error) { if !(config.Dimensionality > 0) { return nil, fmt.Errorf("dimensionality must be >0") } return &Client{ coord: NewCoordinate(config), origin: NewCoordinate(config), config: config, adjustmentIndex: 0, adjustmentSamples: make([]float64, config.AdjustmentWindowSize), latencyFilterSamples: make(map[string][]float64), }, nil }
[ "func", "NewClient", "(", "config", "*", "Config", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "!", "(", "config", ".", "Dimensionality", ">", "0", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", ...
// NewClient creates a new Client and verifies the configuration is valid.
[ "NewClient", "creates", "a", "new", "Client", "and", "verifies", "the", "configuration", "is", "valid", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L54-L67
166,162
hashicorp/serf
coordinate/client.go
GetCoordinate
func (c *Client) GetCoordinate() *Coordinate { c.mutex.RLock() defer c.mutex.RUnlock() return c.coord.Clone() }
go
func (c *Client) GetCoordinate() *Coordinate { c.mutex.RLock() defer c.mutex.RUnlock() return c.coord.Clone() }
[ "func", "(", "c", "*", "Client", ")", "GetCoordinate", "(", ")", "*", "Coordinate", "{", "c", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ".", "coord", ".", "Clone", "("...
// GetCoordinate returns a copy of the coordinate for this client.
[ "GetCoordinate", "returns", "a", "copy", "of", "the", "coordinate", "for", "this", "client", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L70-L75
166,163
hashicorp/serf
coordinate/client.go
SetCoordinate
func (c *Client) SetCoordinate(coord *Coordinate) error { c.mutex.Lock() defer c.mutex.Unlock() if err := c.checkCoordinate(coord); err != nil { return err } c.coord = coord.Clone() return nil }
go
func (c *Client) SetCoordinate(coord *Coordinate) error { c.mutex.Lock() defer c.mutex.Unlock() if err := c.checkCoordinate(coord); err != nil { return err } c.coord = coord.Clone() return nil }
[ "func", "(", "c", "*", "Client", ")", "SetCoordinate", "(", "coord", "*", "Coordinate", ")", "error", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "c", ".", ...
// SetCoordinate forces the client's coordinate to a known state.
[ "SetCoordinate", "forces", "the", "client", "s", "coordinate", "to", "a", "known", "state", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L78-L88
166,164
hashicorp/serf
coordinate/client.go
ForgetNode
func (c *Client) ForgetNode(node string) { c.mutex.Lock() defer c.mutex.Unlock() delete(c.latencyFilterSamples, node) }
go
func (c *Client) ForgetNode(node string) { c.mutex.Lock() defer c.mutex.Unlock() delete(c.latencyFilterSamples, node) }
[ "func", "(", "c", "*", "Client", ")", "ForgetNode", "(", "node", "string", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "c", ".", "latencyFilterSamples", ",", ...
// ForgetNode removes any client state for the given node.
[ "ForgetNode", "removes", "any", "client", "state", "for", "the", "given", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L91-L96
166,165
hashicorp/serf
coordinate/client.go
Stats
func (c *Client) Stats() ClientStats { c.mutex.Lock() defer c.mutex.Unlock() return c.stats }
go
func (c *Client) Stats() ClientStats { c.mutex.Lock() defer c.mutex.Unlock() return c.stats }
[ "func", "(", "c", "*", "Client", ")", "Stats", "(", ")", "ClientStats", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "stats", "\n", "}" ]
// Stats returns a copy of stats for the client.
[ "Stats", "returns", "a", "copy", "of", "stats", "for", "the", "client", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L99-L104
166,166
hashicorp/serf
coordinate/client.go
checkCoordinate
func (c *Client) checkCoordinate(coord *Coordinate) error { if !c.coord.IsCompatibleWith(coord) { return fmt.Errorf("dimensions aren't compatible") } if !coord.IsValid() { return fmt.Errorf("coordinate is invalid") } return nil }
go
func (c *Client) checkCoordinate(coord *Coordinate) error { if !c.coord.IsCompatibleWith(coord) { return fmt.Errorf("dimensions aren't compatible") } if !coord.IsValid() { return fmt.Errorf("coordinate is invalid") } return nil }
[ "func", "(", "c", "*", "Client", ")", "checkCoordinate", "(", "coord", "*", "Coordinate", ")", "error", "{", "if", "!", "c", ".", "coord", ".", "IsCompatibleWith", "(", "coord", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", ...
// checkCoordinate returns an error if the coordinate isn't compatible with // this client, or if the coordinate itself isn't valid. This assumes the mutex // has been locked already.
[ "checkCoordinate", "returns", "an", "error", "if", "the", "coordinate", "isn", "t", "compatible", "with", "this", "client", "or", "if", "the", "coordinate", "itself", "isn", "t", "valid", ".", "This", "assumes", "the", "mutex", "has", "been", "locked", "alre...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L109-L119
166,167
hashicorp/serf
coordinate/client.go
latencyFilter
func (c *Client) latencyFilter(node string, rttSeconds float64) float64 { samples, ok := c.latencyFilterSamples[node] if !ok { samples = make([]float64, 0, c.config.LatencyFilterSize) } // Add the new sample and trim the list, if needed. samples = append(samples, rttSeconds) if len(samples) > int(c.config.LatencyFilterSize) { samples = samples[1:] } c.latencyFilterSamples[node] = samples // Sort a copy of the samples and return the median. sorted := make([]float64, len(samples)) copy(sorted, samples) sort.Float64s(sorted) return sorted[len(sorted)/2] }
go
func (c *Client) latencyFilter(node string, rttSeconds float64) float64 { samples, ok := c.latencyFilterSamples[node] if !ok { samples = make([]float64, 0, c.config.LatencyFilterSize) } // Add the new sample and trim the list, if needed. samples = append(samples, rttSeconds) if len(samples) > int(c.config.LatencyFilterSize) { samples = samples[1:] } c.latencyFilterSamples[node] = samples // Sort a copy of the samples and return the median. sorted := make([]float64, len(samples)) copy(sorted, samples) sort.Float64s(sorted) return sorted[len(sorted)/2] }
[ "func", "(", "c", "*", "Client", ")", "latencyFilter", "(", "node", "string", ",", "rttSeconds", "float64", ")", "float64", "{", "samples", ",", "ok", ":=", "c", ".", "latencyFilterSamples", "[", "node", "]", "\n", "if", "!", "ok", "{", "samples", "=",...
// latencyFilter applies a simple moving median filter with a new sample for // a node. This assumes that the mutex has been locked already.
[ "latencyFilter", "applies", "a", "simple", "moving", "median", "filter", "with", "a", "new", "sample", "for", "a", "node", ".", "This", "assumes", "that", "the", "mutex", "has", "been", "locked", "already", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L123-L141
166,168
hashicorp/serf
coordinate/client.go
updateVivaldi
func (c *Client) updateVivaldi(other *Coordinate, rttSeconds float64) { const zeroThreshold = 1.0e-6 dist := c.coord.DistanceTo(other).Seconds() if rttSeconds < zeroThreshold { rttSeconds = zeroThreshold } wrongness := math.Abs(dist-rttSeconds) / rttSeconds totalError := c.coord.Error + other.Error if totalError < zeroThreshold { totalError = zeroThreshold } weight := c.coord.Error / totalError c.coord.Error = c.config.VivaldiCE*weight*wrongness + c.coord.Error*(1.0-c.config.VivaldiCE*weight) if c.coord.Error > c.config.VivaldiErrorMax { c.coord.Error = c.config.VivaldiErrorMax } delta := c.config.VivaldiCC * weight force := delta * (rttSeconds - dist) c.coord = c.coord.ApplyForce(c.config, force, other) }
go
func (c *Client) updateVivaldi(other *Coordinate, rttSeconds float64) { const zeroThreshold = 1.0e-6 dist := c.coord.DistanceTo(other).Seconds() if rttSeconds < zeroThreshold { rttSeconds = zeroThreshold } wrongness := math.Abs(dist-rttSeconds) / rttSeconds totalError := c.coord.Error + other.Error if totalError < zeroThreshold { totalError = zeroThreshold } weight := c.coord.Error / totalError c.coord.Error = c.config.VivaldiCE*weight*wrongness + c.coord.Error*(1.0-c.config.VivaldiCE*weight) if c.coord.Error > c.config.VivaldiErrorMax { c.coord.Error = c.config.VivaldiErrorMax } delta := c.config.VivaldiCC * weight force := delta * (rttSeconds - dist) c.coord = c.coord.ApplyForce(c.config, force, other) }
[ "func", "(", "c", "*", "Client", ")", "updateVivaldi", "(", "other", "*", "Coordinate", ",", "rttSeconds", "float64", ")", "{", "const", "zeroThreshold", "=", "1.0e-6", "\n\n", "dist", ":=", "c", ".", "coord", ".", "DistanceTo", "(", "other", ")", ".", ...
// updateVivialdi updates the Vivaldi portion of the client's coordinate. This // assumes that the mutex has been locked already.
[ "updateVivialdi", "updates", "the", "Vivaldi", "portion", "of", "the", "client", "s", "coordinate", ".", "This", "assumes", "that", "the", "mutex", "has", "been", "locked", "already", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L145-L168
166,169
hashicorp/serf
coordinate/client.go
updateAdjustment
func (c *Client) updateAdjustment(other *Coordinate, rttSeconds float64) { if c.config.AdjustmentWindowSize == 0 { return } // Note that the existing adjustment factors don't figure in to this // calculation so we use the raw distance here. dist := c.coord.rawDistanceTo(other) c.adjustmentSamples[c.adjustmentIndex] = rttSeconds - dist c.adjustmentIndex = (c.adjustmentIndex + 1) % c.config.AdjustmentWindowSize sum := 0.0 for _, sample := range c.adjustmentSamples { sum += sample } c.coord.Adjustment = sum / (2.0 * float64(c.config.AdjustmentWindowSize)) }
go
func (c *Client) updateAdjustment(other *Coordinate, rttSeconds float64) { if c.config.AdjustmentWindowSize == 0 { return } // Note that the existing adjustment factors don't figure in to this // calculation so we use the raw distance here. dist := c.coord.rawDistanceTo(other) c.adjustmentSamples[c.adjustmentIndex] = rttSeconds - dist c.adjustmentIndex = (c.adjustmentIndex + 1) % c.config.AdjustmentWindowSize sum := 0.0 for _, sample := range c.adjustmentSamples { sum += sample } c.coord.Adjustment = sum / (2.0 * float64(c.config.AdjustmentWindowSize)) }
[ "func", "(", "c", "*", "Client", ")", "updateAdjustment", "(", "other", "*", "Coordinate", ",", "rttSeconds", "float64", ")", "{", "if", "c", ".", "config", ".", "AdjustmentWindowSize", "==", "0", "{", "return", "\n", "}", "\n\n", "// Note that the existing ...
// updateAdjustment updates the adjustment portion of the client's coordinate, if // the feature is enabled. This assumes that the mutex has been locked already.
[ "updateAdjustment", "updates", "the", "adjustment", "portion", "of", "the", "client", "s", "coordinate", "if", "the", "feature", "is", "enabled", ".", "This", "assumes", "that", "the", "mutex", "has", "been", "locked", "already", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L172-L188
166,170
hashicorp/serf
coordinate/client.go
updateGravity
func (c *Client) updateGravity() { dist := c.origin.DistanceTo(c.coord).Seconds() force := -1.0 * math.Pow(dist/c.config.GravityRho, 2.0) c.coord = c.coord.ApplyForce(c.config, force, c.origin) }
go
func (c *Client) updateGravity() { dist := c.origin.DistanceTo(c.coord).Seconds() force := -1.0 * math.Pow(dist/c.config.GravityRho, 2.0) c.coord = c.coord.ApplyForce(c.config, force, c.origin) }
[ "func", "(", "c", "*", "Client", ")", "updateGravity", "(", ")", "{", "dist", ":=", "c", ".", "origin", ".", "DistanceTo", "(", "c", ".", "coord", ")", ".", "Seconds", "(", ")", "\n", "force", ":=", "-", "1.0", "*", "math", ".", "Pow", "(", "di...
// updateGravity applies a small amount of gravity to pull coordinates towards // the center of the coordinate system to combat drift. This assumes that the // mutex is locked already.
[ "updateGravity", "applies", "a", "small", "amount", "of", "gravity", "to", "pull", "coordinates", "towards", "the", "center", "of", "the", "coordinate", "system", "to", "combat", "drift", ".", "This", "assumes", "that", "the", "mutex", "is", "locked", "already...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L193-L197
166,171
hashicorp/serf
coordinate/client.go
Update
func (c *Client) Update(node string, other *Coordinate, rtt time.Duration) (*Coordinate, error) { c.mutex.Lock() defer c.mutex.Unlock() if err := c.checkCoordinate(other); err != nil { return nil, err } // The code down below can handle zero RTTs, which we have seen in // https://github.com/hashicorp/consul/issues/3789, presumably in // environments with coarse-grained monotonic clocks (we are still // trying to pin this down). In any event, this is ok from a code PoV // so we don't need to alert operators with spammy messages. We did // add a counter so this is still observable, though. const maxRTT = 10 * time.Second if rtt < 0 || rtt > maxRTT { return nil, fmt.Errorf("round trip time not in valid range, duration %v is not a positive value less than %v ", rtt, maxRTT) } if rtt == 0 { metrics.IncrCounter([]string{"serf", "coordinate", "zero-rtt"}, 1) } rttSeconds := c.latencyFilter(node, rtt.Seconds()) c.updateVivaldi(other, rttSeconds) c.updateAdjustment(other, rttSeconds) c.updateGravity() if !c.coord.IsValid() { c.stats.Resets++ c.coord = NewCoordinate(c.config) } return c.coord.Clone(), nil }
go
func (c *Client) Update(node string, other *Coordinate, rtt time.Duration) (*Coordinate, error) { c.mutex.Lock() defer c.mutex.Unlock() if err := c.checkCoordinate(other); err != nil { return nil, err } // The code down below can handle zero RTTs, which we have seen in // https://github.com/hashicorp/consul/issues/3789, presumably in // environments with coarse-grained monotonic clocks (we are still // trying to pin this down). In any event, this is ok from a code PoV // so we don't need to alert operators with spammy messages. We did // add a counter so this is still observable, though. const maxRTT = 10 * time.Second if rtt < 0 || rtt > maxRTT { return nil, fmt.Errorf("round trip time not in valid range, duration %v is not a positive value less than %v ", rtt, maxRTT) } if rtt == 0 { metrics.IncrCounter([]string{"serf", "coordinate", "zero-rtt"}, 1) } rttSeconds := c.latencyFilter(node, rtt.Seconds()) c.updateVivaldi(other, rttSeconds) c.updateAdjustment(other, rttSeconds) c.updateGravity() if !c.coord.IsValid() { c.stats.Resets++ c.coord = NewCoordinate(c.config) } return c.coord.Clone(), nil }
[ "func", "(", "c", "*", "Client", ")", "Update", "(", "node", "string", ",", "other", "*", "Coordinate", ",", "rtt", "time", ".", "Duration", ")", "(", "*", "Coordinate", ",", "error", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "def...
// Update takes other, a coordinate for another node, and rtt, a round trip // time observation for a ping to that node, and updates the estimated position of // the client's coordinate. Returns the updated coordinate.
[ "Update", "takes", "other", "a", "coordinate", "for", "another", "node", "and", "rtt", "a", "round", "trip", "time", "observation", "for", "a", "ping", "to", "that", "node", "and", "updates", "the", "estimated", "position", "of", "the", "client", "s", "coo...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L202-L234
166,172
hashicorp/serf
coordinate/client.go
DistanceTo
func (c *Client) DistanceTo(other *Coordinate) time.Duration { c.mutex.RLock() defer c.mutex.RUnlock() return c.coord.DistanceTo(other) }
go
func (c *Client) DistanceTo(other *Coordinate) time.Duration { c.mutex.RLock() defer c.mutex.RUnlock() return c.coord.DistanceTo(other) }
[ "func", "(", "c", "*", "Client", ")", "DistanceTo", "(", "other", "*", "Coordinate", ")", "time", ".", "Duration", "{", "c", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ...
// DistanceTo returns the estimated RTT from the client's coordinate to other, the // coordinate for another node.
[ "DistanceTo", "returns", "the", "estimated", "RTT", "from", "the", "client", "s", "coordinate", "to", "other", "the", "coordinate", "for", "another", "node", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/client.go#L238-L243
166,173
hashicorp/serf
serf/serf.go
UserEvent
func (s *Serf) UserEvent(name string, payload []byte, coalesce bool) error { payloadSizeBeforeEncoding := len(name)+len(payload) // Check size before encoding to prevent needless encoding and return early if it's over the specified limit. if payloadSizeBeforeEncoding > s.config.UserEventSizeLimit { return fmt.Errorf( "user event exceeds configured limit of %d bytes before encoding", s.config.UserEventSizeLimit, ) } if payloadSizeBeforeEncoding > UserEventSizeLimit { return fmt.Errorf( "user event exceeds sane limit of %d bytes before encoding", UserEventSizeLimit, ) } // Create a message msg := messageUserEvent{ LTime: s.eventClock.Time(), Name: name, Payload: payload, CC: coalesce, } // Start broadcasting the event raw, err := encodeMessage(messageUserEventType, &msg) if err != nil { return err } // Check the size after encoding to be sure again that // we're not attempting to send over the specified size limit. if len(raw) > s.config.UserEventSizeLimit { return fmt.Errorf( "encoded user event exceeds configured limit of %d bytes after encoding", s.config.UserEventSizeLimit, ) } if len(raw) > UserEventSizeLimit { return fmt.Errorf( "encoded user event exceeds sane limit of %d bytes before encoding", UserEventSizeLimit, ) } s.eventClock.Increment() // Process update locally s.handleUserEvent(&msg) s.eventBroadcasts.QueueBroadcast(&broadcast{ msg: raw, }) return nil }
go
func (s *Serf) UserEvent(name string, payload []byte, coalesce bool) error { payloadSizeBeforeEncoding := len(name)+len(payload) // Check size before encoding to prevent needless encoding and return early if it's over the specified limit. if payloadSizeBeforeEncoding > s.config.UserEventSizeLimit { return fmt.Errorf( "user event exceeds configured limit of %d bytes before encoding", s.config.UserEventSizeLimit, ) } if payloadSizeBeforeEncoding > UserEventSizeLimit { return fmt.Errorf( "user event exceeds sane limit of %d bytes before encoding", UserEventSizeLimit, ) } // Create a message msg := messageUserEvent{ LTime: s.eventClock.Time(), Name: name, Payload: payload, CC: coalesce, } // Start broadcasting the event raw, err := encodeMessage(messageUserEventType, &msg) if err != nil { return err } // Check the size after encoding to be sure again that // we're not attempting to send over the specified size limit. if len(raw) > s.config.UserEventSizeLimit { return fmt.Errorf( "encoded user event exceeds configured limit of %d bytes after encoding", s.config.UserEventSizeLimit, ) } if len(raw) > UserEventSizeLimit { return fmt.Errorf( "encoded user event exceeds sane limit of %d bytes before encoding", UserEventSizeLimit, ) } s.eventClock.Increment() // Process update locally s.handleUserEvent(&msg) s.eventBroadcasts.QueueBroadcast(&broadcast{ msg: raw, }) return nil }
[ "func", "(", "s", "*", "Serf", ")", "UserEvent", "(", "name", "string", ",", "payload", "[", "]", "byte", ",", "coalesce", "bool", ")", "error", "{", "payloadSizeBeforeEncoding", ":=", "len", "(", "name", ")", "+", "len", "(", "payload", ")", "\n\n", ...
// UserEvent is used to broadcast a custom user event with a given // name and payload. If the configured size limit is exceeded and error will be returned. // If coalesce is enabled, nodes are allowed to coalesce this event. // Coalescing is only available starting in v0.2
[ "UserEvent", "is", "used", "to", "broadcast", "a", "custom", "user", "event", "with", "a", "given", "name", "and", "payload", ".", "If", "the", "configured", "size", "limit", "is", "exceeded", "and", "error", "will", "be", "returned", ".", "If", "coalesce"...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L447-L504
166,174
hashicorp/serf
serf/serf.go
Query
func (s *Serf) Query(name string, payload []byte, params *QueryParam) (*QueryResponse, error) { // Check that the latest protocol is in use if s.ProtocolVersion() < 4 { return nil, FeatureNotSupported } // Provide default parameters if none given if params == nil { params = s.DefaultQueryParams() } else if params.Timeout == 0 { params.Timeout = s.DefaultQueryTimeout() } // Get the local node local := s.memberlist.LocalNode() // Encode the filters filters, err := params.encodeFilters() if err != nil { return nil, fmt.Errorf("Failed to format filters: %v", err) } // Setup the flags var flags uint32 if params.RequestAck { flags |= queryFlagAck } // Create a message q := messageQuery{ LTime: s.queryClock.Time(), ID: uint32(rand.Int31()), Addr: local.Addr, Port: local.Port, Filters: filters, Flags: flags, RelayFactor: params.RelayFactor, Timeout: params.Timeout, Name: name, Payload: payload, } // Encode the query raw, err := encodeMessage(messageQueryType, &q) if err != nil { return nil, err } // Check the size if len(raw) > s.config.QuerySizeLimit { return nil, fmt.Errorf("query exceeds limit of %d bytes", s.config.QuerySizeLimit) } // Register QueryResponse to track acks and responses resp := newQueryResponse(s.memberlist.NumMembers(), &q) s.registerQueryResponse(params.Timeout, resp) // Process query locally s.handleQuery(&q) // Start broadcasting the event s.queryBroadcasts.QueueBroadcast(&broadcast{ msg: raw, }) return resp, nil }
go
func (s *Serf) Query(name string, payload []byte, params *QueryParam) (*QueryResponse, error) { // Check that the latest protocol is in use if s.ProtocolVersion() < 4 { return nil, FeatureNotSupported } // Provide default parameters if none given if params == nil { params = s.DefaultQueryParams() } else if params.Timeout == 0 { params.Timeout = s.DefaultQueryTimeout() } // Get the local node local := s.memberlist.LocalNode() // Encode the filters filters, err := params.encodeFilters() if err != nil { return nil, fmt.Errorf("Failed to format filters: %v", err) } // Setup the flags var flags uint32 if params.RequestAck { flags |= queryFlagAck } // Create a message q := messageQuery{ LTime: s.queryClock.Time(), ID: uint32(rand.Int31()), Addr: local.Addr, Port: local.Port, Filters: filters, Flags: flags, RelayFactor: params.RelayFactor, Timeout: params.Timeout, Name: name, Payload: payload, } // Encode the query raw, err := encodeMessage(messageQueryType, &q) if err != nil { return nil, err } // Check the size if len(raw) > s.config.QuerySizeLimit { return nil, fmt.Errorf("query exceeds limit of %d bytes", s.config.QuerySizeLimit) } // Register QueryResponse to track acks and responses resp := newQueryResponse(s.memberlist.NumMembers(), &q) s.registerQueryResponse(params.Timeout, resp) // Process query locally s.handleQuery(&q) // Start broadcasting the event s.queryBroadcasts.QueueBroadcast(&broadcast{ msg: raw, }) return resp, nil }
[ "func", "(", "s", "*", "Serf", ")", "Query", "(", "name", "string", ",", "payload", "[", "]", "byte", ",", "params", "*", "QueryParam", ")", "(", "*", "QueryResponse", ",", "error", ")", "{", "// Check that the latest protocol is in use", "if", "s", ".", ...
// Query is used to broadcast a new query. The query must be fairly small, // and an error will be returned if the size limit is exceeded. This is only // available with protocol version 4 and newer. Query parameters are optional, // and if not provided, a sane set of defaults will be used.
[ "Query", "is", "used", "to", "broadcast", "a", "new", "query", ".", "The", "query", "must", "be", "fairly", "small", "and", "an", "error", "will", "be", "returned", "if", "the", "size", "limit", "is", "exceeded", ".", "This", "is", "only", "available", ...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L510-L575
166,175
hashicorp/serf
serf/serf.go
registerQueryResponse
func (s *Serf) registerQueryResponse(timeout time.Duration, resp *QueryResponse) { s.queryLock.Lock() defer s.queryLock.Unlock() // Map the LTime to the QueryResponse. This is necessarily 1-to-1, // since we increment the time for each new query. s.queryResponse[resp.lTime] = resp // Setup a timer to close the response and deregister after the timeout time.AfterFunc(timeout, func() { s.queryLock.Lock() delete(s.queryResponse, resp.lTime) resp.Close() s.queryLock.Unlock() }) }
go
func (s *Serf) registerQueryResponse(timeout time.Duration, resp *QueryResponse) { s.queryLock.Lock() defer s.queryLock.Unlock() // Map the LTime to the QueryResponse. This is necessarily 1-to-1, // since we increment the time for each new query. s.queryResponse[resp.lTime] = resp // Setup a timer to close the response and deregister after the timeout time.AfterFunc(timeout, func() { s.queryLock.Lock() delete(s.queryResponse, resp.lTime) resp.Close() s.queryLock.Unlock() }) }
[ "func", "(", "s", "*", "Serf", ")", "registerQueryResponse", "(", "timeout", "time", ".", "Duration", ",", "resp", "*", "QueryResponse", ")", "{", "s", ".", "queryLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "queryLock", ".", "Unlock", "(", ...
// registerQueryResponse is used to setup the listeners for the query, // and to schedule closing the query after the timeout.
[ "registerQueryResponse", "is", "used", "to", "setup", "the", "listeners", "for", "the", "query", "and", "to", "schedule", "closing", "the", "query", "after", "the", "timeout", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L579-L594
166,176
hashicorp/serf
serf/serf.go
SetTags
func (s *Serf) SetTags(tags map[string]string) error { // Check that the meta data length is okay if len(s.encodeTags(tags)) > memberlist.MetaMaxSize { return fmt.Errorf("Encoded length of tags exceeds limit of %d bytes", memberlist.MetaMaxSize) } // Update the config s.config.Tags = tags // Trigger a memberlist update return s.memberlist.UpdateNode(s.config.BroadcastTimeout) }
go
func (s *Serf) SetTags(tags map[string]string) error { // Check that the meta data length is okay if len(s.encodeTags(tags)) > memberlist.MetaMaxSize { return fmt.Errorf("Encoded length of tags exceeds limit of %d bytes", memberlist.MetaMaxSize) } // Update the config s.config.Tags = tags // Trigger a memberlist update return s.memberlist.UpdateNode(s.config.BroadcastTimeout) }
[ "func", "(", "s", "*", "Serf", ")", "SetTags", "(", "tags", "map", "[", "string", "]", "string", ")", "error", "{", "// Check that the meta data length is okay", "if", "len", "(", "s", ".", "encodeTags", "(", "tags", ")", ")", ">", "memberlist", ".", "Me...
// SetTags is used to dynamically update the tags associated with // the local node. This will propagate the change to the rest of // the cluster. Blocks until a the message is broadcast out.
[ "SetTags", "is", "used", "to", "dynamically", "update", "the", "tags", "associated", "with", "the", "local", "node", ".", "This", "will", "propagate", "the", "change", "to", "the", "rest", "of", "the", "cluster", ".", "Blocks", "until", "a", "the", "messag...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L599-L611
166,177
hashicorp/serf
serf/serf.go
Join
func (s *Serf) Join(existing []string, ignoreOld bool) (int, error) { // Do a quick state check if s.State() != SerfAlive { return 0, fmt.Errorf("Serf can't Join after Leave or Shutdown") } // Hold the joinLock, this is to make eventJoinIgnore safe s.joinLock.Lock() defer s.joinLock.Unlock() // Ignore any events from a potential join. This is safe since we hold // the joinLock and nobody else can be doing a Join if ignoreOld { s.eventJoinIgnore.Store(true) defer func() { s.eventJoinIgnore.Store(false) }() } // Have memberlist attempt to join num, err := s.memberlist.Join(existing) // If we joined any nodes, broadcast the join message if num > 0 { // Start broadcasting the update if err := s.broadcastJoin(s.clock.Time()); err != nil { return num, err } } return num, err }
go
func (s *Serf) Join(existing []string, ignoreOld bool) (int, error) { // Do a quick state check if s.State() != SerfAlive { return 0, fmt.Errorf("Serf can't Join after Leave or Shutdown") } // Hold the joinLock, this is to make eventJoinIgnore safe s.joinLock.Lock() defer s.joinLock.Unlock() // Ignore any events from a potential join. This is safe since we hold // the joinLock and nobody else can be doing a Join if ignoreOld { s.eventJoinIgnore.Store(true) defer func() { s.eventJoinIgnore.Store(false) }() } // Have memberlist attempt to join num, err := s.memberlist.Join(existing) // If we joined any nodes, broadcast the join message if num > 0 { // Start broadcasting the update if err := s.broadcastJoin(s.clock.Time()); err != nil { return num, err } } return num, err }
[ "func", "(", "s", "*", "Serf", ")", "Join", "(", "existing", "[", "]", "string", ",", "ignoreOld", "bool", ")", "(", "int", ",", "error", ")", "{", "// Do a quick state check", "if", "s", ".", "State", "(", ")", "!=", "SerfAlive", "{", "return", "0",...
// Join joins an existing Serf cluster. Returns the number of nodes // successfully contacted. The returned error will be non-nil only in the // case that no nodes could be contacted. If ignoreOld is true, then any // user messages sent prior to the join will be ignored.
[ "Join", "joins", "an", "existing", "Serf", "cluster", ".", "Returns", "the", "number", "of", "nodes", "successfully", "contacted", ".", "The", "returned", "error", "will", "be", "non", "-", "nil", "only", "in", "the", "case", "that", "no", "nodes", "could"...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L617-L648
166,178
hashicorp/serf
serf/serf.go
broadcastJoin
func (s *Serf) broadcastJoin(ltime LamportTime) error { // Construct message to update our lamport clock msg := messageJoin{ LTime: ltime, Node: s.config.NodeName, } s.clock.Witness(ltime) // Process update locally s.handleNodeJoinIntent(&msg) // Start broadcasting the update if err := s.broadcast(messageJoinType, &msg, nil); err != nil { s.logger.Printf("[WARN] serf: Failed to broadcast join intent: %v", err) return err } return nil }
go
func (s *Serf) broadcastJoin(ltime LamportTime) error { // Construct message to update our lamport clock msg := messageJoin{ LTime: ltime, Node: s.config.NodeName, } s.clock.Witness(ltime) // Process update locally s.handleNodeJoinIntent(&msg) // Start broadcasting the update if err := s.broadcast(messageJoinType, &msg, nil); err != nil { s.logger.Printf("[WARN] serf: Failed to broadcast join intent: %v", err) return err } return nil }
[ "func", "(", "s", "*", "Serf", ")", "broadcastJoin", "(", "ltime", "LamportTime", ")", "error", "{", "// Construct message to update our lamport clock", "msg", ":=", "messageJoin", "{", "LTime", ":", "ltime", ",", "Node", ":", "s", ".", "config", ".", "NodeNam...
// broadcastJoin broadcasts a new join intent with a // given clock value. It is used on either join, or if // we need to refute an older leave intent. Cannot be called // with the memberLock held.
[ "broadcastJoin", "broadcasts", "a", "new", "join", "intent", "with", "a", "given", "clock", "value", ".", "It", "is", "used", "on", "either", "join", "or", "if", "we", "need", "to", "refute", "an", "older", "leave", "intent", ".", "Cannot", "be", "called...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L654-L671
166,179
hashicorp/serf
serf/serf.go
Leave
func (s *Serf) Leave() error { // Check the current state s.stateLock.Lock() if s.state == SerfLeft { s.stateLock.Unlock() return nil } else if s.state == SerfLeaving { s.stateLock.Unlock() return fmt.Errorf("Leave already in progress") } else if s.state == SerfShutdown { s.stateLock.Unlock() return fmt.Errorf("Leave called after Shutdown") } s.state = SerfLeaving s.stateLock.Unlock() // If we have a snapshot, mark we are leaving if s.snapshotter != nil { s.snapshotter.Leave() } // Construct the message for the graceful leave msg := messageLeave{ LTime: s.clock.Time(), Node: s.config.NodeName, } s.clock.Increment() // Process the leave locally s.handleNodeLeaveIntent(&msg) // Only broadcast the leave message if there is at least one // other node alive. if s.hasAliveMembers() { notifyCh := make(chan struct{}) if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil { return err } select { case <-notifyCh: case <-time.After(s.config.BroadcastTimeout): return errors.New("timeout while waiting for graceful leave") } } // Attempt the memberlist leave err := s.memberlist.Leave(s.config.BroadcastTimeout) if err != nil { return err } // Wait for the leave to propagate through the cluster. The broadcast // timeout is how long we wait for the message to go out from our own // queue, but this wait is for that message to propagate through the // cluster. In particular, we want to stay up long enough to service // any probes from other nodes before they learn about us leaving. time.Sleep(s.config.LeavePropagateDelay) // Transition to Left only if we not already shutdown s.stateLock.Lock() if s.state != SerfShutdown { s.state = SerfLeft } s.stateLock.Unlock() return nil }
go
func (s *Serf) Leave() error { // Check the current state s.stateLock.Lock() if s.state == SerfLeft { s.stateLock.Unlock() return nil } else if s.state == SerfLeaving { s.stateLock.Unlock() return fmt.Errorf("Leave already in progress") } else if s.state == SerfShutdown { s.stateLock.Unlock() return fmt.Errorf("Leave called after Shutdown") } s.state = SerfLeaving s.stateLock.Unlock() // If we have a snapshot, mark we are leaving if s.snapshotter != nil { s.snapshotter.Leave() } // Construct the message for the graceful leave msg := messageLeave{ LTime: s.clock.Time(), Node: s.config.NodeName, } s.clock.Increment() // Process the leave locally s.handleNodeLeaveIntent(&msg) // Only broadcast the leave message if there is at least one // other node alive. if s.hasAliveMembers() { notifyCh := make(chan struct{}) if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil { return err } select { case <-notifyCh: case <-time.After(s.config.BroadcastTimeout): return errors.New("timeout while waiting for graceful leave") } } // Attempt the memberlist leave err := s.memberlist.Leave(s.config.BroadcastTimeout) if err != nil { return err } // Wait for the leave to propagate through the cluster. The broadcast // timeout is how long we wait for the message to go out from our own // queue, but this wait is for that message to propagate through the // cluster. In particular, we want to stay up long enough to service // any probes from other nodes before they learn about us leaving. time.Sleep(s.config.LeavePropagateDelay) // Transition to Left only if we not already shutdown s.stateLock.Lock() if s.state != SerfShutdown { s.state = SerfLeft } s.stateLock.Unlock() return nil }
[ "func", "(", "s", "*", "Serf", ")", "Leave", "(", ")", "error", "{", "// Check the current state", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "if", "s", ".", "state", "==", "SerfLeft", "{", "s", ".", "stateLock", ".", "Unlock", "(", ")", "...
// Leave gracefully exits the cluster. It is safe to call this multiple // times.
[ "Leave", "gracefully", "exits", "the", "cluster", ".", "It", "is", "safe", "to", "call", "this", "multiple", "times", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L675-L741
166,180
hashicorp/serf
serf/serf.go
hasAliveMembers
func (s *Serf) hasAliveMembers() bool { s.memberLock.RLock() defer s.memberLock.RUnlock() hasAlive := false for _, m := range s.members { // Skip ourself, we want to know if OTHER members are alive if m.Name == s.config.NodeName { continue } if m.Status == StatusAlive { hasAlive = true break } } return hasAlive }
go
func (s *Serf) hasAliveMembers() bool { s.memberLock.RLock() defer s.memberLock.RUnlock() hasAlive := false for _, m := range s.members { // Skip ourself, we want to know if OTHER members are alive if m.Name == s.config.NodeName { continue } if m.Status == StatusAlive { hasAlive = true break } } return hasAlive }
[ "func", "(", "s", "*", "Serf", ")", "hasAliveMembers", "(", ")", "bool", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "RUnlock", "(", ")", "\n\n", "hasAlive", ":=", "false", "\n", "for", "_", ",",...
// hasAliveMembers is called to check for any alive members other than // ourself.
[ "hasAliveMembers", "is", "called", "to", "check", "for", "any", "alive", "members", "other", "than", "ourself", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L745-L762
166,181
hashicorp/serf
serf/serf.go
LocalMember
func (s *Serf) LocalMember() Member { s.memberLock.RLock() defer s.memberLock.RUnlock() return s.members[s.config.NodeName].Member }
go
func (s *Serf) LocalMember() Member { s.memberLock.RLock() defer s.memberLock.RUnlock() return s.members[s.config.NodeName].Member }
[ "func", "(", "s", "*", "Serf", ")", "LocalMember", "(", ")", "Member", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "members", "[", "s", ".", "conf...
// LocalMember returns the Member information for the local node
[ "LocalMember", "returns", "the", "Member", "information", "for", "the", "local", "node" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L765-L769
166,182
hashicorp/serf
serf/serf.go
Members
func (s *Serf) Members() []Member { s.memberLock.RLock() defer s.memberLock.RUnlock() members := make([]Member, 0, len(s.members)) for _, m := range s.members { members = append(members, m.Member) } return members }
go
func (s *Serf) Members() []Member { s.memberLock.RLock() defer s.memberLock.RUnlock() members := make([]Member, 0, len(s.members)) for _, m := range s.members { members = append(members, m.Member) } return members }
[ "func", "(", "s", "*", "Serf", ")", "Members", "(", ")", "[", "]", "Member", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "RUnlock", "(", ")", "\n\n", "members", ":=", "make", "(", "[", "]", "...
// Members returns a point-in-time snapshot of the members of this cluster.
[ "Members", "returns", "a", "point", "-", "in", "-", "time", "snapshot", "of", "the", "members", "of", "this", "cluster", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L772-L782
166,183
hashicorp/serf
serf/serf.go
RemoveFailedNode
func (s *Serf) RemoveFailedNode(node string) error { // Construct the message to broadcast msg := messageLeave{ LTime: s.clock.Time(), Node: node, } s.clock.Increment() // Process our own event s.handleNodeLeaveIntent(&msg) // If we have no members, then we don't need to broadcast if !s.hasAliveMembers() { return nil } // Broadcast the remove notifyCh := make(chan struct{}) if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil { return err } // Wait for the broadcast select { case <-notifyCh: case <-time.After(s.config.BroadcastTimeout): return fmt.Errorf("timed out broadcasting node removal") } return nil }
go
func (s *Serf) RemoveFailedNode(node string) error { // Construct the message to broadcast msg := messageLeave{ LTime: s.clock.Time(), Node: node, } s.clock.Increment() // Process our own event s.handleNodeLeaveIntent(&msg) // If we have no members, then we don't need to broadcast if !s.hasAliveMembers() { return nil } // Broadcast the remove notifyCh := make(chan struct{}) if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil { return err } // Wait for the broadcast select { case <-notifyCh: case <-time.After(s.config.BroadcastTimeout): return fmt.Errorf("timed out broadcasting node removal") } return nil }
[ "func", "(", "s", "*", "Serf", ")", "RemoveFailedNode", "(", "node", "string", ")", "error", "{", "// Construct the message to broadcast", "msg", ":=", "messageLeave", "{", "LTime", ":", "s", ".", "clock", ".", "Time", "(", ")", ",", "Node", ":", "node", ...
// RemoveFailedNode forcibly removes a failed node from the cluster // immediately, instead of waiting for the reaper to eventually reclaim it. // This also has the effect that Serf will no longer attempt to reconnect // to this node.
[ "RemoveFailedNode", "forcibly", "removes", "a", "failed", "node", "from", "the", "cluster", "immediately", "instead", "of", "waiting", "for", "the", "reaper", "to", "eventually", "reclaim", "it", ".", "This", "also", "has", "the", "effect", "that", "Serf", "wi...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L788-L818
166,184
hashicorp/serf
serf/serf.go
Shutdown
func (s *Serf) Shutdown() error { s.stateLock.Lock() defer s.stateLock.Unlock() if s.state == SerfShutdown { return nil } if s.state != SerfLeft { s.logger.Printf("[WARN] serf: Shutdown without a Leave") } // Wait to close the shutdown channel until after we've shut down the // memberlist and its associated network resources, since the shutdown // channel signals that we are cleaned up outside of Serf. s.state = SerfShutdown err := s.memberlist.Shutdown() if err != nil { return err } close(s.shutdownCh) // Wait for the snapshoter to finish if we have one if s.snapshotter != nil { s.snapshotter.Wait() } return nil }
go
func (s *Serf) Shutdown() error { s.stateLock.Lock() defer s.stateLock.Unlock() if s.state == SerfShutdown { return nil } if s.state != SerfLeft { s.logger.Printf("[WARN] serf: Shutdown without a Leave") } // Wait to close the shutdown channel until after we've shut down the // memberlist and its associated network resources, since the shutdown // channel signals that we are cleaned up outside of Serf. s.state = SerfShutdown err := s.memberlist.Shutdown() if err != nil { return err } close(s.shutdownCh) // Wait for the snapshoter to finish if we have one if s.snapshotter != nil { s.snapshotter.Wait() } return nil }
[ "func", "(", "s", "*", "Serf", ")", "Shutdown", "(", ")", "error", "{", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "state", "==", "SerfShutdown", "{", "retu...
// Shutdown forcefully shuts down the Serf instance, stopping all network // activity and background maintenance associated with the instance. // // This is not a graceful shutdown, and should be preceded by a call // to Leave. Otherwise, other nodes in the cluster will detect this node's // exit as a node failure. // // It is safe to call this method multiple times.
[ "Shutdown", "forcefully", "shuts", "down", "the", "Serf", "instance", "stopping", "all", "network", "activity", "and", "background", "maintenance", "associated", "with", "the", "instance", ".", "This", "is", "not", "a", "graceful", "shutdown", "and", "should", "...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L828-L856
166,185
hashicorp/serf
serf/serf.go
State
func (s *Serf) State() SerfState { s.stateLock.Lock() defer s.stateLock.Unlock() return s.state }
go
func (s *Serf) State() SerfState { s.stateLock.Lock() defer s.stateLock.Unlock() return s.state }
[ "func", "(", "s", "*", "Serf", ")", "State", "(", ")", "SerfState", "{", "s", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "state", "\n", "}" ]
// State is the current state of this Serf instance.
[ "State", "is", "the", "current", "state", "of", "this", "Serf", "instance", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L870-L874
166,186
hashicorp/serf
serf/serf.go
broadcast
func (s *Serf) broadcast(t messageType, msg interface{}, notify chan<- struct{}) error { raw, err := encodeMessage(t, msg) if err != nil { return err } s.broadcasts.QueueBroadcast(&broadcast{ msg: raw, notify: notify, }) return nil }
go
func (s *Serf) broadcast(t messageType, msg interface{}, notify chan<- struct{}) error { raw, err := encodeMessage(t, msg) if err != nil { return err } s.broadcasts.QueueBroadcast(&broadcast{ msg: raw, notify: notify, }) return nil }
[ "func", "(", "s", "*", "Serf", ")", "broadcast", "(", "t", "messageType", ",", "msg", "interface", "{", "}", ",", "notify", "chan", "<-", "struct", "{", "}", ")", "error", "{", "raw", ",", "err", ":=", "encodeMessage", "(", "t", ",", "msg", ")", ...
// broadcast takes a Serf message type, encodes it for the wire, and queues // the broadcast. If a notify channel is given, this channel will be closed // when the broadcast is sent.
[ "broadcast", "takes", "a", "Serf", "message", "type", "encodes", "it", "for", "the", "wire", "and", "queues", "the", "broadcast", ".", "If", "a", "notify", "channel", "is", "given", "this", "channel", "will", "be", "closed", "when", "the", "broadcast", "is...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L879-L890
166,187
hashicorp/serf
serf/serf.go
handleNodeJoin
func (s *Serf) handleNodeJoin(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() var oldStatus MemberStatus member, ok := s.members[n.Name] if !ok { oldStatus = StatusNone member = &memberState{ Member: Member{ Name: n.Name, Addr: net.IP(n.Addr), Port: n.Port, Tags: s.decodeTags(n.Meta), Status: StatusAlive, }, } // Check if we have a join or leave intent. The intent buffer // will only hold one event for this node, so the more recent // one will take effect. if join, ok := recentIntent(s.recentIntents, n.Name, messageJoinType); ok { member.statusLTime = join } if leave, ok := recentIntent(s.recentIntents, n.Name, messageLeaveType); ok { member.Status = StatusLeaving member.statusLTime = leave } s.members[n.Name] = member } else { oldStatus = member.Status deadTime := time.Now().Sub(member.leaveTime) if oldStatus == StatusFailed && deadTime < s.config.FlapTimeout { metrics.IncrCounter([]string{"serf", "member", "flap"}, 1) } member.Status = StatusAlive member.leaveTime = time.Time{} member.Addr = net.IP(n.Addr) member.Port = n.Port member.Tags = s.decodeTags(n.Meta) } // Update the protocol versions every time we get an event member.ProtocolMin = n.PMin member.ProtocolMax = n.PMax member.ProtocolCur = n.PCur member.DelegateMin = n.DMin member.DelegateMax = n.DMax member.DelegateCur = n.DCur // If node was previously in a failed state, then clean up some // internal accounting. // TODO(mitchellh): needs tests to verify not reaped if oldStatus == StatusFailed || oldStatus == StatusLeft { s.failedMembers = removeOldMember(s.failedMembers, member.Name) s.leftMembers = removeOldMember(s.leftMembers, member.Name) } // Update some metrics metrics.IncrCounter([]string{"serf", "member", "join"}, 1) // Send an event along s.logger.Printf("[INFO] serf: EventMemberJoin: %s %s", member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberJoin, Members: []Member{member.Member}, } } }
go
func (s *Serf) handleNodeJoin(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() var oldStatus MemberStatus member, ok := s.members[n.Name] if !ok { oldStatus = StatusNone member = &memberState{ Member: Member{ Name: n.Name, Addr: net.IP(n.Addr), Port: n.Port, Tags: s.decodeTags(n.Meta), Status: StatusAlive, }, } // Check if we have a join or leave intent. The intent buffer // will only hold one event for this node, so the more recent // one will take effect. if join, ok := recentIntent(s.recentIntents, n.Name, messageJoinType); ok { member.statusLTime = join } if leave, ok := recentIntent(s.recentIntents, n.Name, messageLeaveType); ok { member.Status = StatusLeaving member.statusLTime = leave } s.members[n.Name] = member } else { oldStatus = member.Status deadTime := time.Now().Sub(member.leaveTime) if oldStatus == StatusFailed && deadTime < s.config.FlapTimeout { metrics.IncrCounter([]string{"serf", "member", "flap"}, 1) } member.Status = StatusAlive member.leaveTime = time.Time{} member.Addr = net.IP(n.Addr) member.Port = n.Port member.Tags = s.decodeTags(n.Meta) } // Update the protocol versions every time we get an event member.ProtocolMin = n.PMin member.ProtocolMax = n.PMax member.ProtocolCur = n.PCur member.DelegateMin = n.DMin member.DelegateMax = n.DMax member.DelegateCur = n.DCur // If node was previously in a failed state, then clean up some // internal accounting. // TODO(mitchellh): needs tests to verify not reaped if oldStatus == StatusFailed || oldStatus == StatusLeft { s.failedMembers = removeOldMember(s.failedMembers, member.Name) s.leftMembers = removeOldMember(s.leftMembers, member.Name) } // Update some metrics metrics.IncrCounter([]string{"serf", "member", "join"}, 1) // Send an event along s.logger.Printf("[INFO] serf: EventMemberJoin: %s %s", member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberJoin, Members: []Member{member.Member}, } } }
[ "func", "(", "s", "*", "Serf", ")", "handleNodeJoin", "(", "n", "*", "memberlist", ".", "Node", ")", "{", "s", ".", "memberLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "Unlock", "(", ")", "\n\n", "var", "oldStatus", "Me...
// handleNodeJoin is called when a node join event is received // from memberlist.
[ "handleNodeJoin", "is", "called", "when", "a", "node", "join", "event", "is", "received", "from", "memberlist", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L894-L966
166,188
hashicorp/serf
serf/serf.go
handleNodeLeave
func (s *Serf) handleNodeLeave(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[n.Name] if !ok { // We've never even heard of this node that is supposedly // leaving. Just ignore it completely. return } switch member.Status { case StatusLeaving: member.Status = StatusLeft member.leaveTime = time.Now() s.leftMembers = append(s.leftMembers, member) case StatusAlive: member.Status = StatusFailed member.leaveTime = time.Now() s.failedMembers = append(s.failedMembers, member) default: // Unknown state that it was in? Just don't do anything s.logger.Printf("[WARN] serf: Bad state when leave: %d", member.Status) return } // Send an event along event := EventMemberLeave eventStr := "EventMemberLeave" if member.Status != StatusLeft { event = EventMemberFailed eventStr = "EventMemberFailed" } // Update some metrics metrics.IncrCounter([]string{"serf", "member", member.Status.String()}, 1) s.logger.Printf("[INFO] serf: %s: %s %s", eventStr, member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: event, Members: []Member{member.Member}, } } }
go
func (s *Serf) handleNodeLeave(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[n.Name] if !ok { // We've never even heard of this node that is supposedly // leaving. Just ignore it completely. return } switch member.Status { case StatusLeaving: member.Status = StatusLeft member.leaveTime = time.Now() s.leftMembers = append(s.leftMembers, member) case StatusAlive: member.Status = StatusFailed member.leaveTime = time.Now() s.failedMembers = append(s.failedMembers, member) default: // Unknown state that it was in? Just don't do anything s.logger.Printf("[WARN] serf: Bad state when leave: %d", member.Status) return } // Send an event along event := EventMemberLeave eventStr := "EventMemberLeave" if member.Status != StatusLeft { event = EventMemberFailed eventStr = "EventMemberFailed" } // Update some metrics metrics.IncrCounter([]string{"serf", "member", member.Status.String()}, 1) s.logger.Printf("[INFO] serf: %s: %s %s", eventStr, member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: event, Members: []Member{member.Member}, } } }
[ "func", "(", "s", "*", "Serf", ")", "handleNodeLeave", "(", "n", "*", "memberlist", ".", "Node", ")", "{", "s", ".", "memberLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "Unlock", "(", ")", "\n\n", "member", ",", "ok", ...
// handleNodeLeave is called when a node leave event is received // from memberlist.
[ "handleNodeLeave", "is", "called", "when", "a", "node", "leave", "event", "is", "received", "from", "memberlist", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L970-L1015
166,189
hashicorp/serf
serf/serf.go
handleNodeUpdate
func (s *Serf) handleNodeUpdate(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[n.Name] if !ok { // We've never even heard of this node that is updating. // Just ignore it completely. return } // Update the member attributes member.Addr = net.IP(n.Addr) member.Port = n.Port member.Tags = s.decodeTags(n.Meta) // Snag the latest versions. NOTE - the current memberlist code will NOT // fire an update event if the metadata (for Serf, tags) stays the same // and only the protocol versions change. If we wake any Serf-level // protocol changes where we want to get this event under those // circumstances, we will need to update memberlist to do a check of // versions as well as the metadata. member.ProtocolMin = n.PMin member.ProtocolMax = n.PMax member.ProtocolCur = n.PCur member.DelegateMin = n.DMin member.DelegateMax = n.DMax member.DelegateCur = n.DCur // Update some metrics metrics.IncrCounter([]string{"serf", "member", "update"}, 1) // Send an event along s.logger.Printf("[INFO] serf: EventMemberUpdate: %s", member.Member.Name) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberUpdate, Members: []Member{member.Member}, } } }
go
func (s *Serf) handleNodeUpdate(n *memberlist.Node) { s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[n.Name] if !ok { // We've never even heard of this node that is updating. // Just ignore it completely. return } // Update the member attributes member.Addr = net.IP(n.Addr) member.Port = n.Port member.Tags = s.decodeTags(n.Meta) // Snag the latest versions. NOTE - the current memberlist code will NOT // fire an update event if the metadata (for Serf, tags) stays the same // and only the protocol versions change. If we wake any Serf-level // protocol changes where we want to get this event under those // circumstances, we will need to update memberlist to do a check of // versions as well as the metadata. member.ProtocolMin = n.PMin member.ProtocolMax = n.PMax member.ProtocolCur = n.PCur member.DelegateMin = n.DMin member.DelegateMax = n.DMax member.DelegateCur = n.DCur // Update some metrics metrics.IncrCounter([]string{"serf", "member", "update"}, 1) // Send an event along s.logger.Printf("[INFO] serf: EventMemberUpdate: %s", member.Member.Name) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberUpdate, Members: []Member{member.Member}, } } }
[ "func", "(", "s", "*", "Serf", ")", "handleNodeUpdate", "(", "n", "*", "memberlist", ".", "Node", ")", "{", "s", ".", "memberLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "memberLock", ".", "Unlock", "(", ")", "\n\n", "member", ",", "ok", ...
// handleNodeUpdate is called when a node meta data update // has taken place
[ "handleNodeUpdate", "is", "called", "when", "a", "node", "meta", "data", "update", "has", "taken", "place" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1019-L1059
166,190
hashicorp/serf
serf/serf.go
handleNodeLeaveIntent
func (s *Serf) handleNodeLeaveIntent(leaveMsg *messageLeave) bool { // Witness a potentially newer time s.clock.Witness(leaveMsg.LTime) s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[leaveMsg.Node] if !ok { // Rebroadcast only if this was an update we hadn't seen before. return upsertIntent(s.recentIntents, leaveMsg.Node, messageLeaveType, leaveMsg.LTime, time.Now) } // If the message is old, then it is irrelevant and we can skip it if leaveMsg.LTime <= member.statusLTime { return false } // Refute us leaving if we are in the alive state // Must be done in another goroutine since we have the memberLock if leaveMsg.Node == s.config.NodeName && s.state == SerfAlive { s.logger.Printf("[DEBUG] serf: Refuting an older leave intent") go s.broadcastJoin(s.clock.Time()) return false } // State transition depends on current state switch member.Status { case StatusAlive: member.Status = StatusLeaving member.statusLTime = leaveMsg.LTime return true case StatusFailed: member.Status = StatusLeft member.statusLTime = leaveMsg.LTime // Remove from the failed list and add to the left list. We add // to the left list so that when we do a sync, other nodes will // remove it from their failed list. s.failedMembers = removeOldMember(s.failedMembers, member.Name) s.leftMembers = append(s.leftMembers, member) // We must push a message indicating the node has now // left to allow higher-level applications to handle the // graceful leave. s.logger.Printf("[INFO] serf: EventMemberLeave (forced): %s %s", member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberLeave, Members: []Member{member.Member}, } } return true default: return false } }
go
func (s *Serf) handleNodeLeaveIntent(leaveMsg *messageLeave) bool { // Witness a potentially newer time s.clock.Witness(leaveMsg.LTime) s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[leaveMsg.Node] if !ok { // Rebroadcast only if this was an update we hadn't seen before. return upsertIntent(s.recentIntents, leaveMsg.Node, messageLeaveType, leaveMsg.LTime, time.Now) } // If the message is old, then it is irrelevant and we can skip it if leaveMsg.LTime <= member.statusLTime { return false } // Refute us leaving if we are in the alive state // Must be done in another goroutine since we have the memberLock if leaveMsg.Node == s.config.NodeName && s.state == SerfAlive { s.logger.Printf("[DEBUG] serf: Refuting an older leave intent") go s.broadcastJoin(s.clock.Time()) return false } // State transition depends on current state switch member.Status { case StatusAlive: member.Status = StatusLeaving member.statusLTime = leaveMsg.LTime return true case StatusFailed: member.Status = StatusLeft member.statusLTime = leaveMsg.LTime // Remove from the failed list and add to the left list. We add // to the left list so that when we do a sync, other nodes will // remove it from their failed list. s.failedMembers = removeOldMember(s.failedMembers, member.Name) s.leftMembers = append(s.leftMembers, member) // We must push a message indicating the node has now // left to allow higher-level applications to handle the // graceful leave. s.logger.Printf("[INFO] serf: EventMemberLeave (forced): %s %s", member.Member.Name, member.Member.Addr) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberLeave, Members: []Member{member.Member}, } } return true default: return false } }
[ "func", "(", "s", "*", "Serf", ")", "handleNodeLeaveIntent", "(", "leaveMsg", "*", "messageLeave", ")", "bool", "{", "// Witness a potentially newer time", "s", ".", "clock", ".", "Witness", "(", "leaveMsg", ".", "LTime", ")", "\n\n", "s", ".", "memberLock", ...
// handleNodeLeaveIntent is called when an intent to leave is received.
[ "handleNodeLeaveIntent", "is", "called", "when", "an", "intent", "to", "leave", "is", "received", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1062-L1119
166,191
hashicorp/serf
serf/serf.go
handleNodeJoinIntent
func (s *Serf) handleNodeJoinIntent(joinMsg *messageJoin) bool { // Witness a potentially newer time s.clock.Witness(joinMsg.LTime) s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[joinMsg.Node] if !ok { // Rebroadcast only if this was an update we hadn't seen before. return upsertIntent(s.recentIntents, joinMsg.Node, messageJoinType, joinMsg.LTime, time.Now) } // Check if this time is newer than what we have if joinMsg.LTime <= member.statusLTime { return false } // Update the LTime member.statusLTime = joinMsg.LTime // If we are in the leaving state, we should go back to alive, // since the leaving message must have been for an older time if member.Status == StatusLeaving { member.Status = StatusAlive } return true }
go
func (s *Serf) handleNodeJoinIntent(joinMsg *messageJoin) bool { // Witness a potentially newer time s.clock.Witness(joinMsg.LTime) s.memberLock.Lock() defer s.memberLock.Unlock() member, ok := s.members[joinMsg.Node] if !ok { // Rebroadcast only if this was an update we hadn't seen before. return upsertIntent(s.recentIntents, joinMsg.Node, messageJoinType, joinMsg.LTime, time.Now) } // Check if this time is newer than what we have if joinMsg.LTime <= member.statusLTime { return false } // Update the LTime member.statusLTime = joinMsg.LTime // If we are in the leaving state, we should go back to alive, // since the leaving message must have been for an older time if member.Status == StatusLeaving { member.Status = StatusAlive } return true }
[ "func", "(", "s", "*", "Serf", ")", "handleNodeJoinIntent", "(", "joinMsg", "*", "messageJoin", ")", "bool", "{", "// Witness a potentially newer time", "s", ".", "clock", ".", "Witness", "(", "joinMsg", ".", "LTime", ")", "\n\n", "s", ".", "memberLock", "."...
// handleNodeJoinIntent is called when a node broadcasts a // join message to set the lamport time of its join
[ "handleNodeJoinIntent", "is", "called", "when", "a", "node", "broadcasts", "a", "join", "message", "to", "set", "the", "lamport", "time", "of", "its", "join" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1123-L1150
166,192
hashicorp/serf
serf/serf.go
handleUserEvent
func (s *Serf) handleUserEvent(eventMsg *messageUserEvent) bool { // Witness a potentially newer time s.eventClock.Witness(eventMsg.LTime) s.eventLock.Lock() defer s.eventLock.Unlock() // Ignore if it is before our minimum event time if eventMsg.LTime < s.eventMinTime { return false } // Check if this message is too old curTime := s.eventClock.Time() if curTime > LamportTime(len(s.eventBuffer)) && eventMsg.LTime < curTime-LamportTime(len(s.eventBuffer)) { s.logger.Printf( "[WARN] serf: received old event %s from time %d (current: %d)", eventMsg.Name, eventMsg.LTime, s.eventClock.Time()) return false } // Check if we've already seen this idx := eventMsg.LTime % LamportTime(len(s.eventBuffer)) seen := s.eventBuffer[idx] userEvent := userEvent{Name: eventMsg.Name, Payload: eventMsg.Payload} if seen != nil && seen.LTime == eventMsg.LTime { for _, previous := range seen.Events { if previous.Equals(&userEvent) { return false } } } else { seen = &userEvents{LTime: eventMsg.LTime} s.eventBuffer[idx] = seen } // Add to recent events seen.Events = append(seen.Events, userEvent) // Update some metrics metrics.IncrCounter([]string{"serf", "events"}, 1) metrics.IncrCounter([]string{"serf", "events", eventMsg.Name}, 1) if s.config.EventCh != nil { s.config.EventCh <- UserEvent{ LTime: eventMsg.LTime, Name: eventMsg.Name, Payload: eventMsg.Payload, Coalesce: eventMsg.CC, } } return true }
go
func (s *Serf) handleUserEvent(eventMsg *messageUserEvent) bool { // Witness a potentially newer time s.eventClock.Witness(eventMsg.LTime) s.eventLock.Lock() defer s.eventLock.Unlock() // Ignore if it is before our minimum event time if eventMsg.LTime < s.eventMinTime { return false } // Check if this message is too old curTime := s.eventClock.Time() if curTime > LamportTime(len(s.eventBuffer)) && eventMsg.LTime < curTime-LamportTime(len(s.eventBuffer)) { s.logger.Printf( "[WARN] serf: received old event %s from time %d (current: %d)", eventMsg.Name, eventMsg.LTime, s.eventClock.Time()) return false } // Check if we've already seen this idx := eventMsg.LTime % LamportTime(len(s.eventBuffer)) seen := s.eventBuffer[idx] userEvent := userEvent{Name: eventMsg.Name, Payload: eventMsg.Payload} if seen != nil && seen.LTime == eventMsg.LTime { for _, previous := range seen.Events { if previous.Equals(&userEvent) { return false } } } else { seen = &userEvents{LTime: eventMsg.LTime} s.eventBuffer[idx] = seen } // Add to recent events seen.Events = append(seen.Events, userEvent) // Update some metrics metrics.IncrCounter([]string{"serf", "events"}, 1) metrics.IncrCounter([]string{"serf", "events", eventMsg.Name}, 1) if s.config.EventCh != nil { s.config.EventCh <- UserEvent{ LTime: eventMsg.LTime, Name: eventMsg.Name, Payload: eventMsg.Payload, Coalesce: eventMsg.CC, } } return true }
[ "func", "(", "s", "*", "Serf", ")", "handleUserEvent", "(", "eventMsg", "*", "messageUserEvent", ")", "bool", "{", "// Witness a potentially newer time", "s", ".", "eventClock", ".", "Witness", "(", "eventMsg", ".", "LTime", ")", "\n\n", "s", ".", "eventLock",...
// handleUserEvent is called when a user event broadcast is // received. Returns if the message should be rebroadcast.
[ "handleUserEvent", "is", "called", "when", "a", "user", "event", "broadcast", "is", "received", ".", "Returns", "if", "the", "message", "should", "be", "rebroadcast", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1154-L1209
166,193
hashicorp/serf
serf/serf.go
handleQueryResponse
func (s *Serf) handleQueryResponse(resp *messageQueryResponse) { // Look for a corresponding QueryResponse s.queryLock.RLock() query, ok := s.queryResponse[resp.LTime] s.queryLock.RUnlock() if !ok { s.logger.Printf("[WARN] serf: reply for non-running query (LTime: %d, ID: %d) From: %s", resp.LTime, resp.ID, resp.From) return } // Verify the ID matches if query.id != resp.ID { s.logger.Printf("[WARN] serf: query reply ID mismatch (Local: %d, Response: %d)", query.id, resp.ID) return } // Check if the query is closed if query.Finished() { return } // Process each type of response if resp.Ack() { // Exit early if this is a duplicate ack if _, ok := query.acks[resp.From]; ok { metrics.IncrCounter([]string{"serf", "query_duplicate_acks"}, 1) return } metrics.IncrCounter([]string{"serf", "query_acks"}, 1) select { case query.ackCh <- resp.From: query.acks[resp.From] = struct{}{} default: s.logger.Printf("[WARN] serf: Failed to deliver query ack, dropping") } } else { // Exit early if this is a duplicate response if _, ok := query.responses[resp.From]; ok { metrics.IncrCounter([]string{"serf", "query_duplicate_responses"}, 1) return } metrics.IncrCounter([]string{"serf", "query_responses"}, 1) err := query.sendResponse(NodeResponse{From: resp.From, Payload: resp.Payload}) if err != nil { s.logger.Printf("[WARN] %v", err) } } }
go
func (s *Serf) handleQueryResponse(resp *messageQueryResponse) { // Look for a corresponding QueryResponse s.queryLock.RLock() query, ok := s.queryResponse[resp.LTime] s.queryLock.RUnlock() if !ok { s.logger.Printf("[WARN] serf: reply for non-running query (LTime: %d, ID: %d) From: %s", resp.LTime, resp.ID, resp.From) return } // Verify the ID matches if query.id != resp.ID { s.logger.Printf("[WARN] serf: query reply ID mismatch (Local: %d, Response: %d)", query.id, resp.ID) return } // Check if the query is closed if query.Finished() { return } // Process each type of response if resp.Ack() { // Exit early if this is a duplicate ack if _, ok := query.acks[resp.From]; ok { metrics.IncrCounter([]string{"serf", "query_duplicate_acks"}, 1) return } metrics.IncrCounter([]string{"serf", "query_acks"}, 1) select { case query.ackCh <- resp.From: query.acks[resp.From] = struct{}{} default: s.logger.Printf("[WARN] serf: Failed to deliver query ack, dropping") } } else { // Exit early if this is a duplicate response if _, ok := query.responses[resp.From]; ok { metrics.IncrCounter([]string{"serf", "query_duplicate_responses"}, 1) return } metrics.IncrCounter([]string{"serf", "query_responses"}, 1) err := query.sendResponse(NodeResponse{From: resp.From, Payload: resp.Payload}) if err != nil { s.logger.Printf("[WARN] %v", err) } } }
[ "func", "(", "s", "*", "Serf", ")", "handleQueryResponse", "(", "resp", "*", "messageQueryResponse", ")", "{", "// Look for a corresponding QueryResponse", "s", ".", "queryLock", ".", "RLock", "(", ")", "\n", "query", ",", "ok", ":=", "s", ".", "queryResponse"...
// handleResponse is called when a query response is // received.
[ "handleResponse", "is", "called", "when", "a", "query", "response", "is", "received", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1312-L1363
166,194
hashicorp/serf
serf/serf.go
resolveNodeConflict
func (s *Serf) resolveNodeConflict() { // Get the local node local := s.memberlist.LocalNode() // Start a name resolution query qName := internalQueryName(conflictQuery) payload := []byte(s.config.NodeName) resp, err := s.Query(qName, payload, nil) if err != nil { s.logger.Printf("[ERR] serf: Failed to start name resolution query: %v", err) return } // Counter to determine winner var responses, matching int // Gather responses respCh := resp.ResponseCh() for r := range respCh { // Decode the response if len(r.Payload) < 1 || messageType(r.Payload[0]) != messageConflictResponseType { s.logger.Printf("[ERR] serf: Invalid conflict query response type: %v", r.Payload) continue } var member Member if err := decodeMessage(r.Payload[1:], &member); err != nil { s.logger.Printf("[ERR] serf: Failed to decode conflict query response: %v", err) continue } // Update the counters responses++ if member.Addr.Equal(local.Addr) && member.Port == local.Port { matching++ } } // Query over, determine if we should live majority := (responses / 2) + 1 if matching >= majority { s.logger.Printf("[INFO] serf: majority in name conflict resolution [%d / %d]", matching, responses) return } // Since we lost the vote, we need to exit s.logger.Printf("[WARN] serf: minority in name conflict resolution, quiting [%d / %d]", matching, responses) if err := s.Shutdown(); err != nil { s.logger.Printf("[ERR] serf: Failed to shutdown: %v", err) } }
go
func (s *Serf) resolveNodeConflict() { // Get the local node local := s.memberlist.LocalNode() // Start a name resolution query qName := internalQueryName(conflictQuery) payload := []byte(s.config.NodeName) resp, err := s.Query(qName, payload, nil) if err != nil { s.logger.Printf("[ERR] serf: Failed to start name resolution query: %v", err) return } // Counter to determine winner var responses, matching int // Gather responses respCh := resp.ResponseCh() for r := range respCh { // Decode the response if len(r.Payload) < 1 || messageType(r.Payload[0]) != messageConflictResponseType { s.logger.Printf("[ERR] serf: Invalid conflict query response type: %v", r.Payload) continue } var member Member if err := decodeMessage(r.Payload[1:], &member); err != nil { s.logger.Printf("[ERR] serf: Failed to decode conflict query response: %v", err) continue } // Update the counters responses++ if member.Addr.Equal(local.Addr) && member.Port == local.Port { matching++ } } // Query over, determine if we should live majority := (responses / 2) + 1 if matching >= majority { s.logger.Printf("[INFO] serf: majority in name conflict resolution [%d / %d]", matching, responses) return } // Since we lost the vote, we need to exit s.logger.Printf("[WARN] serf: minority in name conflict resolution, quiting [%d / %d]", matching, responses) if err := s.Shutdown(); err != nil { s.logger.Printf("[ERR] serf: Failed to shutdown: %v", err) } }
[ "func", "(", "s", "*", "Serf", ")", "resolveNodeConflict", "(", ")", "{", "// Get the local node", "local", ":=", "s", ".", "memberlist", ".", "LocalNode", "(", ")", "\n\n", "// Start a name resolution query", "qName", ":=", "internalQueryName", "(", "conflictQuer...
// resolveNodeConflict is used to determine which node should remain during // a name conflict. This is done by running an internal query.
[ "resolveNodeConflict", "is", "used", "to", "determine", "which", "node", "should", "remain", "during", "a", "name", "conflict", ".", "This", "is", "done", "by", "running", "an", "internal", "query", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1388-L1439
166,195
hashicorp/serf
serf/serf.go
handleReap
func (s *Serf) handleReap() { for { select { case <-time.After(s.config.ReapInterval): s.memberLock.Lock() now := time.Now() s.failedMembers = s.reap(s.failedMembers, now, s.config.ReconnectTimeout) s.leftMembers = s.reap(s.leftMembers, now, s.config.TombstoneTimeout) reapIntents(s.recentIntents, now, s.config.RecentIntentTimeout) s.memberLock.Unlock() case <-s.shutdownCh: return } } }
go
func (s *Serf) handleReap() { for { select { case <-time.After(s.config.ReapInterval): s.memberLock.Lock() now := time.Now() s.failedMembers = s.reap(s.failedMembers, now, s.config.ReconnectTimeout) s.leftMembers = s.reap(s.leftMembers, now, s.config.TombstoneTimeout) reapIntents(s.recentIntents, now, s.config.RecentIntentTimeout) s.memberLock.Unlock() case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "Serf", ")", "handleReap", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "s", ".", "config", ".", "ReapInterval", ")", ":", "s", ".", "memberLock", ".", "Lock", "(", ")", "\n", "now", ...
// handleReap periodically reaps the list of failed and left members, as well // as old buffered intents.
[ "handleReap", "periodically", "reaps", "the", "list", "of", "failed", "and", "left", "members", "as", "well", "as", "old", "buffered", "intents", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1443-L1457
166,196
hashicorp/serf
serf/serf.go
handleReconnect
func (s *Serf) handleReconnect() { for { select { case <-time.After(s.config.ReconnectInterval): s.reconnect() case <-s.shutdownCh: return } } }
go
func (s *Serf) handleReconnect() { for { select { case <-time.After(s.config.ReconnectInterval): s.reconnect() case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "Serf", ")", "handleReconnect", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "s", ".", "config", ".", "ReconnectInterval", ")", ":", "s", ".", "reconnect", "(", ")", "\n", "case", "<-", ...
// handleReconnect attempts to reconnect to recently failed nodes // on configured intervals.
[ "handleReconnect", "attempts", "to", "reconnect", "to", "recently", "failed", "nodes", "on", "configured", "intervals", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1461-L1470
166,197
hashicorp/serf
serf/serf.go
reap
func (s *Serf) reap(old []*memberState, now time.Time, timeout time.Duration) []*memberState { n := len(old) for i := 0; i < n; i++ { m := old[i] // Skip if the timeout is not yet reached if now.Sub(m.leaveTime) <= timeout { continue } // Delete from the list old[i], old[n-1] = old[n-1], nil old = old[:n-1] n-- i-- // Delete from members delete(s.members, m.Name) // Tell the coordinate client the node has gone away and delete // its cached coordinates. if !s.config.DisableCoordinates { s.coordClient.ForgetNode(m.Name) s.coordCacheLock.Lock() delete(s.coordCache, m.Name) s.coordCacheLock.Unlock() } // Send an event along s.logger.Printf("[INFO] serf: EventMemberReap: %s", m.Name) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberReap, Members: []Member{m.Member}, } } } return old }
go
func (s *Serf) reap(old []*memberState, now time.Time, timeout time.Duration) []*memberState { n := len(old) for i := 0; i < n; i++ { m := old[i] // Skip if the timeout is not yet reached if now.Sub(m.leaveTime) <= timeout { continue } // Delete from the list old[i], old[n-1] = old[n-1], nil old = old[:n-1] n-- i-- // Delete from members delete(s.members, m.Name) // Tell the coordinate client the node has gone away and delete // its cached coordinates. if !s.config.DisableCoordinates { s.coordClient.ForgetNode(m.Name) s.coordCacheLock.Lock() delete(s.coordCache, m.Name) s.coordCacheLock.Unlock() } // Send an event along s.logger.Printf("[INFO] serf: EventMemberReap: %s", m.Name) if s.config.EventCh != nil { s.config.EventCh <- MemberEvent{ Type: EventMemberReap, Members: []Member{m.Member}, } } } return old }
[ "func", "(", "s", "*", "Serf", ")", "reap", "(", "old", "[", "]", "*", "memberState", ",", "now", "time", ".", "Time", ",", "timeout", "time", ".", "Duration", ")", "[", "]", "*", "memberState", "{", "n", ":=", "len", "(", "old", ")", "\n", "fo...
// reap is called with a list of old members and a timeout, and removes // members that have exceeded the timeout. The members are removed from // both the old list and the members itself. Locking is left to the caller.
[ "reap", "is", "called", "with", "a", "list", "of", "old", "members", "and", "a", "timeout", "and", "removes", "members", "that", "have", "exceeded", "the", "timeout", ".", "The", "members", "are", "removed", "from", "both", "the", "old", "list", "and", "...
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1475-L1515
166,198
hashicorp/serf
serf/serf.go
reconnect
func (s *Serf) reconnect() { s.memberLock.RLock() // Nothing to do if there are no failed members n := len(s.failedMembers) if n == 0 { s.memberLock.RUnlock() return } // Probability we should attempt to reconect is given // by num failed / (num members - num failed - num left) // This means that we probabilistically expect the cluster // to attempt to connect to each failed member once per // reconnect interval numFailed := float32(len(s.failedMembers)) numAlive := float32(len(s.members) - len(s.failedMembers) - len(s.leftMembers)) if numAlive == 0 { numAlive = 1 // guard against zero divide } prob := numFailed / numAlive if rand.Float32() > prob { s.memberLock.RUnlock() s.logger.Printf("[DEBUG] serf: forgoing reconnect for random throttling") return } // Select a random member to try and join idx := rand.Int31n(int32(n)) mem := s.failedMembers[idx] s.memberLock.RUnlock() // Format the addr addr := net.UDPAddr{IP: mem.Addr, Port: int(mem.Port)} s.logger.Printf("[INFO] serf: attempting reconnect to %v %s", mem.Name, addr.String()) // Attempt to join at the memberlist level s.memberlist.Join([]string{addr.String()}) }
go
func (s *Serf) reconnect() { s.memberLock.RLock() // Nothing to do if there are no failed members n := len(s.failedMembers) if n == 0 { s.memberLock.RUnlock() return } // Probability we should attempt to reconect is given // by num failed / (num members - num failed - num left) // This means that we probabilistically expect the cluster // to attempt to connect to each failed member once per // reconnect interval numFailed := float32(len(s.failedMembers)) numAlive := float32(len(s.members) - len(s.failedMembers) - len(s.leftMembers)) if numAlive == 0 { numAlive = 1 // guard against zero divide } prob := numFailed / numAlive if rand.Float32() > prob { s.memberLock.RUnlock() s.logger.Printf("[DEBUG] serf: forgoing reconnect for random throttling") return } // Select a random member to try and join idx := rand.Int31n(int32(n)) mem := s.failedMembers[idx] s.memberLock.RUnlock() // Format the addr addr := net.UDPAddr{IP: mem.Addr, Port: int(mem.Port)} s.logger.Printf("[INFO] serf: attempting reconnect to %v %s", mem.Name, addr.String()) // Attempt to join at the memberlist level s.memberlist.Join([]string{addr.String()}) }
[ "func", "(", "s", "*", "Serf", ")", "reconnect", "(", ")", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "\n\n", "// Nothing to do if there are no failed members", "n", ":=", "len", "(", "s", ".", "failedMembers", ")", "\n", "if", "n", "==", "0", ...
// reconnect attempts to reconnect to recently fail nodes.
[ "reconnect", "attempts", "to", "reconnect", "to", "recently", "fail", "nodes", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1518-L1556
166,199
hashicorp/serf
serf/serf.go
getQueueMax
func (s *Serf) getQueueMax() int { max := s.config.MaxQueueDepth if s.config.MinQueueDepth > 0 { s.memberLock.RLock() max = 2 * len(s.members) s.memberLock.RUnlock() if max < s.config.MinQueueDepth { max = s.config.MinQueueDepth } } return max }
go
func (s *Serf) getQueueMax() int { max := s.config.MaxQueueDepth if s.config.MinQueueDepth > 0 { s.memberLock.RLock() max = 2 * len(s.members) s.memberLock.RUnlock() if max < s.config.MinQueueDepth { max = s.config.MinQueueDepth } } return max }
[ "func", "(", "s", "*", "Serf", ")", "getQueueMax", "(", ")", "int", "{", "max", ":=", "s", ".", "config", ".", "MaxQueueDepth", "\n", "if", "s", ".", "config", ".", "MinQueueDepth", ">", "0", "{", "s", ".", "memberLock", ".", "RLock", "(", ")", "...
// getQueueMax will get the maximum queue depth, which might be dynamic depending // on how Serf is configured.
[ "getQueueMax", "will", "get", "the", "maximum", "queue", "depth", "which", "might", "be", "dynamic", "depending", "on", "how", "Serf", "is", "configured", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/serf.go#L1560-L1572