repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
nlopes/slack
chat.go
PostMessageContext
func (api *Client) PostMessageContext(ctx context.Context, channelID string, options ...MsgOption) (string, string, error) { respChannel, respTimestamp, _, err := api.SendMessageContext( ctx, channelID, MsgOptionPost(), MsgOptionCompose(options...), ) return respChannel, respTimestamp, err }
go
func (api *Client) PostMessageContext(ctx context.Context, channelID string, options ...MsgOption) (string, string, error) { respChannel, respTimestamp, _, err := api.SendMessageContext( ctx, channelID, MsgOptionPost(), MsgOptionCompose(options...), ) return respChannel, respTimestamp, err }
[ "func", "(", "api", "*", "Client", ")", "PostMessageContext", "(", "ctx", "context", ".", "Context", ",", "channelID", "string", ",", "options", "...", "MsgOption", ")", "(", "string", ",", "string", ",", "error", ")", "{", "respChannel", ",", "respTimestamp", ",", "_", ",", "err", ":=", "api", ".", "SendMessageContext", "(", "ctx", ",", "channelID", ",", "MsgOptionPost", "(", ")", ",", "MsgOptionCompose", "(", "options", "...", ")", ",", ")", "\n", "return", "respChannel", ",", "respTimestamp", ",", "err", "\n", "}" ]
// PostMessageContext sends a message to a channel with a custom context // For more details, see PostMessage documentation.
[ "PostMessageContext", "sends", "a", "message", "to", "a", "channel", "with", "a", "custom", "context", "For", "more", "details", "see", "PostMessage", "documentation", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L109-L117
train
nlopes/slack
chat.go
PostEphemeralContext
func (api *Client) PostEphemeralContext(ctx context.Context, channelID, userID string, options ...MsgOption) (timestamp string, err error) { _, timestamp, _, err = api.SendMessageContext(ctx, channelID, MsgOptionPostEphemeral(userID), MsgOptionCompose(options...)) return timestamp, err }
go
func (api *Client) PostEphemeralContext(ctx context.Context, channelID, userID string, options ...MsgOption) (timestamp string, err error) { _, timestamp, _, err = api.SendMessageContext(ctx, channelID, MsgOptionPostEphemeral(userID), MsgOptionCompose(options...)) return timestamp, err }
[ "func", "(", "api", "*", "Client", ")", "PostEphemeralContext", "(", "ctx", "context", ".", "Context", ",", "channelID", ",", "userID", "string", ",", "options", "...", "MsgOption", ")", "(", "timestamp", "string", ",", "err", "error", ")", "{", "_", ",", "timestamp", ",", "_", ",", "err", "=", "api", ".", "SendMessageContext", "(", "ctx", ",", "channelID", ",", "MsgOptionPostEphemeral", "(", "userID", ")", ",", "MsgOptionCompose", "(", "options", "...", ")", ")", "\n", "return", "timestamp", ",", "err", "\n", "}" ]
// PostEphemeralContext sends an ephemeal message to a user in a channel with a custom context // For more details, see PostEphemeral documentation
[ "PostEphemeralContext", "sends", "an", "ephemeal", "message", "to", "a", "user", "in", "a", "channel", "with", "a", "custom", "context", "For", "more", "details", "see", "PostEphemeral", "documentation" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L133-L136
train
nlopes/slack
chat.go
UpdateMessage
func (api *Client) UpdateMessage(channelID, timestamp string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channelID, MsgOptionUpdate(timestamp), MsgOptionCompose(options...)) }
go
func (api *Client) UpdateMessage(channelID, timestamp string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channelID, MsgOptionUpdate(timestamp), MsgOptionCompose(options...)) }
[ "func", "(", "api", "*", "Client", ")", "UpdateMessage", "(", "channelID", ",", "timestamp", "string", ",", "options", "...", "MsgOption", ")", "(", "string", ",", "string", ",", "string", ",", "error", ")", "{", "return", "api", ".", "SendMessageContext", "(", "context", ".", "Background", "(", ")", ",", "channelID", ",", "MsgOptionUpdate", "(", "timestamp", ")", ",", "MsgOptionCompose", "(", "options", "...", ")", ")", "\n", "}" ]
// UpdateMessage updates a message in a channel
[ "UpdateMessage", "updates", "a", "message", "in", "a", "channel" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L139-L141
train
nlopes/slack
chat.go
UpdateMessageContext
func (api *Client) UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(ctx, channelID, MsgOptionUpdate(timestamp), MsgOptionCompose(options...)) }
go
func (api *Client) UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(ctx, channelID, MsgOptionUpdate(timestamp), MsgOptionCompose(options...)) }
[ "func", "(", "api", "*", "Client", ")", "UpdateMessageContext", "(", "ctx", "context", ".", "Context", ",", "channelID", ",", "timestamp", "string", ",", "options", "...", "MsgOption", ")", "(", "string", ",", "string", ",", "string", ",", "error", ")", "{", "return", "api", ".", "SendMessageContext", "(", "ctx", ",", "channelID", ",", "MsgOptionUpdate", "(", "timestamp", ")", ",", "MsgOptionCompose", "(", "options", "...", ")", ")", "\n", "}" ]
// UpdateMessageContext updates a message in a channel
[ "UpdateMessageContext", "updates", "a", "message", "in", "a", "channel" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L144-L146
train
nlopes/slack
chat.go
UnfurlMessage
func (api *Client) UnfurlMessage(channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channelID, MsgOptionUnfurl(timestamp, unfurls), MsgOptionCompose(options...)) }
go
func (api *Client) UnfurlMessage(channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channelID, MsgOptionUnfurl(timestamp, unfurls), MsgOptionCompose(options...)) }
[ "func", "(", "api", "*", "Client", ")", "UnfurlMessage", "(", "channelID", ",", "timestamp", "string", ",", "unfurls", "map", "[", "string", "]", "Attachment", ",", "options", "...", "MsgOption", ")", "(", "string", ",", "string", ",", "string", ",", "error", ")", "{", "return", "api", ".", "SendMessageContext", "(", "context", ".", "Background", "(", ")", ",", "channelID", ",", "MsgOptionUnfurl", "(", "timestamp", ",", "unfurls", ")", ",", "MsgOptionCompose", "(", "options", "...", ")", ")", "\n", "}" ]
// UnfurlMessage unfurls a message in a channel
[ "UnfurlMessage", "unfurls", "a", "message", "in", "a", "channel" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L149-L151
train
nlopes/slack
chat.go
SendMessage
func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channel, options...) }
go
func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error) { return api.SendMessageContext(context.Background(), channel, options...) }
[ "func", "(", "api", "*", "Client", ")", "SendMessage", "(", "channel", "string", ",", "options", "...", "MsgOption", ")", "(", "string", ",", "string", ",", "string", ",", "error", ")", "{", "return", "api", ".", "SendMessageContext", "(", "context", ".", "Background", "(", ")", ",", "channel", ",", "options", "...", ")", "\n", "}" ]
// SendMessage more flexible method for configuring messages.
[ "SendMessage", "more", "flexible", "method", "for", "configuring", "messages", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L154-L156
train
nlopes/slack
chat.go
SendMessageContext
func (api *Client) SendMessageContext(ctx context.Context, channelID string, options ...MsgOption) (channel string, timestamp string, text string, err error) { var ( config sendConfig response chatResponseFull ) if config, err = applyMsgOptions(api.token, channelID, api.endpoint, options...); err != nil { return "", "", "", err } if err = postForm(ctx, api.httpclient, config.endpoint, config.values, &response, api); err != nil { return "", "", "", err } return response.Channel, response.getMessageTimestamp(), response.Text, response.Err() }
go
func (api *Client) SendMessageContext(ctx context.Context, channelID string, options ...MsgOption) (channel string, timestamp string, text string, err error) { var ( config sendConfig response chatResponseFull ) if config, err = applyMsgOptions(api.token, channelID, api.endpoint, options...); err != nil { return "", "", "", err } if err = postForm(ctx, api.httpclient, config.endpoint, config.values, &response, api); err != nil { return "", "", "", err } return response.Channel, response.getMessageTimestamp(), response.Text, response.Err() }
[ "func", "(", "api", "*", "Client", ")", "SendMessageContext", "(", "ctx", "context", ".", "Context", ",", "channelID", "string", ",", "options", "...", "MsgOption", ")", "(", "channel", "string", ",", "timestamp", "string", ",", "text", "string", ",", "err", "error", ")", "{", "var", "(", "config", "sendConfig", "\n", "response", "chatResponseFull", "\n", ")", "\n", "if", "config", ",", "err", "=", "applyMsgOptions", "(", "api", ".", "token", ",", "channelID", ",", "api", ".", "endpoint", ",", "options", "...", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "\"\"", ",", "err", "\n", "}", "\n", "if", "err", "=", "postForm", "(", "ctx", ",", "api", ".", "httpclient", ",", "config", ".", "endpoint", ",", "config", ".", "values", ",", "&", "response", ",", "api", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "\"\"", ",", "err", "\n", "}", "\n", "return", "response", ".", "Channel", ",", "response", ".", "getMessageTimestamp", "(", ")", ",", "response", ".", "Text", ",", "response", ".", "Err", "(", ")", "\n", "}" ]
// SendMessageContext more flexible method for configuring messages with a custom context.
[ "SendMessageContext", "more", "flexible", "method", "for", "configuring", "messages", "with", "a", "custom", "context", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L159-L174
train
nlopes/slack
chat.go
MsgOptionPost
func MsgOptionPost() MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatPostMessage) config.values.Del("ts") return nil } }
go
func MsgOptionPost() MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatPostMessage) config.values.Del("ts") return nil } }
[ "func", "MsgOptionPost", "(", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatPostMessage", ")", "\n", "config", ".", "values", ".", "Del", "(", "\"ts\"", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionPost posts a messages, this is the default.
[ "MsgOptionPost", "posts", "a", "messages", "this", "is", "the", "default", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L224-L230
train
nlopes/slack
chat.go
MsgOptionPostEphemeral
func MsgOptionPostEphemeral(userID string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatPostEphemeral) MsgOptionUser(userID)(config) config.values.Del("ts") return nil } }
go
func MsgOptionPostEphemeral(userID string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatPostEphemeral) MsgOptionUser(userID)(config) config.values.Del("ts") return nil } }
[ "func", "MsgOptionPostEphemeral", "(", "userID", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatPostEphemeral", ")", "\n", "MsgOptionUser", "(", "userID", ")", "(", "config", ")", "\n", "config", ".", "values", ".", "Del", "(", "\"ts\"", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionPostEphemeral - posts an ephemeral message to the provided user.
[ "MsgOptionPostEphemeral", "-", "posts", "an", "ephemeral", "message", "to", "the", "provided", "user", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L233-L241
train
nlopes/slack
chat.go
MsgOptionMeMessage
func MsgOptionMeMessage() MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatMeMessage) return nil } }
go
func MsgOptionMeMessage() MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatMeMessage) return nil } }
[ "func", "MsgOptionMeMessage", "(", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatMeMessage", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionMeMessage posts a "me message" type from the calling user
[ "MsgOptionMeMessage", "posts", "a", "me", "message", "type", "from", "the", "calling", "user" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L244-L249
train
nlopes/slack
chat.go
MsgOptionUpdate
func MsgOptionUpdate(timestamp string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatUpdate) config.values.Add("ts", timestamp) return nil } }
go
func MsgOptionUpdate(timestamp string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatUpdate) config.values.Add("ts", timestamp) return nil } }
[ "func", "MsgOptionUpdate", "(", "timestamp", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatUpdate", ")", "\n", "config", ".", "values", ".", "Add", "(", "\"ts\"", ",", "timestamp", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionUpdate updates a message based on the timestamp.
[ "MsgOptionUpdate", "updates", "a", "message", "based", "on", "the", "timestamp", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L252-L258
train
nlopes/slack
chat.go
MsgOptionDelete
func MsgOptionDelete(timestamp string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatDelete) config.values.Add("ts", timestamp) return nil } }
go
func MsgOptionDelete(timestamp string) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatDelete) config.values.Add("ts", timestamp) return nil } }
[ "func", "MsgOptionDelete", "(", "timestamp", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatDelete", ")", "\n", "config", ".", "values", ".", "Add", "(", "\"ts\"", ",", "timestamp", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionDelete deletes a message based on the timestamp.
[ "MsgOptionDelete", "deletes", "a", "message", "based", "on", "the", "timestamp", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L261-L267
train
nlopes/slack
chat.go
MsgOptionUnfurl
func MsgOptionUnfurl(timestamp string, unfurls map[string]Attachment) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatUnfurl) config.values.Add("ts", timestamp) unfurlsStr, err := json.Marshal(unfurls) if err == nil { config.values.Add("unfurls", string(unfurlsStr)) } return err } }
go
func MsgOptionUnfurl(timestamp string, unfurls map[string]Attachment) MsgOption { return func(config *sendConfig) error { config.endpoint = config.apiurl + string(chatUnfurl) config.values.Add("ts", timestamp) unfurlsStr, err := json.Marshal(unfurls) if err == nil { config.values.Add("unfurls", string(unfurlsStr)) } return err } }
[ "func", "MsgOptionUnfurl", "(", "timestamp", "string", ",", "unfurls", "map", "[", "string", "]", "Attachment", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "endpoint", "=", "config", ".", "apiurl", "+", "string", "(", "chatUnfurl", ")", "\n", "config", ".", "values", ".", "Add", "(", "\"ts\"", ",", "timestamp", ")", "\n", "unfurlsStr", ",", "err", ":=", "json", ".", "Marshal", "(", "unfurls", ")", "\n", "if", "err", "==", "nil", "{", "config", ".", "values", ".", "Add", "(", "\"unfurls\"", ",", "string", "(", "unfurlsStr", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}" ]
// MsgOptionUnfurl unfurls a message based on the timestamp.
[ "MsgOptionUnfurl", "unfurls", "a", "message", "based", "on", "the", "timestamp", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L270-L280
train
nlopes/slack
chat.go
MsgOptionAsUser
func MsgOptionAsUser(b bool) MsgOption { return func(config *sendConfig) error { if b != DEFAULT_MESSAGE_ASUSER { config.values.Set("as_user", "true") } return nil } }
go
func MsgOptionAsUser(b bool) MsgOption { return func(config *sendConfig) error { if b != DEFAULT_MESSAGE_ASUSER { config.values.Set("as_user", "true") } return nil } }
[ "func", "MsgOptionAsUser", "(", "b", "bool", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "if", "b", "!=", "DEFAULT_MESSAGE_ASUSER", "{", "config", ".", "values", ".", "Set", "(", "\"as_user\"", ",", "\"true\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionAsUser whether or not to send the message as the user.
[ "MsgOptionAsUser", "whether", "or", "not", "to", "send", "the", "message", "as", "the", "user", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L283-L290
train
nlopes/slack
chat.go
MsgOptionUser
func MsgOptionUser(userID string) MsgOption { return func(config *sendConfig) error { config.values.Set("user", userID) return nil } }
go
func MsgOptionUser(userID string) MsgOption { return func(config *sendConfig) error { config.values.Set("user", userID) return nil } }
[ "func", "MsgOptionUser", "(", "userID", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "values", ".", "Set", "(", "\"user\"", ",", "userID", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionUser set the user for the message.
[ "MsgOptionUser", "set", "the", "user", "for", "the", "message", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L293-L298
train
nlopes/slack
chat.go
MsgOptionUsername
func MsgOptionUsername(username string) MsgOption { return func(config *sendConfig) error { config.values.Set("username", username) return nil } }
go
func MsgOptionUsername(username string) MsgOption { return func(config *sendConfig) error { config.values.Set("username", username) return nil } }
[ "func", "MsgOptionUsername", "(", "username", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "values", ".", "Set", "(", "\"username\"", ",", "username", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionUsername set the username for the message.
[ "MsgOptionUsername", "set", "the", "username", "for", "the", "message", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L301-L306
train
nlopes/slack
chat.go
MsgOptionText
func MsgOptionText(text string, escape bool) MsgOption { return func(config *sendConfig) error { if escape { text = slackutilsx.EscapeMessage(text) } config.values.Add("text", text) return nil } }
go
func MsgOptionText(text string, escape bool) MsgOption { return func(config *sendConfig) error { if escape { text = slackutilsx.EscapeMessage(text) } config.values.Add("text", text) return nil } }
[ "func", "MsgOptionText", "(", "text", "string", ",", "escape", "bool", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "if", "escape", "{", "text", "=", "slackutilsx", ".", "EscapeMessage", "(", "text", ")", "\n", "}", "\n", "config", ".", "values", ".", "Add", "(", "\"text\"", ",", "text", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionText provide the text for the message, optionally escape the provided // text.
[ "MsgOptionText", "provide", "the", "text", "for", "the", "message", "optionally", "escape", "the", "provided", "text", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L310-L318
train
nlopes/slack
chat.go
MsgOptionAttachments
func MsgOptionAttachments(attachments ...Attachment) MsgOption { return func(config *sendConfig) error { if attachments == nil { return nil } attachments, err := json.Marshal(attachments) if err == nil { config.values.Set("attachments", string(attachments)) } return err } }
go
func MsgOptionAttachments(attachments ...Attachment) MsgOption { return func(config *sendConfig) error { if attachments == nil { return nil } attachments, err := json.Marshal(attachments) if err == nil { config.values.Set("attachments", string(attachments)) } return err } }
[ "func", "MsgOptionAttachments", "(", "attachments", "...", "Attachment", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "if", "attachments", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "attachments", ",", "err", ":=", "json", ".", "Marshal", "(", "attachments", ")", "\n", "if", "err", "==", "nil", "{", "config", ".", "values", ".", "Set", "(", "\"attachments\"", ",", "string", "(", "attachments", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}" ]
// MsgOptionAttachments provide attachments for the message.
[ "MsgOptionAttachments", "provide", "attachments", "for", "the", "message", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L321-L333
train
nlopes/slack
chat.go
MsgOptionBlocks
func MsgOptionBlocks(blocks ...Block) MsgOption { return func(config *sendConfig) error { if blocks == nil { return nil } blocks, err := json.Marshal(blocks) if err == nil { config.values.Set("blocks", string(blocks)) } return err } }
go
func MsgOptionBlocks(blocks ...Block) MsgOption { return func(config *sendConfig) error { if blocks == nil { return nil } blocks, err := json.Marshal(blocks) if err == nil { config.values.Set("blocks", string(blocks)) } return err } }
[ "func", "MsgOptionBlocks", "(", "blocks", "...", "Block", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "if", "blocks", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "blocks", ",", "err", ":=", "json", ".", "Marshal", "(", "blocks", ")", "\n", "if", "err", "==", "nil", "{", "config", ".", "values", ".", "Set", "(", "\"blocks\"", ",", "string", "(", "blocks", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}" ]
// MsgOptionBlocks sets blocks for the message
[ "MsgOptionBlocks", "sets", "blocks", "for", "the", "message" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L336-L348
train
nlopes/slack
chat.go
MsgOptionTS
func MsgOptionTS(ts string) MsgOption { return func(config *sendConfig) error { config.values.Set("thread_ts", ts) return nil } }
go
func MsgOptionTS(ts string) MsgOption { return func(config *sendConfig) error { config.values.Set("thread_ts", ts) return nil } }
[ "func", "MsgOptionTS", "(", "ts", "string", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "config", ".", "values", ".", "Set", "(", "\"thread_ts\"", ",", "ts", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionTS sets the thread TS of the message to enable creating or replying to a thread
[ "MsgOptionTS", "sets", "the", "thread", "TS", "of", "the", "message", "to", "enable", "creating", "or", "replying", "to", "a", "thread" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L383-L388
train
nlopes/slack
chat.go
MsgOptionCompose
func MsgOptionCompose(options ...MsgOption) MsgOption { return func(c *sendConfig) error { for _, opt := range options { if err := opt(c); err != nil { return err } } return nil } }
go
func MsgOptionCompose(options ...MsgOption) MsgOption { return func(c *sendConfig) error { for _, opt := range options { if err := opt(c); err != nil { return err } } return nil } }
[ "func", "MsgOptionCompose", "(", "options", "...", "MsgOption", ")", "MsgOption", "{", "return", "func", "(", "c", "*", "sendConfig", ")", "error", "{", "for", "_", ",", "opt", ":=", "range", "options", "{", "if", "err", ":=", "opt", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionCompose combines multiple options into a single option.
[ "MsgOptionCompose", "combines", "multiple", "options", "into", "a", "single", "option", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L399-L408
train
nlopes/slack
chat.go
MsgOptionParse
func MsgOptionParse(b bool) MsgOption { return func(c *sendConfig) error { var v string if b { v = "1" } else { v = "0" } c.values.Set("parse", v) return nil } }
go
func MsgOptionParse(b bool) MsgOption { return func(c *sendConfig) error { var v string if b { v = "1" } else { v = "0" } c.values.Set("parse", v) return nil } }
[ "func", "MsgOptionParse", "(", "b", "bool", ")", "MsgOption", "{", "return", "func", "(", "c", "*", "sendConfig", ")", "error", "{", "var", "v", "string", "\n", "if", "b", "{", "v", "=", "\"1\"", "\n", "}", "else", "{", "v", "=", "\"0\"", "\n", "}", "\n", "c", ".", "values", ".", "Set", "(", "\"parse\"", ",", "v", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionParse set parse option.
[ "MsgOptionParse", "set", "parse", "option", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L411-L422
train
nlopes/slack
chat.go
MsgOptionIconURL
func MsgOptionIconURL(iconURL string) MsgOption { return func(c *sendConfig) error { c.values.Set("icon_url", iconURL) return nil } }
go
func MsgOptionIconURL(iconURL string) MsgOption { return func(c *sendConfig) error { c.values.Set("icon_url", iconURL) return nil } }
[ "func", "MsgOptionIconURL", "(", "iconURL", "string", ")", "MsgOption", "{", "return", "func", "(", "c", "*", "sendConfig", ")", "error", "{", "c", ".", "values", ".", "Set", "(", "\"icon_url\"", ",", "iconURL", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionIconURL sets an icon URL
[ "MsgOptionIconURL", "sets", "an", "icon", "URL" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L425-L430
train
nlopes/slack
chat.go
MsgOptionIconEmoji
func MsgOptionIconEmoji(iconEmoji string) MsgOption { return func(c *sendConfig) error { c.values.Set("icon_emoji", iconEmoji) return nil } }
go
func MsgOptionIconEmoji(iconEmoji string) MsgOption { return func(c *sendConfig) error { c.values.Set("icon_emoji", iconEmoji) return nil } }
[ "func", "MsgOptionIconEmoji", "(", "iconEmoji", "string", ")", "MsgOption", "{", "return", "func", "(", "c", "*", "sendConfig", ")", "error", "{", "c", ".", "values", ".", "Set", "(", "\"icon_emoji\"", ",", "iconEmoji", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionIconEmoji sets an icon emoji
[ "MsgOptionIconEmoji", "sets", "an", "icon", "emoji" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L433-L438
train
nlopes/slack
chat.go
MsgOptionPostMessageParameters
func MsgOptionPostMessageParameters(params PostMessageParameters) MsgOption { return func(config *sendConfig) error { if params.Username != DEFAULT_MESSAGE_USERNAME { config.values.Set("username", params.Username) } // chat.postEphemeral support if params.User != DEFAULT_MESSAGE_USERNAME { config.values.Set("user", params.User) } // never generates an error. MsgOptionAsUser(params.AsUser)(config) if params.Parse != DEFAULT_MESSAGE_PARSE { config.values.Set("parse", params.Parse) } if params.LinkNames != DEFAULT_MESSAGE_LINK_NAMES { config.values.Set("link_names", "1") } if params.UnfurlLinks != DEFAULT_MESSAGE_UNFURL_LINKS { config.values.Set("unfurl_links", "true") } // I want to send a message with explicit `as_user` `true` and `unfurl_links` `false` in request. // Because setting `as_user` to `true` will change the default value for `unfurl_links` to `true` on Slack API side. if params.AsUser != DEFAULT_MESSAGE_ASUSER && params.UnfurlLinks == DEFAULT_MESSAGE_UNFURL_LINKS { config.values.Set("unfurl_links", "false") } if params.UnfurlMedia != DEFAULT_MESSAGE_UNFURL_MEDIA { config.values.Set("unfurl_media", "false") } if params.IconURL != DEFAULT_MESSAGE_ICON_URL { config.values.Set("icon_url", params.IconURL) } if params.IconEmoji != DEFAULT_MESSAGE_ICON_EMOJI { config.values.Set("icon_emoji", params.IconEmoji) } if params.Markdown != DEFAULT_MESSAGE_MARKDOWN { config.values.Set("mrkdwn", "false") } if params.ThreadTimestamp != DEFAULT_MESSAGE_THREAD_TIMESTAMP { config.values.Set("thread_ts", params.ThreadTimestamp) } if params.ReplyBroadcast != DEFAULT_MESSAGE_REPLY_BROADCAST { config.values.Set("reply_broadcast", "true") } return nil } }
go
func MsgOptionPostMessageParameters(params PostMessageParameters) MsgOption { return func(config *sendConfig) error { if params.Username != DEFAULT_MESSAGE_USERNAME { config.values.Set("username", params.Username) } // chat.postEphemeral support if params.User != DEFAULT_MESSAGE_USERNAME { config.values.Set("user", params.User) } // never generates an error. MsgOptionAsUser(params.AsUser)(config) if params.Parse != DEFAULT_MESSAGE_PARSE { config.values.Set("parse", params.Parse) } if params.LinkNames != DEFAULT_MESSAGE_LINK_NAMES { config.values.Set("link_names", "1") } if params.UnfurlLinks != DEFAULT_MESSAGE_UNFURL_LINKS { config.values.Set("unfurl_links", "true") } // I want to send a message with explicit `as_user` `true` and `unfurl_links` `false` in request. // Because setting `as_user` to `true` will change the default value for `unfurl_links` to `true` on Slack API side. if params.AsUser != DEFAULT_MESSAGE_ASUSER && params.UnfurlLinks == DEFAULT_MESSAGE_UNFURL_LINKS { config.values.Set("unfurl_links", "false") } if params.UnfurlMedia != DEFAULT_MESSAGE_UNFURL_MEDIA { config.values.Set("unfurl_media", "false") } if params.IconURL != DEFAULT_MESSAGE_ICON_URL { config.values.Set("icon_url", params.IconURL) } if params.IconEmoji != DEFAULT_MESSAGE_ICON_EMOJI { config.values.Set("icon_emoji", params.IconEmoji) } if params.Markdown != DEFAULT_MESSAGE_MARKDOWN { config.values.Set("mrkdwn", "false") } if params.ThreadTimestamp != DEFAULT_MESSAGE_THREAD_TIMESTAMP { config.values.Set("thread_ts", params.ThreadTimestamp) } if params.ReplyBroadcast != DEFAULT_MESSAGE_REPLY_BROADCAST { config.values.Set("reply_broadcast", "true") } return nil } }
[ "func", "MsgOptionPostMessageParameters", "(", "params", "PostMessageParameters", ")", "MsgOption", "{", "return", "func", "(", "config", "*", "sendConfig", ")", "error", "{", "if", "params", ".", "Username", "!=", "DEFAULT_MESSAGE_USERNAME", "{", "config", ".", "values", ".", "Set", "(", "\"username\"", ",", "params", ".", "Username", ")", "\n", "}", "\n", "if", "params", ".", "User", "!=", "DEFAULT_MESSAGE_USERNAME", "{", "config", ".", "values", ".", "Set", "(", "\"user\"", ",", "params", ".", "User", ")", "\n", "}", "\n", "MsgOptionAsUser", "(", "params", ".", "AsUser", ")", "(", "config", ")", "\n", "if", "params", ".", "Parse", "!=", "DEFAULT_MESSAGE_PARSE", "{", "config", ".", "values", ".", "Set", "(", "\"parse\"", ",", "params", ".", "Parse", ")", "\n", "}", "\n", "if", "params", ".", "LinkNames", "!=", "DEFAULT_MESSAGE_LINK_NAMES", "{", "config", ".", "values", ".", "Set", "(", "\"link_names\"", ",", "\"1\"", ")", "\n", "}", "\n", "if", "params", ".", "UnfurlLinks", "!=", "DEFAULT_MESSAGE_UNFURL_LINKS", "{", "config", ".", "values", ".", "Set", "(", "\"unfurl_links\"", ",", "\"true\"", ")", "\n", "}", "\n", "if", "params", ".", "AsUser", "!=", "DEFAULT_MESSAGE_ASUSER", "&&", "params", ".", "UnfurlLinks", "==", "DEFAULT_MESSAGE_UNFURL_LINKS", "{", "config", ".", "values", ".", "Set", "(", "\"unfurl_links\"", ",", "\"false\"", ")", "\n", "}", "\n", "if", "params", ".", "UnfurlMedia", "!=", "DEFAULT_MESSAGE_UNFURL_MEDIA", "{", "config", ".", "values", ".", "Set", "(", "\"unfurl_media\"", ",", "\"false\"", ")", "\n", "}", "\n", "if", "params", ".", "IconURL", "!=", "DEFAULT_MESSAGE_ICON_URL", "{", "config", ".", "values", ".", "Set", "(", "\"icon_url\"", ",", "params", ".", "IconURL", ")", "\n", "}", "\n", "if", "params", ".", "IconEmoji", "!=", "DEFAULT_MESSAGE_ICON_EMOJI", "{", "config", ".", "values", ".", "Set", "(", "\"icon_emoji\"", ",", "params", ".", "IconEmoji", ")", "\n", "}", "\n", "if", "params", ".", "Markdown", "!=", "DEFAULT_MESSAGE_MARKDOWN", "{", "config", ".", "values", ".", "Set", "(", "\"mrkdwn\"", ",", "\"false\"", ")", "\n", "}", "\n", "if", "params", ".", "ThreadTimestamp", "!=", "DEFAULT_MESSAGE_THREAD_TIMESTAMP", "{", "config", ".", "values", ".", "Set", "(", "\"thread_ts\"", ",", "params", ".", "ThreadTimestamp", ")", "\n", "}", "\n", "if", "params", ".", "ReplyBroadcast", "!=", "DEFAULT_MESSAGE_REPLY_BROADCAST", "{", "config", ".", "values", ".", "Set", "(", "\"reply_broadcast\"", ",", "\"true\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MsgOptionPostMessageParameters maintain backwards compatibility.
[ "MsgOptionPostMessageParameters", "maintain", "backwards", "compatibility", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L453-L505
train
nlopes/slack
chat.go
GetPermalink
func (api *Client) GetPermalink(params *PermalinkParameters) (string, error) { return api.GetPermalinkContext(context.Background(), params) }
go
func (api *Client) GetPermalink(params *PermalinkParameters) (string, error) { return api.GetPermalinkContext(context.Background(), params) }
[ "func", "(", "api", "*", "Client", ")", "GetPermalink", "(", "params", "*", "PermalinkParameters", ")", "(", "string", ",", "error", ")", "{", "return", "api", ".", "GetPermalinkContext", "(", "context", ".", "Background", "(", ")", ",", "params", ")", "\n", "}" ]
// GetPermalink returns the permalink for a message. It takes // PermalinkParameters and returns a string containing the permalink. It // returns an error if unable to retrieve the permalink.
[ "GetPermalink", "returns", "the", "permalink", "for", "a", "message", ".", "It", "takes", "PermalinkParameters", "and", "returns", "a", "string", "containing", "the", "permalink", ".", "It", "returns", "an", "error", "if", "unable", "to", "retrieve", "the", "permalink", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L518-L520
train
nlopes/slack
chat.go
GetPermalinkContext
func (api *Client) GetPermalinkContext(ctx context.Context, params *PermalinkParameters) (string, error) { values := url.Values{ "token": {api.token}, "channel": {params.Channel}, "message_ts": {params.Ts}, } response := struct { Channel string `json:"channel"` Permalink string `json:"permalink"` SlackResponse }{} err := api.getMethod(ctx, "chat.getPermalink", values, &response) if err != nil { return "", err } return response.Permalink, response.Err() }
go
func (api *Client) GetPermalinkContext(ctx context.Context, params *PermalinkParameters) (string, error) { values := url.Values{ "token": {api.token}, "channel": {params.Channel}, "message_ts": {params.Ts}, } response := struct { Channel string `json:"channel"` Permalink string `json:"permalink"` SlackResponse }{} err := api.getMethod(ctx, "chat.getPermalink", values, &response) if err != nil { return "", err } return response.Permalink, response.Err() }
[ "func", "(", "api", "*", "Client", ")", "GetPermalinkContext", "(", "ctx", "context", ".", "Context", ",", "params", "*", "PermalinkParameters", ")", "(", "string", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "\"channel\"", ":", "{", "params", ".", "Channel", "}", ",", "\"message_ts\"", ":", "{", "params", ".", "Ts", "}", ",", "}", "\n", "response", ":=", "struct", "{", "Channel", "string", "`json:\"channel\"`", "\n", "Permalink", "string", "`json:\"permalink\"`", "\n", "SlackResponse", "\n", "}", "{", "}", "\n", "err", ":=", "api", ".", "getMethod", "(", "ctx", ",", "\"chat.getPermalink\"", ",", "values", ",", "&", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "response", ".", "Permalink", ",", "response", ".", "Err", "(", ")", "\n", "}" ]
// GetPermalinkContext returns the permalink for a message using a custom context.
[ "GetPermalinkContext", "returns", "the", "permalink", "for", "a", "message", "using", "a", "custom", "context", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/chat.go#L523-L540
train
nlopes/slack
websocket_managed_conn.go
ManageConnection
func (rtm *RTM) ManageConnection() { var ( err error info *Info conn *websocket.Conn ) for connectionCount := 0; ; connectionCount++ { // start trying to connect // the returned err is already passed onto the IncomingEvents channel if info, conn, err = rtm.connect(connectionCount, rtm.useRTMStart); err != nil { // when the connection is unsuccessful its fatal, and we need to bail out. rtm.Debugf("Failed to connect with RTM on try %d: %s", connectionCount, err) rtm.disconnect() return } // lock to prevent data races with Disconnect particularly around isConnected // and conn. rtm.mu.Lock() rtm.conn = conn rtm.info = info rtm.mu.Unlock() rtm.IncomingEvents <- RTMEvent{"connected", &ConnectedEvent{ ConnectionCount: connectionCount, Info: info, }} rtm.Debugf("RTM connection succeeded on try %d", connectionCount) // we're now connected so we can set up listeners go rtm.handleIncomingEvents() // this should be a blocking call until the connection has ended rtm.handleEvents() select { case <-rtm.disconnected: // after handle events returns we need to check if we're disconnected return default: // otherwise continue and run the loop again to reconnect } } }
go
func (rtm *RTM) ManageConnection() { var ( err error info *Info conn *websocket.Conn ) for connectionCount := 0; ; connectionCount++ { // start trying to connect // the returned err is already passed onto the IncomingEvents channel if info, conn, err = rtm.connect(connectionCount, rtm.useRTMStart); err != nil { // when the connection is unsuccessful its fatal, and we need to bail out. rtm.Debugf("Failed to connect with RTM on try %d: %s", connectionCount, err) rtm.disconnect() return } // lock to prevent data races with Disconnect particularly around isConnected // and conn. rtm.mu.Lock() rtm.conn = conn rtm.info = info rtm.mu.Unlock() rtm.IncomingEvents <- RTMEvent{"connected", &ConnectedEvent{ ConnectionCount: connectionCount, Info: info, }} rtm.Debugf("RTM connection succeeded on try %d", connectionCount) // we're now connected so we can set up listeners go rtm.handleIncomingEvents() // this should be a blocking call until the connection has ended rtm.handleEvents() select { case <-rtm.disconnected: // after handle events returns we need to check if we're disconnected return default: // otherwise continue and run the loop again to reconnect } } }
[ "func", "(", "rtm", "*", "RTM", ")", "ManageConnection", "(", ")", "{", "var", "(", "err", "error", "\n", "info", "*", "Info", "\n", "conn", "*", "websocket", ".", "Conn", "\n", ")", "\n", "for", "connectionCount", ":=", "0", ";", ";", "connectionCount", "++", "{", "if", "info", ",", "conn", ",", "err", "=", "rtm", ".", "connect", "(", "connectionCount", ",", "rtm", ".", "useRTMStart", ")", ";", "err", "!=", "nil", "{", "rtm", ".", "Debugf", "(", "\"Failed to connect with RTM on try %d: %s\"", ",", "connectionCount", ",", "err", ")", "\n", "rtm", ".", "disconnect", "(", ")", "\n", "return", "\n", "}", "\n", "rtm", ".", "mu", ".", "Lock", "(", ")", "\n", "rtm", ".", "conn", "=", "conn", "\n", "rtm", ".", "info", "=", "info", "\n", "rtm", ".", "mu", ".", "Unlock", "(", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"connected\"", ",", "&", "ConnectedEvent", "{", "ConnectionCount", ":", "connectionCount", ",", "Info", ":", "info", ",", "}", "}", "\n", "rtm", ".", "Debugf", "(", "\"RTM connection succeeded on try %d\"", ",", "connectionCount", ")", "\n", "go", "rtm", ".", "handleIncomingEvents", "(", ")", "\n", "rtm", ".", "handleEvents", "(", ")", "\n", "select", "{", "case", "<-", "rtm", ".", "disconnected", ":", "return", "\n", "default", ":", "}", "\n", "}", "\n", "}" ]
// ManageConnection can be called on a Slack RTM instance returned by the // NewRTM method. It will connect to the slack RTM API and handle all incoming // and outgoing events. If a connection fails then it will attempt to reconnect // and will notify any listeners through an error event on the IncomingEvents // channel. // // If the connection ends and the disconnect was unintentional then this will // attempt to reconnect. // // This should only be called once per slack API! Otherwise expect undefined // behavior. // // The defined error events are located in websocket_internals.go.
[ "ManageConnection", "can", "be", "called", "on", "a", "Slack", "RTM", "instance", "returned", "by", "the", "NewRTM", "method", ".", "It", "will", "connect", "to", "the", "slack", "RTM", "API", "and", "handle", "all", "incoming", "and", "outgoing", "events", ".", "If", "a", "connection", "fails", "then", "it", "will", "attempt", "to", "reconnect", "and", "will", "notify", "any", "listeners", "through", "an", "error", "event", "on", "the", "IncomingEvents", "channel", ".", "If", "the", "connection", "ends", "and", "the", "disconnect", "was", "unintentional", "then", "this", "will", "attempt", "to", "reconnect", ".", "This", "should", "only", "be", "called", "once", "per", "slack", "API!", "Otherwise", "expect", "undefined", "behavior", ".", "The", "defined", "error", "events", "are", "located", "in", "websocket_internals", ".", "go", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L29-L74
train
nlopes/slack
websocket_managed_conn.go
connect
func (rtm *RTM) connect(connectionCount int, useRTMStart bool) (*Info, *websocket.Conn, error) { const ( errInvalidAuth = "invalid_auth" errInactiveAccount = "account_inactive" errMissingAuthToken = "not_authed" ) // used to provide exponential backoff wait time with jitter before trying // to connect to slack again boff := &backoff{ Max: 5 * time.Minute, } for { var ( backoff time.Duration ) // send connecting event rtm.IncomingEvents <- RTMEvent{"connecting", &ConnectingEvent{ Attempt: boff.attempts + 1, ConnectionCount: connectionCount, }} // attempt to start the connection info, conn, err := rtm.startRTMAndDial(useRTMStart) if err == nil { return info, conn, nil } // check for fatal errors switch err.Error() { case errInvalidAuth, errInactiveAccount, errMissingAuthToken: rtm.Debugf("invalid auth when connecting with RTM: %s", err) rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}} return nil, nil, err default: } switch actual := err.(type) { case statusCodeError: if actual.Code == http.StatusNotFound { rtm.Debugf("invalid auth when connecting with RTM: %s", err) rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}} return nil, nil, err } case *RateLimitedError: backoff = actual.RetryAfter default: } backoff = timex.Max(backoff, boff.Duration()) // any other errors are treated as recoverable and we try again after // sending the event along the IncomingEvents channel rtm.IncomingEvents <- RTMEvent{"connection_error", &ConnectionErrorEvent{ Attempt: boff.attempts, Backoff: backoff, ErrorObj: err, }} // check if Disconnect() has been invoked. select { case intentional := <-rtm.killChannel: if intentional { rtm.killConnection(intentional) return nil, nil, ErrRTMDisconnected } case <-rtm.disconnected: return nil, nil, ErrRTMDisconnected default: } // get time we should wait before attempting to connect again rtm.Debugf("reconnection %d failed: %s reconnecting in %v\n", boff.attempts, err, backoff) time.Sleep(backoff) } }
go
func (rtm *RTM) connect(connectionCount int, useRTMStart bool) (*Info, *websocket.Conn, error) { const ( errInvalidAuth = "invalid_auth" errInactiveAccount = "account_inactive" errMissingAuthToken = "not_authed" ) // used to provide exponential backoff wait time with jitter before trying // to connect to slack again boff := &backoff{ Max: 5 * time.Minute, } for { var ( backoff time.Duration ) // send connecting event rtm.IncomingEvents <- RTMEvent{"connecting", &ConnectingEvent{ Attempt: boff.attempts + 1, ConnectionCount: connectionCount, }} // attempt to start the connection info, conn, err := rtm.startRTMAndDial(useRTMStart) if err == nil { return info, conn, nil } // check for fatal errors switch err.Error() { case errInvalidAuth, errInactiveAccount, errMissingAuthToken: rtm.Debugf("invalid auth when connecting with RTM: %s", err) rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}} return nil, nil, err default: } switch actual := err.(type) { case statusCodeError: if actual.Code == http.StatusNotFound { rtm.Debugf("invalid auth when connecting with RTM: %s", err) rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}} return nil, nil, err } case *RateLimitedError: backoff = actual.RetryAfter default: } backoff = timex.Max(backoff, boff.Duration()) // any other errors are treated as recoverable and we try again after // sending the event along the IncomingEvents channel rtm.IncomingEvents <- RTMEvent{"connection_error", &ConnectionErrorEvent{ Attempt: boff.attempts, Backoff: backoff, ErrorObj: err, }} // check if Disconnect() has been invoked. select { case intentional := <-rtm.killChannel: if intentional { rtm.killConnection(intentional) return nil, nil, ErrRTMDisconnected } case <-rtm.disconnected: return nil, nil, ErrRTMDisconnected default: } // get time we should wait before attempting to connect again rtm.Debugf("reconnection %d failed: %s reconnecting in %v\n", boff.attempts, err, backoff) time.Sleep(backoff) } }
[ "func", "(", "rtm", "*", "RTM", ")", "connect", "(", "connectionCount", "int", ",", "useRTMStart", "bool", ")", "(", "*", "Info", ",", "*", "websocket", ".", "Conn", ",", "error", ")", "{", "const", "(", "errInvalidAuth", "=", "\"invalid_auth\"", "\n", "errInactiveAccount", "=", "\"account_inactive\"", "\n", "errMissingAuthToken", "=", "\"not_authed\"", "\n", ")", "\n", "boff", ":=", "&", "backoff", "{", "Max", ":", "5", "*", "time", ".", "Minute", ",", "}", "\n", "for", "{", "var", "(", "backoff", "time", ".", "Duration", "\n", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"connecting\"", ",", "&", "ConnectingEvent", "{", "Attempt", ":", "boff", ".", "attempts", "+", "1", ",", "ConnectionCount", ":", "connectionCount", ",", "}", "}", "\n", "info", ",", "conn", ",", "err", ":=", "rtm", ".", "startRTMAndDial", "(", "useRTMStart", ")", "\n", "if", "err", "==", "nil", "{", "return", "info", ",", "conn", ",", "nil", "\n", "}", "\n", "switch", "err", ".", "Error", "(", ")", "{", "case", "errInvalidAuth", ",", "errInactiveAccount", ",", "errMissingAuthToken", ":", "rtm", ".", "Debugf", "(", "\"invalid auth when connecting with RTM: %s\"", ",", "err", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"invalid_auth\"", ",", "&", "InvalidAuthEvent", "{", "}", "}", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "default", ":", "}", "\n", "switch", "actual", ":=", "err", ".", "(", "type", ")", "{", "case", "statusCodeError", ":", "if", "actual", ".", "Code", "==", "http", ".", "StatusNotFound", "{", "rtm", ".", "Debugf", "(", "\"invalid auth when connecting with RTM: %s\"", ",", "err", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"invalid_auth\"", ",", "&", "InvalidAuthEvent", "{", "}", "}", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "case", "*", "RateLimitedError", ":", "backoff", "=", "actual", ".", "RetryAfter", "\n", "default", ":", "}", "\n", "backoff", "=", "timex", ".", "Max", "(", "backoff", ",", "boff", ".", "Duration", "(", ")", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"connection_error\"", ",", "&", "ConnectionErrorEvent", "{", "Attempt", ":", "boff", ".", "attempts", ",", "Backoff", ":", "backoff", ",", "ErrorObj", ":", "err", ",", "}", "}", "\n", "select", "{", "case", "intentional", ":=", "<-", "rtm", ".", "killChannel", ":", "if", "intentional", "{", "rtm", ".", "killConnection", "(", "intentional", ")", "\n", "return", "nil", ",", "nil", ",", "ErrRTMDisconnected", "\n", "}", "\n", "case", "<-", "rtm", ".", "disconnected", ":", "return", "nil", ",", "nil", ",", "ErrRTMDisconnected", "\n", "default", ":", "}", "\n", "rtm", ".", "Debugf", "(", "\"reconnection %d failed: %s reconnecting in %v\\n\"", ",", "\\n", ",", "boff", ".", "attempts", ",", "err", ")", "\n", "backoff", "\n", "}", "\n", "}" ]
// connect attempts to connect to the slack websocket API. It handles any // errors that occur while connecting and will return once a connection // has been successfully opened. // If useRTMStart is false then it uses rtm.connect to create the connection, // otherwise it uses rtm.start.
[ "connect", "attempts", "to", "connect", "to", "the", "slack", "websocket", "API", ".", "It", "handles", "any", "errors", "that", "occur", "while", "connecting", "and", "will", "return", "once", "a", "connection", "has", "been", "successfully", "opened", ".", "If", "useRTMStart", "is", "false", "then", "it", "uses", "rtm", ".", "connect", "to", "create", "the", "connection", "otherwise", "it", "uses", "rtm", ".", "start", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L81-L157
train
nlopes/slack
websocket_managed_conn.go
startRTMAndDial
func (rtm *RTM) startRTMAndDial(useRTMStart bool) (info *Info, _ *websocket.Conn, err error) { var ( url string ) if useRTMStart { rtm.Debugf("Starting RTM") info, url, err = rtm.StartRTM() } else { rtm.Debugf("Connecting to RTM") info, url, err = rtm.ConnectRTM() } if err != nil { rtm.Debugf("Failed to start or connect to RTM: %s", err) return nil, nil, err } // install connection parameters u, err := stdurl.Parse(url) if err != nil { return nil, nil, err } u.RawQuery = rtm.connParams.Encode() url = u.String() rtm.Debugf("Dialing to websocket on url %s", url) // Only use HTTPS for connections to prevent MITM attacks on the connection. upgradeHeader := http.Header{} upgradeHeader.Add("Origin", "https://api.slack.com") dialer := websocket.DefaultDialer if rtm.dialer != nil { dialer = rtm.dialer } conn, _, err := dialer.Dial(url, upgradeHeader) if err != nil { rtm.Debugf("Failed to dial to the websocket: %s", err) return nil, nil, err } return info, conn, err }
go
func (rtm *RTM) startRTMAndDial(useRTMStart bool) (info *Info, _ *websocket.Conn, err error) { var ( url string ) if useRTMStart { rtm.Debugf("Starting RTM") info, url, err = rtm.StartRTM() } else { rtm.Debugf("Connecting to RTM") info, url, err = rtm.ConnectRTM() } if err != nil { rtm.Debugf("Failed to start or connect to RTM: %s", err) return nil, nil, err } // install connection parameters u, err := stdurl.Parse(url) if err != nil { return nil, nil, err } u.RawQuery = rtm.connParams.Encode() url = u.String() rtm.Debugf("Dialing to websocket on url %s", url) // Only use HTTPS for connections to prevent MITM attacks on the connection. upgradeHeader := http.Header{} upgradeHeader.Add("Origin", "https://api.slack.com") dialer := websocket.DefaultDialer if rtm.dialer != nil { dialer = rtm.dialer } conn, _, err := dialer.Dial(url, upgradeHeader) if err != nil { rtm.Debugf("Failed to dial to the websocket: %s", err) return nil, nil, err } return info, conn, err }
[ "func", "(", "rtm", "*", "RTM", ")", "startRTMAndDial", "(", "useRTMStart", "bool", ")", "(", "info", "*", "Info", ",", "_", "*", "websocket", ".", "Conn", ",", "err", "error", ")", "{", "var", "(", "url", "string", "\n", ")", "\n", "if", "useRTMStart", "{", "rtm", ".", "Debugf", "(", "\"Starting RTM\"", ")", "\n", "info", ",", "url", ",", "err", "=", "rtm", ".", "StartRTM", "(", ")", "\n", "}", "else", "{", "rtm", ".", "Debugf", "(", "\"Connecting to RTM\"", ")", "\n", "info", ",", "url", ",", "err", "=", "rtm", ".", "ConnectRTM", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "rtm", ".", "Debugf", "(", "\"Failed to start or connect to RTM: %s\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "u", ",", "err", ":=", "stdurl", ".", "Parse", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "u", ".", "RawQuery", "=", "rtm", ".", "connParams", ".", "Encode", "(", ")", "\n", "url", "=", "u", ".", "String", "(", ")", "\n", "rtm", ".", "Debugf", "(", "\"Dialing to websocket on url %s\"", ",", "url", ")", "\n", "upgradeHeader", ":=", "http", ".", "Header", "{", "}", "\n", "upgradeHeader", ".", "Add", "(", "\"Origin\"", ",", "\"https://api.slack.com\"", ")", "\n", "dialer", ":=", "websocket", ".", "DefaultDialer", "\n", "if", "rtm", ".", "dialer", "!=", "nil", "{", "dialer", "=", "rtm", ".", "dialer", "\n", "}", "\n", "conn", ",", "_", ",", "err", ":=", "dialer", ".", "Dial", "(", "url", ",", "upgradeHeader", ")", "\n", "if", "err", "!=", "nil", "{", "rtm", ".", "Debugf", "(", "\"Failed to dial to the websocket: %s\"", ",", "err", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "info", ",", "conn", ",", "err", "\n", "}" ]
// startRTMAndDial attempts to connect to the slack websocket. If useRTMStart is true, // then it returns the full information returned by the "rtm.start" method on the // slack API. Else it uses the "rtm.connect" method to connect
[ "startRTMAndDial", "attempts", "to", "connect", "to", "the", "slack", "websocket", ".", "If", "useRTMStart", "is", "true", "then", "it", "returns", "the", "full", "information", "returned", "by", "the", "rtm", ".", "start", "method", "on", "the", "slack", "API", ".", "Else", "it", "uses", "the", "rtm", ".", "connect", "method", "to", "connect" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L162-L201
train
nlopes/slack
websocket_managed_conn.go
sendOutgoingMessage
func (rtm *RTM) sendOutgoingMessage(msg OutgoingMessage) { rtm.Debugln("Sending message:", msg) if len([]rune(msg.Text)) > MaxMessageTextLength { rtm.IncomingEvents <- RTMEvent{"outgoing_error", &MessageTooLongEvent{ Message: msg, MaxLength: MaxMessageTextLength, }} return } if err := rtm.sendWithDeadline(msg); err != nil { rtm.IncomingEvents <- RTMEvent{"outgoing_error", &OutgoingErrorEvent{ Message: msg, ErrorObj: err, }} // TODO force ping? } }
go
func (rtm *RTM) sendOutgoingMessage(msg OutgoingMessage) { rtm.Debugln("Sending message:", msg) if len([]rune(msg.Text)) > MaxMessageTextLength { rtm.IncomingEvents <- RTMEvent{"outgoing_error", &MessageTooLongEvent{ Message: msg, MaxLength: MaxMessageTextLength, }} return } if err := rtm.sendWithDeadline(msg); err != nil { rtm.IncomingEvents <- RTMEvent{"outgoing_error", &OutgoingErrorEvent{ Message: msg, ErrorObj: err, }} // TODO force ping? } }
[ "func", "(", "rtm", "*", "RTM", ")", "sendOutgoingMessage", "(", "msg", "OutgoingMessage", ")", "{", "rtm", ".", "Debugln", "(", "\"Sending message:\"", ",", "msg", ")", "\n", "if", "len", "(", "[", "]", "rune", "(", "msg", ".", "Text", ")", ")", ">", "MaxMessageTextLength", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"outgoing_error\"", ",", "&", "MessageTooLongEvent", "{", "Message", ":", "msg", ",", "MaxLength", ":", "MaxMessageTextLength", ",", "}", "}", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "rtm", ".", "sendWithDeadline", "(", "msg", ")", ";", "err", "!=", "nil", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"outgoing_error\"", ",", "&", "OutgoingErrorEvent", "{", "Message", ":", "msg", ",", "ErrorObj", ":", "err", ",", "}", "}", "\n", "}", "\n", "}" ]
// sendOutgoingMessage sends the given OutgoingMessage to the slack websocket. // // It does not currently detect if a outgoing message fails due to a disconnect // and instead lets a future failed 'PING' detect the failed connection.
[ "sendOutgoingMessage", "sends", "the", "given", "OutgoingMessage", "to", "the", "slack", "websocket", ".", "It", "does", "not", "currently", "detect", "if", "a", "outgoing", "message", "fails", "due", "to", "a", "disconnect", "and", "instead", "lets", "a", "future", "failed", "PING", "detect", "the", "failed", "connection", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L298-L315
train
nlopes/slack
websocket_managed_conn.go
ping
func (rtm *RTM) ping() error { id := rtm.idGen.Next() rtm.Debugln("Sending PING ", id) msg := &Ping{ID: id, Type: "ping", Timestamp: time.Now().Unix()} if err := rtm.sendWithDeadline(msg); err != nil { rtm.Debugf("RTM Error sending 'PING %d': %s", id, err.Error()) return err } return nil }
go
func (rtm *RTM) ping() error { id := rtm.idGen.Next() rtm.Debugln("Sending PING ", id) msg := &Ping{ID: id, Type: "ping", Timestamp: time.Now().Unix()} if err := rtm.sendWithDeadline(msg); err != nil { rtm.Debugf("RTM Error sending 'PING %d': %s", id, err.Error()) return err } return nil }
[ "func", "(", "rtm", "*", "RTM", ")", "ping", "(", ")", "error", "{", "id", ":=", "rtm", ".", "idGen", ".", "Next", "(", ")", "\n", "rtm", ".", "Debugln", "(", "\"Sending PING \"", ",", "id", ")", "\n", "msg", ":=", "&", "Ping", "{", "ID", ":", "id", ",", "Type", ":", "\"ping\"", ",", "Timestamp", ":", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "}", "\n", "if", "err", ":=", "rtm", ".", "sendWithDeadline", "(", "msg", ")", ";", "err", "!=", "nil", "{", "rtm", ".", "Debugf", "(", "\"RTM Error sending 'PING %d': %s\"", ",", "id", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ping sends a 'PING' message to the RTM's websocket. If the 'PING' message // fails to send then this returns an error signifying that the connection // should be considered disconnected. // // This does not handle incoming 'PONG' responses but does store the time of // each successful 'PING' send so latency can be detected upon a 'PONG' // response.
[ "ping", "sends", "a", "PING", "message", "to", "the", "RTM", "s", "websocket", ".", "If", "the", "PING", "message", "fails", "to", "send", "then", "this", "returns", "an", "error", "signifying", "that", "the", "connection", "should", "be", "considered", "disconnected", ".", "This", "does", "not", "handle", "incoming", "PONG", "responses", "but", "does", "store", "the", "time", "of", "each", "successful", "PING", "send", "so", "latency", "can", "be", "detected", "upon", "a", "PONG", "response", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L324-L334
train
nlopes/slack
websocket_managed_conn.go
receiveIncomingEvent
func (rtm *RTM) receiveIncomingEvent() error { event := json.RawMessage{} err := rtm.conn.ReadJSON(&event) switch { case err == io.ErrUnexpectedEOF: // EOF's don't seem to signify a failed connection so instead we ignore // them here and detect a failed connection upon attempting to send a // 'PING' message // trigger a 'PING' to detect potential websocket disconnect select { case rtm.forcePing <- true: case <-rtm.disconnected: } case err != nil: // All other errors from ReadJSON come from NextReader, and should // kill the read loop and force a reconnect. rtm.IncomingEvents <- RTMEvent{"incoming_error", &IncomingEventError{ ErrorObj: err, }} select { case rtm.killChannel <- false: case <-rtm.disconnected: } return err case len(event) == 0: rtm.Debugln("Received empty event") default: rtm.Debugln("Incoming Event:", string(event)) select { case rtm.rawEvents <- event: case <-rtm.disconnected: rtm.Debugln("disonnected while attempting to send raw event") } } return nil }
go
func (rtm *RTM) receiveIncomingEvent() error { event := json.RawMessage{} err := rtm.conn.ReadJSON(&event) switch { case err == io.ErrUnexpectedEOF: // EOF's don't seem to signify a failed connection so instead we ignore // them here and detect a failed connection upon attempting to send a // 'PING' message // trigger a 'PING' to detect potential websocket disconnect select { case rtm.forcePing <- true: case <-rtm.disconnected: } case err != nil: // All other errors from ReadJSON come from NextReader, and should // kill the read loop and force a reconnect. rtm.IncomingEvents <- RTMEvent{"incoming_error", &IncomingEventError{ ErrorObj: err, }} select { case rtm.killChannel <- false: case <-rtm.disconnected: } return err case len(event) == 0: rtm.Debugln("Received empty event") default: rtm.Debugln("Incoming Event:", string(event)) select { case rtm.rawEvents <- event: case <-rtm.disconnected: rtm.Debugln("disonnected while attempting to send raw event") } } return nil }
[ "func", "(", "rtm", "*", "RTM", ")", "receiveIncomingEvent", "(", ")", "error", "{", "event", ":=", "json", ".", "RawMessage", "{", "}", "\n", "err", ":=", "rtm", ".", "conn", ".", "ReadJSON", "(", "&", "event", ")", "\n", "switch", "{", "case", "err", "==", "io", ".", "ErrUnexpectedEOF", ":", "select", "{", "case", "rtm", ".", "forcePing", "<-", "true", ":", "case", "<-", "rtm", ".", "disconnected", ":", "}", "\n", "case", "err", "!=", "nil", ":", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"incoming_error\"", ",", "&", "IncomingEventError", "{", "ErrorObj", ":", "err", ",", "}", "}", "\n", "select", "{", "case", "rtm", ".", "killChannel", "<-", "false", ":", "case", "<-", "rtm", ".", "disconnected", ":", "}", "\n", "return", "err", "\n", "case", "len", "(", "event", ")", "==", "0", ":", "rtm", ".", "Debugln", "(", "\"Received empty event\"", ")", "\n", "default", ":", "rtm", ".", "Debugln", "(", "\"Incoming Event:\"", ",", "string", "(", "event", ")", ")", "\n", "select", "{", "case", "rtm", ".", "rawEvents", "<-", "event", ":", "case", "<-", "rtm", ".", "disconnected", ":", "rtm", ".", "Debugln", "(", "\"disonnected while attempting to send raw event\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// receiveIncomingEvent attempts to receive an event from the RTM's websocket. // This will block until a frame is available from the websocket. // If the read from the websocket results in a fatal error, this function will return non-nil.
[ "receiveIncomingEvent", "attempts", "to", "receive", "an", "event", "from", "the", "RTM", "s", "websocket", ".", "This", "will", "block", "until", "a", "frame", "is", "available", "from", "the", "websocket", ".", "If", "the", "read", "from", "the", "websocket", "results", "in", "a", "fatal", "error", "this", "function", "will", "return", "non", "-", "nil", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L339-L377
train
nlopes/slack
websocket_managed_conn.go
handleRawEvent
func (rtm *RTM) handleRawEvent(rawEvent json.RawMessage) string { event := &Event{} err := json.Unmarshal(rawEvent, event) if err != nil { rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return "" } switch event.Type { case rtmEventTypeAck: rtm.handleAck(rawEvent) case rtmEventTypeHello: rtm.IncomingEvents <- RTMEvent{"hello", &HelloEvent{}} case rtmEventTypePong: rtm.handlePong(rawEvent) case rtmEventTypeGoodbye: // just return the event type up for goodbye, will be handled by caller. case rtmEventTypeDesktopNotification: rtm.Debugln("Received desktop notification, ignoring") default: rtm.handleEvent(event.Type, rawEvent) } return event.Type }
go
func (rtm *RTM) handleRawEvent(rawEvent json.RawMessage) string { event := &Event{} err := json.Unmarshal(rawEvent, event) if err != nil { rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return "" } switch event.Type { case rtmEventTypeAck: rtm.handleAck(rawEvent) case rtmEventTypeHello: rtm.IncomingEvents <- RTMEvent{"hello", &HelloEvent{}} case rtmEventTypePong: rtm.handlePong(rawEvent) case rtmEventTypeGoodbye: // just return the event type up for goodbye, will be handled by caller. case rtmEventTypeDesktopNotification: rtm.Debugln("Received desktop notification, ignoring") default: rtm.handleEvent(event.Type, rawEvent) } return event.Type }
[ "func", "(", "rtm", "*", "RTM", ")", "handleRawEvent", "(", "rawEvent", "json", ".", "RawMessage", ")", "string", "{", "event", ":=", "&", "Event", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "rawEvent", ",", "event", ")", "\n", "if", "err", "!=", "nil", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"unmarshalling_error\"", ",", "&", "UnmarshallingErrorEvent", "{", "err", "}", "}", "\n", "return", "\"\"", "\n", "}", "\n", "switch", "event", ".", "Type", "{", "case", "rtmEventTypeAck", ":", "rtm", ".", "handleAck", "(", "rawEvent", ")", "\n", "case", "rtmEventTypeHello", ":", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"hello\"", ",", "&", "HelloEvent", "{", "}", "}", "\n", "case", "rtmEventTypePong", ":", "rtm", ".", "handlePong", "(", "rawEvent", ")", "\n", "case", "rtmEventTypeGoodbye", ":", "case", "rtmEventTypeDesktopNotification", ":", "rtm", ".", "Debugln", "(", "\"Received desktop notification, ignoring\"", ")", "\n", "default", ":", "rtm", ".", "handleEvent", "(", "event", ".", "Type", ",", "rawEvent", ")", "\n", "}", "\n", "return", "event", ".", "Type", "\n", "}" ]
// handleRawEvent takes a raw JSON message received from the slack websocket // and handles the encoded event. // returns the event type of the message.
[ "handleRawEvent", "takes", "a", "raw", "JSON", "message", "received", "from", "the", "slack", "websocket", "and", "handles", "the", "encoded", "event", ".", "returns", "the", "event", "type", "of", "the", "message", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L382-L406
train
nlopes/slack
websocket_managed_conn.go
handleAck
func (rtm *RTM) handleAck(event json.RawMessage) { ack := &AckMessage{} if err := json.Unmarshal(event, ack); err != nil { rtm.Debugln("RTM Error unmarshalling 'ack' event:", err) rtm.Debugln(" -> Erroneous 'ack' event:", string(event)) return } if ack.Ok { rtm.IncomingEvents <- RTMEvent{"ack", ack} } else if ack.RTMResponse.Error != nil { // As there is no documentation for RTM error-codes, this // identification of a rate-limit warning is very brittle. if ack.RTMResponse.Error.Code == -1 && ack.RTMResponse.Error.Msg == "slow down, too many messages..." { rtm.IncomingEvents <- RTMEvent{"ack_error", &RateLimitEvent{}} } else { rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{ack.Error}} } } else { rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{fmt.Errorf("ack decode failure")}} } }
go
func (rtm *RTM) handleAck(event json.RawMessage) { ack := &AckMessage{} if err := json.Unmarshal(event, ack); err != nil { rtm.Debugln("RTM Error unmarshalling 'ack' event:", err) rtm.Debugln(" -> Erroneous 'ack' event:", string(event)) return } if ack.Ok { rtm.IncomingEvents <- RTMEvent{"ack", ack} } else if ack.RTMResponse.Error != nil { // As there is no documentation for RTM error-codes, this // identification of a rate-limit warning is very brittle. if ack.RTMResponse.Error.Code == -1 && ack.RTMResponse.Error.Msg == "slow down, too many messages..." { rtm.IncomingEvents <- RTMEvent{"ack_error", &RateLimitEvent{}} } else { rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{ack.Error}} } } else { rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{fmt.Errorf("ack decode failure")}} } }
[ "func", "(", "rtm", "*", "RTM", ")", "handleAck", "(", "event", "json", ".", "RawMessage", ")", "{", "ack", ":=", "&", "AckMessage", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "event", ",", "ack", ")", ";", "err", "!=", "nil", "{", "rtm", ".", "Debugln", "(", "\"RTM Error unmarshalling 'ack' event:\"", ",", "err", ")", "\n", "rtm", ".", "Debugln", "(", "\" -> Erroneous 'ack' event:\"", ",", "string", "(", "event", ")", ")", "\n", "return", "\n", "}", "\n", "if", "ack", ".", "Ok", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"ack\"", ",", "ack", "}", "\n", "}", "else", "if", "ack", ".", "RTMResponse", ".", "Error", "!=", "nil", "{", "if", "ack", ".", "RTMResponse", ".", "Error", ".", "Code", "==", "-", "1", "&&", "ack", ".", "RTMResponse", ".", "Error", ".", "Msg", "==", "\"slow down, too many messages...\"", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"ack_error\"", ",", "&", "RateLimitEvent", "{", "}", "}", "\n", "}", "else", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"ack_error\"", ",", "&", "AckErrorEvent", "{", "ack", ".", "Error", "}", "}", "\n", "}", "\n", "}", "else", "{", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"ack_error\"", ",", "&", "AckErrorEvent", "{", "fmt", ".", "Errorf", "(", "\"ack decode failure\"", ")", "}", "}", "\n", "}", "\n", "}" ]
// handleAck handles an incoming 'ACK' message.
[ "handleAck", "handles", "an", "incoming", "ACK", "message", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L409-L430
train
nlopes/slack
websocket_managed_conn.go
handlePong
func (rtm *RTM) handlePong(event json.RawMessage) { var ( p Pong ) rtm.resetDeadman() if err := json.Unmarshal(event, &p); err != nil { rtm.Client.log.Println("RTM Error unmarshalling 'pong' event:", err) return } latency := time.Since(time.Unix(p.Timestamp, 0)) rtm.IncomingEvents <- RTMEvent{"latency_report", &LatencyReport{Value: latency}} }
go
func (rtm *RTM) handlePong(event json.RawMessage) { var ( p Pong ) rtm.resetDeadman() if err := json.Unmarshal(event, &p); err != nil { rtm.Client.log.Println("RTM Error unmarshalling 'pong' event:", err) return } latency := time.Since(time.Unix(p.Timestamp, 0)) rtm.IncomingEvents <- RTMEvent{"latency_report", &LatencyReport{Value: latency}} }
[ "func", "(", "rtm", "*", "RTM", ")", "handlePong", "(", "event", "json", ".", "RawMessage", ")", "{", "var", "(", "p", "Pong", "\n", ")", "\n", "rtm", ".", "resetDeadman", "(", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "event", ",", "&", "p", ")", ";", "err", "!=", "nil", "{", "rtm", ".", "Client", ".", "log", ".", "Println", "(", "\"RTM Error unmarshalling 'pong' event:\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "latency", ":=", "time", ".", "Since", "(", "time", ".", "Unix", "(", "p", ".", "Timestamp", ",", "0", ")", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"latency_report\"", ",", "&", "LatencyReport", "{", "Value", ":", "latency", "}", "}", "\n", "}" ]
// handlePong handles an incoming 'PONG' message which should be in response to // a previously sent 'PING' message. This is then used to compute the // connection's latency.
[ "handlePong", "handles", "an", "incoming", "PONG", "message", "which", "should", "be", "in", "response", "to", "a", "previously", "sent", "PING", "message", ".", "This", "is", "then", "used", "to", "compute", "the", "connection", "s", "latency", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L435-L449
train
nlopes/slack
websocket_managed_conn.go
handleEvent
func (rtm *RTM) handleEvent(typeStr string, event json.RawMessage) { v, exists := EventMapping[typeStr] if !exists { rtm.Debugf("RTM Error - received unmapped event %q: %s\n", typeStr, string(event)) err := fmt.Errorf("RTM Error: Received unmapped event %q: %s", typeStr, string(event)) rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return } t := reflect.TypeOf(v) recvEvent := reflect.New(t).Interface() err := json.Unmarshal(event, recvEvent) if err != nil { rtm.Debugf("RTM Error, could not unmarshall event %q: %s\n", typeStr, string(event)) err := fmt.Errorf("RTM Error: Could not unmarshall event %q: %s", typeStr, string(event)) rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return } rtm.IncomingEvents <- RTMEvent{typeStr, recvEvent} }
go
func (rtm *RTM) handleEvent(typeStr string, event json.RawMessage) { v, exists := EventMapping[typeStr] if !exists { rtm.Debugf("RTM Error - received unmapped event %q: %s\n", typeStr, string(event)) err := fmt.Errorf("RTM Error: Received unmapped event %q: %s", typeStr, string(event)) rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return } t := reflect.TypeOf(v) recvEvent := reflect.New(t).Interface() err := json.Unmarshal(event, recvEvent) if err != nil { rtm.Debugf("RTM Error, could not unmarshall event %q: %s\n", typeStr, string(event)) err := fmt.Errorf("RTM Error: Could not unmarshall event %q: %s", typeStr, string(event)) rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}} return } rtm.IncomingEvents <- RTMEvent{typeStr, recvEvent} }
[ "func", "(", "rtm", "*", "RTM", ")", "handleEvent", "(", "typeStr", "string", ",", "event", "json", ".", "RawMessage", ")", "{", "v", ",", "exists", ":=", "EventMapping", "[", "typeStr", "]", "\n", "if", "!", "exists", "{", "rtm", ".", "Debugf", "(", "\"RTM Error - received unmapped event %q: %s\\n\"", ",", "\\n", ",", "typeStr", ")", "\n", "string", "(", "event", ")", "\n", "err", ":=", "fmt", ".", "Errorf", "(", "\"RTM Error: Received unmapped event %q: %s\"", ",", "typeStr", ",", "string", "(", "event", ")", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"unmarshalling_error\"", ",", "&", "UnmarshallingErrorEvent", "{", "err", "}", "}", "\n", "}", "\n", "return", "\n", "t", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n", "recvEvent", ":=", "reflect", ".", "New", "(", "t", ")", ".", "Interface", "(", ")", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "event", ",", "recvEvent", ")", "\n", "if", "err", "!=", "nil", "{", "rtm", ".", "Debugf", "(", "\"RTM Error, could not unmarshall event %q: %s\\n\"", ",", "\\n", ",", "typeStr", ")", "\n", "string", "(", "event", ")", "\n", "err", ":=", "fmt", ".", "Errorf", "(", "\"RTM Error: Could not unmarshall event %q: %s\"", ",", "typeStr", ",", "string", "(", "event", ")", ")", "\n", "rtm", ".", "IncomingEvents", "<-", "RTMEvent", "{", "\"unmarshalling_error\"", ",", "&", "UnmarshallingErrorEvent", "{", "err", "}", "}", "\n", "}", "\n", "}" ]
// handleEvent is the "default" response to an event that does not have a // special case. It matches the command's name to a mapping of defined events // and then sends the corresponding event struct to the IncomingEvents channel. // If the event type is not found or the event cannot be unmarshalled into the // correct struct then this sends an UnmarshallingErrorEvent to the // IncomingEvents channel.
[ "handleEvent", "is", "the", "default", "response", "to", "an", "event", "that", "does", "not", "have", "a", "special", "case", ".", "It", "matches", "the", "command", "s", "name", "to", "a", "mapping", "of", "defined", "events", "and", "then", "sends", "the", "corresponding", "event", "struct", "to", "the", "IncomingEvents", "channel", ".", "If", "the", "event", "type", "is", "not", "found", "or", "the", "event", "cannot", "be", "unmarshalled", "into", "the", "correct", "struct", "then", "this", "sends", "an", "UnmarshallingErrorEvent", "to", "the", "IncomingEvents", "channel", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/websocket_managed_conn.go#L457-L475
train
nlopes/slack
pins.go
AddPin
func (api *Client) AddPin(channel string, item ItemRef) error { return api.AddPinContext(context.Background(), channel, item) }
go
func (api *Client) AddPin(channel string, item ItemRef) error { return api.AddPinContext(context.Background(), channel, item) }
[ "func", "(", "api", "*", "Client", ")", "AddPin", "(", "channel", "string", ",", "item", "ItemRef", ")", "error", "{", "return", "api", ".", "AddPinContext", "(", "context", ".", "Background", "(", ")", ",", "channel", ",", "item", ")", "\n", "}" ]
// AddPin pins an item in a channel
[ "AddPin", "pins", "an", "item", "in", "a", "channel" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/pins.go#L16-L18
train
nlopes/slack
pins.go
AddPinContext
func (api *Client) AddPinContext(ctx context.Context, channel string, item ItemRef) error { values := url.Values{ "channel": {channel}, "token": {api.token}, } if item.Timestamp != "" { values.Set("timestamp", item.Timestamp) } if item.File != "" { values.Set("file", item.File) } if item.Comment != "" { values.Set("file_comment", item.Comment) } response := &SlackResponse{} if err := api.postMethod(ctx, "pins.add", values, response); err != nil { return err } return response.Err() }
go
func (api *Client) AddPinContext(ctx context.Context, channel string, item ItemRef) error { values := url.Values{ "channel": {channel}, "token": {api.token}, } if item.Timestamp != "" { values.Set("timestamp", item.Timestamp) } if item.File != "" { values.Set("file", item.File) } if item.Comment != "" { values.Set("file_comment", item.Comment) } response := &SlackResponse{} if err := api.postMethod(ctx, "pins.add", values, response); err != nil { return err } return response.Err() }
[ "func", "(", "api", "*", "Client", ")", "AddPinContext", "(", "ctx", "context", ".", "Context", ",", "channel", "string", ",", "item", "ItemRef", ")", "error", "{", "values", ":=", "url", ".", "Values", "{", "\"channel\"", ":", "{", "channel", "}", ",", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "}", "\n", "if", "item", ".", "Timestamp", "!=", "\"\"", "{", "values", ".", "Set", "(", "\"timestamp\"", ",", "item", ".", "Timestamp", ")", "\n", "}", "\n", "if", "item", ".", "File", "!=", "\"\"", "{", "values", ".", "Set", "(", "\"file\"", ",", "item", ".", "File", ")", "\n", "}", "\n", "if", "item", ".", "Comment", "!=", "\"\"", "{", "values", ".", "Set", "(", "\"file_comment\"", ",", "item", ".", "Comment", ")", "\n", "}", "\n", "response", ":=", "&", "SlackResponse", "{", "}", "\n", "if", "err", ":=", "api", ".", "postMethod", "(", "ctx", ",", "\"pins.add\"", ",", "values", ",", "response", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "response", ".", "Err", "(", ")", "\n", "}" ]
// AddPinContext pins an item in a channel with a custom context
[ "AddPinContext", "pins", "an", "item", "in", "a", "channel", "with", "a", "custom", "context" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/pins.go#L21-L42
train
nlopes/slack
pins.go
RemovePin
func (api *Client) RemovePin(channel string, item ItemRef) error { return api.RemovePinContext(context.Background(), channel, item) }
go
func (api *Client) RemovePin(channel string, item ItemRef) error { return api.RemovePinContext(context.Background(), channel, item) }
[ "func", "(", "api", "*", "Client", ")", "RemovePin", "(", "channel", "string", ",", "item", "ItemRef", ")", "error", "{", "return", "api", ".", "RemovePinContext", "(", "context", ".", "Background", "(", ")", ",", "channel", ",", "item", ")", "\n", "}" ]
// RemovePin un-pins an item from a channel
[ "RemovePin", "un", "-", "pins", "an", "item", "from", "a", "channel" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/pins.go#L45-L47
train
nlopes/slack
pins.go
ListPins
func (api *Client) ListPins(channel string) ([]Item, *Paging, error) { return api.ListPinsContext(context.Background(), channel) }
go
func (api *Client) ListPins(channel string) ([]Item, *Paging, error) { return api.ListPinsContext(context.Background(), channel) }
[ "func", "(", "api", "*", "Client", ")", "ListPins", "(", "channel", "string", ")", "(", "[", "]", "Item", ",", "*", "Paging", ",", "error", ")", "{", "return", "api", ".", "ListPinsContext", "(", "context", ".", "Background", "(", ")", ",", "channel", ")", "\n", "}" ]
// ListPins returns information about the items a user reacted to.
[ "ListPins", "returns", "information", "about", "the", "items", "a", "user", "reacted", "to", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/pins.go#L74-L76
train
nlopes/slack
pins.go
ListPinsContext
func (api *Client) ListPinsContext(ctx context.Context, channel string) ([]Item, *Paging, error) { values := url.Values{ "channel": {channel}, "token": {api.token}, } response := &listPinsResponseFull{} err := api.postMethod(ctx, "pins.list", values, response) if err != nil { return nil, nil, err } if !response.Ok { return nil, nil, errors.New(response.Error) } return response.Items, &response.Paging, nil }
go
func (api *Client) ListPinsContext(ctx context.Context, channel string) ([]Item, *Paging, error) { values := url.Values{ "channel": {channel}, "token": {api.token}, } response := &listPinsResponseFull{} err := api.postMethod(ctx, "pins.list", values, response) if err != nil { return nil, nil, err } if !response.Ok { return nil, nil, errors.New(response.Error) } return response.Items, &response.Paging, nil }
[ "func", "(", "api", "*", "Client", ")", "ListPinsContext", "(", "ctx", "context", ".", "Context", ",", "channel", "string", ")", "(", "[", "]", "Item", ",", "*", "Paging", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"channel\"", ":", "{", "channel", "}", ",", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "}", "\n", "response", ":=", "&", "listPinsResponseFull", "{", "}", "\n", "err", ":=", "api", ".", "postMethod", "(", "ctx", ",", "\"pins.list\"", ",", "values", ",", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "!", "response", ".", "Ok", "{", "return", "nil", ",", "nil", ",", "errors", ".", "New", "(", "response", ".", "Error", ")", "\n", "}", "\n", "return", "response", ".", "Items", ",", "&", "response", ".", "Paging", ",", "nil", "\n", "}" ]
// ListPinsContext returns information about the items a user reacted to with a custom context.
[ "ListPinsContext", "returns", "information", "about", "the", "items", "a", "user", "reacted", "to", "with", "a", "custom", "context", "." ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/pins.go#L79-L94
train
nlopes/slack
usergroups.go
CreateUserGroup
func (api *Client) CreateUserGroup(userGroup UserGroup) (UserGroup, error) { return api.CreateUserGroupContext(context.Background(), userGroup) }
go
func (api *Client) CreateUserGroup(userGroup UserGroup) (UserGroup, error) { return api.CreateUserGroupContext(context.Background(), userGroup) }
[ "func", "(", "api", "*", "Client", ")", "CreateUserGroup", "(", "userGroup", "UserGroup", ")", "(", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "CreateUserGroupContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ")", "\n", "}" ]
// CreateUserGroup creates a new user group
[ "CreateUserGroup", "creates", "a", "new", "user", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L54-L56
train
nlopes/slack
usergroups.go
CreateUserGroupContext
func (api *Client) CreateUserGroupContext(ctx context.Context, userGroup UserGroup) (UserGroup, error) { values := url.Values{ "token": {api.token}, "name": {userGroup.Name}, } if userGroup.Handle != "" { values["handle"] = []string{userGroup.Handle} } if userGroup.Description != "" { values["description"] = []string{userGroup.Description} } if len(userGroup.Prefs.Channels) > 0 { values["channels"] = []string{strings.Join(userGroup.Prefs.Channels, ",")} } response, err := api.userGroupRequest(ctx, "usergroups.create", values) if err != nil { return UserGroup{}, err } return response.UserGroup, nil }
go
func (api *Client) CreateUserGroupContext(ctx context.Context, userGroup UserGroup) (UserGroup, error) { values := url.Values{ "token": {api.token}, "name": {userGroup.Name}, } if userGroup.Handle != "" { values["handle"] = []string{userGroup.Handle} } if userGroup.Description != "" { values["description"] = []string{userGroup.Description} } if len(userGroup.Prefs.Channels) > 0 { values["channels"] = []string{strings.Join(userGroup.Prefs.Channels, ",")} } response, err := api.userGroupRequest(ctx, "usergroups.create", values) if err != nil { return UserGroup{}, err } return response.UserGroup, nil }
[ "func", "(", "api", "*", "Client", ")", "CreateUserGroupContext", "(", "ctx", "context", ".", "Context", ",", "userGroup", "UserGroup", ")", "(", "UserGroup", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "\"name\"", ":", "{", "userGroup", ".", "Name", "}", ",", "}", "\n", "if", "userGroup", ".", "Handle", "!=", "\"\"", "{", "values", "[", "\"handle\"", "]", "=", "[", "]", "string", "{", "userGroup", ".", "Handle", "}", "\n", "}", "\n", "if", "userGroup", ".", "Description", "!=", "\"\"", "{", "values", "[", "\"description\"", "]", "=", "[", "]", "string", "{", "userGroup", ".", "Description", "}", "\n", "}", "\n", "if", "len", "(", "userGroup", ".", "Prefs", ".", "Channels", ")", ">", "0", "{", "values", "[", "\"channels\"", "]", "=", "[", "]", "string", "{", "strings", ".", "Join", "(", "userGroup", ".", "Prefs", ".", "Channels", ",", "\",\"", ")", "}", "\n", "}", "\n", "response", ",", "err", ":=", "api", ".", "userGroupRequest", "(", "ctx", ",", "\"usergroups.create\"", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "UserGroup", "{", "}", ",", "err", "\n", "}", "\n", "return", "response", ".", "UserGroup", ",", "nil", "\n", "}" ]
// CreateUserGroupContext creates a new user group with a custom context
[ "CreateUserGroupContext", "creates", "a", "new", "user", "group", "with", "a", "custom", "context" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L59-L82
train
nlopes/slack
usergroups.go
DisableUserGroup
func (api *Client) DisableUserGroup(userGroup string) (UserGroup, error) { return api.DisableUserGroupContext(context.Background(), userGroup) }
go
func (api *Client) DisableUserGroup(userGroup string) (UserGroup, error) { return api.DisableUserGroupContext(context.Background(), userGroup) }
[ "func", "(", "api", "*", "Client", ")", "DisableUserGroup", "(", "userGroup", "string", ")", "(", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "DisableUserGroupContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ")", "\n", "}" ]
// DisableUserGroup disables an existing user group
[ "DisableUserGroup", "disables", "an", "existing", "user", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L85-L87
train
nlopes/slack
usergroups.go
EnableUserGroup
func (api *Client) EnableUserGroup(userGroup string) (UserGroup, error) { return api.EnableUserGroupContext(context.Background(), userGroup) }
go
func (api *Client) EnableUserGroup(userGroup string) (UserGroup, error) { return api.EnableUserGroupContext(context.Background(), userGroup) }
[ "func", "(", "api", "*", "Client", ")", "EnableUserGroup", "(", "userGroup", "string", ")", "(", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "EnableUserGroupContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ")", "\n", "}" ]
// EnableUserGroup enables an existing user group
[ "EnableUserGroup", "enables", "an", "existing", "user", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L104-L106
train
nlopes/slack
usergroups.go
EnableUserGroupContext
func (api *Client) EnableUserGroupContext(ctx context.Context, userGroup string) (UserGroup, error) { values := url.Values{ "token": {api.token}, "usergroup": {userGroup}, } response, err := api.userGroupRequest(ctx, "usergroups.enable", values) if err != nil { return UserGroup{}, err } return response.UserGroup, nil }
go
func (api *Client) EnableUserGroupContext(ctx context.Context, userGroup string) (UserGroup, error) { values := url.Values{ "token": {api.token}, "usergroup": {userGroup}, } response, err := api.userGroupRequest(ctx, "usergroups.enable", values) if err != nil { return UserGroup{}, err } return response.UserGroup, nil }
[ "func", "(", "api", "*", "Client", ")", "EnableUserGroupContext", "(", "ctx", "context", ".", "Context", ",", "userGroup", "string", ")", "(", "UserGroup", ",", "error", ")", "{", "values", ":=", "url", ".", "Values", "{", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "\"usergroup\"", ":", "{", "userGroup", "}", ",", "}", "\n", "response", ",", "err", ":=", "api", ".", "userGroupRequest", "(", "ctx", ",", "\"usergroups.enable\"", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "UserGroup", "{", "}", ",", "err", "\n", "}", "\n", "return", "response", ".", "UserGroup", ",", "nil", "\n", "}" ]
// EnableUserGroupContext enables an existing user group with a custom context
[ "EnableUserGroupContext", "enables", "an", "existing", "user", "group", "with", "a", "custom", "context" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L109-L120
train
nlopes/slack
usergroups.go
GetUserGroups
func (api *Client) GetUserGroups(options ...GetUserGroupsOption) ([]UserGroup, error) { return api.GetUserGroupsContext(context.Background(), options...) }
go
func (api *Client) GetUserGroups(options ...GetUserGroupsOption) ([]UserGroup, error) { return api.GetUserGroupsContext(context.Background(), options...) }
[ "func", "(", "api", "*", "Client", ")", "GetUserGroups", "(", "options", "...", "GetUserGroupsOption", ")", "(", "[", "]", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "GetUserGroupsContext", "(", "context", ".", "Background", "(", ")", ",", "options", "...", ")", "\n", "}" ]
// GetUserGroups returns a list of user groups for the team
[ "GetUserGroups", "returns", "a", "list", "of", "user", "groups", "for", "the", "team" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L154-L156
train
nlopes/slack
usergroups.go
GetUserGroupsContext
func (api *Client) GetUserGroupsContext(ctx context.Context, options ...GetUserGroupsOption) ([]UserGroup, error) { params := GetUserGroupsParams{} for _, opt := range options { opt(&params) } values := url.Values{ "token": {api.token}, } if params.IncludeCount { values.Add("include_count", "true") } if params.IncludeDisabled { values.Add("include_disabled", "true") } if params.IncludeUsers { values.Add("include_users", "true") } response, err := api.userGroupRequest(ctx, "usergroups.list", values) if err != nil { return nil, err } return response.UserGroups, nil }
go
func (api *Client) GetUserGroupsContext(ctx context.Context, options ...GetUserGroupsOption) ([]UserGroup, error) { params := GetUserGroupsParams{} for _, opt := range options { opt(&params) } values := url.Values{ "token": {api.token}, } if params.IncludeCount { values.Add("include_count", "true") } if params.IncludeDisabled { values.Add("include_disabled", "true") } if params.IncludeUsers { values.Add("include_users", "true") } response, err := api.userGroupRequest(ctx, "usergroups.list", values) if err != nil { return nil, err } return response.UserGroups, nil }
[ "func", "(", "api", "*", "Client", ")", "GetUserGroupsContext", "(", "ctx", "context", ".", "Context", ",", "options", "...", "GetUserGroupsOption", ")", "(", "[", "]", "UserGroup", ",", "error", ")", "{", "params", ":=", "GetUserGroupsParams", "{", "}", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "&", "params", ")", "\n", "}", "\n", "values", ":=", "url", ".", "Values", "{", "\"token\"", ":", "{", "api", ".", "token", "}", ",", "}", "\n", "if", "params", ".", "IncludeCount", "{", "values", ".", "Add", "(", "\"include_count\"", ",", "\"true\"", ")", "\n", "}", "\n", "if", "params", ".", "IncludeDisabled", "{", "values", ".", "Add", "(", "\"include_disabled\"", ",", "\"true\"", ")", "\n", "}", "\n", "if", "params", ".", "IncludeUsers", "{", "values", ".", "Add", "(", "\"include_users\"", ",", "\"true\"", ")", "\n", "}", "\n", "response", ",", "err", ":=", "api", ".", "userGroupRequest", "(", "ctx", ",", "\"usergroups.list\"", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "response", ".", "UserGroups", ",", "nil", "\n", "}" ]
// GetUserGroupsContext returns a list of user groups for the team with a custom context
[ "GetUserGroupsContext", "returns", "a", "list", "of", "user", "groups", "for", "the", "team", "with", "a", "custom", "context" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L159-L184
train
nlopes/slack
usergroups.go
UpdateUserGroup
func (api *Client) UpdateUserGroup(userGroup UserGroup) (UserGroup, error) { return api.UpdateUserGroupContext(context.Background(), userGroup) }
go
func (api *Client) UpdateUserGroup(userGroup UserGroup) (UserGroup, error) { return api.UpdateUserGroupContext(context.Background(), userGroup) }
[ "func", "(", "api", "*", "Client", ")", "UpdateUserGroup", "(", "userGroup", "UserGroup", ")", "(", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "UpdateUserGroupContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ")", "\n", "}" ]
// UpdateUserGroup will update an existing user group
[ "UpdateUserGroup", "will", "update", "an", "existing", "user", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L187-L189
train
nlopes/slack
usergroups.go
GetUserGroupMembers
func (api *Client) GetUserGroupMembers(userGroup string) ([]string, error) { return api.GetUserGroupMembersContext(context.Background(), userGroup) }
go
func (api *Client) GetUserGroupMembers(userGroup string) ([]string, error) { return api.GetUserGroupMembersContext(context.Background(), userGroup) }
[ "func", "(", "api", "*", "Client", ")", "GetUserGroupMembers", "(", "userGroup", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "api", ".", "GetUserGroupMembersContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ")", "\n", "}" ]
// GetUserGroupMembers will retrieve the current list of users in a group
[ "GetUserGroupMembers", "will", "retrieve", "the", "current", "list", "of", "users", "in", "a", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L222-L224
train
nlopes/slack
usergroups.go
UpdateUserGroupMembers
func (api *Client) UpdateUserGroupMembers(userGroup string, members string) (UserGroup, error) { return api.UpdateUserGroupMembersContext(context.Background(), userGroup, members) }
go
func (api *Client) UpdateUserGroupMembers(userGroup string, members string) (UserGroup, error) { return api.UpdateUserGroupMembersContext(context.Background(), userGroup, members) }
[ "func", "(", "api", "*", "Client", ")", "UpdateUserGroupMembers", "(", "userGroup", "string", ",", "members", "string", ")", "(", "UserGroup", ",", "error", ")", "{", "return", "api", ".", "UpdateUserGroupMembersContext", "(", "context", ".", "Background", "(", ")", ",", "userGroup", ",", "members", ")", "\n", "}" ]
// UpdateUserGroupMembers will update the members of an existing user group
[ "UpdateUserGroupMembers", "will", "update", "the", "members", "of", "an", "existing", "user", "group" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/usergroups.go#L241-L243
train
nlopes/slack
slash.go
SlashCommandParse
func SlashCommandParse(r *http.Request) (s SlashCommand, err error) { if err = r.ParseForm(); err != nil { return s, err } s.Token = r.PostForm.Get("token") s.TeamID = r.PostForm.Get("team_id") s.TeamDomain = r.PostForm.Get("team_domain") s.EnterpriseID = r.PostForm.Get("enterprise_id") s.EnterpriseName = r.PostForm.Get("enterprise_name") s.ChannelID = r.PostForm.Get("channel_id") s.ChannelName = r.PostForm.Get("channel_name") s.UserID = r.PostForm.Get("user_id") s.UserName = r.PostForm.Get("user_name") s.Command = r.PostForm.Get("command") s.Text = r.PostForm.Get("text") s.ResponseURL = r.PostForm.Get("response_url") s.TriggerID = r.PostForm.Get("trigger_id") return s, nil }
go
func SlashCommandParse(r *http.Request) (s SlashCommand, err error) { if err = r.ParseForm(); err != nil { return s, err } s.Token = r.PostForm.Get("token") s.TeamID = r.PostForm.Get("team_id") s.TeamDomain = r.PostForm.Get("team_domain") s.EnterpriseID = r.PostForm.Get("enterprise_id") s.EnterpriseName = r.PostForm.Get("enterprise_name") s.ChannelID = r.PostForm.Get("channel_id") s.ChannelName = r.PostForm.Get("channel_name") s.UserID = r.PostForm.Get("user_id") s.UserName = r.PostForm.Get("user_name") s.Command = r.PostForm.Get("command") s.Text = r.PostForm.Get("text") s.ResponseURL = r.PostForm.Get("response_url") s.TriggerID = r.PostForm.Get("trigger_id") return s, nil }
[ "func", "SlashCommandParse", "(", "r", "*", "http", ".", "Request", ")", "(", "s", "SlashCommand", ",", "err", "error", ")", "{", "if", "err", "=", "r", ".", "ParseForm", "(", ")", ";", "err", "!=", "nil", "{", "return", "s", ",", "err", "\n", "}", "\n", "s", ".", "Token", "=", "r", ".", "PostForm", ".", "Get", "(", "\"token\"", ")", "\n", "s", ".", "TeamID", "=", "r", ".", "PostForm", ".", "Get", "(", "\"team_id\"", ")", "\n", "s", ".", "TeamDomain", "=", "r", ".", "PostForm", ".", "Get", "(", "\"team_domain\"", ")", "\n", "s", ".", "EnterpriseID", "=", "r", ".", "PostForm", ".", "Get", "(", "\"enterprise_id\"", ")", "\n", "s", ".", "EnterpriseName", "=", "r", ".", "PostForm", ".", "Get", "(", "\"enterprise_name\"", ")", "\n", "s", ".", "ChannelID", "=", "r", ".", "PostForm", ".", "Get", "(", "\"channel_id\"", ")", "\n", "s", ".", "ChannelName", "=", "r", ".", "PostForm", ".", "Get", "(", "\"channel_name\"", ")", "\n", "s", ".", "UserID", "=", "r", ".", "PostForm", ".", "Get", "(", "\"user_id\"", ")", "\n", "s", ".", "UserName", "=", "r", ".", "PostForm", ".", "Get", "(", "\"user_name\"", ")", "\n", "s", ".", "Command", "=", "r", ".", "PostForm", ".", "Get", "(", "\"command\"", ")", "\n", "s", ".", "Text", "=", "r", ".", "PostForm", ".", "Get", "(", "\"text\"", ")", "\n", "s", ".", "ResponseURL", "=", "r", ".", "PostForm", ".", "Get", "(", "\"response_url\"", ")", "\n", "s", ".", "TriggerID", "=", "r", ".", "PostForm", ".", "Get", "(", "\"trigger_id\"", ")", "\n", "return", "s", ",", "nil", "\n", "}" ]
// SlashCommandParse will parse the request of the slash command
[ "SlashCommandParse", "will", "parse", "the", "request", "of", "the", "slash", "command" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/slash.go#L25-L43
train
nlopes/slack
slash.go
ValidateToken
func (s SlashCommand) ValidateToken(verificationTokens ...string) bool { for _, token := range verificationTokens { if s.Token == token { return true } } return false }
go
func (s SlashCommand) ValidateToken(verificationTokens ...string) bool { for _, token := range verificationTokens { if s.Token == token { return true } } return false }
[ "func", "(", "s", "SlashCommand", ")", "ValidateToken", "(", "verificationTokens", "...", "string", ")", "bool", "{", "for", "_", ",", "token", ":=", "range", "verificationTokens", "{", "if", "s", ".", "Token", "==", "token", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ValidateToken validates verificationTokens
[ "ValidateToken", "validates", "verificationTokens" ]
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/slash.go#L46-L53
train
hashicorp/serf
coordinate/coordinate.go
NewCoordinate
func NewCoordinate(config *Config) *Coordinate { return &Coordinate{ Vec: make([]float64, config.Dimensionality), Error: config.VivaldiErrorMax, Adjustment: 0.0, Height: config.HeightMin, } }
go
func NewCoordinate(config *Config) *Coordinate { return &Coordinate{ Vec: make([]float64, config.Dimensionality), Error: config.VivaldiErrorMax, Adjustment: 0.0, Height: config.HeightMin, } }
[ "func", "NewCoordinate", "(", "config", "*", "Config", ")", "*", "Coordinate", "{", "return", "&", "Coordinate", "{", "Vec", ":", "make", "(", "[", "]", "float64", ",", "config", ".", "Dimensionality", ")", ",", "Error", ":", "config", ".", "VivaldiErrorMax", ",", "Adjustment", ":", "0.0", ",", "Height", ":", "config", ".", "HeightMin", ",", "}", "\n", "}" ]
// NewCoordinate creates a new coordinate at the origin, using the given config // to supply key initial values.
[ "NewCoordinate", "creates", "a", "new", "coordinate", "at", "the", "origin", "using", "the", "given", "config", "to", "supply", "key", "initial", "values", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L54-L61
train
hashicorp/serf
coordinate/coordinate.go
Clone
func (c *Coordinate) Clone() *Coordinate { vec := make([]float64, len(c.Vec)) copy(vec, c.Vec) return &Coordinate{ Vec: vec, Error: c.Error, Adjustment: c.Adjustment, Height: c.Height, } }
go
func (c *Coordinate) Clone() *Coordinate { vec := make([]float64, len(c.Vec)) copy(vec, c.Vec) return &Coordinate{ Vec: vec, Error: c.Error, Adjustment: c.Adjustment, Height: c.Height, } }
[ "func", "(", "c", "*", "Coordinate", ")", "Clone", "(", ")", "*", "Coordinate", "{", "vec", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "c", ".", "Vec", ")", ")", "\n", "copy", "(", "vec", ",", "c", ".", "Vec", ")", "\n", "return", "&", "Coordinate", "{", "Vec", ":", "vec", ",", "Error", ":", "c", ".", "Error", ",", "Adjustment", ":", "c", ".", "Adjustment", ",", "Height", ":", "c", ".", "Height", ",", "}", "\n", "}" ]
// Clone creates an independent copy of this coordinate.
[ "Clone", "creates", "an", "independent", "copy", "of", "this", "coordinate", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L64-L73
train
hashicorp/serf
coordinate/coordinate.go
componentIsValid
func componentIsValid(f float64) bool { return !math.IsInf(f, 0) && !math.IsNaN(f) }
go
func componentIsValid(f float64) bool { return !math.IsInf(f, 0) && !math.IsNaN(f) }
[ "func", "componentIsValid", "(", "f", "float64", ")", "bool", "{", "return", "!", "math", ".", "IsInf", "(", "f", ",", "0", ")", "&&", "!", "math", ".", "IsNaN", "(", "f", ")", "\n", "}" ]
// componentIsValid returns false if a floating point value is a NaN or an // infinity.
[ "componentIsValid", "returns", "false", "if", "a", "floating", "point", "value", "is", "a", "NaN", "or", "an", "infinity", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L77-L79
train
hashicorp/serf
coordinate/coordinate.go
IsCompatibleWith
func (c *Coordinate) IsCompatibleWith(other *Coordinate) bool { return len(c.Vec) == len(other.Vec) }
go
func (c *Coordinate) IsCompatibleWith(other *Coordinate) bool { return len(c.Vec) == len(other.Vec) }
[ "func", "(", "c", "*", "Coordinate", ")", "IsCompatibleWith", "(", "other", "*", "Coordinate", ")", "bool", "{", "return", "len", "(", "c", ".", "Vec", ")", "==", "len", "(", "other", ".", "Vec", ")", "\n", "}" ]
// IsCompatibleWith checks to see if the two coordinates are compatible // dimensionally. If this returns true then you are guaranteed to not get // any runtime errors operating on them.
[ "IsCompatibleWith", "checks", "to", "see", "if", "the", "two", "coordinates", "are", "compatible", "dimensionally", ".", "If", "this", "returns", "true", "then", "you", "are", "guaranteed", "to", "not", "get", "any", "runtime", "errors", "operating", "on", "them", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L98-L100
train
hashicorp/serf
coordinate/coordinate.go
ApplyForce
func (c *Coordinate) ApplyForce(config *Config, force float64, other *Coordinate) *Coordinate { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } ret := c.Clone() unit, mag := unitVectorAt(c.Vec, other.Vec) ret.Vec = add(ret.Vec, mul(unit, force)) if mag > zeroThreshold { ret.Height = (ret.Height+other.Height)*force/mag + ret.Height ret.Height = math.Max(ret.Height, config.HeightMin) } return ret }
go
func (c *Coordinate) ApplyForce(config *Config, force float64, other *Coordinate) *Coordinate { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } ret := c.Clone() unit, mag := unitVectorAt(c.Vec, other.Vec) ret.Vec = add(ret.Vec, mul(unit, force)) if mag > zeroThreshold { ret.Height = (ret.Height+other.Height)*force/mag + ret.Height ret.Height = math.Max(ret.Height, config.HeightMin) } return ret }
[ "func", "(", "c", "*", "Coordinate", ")", "ApplyForce", "(", "config", "*", "Config", ",", "force", "float64", ",", "other", "*", "Coordinate", ")", "*", "Coordinate", "{", "if", "!", "c", ".", "IsCompatibleWith", "(", "other", ")", "{", "panic", "(", "DimensionalityConflictError", "{", "}", ")", "\n", "}", "\n", "ret", ":=", "c", ".", "Clone", "(", ")", "\n", "unit", ",", "mag", ":=", "unitVectorAt", "(", "c", ".", "Vec", ",", "other", ".", "Vec", ")", "\n", "ret", ".", "Vec", "=", "add", "(", "ret", ".", "Vec", ",", "mul", "(", "unit", ",", "force", ")", ")", "\n", "if", "mag", ">", "zeroThreshold", "{", "ret", ".", "Height", "=", "(", "ret", ".", "Height", "+", "other", ".", "Height", ")", "*", "force", "/", "mag", "+", "ret", ".", "Height", "\n", "ret", ".", "Height", "=", "math", ".", "Max", "(", "ret", ".", "Height", ",", "config", ".", "HeightMin", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ApplyForce returns the result of applying the force from the direction of the // other coordinate.
[ "ApplyForce", "returns", "the", "result", "of", "applying", "the", "force", "from", "the", "direction", "of", "the", "other", "coordinate", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L104-L117
train
hashicorp/serf
coordinate/coordinate.go
DistanceTo
func (c *Coordinate) DistanceTo(other *Coordinate) time.Duration { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } dist := c.rawDistanceTo(other) adjustedDist := dist + c.Adjustment + other.Adjustment if adjustedDist > 0.0 { dist = adjustedDist } return time.Duration(dist * secondsToNanoseconds) }
go
func (c *Coordinate) DistanceTo(other *Coordinate) time.Duration { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } dist := c.rawDistanceTo(other) adjustedDist := dist + c.Adjustment + other.Adjustment if adjustedDist > 0.0 { dist = adjustedDist } return time.Duration(dist * secondsToNanoseconds) }
[ "func", "(", "c", "*", "Coordinate", ")", "DistanceTo", "(", "other", "*", "Coordinate", ")", "time", ".", "Duration", "{", "if", "!", "c", ".", "IsCompatibleWith", "(", "other", ")", "{", "panic", "(", "DimensionalityConflictError", "{", "}", ")", "\n", "}", "\n", "dist", ":=", "c", ".", "rawDistanceTo", "(", "other", ")", "\n", "adjustedDist", ":=", "dist", "+", "c", ".", "Adjustment", "+", "other", ".", "Adjustment", "\n", "if", "adjustedDist", ">", "0.0", "{", "dist", "=", "adjustedDist", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "dist", "*", "secondsToNanoseconds", ")", "\n", "}" ]
// DistanceTo returns the distance between this coordinate and the other // coordinate, including adjustments.
[ "DistanceTo", "returns", "the", "distance", "between", "this", "coordinate", "and", "the", "other", "coordinate", "including", "adjustments", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L121-L132
train
hashicorp/serf
coordinate/coordinate.go
rawDistanceTo
func (c *Coordinate) rawDistanceTo(other *Coordinate) float64 { return magnitude(diff(c.Vec, other.Vec)) + c.Height + other.Height }
go
func (c *Coordinate) rawDistanceTo(other *Coordinate) float64 { return magnitude(diff(c.Vec, other.Vec)) + c.Height + other.Height }
[ "func", "(", "c", "*", "Coordinate", ")", "rawDistanceTo", "(", "other", "*", "Coordinate", ")", "float64", "{", "return", "magnitude", "(", "diff", "(", "c", ".", "Vec", ",", "other", ".", "Vec", ")", ")", "+", "c", ".", "Height", "+", "other", ".", "Height", "\n", "}" ]
// rawDistanceTo returns the Vivaldi distance between this coordinate and the // other coordinate in seconds, not including adjustments. This assumes the // dimensions have already been checked to be compatible.
[ "rawDistanceTo", "returns", "the", "Vivaldi", "distance", "between", "this", "coordinate", "and", "the", "other", "coordinate", "in", "seconds", "not", "including", "adjustments", ".", "This", "assumes", "the", "dimensions", "have", "already", "been", "checked", "to", "be", "compatible", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L137-L139
train
hashicorp/serf
coordinate/coordinate.go
add
func add(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] + vec2[i] } return ret }
go
func add(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] + vec2[i] } return ret }
[ "func", "add", "(", "vec1", "[", "]", "float64", ",", "vec2", "[", "]", "float64", ")", "[", "]", "float64", "{", "ret", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "vec1", ")", ")", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", "=", "vec1", "[", "i", "]", "+", "vec2", "[", "i", "]", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// add returns the sum of vec1 and vec2. This assumes the dimensions have // already been checked to be compatible.
[ "add", "returns", "the", "sum", "of", "vec1", "and", "vec2", ".", "This", "assumes", "the", "dimensions", "have", "already", "been", "checked", "to", "be", "compatible", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L143-L149
train
hashicorp/serf
coordinate/coordinate.go
diff
func diff(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] - vec2[i] } return ret }
go
func diff(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] - vec2[i] } return ret }
[ "func", "diff", "(", "vec1", "[", "]", "float64", ",", "vec2", "[", "]", "float64", ")", "[", "]", "float64", "{", "ret", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "vec1", ")", ")", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", "=", "vec1", "[", "i", "]", "-", "vec2", "[", "i", "]", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// diff returns the difference between the vec1 and vec2. This assumes the // dimensions have already been checked to be compatible.
[ "diff", "returns", "the", "difference", "between", "the", "vec1", "and", "vec2", ".", "This", "assumes", "the", "dimensions", "have", "already", "been", "checked", "to", "be", "compatible", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L153-L159
train
hashicorp/serf
coordinate/coordinate.go
mul
func mul(vec []float64, factor float64) []float64 { ret := make([]float64, len(vec)) for i := range vec { ret[i] = vec[i] * factor } return ret }
go
func mul(vec []float64, factor float64) []float64 { ret := make([]float64, len(vec)) for i := range vec { ret[i] = vec[i] * factor } return ret }
[ "func", "mul", "(", "vec", "[", "]", "float64", ",", "factor", "float64", ")", "[", "]", "float64", "{", "ret", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "vec", ")", ")", "\n", "for", "i", ":=", "range", "vec", "{", "ret", "[", "i", "]", "=", "vec", "[", "i", "]", "*", "factor", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// mul returns vec multiplied by a scalar factor.
[ "mul", "returns", "vec", "multiplied", "by", "a", "scalar", "factor", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L162-L168
train
hashicorp/serf
coordinate/coordinate.go
magnitude
func magnitude(vec []float64) float64 { sum := 0.0 for i := range vec { sum += vec[i] * vec[i] } return math.Sqrt(sum) }
go
func magnitude(vec []float64) float64 { sum := 0.0 for i := range vec { sum += vec[i] * vec[i] } return math.Sqrt(sum) }
[ "func", "magnitude", "(", "vec", "[", "]", "float64", ")", "float64", "{", "sum", ":=", "0.0", "\n", "for", "i", ":=", "range", "vec", "{", "sum", "+=", "vec", "[", "i", "]", "*", "vec", "[", "i", "]", "\n", "}", "\n", "return", "math", ".", "Sqrt", "(", "sum", ")", "\n", "}" ]
// magnitude computes the magnitude of the vec.
[ "magnitude", "computes", "the", "magnitude", "of", "the", "vec", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L171-L177
train
hashicorp/serf
coordinate/coordinate.go
unitVectorAt
func unitVectorAt(vec1 []float64, vec2 []float64) ([]float64, float64) { ret := diff(vec1, vec2) // If the coordinates aren't on top of each other we can normalize. if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), mag } // Otherwise, just return a random unit vector. for i := range ret { ret[i] = rand.Float64() - 0.5 } if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), 0.0 } // And finally just give up and make a unit vector along the first // dimension. This should be exceedingly rare. ret = make([]float64, len(ret)) ret[0] = 1.0 return ret, 0.0 }
go
func unitVectorAt(vec1 []float64, vec2 []float64) ([]float64, float64) { ret := diff(vec1, vec2) // If the coordinates aren't on top of each other we can normalize. if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), mag } // Otherwise, just return a random unit vector. for i := range ret { ret[i] = rand.Float64() - 0.5 } if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), 0.0 } // And finally just give up and make a unit vector along the first // dimension. This should be exceedingly rare. ret = make([]float64, len(ret)) ret[0] = 1.0 return ret, 0.0 }
[ "func", "unitVectorAt", "(", "vec1", "[", "]", "float64", ",", "vec2", "[", "]", "float64", ")", "(", "[", "]", "float64", ",", "float64", ")", "{", "ret", ":=", "diff", "(", "vec1", ",", "vec2", ")", "\n", "if", "mag", ":=", "magnitude", "(", "ret", ")", ";", "mag", ">", "zeroThreshold", "{", "return", "mul", "(", "ret", ",", "1.0", "/", "mag", ")", ",", "mag", "\n", "}", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", "=", "rand", ".", "Float64", "(", ")", "-", "0.5", "\n", "}", "\n", "if", "mag", ":=", "magnitude", "(", "ret", ")", ";", "mag", ">", "zeroThreshold", "{", "return", "mul", "(", "ret", ",", "1.0", "/", "mag", ")", ",", "0.0", "\n", "}", "\n", "ret", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "ret", ")", ")", "\n", "ret", "[", "0", "]", "=", "1.0", "\n", "return", "ret", ",", "0.0", "\n", "}" ]
// unitVectorAt returns a unit vector pointing at vec1 from vec2. If the two // positions are the same then a random unit vector is returned. We also return // the distance between the points for use in the later height calculation.
[ "unitVectorAt", "returns", "a", "unit", "vector", "pointing", "at", "vec1", "from", "vec2", ".", "If", "the", "two", "positions", "are", "the", "same", "then", "a", "random", "unit", "vector", "is", "returned", ".", "We", "also", "return", "the", "distance", "between", "the", "points", "for", "use", "in", "the", "later", "height", "calculation", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/coordinate.go#L182-L203
train
hashicorp/serf
serf/internal_query.go
newSerfQueries
func newSerfQueries(serf *Serf, logger *log.Logger, outCh chan<- Event, shutdownCh <-chan struct{}) (chan<- Event, error) { inCh := make(chan Event, 1024) q := &serfQueries{ inCh: inCh, logger: logger, outCh: outCh, serf: serf, shutdownCh: shutdownCh, } go q.stream() return inCh, nil }
go
func newSerfQueries(serf *Serf, logger *log.Logger, outCh chan<- Event, shutdownCh <-chan struct{}) (chan<- Event, error) { inCh := make(chan Event, 1024) q := &serfQueries{ inCh: inCh, logger: logger, outCh: outCh, serf: serf, shutdownCh: shutdownCh, } go q.stream() return inCh, nil }
[ "func", "newSerfQueries", "(", "serf", "*", "Serf", ",", "logger", "*", "log", ".", "Logger", ",", "outCh", "chan", "<-", "Event", ",", "shutdownCh", "<-", "chan", "struct", "{", "}", ")", "(", "chan", "<-", "Event", ",", "error", ")", "{", "inCh", ":=", "make", "(", "chan", "Event", ",", "1024", ")", "\n", "q", ":=", "&", "serfQueries", "{", "inCh", ":", "inCh", ",", "logger", ":", "logger", ",", "outCh", ":", "outCh", ",", "serf", ":", "serf", ",", "shutdownCh", ":", "shutdownCh", ",", "}", "\n", "go", "q", ".", "stream", "(", ")", "\n", "return", "inCh", ",", "nil", "\n", "}" ]
// newSerfQueries is used to create a new serfQueries. We return an event // channel that is ingested and forwarded to an outCh. Any Queries that // have the InternalQueryPrefix are handled instead of forwarded.
[ "newSerfQueries", "is", "used", "to", "create", "a", "new", "serfQueries", ".", "We", "return", "an", "event", "channel", "that", "is", "ingested", "and", "forwarded", "to", "an", "outCh", ".", "Any", "Queries", "that", "have", "the", "InternalQueryPrefix", "are", "handled", "instead", "of", "forwarded", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L72-L83
train
hashicorp/serf
serf/internal_query.go
stream
func (s *serfQueries) stream() { for { select { case e := <-s.inCh: // Check if this is a query we should process if q, ok := e.(*Query); ok && strings.HasPrefix(q.Name, InternalQueryPrefix) { go s.handleQuery(q) } else if s.outCh != nil { s.outCh <- e } case <-s.shutdownCh: return } } }
go
func (s *serfQueries) stream() { for { select { case e := <-s.inCh: // Check if this is a query we should process if q, ok := e.(*Query); ok && strings.HasPrefix(q.Name, InternalQueryPrefix) { go s.handleQuery(q) } else if s.outCh != nil { s.outCh <- e } case <-s.shutdownCh: return } } }
[ "func", "(", "s", "*", "serfQueries", ")", "stream", "(", ")", "{", "for", "{", "select", "{", "case", "e", ":=", "<-", "s", ".", "inCh", ":", "if", "q", ",", "ok", ":=", "e", ".", "(", "*", "Query", ")", ";", "ok", "&&", "strings", ".", "HasPrefix", "(", "q", ".", "Name", ",", "InternalQueryPrefix", ")", "{", "go", "s", ".", "handleQuery", "(", "q", ")", "\n", "}", "else", "if", "s", ".", "outCh", "!=", "nil", "{", "s", ".", "outCh", "<-", "e", "\n", "}", "\n", "case", "<-", "s", ".", "shutdownCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// stream is a long running routine to ingest the event stream
[ "stream", "is", "a", "long", "running", "routine", "to", "ingest", "the", "event", "stream" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L86-L102
train
hashicorp/serf
serf/internal_query.go
handleQuery
func (s *serfQueries) handleQuery(q *Query) { // Get the queryName after the initial prefix queryName := q.Name[len(InternalQueryPrefix):] switch queryName { case pingQuery: // Nothing to do, we will ack the query case conflictQuery: s.handleConflict(q) case installKeyQuery: s.handleInstallKey(q) case useKeyQuery: s.handleUseKey(q) case removeKeyQuery: s.handleRemoveKey(q) case listKeysQuery: s.handleListKeys(q) default: s.logger.Printf("[WARN] serf: Unhandled internal query '%s'", queryName) } }
go
func (s *serfQueries) handleQuery(q *Query) { // Get the queryName after the initial prefix queryName := q.Name[len(InternalQueryPrefix):] switch queryName { case pingQuery: // Nothing to do, we will ack the query case conflictQuery: s.handleConflict(q) case installKeyQuery: s.handleInstallKey(q) case useKeyQuery: s.handleUseKey(q) case removeKeyQuery: s.handleRemoveKey(q) case listKeysQuery: s.handleListKeys(q) default: s.logger.Printf("[WARN] serf: Unhandled internal query '%s'", queryName) } }
[ "func", "(", "s", "*", "serfQueries", ")", "handleQuery", "(", "q", "*", "Query", ")", "{", "queryName", ":=", "q", ".", "Name", "[", "len", "(", "InternalQueryPrefix", ")", ":", "]", "\n", "switch", "queryName", "{", "case", "pingQuery", ":", "case", "conflictQuery", ":", "s", ".", "handleConflict", "(", "q", ")", "\n", "case", "installKeyQuery", ":", "s", ".", "handleInstallKey", "(", "q", ")", "\n", "case", "useKeyQuery", ":", "s", ".", "handleUseKey", "(", "q", ")", "\n", "case", "removeKeyQuery", ":", "s", ".", "handleRemoveKey", "(", "q", ")", "\n", "case", "listKeysQuery", ":", "s", ".", "handleListKeys", "(", "q", ")", "\n", "default", ":", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] serf: Unhandled internal query '%s'\"", ",", "queryName", ")", "\n", "}", "\n", "}" ]
// handleQuery is invoked when we get an internal query
[ "handleQuery", "is", "invoked", "when", "we", "get", "an", "internal", "query" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L105-L124
train
hashicorp/serf
serf/internal_query.go
handleConflict
func (s *serfQueries) handleConflict(q *Query) { // The target node name is the payload node := string(q.Payload) // Do not respond to the query if it is about us if node == s.serf.config.NodeName { return } s.logger.Printf("[DEBUG] serf: Got conflict resolution query for '%s'", node) // Look for the member info var out *Member s.serf.memberLock.Lock() if member, ok := s.serf.members[node]; ok { out = &member.Member } s.serf.memberLock.Unlock() // Encode the response buf, err := encodeMessage(messageConflictResponseType, out) if err != nil { s.logger.Printf("[ERR] serf: Failed to encode conflict query response: %v", err) return } // Send our answer if err := q.Respond(buf); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to conflict query: %v", err) } }
go
func (s *serfQueries) handleConflict(q *Query) { // The target node name is the payload node := string(q.Payload) // Do not respond to the query if it is about us if node == s.serf.config.NodeName { return } s.logger.Printf("[DEBUG] serf: Got conflict resolution query for '%s'", node) // Look for the member info var out *Member s.serf.memberLock.Lock() if member, ok := s.serf.members[node]; ok { out = &member.Member } s.serf.memberLock.Unlock() // Encode the response buf, err := encodeMessage(messageConflictResponseType, out) if err != nil { s.logger.Printf("[ERR] serf: Failed to encode conflict query response: %v", err) return } // Send our answer if err := q.Respond(buf); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to conflict query: %v", err) } }
[ "func", "(", "s", "*", "serfQueries", ")", "handleConflict", "(", "q", "*", "Query", ")", "{", "node", ":=", "string", "(", "q", ".", "Payload", ")", "\n", "if", "node", "==", "s", ".", "serf", ".", "config", ".", "NodeName", "{", "return", "\n", "}", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[DEBUG] serf: Got conflict resolution query for '%s'\"", ",", "node", ")", "\n", "var", "out", "*", "Member", "\n", "s", ".", "serf", ".", "memberLock", ".", "Lock", "(", ")", "\n", "if", "member", ",", "ok", ":=", "s", ".", "serf", ".", "members", "[", "node", "]", ";", "ok", "{", "out", "=", "&", "member", ".", "Member", "\n", "}", "\n", "s", ".", "serf", ".", "memberLock", ".", "Unlock", "(", ")", "\n", "buf", ",", "err", ":=", "encodeMessage", "(", "messageConflictResponseType", ",", "out", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to encode conflict query response: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "q", ".", "Respond", "(", "buf", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to respond to conflict query: %v\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// handleConflict is invoked when we get a query that is attempting to // disambiguate a name conflict. They payload is a node name, and the response // should the address we believe that node is at, if any.
[ "handleConflict", "is", "invoked", "when", "we", "get", "a", "query", "that", "is", "attempting", "to", "disambiguate", "a", "name", "conflict", ".", "They", "payload", "is", "a", "node", "name", "and", "the", "response", "should", "the", "address", "we", "believe", "that", "node", "is", "at", "if", "any", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L129-L158
train
hashicorp/serf
serf/internal_query.go
sendKeyResponse
func (s *serfQueries) sendKeyResponse(q *Query, resp *nodeKeyResponse) { switch q.Name { case internalQueryName(listKeysQuery): raw, qresp, err := s.keyListResponseWithCorrectSize(q, resp) if err != nil { s.logger.Printf("[ERR] serf: %v", err) return } if err := q.respondWithMessageAndResponse(raw, qresp); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to key query: %v", err) return } default: buf, err := encodeMessage(messageKeyResponseType, resp) if err != nil { s.logger.Printf("[ERR] serf: Failed to encode key response: %v", err) return } if err := q.Respond(buf); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to key query: %v", err) return } } }
go
func (s *serfQueries) sendKeyResponse(q *Query, resp *nodeKeyResponse) { switch q.Name { case internalQueryName(listKeysQuery): raw, qresp, err := s.keyListResponseWithCorrectSize(q, resp) if err != nil { s.logger.Printf("[ERR] serf: %v", err) return } if err := q.respondWithMessageAndResponse(raw, qresp); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to key query: %v", err) return } default: buf, err := encodeMessage(messageKeyResponseType, resp) if err != nil { s.logger.Printf("[ERR] serf: Failed to encode key response: %v", err) return } if err := q.Respond(buf); err != nil { s.logger.Printf("[ERR] serf: Failed to respond to key query: %v", err) return } } }
[ "func", "(", "s", "*", "serfQueries", ")", "sendKeyResponse", "(", "q", "*", "Query", ",", "resp", "*", "nodeKeyResponse", ")", "{", "switch", "q", ".", "Name", "{", "case", "internalQueryName", "(", "listKeysQuery", ")", ":", "raw", ",", "qresp", ",", "err", ":=", "s", ".", "keyListResponseWithCorrectSize", "(", "q", ",", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "q", ".", "respondWithMessageAndResponse", "(", "raw", ",", "qresp", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to respond to key query: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "default", ":", "buf", ",", "err", ":=", "encodeMessage", "(", "messageKeyResponseType", ",", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to encode key response: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "q", ".", "Respond", "(", "buf", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to respond to key query: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// sendKeyResponse handles responding to key-related queries.
[ "sendKeyResponse", "handles", "responding", "to", "key", "-", "related", "queries", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L194-L217
train
hashicorp/serf
serf/internal_query.go
handleInstallKey
func (s *serfQueries) handleInstallKey(q *Query) { response := nodeKeyResponse{Result: false} keyring := s.serf.config.MemberlistConfig.Keyring req := keyRequest{} err := decodeMessage(q.Payload[1:], &req) if err != nil { s.logger.Printf("[ERR] serf: Failed to decode key request: %v", err) goto SEND } if !s.serf.EncryptionEnabled() { response.Message = "No keyring to modify (encryption not enabled)" s.logger.Printf("[ERR] serf: No keyring to modify (encryption not enabled)") goto SEND } s.logger.Printf("[INFO] serf: Received install-key query") if err := keyring.AddKey(req.Key); err != nil { response.Message = err.Error() s.logger.Printf("[ERR] serf: Failed to install key: %s", err) goto SEND } if s.serf.config.KeyringFile != "" { if err := s.serf.writeKeyringFile(); err != nil { response.Message = err.Error() s.logger.Printf("[ERR] serf: Failed to write keyring file: %s", err) goto SEND } } response.Result = true SEND: s.sendKeyResponse(q, &response) }
go
func (s *serfQueries) handleInstallKey(q *Query) { response := nodeKeyResponse{Result: false} keyring := s.serf.config.MemberlistConfig.Keyring req := keyRequest{} err := decodeMessage(q.Payload[1:], &req) if err != nil { s.logger.Printf("[ERR] serf: Failed to decode key request: %v", err) goto SEND } if !s.serf.EncryptionEnabled() { response.Message = "No keyring to modify (encryption not enabled)" s.logger.Printf("[ERR] serf: No keyring to modify (encryption not enabled)") goto SEND } s.logger.Printf("[INFO] serf: Received install-key query") if err := keyring.AddKey(req.Key); err != nil { response.Message = err.Error() s.logger.Printf("[ERR] serf: Failed to install key: %s", err) goto SEND } if s.serf.config.KeyringFile != "" { if err := s.serf.writeKeyringFile(); err != nil { response.Message = err.Error() s.logger.Printf("[ERR] serf: Failed to write keyring file: %s", err) goto SEND } } response.Result = true SEND: s.sendKeyResponse(q, &response) }
[ "func", "(", "s", "*", "serfQueries", ")", "handleInstallKey", "(", "q", "*", "Query", ")", "{", "response", ":=", "nodeKeyResponse", "{", "Result", ":", "false", "}", "\n", "keyring", ":=", "s", ".", "serf", ".", "config", ".", "MemberlistConfig", ".", "Keyring", "\n", "req", ":=", "keyRequest", "{", "}", "\n", "err", ":=", "decodeMessage", "(", "q", ".", "Payload", "[", "1", ":", "]", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to decode key request: %v\"", ",", "err", ")", "\n", "goto", "SEND", "\n", "}", "\n", "if", "!", "s", ".", "serf", ".", "EncryptionEnabled", "(", ")", "{", "response", ".", "Message", "=", "\"No keyring to modify (encryption not enabled)\"", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: No keyring to modify (encryption not enabled)\"", ")", "\n", "goto", "SEND", "\n", "}", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[INFO] serf: Received install-key query\"", ")", "\n", "if", "err", ":=", "keyring", ".", "AddKey", "(", "req", ".", "Key", ")", ";", "err", "!=", "nil", "{", "response", ".", "Message", "=", "err", ".", "Error", "(", ")", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to install key: %s\"", ",", "err", ")", "\n", "goto", "SEND", "\n", "}", "\n", "if", "s", ".", "serf", ".", "config", ".", "KeyringFile", "!=", "\"\"", "{", "if", "err", ":=", "s", ".", "serf", ".", "writeKeyringFile", "(", ")", ";", "err", "!=", "nil", "{", "response", ".", "Message", "=", "err", ".", "Error", "(", ")", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Failed to write keyring file: %s\"", ",", "err", ")", "\n", "goto", "SEND", "\n", "}", "\n", "}", "\n", "response", ".", "Result", "=", "true", "\n", "SEND", ":", "s", ".", "sendKeyResponse", "(", "q", ",", "&", "response", ")", "\n", "}" ]
// handleInstallKey is invoked whenever a new encryption key is received from // another member in the cluster, and handles the process of installing it onto // the memberlist keyring. This type of query may fail if the provided key does // not fit the constraints that memberlist enforces. If the query fails, the // response will contain the error message so that it may be relayed.
[ "handleInstallKey", "is", "invoked", "whenever", "a", "new", "encryption", "key", "is", "received", "from", "another", "member", "in", "the", "cluster", "and", "handles", "the", "process", "of", "installing", "it", "onto", "the", "memberlist", "keyring", ".", "This", "type", "of", "query", "may", "fail", "if", "the", "provided", "key", "does", "not", "fit", "the", "constraints", "that", "memberlist", "enforces", ".", "If", "the", "query", "fails", "the", "response", "will", "contain", "the", "error", "message", "so", "that", "it", "may", "be", "relayed", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L224-L260
train
hashicorp/serf
serf/internal_query.go
handleListKeys
func (s *serfQueries) handleListKeys(q *Query) { response := nodeKeyResponse{Result: false} keyring := s.serf.config.MemberlistConfig.Keyring if !s.serf.EncryptionEnabled() { response.Message = "Keyring is empty (encryption not enabled)" s.logger.Printf("[ERR] serf: Keyring is empty (encryption not enabled)") goto SEND } s.logger.Printf("[INFO] serf: Received list-keys query") for _, keyBytes := range keyring.GetKeys() { // Encode the keys before sending the response. This should help take // some the burden of doing this off of the asking member. key := base64.StdEncoding.EncodeToString(keyBytes) response.Keys = append(response.Keys, key) } response.Result = true SEND: s.sendKeyResponse(q, &response) }
go
func (s *serfQueries) handleListKeys(q *Query) { response := nodeKeyResponse{Result: false} keyring := s.serf.config.MemberlistConfig.Keyring if !s.serf.EncryptionEnabled() { response.Message = "Keyring is empty (encryption not enabled)" s.logger.Printf("[ERR] serf: Keyring is empty (encryption not enabled)") goto SEND } s.logger.Printf("[INFO] serf: Received list-keys query") for _, keyBytes := range keyring.GetKeys() { // Encode the keys before sending the response. This should help take // some the burden of doing this off of the asking member. key := base64.StdEncoding.EncodeToString(keyBytes) response.Keys = append(response.Keys, key) } response.Result = true SEND: s.sendKeyResponse(q, &response) }
[ "func", "(", "s", "*", "serfQueries", ")", "handleListKeys", "(", "q", "*", "Query", ")", "{", "response", ":=", "nodeKeyResponse", "{", "Result", ":", "false", "}", "\n", "keyring", ":=", "s", ".", "serf", ".", "config", ".", "MemberlistConfig", ".", "Keyring", "\n", "if", "!", "s", ".", "serf", ".", "EncryptionEnabled", "(", ")", "{", "response", ".", "Message", "=", "\"Keyring is empty (encryption not enabled)\"", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[ERR] serf: Keyring is empty (encryption not enabled)\"", ")", "\n", "goto", "SEND", "\n", "}", "\n", "s", ".", "logger", ".", "Printf", "(", "\"[INFO] serf: Received list-keys query\"", ")", "\n", "for", "_", ",", "keyBytes", ":=", "range", "keyring", ".", "GetKeys", "(", ")", "{", "key", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "keyBytes", ")", "\n", "response", ".", "Keys", "=", "append", "(", "response", ".", "Keys", ",", "key", ")", "\n", "}", "\n", "response", ".", "Result", "=", "true", "\n", "SEND", ":", "s", ".", "sendKeyResponse", "(", "q", ",", "&", "response", ")", "\n", "}" ]
// handleListKeys is invoked when a query is received to return a list of all // installed keys the Serf instance knows of. For performance, the keys are // encoded to base64 on each of the members to remove this burden from the // node asking for the results.
[ "handleListKeys", "is", "invoked", "when", "a", "query", "is", "received", "to", "return", "a", "list", "of", "all", "installed", "keys", "the", "Serf", "instance", "knows", "of", ".", "For", "performance", "the", "keys", "are", "encoded", "to", "base64", "on", "each", "of", "the", "members", "to", "remove", "this", "burden", "from", "the", "node", "asking", "for", "the", "results", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/internal_query.go#L346-L367
train
hashicorp/serf
serf/query.go
DefaultQueryParams
func (s *Serf) DefaultQueryParams() *QueryParam { return &QueryParam{ FilterNodes: nil, FilterTags: nil, RequestAck: false, Timeout: s.DefaultQueryTimeout(), } }
go
func (s *Serf) DefaultQueryParams() *QueryParam { return &QueryParam{ FilterNodes: nil, FilterTags: nil, RequestAck: false, Timeout: s.DefaultQueryTimeout(), } }
[ "func", "(", "s", "*", "Serf", ")", "DefaultQueryParams", "(", ")", "*", "QueryParam", "{", "return", "&", "QueryParam", "{", "FilterNodes", ":", "nil", ",", "FilterTags", ":", "nil", ",", "RequestAck", ":", "false", ",", "Timeout", ":", "s", ".", "DefaultQueryTimeout", "(", ")", ",", "}", "\n", "}" ]
// DefaultQueryParam is used to return the default query parameters
[ "DefaultQueryParam", "is", "used", "to", "return", "the", "default", "query", "parameters" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L51-L58
train
hashicorp/serf
serf/query.go
encodeFilters
func (q *QueryParam) encodeFilters() ([][]byte, error) { var filters [][]byte // Add the node filter if len(q.FilterNodes) > 0 { if buf, err := encodeFilter(filterNodeType, q.FilterNodes); err != nil { return nil, err } else { filters = append(filters, buf) } } // Add the tag filters for tag, expr := range q.FilterTags { filt := filterTag{tag, expr} if buf, err := encodeFilter(filterTagType, &filt); err != nil { return nil, err } else { filters = append(filters, buf) } } return filters, nil }
go
func (q *QueryParam) encodeFilters() ([][]byte, error) { var filters [][]byte // Add the node filter if len(q.FilterNodes) > 0 { if buf, err := encodeFilter(filterNodeType, q.FilterNodes); err != nil { return nil, err } else { filters = append(filters, buf) } } // Add the tag filters for tag, expr := range q.FilterTags { filt := filterTag{tag, expr} if buf, err := encodeFilter(filterTagType, &filt); err != nil { return nil, err } else { filters = append(filters, buf) } } return filters, nil }
[ "func", "(", "q", "*", "QueryParam", ")", "encodeFilters", "(", ")", "(", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "var", "filters", "[", "]", "[", "]", "byte", "\n", "if", "len", "(", "q", ".", "FilterNodes", ")", ">", "0", "{", "if", "buf", ",", "err", ":=", "encodeFilter", "(", "filterNodeType", ",", "q", ".", "FilterNodes", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "filters", "=", "append", "(", "filters", ",", "buf", ")", "\n", "}", "\n", "}", "\n", "for", "tag", ",", "expr", ":=", "range", "q", ".", "FilterTags", "{", "filt", ":=", "filterTag", "{", "tag", ",", "expr", "}", "\n", "if", "buf", ",", "err", ":=", "encodeFilter", "(", "filterTagType", ",", "&", "filt", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "filters", "=", "append", "(", "filters", ",", "buf", ")", "\n", "}", "\n", "}", "\n", "return", "filters", ",", "nil", "\n", "}" ]
// encodeFilters is used to convert the filters into the wire format
[ "encodeFilters", "is", "used", "to", "convert", "the", "filters", "into", "the", "wire", "format" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L61-L84
train
hashicorp/serf
serf/query.go
newQueryResponse
func newQueryResponse(n int, q *messageQuery) *QueryResponse { resp := &QueryResponse{ deadline: time.Now().Add(q.Timeout), id: q.ID, lTime: q.LTime, respCh: make(chan NodeResponse, n), responses: make(map[string]struct{}), } if q.Ack() { resp.ackCh = make(chan string, n) resp.acks = make(map[string]struct{}) } return resp }
go
func newQueryResponse(n int, q *messageQuery) *QueryResponse { resp := &QueryResponse{ deadline: time.Now().Add(q.Timeout), id: q.ID, lTime: q.LTime, respCh: make(chan NodeResponse, n), responses: make(map[string]struct{}), } if q.Ack() { resp.ackCh = make(chan string, n) resp.acks = make(map[string]struct{}) } return resp }
[ "func", "newQueryResponse", "(", "n", "int", ",", "q", "*", "messageQuery", ")", "*", "QueryResponse", "{", "resp", ":=", "&", "QueryResponse", "{", "deadline", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "q", ".", "Timeout", ")", ",", "id", ":", "q", ".", "ID", ",", "lTime", ":", "q", ".", "LTime", ",", "respCh", ":", "make", "(", "chan", "NodeResponse", ",", "n", ")", ",", "responses", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "}", "\n", "if", "q", ".", "Ack", "(", ")", "{", "resp", ".", "ackCh", "=", "make", "(", "chan", "string", ",", "n", ")", "\n", "resp", ".", "acks", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "}", "\n", "return", "resp", "\n", "}" ]
// newQueryResponse is used to construct a new query response
[ "newQueryResponse", "is", "used", "to", "construct", "a", "new", "query", "response" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L113-L126
train
hashicorp/serf
serf/query.go
Close
func (r *QueryResponse) Close() { r.closeLock.Lock() defer r.closeLock.Unlock() if r.closed { return } r.closed = true if r.ackCh != nil { close(r.ackCh) } if r.respCh != nil { close(r.respCh) } }
go
func (r *QueryResponse) Close() { r.closeLock.Lock() defer r.closeLock.Unlock() if r.closed { return } r.closed = true if r.ackCh != nil { close(r.ackCh) } if r.respCh != nil { close(r.respCh) } }
[ "func", "(", "r", "*", "QueryResponse", ")", "Close", "(", ")", "{", "r", ".", "closeLock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "closeLock", ".", "Unlock", "(", ")", "\n", "if", "r", ".", "closed", "{", "return", "\n", "}", "\n", "r", ".", "closed", "=", "true", "\n", "if", "r", ".", "ackCh", "!=", "nil", "{", "close", "(", "r", ".", "ackCh", ")", "\n", "}", "\n", "if", "r", ".", "respCh", "!=", "nil", "{", "close", "(", "r", ".", "respCh", ")", "\n", "}", "\n", "}" ]
// Close is used to close the query, which will close the underlying // channels and prevent further deliveries
[ "Close", "is", "used", "to", "close", "the", "query", "which", "will", "close", "the", "underlying", "channels", "and", "prevent", "further", "deliveries" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L130-L143
train
hashicorp/serf
serf/query.go
Finished
func (r *QueryResponse) Finished() bool { r.closeLock.Lock() defer r.closeLock.Unlock() return r.closed || time.Now().After(r.deadline) }
go
func (r *QueryResponse) Finished() bool { r.closeLock.Lock() defer r.closeLock.Unlock() return r.closed || time.Now().After(r.deadline) }
[ "func", "(", "r", "*", "QueryResponse", ")", "Finished", "(", ")", "bool", "{", "r", ".", "closeLock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "closeLock", ".", "Unlock", "(", ")", "\n", "return", "r", ".", "closed", "||", "time", ".", "Now", "(", ")", ".", "After", "(", "r", ".", "deadline", ")", "\n", "}" ]
// Finished returns if the query is finished running
[ "Finished", "returns", "if", "the", "query", "is", "finished", "running" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L151-L155
train
hashicorp/serf
serf/query.go
sendResponse
func (r *QueryResponse) sendResponse(nr NodeResponse) error { r.closeLock.Lock() defer r.closeLock.Unlock() if r.closed { return nil } select { case r.respCh <- nr: r.responses[nr.From] = struct{}{} default: return errors.New("serf: Failed to deliver query response, dropping") } return nil }
go
func (r *QueryResponse) sendResponse(nr NodeResponse) error { r.closeLock.Lock() defer r.closeLock.Unlock() if r.closed { return nil } select { case r.respCh <- nr: r.responses[nr.From] = struct{}{} default: return errors.New("serf: Failed to deliver query response, dropping") } return nil }
[ "func", "(", "r", "*", "QueryResponse", ")", "sendResponse", "(", "nr", "NodeResponse", ")", "error", "{", "r", ".", "closeLock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "closeLock", ".", "Unlock", "(", ")", "\n", "if", "r", ".", "closed", "{", "return", "nil", "\n", "}", "\n", "select", "{", "case", "r", ".", "respCh", "<-", "nr", ":", "r", ".", "responses", "[", "nr", ".", "From", "]", "=", "struct", "{", "}", "{", "}", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"serf: Failed to deliver query response, dropping\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// sendResponse sends a response on the response channel ensuring the channel is not closed.
[ "sendResponse", "sends", "a", "response", "on", "the", "response", "channel", "ensuring", "the", "channel", "is", "not", "closed", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L171-L184
train
hashicorp/serf
serf/query.go
shouldProcessQuery
func (s *Serf) shouldProcessQuery(filters [][]byte) bool { for _, filter := range filters { switch filterType(filter[0]) { case filterNodeType: // Decode the filter var nodes filterNode if err := decodeMessage(filter[1:], &nodes); err != nil { s.logger.Printf("[WARN] serf: failed to decode filterNodeType: %v", err) return false } // Check if we are being targeted found := false for _, n := range nodes { if n == s.config.NodeName { found = true break } } if !found { return false } case filterTagType: // Decode the filter var filt filterTag if err := decodeMessage(filter[1:], &filt); err != nil { s.logger.Printf("[WARN] serf: failed to decode filterTagType: %v", err) return false } // Check if we match this regex tags := s.config.Tags matched, err := regexp.MatchString(filt.Expr, tags[filt.Tag]) if err != nil { s.logger.Printf("[WARN] serf: failed to compile filter regex (%s): %v", filt.Expr, err) return false } if !matched { return false } default: s.logger.Printf("[WARN] serf: query has unrecognized filter type: %d", filter[0]) return false } } return true }
go
func (s *Serf) shouldProcessQuery(filters [][]byte) bool { for _, filter := range filters { switch filterType(filter[0]) { case filterNodeType: // Decode the filter var nodes filterNode if err := decodeMessage(filter[1:], &nodes); err != nil { s.logger.Printf("[WARN] serf: failed to decode filterNodeType: %v", err) return false } // Check if we are being targeted found := false for _, n := range nodes { if n == s.config.NodeName { found = true break } } if !found { return false } case filterTagType: // Decode the filter var filt filterTag if err := decodeMessage(filter[1:], &filt); err != nil { s.logger.Printf("[WARN] serf: failed to decode filterTagType: %v", err) return false } // Check if we match this regex tags := s.config.Tags matched, err := regexp.MatchString(filt.Expr, tags[filt.Tag]) if err != nil { s.logger.Printf("[WARN] serf: failed to compile filter regex (%s): %v", filt.Expr, err) return false } if !matched { return false } default: s.logger.Printf("[WARN] serf: query has unrecognized filter type: %d", filter[0]) return false } } return true }
[ "func", "(", "s", "*", "Serf", ")", "shouldProcessQuery", "(", "filters", "[", "]", "[", "]", "byte", ")", "bool", "{", "for", "_", ",", "filter", ":=", "range", "filters", "{", "switch", "filterType", "(", "filter", "[", "0", "]", ")", "{", "case", "filterNodeType", ":", "var", "nodes", "filterNode", "\n", "if", "err", ":=", "decodeMessage", "(", "filter", "[", "1", ":", "]", ",", "&", "nodes", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] serf: failed to decode filterNodeType: %v\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "found", ":=", "false", "\n", "for", "_", ",", "n", ":=", "range", "nodes", "{", "if", "n", "==", "s", ".", "config", ".", "NodeName", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "false", "\n", "}", "\n", "case", "filterTagType", ":", "var", "filt", "filterTag", "\n", "if", "err", ":=", "decodeMessage", "(", "filter", "[", "1", ":", "]", ",", "&", "filt", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] serf: failed to decode filterTagType: %v\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "tags", ":=", "s", ".", "config", ".", "Tags", "\n", "matched", ",", "err", ":=", "regexp", ".", "MatchString", "(", "filt", ".", "Expr", ",", "tags", "[", "filt", ".", "Tag", "]", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] serf: failed to compile filter regex (%s): %v\"", ",", "filt", ".", "Expr", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "if", "!", "matched", "{", "return", "false", "\n", "}", "\n", "default", ":", "s", ".", "logger", ".", "Printf", "(", "\"[WARN] serf: query has unrecognized filter type: %d\"", ",", "filter", "[", "0", "]", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// shouldProcessQuery checks if a query should be proceeded given // a set of filers.
[ "shouldProcessQuery", "checks", "if", "a", "query", "should", "be", "proceeded", "given", "a", "set", "of", "filers", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L194-L242
train
hashicorp/serf
serf/query.go
relayResponse
func (s *Serf) relayResponse(relayFactor uint8, addr net.UDPAddr, resp *messageQueryResponse) error { if relayFactor == 0 { return nil } // Needs to be worth it; we need to have at least relayFactor *other* // nodes. If you have a tiny cluster then the relayFactor shouldn't // be needed. members := s.Members() if len(members) < int(relayFactor)+1 { return nil } // Prep the relay message, which is a wrapped version of the original. raw, err := encodeRelayMessage(messageQueryResponseType, addr, &resp) if err != nil { return fmt.Errorf("failed to format relayed response: %v", err) } if len(raw) > s.config.QueryResponseSizeLimit { return fmt.Errorf("relayed response exceeds limit of %d bytes", s.config.QueryResponseSizeLimit) } // Relay to a random set of peers. localName := s.LocalMember().Name relayMembers := kRandomMembers(int(relayFactor), members, func(m Member) bool { return m.Status != StatusAlive || m.ProtocolMax < 5 || m.Name == localName }) for _, m := range relayMembers { relayAddr := net.UDPAddr{IP: m.Addr, Port: int(m.Port)} if err := s.memberlist.SendTo(&relayAddr, raw); err != nil { return fmt.Errorf("failed to send relay response: %v", err) } } return nil }
go
func (s *Serf) relayResponse(relayFactor uint8, addr net.UDPAddr, resp *messageQueryResponse) error { if relayFactor == 0 { return nil } // Needs to be worth it; we need to have at least relayFactor *other* // nodes. If you have a tiny cluster then the relayFactor shouldn't // be needed. members := s.Members() if len(members) < int(relayFactor)+1 { return nil } // Prep the relay message, which is a wrapped version of the original. raw, err := encodeRelayMessage(messageQueryResponseType, addr, &resp) if err != nil { return fmt.Errorf("failed to format relayed response: %v", err) } if len(raw) > s.config.QueryResponseSizeLimit { return fmt.Errorf("relayed response exceeds limit of %d bytes", s.config.QueryResponseSizeLimit) } // Relay to a random set of peers. localName := s.LocalMember().Name relayMembers := kRandomMembers(int(relayFactor), members, func(m Member) bool { return m.Status != StatusAlive || m.ProtocolMax < 5 || m.Name == localName }) for _, m := range relayMembers { relayAddr := net.UDPAddr{IP: m.Addr, Port: int(m.Port)} if err := s.memberlist.SendTo(&relayAddr, raw); err != nil { return fmt.Errorf("failed to send relay response: %v", err) } } return nil }
[ "func", "(", "s", "*", "Serf", ")", "relayResponse", "(", "relayFactor", "uint8", ",", "addr", "net", ".", "UDPAddr", ",", "resp", "*", "messageQueryResponse", ")", "error", "{", "if", "relayFactor", "==", "0", "{", "return", "nil", "\n", "}", "\n", "members", ":=", "s", ".", "Members", "(", ")", "\n", "if", "len", "(", "members", ")", "<", "int", "(", "relayFactor", ")", "+", "1", "{", "return", "nil", "\n", "}", "\n", "raw", ",", "err", ":=", "encodeRelayMessage", "(", "messageQueryResponseType", ",", "addr", ",", "&", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to format relayed response: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "raw", ")", ">", "s", ".", "config", ".", "QueryResponseSizeLimit", "{", "return", "fmt", ".", "Errorf", "(", "\"relayed response exceeds limit of %d bytes\"", ",", "s", ".", "config", ".", "QueryResponseSizeLimit", ")", "\n", "}", "\n", "localName", ":=", "s", ".", "LocalMember", "(", ")", ".", "Name", "\n", "relayMembers", ":=", "kRandomMembers", "(", "int", "(", "relayFactor", ")", ",", "members", ",", "func", "(", "m", "Member", ")", "bool", "{", "return", "m", ".", "Status", "!=", "StatusAlive", "||", "m", ".", "ProtocolMax", "<", "5", "||", "m", ".", "Name", "==", "localName", "\n", "}", ")", "\n", "for", "_", ",", "m", ":=", "range", "relayMembers", "{", "relayAddr", ":=", "net", ".", "UDPAddr", "{", "IP", ":", "m", ".", "Addr", ",", "Port", ":", "int", "(", "m", ".", "Port", ")", "}", "\n", "if", "err", ":=", "s", ".", "memberlist", ".", "SendTo", "(", "&", "relayAddr", ",", "raw", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to send relay response: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// relayResponse will relay a copy of the given response to up to relayFactor // other members.
[ "relayResponse", "will", "relay", "a", "copy", "of", "the", "given", "response", "to", "up", "to", "relayFactor", "other", "members", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L246-L280
train
hashicorp/serf
serf/query.go
kRandomMembers
func kRandomMembers(k int, members []Member, filterFunc func(Member) bool) []Member { n := len(members) kMembers := make([]Member, 0, k) OUTER: // Probe up to 3*n times, with large n this is not necessary // since k << n, but with small n we want search to be // exhaustive for i := 0; i < 3*n && len(kMembers) < k; i++ { // Get random member idx := rand.Intn(n) member := members[idx] // Give the filter a shot at it. if filterFunc != nil && filterFunc(member) { continue OUTER } // Check if we have this member already for j := 0; j < len(kMembers); j++ { if member.Name == kMembers[j].Name { continue OUTER } } // Append the member kMembers = append(kMembers, member) } return kMembers }
go
func kRandomMembers(k int, members []Member, filterFunc func(Member) bool) []Member { n := len(members) kMembers := make([]Member, 0, k) OUTER: // Probe up to 3*n times, with large n this is not necessary // since k << n, but with small n we want search to be // exhaustive for i := 0; i < 3*n && len(kMembers) < k; i++ { // Get random member idx := rand.Intn(n) member := members[idx] // Give the filter a shot at it. if filterFunc != nil && filterFunc(member) { continue OUTER } // Check if we have this member already for j := 0; j < len(kMembers); j++ { if member.Name == kMembers[j].Name { continue OUTER } } // Append the member kMembers = append(kMembers, member) } return kMembers }
[ "func", "kRandomMembers", "(", "k", "int", ",", "members", "[", "]", "Member", ",", "filterFunc", "func", "(", "Member", ")", "bool", ")", "[", "]", "Member", "{", "n", ":=", "len", "(", "members", ")", "\n", "kMembers", ":=", "make", "(", "[", "]", "Member", ",", "0", ",", "k", ")", "\n", "OUTER", ":", "for", "i", ":=", "0", ";", "i", "<", "3", "*", "n", "&&", "len", "(", "kMembers", ")", "<", "k", ";", "i", "++", "{", "idx", ":=", "rand", ".", "Intn", "(", "n", ")", "\n", "member", ":=", "members", "[", "idx", "]", "\n", "if", "filterFunc", "!=", "nil", "&&", "filterFunc", "(", "member", ")", "{", "continue", "OUTER", "\n", "}", "\n", "for", "j", ":=", "0", ";", "j", "<", "len", "(", "kMembers", ")", ";", "j", "++", "{", "if", "member", ".", "Name", "==", "kMembers", "[", "j", "]", ".", "Name", "{", "continue", "OUTER", "\n", "}", "\n", "}", "\n", "kMembers", "=", "append", "(", "kMembers", ",", "member", ")", "\n", "}", "\n", "return", "kMembers", "\n", "}" ]
// kRandomMembers selects up to k members from a given list, optionally // filtering by the given filterFunc
[ "kRandomMembers", "selects", "up", "to", "k", "members", "from", "a", "given", "list", "optionally", "filtering", "by", "the", "given", "filterFunc" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/query.go#L284-L313
train
hashicorp/serf
cmd/serf/command/agent/mdns.go
NewAgentMDNS
func NewAgentMDNS(agent *Agent, logOutput io.Writer, replay bool, node, discover string, iface *net.Interface, bind net.IP, port int) (*AgentMDNS, error) { // Create the service service, err := mdns.NewMDNSService( node, mdnsName(discover), "", "", port, []net.IP{bind}, []string{fmt.Sprintf("Serf '%s' cluster", discover)}) if err != nil { return nil, err } // Configure mdns server conf := &mdns.Config{ Zone: service, Iface: iface, } // Create the server server, err := mdns.NewServer(conf) if err != nil { return nil, err } // Initialize the AgentMDNS m := &AgentMDNS{ agent: agent, discover: discover, logger: log.New(logOutput, "", log.LstdFlags), seen: make(map[string]struct{}), server: server, replay: replay, iface: iface, } // Start the background workers go m.run() return m, nil }
go
func NewAgentMDNS(agent *Agent, logOutput io.Writer, replay bool, node, discover string, iface *net.Interface, bind net.IP, port int) (*AgentMDNS, error) { // Create the service service, err := mdns.NewMDNSService( node, mdnsName(discover), "", "", port, []net.IP{bind}, []string{fmt.Sprintf("Serf '%s' cluster", discover)}) if err != nil { return nil, err } // Configure mdns server conf := &mdns.Config{ Zone: service, Iface: iface, } // Create the server server, err := mdns.NewServer(conf) if err != nil { return nil, err } // Initialize the AgentMDNS m := &AgentMDNS{ agent: agent, discover: discover, logger: log.New(logOutput, "", log.LstdFlags), seen: make(map[string]struct{}), server: server, replay: replay, iface: iface, } // Start the background workers go m.run() return m, nil }
[ "func", "NewAgentMDNS", "(", "agent", "*", "Agent", ",", "logOutput", "io", ".", "Writer", ",", "replay", "bool", ",", "node", ",", "discover", "string", ",", "iface", "*", "net", ".", "Interface", ",", "bind", "net", ".", "IP", ",", "port", "int", ")", "(", "*", "AgentMDNS", ",", "error", ")", "{", "service", ",", "err", ":=", "mdns", ".", "NewMDNSService", "(", "node", ",", "mdnsName", "(", "discover", ")", ",", "\"\"", ",", "\"\"", ",", "port", ",", "[", "]", "net", ".", "IP", "{", "bind", "}", ",", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"Serf '%s' cluster\"", ",", "discover", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "conf", ":=", "&", "mdns", ".", "Config", "{", "Zone", ":", "service", ",", "Iface", ":", "iface", ",", "}", "\n", "server", ",", "err", ":=", "mdns", ".", "NewServer", "(", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ":=", "&", "AgentMDNS", "{", "agent", ":", "agent", ",", "discover", ":", "discover", ",", "logger", ":", "log", ".", "New", "(", "logOutput", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", ",", "seen", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "server", ":", "server", ",", "replay", ":", "replay", ",", "iface", ":", "iface", ",", "}", "\n", "go", "m", ".", "run", "(", ")", "\n", "return", "m", ",", "nil", "\n", "}" ]
// NewAgentMDNS is used to create a new AgentMDNS
[ "NewAgentMDNS", "is", "used", "to", "create", "a", "new", "AgentMDNS" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/mdns.go#L31-L72
train
hashicorp/serf
cmd/serf/command/agent/mdns.go
run
func (m *AgentMDNS) run() { hosts := make(chan *mdns.ServiceEntry, 32) poll := time.After(0) var quiet <-chan time.Time var join []string for { select { case h := <-hosts: // Format the host address addr := net.TCPAddr{IP: h.Addr, Port: h.Port} addrS := addr.String() // Skip if we've handled this host already if _, ok := m.seen[addrS]; ok { continue } // Queue for handling join = append(join, addrS) quiet = time.After(mdnsQuietInterval) case <-quiet: // Attempt the join n, err := m.agent.Join(join, m.replay) if err != nil { m.logger.Printf("[ERR] agent.mdns: Failed to join: %v", err) } if n > 0 { m.logger.Printf("[INFO] agent.mdns: Joined %d hosts", n) } // Mark all as seen for _, n := range join { m.seen[n] = struct{}{} } join = nil case <-poll: poll = time.After(mdnsPollInterval) go m.poll(hosts) } } }
go
func (m *AgentMDNS) run() { hosts := make(chan *mdns.ServiceEntry, 32) poll := time.After(0) var quiet <-chan time.Time var join []string for { select { case h := <-hosts: // Format the host address addr := net.TCPAddr{IP: h.Addr, Port: h.Port} addrS := addr.String() // Skip if we've handled this host already if _, ok := m.seen[addrS]; ok { continue } // Queue for handling join = append(join, addrS) quiet = time.After(mdnsQuietInterval) case <-quiet: // Attempt the join n, err := m.agent.Join(join, m.replay) if err != nil { m.logger.Printf("[ERR] agent.mdns: Failed to join: %v", err) } if n > 0 { m.logger.Printf("[INFO] agent.mdns: Joined %d hosts", n) } // Mark all as seen for _, n := range join { m.seen[n] = struct{}{} } join = nil case <-poll: poll = time.After(mdnsPollInterval) go m.poll(hosts) } } }
[ "func", "(", "m", "*", "AgentMDNS", ")", "run", "(", ")", "{", "hosts", ":=", "make", "(", "chan", "*", "mdns", ".", "ServiceEntry", ",", "32", ")", "\n", "poll", ":=", "time", ".", "After", "(", "0", ")", "\n", "var", "quiet", "<-", "chan", "time", ".", "Time", "\n", "var", "join", "[", "]", "string", "\n", "for", "{", "select", "{", "case", "h", ":=", "<-", "hosts", ":", "addr", ":=", "net", ".", "TCPAddr", "{", "IP", ":", "h", ".", "Addr", ",", "Port", ":", "h", ".", "Port", "}", "\n", "addrS", ":=", "addr", ".", "String", "(", ")", "\n", "if", "_", ",", "ok", ":=", "m", ".", "seen", "[", "addrS", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "join", "=", "append", "(", "join", ",", "addrS", ")", "\n", "quiet", "=", "time", ".", "After", "(", "mdnsQuietInterval", ")", "\n", "case", "<-", "quiet", ":", "n", ",", "err", ":=", "m", ".", "agent", ".", "Join", "(", "join", ",", "m", ".", "replay", ")", "\n", "if", "err", "!=", "nil", "{", "m", ".", "logger", ".", "Printf", "(", "\"[ERR] agent.mdns: Failed to join: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "n", ">", "0", "{", "m", ".", "logger", ".", "Printf", "(", "\"[INFO] agent.mdns: Joined %d hosts\"", ",", "n", ")", "\n", "}", "\n", "for", "_", ",", "n", ":=", "range", "join", "{", "m", ".", "seen", "[", "n", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "join", "=", "nil", "\n", "case", "<-", "poll", ":", "poll", "=", "time", ".", "After", "(", "mdnsPollInterval", ")", "\n", "go", "m", ".", "poll", "(", "hosts", ")", "\n", "}", "\n", "}", "\n", "}" ]
// run is a long running goroutine that scans for new hosts periodically
[ "run", "is", "a", "long", "running", "goroutine", "that", "scans", "for", "new", "hosts", "periodically" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/mdns.go#L75-L118
train
hashicorp/serf
cmd/serf/command/agent/mdns.go
poll
func (m *AgentMDNS) poll(hosts chan *mdns.ServiceEntry) { params := mdns.QueryParam{ Service: mdnsName(m.discover), Interface: m.iface, Entries: hosts, } if err := mdns.Query(&params); err != nil { m.logger.Printf("[ERR] agent.mdns: Failed to poll for new hosts: %v", err) } }
go
func (m *AgentMDNS) poll(hosts chan *mdns.ServiceEntry) { params := mdns.QueryParam{ Service: mdnsName(m.discover), Interface: m.iface, Entries: hosts, } if err := mdns.Query(&params); err != nil { m.logger.Printf("[ERR] agent.mdns: Failed to poll for new hosts: %v", err) } }
[ "func", "(", "m", "*", "AgentMDNS", ")", "poll", "(", "hosts", "chan", "*", "mdns", ".", "ServiceEntry", ")", "{", "params", ":=", "mdns", ".", "QueryParam", "{", "Service", ":", "mdnsName", "(", "m", ".", "discover", ")", ",", "Interface", ":", "m", ".", "iface", ",", "Entries", ":", "hosts", ",", "}", "\n", "if", "err", ":=", "mdns", ".", "Query", "(", "&", "params", ")", ";", "err", "!=", "nil", "{", "m", ".", "logger", ".", "Printf", "(", "\"[ERR] agent.mdns: Failed to poll for new hosts: %v\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// poll is invoked periodically to check for new hosts
[ "poll", "is", "invoked", "periodically", "to", "check", "for", "new", "hosts" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/mdns.go#L121-L130
train
hashicorp/serf
coordinate/config.go
DefaultConfig
func DefaultConfig() *Config { return &Config{ Dimensionality: 8, VivaldiErrorMax: 1.5, VivaldiCE: 0.25, VivaldiCC: 0.25, AdjustmentWindowSize: 20, HeightMin: 10.0e-6, LatencyFilterSize: 3, GravityRho: 150.0, } }
go
func DefaultConfig() *Config { return &Config{ Dimensionality: 8, VivaldiErrorMax: 1.5, VivaldiCE: 0.25, VivaldiCC: 0.25, AdjustmentWindowSize: 20, HeightMin: 10.0e-6, LatencyFilterSize: 3, GravityRho: 150.0, } }
[ "func", "DefaultConfig", "(", ")", "*", "Config", "{", "return", "&", "Config", "{", "Dimensionality", ":", "8", ",", "VivaldiErrorMax", ":", "1.5", ",", "VivaldiCE", ":", "0.25", ",", "VivaldiCC", ":", "0.25", ",", "AdjustmentWindowSize", ":", "20", ",", "HeightMin", ":", "10.0e-6", ",", "LatencyFilterSize", ":", "3", ",", "GravityRho", ":", "150.0", ",", "}", "\n", "}" ]
// DefaultConfig returns a Config that has some default values suitable for // basic testing of the algorithm, but not tuned to any particular type of cluster.
[ "DefaultConfig", "returns", "a", "Config", "that", "has", "some", "default", "values", "suitable", "for", "basic", "testing", "of", "the", "algorithm", "but", "not", "tuned", "to", "any", "particular", "type", "of", "cluster", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/coordinate/config.go#L59-L70
train
hashicorp/serf
serf/lamport.go
Witness
func (l *LamportClock) Witness(v LamportTime) { WITNESS: // If the other value is old, we do not need to do anything cur := atomic.LoadUint64(&l.counter) other := uint64(v) if other < cur { return } // Ensure that our local clock is at least one ahead. if !atomic.CompareAndSwapUint64(&l.counter, cur, other+1) { // The CAS failed, so we just retry. Eventually our CAS should // succeed or a future witness will pass us by and our witness // will end. goto WITNESS } }
go
func (l *LamportClock) Witness(v LamportTime) { WITNESS: // If the other value is old, we do not need to do anything cur := atomic.LoadUint64(&l.counter) other := uint64(v) if other < cur { return } // Ensure that our local clock is at least one ahead. if !atomic.CompareAndSwapUint64(&l.counter, cur, other+1) { // The CAS failed, so we just retry. Eventually our CAS should // succeed or a future witness will pass us by and our witness // will end. goto WITNESS } }
[ "func", "(", "l", "*", "LamportClock", ")", "Witness", "(", "v", "LamportTime", ")", "{", "WITNESS", ":", "cur", ":=", "atomic", ".", "LoadUint64", "(", "&", "l", ".", "counter", ")", "\n", "other", ":=", "uint64", "(", "v", ")", "\n", "if", "other", "<", "cur", "{", "return", "\n", "}", "\n", "if", "!", "atomic", ".", "CompareAndSwapUint64", "(", "&", "l", ".", "counter", ",", "cur", ",", "other", "+", "1", ")", "{", "goto", "WITNESS", "\n", "}", "\n", "}" ]
// Witness is called to update our local clock if necessary after // witnessing a clock value received from another process
[ "Witness", "is", "called", "to", "update", "our", "local", "clock", "if", "necessary", "after", "witnessing", "a", "clock", "value", "received", "from", "another", "process" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/serf/lamport.go#L29-L45
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Create
func Create(agentConf *Config, conf *serf.Config, logOutput io.Writer) (*Agent, error) { // Ensure we have a log sink if logOutput == nil { logOutput = os.Stderr } // Setup the underlying loggers conf.MemberlistConfig.LogOutput = logOutput conf.MemberlistConfig.EnableCompression = agentConf.EnableCompression conf.LogOutput = logOutput // Create a channel to listen for events from Serf eventCh := make(chan serf.Event, 64) conf.EventCh = eventCh // Setup the agent agent := &Agent{ conf: conf, agentConf: agentConf, eventCh: eventCh, eventHandlers: make(map[EventHandler]struct{}), logger: log.New(logOutput, "", log.LstdFlags), shutdownCh: make(chan struct{}), } // Restore agent tags from a tags file if agentConf.TagsFile != "" { if err := agent.loadTagsFile(agentConf.TagsFile); err != nil { return nil, err } } // Load in a keyring file if provided if agentConf.KeyringFile != "" { if err := agent.loadKeyringFile(agentConf.KeyringFile); err != nil { return nil, err } } return agent, nil }
go
func Create(agentConf *Config, conf *serf.Config, logOutput io.Writer) (*Agent, error) { // Ensure we have a log sink if logOutput == nil { logOutput = os.Stderr } // Setup the underlying loggers conf.MemberlistConfig.LogOutput = logOutput conf.MemberlistConfig.EnableCompression = agentConf.EnableCompression conf.LogOutput = logOutput // Create a channel to listen for events from Serf eventCh := make(chan serf.Event, 64) conf.EventCh = eventCh // Setup the agent agent := &Agent{ conf: conf, agentConf: agentConf, eventCh: eventCh, eventHandlers: make(map[EventHandler]struct{}), logger: log.New(logOutput, "", log.LstdFlags), shutdownCh: make(chan struct{}), } // Restore agent tags from a tags file if agentConf.TagsFile != "" { if err := agent.loadTagsFile(agentConf.TagsFile); err != nil { return nil, err } } // Load in a keyring file if provided if agentConf.KeyringFile != "" { if err := agent.loadKeyringFile(agentConf.KeyringFile); err != nil { return nil, err } } return agent, nil }
[ "func", "Create", "(", "agentConf", "*", "Config", ",", "conf", "*", "serf", ".", "Config", ",", "logOutput", "io", ".", "Writer", ")", "(", "*", "Agent", ",", "error", ")", "{", "if", "logOutput", "==", "nil", "{", "logOutput", "=", "os", ".", "Stderr", "\n", "}", "\n", "conf", ".", "MemberlistConfig", ".", "LogOutput", "=", "logOutput", "\n", "conf", ".", "MemberlistConfig", ".", "EnableCompression", "=", "agentConf", ".", "EnableCompression", "\n", "conf", ".", "LogOutput", "=", "logOutput", "\n", "eventCh", ":=", "make", "(", "chan", "serf", ".", "Event", ",", "64", ")", "\n", "conf", ".", "EventCh", "=", "eventCh", "\n", "agent", ":=", "&", "Agent", "{", "conf", ":", "conf", ",", "agentConf", ":", "agentConf", ",", "eventCh", ":", "eventCh", ",", "eventHandlers", ":", "make", "(", "map", "[", "EventHandler", "]", "struct", "{", "}", ")", ",", "logger", ":", "log", ".", "New", "(", "logOutput", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", ",", "shutdownCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "if", "agentConf", ".", "TagsFile", "!=", "\"\"", "{", "if", "err", ":=", "agent", ".", "loadTagsFile", "(", "agentConf", ".", "TagsFile", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "agentConf", ".", "KeyringFile", "!=", "\"\"", "{", "if", "err", ":=", "agent", ".", "loadKeyringFile", "(", "agentConf", ".", "KeyringFile", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "agent", ",", "nil", "\n", "}" ]
// Start creates a new agent, potentially returning an error
[ "Start", "creates", "a", "new", "agent", "potentially", "returning", "an", "error" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L49-L89
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Start
func (a *Agent) Start() error { a.logger.Printf("[INFO] agent: Serf agent starting") // Create serf first serf, err := serf.Create(a.conf) if err != nil { return fmt.Errorf("Error creating Serf: %s", err) } a.serf = serf // Start event loop go a.eventLoop() return nil }
go
func (a *Agent) Start() error { a.logger.Printf("[INFO] agent: Serf agent starting") // Create serf first serf, err := serf.Create(a.conf) if err != nil { return fmt.Errorf("Error creating Serf: %s", err) } a.serf = serf // Start event loop go a.eventLoop() return nil }
[ "func", "(", "a", "*", "Agent", ")", "Start", "(", ")", "error", "{", "a", ".", "logger", ".", "Printf", "(", "\"[INFO] agent: Serf agent starting\"", ")", "\n", "serf", ",", "err", ":=", "serf", ".", "Create", "(", "a", ".", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Error creating Serf: %s\"", ",", "err", ")", "\n", "}", "\n", "a", ".", "serf", "=", "serf", "\n", "go", "a", ".", "eventLoop", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start is used to initiate the event listeners. It is separate from // create so that there isn't a race condition between creating the // agent and registering handlers
[ "Start", "is", "used", "to", "initiate", "the", "event", "listeners", ".", "It", "is", "separate", "from", "create", "so", "that", "there", "isn", "t", "a", "race", "condition", "between", "creating", "the", "agent", "and", "registering", "handlers" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L94-L107
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Leave
func (a *Agent) Leave() error { if a.serf == nil { return nil } a.logger.Println("[INFO] agent: requesting graceful leave from Serf") return a.serf.Leave() }
go
func (a *Agent) Leave() error { if a.serf == nil { return nil } a.logger.Println("[INFO] agent: requesting graceful leave from Serf") return a.serf.Leave() }
[ "func", "(", "a", "*", "Agent", ")", "Leave", "(", ")", "error", "{", "if", "a", ".", "serf", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "a", ".", "logger", ".", "Println", "(", "\"[INFO] agent: requesting graceful leave from Serf\"", ")", "\n", "return", "a", ".", "serf", ".", "Leave", "(", ")", "\n", "}" ]
// Leave prepares for a graceful shutdown of the agent and its processes
[ "Leave", "prepares", "for", "a", "graceful", "shutdown", "of", "the", "agent", "and", "its", "processes" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L110-L117
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Shutdown
func (a *Agent) Shutdown() error { a.shutdownLock.Lock() defer a.shutdownLock.Unlock() if a.shutdown { return nil } if a.serf == nil { goto EXIT } a.logger.Println("[INFO] agent: requesting serf shutdown") if err := a.serf.Shutdown(); err != nil { return err } EXIT: a.logger.Println("[INFO] agent: shutdown complete") a.shutdown = true close(a.shutdownCh) return nil }
go
func (a *Agent) Shutdown() error { a.shutdownLock.Lock() defer a.shutdownLock.Unlock() if a.shutdown { return nil } if a.serf == nil { goto EXIT } a.logger.Println("[INFO] agent: requesting serf shutdown") if err := a.serf.Shutdown(); err != nil { return err } EXIT: a.logger.Println("[INFO] agent: shutdown complete") a.shutdown = true close(a.shutdownCh) return nil }
[ "func", "(", "a", "*", "Agent", ")", "Shutdown", "(", ")", "error", "{", "a", ".", "shutdownLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "shutdownLock", ".", "Unlock", "(", ")", "\n", "if", "a", ".", "shutdown", "{", "return", "nil", "\n", "}", "\n", "if", "a", ".", "serf", "==", "nil", "{", "goto", "EXIT", "\n", "}", "\n", "a", ".", "logger", ".", "Println", "(", "\"[INFO] agent: requesting serf shutdown\"", ")", "\n", "if", "err", ":=", "a", ".", "serf", ".", "Shutdown", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "EXIT", ":", "a", ".", "logger", ".", "Println", "(", "\"[INFO] agent: shutdown complete\"", ")", "\n", "a", ".", "shutdown", "=", "true", "\n", "close", "(", "a", ".", "shutdownCh", ")", "\n", "return", "nil", "\n", "}" ]
// Shutdown closes this agent and all of its processes. Should be preceded // by a Leave for a graceful shutdown.
[ "Shutdown", "closes", "this", "agent", "and", "all", "of", "its", "processes", ".", "Should", "be", "preceded", "by", "a", "Leave", "for", "a", "graceful", "shutdown", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L121-L143
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Join
func (a *Agent) Join(addrs []string, replay bool) (n int, err error) { a.logger.Printf("[INFO] agent: joining: %v replay: %v", addrs, replay) ignoreOld := !replay n, err = a.serf.Join(addrs, ignoreOld) if n > 0 { a.logger.Printf("[INFO] agent: joined: %d nodes", n) } if err != nil { a.logger.Printf("[WARN] agent: error joining: %v", err) } return }
go
func (a *Agent) Join(addrs []string, replay bool) (n int, err error) { a.logger.Printf("[INFO] agent: joining: %v replay: %v", addrs, replay) ignoreOld := !replay n, err = a.serf.Join(addrs, ignoreOld) if n > 0 { a.logger.Printf("[INFO] agent: joined: %d nodes", n) } if err != nil { a.logger.Printf("[WARN] agent: error joining: %v", err) } return }
[ "func", "(", "a", "*", "Agent", ")", "Join", "(", "addrs", "[", "]", "string", ",", "replay", "bool", ")", "(", "n", "int", ",", "err", "error", ")", "{", "a", ".", "logger", ".", "Printf", "(", "\"[INFO] agent: joining: %v replay: %v\"", ",", "addrs", ",", "replay", ")", "\n", "ignoreOld", ":=", "!", "replay", "\n", "n", ",", "err", "=", "a", ".", "serf", ".", "Join", "(", "addrs", ",", "ignoreOld", ")", "\n", "if", "n", ">", "0", "{", "a", ".", "logger", ".", "Printf", "(", "\"[INFO] agent: joined: %d nodes\"", ",", "n", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "a", ".", "logger", ".", "Printf", "(", "\"[WARN] agent: error joining: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Join asks the Serf instance to join. See the Serf.Join function.
[ "Join", "asks", "the", "Serf", "instance", "to", "join", ".", "See", "the", "Serf", ".", "Join", "function", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L162-L173
train
hashicorp/serf
cmd/serf/command/agent/agent.go
UserEvent
func (a *Agent) UserEvent(name string, payload []byte, coalesce bool) error { a.logger.Printf("[DEBUG] agent: Requesting user event send: %s. Coalesced: %#v. Payload: %#v", name, coalesce, string(payload)) err := a.serf.UserEvent(name, payload, coalesce) if err != nil { a.logger.Printf("[WARN] agent: failed to send user event: %v", err) } return err }
go
func (a *Agent) UserEvent(name string, payload []byte, coalesce bool) error { a.logger.Printf("[DEBUG] agent: Requesting user event send: %s. Coalesced: %#v. Payload: %#v", name, coalesce, string(payload)) err := a.serf.UserEvent(name, payload, coalesce) if err != nil { a.logger.Printf("[WARN] agent: failed to send user event: %v", err) } return err }
[ "func", "(", "a", "*", "Agent", ")", "UserEvent", "(", "name", "string", ",", "payload", "[", "]", "byte", ",", "coalesce", "bool", ")", "error", "{", "a", ".", "logger", ".", "Printf", "(", "\"[DEBUG] agent: Requesting user event send: %s. Coalesced: %#v. Payload: %#v\"", ",", "name", ",", "coalesce", ",", "string", "(", "payload", ")", ")", "\n", "err", ":=", "a", ".", "serf", ".", "UserEvent", "(", "name", ",", "payload", ",", "coalesce", ")", "\n", "if", "err", "!=", "nil", "{", "a", ".", "logger", ".", "Printf", "(", "\"[WARN] agent: failed to send user event: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// UserEvent sends a UserEvent on Serf, see Serf.UserEvent.
[ "UserEvent", "sends", "a", "UserEvent", "on", "Serf", "see", "Serf", ".", "UserEvent", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L186-L194
train
hashicorp/serf
cmd/serf/command/agent/agent.go
Query
func (a *Agent) Query(name string, payload []byte, params *serf.QueryParam) (*serf.QueryResponse, error) { // Prevent the use of the internal prefix if strings.HasPrefix(name, serf.InternalQueryPrefix) { // Allow the special "ping" query if name != serf.InternalQueryPrefix+"ping" || payload != nil { return nil, fmt.Errorf("Queries cannot contain the '%s' prefix", serf.InternalQueryPrefix) } } a.logger.Printf("[DEBUG] agent: Requesting query send: %s. Payload: %#v", name, string(payload)) resp, err := a.serf.Query(name, payload, params) if err != nil { a.logger.Printf("[WARN] agent: failed to start user query: %v", err) } return resp, err }
go
func (a *Agent) Query(name string, payload []byte, params *serf.QueryParam) (*serf.QueryResponse, error) { // Prevent the use of the internal prefix if strings.HasPrefix(name, serf.InternalQueryPrefix) { // Allow the special "ping" query if name != serf.InternalQueryPrefix+"ping" || payload != nil { return nil, fmt.Errorf("Queries cannot contain the '%s' prefix", serf.InternalQueryPrefix) } } a.logger.Printf("[DEBUG] agent: Requesting query send: %s. Payload: %#v", name, string(payload)) resp, err := a.serf.Query(name, payload, params) if err != nil { a.logger.Printf("[WARN] agent: failed to start user query: %v", err) } return resp, err }
[ "func", "(", "a", "*", "Agent", ")", "Query", "(", "name", "string", ",", "payload", "[", "]", "byte", ",", "params", "*", "serf", ".", "QueryParam", ")", "(", "*", "serf", ".", "QueryResponse", ",", "error", ")", "{", "if", "strings", ".", "HasPrefix", "(", "name", ",", "serf", ".", "InternalQueryPrefix", ")", "{", "if", "name", "!=", "serf", ".", "InternalQueryPrefix", "+", "\"ping\"", "||", "payload", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Queries cannot contain the '%s' prefix\"", ",", "serf", ".", "InternalQueryPrefix", ")", "\n", "}", "\n", "}", "\n", "a", ".", "logger", ".", "Printf", "(", "\"[DEBUG] agent: Requesting query send: %s. Payload: %#v\"", ",", "name", ",", "string", "(", "payload", ")", ")", "\n", "resp", ",", "err", ":=", "a", ".", "serf", ".", "Query", "(", "name", ",", "payload", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "a", ".", "logger", ".", "Printf", "(", "\"[WARN] agent: failed to start user query: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Query sends a Query on Serf, see Serf.Query.
[ "Query", "sends", "a", "Query", "on", "Serf", "see", "Serf", ".", "Query", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L197-L212
train
hashicorp/serf
cmd/serf/command/agent/agent.go
RegisterEventHandler
func (a *Agent) RegisterEventHandler(eh EventHandler) { a.eventHandlersLock.Lock() defer a.eventHandlersLock.Unlock() a.eventHandlers[eh] = struct{}{} a.eventHandlerList = nil for eh := range a.eventHandlers { a.eventHandlerList = append(a.eventHandlerList, eh) } }
go
func (a *Agent) RegisterEventHandler(eh EventHandler) { a.eventHandlersLock.Lock() defer a.eventHandlersLock.Unlock() a.eventHandlers[eh] = struct{}{} a.eventHandlerList = nil for eh := range a.eventHandlers { a.eventHandlerList = append(a.eventHandlerList, eh) } }
[ "func", "(", "a", "*", "Agent", ")", "RegisterEventHandler", "(", "eh", "EventHandler", ")", "{", "a", ".", "eventHandlersLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "eventHandlersLock", ".", "Unlock", "(", ")", "\n", "a", ".", "eventHandlers", "[", "eh", "]", "=", "struct", "{", "}", "{", "}", "\n", "a", ".", "eventHandlerList", "=", "nil", "\n", "for", "eh", ":=", "range", "a", ".", "eventHandlers", "{", "a", ".", "eventHandlerList", "=", "append", "(", "a", ".", "eventHandlerList", ",", "eh", ")", "\n", "}", "\n", "}" ]
// RegisterEventHandler adds an event handler to receive event notifications
[ "RegisterEventHandler", "adds", "an", "event", "handler", "to", "receive", "event", "notifications" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L215-L224
train
hashicorp/serf
cmd/serf/command/agent/agent.go
DeregisterEventHandler
func (a *Agent) DeregisterEventHandler(eh EventHandler) { a.eventHandlersLock.Lock() defer a.eventHandlersLock.Unlock() delete(a.eventHandlers, eh) a.eventHandlerList = nil for eh := range a.eventHandlers { a.eventHandlerList = append(a.eventHandlerList, eh) } }
go
func (a *Agent) DeregisterEventHandler(eh EventHandler) { a.eventHandlersLock.Lock() defer a.eventHandlersLock.Unlock() delete(a.eventHandlers, eh) a.eventHandlerList = nil for eh := range a.eventHandlers { a.eventHandlerList = append(a.eventHandlerList, eh) } }
[ "func", "(", "a", "*", "Agent", ")", "DeregisterEventHandler", "(", "eh", "EventHandler", ")", "{", "a", ".", "eventHandlersLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "eventHandlersLock", ".", "Unlock", "(", ")", "\n", "delete", "(", "a", ".", "eventHandlers", ",", "eh", ")", "\n", "a", ".", "eventHandlerList", "=", "nil", "\n", "for", "eh", ":=", "range", "a", ".", "eventHandlers", "{", "a", ".", "eventHandlerList", "=", "append", "(", "a", ".", "eventHandlerList", ",", "eh", ")", "\n", "}", "\n", "}" ]
// DeregisterEventHandler removes an EventHandler and prevents more invocations
[ "DeregisterEventHandler", "removes", "an", "EventHandler", "and", "prevents", "more", "invocations" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L227-L236
train
hashicorp/serf
cmd/serf/command/agent/agent.go
eventLoop
func (a *Agent) eventLoop() { serfShutdownCh := a.serf.ShutdownCh() for { select { case e := <-a.eventCh: a.logger.Printf("[INFO] agent: Received event: %s", e.String()) a.eventHandlersLock.Lock() handlers := a.eventHandlerList a.eventHandlersLock.Unlock() for _, eh := range handlers { eh.HandleEvent(e) } case <-serfShutdownCh: a.logger.Printf("[WARN] agent: Serf shutdown detected, quitting") a.Shutdown() return case <-a.shutdownCh: return } } }
go
func (a *Agent) eventLoop() { serfShutdownCh := a.serf.ShutdownCh() for { select { case e := <-a.eventCh: a.logger.Printf("[INFO] agent: Received event: %s", e.String()) a.eventHandlersLock.Lock() handlers := a.eventHandlerList a.eventHandlersLock.Unlock() for _, eh := range handlers { eh.HandleEvent(e) } case <-serfShutdownCh: a.logger.Printf("[WARN] agent: Serf shutdown detected, quitting") a.Shutdown() return case <-a.shutdownCh: return } } }
[ "func", "(", "a", "*", "Agent", ")", "eventLoop", "(", ")", "{", "serfShutdownCh", ":=", "a", ".", "serf", ".", "ShutdownCh", "(", ")", "\n", "for", "{", "select", "{", "case", "e", ":=", "<-", "a", ".", "eventCh", ":", "a", ".", "logger", ".", "Printf", "(", "\"[INFO] agent: Received event: %s\"", ",", "e", ".", "String", "(", ")", ")", "\n", "a", ".", "eventHandlersLock", ".", "Lock", "(", ")", "\n", "handlers", ":=", "a", ".", "eventHandlerList", "\n", "a", ".", "eventHandlersLock", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "eh", ":=", "range", "handlers", "{", "eh", ".", "HandleEvent", "(", "e", ")", "\n", "}", "\n", "case", "<-", "serfShutdownCh", ":", "a", ".", "logger", ".", "Printf", "(", "\"[WARN] agent: Serf shutdown detected, quitting\"", ")", "\n", "a", ".", "Shutdown", "(", ")", "\n", "return", "\n", "case", "<-", "a", ".", "shutdownCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// eventLoop listens to events from Serf and fans out to event handlers
[ "eventLoop", "listens", "to", "events", "from", "Serf", "and", "fans", "out", "to", "event", "handlers" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L239-L261
train
hashicorp/serf
cmd/serf/command/agent/agent.go
InstallKey
func (a *Agent) InstallKey(key string) (*serf.KeyResponse, error) { a.logger.Print("[INFO] agent: Initiating key installation") manager := a.serf.KeyManager() return manager.InstallKey(key) }
go
func (a *Agent) InstallKey(key string) (*serf.KeyResponse, error) { a.logger.Print("[INFO] agent: Initiating key installation") manager := a.serf.KeyManager() return manager.InstallKey(key) }
[ "func", "(", "a", "*", "Agent", ")", "InstallKey", "(", "key", "string", ")", "(", "*", "serf", ".", "KeyResponse", ",", "error", ")", "{", "a", ".", "logger", ".", "Print", "(", "\"[INFO] agent: Initiating key installation\"", ")", "\n", "manager", ":=", "a", ".", "serf", ".", "KeyManager", "(", ")", "\n", "return", "manager", ".", "InstallKey", "(", "key", ")", "\n", "}" ]
// InstallKey initiates a query to install a new key on all members
[ "InstallKey", "initiates", "a", "query", "to", "install", "a", "new", "key", "on", "all", "members" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L264-L268
train
hashicorp/serf
cmd/serf/command/agent/agent.go
ListKeys
func (a *Agent) ListKeys() (*serf.KeyResponse, error) { a.logger.Print("[INFO] agent: Initiating key listing") manager := a.serf.KeyManager() return manager.ListKeys() }
go
func (a *Agent) ListKeys() (*serf.KeyResponse, error) { a.logger.Print("[INFO] agent: Initiating key listing") manager := a.serf.KeyManager() return manager.ListKeys() }
[ "func", "(", "a", "*", "Agent", ")", "ListKeys", "(", ")", "(", "*", "serf", ".", "KeyResponse", ",", "error", ")", "{", "a", ".", "logger", ".", "Print", "(", "\"[INFO] agent: Initiating key listing\"", ")", "\n", "manager", ":=", "a", ".", "serf", ".", "KeyManager", "(", ")", "\n", "return", "manager", ".", "ListKeys", "(", ")", "\n", "}" ]
// ListKeys sends a query to all members to return a list of their keys
[ "ListKeys", "sends", "a", "query", "to", "all", "members", "to", "return", "a", "list", "of", "their", "keys" ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L285-L289
train
hashicorp/serf
cmd/serf/command/agent/agent.go
SetTags
func (a *Agent) SetTags(tags map[string]string) error { // Update the tags file if we have one if a.agentConf.TagsFile != "" { if err := a.writeTagsFile(tags); err != nil { a.logger.Printf("[ERR] agent: %s", err) return err } } // Set the tags in Serf, start gossiping out return a.serf.SetTags(tags) }
go
func (a *Agent) SetTags(tags map[string]string) error { // Update the tags file if we have one if a.agentConf.TagsFile != "" { if err := a.writeTagsFile(tags); err != nil { a.logger.Printf("[ERR] agent: %s", err) return err } } // Set the tags in Serf, start gossiping out return a.serf.SetTags(tags) }
[ "func", "(", "a", "*", "Agent", ")", "SetTags", "(", "tags", "map", "[", "string", "]", "string", ")", "error", "{", "if", "a", ".", "agentConf", ".", "TagsFile", "!=", "\"\"", "{", "if", "err", ":=", "a", ".", "writeTagsFile", "(", "tags", ")", ";", "err", "!=", "nil", "{", "a", ".", "logger", ".", "Printf", "(", "\"[ERR] agent: %s\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "a", ".", "serf", ".", "SetTags", "(", "tags", ")", "\n", "}" ]
// SetTags is used to update the tags. The agent will make sure to // persist tags if necessary before gossiping to the cluster.
[ "SetTags", "is", "used", "to", "update", "the", "tags", ".", "The", "agent", "will", "make", "sure", "to", "persist", "tags", "if", "necessary", "before", "gossiping", "to", "the", "cluster", "." ]
15cfd05de3dffb3664aa37b06e91f970b825e380
https://github.com/hashicorp/serf/blob/15cfd05de3dffb3664aa37b06e91f970b825e380/cmd/serf/command/agent/agent.go#L293-L304
train