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
deis/deis
client/pkg/git/git.go
RemoteURL
func RemoteURL(host, appID string) string { // Strip off any trailing :port number after the host name. host = strings.Split(host, ":")[0] return fmt.Sprintf("ssh://git@%s:2222/%s.git", host, appID) }
go
func RemoteURL(host, appID string) string { // Strip off any trailing :port number after the host name. host = strings.Split(host, ":")[0] return fmt.Sprintf("ssh://git@%s:2222/%s.git", host, appID) }
[ "func", "RemoteURL", "(", "host", ",", "appID", "string", ")", "string", "{", "// Strip off any trailing :port number after the host name.", "host", "=", "strings", ".", "Split", "(", "host", ",", "\"", "\"", ")", "[", "0", "]", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "appID", ")", "\n", "}" ]
// RemoteURL returns the git URL of app.
[ "RemoteURL", "returns", "the", "git", "URL", "of", "app", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/client/pkg/git/git.go#L111-L115
train
deis/deis
client/cmd/keys.go
KeysList
func KeysList(results int) error { c, err := client.New() if err != nil { return err } if results == defaultLimit { results = c.ResponseLimit } keys, count, err := keys.List(c, results) if err != nil { return err } fmt.Printf("=== %s Keys%s", c.Username, limitCount(len(keys), count)) sort.Sort(keys) for _, key := range keys { fmt.Printf("%s %s...%s\n", key.ID, key.Public[:16], key.Public[len(key.Public)-10:]) } return nil }
go
func KeysList(results int) error { c, err := client.New() if err != nil { return err } if results == defaultLimit { results = c.ResponseLimit } keys, count, err := keys.List(c, results) if err != nil { return err } fmt.Printf("=== %s Keys%s", c.Username, limitCount(len(keys), count)) sort.Sort(keys) for _, key := range keys { fmt.Printf("%s %s...%s\n", key.ID, key.Public[:16], key.Public[len(key.Public)-10:]) } return nil }
[ "func", "KeysList", "(", "results", "int", ")", "error", "{", "c", ",", "err", ":=", "client", ".", "New", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "results", "==", "defaultLimit", "{", "results", "=", "c", ".", "ResponseLimit", "\n", "}", "\n\n", "keys", ",", "count", ",", "err", ":=", "keys", ".", "List", "(", "c", ",", "results", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "c", ".", "Username", ",", "limitCount", "(", "len", "(", "keys", ")", ",", "count", ")", ")", "\n\n", "sort", ".", "Sort", "(", "keys", ")", "\n\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "key", ".", "ID", ",", "key", ".", "Public", "[", ":", "16", "]", ",", "key", ".", "Public", "[", "len", "(", "key", ".", "Public", ")", "-", "10", ":", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// KeysList lists a user's keys.
[ "KeysList", "lists", "a", "user", "s", "keys", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/client/cmd/keys.go#L18-L43
train
deis/deis
client/cmd/keys.go
KeyRemove
func KeyRemove(keyID string) error { c, err := client.New() if err != nil { return err } fmt.Printf("Removing %s SSH Key...", keyID) if err = keys.Delete(c, keyID); err != nil { fmt.Println() return err } fmt.Println(" done") return nil }
go
func KeyRemove(keyID string) error { c, err := client.New() if err != nil { return err } fmt.Printf("Removing %s SSH Key...", keyID) if err = keys.Delete(c, keyID); err != nil { fmt.Println() return err } fmt.Println(" done") return nil }
[ "func", "KeyRemove", "(", "keyID", "string", ")", "error", "{", "c", ",", "err", ":=", "client", ".", "New", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "keyID", ")", "\n\n", "if", "err", "=", "keys", ".", "Delete", "(", "c", ",", "keyID", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// KeyRemove removes keys.
[ "KeyRemove", "removes", "keys", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/client/cmd/keys.go#L46-L62
train
deis/deis
client/cmd/keys.go
KeyAdd
func KeyAdd(keyLocation string) error { c, err := client.New() if err != nil { return err } var key api.KeyCreateRequest if keyLocation == "" { key, err = chooseKey() } else { key, err = getKey(keyLocation) } if err != nil { return err } fmt.Printf("Uploading %s to deis...", path.Base(key.Name)) if _, err = keys.New(c, key.ID, key.Public); err != nil { fmt.Println() return err } fmt.Println(" done") return nil }
go
func KeyAdd(keyLocation string) error { c, err := client.New() if err != nil { return err } var key api.KeyCreateRequest if keyLocation == "" { key, err = chooseKey() } else { key, err = getKey(keyLocation) } if err != nil { return err } fmt.Printf("Uploading %s to deis...", path.Base(key.Name)) if _, err = keys.New(c, key.ID, key.Public); err != nil { fmt.Println() return err } fmt.Println(" done") return nil }
[ "func", "KeyAdd", "(", "keyLocation", "string", ")", "error", "{", "c", ",", "err", ":=", "client", ".", "New", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "key", "api", ".", "KeyCreateRequest", "\n\n", "if", "keyLocation", "==", "\"", "\"", "{", "key", ",", "err", "=", "chooseKey", "(", ")", "\n", "}", "else", "{", "key", ",", "err", "=", "getKey", "(", "keyLocation", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "path", ".", "Base", "(", "key", ".", "Name", ")", ")", "\n\n", "if", "_", ",", "err", "=", "keys", ".", "New", "(", "c", ",", "key", ".", "ID", ",", "key", ".", "Public", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// KeyAdd adds keys.
[ "KeyAdd", "adds", "keys", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/client/cmd/keys.go#L65-L93
train
deis/deis
client/controller/models/keys/keys.go
New
func New(c *client.Client, id string, pubKey string) (api.Key, error) { req := api.KeyCreateRequest{ID: id, Public: pubKey} body, err := json.Marshal(req) resBody, err := c.BasicRequest("POST", "/v1/keys/", body) if err != nil { return api.Key{}, err } key := api.Key{} if err = json.Unmarshal([]byte(resBody), &key); err != nil { return api.Key{}, err } return key, nil }
go
func New(c *client.Client, id string, pubKey string) (api.Key, error) { req := api.KeyCreateRequest{ID: id, Public: pubKey} body, err := json.Marshal(req) resBody, err := c.BasicRequest("POST", "/v1/keys/", body) if err != nil { return api.Key{}, err } key := api.Key{} if err = json.Unmarshal([]byte(resBody), &key); err != nil { return api.Key{}, err } return key, nil }
[ "func", "New", "(", "c", "*", "client", ".", "Client", ",", "id", "string", ",", "pubKey", "string", ")", "(", "api", ".", "Key", ",", "error", ")", "{", "req", ":=", "api", ".", "KeyCreateRequest", "{", "ID", ":", "id", ",", "Public", ":", "pubKey", "}", "\n", "body", ",", "err", ":=", "json", ".", "Marshal", "(", "req", ")", "\n\n", "resBody", ",", "err", ":=", "c", ".", "BasicRequest", "(", "\"", "\"", ",", "\"", "\"", ",", "body", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "api", ".", "Key", "{", "}", ",", "err", "\n", "}", "\n\n", "key", ":=", "api", ".", "Key", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "resBody", ")", ",", "&", "key", ")", ";", "err", "!=", "nil", "{", "return", "api", ".", "Key", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "key", ",", "nil", "\n", "}" ]
// New creates a new key.
[ "New", "creates", "a", "new", "key", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/client/controller/models/keys/keys.go#L28-L44
train
deis/deis
pkg/time/time.go
MarshalJSON
func (t *Time) MarshalJSON() ([]byte, error) { return []byte(t.Time.Format(`"` + DeisDatetimeFormat + `"`)), nil }
go
func (t *Time) MarshalJSON() ([]byte, error) { return []byte(t.Time.Format(`"` + DeisDatetimeFormat + `"`)), nil }
[ "func", "(", "t", "*", "Time", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "t", ".", "Time", ".", "Format", "(", "`\"`", "+", "DeisDatetimeFormat", "+", "`\"`", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON implements the json.Marshaler interface. // The time is a quoted string in Deis' datetime format.
[ "MarshalJSON", "implements", "the", "json", ".", "Marshaler", "interface", ".", "The", "time", "is", "a", "quoted", "string", "in", "Deis", "datetime", "format", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/pkg/time/time.go#L19-L21
train
deis/deis
pkg/prettyprint/colorizer.go
DeisIfy
func DeisIfy(msg string) string { var t = struct { Msg string C map[string]string }{ Msg: msg, C: Colors, } tpl := "{{.C.Deis1}}\n{{.C.Deis2}} {{.Msg}}\n{{.C.Deis3}}\n" var buf bytes.Buffer template.Must(template.New("deis").Parse(tpl)).Execute(&buf, t) return buf.String() }
go
func DeisIfy(msg string) string { var t = struct { Msg string C map[string]string }{ Msg: msg, C: Colors, } tpl := "{{.C.Deis1}}\n{{.C.Deis2}} {{.Msg}}\n{{.C.Deis3}}\n" var buf bytes.Buffer template.Must(template.New("deis").Parse(tpl)).Execute(&buf, t) return buf.String() }
[ "func", "DeisIfy", "(", "msg", "string", ")", "string", "{", "var", "t", "=", "struct", "{", "Msg", "string", "\n", "C", "map", "[", "string", "]", "string", "\n", "}", "{", "Msg", ":", "msg", ",", "C", ":", "Colors", ",", "}", "\n", "tpl", ":=", "\"", "\\n", "\\n", "\\n", "\"", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "tpl", ")", ")", ".", "Execute", "(", "&", "buf", ",", "t", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// DeisIfy returns a pretty-printed deis logo along with the corresponding message
[ "DeisIfy", "returns", "a", "pretty", "-", "printed", "deis", "logo", "along", "with", "the", "corresponding", "message" ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/pkg/prettyprint/colorizer.go#L63-L75
train
deis/deis
pkg/prettyprint/colorizer.go
NoColor
func NoColor(msg string) string { empties := make(map[string]string, len(Colors)) for k := range Colors { empties[k] = "" } return colorize(msg, empties) }
go
func NoColor(msg string) string { empties := make(map[string]string, len(Colors)) for k := range Colors { empties[k] = "" } return colorize(msg, empties) }
[ "func", "NoColor", "(", "msg", "string", ")", "string", "{", "empties", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "Colors", ")", ")", "\n", "for", "k", ":=", "range", "Colors", "{", "empties", "[", "k", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "colorize", "(", "msg", ",", "empties", ")", "\n", "}" ]
// NoColor strips colors from the template. // // NoColor provides support for non-color ANSI terminals. It can be used // as an alternative to Colorize when it is detected that the terminal does // not support colors.
[ "NoColor", "strips", "colors", "from", "the", "template", ".", "NoColor", "provides", "support", "for", "non", "-", "color", "ANSI", "terminals", ".", "It", "can", "be", "used", "as", "an", "alternative", "to", "Colorize", "when", "it", "is", "detected", "that", "the", "terminal", "does", "not", "support", "colors", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/pkg/prettyprint/colorizer.go#L87-L93
train
deis/deis
pkg/prettyprint/colorizer.go
Overwritef
func Overwritef(msg string, args ...interface{}) string { return Overwrite(fmt.Sprintf(msg, args...)) }
go
func Overwritef(msg string, args ...interface{}) string { return Overwrite(fmt.Sprintf(msg, args...)) }
[ "func", "Overwritef", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "string", "{", "return", "Overwrite", "(", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", ")", "\n", "}" ]
// Overwritef formats a string and then returns an overwrite line. // // See `Overwrite` for details.
[ "Overwritef", "formats", "a", "string", "and", "then", "returns", "an", "overwrite", "line", ".", "See", "Overwrite", "for", "details", "." ]
1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410
https://github.com/deis/deis/blob/1d9e59fbdbfc9d7767f77c2e0097e335b0fcd410/pkg/prettyprint/colorizer.go#L162-L164
train
hashicorp/go-getter
get.go
Get
func Get(dst, src string, opts ...ClientOption) error { return (&Client{ Src: src, Dst: dst, Dir: true, Options: opts, }).Get() }
go
func Get(dst, src string, opts ...ClientOption) error { return (&Client{ Src: src, Dst: dst, Dir: true, Options: opts, }).Get() }
[ "func", "Get", "(", "dst", ",", "src", "string", ",", "opts", "...", "ClientOption", ")", "error", "{", "return", "(", "&", "Client", "{", "Src", ":", "src", ",", "Dst", ":", "dst", ",", "Dir", ":", "true", ",", "Options", ":", "opts", ",", "}", ")", ".", "Get", "(", ")", "\n", "}" ]
// Get downloads the directory specified by src into the folder specified by // dst. If dst already exists, Get will attempt to update it. // // src is a URL, whereas dst is always just a file path to a folder. This // folder doesn't need to exist. It will be created if it doesn't exist.
[ "Get", "downloads", "the", "directory", "specified", "by", "src", "into", "the", "folder", "specified", "by", "dst", ".", "If", "dst", "already", "exists", "Get", "will", "attempt", "to", "update", "it", ".", "src", "is", "a", "URL", "whereas", "dst", "is", "always", "just", "a", "file", "path", "to", "a", "folder", ".", "This", "folder", "doesn", "t", "need", "to", "exist", ".", "It", "will", "be", "created", "if", "it", "doesn", "t", "exist", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get.go#L83-L90
train
hashicorp/go-getter
get.go
GetAny
func GetAny(dst, src string, opts ...ClientOption) error { return (&Client{ Src: src, Dst: dst, Mode: ClientModeAny, Options: opts, }).Get() }
go
func GetAny(dst, src string, opts ...ClientOption) error { return (&Client{ Src: src, Dst: dst, Mode: ClientModeAny, Options: opts, }).Get() }
[ "func", "GetAny", "(", "dst", ",", "src", "string", ",", "opts", "...", "ClientOption", ")", "error", "{", "return", "(", "&", "Client", "{", "Src", ":", "src", ",", "Dst", ":", "dst", ",", "Mode", ":", "ClientModeAny", ",", "Options", ":", "opts", ",", "}", ")", ".", "Get", "(", ")", "\n", "}" ]
// GetAny downloads a URL into the given destination. Unlike Get or // GetFile, both directories and files are supported. // // dst must be a directory. If src is a file, it will be downloaded // into dst with the basename of the URL. If src is a directory or // archive, it will be unpacked directly into dst.
[ "GetAny", "downloads", "a", "URL", "into", "the", "given", "destination", ".", "Unlike", "Get", "or", "GetFile", "both", "directories", "and", "files", "are", "supported", ".", "dst", "must", "be", "a", "directory", ".", "If", "src", "is", "a", "file", "it", "will", "be", "downloaded", "into", "dst", "with", "the", "basename", "of", "the", "URL", ".", "If", "src", "is", "a", "directory", "or", "archive", "it", "will", "be", "unpacked", "directly", "into", "dst", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get.go#L98-L105
train
hashicorp/go-getter
get.go
getRunCommand
func getRunCommand(cmd *exec.Cmd) error { var buf bytes.Buffer cmd.Stdout = &buf cmd.Stderr = &buf err := cmd.Run() if err == nil { return nil } if exiterr, ok := err.(*exec.ExitError); ok { // The program has exited with an exit code != 0 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { return fmt.Errorf( "%s exited with %d: %s", cmd.Path, status.ExitStatus(), buf.String()) } } return fmt.Errorf("error running %s: %s", cmd.Path, buf.String()) }
go
func getRunCommand(cmd *exec.Cmd) error { var buf bytes.Buffer cmd.Stdout = &buf cmd.Stderr = &buf err := cmd.Run() if err == nil { return nil } if exiterr, ok := err.(*exec.ExitError); ok { // The program has exited with an exit code != 0 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { return fmt.Errorf( "%s exited with %d: %s", cmd.Path, status.ExitStatus(), buf.String()) } } return fmt.Errorf("error running %s: %s", cmd.Path, buf.String()) }
[ "func", "getRunCommand", "(", "cmd", "*", "exec", ".", "Cmd", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "cmd", ".", "Stdout", "=", "&", "buf", "\n", "cmd", ".", "Stderr", "=", "&", "buf", "\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "exiterr", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "// The program has exited with an exit code != 0", "if", "status", ",", "ok", ":=", "exiterr", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ".", "Path", ",", "status", ".", "ExitStatus", "(", ")", ",", "buf", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ".", "Path", ",", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// getRunCommand is a helper that will run a command and capture the output // in the case an error happens.
[ "getRunCommand", "is", "a", "helper", "that", "will", "run", "a", "command", "and", "capture", "the", "output", "in", "the", "case", "an", "error", "happens", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get.go#L120-L140
train
hashicorp/go-getter
client_option_progress.go
WithProgress
func WithProgress(pl ProgressTracker) func(*Client) error { return func(c *Client) error { c.ProgressListener = pl return nil } }
go
func WithProgress(pl ProgressTracker) func(*Client) error { return func(c *Client) error { c.ProgressListener = pl return nil } }
[ "func", "WithProgress", "(", "pl", "ProgressTracker", ")", "func", "(", "*", "Client", ")", "error", "{", "return", "func", "(", "c", "*", "Client", ")", "error", "{", "c", ".", "ProgressListener", "=", "pl", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithProgress allows for a user to track // the progress of a download. // For example by displaying a progress bar with // current download. // Not all getters have progress support yet.
[ "WithProgress", "allows", "for", "a", "user", "to", "track", "the", "progress", "of", "a", "download", ".", "For", "example", "by", "displaying", "a", "progress", "bar", "with", "current", "download", ".", "Not", "all", "getters", "have", "progress", "support", "yet", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/client_option_progress.go#L12-L17
train
hashicorp/go-getter
get_git.go
fetchSubmodules
func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, depth int) error { args := []string{"submodule", "update", "--init", "--recursive"} if depth > 0 { args = append(args, "--depth", strconv.Itoa(depth)) } cmd := exec.CommandContext(ctx, "git", args...) cmd.Dir = dst setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) }
go
func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, depth int) error { args := []string{"submodule", "update", "--init", "--recursive"} if depth > 0 { args = append(args, "--depth", strconv.Itoa(depth)) } cmd := exec.CommandContext(ctx, "git", args...) cmd.Dir = dst setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) }
[ "func", "(", "g", "*", "GitGetter", ")", "fetchSubmodules", "(", "ctx", "context", ".", "Context", ",", "dst", ",", "sshKeyFile", "string", ",", "depth", "int", ")", "error", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "if", "depth", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "depth", ")", ")", "\n", "}", "\n", "cmd", ":=", "exec", ".", "CommandContext", "(", "ctx", ",", "\"", "\"", ",", "args", "...", ")", "\n", "cmd", ".", "Dir", "=", "dst", "\n", "setupGitEnv", "(", "cmd", ",", "sshKeyFile", ")", "\n", "return", "getRunCommand", "(", "cmd", ")", "\n", "}" ]
// fetchSubmodules downloads any configured submodules recursively.
[ "fetchSubmodules", "downloads", "any", "configured", "submodules", "recursively", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_git.go#L216-L225
train
hashicorp/go-getter
get_git.go
setupGitEnv
func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { const gitSSHCommand = "GIT_SSH_COMMAND=" var sshCmd []string // If we have an existing GIT_SSH_COMMAND, we need to append our options. // We will also remove our old entry to make sure the behavior is the same // with versions of Go < 1.9. env := os.Environ() for i, v := range env { if strings.HasPrefix(v, gitSSHCommand) && len(v) > len(gitSSHCommand) { sshCmd = []string{v} env[i], env[len(env)-1] = env[len(env)-1], env[i] env = env[:len(env)-1] break } } if len(sshCmd) == 0 { sshCmd = []string{gitSSHCommand + "ssh"} } if sshKeyFile != "" { // We have an SSH key temp file configured, tell ssh about this. if runtime.GOOS == "windows" { sshKeyFile = strings.Replace(sshKeyFile, `\`, `/`, -1) } sshCmd = append(sshCmd, "-i", sshKeyFile) } env = append(env, strings.Join(sshCmd, " ")) cmd.Env = env }
go
func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { const gitSSHCommand = "GIT_SSH_COMMAND=" var sshCmd []string // If we have an existing GIT_SSH_COMMAND, we need to append our options. // We will also remove our old entry to make sure the behavior is the same // with versions of Go < 1.9. env := os.Environ() for i, v := range env { if strings.HasPrefix(v, gitSSHCommand) && len(v) > len(gitSSHCommand) { sshCmd = []string{v} env[i], env[len(env)-1] = env[len(env)-1], env[i] env = env[:len(env)-1] break } } if len(sshCmd) == 0 { sshCmd = []string{gitSSHCommand + "ssh"} } if sshKeyFile != "" { // We have an SSH key temp file configured, tell ssh about this. if runtime.GOOS == "windows" { sshKeyFile = strings.Replace(sshKeyFile, `\`, `/`, -1) } sshCmd = append(sshCmd, "-i", sshKeyFile) } env = append(env, strings.Join(sshCmd, " ")) cmd.Env = env }
[ "func", "setupGitEnv", "(", "cmd", "*", "exec", ".", "Cmd", ",", "sshKeyFile", "string", ")", "{", "const", "gitSSHCommand", "=", "\"", "\"", "\n", "var", "sshCmd", "[", "]", "string", "\n\n", "// If we have an existing GIT_SSH_COMMAND, we need to append our options.", "// We will also remove our old entry to make sure the behavior is the same", "// with versions of Go < 1.9.", "env", ":=", "os", ".", "Environ", "(", ")", "\n", "for", "i", ",", "v", ":=", "range", "env", "{", "if", "strings", ".", "HasPrefix", "(", "v", ",", "gitSSHCommand", ")", "&&", "len", "(", "v", ")", ">", "len", "(", "gitSSHCommand", ")", "{", "sshCmd", "=", "[", "]", "string", "{", "v", "}", "\n\n", "env", "[", "i", "]", ",", "env", "[", "len", "(", "env", ")", "-", "1", "]", "=", "env", "[", "len", "(", "env", ")", "-", "1", "]", ",", "env", "[", "i", "]", "\n", "env", "=", "env", "[", ":", "len", "(", "env", ")", "-", "1", "]", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "sshCmd", ")", "==", "0", "{", "sshCmd", "=", "[", "]", "string", "{", "gitSSHCommand", "+", "\"", "\"", "}", "\n", "}", "\n\n", "if", "sshKeyFile", "!=", "\"", "\"", "{", "// We have an SSH key temp file configured, tell ssh about this.", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "sshKeyFile", "=", "strings", ".", "Replace", "(", "sshKeyFile", ",", "`\\`", ",", "`/`", ",", "-", "1", ")", "\n", "}", "\n", "sshCmd", "=", "append", "(", "sshCmd", ",", "\"", "\"", ",", "sshKeyFile", ")", "\n", "}", "\n\n", "env", "=", "append", "(", "env", ",", "strings", ".", "Join", "(", "sshCmd", ",", "\"", "\"", ")", ")", "\n", "cmd", ".", "Env", "=", "env", "\n", "}" ]
// setupGitEnv sets up the environment for the given command. This is used to // pass configuration data to git and ssh and enables advanced cloning methods.
[ "setupGitEnv", "sets", "up", "the", "environment", "for", "the", "given", "command", ".", "This", "is", "used", "to", "pass", "configuration", "data", "to", "git", "and", "ssh", "and", "enables", "advanced", "cloning", "methods", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_git.go#L229-L261
train
hashicorp/go-getter
get_git.go
checkGitVersion
func checkGitVersion(min string) error { want, err := version.NewVersion(min) if err != nil { return err } out, err := exec.Command("git", "version").Output() if err != nil { return err } fields := strings.Fields(string(out)) if len(fields) < 3 { return fmt.Errorf("Unexpected 'git version' output: %q", string(out)) } v := fields[2] if runtime.GOOS == "windows" && strings.Contains(v, ".windows.") { // on windows, git version will return for example: // git version 2.20.1.windows.1 // Which does not follow the semantic versionning specs // https://semver.org. We remove that part in order for // go-version to not error. v = v[:strings.Index(v, ".windows.")] } have, err := version.NewVersion(v) if err != nil { return err } if have.LessThan(want) { return fmt.Errorf("Required git version = %s, have %s", want, have) } return nil }
go
func checkGitVersion(min string) error { want, err := version.NewVersion(min) if err != nil { return err } out, err := exec.Command("git", "version").Output() if err != nil { return err } fields := strings.Fields(string(out)) if len(fields) < 3 { return fmt.Errorf("Unexpected 'git version' output: %q", string(out)) } v := fields[2] if runtime.GOOS == "windows" && strings.Contains(v, ".windows.") { // on windows, git version will return for example: // git version 2.20.1.windows.1 // Which does not follow the semantic versionning specs // https://semver.org. We remove that part in order for // go-version to not error. v = v[:strings.Index(v, ".windows.")] } have, err := version.NewVersion(v) if err != nil { return err } if have.LessThan(want) { return fmt.Errorf("Required git version = %s, have %s", want, have) } return nil }
[ "func", "checkGitVersion", "(", "min", "string", ")", "error", "{", "want", ",", "err", ":=", "version", ".", "NewVersion", "(", "min", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "out", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fields", ":=", "strings", ".", "Fields", "(", "string", "(", "out", ")", ")", "\n", "if", "len", "(", "fields", ")", "<", "3", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "out", ")", ")", "\n", "}", "\n", "v", ":=", "fields", "[", "2", "]", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "&&", "strings", ".", "Contains", "(", "v", ",", "\"", "\"", ")", "{", "// on windows, git version will return for example:", "// git version 2.20.1.windows.1", "// Which does not follow the semantic versionning specs", "// https://semver.org. We remove that part in order for", "// go-version to not error.", "v", "=", "v", "[", ":", "strings", ".", "Index", "(", "v", ",", "\"", "\"", ")", "]", "\n", "}", "\n\n", "have", ",", "err", ":=", "version", ".", "NewVersion", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "have", ".", "LessThan", "(", "want", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "want", ",", "have", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkGitVersion is used to check the version of git installed on the system // against a known minimum version. Returns an error if the installed version // is older than the given minimum.
[ "checkGitVersion", "is", "used", "to", "check", "the", "version", "of", "git", "installed", "on", "the", "system", "against", "a", "known", "minimum", "version", ".", "Returns", "an", "error", "if", "the", "installed", "version", "is", "older", "than", "the", "given", "minimum", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_git.go#L266-L301
train
hashicorp/go-getter
get_http.go
getSubdir
func (g *HttpGetter) getSubdir(ctx context.Context, dst, source, subDir string) error { // Create a temporary directory to store the full source. This has to be // a non-existent directory. td, tdcloser, err := safetemp.Dir("", "getter") if err != nil { return err } defer tdcloser.Close() var opts []ClientOption if g.client != nil { opts = g.client.Options } // Download that into the given directory if err := Get(td, source, opts...); err != nil { return err } // Process any globbing sourcePath, err := SubdirGlob(td, subDir) if err != nil { return err } // Make sure the subdir path actually exists if _, err := os.Stat(sourcePath); err != nil { return fmt.Errorf( "Error downloading %s: %s", source, err) } // Copy the subdirectory into our actual destination. if err := os.RemoveAll(dst); err != nil { return err } // Make the final destination if err := os.MkdirAll(dst, 0755); err != nil { return err } return copyDir(ctx, dst, sourcePath, false) }
go
func (g *HttpGetter) getSubdir(ctx context.Context, dst, source, subDir string) error { // Create a temporary directory to store the full source. This has to be // a non-existent directory. td, tdcloser, err := safetemp.Dir("", "getter") if err != nil { return err } defer tdcloser.Close() var opts []ClientOption if g.client != nil { opts = g.client.Options } // Download that into the given directory if err := Get(td, source, opts...); err != nil { return err } // Process any globbing sourcePath, err := SubdirGlob(td, subDir) if err != nil { return err } // Make sure the subdir path actually exists if _, err := os.Stat(sourcePath); err != nil { return fmt.Errorf( "Error downloading %s: %s", source, err) } // Copy the subdirectory into our actual destination. if err := os.RemoveAll(dst); err != nil { return err } // Make the final destination if err := os.MkdirAll(dst, 0755); err != nil { return err } return copyDir(ctx, dst, sourcePath, false) }
[ "func", "(", "g", "*", "HttpGetter", ")", "getSubdir", "(", "ctx", "context", ".", "Context", ",", "dst", ",", "source", ",", "subDir", "string", ")", "error", "{", "// Create a temporary directory to store the full source. This has to be", "// a non-existent directory.", "td", ",", "tdcloser", ",", "err", ":=", "safetemp", ".", "Dir", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "tdcloser", ".", "Close", "(", ")", "\n\n", "var", "opts", "[", "]", "ClientOption", "\n", "if", "g", ".", "client", "!=", "nil", "{", "opts", "=", "g", ".", "client", ".", "Options", "\n", "}", "\n", "// Download that into the given directory", "if", "err", ":=", "Get", "(", "td", ",", "source", ",", "opts", "...", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Process any globbing", "sourcePath", ",", "err", ":=", "SubdirGlob", "(", "td", ",", "subDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Make sure the subdir path actually exists", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "sourcePath", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "source", ",", "err", ")", "\n", "}", "\n\n", "// Copy the subdirectory into our actual destination.", "if", "err", ":=", "os", ".", "RemoveAll", "(", "dst", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Make the final destination", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dst", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "copyDir", "(", "ctx", ",", "dst", ",", "sourcePath", ",", "false", ")", "\n", "}" ]
// getSubdir downloads the source into the destination, but with // the proper subdir.
[ "getSubdir", "downloads", "the", "source", "into", "the", "destination", "but", "with", "the", "proper", "subdir", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_http.go#L220-L261
train
hashicorp/go-getter
get_http.go
parseMeta
func (g *HttpGetter) parseMeta(r io.Reader) (string, error) { d := xml.NewDecoder(r) d.CharsetReader = charsetReader d.Strict = false var err error var t xml.Token for { t, err = d.Token() if err != nil { if err == io.EOF { err = nil } return "", err } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { return "", nil } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { return "", nil } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "terraform-get" { continue } if f := attrValue(e.Attr, "content"); f != "" { return f, nil } } }
go
func (g *HttpGetter) parseMeta(r io.Reader) (string, error) { d := xml.NewDecoder(r) d.CharsetReader = charsetReader d.Strict = false var err error var t xml.Token for { t, err = d.Token() if err != nil { if err == io.EOF { err = nil } return "", err } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { return "", nil } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { return "", nil } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "terraform-get" { continue } if f := attrValue(e.Attr, "content"); f != "" { return f, nil } } }
[ "func", "(", "g", "*", "HttpGetter", ")", "parseMeta", "(", "r", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "d", ":=", "xml", ".", "NewDecoder", "(", "r", ")", "\n", "d", ".", "CharsetReader", "=", "charsetReader", "\n", "d", ".", "Strict", "=", "false", "\n", "var", "err", "error", "\n", "var", "t", "xml", ".", "Token", "\n", "for", "{", "t", ",", "err", "=", "d", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "t", ".", "(", "xml", ".", "StartElement", ")", ";", "ok", "&&", "strings", ".", "EqualFold", "(", "e", ".", "Name", ".", "Local", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "t", ".", "(", "xml", ".", "EndElement", ")", ";", "ok", "&&", "strings", ".", "EqualFold", "(", "e", ".", "Name", ".", "Local", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "e", ",", "ok", ":=", "t", ".", "(", "xml", ".", "StartElement", ")", "\n", "if", "!", "ok", "||", "!", "strings", ".", "EqualFold", "(", "e", ".", "Name", ".", "Local", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "if", "attrValue", "(", "e", ".", "Attr", ",", "\"", "\"", ")", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "f", ":=", "attrValue", "(", "e", ".", "Attr", ",", "\"", "\"", ")", ";", "f", "!=", "\"", "\"", "{", "return", "f", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// parseMeta looks for the first meta tag in the given reader that // will give us the source URL.
[ "parseMeta", "looks", "for", "the", "first", "meta", "tag", "in", "the", "given", "reader", "that", "will", "give", "us", "the", "source", "URL", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_http.go#L265-L296
train
hashicorp/go-getter
cmd/go-getter/progress_tracking.go
TrackProgress
func (cpb *ProgressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { cpb.lock.Lock() defer cpb.lock.Unlock() newPb := pb.New64(totalSize) newPb.Set64(currentSize) ProgressBarConfig(newPb, filepath.Base(src)) if cpb.pool == nil { cpb.pool = pb.NewPool() cpb.pool.Start() } cpb.pool.Add(newPb) reader := newPb.NewProxyReader(stream) cpb.pbs++ return &readCloser{ Reader: reader, close: func() error { cpb.lock.Lock() defer cpb.lock.Unlock() newPb.Finish() cpb.pbs-- if cpb.pbs <= 0 { cpb.pool.Stop() cpb.pool = nil } return nil }, } }
go
func (cpb *ProgressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { cpb.lock.Lock() defer cpb.lock.Unlock() newPb := pb.New64(totalSize) newPb.Set64(currentSize) ProgressBarConfig(newPb, filepath.Base(src)) if cpb.pool == nil { cpb.pool = pb.NewPool() cpb.pool.Start() } cpb.pool.Add(newPb) reader := newPb.NewProxyReader(stream) cpb.pbs++ return &readCloser{ Reader: reader, close: func() error { cpb.lock.Lock() defer cpb.lock.Unlock() newPb.Finish() cpb.pbs-- if cpb.pbs <= 0 { cpb.pool.Stop() cpb.pool = nil } return nil }, } }
[ "func", "(", "cpb", "*", "ProgressBar", ")", "TrackProgress", "(", "src", "string", ",", "currentSize", ",", "totalSize", "int64", ",", "stream", "io", ".", "ReadCloser", ")", "io", ".", "ReadCloser", "{", "cpb", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "cpb", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "newPb", ":=", "pb", ".", "New64", "(", "totalSize", ")", "\n", "newPb", ".", "Set64", "(", "currentSize", ")", "\n", "ProgressBarConfig", "(", "newPb", ",", "filepath", ".", "Base", "(", "src", ")", ")", "\n", "if", "cpb", ".", "pool", "==", "nil", "{", "cpb", ".", "pool", "=", "pb", ".", "NewPool", "(", ")", "\n", "cpb", ".", "pool", ".", "Start", "(", ")", "\n", "}", "\n", "cpb", ".", "pool", ".", "Add", "(", "newPb", ")", "\n", "reader", ":=", "newPb", ".", "NewProxyReader", "(", "stream", ")", "\n\n", "cpb", ".", "pbs", "++", "\n", "return", "&", "readCloser", "{", "Reader", ":", "reader", ",", "close", ":", "func", "(", ")", "error", "{", "cpb", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "cpb", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "newPb", ".", "Finish", "(", ")", "\n", "cpb", ".", "pbs", "--", "\n", "if", "cpb", ".", "pbs", "<=", "0", "{", "cpb", ".", "pool", ".", "Stop", "(", ")", "\n", "cpb", ".", "pool", "=", "nil", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "}", "\n", "}" ]
// TrackProgress instantiates a new progress bar that will // display the progress of stream until closed. // total can be 0.
[ "TrackProgress", "instantiates", "a", "new", "progress", "bar", "that", "will", "display", "the", "progress", "of", "stream", "until", "closed", ".", "total", "can", "be", "0", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/cmd/go-getter/progress_tracking.go#L40-L70
train
hashicorp/go-getter
detect_ssh.go
detectSSH
func detectSSH(src string) (*url.URL, error) { matched := sshPattern.FindStringSubmatch(src) if matched == nil { return nil, nil } user := matched[1] host := matched[2] path := matched[3] qidx := strings.Index(path, "?") if qidx == -1 { qidx = len(path) } var u url.URL u.Scheme = "ssh" u.User = url.User(user) u.Host = host u.Path = path[0:qidx] if qidx < len(path) { q, err := url.ParseQuery(path[qidx+1:]) if err != nil { return nil, fmt.Errorf("error parsing GitHub SSH URL: %s", err) } u.RawQuery = q.Encode() } return &u, nil }
go
func detectSSH(src string) (*url.URL, error) { matched := sshPattern.FindStringSubmatch(src) if matched == nil { return nil, nil } user := matched[1] host := matched[2] path := matched[3] qidx := strings.Index(path, "?") if qidx == -1 { qidx = len(path) } var u url.URL u.Scheme = "ssh" u.User = url.User(user) u.Host = host u.Path = path[0:qidx] if qidx < len(path) { q, err := url.ParseQuery(path[qidx+1:]) if err != nil { return nil, fmt.Errorf("error parsing GitHub SSH URL: %s", err) } u.RawQuery = q.Encode() } return &u, nil }
[ "func", "detectSSH", "(", "src", "string", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "matched", ":=", "sshPattern", ".", "FindStringSubmatch", "(", "src", ")", "\n", "if", "matched", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "user", ":=", "matched", "[", "1", "]", "\n", "host", ":=", "matched", "[", "2", "]", "\n", "path", ":=", "matched", "[", "3", "]", "\n", "qidx", ":=", "strings", ".", "Index", "(", "path", ",", "\"", "\"", ")", "\n", "if", "qidx", "==", "-", "1", "{", "qidx", "=", "len", "(", "path", ")", "\n", "}", "\n\n", "var", "u", "url", ".", "URL", "\n", "u", ".", "Scheme", "=", "\"", "\"", "\n", "u", ".", "User", "=", "url", ".", "User", "(", "user", ")", "\n", "u", ".", "Host", "=", "host", "\n", "u", ".", "Path", "=", "path", "[", "0", ":", "qidx", "]", "\n", "if", "qidx", "<", "len", "(", "path", ")", "{", "q", ",", "err", ":=", "url", ".", "ParseQuery", "(", "path", "[", "qidx", "+", "1", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "u", ".", "RawQuery", "=", "q", ".", "Encode", "(", ")", "\n", "}", "\n\n", "return", "&", "u", ",", "nil", "\n", "}" ]
// detectSSH determines if the src string matches an SSH-like URL and // converts it into a net.URL compatible string. This returns nil if the // string doesn't match the SSH pattern. // // This function is tested indirectly via detect_git_test.go
[ "detectSSH", "determines", "if", "the", "src", "string", "matches", "an", "SSH", "-", "like", "URL", "and", "converts", "it", "into", "a", "net", ".", "URL", "compatible", "string", ".", "This", "returns", "nil", "if", "the", "string", "doesn", "t", "match", "the", "SSH", "pattern", ".", "This", "function", "is", "tested", "indirectly", "via", "detect_git_test", ".", "go" ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/detect_ssh.go#L21-L49
train
hashicorp/go-getter
get_hg.go
GetFile
func (g *HgGetter) GetFile(dst string, u *url.URL) error { // Create a temporary directory to store the full source. This has to be // a non-existent directory. td, tdcloser, err := safetemp.Dir("", "getter") if err != nil { return err } defer tdcloser.Close() // Get the filename, and strip the filename from the URL so we can // just get the repository directly. filename := filepath.Base(u.Path) u.Path = filepath.ToSlash(filepath.Dir(u.Path)) // If we're on Windows, we need to set the host to "localhost" for hg if runtime.GOOS == "windows" { u.Host = "localhost" } // Get the full repository if err := g.Get(td, u); err != nil { return err } // Copy the single file u, err = urlhelper.Parse(fmtFileURL(filepath.Join(td, filename))) if err != nil { return err } fg := &FileGetter{Copy: true, getter: g.getter} return fg.GetFile(dst, u) }
go
func (g *HgGetter) GetFile(dst string, u *url.URL) error { // Create a temporary directory to store the full source. This has to be // a non-existent directory. td, tdcloser, err := safetemp.Dir("", "getter") if err != nil { return err } defer tdcloser.Close() // Get the filename, and strip the filename from the URL so we can // just get the repository directly. filename := filepath.Base(u.Path) u.Path = filepath.ToSlash(filepath.Dir(u.Path)) // If we're on Windows, we need to set the host to "localhost" for hg if runtime.GOOS == "windows" { u.Host = "localhost" } // Get the full repository if err := g.Get(td, u); err != nil { return err } // Copy the single file u, err = urlhelper.Parse(fmtFileURL(filepath.Join(td, filename))) if err != nil { return err } fg := &FileGetter{Copy: true, getter: g.getter} return fg.GetFile(dst, u) }
[ "func", "(", "g", "*", "HgGetter", ")", "GetFile", "(", "dst", "string", ",", "u", "*", "url", ".", "URL", ")", "error", "{", "// Create a temporary directory to store the full source. This has to be", "// a non-existent directory.", "td", ",", "tdcloser", ",", "err", ":=", "safetemp", ".", "Dir", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "tdcloser", ".", "Close", "(", ")", "\n\n", "// Get the filename, and strip the filename from the URL so we can", "// just get the repository directly.", "filename", ":=", "filepath", ".", "Base", "(", "u", ".", "Path", ")", "\n", "u", ".", "Path", "=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Dir", "(", "u", ".", "Path", ")", ")", "\n\n", "// If we're on Windows, we need to set the host to \"localhost\" for hg", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "u", ".", "Host", "=", "\"", "\"", "\n", "}", "\n\n", "// Get the full repository", "if", "err", ":=", "g", ".", "Get", "(", "td", ",", "u", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Copy the single file", "u", ",", "err", "=", "urlhelper", ".", "Parse", "(", "fmtFileURL", "(", "filepath", ".", "Join", "(", "td", ",", "filename", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fg", ":=", "&", "FileGetter", "{", "Copy", ":", "true", ",", "getter", ":", "g", ".", "getter", "}", "\n", "return", "fg", ".", "GetFile", "(", "dst", ",", "u", ")", "\n", "}" ]
// GetFile for Hg doesn't support updating at this time. It will download // the file every time.
[ "GetFile", "for", "Hg", "doesn", "t", "support", "updating", "at", "this", "time", ".", "It", "will", "download", "the", "file", "every", "time", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_hg.go#L70-L102
train
hashicorp/go-getter
folder_storage.go
Dir
func (s *FolderStorage) Dir(key string) (d string, e bool, err error) { d = s.dir(key) _, err = os.Stat(d) if err == nil { // Directory exists e = true return } if os.IsNotExist(err) { // Directory doesn't exist d = "" e = false err = nil return } // An error d = "" e = false return }
go
func (s *FolderStorage) Dir(key string) (d string, e bool, err error) { d = s.dir(key) _, err = os.Stat(d) if err == nil { // Directory exists e = true return } if os.IsNotExist(err) { // Directory doesn't exist d = "" e = false err = nil return } // An error d = "" e = false return }
[ "func", "(", "s", "*", "FolderStorage", ")", "Dir", "(", "key", "string", ")", "(", "d", "string", ",", "e", "bool", ",", "err", "error", ")", "{", "d", "=", "s", ".", "dir", "(", "key", ")", "\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "d", ")", "\n", "if", "err", "==", "nil", "{", "// Directory exists", "e", "=", "true", "\n", "return", "\n", "}", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// Directory doesn't exist", "d", "=", "\"", "\"", "\n", "e", "=", "false", "\n", "err", "=", "nil", "\n", "return", "\n", "}", "\n\n", "// An error", "d", "=", "\"", "\"", "\n", "e", "=", "false", "\n", "return", "\n", "}" ]
// Dir implements Storage.Dir
[ "Dir", "implements", "Storage", ".", "Dir" ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/folder_storage.go#L19-L39
train
hashicorp/go-getter
folder_storage.go
dir
func (s *FolderStorage) dir(key string) string { sum := md5.Sum([]byte(key)) return filepath.Join(s.StorageDir, hex.EncodeToString(sum[:])) }
go
func (s *FolderStorage) dir(key string) string { sum := md5.Sum([]byte(key)) return filepath.Join(s.StorageDir, hex.EncodeToString(sum[:])) }
[ "func", "(", "s", "*", "FolderStorage", ")", "dir", "(", "key", "string", ")", "string", "{", "sum", ":=", "md5", ".", "Sum", "(", "[", "]", "byte", "(", "key", ")", ")", "\n", "return", "filepath", ".", "Join", "(", "s", ".", "StorageDir", ",", "hex", ".", "EncodeToString", "(", "sum", "[", ":", "]", ")", ")", "\n", "}" ]
// dir returns the directory name internally that we'll use to map to // internally.
[ "dir", "returns", "the", "directory", "name", "internally", "that", "we", "ll", "use", "to", "map", "to", "internally", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/folder_storage.go#L62-L65
train
hashicorp/go-getter
get_file_copy.go
Copy
func Copy(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) { // Copy will call the Reader and Writer interface multiple time, in order // to copy by chunk (avoiding loading the whole file in memory). return io.Copy(dst, readerFunc(func(p []byte) (int, error) { select { case <-ctx.Done(): // context has been canceled // stop process and propagate "context canceled" error return 0, ctx.Err() default: // otherwise just run default io.Reader implementation return src.Read(p) } })) }
go
func Copy(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) { // Copy will call the Reader and Writer interface multiple time, in order // to copy by chunk (avoiding loading the whole file in memory). return io.Copy(dst, readerFunc(func(p []byte) (int, error) { select { case <-ctx.Done(): // context has been canceled // stop process and propagate "context canceled" error return 0, ctx.Err() default: // otherwise just run default io.Reader implementation return src.Read(p) } })) }
[ "func", "Copy", "(", "ctx", "context", ".", "Context", ",", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "// Copy will call the Reader and Writer interface multiple time, in order", "// to copy by chunk (avoiding loading the whole file in memory).", "return", "io", ".", "Copy", "(", "dst", ",", "readerFunc", "(", "func", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "// context has been canceled", "// stop process and propagate \"context canceled\" error", "return", "0", ",", "ctx", ".", "Err", "(", ")", "\n", "default", ":", "// otherwise just run default io.Reader implementation", "return", "src", ".", "Read", "(", "p", ")", "\n", "}", "\n", "}", ")", ")", "\n", "}" ]
// Copy is a io.Copy cancellable by context
[ "Copy", "is", "a", "io", ".", "Copy", "cancellable", "by", "context" ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/get_file_copy.go#L14-L29
train
hashicorp/go-getter
netrc.go
addAuthFromNetrc
func addAuthFromNetrc(u *url.URL) error { // If the URL already has auth information, do nothing if u.User != nil && u.User.Username() != "" { return nil } // Get the netrc file path path := os.Getenv("NETRC") if path == "" { filename := ".netrc" if runtime.GOOS == "windows" { filename = "_netrc" } var err error path, err = homedir.Expand("~/" + filename) if err != nil { return err } } // If the file is not a file, then do nothing if fi, err := os.Stat(path); err != nil { // File doesn't exist, do nothing if os.IsNotExist(err) { return nil } // Some other error! return err } else if fi.IsDir() { // File is directory, ignore return nil } // Load up the netrc file net, err := netrc.ParseFile(path) if err != nil { return fmt.Errorf("Error parsing netrc file at %q: %s", path, err) } machine := net.FindMachine(u.Host) if machine == nil { // Machine not found, no problem return nil } // Set the user info u.User = url.UserPassword(machine.Login, machine.Password) return nil }
go
func addAuthFromNetrc(u *url.URL) error { // If the URL already has auth information, do nothing if u.User != nil && u.User.Username() != "" { return nil } // Get the netrc file path path := os.Getenv("NETRC") if path == "" { filename := ".netrc" if runtime.GOOS == "windows" { filename = "_netrc" } var err error path, err = homedir.Expand("~/" + filename) if err != nil { return err } } // If the file is not a file, then do nothing if fi, err := os.Stat(path); err != nil { // File doesn't exist, do nothing if os.IsNotExist(err) { return nil } // Some other error! return err } else if fi.IsDir() { // File is directory, ignore return nil } // Load up the netrc file net, err := netrc.ParseFile(path) if err != nil { return fmt.Errorf("Error parsing netrc file at %q: %s", path, err) } machine := net.FindMachine(u.Host) if machine == nil { // Machine not found, no problem return nil } // Set the user info u.User = url.UserPassword(machine.Login, machine.Password) return nil }
[ "func", "addAuthFromNetrc", "(", "u", "*", "url", ".", "URL", ")", "error", "{", "// If the URL already has auth information, do nothing", "if", "u", ".", "User", "!=", "nil", "&&", "u", ".", "User", ".", "Username", "(", ")", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "// Get the netrc file path", "path", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "path", "==", "\"", "\"", "{", "filename", ":=", "\"", "\"", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "filename", "=", "\"", "\"", "\n", "}", "\n\n", "var", "err", "error", "\n", "path", ",", "err", "=", "homedir", ".", "Expand", "(", "\"", "\"", "+", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// If the file is not a file, then do nothing", "if", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "!=", "nil", "{", "// File doesn't exist, do nothing", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Some other error!", "return", "err", "\n", "}", "else", "if", "fi", ".", "IsDir", "(", ")", "{", "// File is directory, ignore", "return", "nil", "\n", "}", "\n\n", "// Load up the netrc file", "net", ",", "err", ":=", "netrc", ".", "ParseFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n\n", "machine", ":=", "net", ".", "FindMachine", "(", "u", ".", "Host", ")", "\n", "if", "machine", "==", "nil", "{", "// Machine not found, no problem", "return", "nil", "\n", "}", "\n\n", "// Set the user info", "u", ".", "User", "=", "url", ".", "UserPassword", "(", "machine", ".", "Login", ",", "machine", ".", "Password", ")", "\n", "return", "nil", "\n", "}" ]
// addAuthFromNetrc adds auth information to the URL from the user's // netrc file if it can be found. This will only add the auth info // if the URL doesn't already have auth info specified and the // the username is blank.
[ "addAuthFromNetrc", "adds", "auth", "information", "to", "the", "URL", "from", "the", "user", "s", "netrc", "file", "if", "it", "can", "be", "found", ".", "This", "will", "only", "add", "the", "auth", "info", "if", "the", "URL", "doesn", "t", "already", "have", "auth", "info", "specified", "and", "the", "the", "username", "is", "blank", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/netrc.go#L17-L67
train
hashicorp/go-getter
client_option.go
Configure
func (c *Client) Configure(opts ...ClientOption) error { if c.Ctx == nil { c.Ctx = context.Background() } c.Options = opts for _, opt := range opts { err := opt(c) if err != nil { return err } } // Default decompressor values if c.Decompressors == nil { c.Decompressors = Decompressors } // Default detector values if c.Detectors == nil { c.Detectors = Detectors } // Default getter values if c.Getters == nil { c.Getters = Getters } for _, getter := range c.Getters { getter.SetClient(c) } return nil }
go
func (c *Client) Configure(opts ...ClientOption) error { if c.Ctx == nil { c.Ctx = context.Background() } c.Options = opts for _, opt := range opts { err := opt(c) if err != nil { return err } } // Default decompressor values if c.Decompressors == nil { c.Decompressors = Decompressors } // Default detector values if c.Detectors == nil { c.Detectors = Detectors } // Default getter values if c.Getters == nil { c.Getters = Getters } for _, getter := range c.Getters { getter.SetClient(c) } return nil }
[ "func", "(", "c", "*", "Client", ")", "Configure", "(", "opts", "...", "ClientOption", ")", "error", "{", "if", "c", ".", "Ctx", "==", "nil", "{", "c", ".", "Ctx", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "c", ".", "Options", "=", "opts", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "err", ":=", "opt", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Default decompressor values", "if", "c", ".", "Decompressors", "==", "nil", "{", "c", ".", "Decompressors", "=", "Decompressors", "\n", "}", "\n", "// Default detector values", "if", "c", ".", "Detectors", "==", "nil", "{", "c", ".", "Detectors", "=", "Detectors", "\n", "}", "\n", "// Default getter values", "if", "c", ".", "Getters", "==", "nil", "{", "c", ".", "Getters", "=", "Getters", "\n", "}", "\n\n", "for", "_", ",", "getter", ":=", "range", "c", ".", "Getters", "{", "getter", ".", "SetClient", "(", "c", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Configure configures a client with options.
[ "Configure", "configures", "a", "client", "with", "options", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/client_option.go#L9-L37
train
hashicorp/go-getter
client_option.go
WithContext
func WithContext(ctx context.Context) func(*Client) error { return func(c *Client) error { c.Ctx = ctx return nil } }
go
func WithContext(ctx context.Context) func(*Client) error { return func(c *Client) error { c.Ctx = ctx return nil } }
[ "func", "WithContext", "(", "ctx", "context", ".", "Context", ")", "func", "(", "*", "Client", ")", "error", "{", "return", "func", "(", "c", "*", "Client", ")", "error", "{", "c", ".", "Ctx", "=", "ctx", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithContext allows to pass a context to operation // in order to be able to cancel a download in progress.
[ "WithContext", "allows", "to", "pass", "a", "context", "to", "operation", "in", "order", "to", "be", "able", "to", "cancel", "a", "download", "in", "progress", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/client_option.go#L41-L46
train
hashicorp/go-getter
checksum.go
checksum
func (c *fileChecksum) checksum(source string) error { f, err := os.Open(source) if err != nil { return fmt.Errorf("Failed to open file for checksum: %s", err) } defer f.Close() c.Hash.Reset() if _, err := io.Copy(c.Hash, f); err != nil { return fmt.Errorf("Failed to hash: %s", err) } if actual := c.Hash.Sum(nil); !bytes.Equal(actual, c.Value) { return &ChecksumError{ Hash: c.Hash, Actual: actual, Expected: c.Value, File: source, } } return nil }
go
func (c *fileChecksum) checksum(source string) error { f, err := os.Open(source) if err != nil { return fmt.Errorf("Failed to open file for checksum: %s", err) } defer f.Close() c.Hash.Reset() if _, err := io.Copy(c.Hash, f); err != nil { return fmt.Errorf("Failed to hash: %s", err) } if actual := c.Hash.Sum(nil); !bytes.Equal(actual, c.Value) { return &ChecksumError{ Hash: c.Hash, Actual: actual, Expected: c.Value, File: source, } } return nil }
[ "func", "(", "c", "*", "fileChecksum", ")", "checksum", "(", "source", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "c", ".", "Hash", ".", "Reset", "(", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "c", ".", "Hash", ",", "f", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "actual", ":=", "c", ".", "Hash", ".", "Sum", "(", "nil", ")", ";", "!", "bytes", ".", "Equal", "(", "actual", ",", "c", ".", "Value", ")", "{", "return", "&", "ChecksumError", "{", "Hash", ":", "c", ".", "Hash", ",", "Actual", ":", "actual", ",", "Expected", ":", "c", ".", "Value", ",", "File", ":", "source", ",", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checksum is a simple method to compute the checksum of a source file // and compare it to the given expected value.
[ "checksum", "is", "a", "simple", "method", "to", "compute", "the", "checksum", "of", "a", "source", "file", "and", "compare", "it", "to", "the", "given", "expected", "value", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/checksum.go#L53-L75
train
hashicorp/go-getter
checksum.go
checksumFromFile
func (c *Client) checksumFromFile(checksumFile string, src *url.URL) (*fileChecksum, error) { checksumFileURL, err := urlhelper.Parse(checksumFile) if err != nil { return nil, err } tempfile, err := tmpFile("", filepath.Base(checksumFileURL.Path)) if err != nil { return nil, err } defer os.Remove(tempfile) c2 := &Client{ Ctx: c.Ctx, Getters: c.Getters, Decompressors: c.Decompressors, Detectors: c.Detectors, Pwd: c.Pwd, Dir: false, Src: checksumFile, Dst: tempfile, ProgressListener: c.ProgressListener, } if err = c2.Get(); err != nil { return nil, fmt.Errorf( "Error downloading checksum file: %s", err) } filename := filepath.Base(src.Path) absPath, err := filepath.Abs(src.Path) if err != nil { return nil, err } checksumFileDir := filepath.Dir(checksumFileURL.Path) relpath, err := filepath.Rel(checksumFileDir, absPath) switch { case err == nil || err.Error() == "Rel: can't make "+absPath+" relative to "+checksumFileDir: // ex: on windows C:\gopath\...\content.txt cannot be relative to \ // which is okay, may be another expected path will work. break default: return nil, err } // possible file identifiers: options := []string{ filename, // ubuntu-14.04.1-server-amd64.iso "*" + filename, // *ubuntu-14.04.1-server-amd64.iso Standard checksum "?" + filename, // ?ubuntu-14.04.1-server-amd64.iso shasum -p relpath, // dir/ubuntu-14.04.1-server-amd64.iso "./" + relpath, // ./dir/ubuntu-14.04.1-server-amd64.iso absPath, // fullpath; set if local } f, err := os.Open(tempfile) if err != nil { return nil, fmt.Errorf( "Error opening downloaded file: %s", err) } defer f.Close() rd := bufio.NewReader(f) for { line, err := rd.ReadString('\n') if err != nil { if err != io.EOF { return nil, fmt.Errorf( "Error reading checksum file: %s", err) } break } checksum, err := parseChecksumLine(line) if err != nil || checksum == nil { continue } if checksum.Filename == "" { // filename not sure, let's try return checksum, nil } // make sure the checksum is for the right file for _, option := range options { if option != "" && checksum.Filename == option { // any checksum will work so we return the first one return checksum, nil } } } return nil, fmt.Errorf("no checksum found in: %s", checksumFile) }
go
func (c *Client) checksumFromFile(checksumFile string, src *url.URL) (*fileChecksum, error) { checksumFileURL, err := urlhelper.Parse(checksumFile) if err != nil { return nil, err } tempfile, err := tmpFile("", filepath.Base(checksumFileURL.Path)) if err != nil { return nil, err } defer os.Remove(tempfile) c2 := &Client{ Ctx: c.Ctx, Getters: c.Getters, Decompressors: c.Decompressors, Detectors: c.Detectors, Pwd: c.Pwd, Dir: false, Src: checksumFile, Dst: tempfile, ProgressListener: c.ProgressListener, } if err = c2.Get(); err != nil { return nil, fmt.Errorf( "Error downloading checksum file: %s", err) } filename := filepath.Base(src.Path) absPath, err := filepath.Abs(src.Path) if err != nil { return nil, err } checksumFileDir := filepath.Dir(checksumFileURL.Path) relpath, err := filepath.Rel(checksumFileDir, absPath) switch { case err == nil || err.Error() == "Rel: can't make "+absPath+" relative to "+checksumFileDir: // ex: on windows C:\gopath\...\content.txt cannot be relative to \ // which is okay, may be another expected path will work. break default: return nil, err } // possible file identifiers: options := []string{ filename, // ubuntu-14.04.1-server-amd64.iso "*" + filename, // *ubuntu-14.04.1-server-amd64.iso Standard checksum "?" + filename, // ?ubuntu-14.04.1-server-amd64.iso shasum -p relpath, // dir/ubuntu-14.04.1-server-amd64.iso "./" + relpath, // ./dir/ubuntu-14.04.1-server-amd64.iso absPath, // fullpath; set if local } f, err := os.Open(tempfile) if err != nil { return nil, fmt.Errorf( "Error opening downloaded file: %s", err) } defer f.Close() rd := bufio.NewReader(f) for { line, err := rd.ReadString('\n') if err != nil { if err != io.EOF { return nil, fmt.Errorf( "Error reading checksum file: %s", err) } break } checksum, err := parseChecksumLine(line) if err != nil || checksum == nil { continue } if checksum.Filename == "" { // filename not sure, let's try return checksum, nil } // make sure the checksum is for the right file for _, option := range options { if option != "" && checksum.Filename == option { // any checksum will work so we return the first one return checksum, nil } } } return nil, fmt.Errorf("no checksum found in: %s", checksumFile) }
[ "func", "(", "c", "*", "Client", ")", "checksumFromFile", "(", "checksumFile", "string", ",", "src", "*", "url", ".", "URL", ")", "(", "*", "fileChecksum", ",", "error", ")", "{", "checksumFileURL", ",", "err", ":=", "urlhelper", ".", "Parse", "(", "checksumFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "tempfile", ",", "err", ":=", "tmpFile", "(", "\"", "\"", ",", "filepath", ".", "Base", "(", "checksumFileURL", ".", "Path", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "tempfile", ")", "\n\n", "c2", ":=", "&", "Client", "{", "Ctx", ":", "c", ".", "Ctx", ",", "Getters", ":", "c", ".", "Getters", ",", "Decompressors", ":", "c", ".", "Decompressors", ",", "Detectors", ":", "c", ".", "Detectors", ",", "Pwd", ":", "c", ".", "Pwd", ",", "Dir", ":", "false", ",", "Src", ":", "checksumFile", ",", "Dst", ":", "tempfile", ",", "ProgressListener", ":", "c", ".", "ProgressListener", ",", "}", "\n", "if", "err", "=", "c2", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "filename", ":=", "filepath", ".", "Base", "(", "src", ".", "Path", ")", "\n", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "src", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "checksumFileDir", ":=", "filepath", ".", "Dir", "(", "checksumFileURL", ".", "Path", ")", "\n", "relpath", ",", "err", ":=", "filepath", ".", "Rel", "(", "checksumFileDir", ",", "absPath", ")", "\n", "switch", "{", "case", "err", "==", "nil", "||", "err", ".", "Error", "(", ")", "==", "\"", "\"", "+", "absPath", "+", "\"", "\"", "+", "checksumFileDir", ":", "// ex: on windows C:\\gopath\\...\\content.txt cannot be relative to \\", "// which is okay, may be another expected path will work.", "break", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n\n", "// possible file identifiers:", "options", ":=", "[", "]", "string", "{", "filename", ",", "// ubuntu-14.04.1-server-amd64.iso", "\"", "\"", "+", "filename", ",", "// *ubuntu-14.04.1-server-amd64.iso Standard checksum", "\"", "\"", "+", "filename", ",", "// ?ubuntu-14.04.1-server-amd64.iso shasum -p", "relpath", ",", "// dir/ubuntu-14.04.1-server-amd64.iso", "\"", "\"", "+", "relpath", ",", "// ./dir/ubuntu-14.04.1-server-amd64.iso", "absPath", ",", "// fullpath; set if local", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "tempfile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "rd", ":=", "bufio", ".", "NewReader", "(", "f", ")", "\n", "for", "{", "line", ",", "err", ":=", "rd", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "checksum", ",", "err", ":=", "parseChecksumLine", "(", "line", ")", "\n", "if", "err", "!=", "nil", "||", "checksum", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "checksum", ".", "Filename", "==", "\"", "\"", "{", "// filename not sure, let's try", "return", "checksum", ",", "nil", "\n", "}", "\n", "// make sure the checksum is for the right file", "for", "_", ",", "option", ":=", "range", "options", "{", "if", "option", "!=", "\"", "\"", "&&", "checksum", ".", "Filename", "==", "option", "{", "// any checksum will work so we return the first one", "return", "checksum", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "checksumFile", ")", "\n", "}" ]
// checksumsFromFile will return all the fileChecksums found in file // // checksumsFromFile will try to guess the hashing algorithm based on content // of checksum file // // checksumsFromFile will only return checksums for files that match file // behind src
[ "checksumsFromFile", "will", "return", "all", "the", "fileChecksums", "found", "in", "file", "checksumsFromFile", "will", "try", "to", "guess", "the", "hashing", "algorithm", "based", "on", "content", "of", "checksum", "file", "checksumsFromFile", "will", "only", "return", "checksums", "for", "files", "that", "match", "file", "behind", "src" ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/checksum.go#L193-L281
train
hashicorp/go-getter
checksum.go
parseChecksumLine
func parseChecksumLine(line string) (*fileChecksum, error) { parts := strings.Fields(line) switch len(parts) { case 4: // BSD-style checksum: // MD5 (file1) = <checksum> // MD5 (file2) = <checksum> if len(parts[1]) <= 2 || parts[1][0] != '(' || parts[1][len(parts[1])-1] != ')' { return nil, fmt.Errorf( "Unexpected BSD-style-checksum filename format: %s", line) } filename := parts[1][1 : len(parts[1])-1] return newChecksumFromType(parts[0], parts[3], filename) case 2: // GNU-style: // <checksum> file1 // <checksum> *file2 return newChecksumFromValue(parts[0], parts[1]) case 0: return nil, nil // empty line default: return newChecksumFromValue(parts[0], "") } }
go
func parseChecksumLine(line string) (*fileChecksum, error) { parts := strings.Fields(line) switch len(parts) { case 4: // BSD-style checksum: // MD5 (file1) = <checksum> // MD5 (file2) = <checksum> if len(parts[1]) <= 2 || parts[1][0] != '(' || parts[1][len(parts[1])-1] != ')' { return nil, fmt.Errorf( "Unexpected BSD-style-checksum filename format: %s", line) } filename := parts[1][1 : len(parts[1])-1] return newChecksumFromType(parts[0], parts[3], filename) case 2: // GNU-style: // <checksum> file1 // <checksum> *file2 return newChecksumFromValue(parts[0], parts[1]) case 0: return nil, nil // empty line default: return newChecksumFromValue(parts[0], "") } }
[ "func", "parseChecksumLine", "(", "line", "string", ")", "(", "*", "fileChecksum", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Fields", "(", "line", ")", "\n\n", "switch", "len", "(", "parts", ")", "{", "case", "4", ":", "// BSD-style checksum:", "// MD5 (file1) = <checksum>", "// MD5 (file2) = <checksum>", "if", "len", "(", "parts", "[", "1", "]", ")", "<=", "2", "||", "parts", "[", "1", "]", "[", "0", "]", "!=", "'('", "||", "parts", "[", "1", "]", "[", "len", "(", "parts", "[", "1", "]", ")", "-", "1", "]", "!=", "')'", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ")", "\n", "}", "\n", "filename", ":=", "parts", "[", "1", "]", "[", "1", ":", "len", "(", "parts", "[", "1", "]", ")", "-", "1", "]", "\n", "return", "newChecksumFromType", "(", "parts", "[", "0", "]", ",", "parts", "[", "3", "]", ",", "filename", ")", "\n", "case", "2", ":", "// GNU-style:", "// <checksum> file1", "// <checksum> *file2", "return", "newChecksumFromValue", "(", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ")", "\n", "case", "0", ":", "return", "nil", ",", "nil", "// empty line", "\n", "default", ":", "return", "newChecksumFromValue", "(", "parts", "[", "0", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// parseChecksumLine takes a line from a checksum file and returns // checksumType, checksumValue and filename parseChecksumLine guesses the style // of the checksum BSD vs GNU by splitting the line and by counting the parts. // of a line. // for BSD type sums parseChecksumLine guesses the hashing algorithm // by checking the length of the checksum.
[ "parseChecksumLine", "takes", "a", "line", "from", "a", "checksum", "file", "and", "returns", "checksumType", "checksumValue", "and", "filename", "parseChecksumLine", "guesses", "the", "style", "of", "the", "checksum", "BSD", "vs", "GNU", "by", "splitting", "the", "line", "and", "by", "counting", "the", "parts", ".", "of", "a", "line", ".", "for", "BSD", "type", "sums", "parseChecksumLine", "guesses", "the", "hashing", "algorithm", "by", "checking", "the", "length", "of", "the", "checksum", "." ]
69dec094fde6ac8d2659bff743fc0b2096ccb54f
https://github.com/hashicorp/go-getter/blob/69dec094fde6ac8d2659bff743fc0b2096ccb54f/checksum.go#L289-L314
train
yanzay/tbot
server.go
WithHTTPClient
func WithHTTPClient(client *http.Client) ServerOption { return func(s *Server) { s.httpClient = client } }
go
func WithHTTPClient(client *http.Client) ServerOption { return func(s *Server) { s.httpClient = client } }
[ "func", "WithHTTPClient", "(", "client", "*", "http", ".", "Client", ")", "ServerOption", "{", "return", "func", "(", "s", "*", "Server", ")", "{", "s", ".", "httpClient", "=", "client", "\n", "}", "\n", "}" ]
// WithHTTPClient sets custom http client for server.
[ "WithHTTPClient", "sets", "custom", "http", "client", "for", "server", "." ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/server.go#L99-L103
train
yanzay/tbot
server.go
Use
func (s *Server) Use(m Middleware) { s.middlewares = append(s.middlewares, m) }
go
func (s *Server) Use(m Middleware) { s.middlewares = append(s.middlewares, m) }
[ "func", "(", "s", "*", "Server", ")", "Use", "(", "m", "Middleware", ")", "{", "s", ".", "middlewares", "=", "append", "(", "s", ".", "middlewares", ",", "m", ")", "\n", "}" ]
// Use adds middleware to server
[ "Use", "adds", "middleware", "to", "server" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/server.go#L113-L115
train
yanzay/tbot
server.go
Start
func (s *Server) Start() error { if len(s.token) == 0 { return fmt.Errorf("token is empty") } updates, err := s.getUpdates() if err != nil { return err } for { select { case update := <-updates: handleUpdate := func(update *Update) { switch { case update.Message != nil: s.handleMessage(update.Message) case update.EditedMessage != nil: s.editMessageHandler(update.EditedMessage) case update.ChannelPost != nil: s.channelPostHandler(update.ChannelPost) case update.EditedChannelPost != nil: s.editChannelPostHandler(update.EditedChannelPost) case update.InlineQuery != nil: s.inlineQueryHandler(update.InlineQuery) case update.ChosenInlineResult != nil: s.inlineResultHandler(update.ChosenInlineResult) case update.CallbackQuery != nil: s.callbackHandler(update.CallbackQuery) case update.ShippingQuery != nil: s.shippingHandler(update.ShippingQuery) case update.PreCheckoutQuery != nil: s.preCheckoutHandler(update.PreCheckoutQuery) case update.Poll != nil: s.pollHandler(update.Poll) } } var f = handleUpdate for i := len(s.middlewares) - 1; i >= 0; i-- { f = s.middlewares[i](f) } go f(update) case <-s.stop: return nil } } }
go
func (s *Server) Start() error { if len(s.token) == 0 { return fmt.Errorf("token is empty") } updates, err := s.getUpdates() if err != nil { return err } for { select { case update := <-updates: handleUpdate := func(update *Update) { switch { case update.Message != nil: s.handleMessage(update.Message) case update.EditedMessage != nil: s.editMessageHandler(update.EditedMessage) case update.ChannelPost != nil: s.channelPostHandler(update.ChannelPost) case update.EditedChannelPost != nil: s.editChannelPostHandler(update.EditedChannelPost) case update.InlineQuery != nil: s.inlineQueryHandler(update.InlineQuery) case update.ChosenInlineResult != nil: s.inlineResultHandler(update.ChosenInlineResult) case update.CallbackQuery != nil: s.callbackHandler(update.CallbackQuery) case update.ShippingQuery != nil: s.shippingHandler(update.ShippingQuery) case update.PreCheckoutQuery != nil: s.preCheckoutHandler(update.PreCheckoutQuery) case update.Poll != nil: s.pollHandler(update.Poll) } } var f = handleUpdate for i := len(s.middlewares) - 1; i >= 0; i-- { f = s.middlewares[i](f) } go f(update) case <-s.stop: return nil } } }
[ "func", "(", "s", "*", "Server", ")", "Start", "(", ")", "error", "{", "if", "len", "(", "s", ".", "token", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "updates", ",", "err", ":=", "s", ".", "getUpdates", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "{", "select", "{", "case", "update", ":=", "<-", "updates", ":", "handleUpdate", ":=", "func", "(", "update", "*", "Update", ")", "{", "switch", "{", "case", "update", ".", "Message", "!=", "nil", ":", "s", ".", "handleMessage", "(", "update", ".", "Message", ")", "\n", "case", "update", ".", "EditedMessage", "!=", "nil", ":", "s", ".", "editMessageHandler", "(", "update", ".", "EditedMessage", ")", "\n", "case", "update", ".", "ChannelPost", "!=", "nil", ":", "s", ".", "channelPostHandler", "(", "update", ".", "ChannelPost", ")", "\n", "case", "update", ".", "EditedChannelPost", "!=", "nil", ":", "s", ".", "editChannelPostHandler", "(", "update", ".", "EditedChannelPost", ")", "\n", "case", "update", ".", "InlineQuery", "!=", "nil", ":", "s", ".", "inlineQueryHandler", "(", "update", ".", "InlineQuery", ")", "\n", "case", "update", ".", "ChosenInlineResult", "!=", "nil", ":", "s", ".", "inlineResultHandler", "(", "update", ".", "ChosenInlineResult", ")", "\n", "case", "update", ".", "CallbackQuery", "!=", "nil", ":", "s", ".", "callbackHandler", "(", "update", ".", "CallbackQuery", ")", "\n", "case", "update", ".", "ShippingQuery", "!=", "nil", ":", "s", ".", "shippingHandler", "(", "update", ".", "ShippingQuery", ")", "\n", "case", "update", ".", "PreCheckoutQuery", "!=", "nil", ":", "s", ".", "preCheckoutHandler", "(", "update", ".", "PreCheckoutQuery", ")", "\n", "case", "update", ".", "Poll", "!=", "nil", ":", "s", ".", "pollHandler", "(", "update", ".", "Poll", ")", "\n", "}", "\n", "}", "\n", "var", "f", "=", "handleUpdate", "\n", "for", "i", ":=", "len", "(", "s", ".", "middlewares", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "f", "=", "s", ".", "middlewares", "[", "i", "]", "(", "f", ")", "\n", "}", "\n", "go", "f", "(", "update", ")", "\n", "case", "<-", "s", ".", "stop", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Start listening for updates
[ "Start", "listening", "for", "updates" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/server.go#L118-L162
train
yanzay/tbot
server.go
HandleMessage
func (s *Server) HandleMessage(pattern string, handler func(*Message)) { rx := regexp.MustCompile(pattern) s.messageHandlers = append(s.messageHandlers, messageHandler{rx: rx, f: handler}) }
go
func (s *Server) HandleMessage(pattern string, handler func(*Message)) { rx := regexp.MustCompile(pattern) s.messageHandlers = append(s.messageHandlers, messageHandler{rx: rx, f: handler}) }
[ "func", "(", "s", "*", "Server", ")", "HandleMessage", "(", "pattern", "string", ",", "handler", "func", "(", "*", "Message", ")", ")", "{", "rx", ":=", "regexp", ".", "MustCompile", "(", "pattern", ")", "\n", "s", ".", "messageHandlers", "=", "append", "(", "s", ".", "messageHandlers", ",", "messageHandler", "{", "rx", ":", "rx", ",", "f", ":", "handler", "}", ")", "\n", "}" ]
// HandleMessage sets handler for incoming messages
[ "HandleMessage", "sets", "handler", "for", "incoming", "messages" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/server.go#L259-L262
train
yanzay/tbot
client.go
NewClient
func NewClient(token string, httpClient *http.Client, baseURL string) *Client { return &Client{ token: token, httpClient: httpClient, url: fmt.Sprintf("%s/bot%s/", baseURL, token) + "%s", } }
go
func NewClient(token string, httpClient *http.Client, baseURL string) *Client { return &Client{ token: token, httpClient: httpClient, url: fmt.Sprintf("%s/bot%s/", baseURL, token) + "%s", } }
[ "func", "NewClient", "(", "token", "string", ",", "httpClient", "*", "http", ".", "Client", ",", "baseURL", "string", ")", "*", "Client", "{", "return", "&", "Client", "{", "token", ":", "token", ",", "httpClient", ":", "httpClient", ",", "url", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "baseURL", ",", "token", ")", "+", "\"", "\"", ",", "}", "\n", "}" ]
// NewClient creates new Telegram API client
[ "NewClient", "creates", "new", "Telegram", "API", "client" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/client.go#L25-L31
train
yanzay/tbot
client.go
GetMe
func (c *Client) GetMe() (*User, error) { me := &User{} err := c.doRequest("getMe", nil, me) return me, err }
go
func (c *Client) GetMe() (*User, error) { me := &User{} err := c.doRequest("getMe", nil, me) return me, err }
[ "func", "(", "c", "*", "Client", ")", "GetMe", "(", ")", "(", "*", "User", ",", "error", ")", "{", "me", ":=", "&", "User", "{", "}", "\n", "err", ":=", "c", ".", "doRequest", "(", "\"", "\"", ",", "nil", ",", "me", ")", "\n", "return", "me", ",", "err", "\n", "}" ]
// GetMe returns info about bot as a User object
[ "GetMe", "returns", "info", "about", "bot", "as", "a", "User", "object" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/client.go#L64-L68
train
yanzay/tbot
client.go
SendMediaGroup
func (c *Client) SendMediaGroup(chatID string, media []InputMedia, opts ...sendOption) ([]*Message, error) { req := url.Values{} req.Set("chat_id", chatID) m, _ := json.Marshal(media) req.Set("media", string(m)) for _, opt := range opts { opt(req) } var msgs []*Message err := c.doRequest("sendMediaGroup", req, &msgs) return msgs, err }
go
func (c *Client) SendMediaGroup(chatID string, media []InputMedia, opts ...sendOption) ([]*Message, error) { req := url.Values{} req.Set("chat_id", chatID) m, _ := json.Marshal(media) req.Set("media", string(m)) for _, opt := range opts { opt(req) } var msgs []*Message err := c.doRequest("sendMediaGroup", req, &msgs) return msgs, err }
[ "func", "(", "c", "*", "Client", ")", "SendMediaGroup", "(", "chatID", "string", ",", "media", "[", "]", "InputMedia", ",", "opts", "...", "sendOption", ")", "(", "[", "]", "*", "Message", ",", "error", ")", "{", "req", ":=", "url", ".", "Values", "{", "}", "\n", "req", ".", "Set", "(", "\"", "\"", ",", "chatID", ")", "\n", "m", ",", "_", ":=", "json", ".", "Marshal", "(", "media", ")", "\n", "req", ".", "Set", "(", "\"", "\"", ",", "string", "(", "m", ")", ")", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "req", ")", "\n", "}", "\n", "var", "msgs", "[", "]", "*", "Message", "\n", "err", ":=", "c", ".", "doRequest", "(", "\"", "\"", ",", "req", ",", "&", "msgs", ")", "\n", "return", "msgs", ",", "err", "\n", "}" ]
// SendMediaGroup send a group of photos or videos as an album
[ "SendMediaGroup", "send", "a", "group", "of", "photos", "or", "videos", "as", "an", "album" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/client.go#L699-L710
train
yanzay/tbot
helpers.go
Buttons
func Buttons(buttons [][]string) *ReplyKeyboardMarkup { keyboard := make([][]KeyboardButton, len(buttons)) for i := range buttons { keyboard[i] = make([]KeyboardButton, len(buttons[i])) for j := range buttons[i] { keyboard[i][j] = KeyboardButton{Text: buttons[i][j]} } } return &ReplyKeyboardMarkup{Keyboard: keyboard} }
go
func Buttons(buttons [][]string) *ReplyKeyboardMarkup { keyboard := make([][]KeyboardButton, len(buttons)) for i := range buttons { keyboard[i] = make([]KeyboardButton, len(buttons[i])) for j := range buttons[i] { keyboard[i][j] = KeyboardButton{Text: buttons[i][j]} } } return &ReplyKeyboardMarkup{Keyboard: keyboard} }
[ "func", "Buttons", "(", "buttons", "[", "]", "[", "]", "string", ")", "*", "ReplyKeyboardMarkup", "{", "keyboard", ":=", "make", "(", "[", "]", "[", "]", "KeyboardButton", ",", "len", "(", "buttons", ")", ")", "\n", "for", "i", ":=", "range", "buttons", "{", "keyboard", "[", "i", "]", "=", "make", "(", "[", "]", "KeyboardButton", ",", "len", "(", "buttons", "[", "i", "]", ")", ")", "\n", "for", "j", ":=", "range", "buttons", "[", "i", "]", "{", "keyboard", "[", "i", "]", "[", "j", "]", "=", "KeyboardButton", "{", "Text", ":", "buttons", "[", "i", "]", "[", "j", "]", "}", "\n", "}", "\n", "}", "\n", "return", "&", "ReplyKeyboardMarkup", "{", "Keyboard", ":", "keyboard", "}", "\n", "}" ]
// Buttons construct ReplyKeyboardMarkup from strings
[ "Buttons", "construct", "ReplyKeyboardMarkup", "from", "strings" ]
f0e9ff0b2e656aa7e3348a3ef59e568d87538c77
https://github.com/yanzay/tbot/blob/f0e9ff0b2e656aa7e3348a3ef59e568d87538c77/helpers.go#L4-L13
train
uber/ringpop-go
swim/gossip.go
newGossip
func newGossip(node *Node, minProtocolPeriod time.Duration) *gossip { gossip := &gossip{ node: node, minProtocolPeriod: minProtocolPeriod, logger: logging.Logger("gossip").WithField("local", node.Address()), } gossip.protocol.timing = metrics.NewHistogram(metrics.NewUniformSample(10)) gossip.protocol.timing.Update(int64(gossip.minProtocolPeriod)) return gossip }
go
func newGossip(node *Node, minProtocolPeriod time.Duration) *gossip { gossip := &gossip{ node: node, minProtocolPeriod: minProtocolPeriod, logger: logging.Logger("gossip").WithField("local", node.Address()), } gossip.protocol.timing = metrics.NewHistogram(metrics.NewUniformSample(10)) gossip.protocol.timing.Update(int64(gossip.minProtocolPeriod)) return gossip }
[ "func", "newGossip", "(", "node", "*", "Node", ",", "minProtocolPeriod", "time", ".", "Duration", ")", "*", "gossip", "{", "gossip", ":=", "&", "gossip", "{", "node", ":", "node", ",", "minProtocolPeriod", ":", "minProtocolPeriod", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "node", ".", "Address", "(", ")", ")", ",", "}", "\n\n", "gossip", ".", "protocol", ".", "timing", "=", "metrics", ".", "NewHistogram", "(", "metrics", ".", "NewUniformSample", "(", "10", ")", ")", "\n", "gossip", ".", "protocol", ".", "timing", ".", "Update", "(", "int64", "(", "gossip", ".", "minProtocolPeriod", ")", ")", "\n\n", "return", "gossip", "\n", "}" ]
// newGossip returns a new gossip SWIM sub-protocol with the given protocol period
[ "newGossip", "returns", "a", "new", "gossip", "SWIM", "sub", "-", "protocol", "with", "the", "given", "protocol", "period" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L62-L73
train
uber/ringpop-go
swim/gossip.go
ComputeProtocolDelay
func (g *gossip) ComputeProtocolDelay() time.Duration { g.protocol.RLock() defer g.protocol.RUnlock() var delay time.Duration if g.protocol.numPeriods != 0 { target := g.protocol.lastPeriod.Add(g.protocol.lastRate) delay = time.Duration(math.Max(float64(target.Sub(time.Now())), float64(g.minProtocolPeriod))) } else { // delay for first tick in [0, minProtocolPeriod]ms delay = time.Duration(rand.Intn(int(g.minProtocolPeriod + 1))) } g.node.EmitEvent(ProtocolDelayComputeEvent{ Duration: delay, }) return delay }
go
func (g *gossip) ComputeProtocolDelay() time.Duration { g.protocol.RLock() defer g.protocol.RUnlock() var delay time.Duration if g.protocol.numPeriods != 0 { target := g.protocol.lastPeriod.Add(g.protocol.lastRate) delay = time.Duration(math.Max(float64(target.Sub(time.Now())), float64(g.minProtocolPeriod))) } else { // delay for first tick in [0, minProtocolPeriod]ms delay = time.Duration(rand.Intn(int(g.minProtocolPeriod + 1))) } g.node.EmitEvent(ProtocolDelayComputeEvent{ Duration: delay, }) return delay }
[ "func", "(", "g", "*", "gossip", ")", "ComputeProtocolDelay", "(", ")", "time", ".", "Duration", "{", "g", ".", "protocol", ".", "RLock", "(", ")", "\n", "defer", "g", ".", "protocol", ".", "RUnlock", "(", ")", "\n\n", "var", "delay", "time", ".", "Duration", "\n\n", "if", "g", ".", "protocol", ".", "numPeriods", "!=", "0", "{", "target", ":=", "g", ".", "protocol", ".", "lastPeriod", ".", "Add", "(", "g", ".", "protocol", ".", "lastRate", ")", "\n", "delay", "=", "time", ".", "Duration", "(", "math", ".", "Max", "(", "float64", "(", "target", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", ")", ",", "float64", "(", "g", ".", "minProtocolPeriod", ")", ")", ")", "\n", "}", "else", "{", "// delay for first tick in [0, minProtocolPeriod]ms", "delay", "=", "time", ".", "Duration", "(", "rand", ".", "Intn", "(", "int", "(", "g", ".", "minProtocolPeriod", "+", "1", ")", ")", ")", "\n", "}", "\n\n", "g", ".", "node", ".", "EmitEvent", "(", "ProtocolDelayComputeEvent", "{", "Duration", ":", "delay", ",", "}", ")", "\n", "return", "delay", "\n", "}" ]
// computes a delay for the gossip protocol period
[ "computes", "a", "delay", "for", "the", "gossip", "protocol", "period" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L76-L94
train
uber/ringpop-go
swim/gossip.go
AdjustProtocolRate
func (g *gossip) AdjustProtocolRate() { g.protocol.Lock() observed := g.protocol.timing.Percentile(0.5) * 2.0 g.protocol.lastRate = time.Duration(math.Max(observed, float64(g.minProtocolPeriod))) g.protocol.Unlock() }
go
func (g *gossip) AdjustProtocolRate() { g.protocol.Lock() observed := g.protocol.timing.Percentile(0.5) * 2.0 g.protocol.lastRate = time.Duration(math.Max(observed, float64(g.minProtocolPeriod))) g.protocol.Unlock() }
[ "func", "(", "g", "*", "gossip", ")", "AdjustProtocolRate", "(", ")", "{", "g", ".", "protocol", ".", "Lock", "(", ")", "\n", "observed", ":=", "g", ".", "protocol", ".", "timing", ".", "Percentile", "(", "0.5", ")", "*", "2.0", "\n", "g", ".", "protocol", ".", "lastRate", "=", "time", ".", "Duration", "(", "math", ".", "Max", "(", "observed", ",", "float64", "(", "g", ".", "minProtocolPeriod", ")", ")", ")", "\n", "g", ".", "protocol", ".", "Unlock", "(", ")", "\n", "}" ]
// computes a ProtocolRate for the Gossip
[ "computes", "a", "ProtocolRate", "for", "the", "Gossip" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L105-L110
train
uber/ringpop-go
swim/gossip.go
Start
func (g *gossip) Start() { g.state.Lock() defer g.state.Unlock() if g.state.running { g.logger.Warn("gossip already started") return } // mark the state to be running g.state.running = true // schedule repeat execution in the background g.state.protocolPeriodStop, g.state.protocolPeriodWait = scheduleRepeaditly(g.ProtocolPeriod, g.ComputeProtocolDelay, g.node.clock) g.state.protocolRateChannel, _ = scheduleRepeaditly(g.AdjustProtocolRate, func() time.Duration { return time.Second }, g.node.clock) g.logger.Debug("started gossip protocol") }
go
func (g *gossip) Start() { g.state.Lock() defer g.state.Unlock() if g.state.running { g.logger.Warn("gossip already started") return } // mark the state to be running g.state.running = true // schedule repeat execution in the background g.state.protocolPeriodStop, g.state.protocolPeriodWait = scheduleRepeaditly(g.ProtocolPeriod, g.ComputeProtocolDelay, g.node.clock) g.state.protocolRateChannel, _ = scheduleRepeaditly(g.AdjustProtocolRate, func() time.Duration { return time.Second }, g.node.clock) g.logger.Debug("started gossip protocol") }
[ "func", "(", "g", "*", "gossip", ")", "Start", "(", ")", "{", "g", ".", "state", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "state", ".", "Unlock", "(", ")", "\n\n", "if", "g", ".", "state", ".", "running", "{", "g", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "// mark the state to be running", "g", ".", "state", ".", "running", "=", "true", "\n\n", "// schedule repeat execution in the background", "g", ".", "state", ".", "protocolPeriodStop", ",", "g", ".", "state", ".", "protocolPeriodWait", "=", "scheduleRepeaditly", "(", "g", ".", "ProtocolPeriod", ",", "g", ".", "ComputeProtocolDelay", ",", "g", ".", "node", ".", "clock", ")", "\n", "g", ".", "state", ".", "protocolRateChannel", ",", "_", "=", "scheduleRepeaditly", "(", "g", ".", "AdjustProtocolRate", ",", "func", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Second", "\n", "}", ",", "g", ".", "node", ".", "clock", ")", "\n\n", "g", ".", "logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "}" ]
// start the gossip protocol
[ "start", "the", "gossip", "protocol" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L121-L140
train
uber/ringpop-go
swim/gossip.go
Stop
func (g *gossip) Stop() { g.state.Lock() defer g.state.Unlock() if !g.state.running { g.logger.Warn("gossip already stopped") return } g.state.running = false // stop background execution of running tasks close(g.state.protocolPeriodStop) close(g.state.protocolRateChannel) // wait for the goroutine to be stopped _ = <-g.state.protocolPeriodWait g.logger.Debug("stopped gossip protocol") }
go
func (g *gossip) Stop() { g.state.Lock() defer g.state.Unlock() if !g.state.running { g.logger.Warn("gossip already stopped") return } g.state.running = false // stop background execution of running tasks close(g.state.protocolPeriodStop) close(g.state.protocolRateChannel) // wait for the goroutine to be stopped _ = <-g.state.protocolPeriodWait g.logger.Debug("stopped gossip protocol") }
[ "func", "(", "g", "*", "gossip", ")", "Stop", "(", ")", "{", "g", ".", "state", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "state", ".", "Unlock", "(", ")", "\n\n", "if", "!", "g", ".", "state", ".", "running", "{", "g", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "g", ".", "state", ".", "running", "=", "false", "\n\n", "// stop background execution of running tasks", "close", "(", "g", ".", "state", ".", "protocolPeriodStop", ")", "\n", "close", "(", "g", ".", "state", ".", "protocolRateChannel", ")", "\n\n", "// wait for the goroutine to be stopped", "_", "=", "<-", "g", ".", "state", ".", "protocolPeriodWait", "\n\n", "g", ".", "logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "}" ]
// stop the gossip protocol
[ "stop", "the", "gossip", "protocol" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L143-L162
train
uber/ringpop-go
swim/gossip.go
Stopped
func (g *gossip) Stopped() bool { g.state.RLock() stopped := !g.state.running g.state.RUnlock() return stopped }
go
func (g *gossip) Stopped() bool { g.state.RLock() stopped := !g.state.running g.state.RUnlock() return stopped }
[ "func", "(", "g", "*", "gossip", ")", "Stopped", "(", ")", "bool", "{", "g", ".", "state", ".", "RLock", "(", ")", "\n", "stopped", ":=", "!", "g", ".", "state", ".", "running", "\n", "g", ".", "state", ".", "RUnlock", "(", ")", "\n\n", "return", "stopped", "\n", "}" ]
// returns whether or not the gossip sub-protocol is stopped
[ "returns", "whether", "or", "not", "the", "gossip", "sub", "-", "protocol", "is", "stopped" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L165-L171
train
uber/ringpop-go
swim/gossip.go
ProtocolPeriod
func (g *gossip) ProtocolPeriod() { startTime := time.Now() g.node.pingNextMember() endTime := time.Now() g.protocol.Lock() lag := endTime.Sub(g.protocol.lastPeriod) wasFirst := (g.protocol.numPeriods == 0) g.protocol.lastPeriod = endTime g.protocol.numPeriods++ g.protocol.timing.Update(int64(time.Now().Sub(startTime))) g.protocol.Unlock() if !wasFirst { g.node.EmitEvent(ProtocolFrequencyEvent{ Duration: lag, }) } }
go
func (g *gossip) ProtocolPeriod() { startTime := time.Now() g.node.pingNextMember() endTime := time.Now() g.protocol.Lock() lag := endTime.Sub(g.protocol.lastPeriod) wasFirst := (g.protocol.numPeriods == 0) g.protocol.lastPeriod = endTime g.protocol.numPeriods++ g.protocol.timing.Update(int64(time.Now().Sub(startTime))) g.protocol.Unlock() if !wasFirst { g.node.EmitEvent(ProtocolFrequencyEvent{ Duration: lag, }) } }
[ "func", "(", "g", "*", "gossip", ")", "ProtocolPeriod", "(", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "g", ".", "node", ".", "pingNextMember", "(", ")", "\n", "endTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "g", ".", "protocol", ".", "Lock", "(", ")", "\n\n", "lag", ":=", "endTime", ".", "Sub", "(", "g", ".", "protocol", ".", "lastPeriod", ")", "\n", "wasFirst", ":=", "(", "g", ".", "protocol", ".", "numPeriods", "==", "0", ")", "\n\n", "g", ".", "protocol", ".", "lastPeriod", "=", "endTime", "\n", "g", ".", "protocol", ".", "numPeriods", "++", "\n", "g", ".", "protocol", ".", "timing", ".", "Update", "(", "int64", "(", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ")", ")", "\n", "g", ".", "protocol", ".", "Unlock", "(", ")", "\n\n", "if", "!", "wasFirst", "{", "g", ".", "node", ".", "EmitEvent", "(", "ProtocolFrequencyEvent", "{", "Duration", ":", "lag", ",", "}", ")", "\n", "}", "\n", "}" ]
// run a gossip protocol period
[ "run", "a", "gossip", "protocol", "period" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/gossip.go#L174-L195
train
uber/ringpop-go
logging/facility.go
NewFacility
func NewFacility(log bark.Logger) *Facility { if log == nil { log = NoLogger } return &Facility{ logger: log, levels: make(map[string]Level), } }
go
func NewFacility(log bark.Logger) *Facility { if log == nil { log = NoLogger } return &Facility{ logger: log, levels: make(map[string]Level), } }
[ "func", "NewFacility", "(", "log", "bark", ".", "Logger", ")", "*", "Facility", "{", "if", "log", "==", "nil", "{", "log", "=", "NoLogger", "\n", "}", "\n", "return", "&", "Facility", "{", "logger", ":", "log", ",", "levels", ":", "make", "(", "map", "[", "string", "]", "Level", ")", ",", "}", "\n", "}" ]
// NewFacility creates a new log facility with the specified logger as the // underlying logger. If no logger is passed, a no-op implementation is used.
[ "NewFacility", "creates", "a", "new", "log", "facility", "with", "the", "specified", "logger", "as", "the", "underlying", "logger", ".", "If", "no", "logger", "is", "passed", "a", "no", "-", "op", "implementation", "is", "used", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L41-L49
train
uber/ringpop-go
logging/facility.go
SetLevels
func (f *Facility) SetLevels(levels map[string]Level) error { for logName, level := range levels { if level < Fatal { return fmt.Errorf("cannot set a level above %s for %s", Fatal, logName) } } // Prevent changing levels while a message is logged. f.mu.Lock() defer f.mu.Unlock() for logName, level := range levels { f.levels[logName] = level } return nil }
go
func (f *Facility) SetLevels(levels map[string]Level) error { for logName, level := range levels { if level < Fatal { return fmt.Errorf("cannot set a level above %s for %s", Fatal, logName) } } // Prevent changing levels while a message is logged. f.mu.Lock() defer f.mu.Unlock() for logName, level := range levels { f.levels[logName] = level } return nil }
[ "func", "(", "f", "*", "Facility", ")", "SetLevels", "(", "levels", "map", "[", "string", "]", "Level", ")", "error", "{", "for", "logName", ",", "level", ":=", "range", "levels", "{", "if", "level", "<", "Fatal", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "Fatal", ",", "logName", ")", "\n", "}", "\n", "}", "\n", "// Prevent changing levels while a message is logged.", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "logName", ",", "level", ":=", "range", "levels", "{", "f", ".", "levels", "[", "logName", "]", "=", "level", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetLevels is like SetLevel but for multiple named loggers.
[ "SetLevels", "is", "like", "SetLevel", "but", "for", "multiple", "named", "loggers", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L52-L65
train
uber/ringpop-go
logging/facility.go
SetLogger
func (f *Facility) SetLogger(log bark.Logger) { // Prevent changing the logger while a message is logged. f.mu.Lock() defer f.mu.Unlock() if log == nil { log = NoLogger } f.logger = log }
go
func (f *Facility) SetLogger(log bark.Logger) { // Prevent changing the logger while a message is logged. f.mu.Lock() defer f.mu.Unlock() if log == nil { log = NoLogger } f.logger = log }
[ "func", "(", "f", "*", "Facility", ")", "SetLogger", "(", "log", "bark", ".", "Logger", ")", "{", "// Prevent changing the logger while a message is logged.", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "log", "==", "nil", "{", "log", "=", "NoLogger", "\n", "}", "\n", "f", ".", "logger", "=", "log", "\n", "}" ]
// SetLogger sets the underlying logger. All log messages produced, that are // not silenced, are propagated to this logger.
[ "SetLogger", "sets", "the", "underlying", "logger", ".", "All", "log", "messages", "produced", "that", "are", "not", "silenced", "are", "propagated", "to", "this", "logger", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L87-L95
train
uber/ringpop-go
logging/facility.go
Logger
func (f *Facility) Logger(logName string) bark.Logger { return &namedLogger{ name: logName, forwardTo: f, } }
go
func (f *Facility) Logger(logName string) bark.Logger { return &namedLogger{ name: logName, forwardTo: f, } }
[ "func", "(", "f", "*", "Facility", ")", "Logger", "(", "logName", "string", ")", "bark", ".", "Logger", "{", "return", "&", "namedLogger", "{", "name", ":", "logName", ",", "forwardTo", ":", "f", ",", "}", "\n\n", "}" ]
// Logger returns a new named logger.
[ "Logger", "returns", "a", "new", "named", "logger", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L98-L104
train
uber/ringpop-go
logging/facility.go
Log
func (f *Facility) Log(logName string, wantLevel Level, fields bark.Fields, msg []interface{}) { f.mu.RLock() defer f.mu.RUnlock() if setLevel, ok := f.levels[logName]; ok { // For me this is confusing, so here's a clarification. // The levels are consecutive integers starting from 0 defined in this order: // Panic=0, Fatal=1, Error=2, Warning=3, etc... // For the condition to make more sense, consider a named // logger set to Fatal and an incoming Error message. if setLevel < wantLevel { return } } logger := f.logger // If there are any fields, apply them. if len(fields) > 0 { logger = logger.WithFields(fields) } switch wantLevel { case Debug: logger.Debug(msg...) case Info: logger.Info(msg...) case Warn: logger.Warn(msg...) case Error: logger.Error(msg...) case Fatal: logger.Fatal(msg...) case Panic: logger.Panic(msg...) } }
go
func (f *Facility) Log(logName string, wantLevel Level, fields bark.Fields, msg []interface{}) { f.mu.RLock() defer f.mu.RUnlock() if setLevel, ok := f.levels[logName]; ok { // For me this is confusing, so here's a clarification. // The levels are consecutive integers starting from 0 defined in this order: // Panic=0, Fatal=1, Error=2, Warning=3, etc... // For the condition to make more sense, consider a named // logger set to Fatal and an incoming Error message. if setLevel < wantLevel { return } } logger := f.logger // If there are any fields, apply them. if len(fields) > 0 { logger = logger.WithFields(fields) } switch wantLevel { case Debug: logger.Debug(msg...) case Info: logger.Info(msg...) case Warn: logger.Warn(msg...) case Error: logger.Error(msg...) case Fatal: logger.Fatal(msg...) case Panic: logger.Panic(msg...) } }
[ "func", "(", "f", "*", "Facility", ")", "Log", "(", "logName", "string", ",", "wantLevel", "Level", ",", "fields", "bark", ".", "Fields", ",", "msg", "[", "]", "interface", "{", "}", ")", "{", "f", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "setLevel", ",", "ok", ":=", "f", ".", "levels", "[", "logName", "]", ";", "ok", "{", "// For me this is confusing, so here's a clarification.", "// The levels are consecutive integers starting from 0 defined in this order:", "// Panic=0, Fatal=1, Error=2, Warning=3, etc...", "// For the condition to make more sense, consider a named", "// logger set to Fatal and an incoming Error message.", "if", "setLevel", "<", "wantLevel", "{", "return", "\n", "}", "\n", "}", "\n", "logger", ":=", "f", ".", "logger", "\n", "// If there are any fields, apply them.", "if", "len", "(", "fields", ")", ">", "0", "{", "logger", "=", "logger", ".", "WithFields", "(", "fields", ")", "\n", "}", "\n", "switch", "wantLevel", "{", "case", "Debug", ":", "logger", ".", "Debug", "(", "msg", "...", ")", "\n", "case", "Info", ":", "logger", ".", "Info", "(", "msg", "...", ")", "\n", "case", "Warn", ":", "logger", ".", "Warn", "(", "msg", "...", ")", "\n", "case", "Error", ":", "logger", ".", "Error", "(", "msg", "...", ")", "\n", "case", "Fatal", ":", "logger", ".", "Fatal", "(", "msg", "...", ")", "\n", "case", "Panic", ":", "logger", ".", "Panic", "(", "msg", "...", ")", "\n", "}", "\n", "}" ]
// Log logs messages with a severity level equal to or higher than the one set // with SetLevel. If that's not the case, the message is silenced. // If the logName was not previously configured with SetLevel, the messages are // never silenced. // Instead on using this method directly, one can call Logger method to get a // bark.Logger instance bound to a specific name.
[ "Log", "logs", "messages", "with", "a", "severity", "level", "equal", "to", "or", "higher", "than", "the", "one", "set", "with", "SetLevel", ".", "If", "that", "s", "not", "the", "case", "the", "message", "is", "silenced", ".", "If", "the", "logName", "was", "not", "previously", "configured", "with", "SetLevel", "the", "messages", "are", "never", "silenced", ".", "Instead", "on", "using", "this", "method", "directly", "one", "can", "call", "Logger", "method", "to", "get", "a", "bark", ".", "Logger", "instance", "bound", "to", "a", "specific", "name", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L112-L144
train
uber/ringpop-go
logging/facility.go
Logf
func (f *Facility) Logf(logName string, wantLevel Level, fields bark.Fields, format string, msg []interface{}) { f.mu.RLock() defer f.mu.RUnlock() if setLevel, ok := f.levels[logName]; ok { if setLevel < wantLevel { return } } logger := f.logger if len(fields) > 0 { logger = logger.WithFields(fields) } switch wantLevel { case Debug: logger.Debugf(format, msg...) case Info: logger.Infof(format, msg...) case Warn: logger.Warnf(format, msg...) case Error: logger.Errorf(format, msg...) case Fatal: logger.Fatalf(format, msg...) case Panic: logger.Panicf(format, msg...) } }
go
func (f *Facility) Logf(logName string, wantLevel Level, fields bark.Fields, format string, msg []interface{}) { f.mu.RLock() defer f.mu.RUnlock() if setLevel, ok := f.levels[logName]; ok { if setLevel < wantLevel { return } } logger := f.logger if len(fields) > 0 { logger = logger.WithFields(fields) } switch wantLevel { case Debug: logger.Debugf(format, msg...) case Info: logger.Infof(format, msg...) case Warn: logger.Warnf(format, msg...) case Error: logger.Errorf(format, msg...) case Fatal: logger.Fatalf(format, msg...) case Panic: logger.Panicf(format, msg...) } }
[ "func", "(", "f", "*", "Facility", ")", "Logf", "(", "logName", "string", ",", "wantLevel", "Level", ",", "fields", "bark", ".", "Fields", ",", "format", "string", ",", "msg", "[", "]", "interface", "{", "}", ")", "{", "f", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "setLevel", ",", "ok", ":=", "f", ".", "levels", "[", "logName", "]", ";", "ok", "{", "if", "setLevel", "<", "wantLevel", "{", "return", "\n", "}", "\n", "}", "\n", "logger", ":=", "f", ".", "logger", "\n", "if", "len", "(", "fields", ")", ">", "0", "{", "logger", "=", "logger", ".", "WithFields", "(", "fields", ")", "\n", "}", "\n", "switch", "wantLevel", "{", "case", "Debug", ":", "logger", ".", "Debugf", "(", "format", ",", "msg", "...", ")", "\n", "case", "Info", ":", "logger", ".", "Infof", "(", "format", ",", "msg", "...", ")", "\n", "case", "Warn", ":", "logger", ".", "Warnf", "(", "format", ",", "msg", "...", ")", "\n", "case", "Error", ":", "logger", ".", "Errorf", "(", "format", ",", "msg", "...", ")", "\n", "case", "Fatal", ":", "logger", ".", "Fatalf", "(", "format", ",", "msg", "...", ")", "\n", "case", "Panic", ":", "logger", ".", "Panicf", "(", "format", ",", "msg", "...", ")", "\n", "}", "\n", "}" ]
// Logf is the same as Log but with fmt.Printf-like formatting
[ "Logf", "is", "the", "same", "as", "Log", "but", "with", "fmt", ".", "Printf", "-", "like", "formatting" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/logging/facility.go#L147-L173
train
uber/ringpop-go
swim/member_predicate.go
MemberMatchesPredicates
func MemberMatchesPredicates(member Member, predicates ...MemberPredicate) bool { for _, p := range predicates { if !p(member) { return false } } return true }
go
func MemberMatchesPredicates(member Member, predicates ...MemberPredicate) bool { for _, p := range predicates { if !p(member) { return false } } return true }
[ "func", "MemberMatchesPredicates", "(", "member", "Member", ",", "predicates", "...", "MemberPredicate", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "predicates", "{", "if", "!", "p", "(", "member", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// MemberMatchesPredicates can take multiple predicates and test them against a // member returning if the member satisfies all the predicates. This means that // if one test fails it will stop executing and return with false.
[ "MemberMatchesPredicates", "can", "take", "multiple", "predicates", "and", "test", "them", "against", "a", "member", "returning", "if", "the", "member", "satisfies", "all", "the", "predicates", ".", "This", "means", "that", "if", "one", "test", "fails", "it", "will", "stop", "executing", "and", "return", "with", "false", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member_predicate.go#L12-L19
train
uber/ringpop-go
swim/member_predicate.go
MemberWithLabelAndValue
func MemberWithLabelAndValue(key, value string) MemberPredicate { return func(member Member) bool { v, ok := member.Labels[key] if !ok { return false } // test if the values match return v == value } }
go
func MemberWithLabelAndValue(key, value string) MemberPredicate { return func(member Member) bool { v, ok := member.Labels[key] if !ok { return false } // test if the values match return v == value } }
[ "func", "MemberWithLabelAndValue", "(", "key", ",", "value", "string", ")", "MemberPredicate", "{", "return", "func", "(", "member", "Member", ")", "bool", "{", "v", ",", "ok", ":=", "member", ".", "Labels", "[", "key", "]", "\n\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// test if the values match", "return", "v", "==", "value", "\n", "}", "\n", "}" ]
// MemberWithLabelAndValue returns a predicate able to test if the value of a // label on a member is equal to the provided value.
[ "MemberWithLabelAndValue", "returns", "a", "predicate", "able", "to", "test", "if", "the", "value", "of", "a", "label", "on", "a", "member", "is", "equal", "to", "the", "provided", "value", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member_predicate.go#L32-L43
train
uber/ringpop-go
shared/shared.go
NewTChannelContext
func NewTChannelContext(timeout time.Duration) (tchannel.ContextWithHeaders, context.CancelFunc) { return tchannel.NewContextBuilder(timeout). DisableTracing(). SetRetryOptions(retryOptions). Build() }
go
func NewTChannelContext(timeout time.Duration) (tchannel.ContextWithHeaders, context.CancelFunc) { return tchannel.NewContextBuilder(timeout). DisableTracing(). SetRetryOptions(retryOptions). Build() }
[ "func", "NewTChannelContext", "(", "timeout", "time", ".", "Duration", ")", "(", "tchannel", ".", "ContextWithHeaders", ",", "context", ".", "CancelFunc", ")", "{", "return", "tchannel", ".", "NewContextBuilder", "(", "timeout", ")", ".", "DisableTracing", "(", ")", ".", "SetRetryOptions", "(", "retryOptions", ")", ".", "Build", "(", ")", "\n", "}" ]
// NewTChannelContext creates a new TChannel context with default options // suitable for use in Ringpop.
[ "NewTChannelContext", "creates", "a", "new", "TChannel", "context", "with", "default", "options", "suitable", "for", "use", "in", "Ringpop", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/shared/shared.go#L17-L22
train
uber/ringpop-go
swim/disseminator.go
newDisseminator
func newDisseminator(n *Node) *disseminator { d := &disseminator{ node: n, changes: make(map[string]*pChange), maxP: defaultPFactor, pFactor: defaultPFactor, logger: logging.Logger("disseminator").WithField("local", n.Address()), reverseFullSyncJobs: make(chan struct{}, n.maxReverseFullSyncJobs), } return d }
go
func newDisseminator(n *Node) *disseminator { d := &disseminator{ node: n, changes: make(map[string]*pChange), maxP: defaultPFactor, pFactor: defaultPFactor, logger: logging.Logger("disseminator").WithField("local", n.Address()), reverseFullSyncJobs: make(chan struct{}, n.maxReverseFullSyncJobs), } return d }
[ "func", "newDisseminator", "(", "n", "*", "Node", ")", "*", "disseminator", "{", "d", ":=", "&", "disseminator", "{", "node", ":", "n", ",", "changes", ":", "make", "(", "map", "[", "string", "]", "*", "pChange", ")", ",", "maxP", ":", "defaultPFactor", ",", "pFactor", ":", "defaultPFactor", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "n", ".", "Address", "(", ")", ")", ",", "reverseFullSyncJobs", ":", "make", "(", "chan", "struct", "{", "}", ",", "n", ".", "maxReverseFullSyncJobs", ")", ",", "}", "\n\n", "return", "d", "\n", "}" ]
// newDisseminator returns a new Disseminator instance.
[ "newDisseminator", "returns", "a", "new", "Disseminator", "instance", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L62-L73
train
uber/ringpop-go
swim/disseminator.go
HasChanges
func (d *disseminator) HasChanges() bool { d.RLock() result := len(d.changes) > 0 d.RUnlock() return result }
go
func (d *disseminator) HasChanges() bool { d.RLock() result := len(d.changes) > 0 d.RUnlock() return result }
[ "func", "(", "d", "*", "disseminator", ")", "HasChanges", "(", ")", "bool", "{", "d", ".", "RLock", "(", ")", "\n", "result", ":=", "len", "(", "d", ".", "changes", ")", ">", "0", "\n", "d", ".", "RUnlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// HasChanges reports whether disseminator has changes to disseminate.
[ "HasChanges", "reports", "whether", "disseminator", "has", "changes", "to", "disseminate", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L100-L105
train
uber/ringpop-go
swim/disseminator.go
IssueAsSender
func (d *disseminator) IssueAsSender() (changes []Change, bumpPiggybackCounters func()) { changes = d.issueChanges() return changes, func() { d.bumpPiggybackCounters(changes) } }
go
func (d *disseminator) IssueAsSender() (changes []Change, bumpPiggybackCounters func()) { changes = d.issueChanges() return changes, func() { d.bumpPiggybackCounters(changes) } }
[ "func", "(", "d", "*", "disseminator", ")", "IssueAsSender", "(", ")", "(", "changes", "[", "]", "Change", ",", "bumpPiggybackCounters", "func", "(", ")", ")", "{", "changes", "=", "d", ".", "issueChanges", "(", ")", "\n", "return", "changes", ",", "func", "(", ")", "{", "d", ".", "bumpPiggybackCounters", "(", "changes", ")", "\n", "}", "\n", "}" ]
// IssueAsSender collects all changes a node needs when sending a ping or // ping-req. The second return value is a callback that raises the piggyback // counters of the given changes.
[ "IssueAsSender", "collects", "all", "changes", "a", "node", "needs", "when", "sending", "a", "ping", "or", "ping", "-", "req", ".", "The", "second", "return", "value", "is", "a", "callback", "that", "raises", "the", "piggyback", "counters", "of", "the", "given", "changes", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L127-L132
train
uber/ringpop-go
swim/disseminator.go
IssueAsReceiver
func (d *disseminator) IssueAsReceiver( senderAddress string, senderIncarnation int64, senderChecksum uint32) (changes []Change, fullSync bool) { changes = d.issueChanges() // filter out changes that came from the sender previously changes = d.filterChangesFromSender(changes, senderAddress, senderIncarnation) d.bumpPiggybackCounters(changes) if len(changes) > 0 || d.node.memberlist.Checksum() == senderChecksum { return changes, false } d.node.EmitEvent(FullSyncEvent{senderAddress, senderChecksum}) d.node.logger.WithFields(log.Fields{ "localChecksum": d.node.memberlist.Checksum(), "remote": senderAddress, "remoteChecksum": senderChecksum, }).Info("full sync") return d.MembershipAsChanges(), true }
go
func (d *disseminator) IssueAsReceiver( senderAddress string, senderIncarnation int64, senderChecksum uint32) (changes []Change, fullSync bool) { changes = d.issueChanges() // filter out changes that came from the sender previously changes = d.filterChangesFromSender(changes, senderAddress, senderIncarnation) d.bumpPiggybackCounters(changes) if len(changes) > 0 || d.node.memberlist.Checksum() == senderChecksum { return changes, false } d.node.EmitEvent(FullSyncEvent{senderAddress, senderChecksum}) d.node.logger.WithFields(log.Fields{ "localChecksum": d.node.memberlist.Checksum(), "remote": senderAddress, "remoteChecksum": senderChecksum, }).Info("full sync") return d.MembershipAsChanges(), true }
[ "func", "(", "d", "*", "disseminator", ")", "IssueAsReceiver", "(", "senderAddress", "string", ",", "senderIncarnation", "int64", ",", "senderChecksum", "uint32", ")", "(", "changes", "[", "]", "Change", ",", "fullSync", "bool", ")", "{", "changes", "=", "d", ".", "issueChanges", "(", ")", "\n\n", "// filter out changes that came from the sender previously", "changes", "=", "d", ".", "filterChangesFromSender", "(", "changes", ",", "senderAddress", ",", "senderIncarnation", ")", "\n\n", "d", ".", "bumpPiggybackCounters", "(", "changes", ")", "\n\n", "if", "len", "(", "changes", ")", ">", "0", "||", "d", ".", "node", ".", "memberlist", ".", "Checksum", "(", ")", "==", "senderChecksum", "{", "return", "changes", ",", "false", "\n", "}", "\n\n", "d", ".", "node", ".", "EmitEvent", "(", "FullSyncEvent", "{", "senderAddress", ",", "senderChecksum", "}", ")", "\n\n", "d", ".", "node", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "d", ".", "node", ".", "memberlist", ".", "Checksum", "(", ")", ",", "\"", "\"", ":", "senderAddress", ",", "\"", "\"", ":", "senderChecksum", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "return", "d", ".", "MembershipAsChanges", "(", ")", ",", "true", "\n", "}" ]
// IssueAsReceiver collects all changes a node needs when responding to a ping // or ping-req. Unlike IssueAsSender, IssueAsReceiver automatically increments // the piggyback counters because it's difficult to find out whether a response // reaches the client. The second return value indicates whether a full sync // is triggered.
[ "IssueAsReceiver", "collects", "all", "changes", "a", "node", "needs", "when", "responding", "to", "a", "ping", "or", "ping", "-", "req", ".", "Unlike", "IssueAsSender", "IssueAsReceiver", "automatically", "increments", "the", "piggyback", "counters", "because", "it", "s", "difficult", "to", "find", "out", "whether", "a", "response", "reaches", "the", "client", ".", "The", "second", "return", "value", "indicates", "whether", "a", "full", "sync", "is", "triggered", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L155-L180
train
uber/ringpop-go
swim/disseminator.go
filterChangesFromSender
func (d *disseminator) filterChangesFromSender(cs []Change, source string, incarnation int64) []Change { for i := 0; i < len(cs); i++ { if incarnation == cs[i].SourceIncarnation && source == cs[i].Source { d.node.EmitEvent(ChangeFilteredEvent{cs[i]}) // swap, and not just overwrite, so that in the end only the order // of the underlying array has changed. cs[i], cs[len(cs)-1] = cs[len(cs)-1], cs[i] cs = cs[:len(cs)-1] i-- } } return cs }
go
func (d *disseminator) filterChangesFromSender(cs []Change, source string, incarnation int64) []Change { for i := 0; i < len(cs); i++ { if incarnation == cs[i].SourceIncarnation && source == cs[i].Source { d.node.EmitEvent(ChangeFilteredEvent{cs[i]}) // swap, and not just overwrite, so that in the end only the order // of the underlying array has changed. cs[i], cs[len(cs)-1] = cs[len(cs)-1], cs[i] cs = cs[:len(cs)-1] i-- } } return cs }
[ "func", "(", "d", "*", "disseminator", ")", "filterChangesFromSender", "(", "cs", "[", "]", "Change", ",", "source", "string", ",", "incarnation", "int64", ")", "[", "]", "Change", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "cs", ")", ";", "i", "++", "{", "if", "incarnation", "==", "cs", "[", "i", "]", ".", "SourceIncarnation", "&&", "source", "==", "cs", "[", "i", "]", ".", "Source", "{", "d", ".", "node", ".", "EmitEvent", "(", "ChangeFilteredEvent", "{", "cs", "[", "i", "]", "}", ")", "\n\n", "// swap, and not just overwrite, so that in the end only the order", "// of the underlying array has changed.", "cs", "[", "i", "]", ",", "cs", "[", "len", "(", "cs", ")", "-", "1", "]", "=", "cs", "[", "len", "(", "cs", ")", "-", "1", "]", ",", "cs", "[", "i", "]", "\n\n", "cs", "=", "cs", "[", ":", "len", "(", "cs", ")", "-", "1", "]", "\n", "i", "--", "\n", "}", "\n", "}", "\n", "return", "cs", "\n", "}" ]
// filterChangesFromSender returns changes that didn't originate at the sender. // Attention, this function reorders the underlaying input array.
[ "filterChangesFromSender", "returns", "changes", "that", "didn", "t", "originate", "at", "the", "sender", ".", "Attention", "this", "function", "reorders", "the", "underlaying", "input", "array", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L184-L198
train
uber/ringpop-go
swim/disseminator.go
tryStartReverseFullSync
func (d *disseminator) tryStartReverseFullSync(target string, timeout time.Duration) { // occupy a job, return if none are available select { case d.reverseFullSyncJobs <- struct{}{}: // continue if job is available default: d.logger.WithFields(log.Fields{ "remote": target, }).Info("omit bidirectional full sync, too many already running") d.node.EmitEvent(OmitReverseFullSyncEvent{Target: target}) return } // start reverse full sync go func() { d.reverseFullSync(target, timeout) // create a new vacancy when the job is done <-d.reverseFullSyncJobs }() }
go
func (d *disseminator) tryStartReverseFullSync(target string, timeout time.Duration) { // occupy a job, return if none are available select { case d.reverseFullSyncJobs <- struct{}{}: // continue if job is available default: d.logger.WithFields(log.Fields{ "remote": target, }).Info("omit bidirectional full sync, too many already running") d.node.EmitEvent(OmitReverseFullSyncEvent{Target: target}) return } // start reverse full sync go func() { d.reverseFullSync(target, timeout) // create a new vacancy when the job is done <-d.reverseFullSyncJobs }() }
[ "func", "(", "d", "*", "disseminator", ")", "tryStartReverseFullSync", "(", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "{", "// occupy a job, return if none are available", "select", "{", "case", "d", ".", "reverseFullSyncJobs", "<-", "struct", "{", "}", "{", "}", ":", "// continue if job is available", "default", ":", "d", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "d", ".", "node", ".", "EmitEvent", "(", "OmitReverseFullSyncEvent", "{", "Target", ":", "target", "}", ")", "\n", "return", "\n", "}", "\n\n", "// start reverse full sync", "go", "func", "(", ")", "{", "d", ".", "reverseFullSync", "(", "target", ",", "timeout", ")", "\n\n", "// create a new vacancy when the job is done", "<-", "d", ".", "reverseFullSyncJobs", "\n", "}", "(", ")", "\n", "}" ]
// tryStartReverseFullSync fires a goroutine that performs a full sync. We omit // the reverse full sync if the maximum number of processes are already // running. This ensures no more than reverseFullSyncJobs processes are // running concurrently.
[ "tryStartReverseFullSync", "fires", "a", "goroutine", "that", "performs", "a", "full", "sync", ".", "We", "omit", "the", "reverse", "full", "sync", "if", "the", "maximum", "number", "of", "processes", "are", "already", "running", ".", "This", "ensures", "no", "more", "than", "reverseFullSyncJobs", "processes", "are", "running", "concurrently", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L256-L277
train
uber/ringpop-go
swim/disseminator.go
reverseFullSync
func (d *disseminator) reverseFullSync(target string, timeout time.Duration) { d.node.EmitEvent(StartReverseFullSyncEvent{Target: target}) res, err := sendJoinRequest(d.node, target, timeout) if err != nil || res == nil { d.logger.WithFields(log.Fields{ "remote": target, "error": err, }).Warn("bidirectional full sync failed due to failed join request") return } d.logger.WithFields(log.Fields{ "remote": target, }).Info("bidirectional full sync") cs := d.node.memberlist.Update(res.Membership) if len(cs) == 0 { d.node.EmitEvent(RedundantReverseFullSyncEvent{Target: target}) } }
go
func (d *disseminator) reverseFullSync(target string, timeout time.Duration) { d.node.EmitEvent(StartReverseFullSyncEvent{Target: target}) res, err := sendJoinRequest(d.node, target, timeout) if err != nil || res == nil { d.logger.WithFields(log.Fields{ "remote": target, "error": err, }).Warn("bidirectional full sync failed due to failed join request") return } d.logger.WithFields(log.Fields{ "remote": target, }).Info("bidirectional full sync") cs := d.node.memberlist.Update(res.Membership) if len(cs) == 0 { d.node.EmitEvent(RedundantReverseFullSyncEvent{Target: target}) } }
[ "func", "(", "d", "*", "disseminator", ")", "reverseFullSync", "(", "target", "string", ",", "timeout", "time", ".", "Duration", ")", "{", "d", ".", "node", ".", "EmitEvent", "(", "StartReverseFullSyncEvent", "{", "Target", ":", "target", "}", ")", "\n\n", "res", ",", "err", ":=", "sendJoinRequest", "(", "d", ".", "node", ",", "target", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "||", "res", "==", "nil", "{", "d", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "d", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "target", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "cs", ":=", "d", ".", "node", ".", "memberlist", ".", "Update", "(", "res", ".", "Membership", ")", "\n", "if", "len", "(", "cs", ")", "==", "0", "{", "d", ".", "node", ".", "EmitEvent", "(", "RedundantReverseFullSyncEvent", "{", "Target", ":", "target", "}", ")", "\n", "}", "\n", "}" ]
// reverseFullSync is the second part of a bidirectional full sync. The first // part is performed by the IssueAsReceiver method. The reverse full sync // ensures that this node merges the membership of the target node's membership // with its own.
[ "reverseFullSync", "is", "the", "second", "part", "of", "a", "bidirectional", "full", "sync", ".", "The", "first", "part", "is", "performed", "by", "the", "IssueAsReceiver", "method", ".", "The", "reverse", "full", "sync", "ensures", "that", "this", "node", "merges", "the", "membership", "of", "the", "target", "node", "s", "membership", "with", "its", "own", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/disseminator.go#L283-L303
train
uber/ringpop-go
examples/ping-json/main.go
Bytes
func (p Ping) Bytes() []byte { data, _ := json2.Marshal(p) return data }
go
func (p Ping) Bytes() []byte { data, _ := json2.Marshal(p) return data }
[ "func", "(", "p", "Ping", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "data", ",", "_", ":=", "json2", ".", "Marshal", "(", "p", ")", "\n", "return", "data", "\n", "}" ]
// Bytes returns the byets for a ping
[ "Bytes", "returns", "the", "byets", "for", "a", "ping" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/examples/ping-json/main.go#L55-L58
train
uber/ringpop-go
swim/member.go
Label
func (m Member) Label(key string) (value string, has bool) { value, has = m.Labels[key] return }
go
func (m Member) Label(key string) (value string, has bool) { value, has = m.Labels[key] return }
[ "func", "(", "m", "Member", ")", "Label", "(", "key", "string", ")", "(", "value", "string", ",", "has", "bool", ")", "{", "value", ",", "has", "=", "m", ".", "Labels", "[", "key", "]", "\n", "return", "\n", "}" ]
// Label returns the value of a label named by key. The `has` boolean indicates // if the label was set on the member or not
[ "Label", "returns", "the", "value", "of", "a", "label", "named", "by", "key", ".", "The", "has", "boolean", "indicates", "if", "the", "label", "was", "set", "on", "the", "member", "or", "not" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L80-L83
train
uber/ringpop-go
swim/member.go
Identity
func (m Member) Identity() string { // Read the identity from the labels identity, set := m.Label(membership.IdentityLabelKey) if set { return identity } // return the member's address if there is no identity set return m.Address }
go
func (m Member) Identity() string { // Read the identity from the labels identity, set := m.Label(membership.IdentityLabelKey) if set { return identity } // return the member's address if there is no identity set return m.Address }
[ "func", "(", "m", "Member", ")", "Identity", "(", ")", "string", "{", "// Read the identity from the labels", "identity", ",", "set", ":=", "m", ".", "Label", "(", "membership", ".", "IdentityLabelKey", ")", "\n", "if", "set", "{", "return", "identity", "\n", "}", "\n\n", "// return the member's address if there is no identity set", "return", "m", ".", "Address", "\n", "}" ]
// Identity returns the identity of a member. If a specific identity is not set // for the member the address will be used as the identity
[ "Identity", "returns", "the", "identity", "of", "a", "member", ".", "If", "a", "specific", "identity", "is", "not", "set", "for", "the", "member", "the", "address", "will", "be", "used", "as", "the", "identity" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L87-L96
train
uber/ringpop-go
swim/member.go
checksumString
func (m Member) checksumString(b *bytes.Buffer) { b.WriteString(m.Address) b.WriteString(m.Status) b.WriteString(strconv.FormatInt(m.Incarnation, 10)) m.Labels.checksumString(b) }
go
func (m Member) checksumString(b *bytes.Buffer) { b.WriteString(m.Address) b.WriteString(m.Status) b.WriteString(strconv.FormatInt(m.Incarnation, 10)) m.Labels.checksumString(b) }
[ "func", "(", "m", "Member", ")", "checksumString", "(", "b", "*", "bytes", ".", "Buffer", ")", "{", "b", ".", "WriteString", "(", "m", ".", "Address", ")", "\n", "b", ".", "WriteString", "(", "m", ".", "Status", ")", "\n", "b", ".", "WriteString", "(", "strconv", ".", "FormatInt", "(", "m", ".", "Incarnation", ",", "10", ")", ")", "\n", "m", ".", "Labels", ".", "checksumString", "(", "b", ")", "\n", "}" ]
// checksumString fills a buffer that is passed with the contents that this node // needs to add to the checksum string.
[ "checksumString", "fills", "a", "buffer", "that", "is", "passed", "with", "the", "contents", "that", "this", "node", "needs", "to", "add", "to", "the", "checksum", "string", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L116-L121
train
uber/ringpop-go
swim/member.go
copy
func (l LabelMap) copy() (result LabelMap) { result = make(map[string]string, len(l)) for key, value := range l { result[key] = value } return }
go
func (l LabelMap) copy() (result LabelMap) { result = make(map[string]string, len(l)) for key, value := range l { result[key] = value } return }
[ "func", "(", "l", "LabelMap", ")", "copy", "(", ")", "(", "result", "LabelMap", ")", "{", "result", "=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "l", ")", ")", "\n", "for", "key", ",", "value", ":=", "range", "l", "{", "result", "[", "key", "]", "=", "value", "\n", "}", "\n", "return", "\n", "}" ]
// copy creates a non-nil version of the LabelMap that copies all existing // entries of the map. This can be used to create a new version of the labels // that can be mutated before putting it on a Member to make updates without // mutating the map that was already on a Member
[ "copy", "creates", "a", "non", "-", "nil", "version", "of", "the", "LabelMap", "that", "copies", "all", "existing", "entries", "of", "the", "map", ".", "This", "can", "be", "used", "to", "create", "a", "new", "version", "of", "the", "labels", "that", "can", "be", "mutated", "before", "putting", "it", "on", "a", "Member", "to", "make", "updates", "without", "mutating", "the", "map", "that", "was", "already", "on", "a", "Member" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L127-L133
train
uber/ringpop-go
swim/member.go
checksumString
func (l LabelMap) checksumString(b *bytes.Buffer) { checksum := l.checksum() if checksum == 0 { // we don't write the checksum of the labels if the value of the checksum // is 0 (zero) to be backwards compatible with ringpop applications on // an older version. This only works if the newer version does not use // labels return } // write #labels<checksum> to the buffer which will be appended to the // checksum string for the node. b.WriteString("#labels") b.WriteString(strconv.Itoa(int(checksum))) }
go
func (l LabelMap) checksumString(b *bytes.Buffer) { checksum := l.checksum() if checksum == 0 { // we don't write the checksum of the labels if the value of the checksum // is 0 (zero) to be backwards compatible with ringpop applications on // an older version. This only works if the newer version does not use // labels return } // write #labels<checksum> to the buffer which will be appended to the // checksum string for the node. b.WriteString("#labels") b.WriteString(strconv.Itoa(int(checksum))) }
[ "func", "(", "l", "LabelMap", ")", "checksumString", "(", "b", "*", "bytes", ".", "Buffer", ")", "{", "checksum", ":=", "l", ".", "checksum", "(", ")", "\n\n", "if", "checksum", "==", "0", "{", "// we don't write the checksum of the labels if the value of the checksum", "// is 0 (zero) to be backwards compatible with ringpop applications on", "// an older version. This only works if the newer version does not use", "// labels", "return", "\n", "}", "\n\n", "// write #labels<checksum> to the buffer which will be appended to the", "// checksum string for the node.", "b", ".", "WriteString", "(", "\"", "\"", ")", "\n", "b", ".", "WriteString", "(", "strconv", ".", "Itoa", "(", "int", "(", "checksum", ")", ")", ")", "\n", "}" ]
// checksumString adds the label portion of the checksum to the buffer that is // passed in. The string will not be appended in the case where labels are not // set on this member. This is for backwards compatibility reasons with older // versions.
[ "checksumString", "adds", "the", "label", "portion", "of", "the", "checksum", "to", "the", "buffer", "that", "is", "passed", "in", ".", "The", "string", "will", "not", "be", "appended", "in", "the", "case", "where", "labels", "are", "not", "set", "on", "this", "member", ".", "This", "is", "for", "backwards", "compatibility", "reasons", "with", "older", "versions", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L139-L154
train
uber/ringpop-go
swim/member.go
shuffle
func shuffle(members []*Member) []*Member { newMembers := make([]*Member, len(members), cap(members)) newIndexes := rand.Perm(len(members)) for o, n := range newIndexes { newMembers[n] = members[o] } return newMembers }
go
func shuffle(members []*Member) []*Member { newMembers := make([]*Member, len(members), cap(members)) newIndexes := rand.Perm(len(members)) for o, n := range newIndexes { newMembers[n] = members[o] } return newMembers }
[ "func", "shuffle", "(", "members", "[", "]", "*", "Member", ")", "[", "]", "*", "Member", "{", "newMembers", ":=", "make", "(", "[", "]", "*", "Member", ",", "len", "(", "members", ")", ",", "cap", "(", "members", ")", ")", "\n", "newIndexes", ":=", "rand", ".", "Perm", "(", "len", "(", "members", ")", ")", "\n\n", "for", "o", ",", "n", ":=", "range", "newIndexes", "{", "newMembers", "[", "n", "]", "=", "members", "[", "o", "]", "\n", "}", "\n\n", "return", "newMembers", "\n", "}" ]
// shuffles slice of members pseudo-randomly, returns new slice
[ "shuffles", "slice", "of", "members", "pseudo", "-", "randomly", "returns", "new", "slice" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L200-L209
train
uber/ringpop-go
swim/member.go
validateIncoming
func (c Change) validateIncoming() Change { if c.Status == Faulty && c.Tombstone { c.Status = Tombstone } return c }
go
func (c Change) validateIncoming() Change { if c.Status == Faulty && c.Tombstone { c.Status = Tombstone } return c }
[ "func", "(", "c", "Change", ")", "validateIncoming", "(", ")", "Change", "{", "if", "c", ".", "Status", "==", "Faulty", "&&", "c", ".", "Tombstone", "{", "c", ".", "Status", "=", "Tombstone", "\n", "}", "\n", "return", "c", "\n", "}" ]
// validateIncoming validates incoming changes before they are passed into the // swim state machine. This is usefull to make late adjustments to incoming // changes to transform some legacy wire protocol changes into new swim terminology
[ "validateIncoming", "validates", "incoming", "changes", "before", "they", "are", "passed", "into", "the", "swim", "state", "machine", ".", "This", "is", "usefull", "to", "make", "late", "adjustments", "to", "incoming", "changes", "to", "transform", "some", "legacy", "wire", "protocol", "changes", "into", "new", "swim", "terminology" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L315-L320
train
uber/ringpop-go
swim/member.go
validateOutgoing
func (c Change) validateOutgoing() Change { if c.Status == Tombstone { c.Status = Faulty c.Tombstone = true } return c }
go
func (c Change) validateOutgoing() Change { if c.Status == Tombstone { c.Status = Faulty c.Tombstone = true } return c }
[ "func", "(", "c", "Change", ")", "validateOutgoing", "(", ")", "Change", "{", "if", "c", ".", "Status", "==", "Tombstone", "{", "c", ".", "Status", "=", "Faulty", "\n", "c", ".", "Tombstone", "=", "true", "\n", "}", "\n", "return", "c", "\n", "}" ]
// validateOutgoing validates outgoing changes before they are passed to the module // responsible for sending the change to the other side. This can be used to make sure // that our changes are parsable by older version of ringpop-go to prevent unwanted // behavior when incompatible changes are sent to older versions.
[ "validateOutgoing", "validates", "outgoing", "changes", "before", "they", "are", "passed", "to", "the", "module", "responsible", "for", "sending", "the", "change", "to", "the", "other", "side", ".", "This", "can", "be", "used", "to", "make", "sure", "that", "our", "changes", "are", "parsable", "by", "older", "version", "of", "ringpop", "-", "go", "to", "prevent", "unwanted", "behavior", "when", "incompatible", "changes", "are", "sent", "to", "older", "versions", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/member.go#L326-L332
train
uber/ringpop-go
ringpop.go
New
func New(app string, opts ...Option) (*Ringpop, error) { var err error ringpop := &Ringpop{ config: &configuration{ App: app, InitialLabels: make(swim.LabelMap), }, logger: logging.Logger("ringpop"), } err = applyOptions(ringpop, defaultOptions) if err != nil { panic(fmt.Errorf("Error applying default Ringpop options: %v", err)) } err = applyOptions(ringpop, opts) if err != nil { return nil, err } errs := checkOptions(ringpop) if len(errs) != 0 { return nil, fmt.Errorf("%v", errs) } ringpop.setState(created) return ringpop, nil }
go
func New(app string, opts ...Option) (*Ringpop, error) { var err error ringpop := &Ringpop{ config: &configuration{ App: app, InitialLabels: make(swim.LabelMap), }, logger: logging.Logger("ringpop"), } err = applyOptions(ringpop, defaultOptions) if err != nil { panic(fmt.Errorf("Error applying default Ringpop options: %v", err)) } err = applyOptions(ringpop, opts) if err != nil { return nil, err } errs := checkOptions(ringpop) if len(errs) != 0 { return nil, fmt.Errorf("%v", errs) } ringpop.setState(created) return ringpop, nil }
[ "func", "New", "(", "app", "string", ",", "opts", "...", "Option", ")", "(", "*", "Ringpop", ",", "error", ")", "{", "var", "err", "error", "\n\n", "ringpop", ":=", "&", "Ringpop", "{", "config", ":", "&", "configuration", "{", "App", ":", "app", ",", "InitialLabels", ":", "make", "(", "swim", ".", "LabelMap", ")", ",", "}", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ",", "}", "\n\n", "err", "=", "applyOptions", "(", "ringpop", ",", "defaultOptions", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "err", "=", "applyOptions", "(", "ringpop", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "errs", ":=", "checkOptions", "(", "ringpop", ")", "\n", "if", "len", "(", "errs", ")", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errs", ")", "\n", "}", "\n\n", "ringpop", ".", "setState", "(", "created", ")", "\n\n", "return", "ringpop", ",", "nil", "\n", "}" ]
// New returns a new Ringpop instance.
[ "New", "returns", "a", "new", "Ringpop", "instance", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L142-L171
train
uber/ringpop-go
ringpop.go
init
func (rp *Ringpop) init() error { if rp.channel == nil { return errors.New("Missing channel") } address, err := rp.address() if err != nil { return err } // early initialization of statter before registering listeners that might // fire and try to stat rp.stats.hostport = genStatsHostport(address) rp.stats.prefix = fmt.Sprintf("ringpop.%s", rp.stats.hostport) rp.stats.keys = make(map[string]string) rp.subChannel = rp.channel.GetSubChannel("ringpop", tchannel.Isolated) rp.registerHandlers() rp.node = swim.NewNode(rp.config.App, address, rp.subChannel, &swim.Options{ StateTimeouts: rp.config.StateTimeouts, Clock: rp.clock, LabelLimits: rp.config.LabelLimits, InitialLabels: rp.config.InitialLabels, SelfEvict: rp.config.SelfEvict, RequiresAppInPing: rp.config.RequiresAppInPing, }) rp.node.AddListener(rp) rp.ring = hashring.New(farm.Fingerprint32, rp.configHashRing.ReplicaPoints) rp.ring.AddListener(rp) // add all members present in the membership of the node on startup. for _, member := range rp.node.GetReachableMembers() { rp.ring.AddMembers(member) } rp.forwarder = forward.NewForwarder(rp, rp.subChannel) rp.forwarder.AddListener(rp) rp.startTimers() rp.setState(initialized) return nil }
go
func (rp *Ringpop) init() error { if rp.channel == nil { return errors.New("Missing channel") } address, err := rp.address() if err != nil { return err } // early initialization of statter before registering listeners that might // fire and try to stat rp.stats.hostport = genStatsHostport(address) rp.stats.prefix = fmt.Sprintf("ringpop.%s", rp.stats.hostport) rp.stats.keys = make(map[string]string) rp.subChannel = rp.channel.GetSubChannel("ringpop", tchannel.Isolated) rp.registerHandlers() rp.node = swim.NewNode(rp.config.App, address, rp.subChannel, &swim.Options{ StateTimeouts: rp.config.StateTimeouts, Clock: rp.clock, LabelLimits: rp.config.LabelLimits, InitialLabels: rp.config.InitialLabels, SelfEvict: rp.config.SelfEvict, RequiresAppInPing: rp.config.RequiresAppInPing, }) rp.node.AddListener(rp) rp.ring = hashring.New(farm.Fingerprint32, rp.configHashRing.ReplicaPoints) rp.ring.AddListener(rp) // add all members present in the membership of the node on startup. for _, member := range rp.node.GetReachableMembers() { rp.ring.AddMembers(member) } rp.forwarder = forward.NewForwarder(rp, rp.subChannel) rp.forwarder.AddListener(rp) rp.startTimers() rp.setState(initialized) return nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "init", "(", ")", "error", "{", "if", "rp", ".", "channel", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "address", ",", "err", ":=", "rp", ".", "address", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// early initialization of statter before registering listeners that might", "// fire and try to stat", "rp", ".", "stats", ".", "hostport", "=", "genStatsHostport", "(", "address", ")", "\n", "rp", ".", "stats", ".", "prefix", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rp", ".", "stats", ".", "hostport", ")", "\n", "rp", ".", "stats", ".", "keys", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n\n", "rp", ".", "subChannel", "=", "rp", ".", "channel", ".", "GetSubChannel", "(", "\"", "\"", ",", "tchannel", ".", "Isolated", ")", "\n", "rp", ".", "registerHandlers", "(", ")", "\n\n", "rp", ".", "node", "=", "swim", ".", "NewNode", "(", "rp", ".", "config", ".", "App", ",", "address", ",", "rp", ".", "subChannel", ",", "&", "swim", ".", "Options", "{", "StateTimeouts", ":", "rp", ".", "config", ".", "StateTimeouts", ",", "Clock", ":", "rp", ".", "clock", ",", "LabelLimits", ":", "rp", ".", "config", ".", "LabelLimits", ",", "InitialLabels", ":", "rp", ".", "config", ".", "InitialLabels", ",", "SelfEvict", ":", "rp", ".", "config", ".", "SelfEvict", ",", "RequiresAppInPing", ":", "rp", ".", "config", ".", "RequiresAppInPing", ",", "}", ")", "\n", "rp", ".", "node", ".", "AddListener", "(", "rp", ")", "\n\n", "rp", ".", "ring", "=", "hashring", ".", "New", "(", "farm", ".", "Fingerprint32", ",", "rp", ".", "configHashRing", ".", "ReplicaPoints", ")", "\n", "rp", ".", "ring", ".", "AddListener", "(", "rp", ")", "\n\n", "// add all members present in the membership of the node on startup.", "for", "_", ",", "member", ":=", "range", "rp", ".", "node", ".", "GetReachableMembers", "(", ")", "{", "rp", ".", "ring", ".", "AddMembers", "(", "member", ")", "\n", "}", "\n\n", "rp", ".", "forwarder", "=", "forward", ".", "NewForwarder", "(", "rp", ",", "rp", ".", "subChannel", ")", "\n", "rp", ".", "forwarder", ".", "AddListener", "(", "rp", ")", "\n\n", "rp", ".", "startTimers", "(", ")", "\n", "rp", ".", "setState", "(", "initialized", ")", "\n\n", "return", "nil", "\n", "}" ]
// init configures a Ringpop instance and makes it ready to do comms.
[ "init", "configures", "a", "Ringpop", "instance", "and", "makes", "it", "ready", "to", "do", "comms", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L174-L218
train
uber/ringpop-go
ringpop.go
startTimers
func (rp *Ringpop) startTimers() { if rp.tickers != nil { return } rp.tickers = make(chan *clock.Ticker, 32) // 32 == max number of tickers if rp.config.MembershipChecksumStatPeriod != StatPeriodNever { ticker := rp.clock.Ticker(rp.config.MembershipChecksumStatPeriod) rp.tickers <- ticker go func() { for range ticker.C { rp.statter.UpdateGauge( rp.getStatKey("membership.checksum-periodic"), nil, int64(rp.node.GetChecksum()), ) } }() } if rp.config.RingChecksumStatPeriod != StatPeriodNever { ticker := rp.clock.Ticker(rp.config.RingChecksumStatPeriod) rp.tickers <- ticker go func() { for range ticker.C { rp.statter.UpdateGauge( rp.getStatKey("ring.checksum-periodic"), nil, int64(rp.ring.Checksum()), ) // emit all named checksums as well for name, checksum := range rp.ring.Checksums() { rp.statter.UpdateGauge( rp.getStatKey("ring.checksums-periodic."+name), nil, int64(checksum), ) } } }() } }
go
func (rp *Ringpop) startTimers() { if rp.tickers != nil { return } rp.tickers = make(chan *clock.Ticker, 32) // 32 == max number of tickers if rp.config.MembershipChecksumStatPeriod != StatPeriodNever { ticker := rp.clock.Ticker(rp.config.MembershipChecksumStatPeriod) rp.tickers <- ticker go func() { for range ticker.C { rp.statter.UpdateGauge( rp.getStatKey("membership.checksum-periodic"), nil, int64(rp.node.GetChecksum()), ) } }() } if rp.config.RingChecksumStatPeriod != StatPeriodNever { ticker := rp.clock.Ticker(rp.config.RingChecksumStatPeriod) rp.tickers <- ticker go func() { for range ticker.C { rp.statter.UpdateGauge( rp.getStatKey("ring.checksum-periodic"), nil, int64(rp.ring.Checksum()), ) // emit all named checksums as well for name, checksum := range rp.ring.Checksums() { rp.statter.UpdateGauge( rp.getStatKey("ring.checksums-periodic."+name), nil, int64(checksum), ) } } }() } }
[ "func", "(", "rp", "*", "Ringpop", ")", "startTimers", "(", ")", "{", "if", "rp", ".", "tickers", "!=", "nil", "{", "return", "\n", "}", "\n", "rp", ".", "tickers", "=", "make", "(", "chan", "*", "clock", ".", "Ticker", ",", "32", ")", "// 32 == max number of tickers", "\n\n", "if", "rp", ".", "config", ".", "MembershipChecksumStatPeriod", "!=", "StatPeriodNever", "{", "ticker", ":=", "rp", ".", "clock", ".", "Ticker", "(", "rp", ".", "config", ".", "MembershipChecksumStatPeriod", ")", "\n", "rp", ".", "tickers", "<-", "ticker", "\n", "go", "func", "(", ")", "{", "for", "range", "ticker", ".", "C", "{", "rp", ".", "statter", ".", "UpdateGauge", "(", "rp", ".", "getStatKey", "(", "\"", "\"", ")", ",", "nil", ",", "int64", "(", "rp", ".", "node", ".", "GetChecksum", "(", ")", ")", ",", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n\n", "if", "rp", ".", "config", ".", "RingChecksumStatPeriod", "!=", "StatPeriodNever", "{", "ticker", ":=", "rp", ".", "clock", ".", "Ticker", "(", "rp", ".", "config", ".", "RingChecksumStatPeriod", ")", "\n", "rp", ".", "tickers", "<-", "ticker", "\n", "go", "func", "(", ")", "{", "for", "range", "ticker", ".", "C", "{", "rp", ".", "statter", ".", "UpdateGauge", "(", "rp", ".", "getStatKey", "(", "\"", "\"", ")", ",", "nil", ",", "int64", "(", "rp", ".", "ring", ".", "Checksum", "(", ")", ")", ",", ")", "\n\n", "// emit all named checksums as well", "for", "name", ",", "checksum", ":=", "range", "rp", ".", "ring", ".", "Checksums", "(", ")", "{", "rp", ".", "statter", ".", "UpdateGauge", "(", "rp", ".", "getStatKey", "(", "\"", "\"", "+", "name", ")", ",", "nil", ",", "int64", "(", "checksum", ")", ",", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "}" ]
// Starts periodic timers in a single goroutine. Can be turned back off via // stopTimers.
[ "Starts", "periodic", "timers", "in", "a", "single", "goroutine", ".", "Can", "be", "turned", "back", "off", "via", "stopTimers", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L222-L264
train
uber/ringpop-go
ringpop.go
channelAddressResolver
func (rp *Ringpop) channelAddressResolver() (string, error) { peerInfo := rp.channel.PeerInfo() // Check that TChannel is listening on a real hostport. By default, // TChannel listens on an ephemeral host/port. The real port is then // assigned by the OS when ListenAndServe is called. If the hostport is // ephemeral, it means TChannel is not yet listening and the hostport // cannot be resolved. if peerInfo.IsEphemeralHostPort() { return "", ErrEphemeralAddress } return peerInfo.HostPort, nil }
go
func (rp *Ringpop) channelAddressResolver() (string, error) { peerInfo := rp.channel.PeerInfo() // Check that TChannel is listening on a real hostport. By default, // TChannel listens on an ephemeral host/port. The real port is then // assigned by the OS when ListenAndServe is called. If the hostport is // ephemeral, it means TChannel is not yet listening and the hostport // cannot be resolved. if peerInfo.IsEphemeralHostPort() { return "", ErrEphemeralAddress } return peerInfo.HostPort, nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "channelAddressResolver", "(", ")", "(", "string", ",", "error", ")", "{", "peerInfo", ":=", "rp", ".", "channel", ".", "PeerInfo", "(", ")", "\n", "// Check that TChannel is listening on a real hostport. By default,", "// TChannel listens on an ephemeral host/port. The real port is then", "// assigned by the OS when ListenAndServe is called. If the hostport is", "// ephemeral, it means TChannel is not yet listening and the hostport", "// cannot be resolved.", "if", "peerInfo", ".", "IsEphemeralHostPort", "(", ")", "{", "return", "\"", "\"", ",", "ErrEphemeralAddress", "\n", "}", "\n", "return", "peerInfo", ".", "HostPort", ",", "nil", "\n", "}" ]
// r.channelAddressResolver resolves the hostport from the current // TChannel object on the Ringpop instance.
[ "r", ".", "channelAddressResolver", "resolves", "the", "hostport", "from", "the", "current", "TChannel", "object", "on", "the", "Ringpop", "instance", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L284-L295
train
uber/ringpop-go
ringpop.go
Destroy
func (rp *Ringpop) Destroy() { if rp.node != nil { rp.node.Destroy() } rp.stopTimers() rp.setState(destroyed) }
go
func (rp *Ringpop) Destroy() { if rp.node != nil { rp.node.Destroy() } rp.stopTimers() rp.setState(destroyed) }
[ "func", "(", "rp", "*", "Ringpop", ")", "Destroy", "(", ")", "{", "if", "rp", ".", "node", "!=", "nil", "{", "rp", ".", "node", ".", "Destroy", "(", ")", "\n", "}", "\n\n", "rp", ".", "stopTimers", "(", ")", "\n\n", "rp", ".", "setState", "(", "destroyed", ")", "\n", "}" ]
// Destroy stops all communication. Note that this does not close the TChannel // instance that was passed to Ringpop in the constructor. Once an instance is // destroyed, it cannot be restarted.
[ "Destroy", "stops", "all", "communication", ".", "Note", "that", "this", "does", "not", "close", "the", "TChannel", "instance", "that", "was", "passed", "to", "Ringpop", "in", "the", "constructor", ".", "Once", "an", "instance", "is", "destroyed", "it", "cannot", "be", "restarted", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L300-L308
train
uber/ringpop-go
ringpop.go
Uptime
func (rp *Ringpop) Uptime() (time.Duration, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return time.Now().Sub(rp.startTime), nil }
go
func (rp *Ringpop) Uptime() (time.Duration, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return time.Now().Sub(rp.startTime), nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "Uptime", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "0", ",", "ErrNotBootstrapped", "\n", "}", "\n", "return", "time", ".", "Now", "(", ")", ".", "Sub", "(", "rp", ".", "startTime", ")", ",", "nil", "\n", "}" ]
// Uptime returns the amount of time that this Ringpop instance has been // bootstrapped for.
[ "Uptime", "returns", "the", "amount", "of", "time", "that", "this", "Ringpop", "instance", "has", "been", "bootstrapped", "for", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L333-L338
train
uber/ringpop-go
ringpop.go
RegisterListener
func (rp *Ringpop) RegisterListener(l events.EventListener) { rp.logger.Warn("RegisterListener is deprecated, use AddListener") rp.AddListener(l) }
go
func (rp *Ringpop) RegisterListener(l events.EventListener) { rp.logger.Warn("RegisterListener is deprecated, use AddListener") rp.AddListener(l) }
[ "func", "(", "rp", "*", "Ringpop", ")", "RegisterListener", "(", "l", "events", ".", "EventListener", ")", "{", "rp", ".", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "rp", ".", "AddListener", "(", "l", ")", "\n", "}" ]
// RegisterListener is DEPRECATED, use AddListener. This function is kept around // for the time being to make sure that ringpop is a drop in replacement for // now. It should not be used by new projects, to accomplish this it will log a // warning message that the developer can understand. A release in the future // will remove this function completely which will cause a breaking change to // the ringpop public interface.
[ "RegisterListener", "is", "DEPRECATED", "use", "AddListener", ".", "This", "function", "is", "kept", "around", "for", "the", "time", "being", "to", "make", "sure", "that", "ringpop", "is", "a", "drop", "in", "replacement", "for", "now", ".", "It", "should", "not", "be", "used", "by", "new", "projects", "to", "accomplish", "this", "it", "will", "log", "a", "warning", "message", "that", "the", "developer", "can", "understand", ".", "A", "release", "in", "the", "future", "will", "remove", "this", "function", "completely", "which", "will", "cause", "a", "breaking", "change", "to", "the", "ringpop", "public", "interface", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L346-L349
train
uber/ringpop-go
ringpop.go
getState
func (rp *Ringpop) getState() state { rp.stateMutex.RLock() r := rp.state rp.stateMutex.RUnlock() return r }
go
func (rp *Ringpop) getState() state { rp.stateMutex.RLock() r := rp.state rp.stateMutex.RUnlock() return r }
[ "func", "(", "rp", "*", "Ringpop", ")", "getState", "(", ")", "state", "{", "rp", ".", "stateMutex", ".", "RLock", "(", ")", "\n", "r", ":=", "rp", ".", "state", "\n", "rp", ".", "stateMutex", ".", "RUnlock", "(", ")", "\n", "return", "r", "\n", "}" ]
// getState gets the state of the current Ringpop instance.
[ "getState", "gets", "the", "state", "of", "the", "current", "Ringpop", "instance", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L352-L357
train
uber/ringpop-go
ringpop.go
setState
func (rp *Ringpop) setState(s state) { rp.stateMutex.Lock() oldState := rp.state rp.state = s rp.stateMutex.Unlock() // test if the state has changed with this call to setState if oldState != s { switch s { case ready: rp.EmitEvent(events.Ready{}) case destroyed: rp.EmitEvent(events.Destroyed{}) } } }
go
func (rp *Ringpop) setState(s state) { rp.stateMutex.Lock() oldState := rp.state rp.state = s rp.stateMutex.Unlock() // test if the state has changed with this call to setState if oldState != s { switch s { case ready: rp.EmitEvent(events.Ready{}) case destroyed: rp.EmitEvent(events.Destroyed{}) } } }
[ "func", "(", "rp", "*", "Ringpop", ")", "setState", "(", "s", "state", ")", "{", "rp", ".", "stateMutex", ".", "Lock", "(", ")", "\n", "oldState", ":=", "rp", ".", "state", "\n", "rp", ".", "state", "=", "s", "\n", "rp", ".", "stateMutex", ".", "Unlock", "(", ")", "\n\n", "// test if the state has changed with this call to setState", "if", "oldState", "!=", "s", "{", "switch", "s", "{", "case", "ready", ":", "rp", ".", "EmitEvent", "(", "events", ".", "Ready", "{", "}", ")", "\n", "case", "destroyed", ":", "rp", ".", "EmitEvent", "(", "events", ".", "Destroyed", "{", "}", ")", "\n", "}", "\n", "}", "\n", "}" ]
// setState sets the state of the current Ringpop instance. It will emit an appropriate // event when the state will actually change
[ "setState", "sets", "the", "state", "of", "the", "current", "Ringpop", "instance", ".", "It", "will", "emit", "an", "appropriate", "event", "when", "the", "state", "will", "actually", "change" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L361-L376
train
uber/ringpop-go
ringpop.go
SelfEvict
func (rp *Ringpop) SelfEvict() error { if !rp.Ready() { return ErrNotBootstrapped } return rp.node.SelfEvict() }
go
func (rp *Ringpop) SelfEvict() error { if !rp.Ready() { return ErrNotBootstrapped } return rp.node.SelfEvict() }
[ "func", "(", "rp", "*", "Ringpop", ")", "SelfEvict", "(", ")", "error", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "ErrNotBootstrapped", "\n", "}", "\n", "return", "rp", ".", "node", ".", "SelfEvict", "(", ")", "\n", "}" ]
// SelfEvict should be called before shutting down the application. When calling // this function ringpop will gracefully evict itself from the network. Utilities // that hook into ringpop will have the opportunity to hook into this system to // gracefully handle the shutdown of ringpop.
[ "SelfEvict", "should", "be", "called", "before", "shutting", "down", "the", "application", ".", "When", "calling", "this", "function", "ringpop", "will", "gracefully", "evict", "itself", "from", "the", "network", ".", "Utilities", "that", "hook", "into", "ringpop", "will", "have", "the", "opportunity", "to", "hook", "into", "this", "system", "to", "gracefully", "handle", "the", "shutdown", "of", "ringpop", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L396-L401
train
uber/ringpop-go
ringpop.go
Bootstrap
func (rp *Ringpop) Bootstrap(bootstrapOpts *swim.BootstrapOptions) ([]string, error) { if rp.getState() < initialized { err := rp.init() if err != nil { return nil, err } } // We shouldn't try to bootstrap if the channel is not listening if rp.channel.State() != tchannel.ChannelListening { rp.logger.WithField("channelState", rp.channel.State()).Error(ErrChannelNotListening.Error()) return nil, ErrChannelNotListening } joined, err := rp.node.Bootstrap(bootstrapOpts) if err != nil { rp.logger.WithField("error", err).Info("bootstrap failed") rp.setState(initialized) return nil, err } rp.setState(ready) rp.logger.WithField("joined", joined).Info("bootstrap complete") return joined, nil }
go
func (rp *Ringpop) Bootstrap(bootstrapOpts *swim.BootstrapOptions) ([]string, error) { if rp.getState() < initialized { err := rp.init() if err != nil { return nil, err } } // We shouldn't try to bootstrap if the channel is not listening if rp.channel.State() != tchannel.ChannelListening { rp.logger.WithField("channelState", rp.channel.State()).Error(ErrChannelNotListening.Error()) return nil, ErrChannelNotListening } joined, err := rp.node.Bootstrap(bootstrapOpts) if err != nil { rp.logger.WithField("error", err).Info("bootstrap failed") rp.setState(initialized) return nil, err } rp.setState(ready) rp.logger.WithField("joined", joined).Info("bootstrap complete") return joined, nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "Bootstrap", "(", "bootstrapOpts", "*", "swim", ".", "BootstrapOptions", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "rp", ".", "getState", "(", ")", "<", "initialized", "{", "err", ":=", "rp", ".", "init", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// We shouldn't try to bootstrap if the channel is not listening", "if", "rp", ".", "channel", ".", "State", "(", ")", "!=", "tchannel", ".", "ChannelListening", "{", "rp", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "rp", ".", "channel", ".", "State", "(", ")", ")", ".", "Error", "(", "ErrChannelNotListening", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "ErrChannelNotListening", "\n", "}", "\n\n", "joined", ",", "err", ":=", "rp", ".", "node", ".", "Bootstrap", "(", "bootstrapOpts", ")", "\n", "if", "err", "!=", "nil", "{", "rp", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "err", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "rp", ".", "setState", "(", "initialized", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "rp", ".", "setState", "(", "ready", ")", "\n\n", "rp", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "joined", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "joined", ",", "nil", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Bootstrap // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Bootstrap starts communication for this Ringpop instance. // // When Bootstrap is called, this Ringpop instance will attempt to contact // other instances from the DiscoverProvider. // // If no seed hosts are provided, a single-node cluster will be created.
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Bootstrap", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Bootstrap", "starts", "communication", "for", "this", "Ringpop", "instance", ".", "When", "Bootstrap", "is", "called", "this", "Ringpop", "instance", "will", "attempt", "to", "contact", "other", "instances", "from", "the", "DiscoverProvider", ".", "If", "no", "seed", "hosts", "are", "provided", "a", "single", "-", "node", "cluster", "will", "be", "created", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L415-L440
train
uber/ringpop-go
ringpop.go
Ready
func (rp *Ringpop) Ready() bool { if rp.getState() != ready { return false } return rp.node.Ready() }
go
func (rp *Ringpop) Ready() bool { if rp.getState() != ready { return false } return rp.node.Ready() }
[ "func", "(", "rp", "*", "Ringpop", ")", "Ready", "(", ")", "bool", "{", "if", "rp", ".", "getState", "(", ")", "!=", "ready", "{", "return", "false", "\n", "}", "\n", "return", "rp", ".", "node", ".", "Ready", "(", ")", "\n", "}" ]
// Ready returns whether or not ringpop is bootstrapped and ready to receive // requests.
[ "Ready", "returns", "whether", "or", "not", "ringpop", "is", "bootstrapped", "and", "ready", "to", "receive", "requests", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L444-L449
train
uber/ringpop-go
ringpop.go
Checksum
func (rp *Ringpop) Checksum() (uint32, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return rp.ring.Checksum(), nil }
go
func (rp *Ringpop) Checksum() (uint32, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return rp.ring.Checksum(), nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "Checksum", "(", ")", "(", "uint32", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "0", ",", "ErrNotBootstrapped", "\n", "}", "\n", "return", "rp", ".", "ring", ".", "Checksum", "(", ")", ",", "nil", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Ring // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Checksum returns the current checksum of this Ringpop instance's hashring.
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Ring", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Checksum", "returns", "the", "current", "checksum", "of", "this", "Ringpop", "instance", "s", "hashring", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L641-L646
train
uber/ringpop-go
ringpop.go
GetReachableMembers
func (rp *Ringpop) GetReachableMembers(predicates ...swim.MemberPredicate) ([]string, error) { if !rp.Ready() { return nil, ErrNotBootstrapped } members := rp.node.GetReachableMembers(predicates...) addresses := make([]string, 0, len(members)) for _, member := range members { addresses = append(addresses, member.Address) } return addresses, nil }
go
func (rp *Ringpop) GetReachableMembers(predicates ...swim.MemberPredicate) ([]string, error) { if !rp.Ready() { return nil, ErrNotBootstrapped } members := rp.node.GetReachableMembers(predicates...) addresses := make([]string, 0, len(members)) for _, member := range members { addresses = append(addresses, member.Address) } return addresses, nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "GetReachableMembers", "(", "predicates", "...", "swim", ".", "MemberPredicate", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "nil", ",", "ErrNotBootstrapped", "\n", "}", "\n\n", "members", ":=", "rp", ".", "node", ".", "GetReachableMembers", "(", "predicates", "...", ")", "\n\n", "addresses", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "members", ")", ")", "\n", "for", "_", ",", "member", ":=", "range", "members", "{", "addresses", "=", "append", "(", "addresses", ",", "member", ".", "Address", ")", "\n", "}", "\n", "return", "addresses", ",", "nil", "\n", "}" ]
// GetReachableMembers returns a slice of members currently in this instance's // active membership list that match all provided predicates.
[ "GetReachableMembers", "returns", "a", "slice", "of", "members", "currently", "in", "this", "instance", "s", "active", "membership", "list", "that", "match", "all", "provided", "predicates", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L712-L724
train
uber/ringpop-go
ringpop.go
CountReachableMembers
func (rp *Ringpop) CountReachableMembers(predicates ...swim.MemberPredicate) (int, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return rp.node.CountReachableMembers(predicates...), nil }
go
func (rp *Ringpop) CountReachableMembers(predicates ...swim.MemberPredicate) (int, error) { if !rp.Ready() { return 0, ErrNotBootstrapped } return rp.node.CountReachableMembers(predicates...), nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "CountReachableMembers", "(", "predicates", "...", "swim", ".", "MemberPredicate", ")", "(", "int", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "0", ",", "ErrNotBootstrapped", "\n", "}", "\n", "return", "rp", ".", "node", ".", "CountReachableMembers", "(", "predicates", "...", ")", ",", "nil", "\n", "}" ]
// CountReachableMembers returns the number of members currently in this // instance's active membership list that match all provided predicates.
[ "CountReachableMembers", "returns", "the", "number", "of", "members", "currently", "in", "this", "instance", "s", "active", "membership", "list", "that", "match", "all", "provided", "predicates", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L728-L733
train
uber/ringpop-go
ringpop.go
getStatKey
func (rp *Ringpop) getStatKey(key string) string { rp.stats.Lock() rpKey, ok := rp.stats.keys[key] if !ok { rpKey = fmt.Sprintf("%s.%s", rp.stats.prefix, key) rp.stats.keys[key] = rpKey } rp.stats.Unlock() return rpKey }
go
func (rp *Ringpop) getStatKey(key string) string { rp.stats.Lock() rpKey, ok := rp.stats.keys[key] if !ok { rpKey = fmt.Sprintf("%s.%s", rp.stats.prefix, key) rp.stats.keys[key] = rpKey } rp.stats.Unlock() return rpKey }
[ "func", "(", "rp", "*", "Ringpop", ")", "getStatKey", "(", "key", "string", ")", "string", "{", "rp", ".", "stats", ".", "Lock", "(", ")", "\n", "rpKey", ",", "ok", ":=", "rp", ".", "stats", ".", "keys", "[", "key", "]", "\n", "if", "!", "ok", "{", "rpKey", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rp", ".", "stats", ".", "prefix", ",", "key", ")", "\n", "rp", ".", "stats", ".", "keys", "[", "key", "]", "=", "rpKey", "\n", "}", "\n", "rp", ".", "stats", ".", "Unlock", "(", ")", "\n\n", "return", "rpKey", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Stats // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Stats", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L741-L751
train
uber/ringpop-go
ringpop.go
HandleOrForward
func (rp *Ringpop) HandleOrForward(key string, request []byte, response *[]byte, service, endpoint string, format tchannel.Format, opts *forward.Options) (bool, error) { if !rp.Ready() { return false, ErrNotBootstrapped } dest, err := rp.Lookup(key) if err != nil { return false, err } address, err := rp.WhoAmI() if err != nil { return false, err } if dest == address { return true, nil } res, err := rp.Forward(dest, []string{key}, request, service, endpoint, format, opts) *response = res return false, err }
go
func (rp *Ringpop) HandleOrForward(key string, request []byte, response *[]byte, service, endpoint string, format tchannel.Format, opts *forward.Options) (bool, error) { if !rp.Ready() { return false, ErrNotBootstrapped } dest, err := rp.Lookup(key) if err != nil { return false, err } address, err := rp.WhoAmI() if err != nil { return false, err } if dest == address { return true, nil } res, err := rp.Forward(dest, []string{key}, request, service, endpoint, format, opts) *response = res return false, err }
[ "func", "(", "rp", "*", "Ringpop", ")", "HandleOrForward", "(", "key", "string", ",", "request", "[", "]", "byte", ",", "response", "*", "[", "]", "byte", ",", "service", ",", "endpoint", "string", ",", "format", "tchannel", ".", "Format", ",", "opts", "*", "forward", ".", "Options", ")", "(", "bool", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "false", ",", "ErrNotBootstrapped", "\n", "}", "\n\n", "dest", ",", "err", ":=", "rp", ".", "Lookup", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "address", ",", "err", ":=", "rp", ".", "WhoAmI", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "dest", "==", "address", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "res", ",", "err", ":=", "rp", ".", "Forward", "(", "dest", ",", "[", "]", "string", "{", "key", "}", ",", "request", ",", "service", ",", "endpoint", ",", "format", ",", "opts", ")", "\n", "*", "response", "=", "res", "\n\n", "return", "false", ",", "err", "\n", "}" ]
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // // Forwarding // //= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // HandleOrForward returns true if the request should be handled locally, or false // if it should be forwarded to a different node. If false is returned, forwarding // is taken care of internally by the method, and, if no error has occured, the // response is written in the provided response field.
[ "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "Forwarding", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "=", "HandleOrForward", "returns", "true", "if", "the", "request", "should", "be", "handled", "locally", "or", "false", "if", "it", "should", "be", "forwarded", "to", "a", "different", "node", ".", "If", "false", "is", "returned", "forwarding", "is", "taken", "care", "of", "internally", "by", "the", "method", "and", "if", "no", "error", "has", "occured", "the", "response", "is", "written", "in", "the", "provided", "response", "field", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L763-L788
train
uber/ringpop-go
ringpop.go
Forward
func (rp *Ringpop) Forward(dest string, keys []string, request []byte, service, endpoint string, format tchannel.Format, opts *forward.Options) ([]byte, error) { return rp.forwarder.ForwardRequest(request, dest, service, endpoint, keys, format, opts) }
go
func (rp *Ringpop) Forward(dest string, keys []string, request []byte, service, endpoint string, format tchannel.Format, opts *forward.Options) ([]byte, error) { return rp.forwarder.ForwardRequest(request, dest, service, endpoint, keys, format, opts) }
[ "func", "(", "rp", "*", "Ringpop", ")", "Forward", "(", "dest", "string", ",", "keys", "[", "]", "string", ",", "request", "[", "]", "byte", ",", "service", ",", "endpoint", "string", ",", "format", "tchannel", ".", "Format", ",", "opts", "*", "forward", ".", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "rp", ".", "forwarder", ".", "ForwardRequest", "(", "request", ",", "dest", ",", "service", ",", "endpoint", ",", "keys", ",", "format", ",", "opts", ")", "\n", "}" ]
// Forward forwards the request to given destination host and returns the response.
[ "Forward", "forwards", "the", "request", "to", "given", "destination", "host", "and", "returns", "the", "response", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L791-L795
train
uber/ringpop-go
ringpop.go
Labels
func (rp *Ringpop) Labels() (*swim.NodeLabels, error) { if !rp.Ready() { return nil, ErrNotBootstrapped } return rp.node.Labels(), nil }
go
func (rp *Ringpop) Labels() (*swim.NodeLabels, error) { if !rp.Ready() { return nil, ErrNotBootstrapped } return rp.node.Labels(), nil }
[ "func", "(", "rp", "*", "Ringpop", ")", "Labels", "(", ")", "(", "*", "swim", ".", "NodeLabels", ",", "error", ")", "{", "if", "!", "rp", ".", "Ready", "(", ")", "{", "return", "nil", ",", "ErrNotBootstrapped", "\n", "}", "\n\n", "return", "rp", ".", "node", ".", "Labels", "(", ")", ",", "nil", "\n", "}" ]
// Labels provides access to a mutator of ringpop Labels that will be shared on // the membership. Changes made on the mutator are synchronized accross the // cluster for other members to make local decisions on.
[ "Labels", "provides", "access", "to", "a", "mutator", "of", "ringpop", "Labels", "that", "will", "be", "shared", "on", "the", "membership", ".", "Changes", "made", "on", "the", "mutator", "are", "synchronized", "accross", "the", "cluster", "for", "other", "members", "to", "make", "local", "decisions", "on", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L800-L806
train
uber/ringpop-go
ringpop.go
SerializeThrift
func SerializeThrift(s athrift.TStruct) ([]byte, error) { var b []byte var buffer = bytes.NewBuffer(b) transport := athrift.NewStreamTransportW(buffer) if err := s.Write(athrift.NewTBinaryProtocolTransport(transport)); err != nil { return nil, err } if err := transport.Flush(); err != nil { return nil, err } return buffer.Bytes(), nil }
go
func SerializeThrift(s athrift.TStruct) ([]byte, error) { var b []byte var buffer = bytes.NewBuffer(b) transport := athrift.NewStreamTransportW(buffer) if err := s.Write(athrift.NewTBinaryProtocolTransport(transport)); err != nil { return nil, err } if err := transport.Flush(); err != nil { return nil, err } return buffer.Bytes(), nil }
[ "func", "SerializeThrift", "(", "s", "athrift", ".", "TStruct", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "b", "[", "]", "byte", "\n", "var", "buffer", "=", "bytes", ".", "NewBuffer", "(", "b", ")", "\n\n", "transport", ":=", "athrift", ".", "NewStreamTransportW", "(", "buffer", ")", "\n", "if", "err", ":=", "s", ".", "Write", "(", "athrift", ".", "NewTBinaryProtocolTransport", "(", "transport", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "transport", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buffer", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// SerializeThrift takes a thrift struct and returns the serialized bytes // of that struct using the thrift binary protocol. This is a temporary // measure before frames can forwarded directly past the endpoint to the proper // destinaiton.
[ "SerializeThrift", "takes", "a", "thrift", "struct", "and", "returns", "the", "serialized", "bytes", "of", "that", "struct", "using", "the", "thrift", "binary", "protocol", ".", "This", "is", "a", "temporary", "measure", "before", "frames", "can", "forwarded", "directly", "past", "the", "endpoint", "to", "the", "proper", "destinaiton", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L812-L825
train
uber/ringpop-go
ringpop.go
DeserializeThrift
func DeserializeThrift(b []byte, s athrift.TStruct) error { reader := bytes.NewReader(b) transport := athrift.NewStreamTransportR(reader) return s.Read(athrift.NewTBinaryProtocolTransport(transport)) }
go
func DeserializeThrift(b []byte, s athrift.TStruct) error { reader := bytes.NewReader(b) transport := athrift.NewStreamTransportR(reader) return s.Read(athrift.NewTBinaryProtocolTransport(transport)) }
[ "func", "DeserializeThrift", "(", "b", "[", "]", "byte", ",", "s", "athrift", ".", "TStruct", ")", "error", "{", "reader", ":=", "bytes", ".", "NewReader", "(", "b", ")", "\n", "transport", ":=", "athrift", ".", "NewStreamTransportR", "(", "reader", ")", "\n", "return", "s", ".", "Read", "(", "athrift", ".", "NewTBinaryProtocolTransport", "(", "transport", ")", ")", "\n", "}" ]
// DeserializeThrift takes a byte slice and attempts to write it into the // given thrift struct using the thrift binary protocol. This is a temporary // measure before frames can forwarded directly past the endpoint to the proper // destinaiton.
[ "DeserializeThrift", "takes", "a", "byte", "slice", "and", "attempts", "to", "write", "it", "into", "the", "given", "thrift", "struct", "using", "the", "thrift", "binary", "protocol", ".", "This", "is", "a", "temporary", "measure", "before", "frames", "can", "forwarded", "directly", "past", "the", "endpoint", "to", "the", "proper", "destinaiton", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/ringpop.go#L831-L835
train
uber/ringpop-go
swim/heal_partition.go
reincarnateNodes
func reincarnateNodes(node *Node, target string, changesForA, changesForB []Change) error { // reincarnate all nodes by disseminating that they are suspect node.healer.logger.WithField("target", target).Info("reincarnate nodes before we can merge the partitions") node.memberlist.Update(changesForA) var err error if len(changesForB) != 0 { _, err = sendPingWithChanges(node, target, changesForB, time.Second) } return err }
go
func reincarnateNodes(node *Node, target string, changesForA, changesForB []Change) error { // reincarnate all nodes by disseminating that they are suspect node.healer.logger.WithField("target", target).Info("reincarnate nodes before we can merge the partitions") node.memberlist.Update(changesForA) var err error if len(changesForB) != 0 { _, err = sendPingWithChanges(node, target, changesForB, time.Second) } return err }
[ "func", "reincarnateNodes", "(", "node", "*", "Node", ",", "target", "string", ",", "changesForA", ",", "changesForB", "[", "]", "Change", ")", "error", "{", "// reincarnate all nodes by disseminating that they are suspect", "node", ".", "healer", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "node", ".", "memberlist", ".", "Update", "(", "changesForA", ")", "\n\n", "var", "err", "error", "\n", "if", "len", "(", "changesForB", ")", "!=", "0", "{", "_", ",", "err", "=", "sendPingWithChanges", "(", "node", ",", "target", ",", "changesForB", ",", "time", ".", "Second", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// reincarnateNodes applies changesForA to this nodes membership, and sends a ping // with changesForB to B's membership, so that B will apply those changes in its // ping handler.
[ "reincarnateNodes", "applies", "changesForA", "to", "this", "nodes", "membership", "and", "sends", "a", "ping", "with", "changesForB", "to", "B", "s", "membership", "so", "that", "B", "will", "apply", "those", "changes", "in", "its", "ping", "handler", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_partition.go#L119-L130
train
uber/ringpop-go
swim/heal_partition.go
mergePartitions
func mergePartitions(node *Node, target string, MB []Change) error { node.healer.logger.WithField("target", target).Info("merge two partitions") // Add membership of B to this node, so that the membership // information of B will be disseminated through A. node.memberlist.Update(MB) // Send membership of A to the target node, so that the membership // information of partition A will be disseminated through B. MA := node.disseminator.MembershipAsChanges() _, err := sendPingWithChanges(node, target, MA, time.Second) return err }
go
func mergePartitions(node *Node, target string, MB []Change) error { node.healer.logger.WithField("target", target).Info("merge two partitions") // Add membership of B to this node, so that the membership // information of B will be disseminated through A. node.memberlist.Update(MB) // Send membership of A to the target node, so that the membership // information of partition A will be disseminated through B. MA := node.disseminator.MembershipAsChanges() _, err := sendPingWithChanges(node, target, MA, time.Second) return err }
[ "func", "mergePartitions", "(", "node", "*", "Node", ",", "target", "string", ",", "MB", "[", "]", "Change", ")", "error", "{", "node", ".", "healer", ".", "logger", ".", "WithField", "(", "\"", "\"", ",", "target", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// Add membership of B to this node, so that the membership", "// information of B will be disseminated through A.", "node", ".", "memberlist", ".", "Update", "(", "MB", ")", "\n\n", "// Send membership of A to the target node, so that the membership", "// information of partition A will be disseminated through B.", "MA", ":=", "node", ".", "disseminator", ".", "MembershipAsChanges", "(", ")", "\n", "_", ",", "err", ":=", "sendPingWithChanges", "(", "node", ",", "target", ",", "MA", ",", "time", ".", "Second", ")", "\n", "return", "err", "\n", "}" ]
// mergePartitions applies the membership of B to a and send the membership // A to B piggybacked on top of a ping.
[ "mergePartitions", "applies", "the", "membership", "of", "B", "to", "a", "and", "send", "the", "membership", "A", "to", "B", "piggybacked", "on", "top", "of", "a", "ping", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_partition.go#L134-L146
train
uber/ringpop-go
swim/heal_partition.go
pingableHosts
func pingableHosts(changes []Change) (ret []string) { for _, b := range changes { if b.isPingable() { ret = append(ret, b.Address) } } return }
go
func pingableHosts(changes []Change) (ret []string) { for _, b := range changes { if b.isPingable() { ret = append(ret, b.Address) } } return }
[ "func", "pingableHosts", "(", "changes", "[", "]", "Change", ")", "(", "ret", "[", "]", "string", ")", "{", "for", "_", ",", "b", ":=", "range", "changes", "{", "if", "b", ".", "isPingable", "(", ")", "{", "ret", "=", "append", "(", "ret", ",", "b", ".", "Address", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// pingableHosts returns the address of those changes that are pingable.
[ "pingableHosts", "returns", "the", "address", "of", "those", "changes", "that", "are", "pingable", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_partition.go#L149-L156
train
uber/ringpop-go
swim/heal_partition.go
selectMember
func selectMember(partition []Change, address string) (Change, bool) { for _, m := range partition { if m.Address == address { return m, true } } return Change{}, false }
go
func selectMember(partition []Change, address string) (Change, bool) { for _, m := range partition { if m.Address == address { return m, true } } return Change{}, false }
[ "func", "selectMember", "(", "partition", "[", "]", "Change", ",", "address", "string", ")", "(", "Change", ",", "bool", ")", "{", "for", "_", ",", "m", ":=", "range", "partition", "{", "if", "m", ".", "Address", "==", "address", "{", "return", "m", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "Change", "{", "}", ",", "false", "\n", "}" ]
// selectMember selects the member with the specified address from the partition.
[ "selectMember", "selects", "the", "member", "with", "the", "specified", "address", "from", "the", "partition", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/heal_partition.go#L159-L167
train
uber/ringpop-go
swim/memberlist.go
newMemberlist
func newMemberlist(n *Node, initialLabels LabelMap) *memberlist { m := &memberlist{ node: n, logger: logging.Logger("membership").WithField("local", n.address), // prepopulate the local member with its state local: &Member{ Address: n.Address(), Incarnation: nowInMillis(n.clock), Status: Alive, Labels: initialLabels, }, } m.members.byAddress = make(map[string]*Member) m.members.byAddress[m.local.Address] = m.local m.members.list = append(m.members.list, m.local) return m }
go
func newMemberlist(n *Node, initialLabels LabelMap) *memberlist { m := &memberlist{ node: n, logger: logging.Logger("membership").WithField("local", n.address), // prepopulate the local member with its state local: &Member{ Address: n.Address(), Incarnation: nowInMillis(n.clock), Status: Alive, Labels: initialLabels, }, } m.members.byAddress = make(map[string]*Member) m.members.byAddress[m.local.Address] = m.local m.members.list = append(m.members.list, m.local) return m }
[ "func", "newMemberlist", "(", "n", "*", "Node", ",", "initialLabels", "LabelMap", ")", "*", "memberlist", "{", "m", ":=", "&", "memberlist", "{", "node", ":", "n", ",", "logger", ":", "logging", ".", "Logger", "(", "\"", "\"", ")", ".", "WithField", "(", "\"", "\"", ",", "n", ".", "address", ")", ",", "// prepopulate the local member with its state", "local", ":", "&", "Member", "{", "Address", ":", "n", ".", "Address", "(", ")", ",", "Incarnation", ":", "nowInMillis", "(", "n", ".", "clock", ")", ",", "Status", ":", "Alive", ",", "Labels", ":", "initialLabels", ",", "}", ",", "}", "\n\n", "m", ".", "members", ".", "byAddress", "=", "make", "(", "map", "[", "string", "]", "*", "Member", ")", "\n", "m", ".", "members", ".", "byAddress", "[", "m", ".", "local", ".", "Address", "]", "=", "m", ".", "local", "\n", "m", ".", "members", ".", "list", "=", "append", "(", "m", ".", "members", ".", "list", ",", "m", ".", "local", ")", "\n\n", "return", "m", "\n", "}" ]
// newMemberlist returns a new member list
[ "newMemberlist", "returns", "a", "new", "member", "list" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist.go#L64-L83
train
uber/ringpop-go
swim/memberlist.go
ComputeChecksum
func (m *memberlist) ComputeChecksum() { startTime := time.Now() m.members.Lock() checksum := farm.Fingerprint32([]byte(m.genChecksumString())) oldChecksum := m.members.checksum m.members.checksum = checksum m.members.Unlock() if oldChecksum != checksum { m.logger.WithFields(bark.Fields{ "checksum": checksum, "oldChecksum": oldChecksum, }).Debug("ringpop membership computed new checksum") } m.node.EmitEvent(ChecksumComputeEvent{ Duration: time.Now().Sub(startTime), Checksum: checksum, OldChecksum: oldChecksum, }) }
go
func (m *memberlist) ComputeChecksum() { startTime := time.Now() m.members.Lock() checksum := farm.Fingerprint32([]byte(m.genChecksumString())) oldChecksum := m.members.checksum m.members.checksum = checksum m.members.Unlock() if oldChecksum != checksum { m.logger.WithFields(bark.Fields{ "checksum": checksum, "oldChecksum": oldChecksum, }).Debug("ringpop membership computed new checksum") } m.node.EmitEvent(ChecksumComputeEvent{ Duration: time.Now().Sub(startTime), Checksum: checksum, OldChecksum: oldChecksum, }) }
[ "func", "(", "m", "*", "memberlist", ")", "ComputeChecksum", "(", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "m", ".", "members", ".", "Lock", "(", ")", "\n", "checksum", ":=", "farm", ".", "Fingerprint32", "(", "[", "]", "byte", "(", "m", ".", "genChecksumString", "(", ")", ")", ")", "\n", "oldChecksum", ":=", "m", ".", "members", ".", "checksum", "\n", "m", ".", "members", ".", "checksum", "=", "checksum", "\n", "m", ".", "members", ".", "Unlock", "(", ")", "\n\n", "if", "oldChecksum", "!=", "checksum", "{", "m", ".", "logger", ".", "WithFields", "(", "bark", ".", "Fields", "{", "\"", "\"", ":", "checksum", ",", "\"", "\"", ":", "oldChecksum", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "m", ".", "node", ".", "EmitEvent", "(", "ChecksumComputeEvent", "{", "Duration", ":", "time", ".", "Now", "(", ")", ".", "Sub", "(", "startTime", ")", ",", "Checksum", ":", "checksum", ",", "OldChecksum", ":", "oldChecksum", ",", "}", ")", "\n", "}" ]
// computes membership checksum
[ "computes", "membership", "checksum" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist.go#L94-L114
train
uber/ringpop-go
swim/memberlist.go
genChecksumString
func (m *memberlist) genChecksumString() string { var strings sort.StringSlice var buffer bytes.Buffer for _, member := range m.members.list { // Don't include Tombstone nodes in the checksum to avoid // bringing them back to life through full syncs if member.Status == Tombstone { continue } // collect the string from the member and add it to the list of strings member.checksumString(&buffer) strings = append(strings, buffer.String()) // the buffer is reused for the next member and collection below buffer.Reset() } strings.Sort() for _, str := range strings { buffer.WriteString(str) buffer.WriteString(";") } return buffer.String() }
go
func (m *memberlist) genChecksumString() string { var strings sort.StringSlice var buffer bytes.Buffer for _, member := range m.members.list { // Don't include Tombstone nodes in the checksum to avoid // bringing them back to life through full syncs if member.Status == Tombstone { continue } // collect the string from the member and add it to the list of strings member.checksumString(&buffer) strings = append(strings, buffer.String()) // the buffer is reused for the next member and collection below buffer.Reset() } strings.Sort() for _, str := range strings { buffer.WriteString(str) buffer.WriteString(";") } return buffer.String() }
[ "func", "(", "m", "*", "memberlist", ")", "genChecksumString", "(", ")", "string", "{", "var", "strings", "sort", ".", "StringSlice", "\n", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "for", "_", ",", "member", ":=", "range", "m", ".", "members", ".", "list", "{", "// Don't include Tombstone nodes in the checksum to avoid", "// bringing them back to life through full syncs", "if", "member", ".", "Status", "==", "Tombstone", "{", "continue", "\n", "}", "\n\n", "// collect the string from the member and add it to the list of strings", "member", ".", "checksumString", "(", "&", "buffer", ")", "\n", "strings", "=", "append", "(", "strings", ",", "buffer", ".", "String", "(", ")", ")", "\n", "// the buffer is reused for the next member and collection below", "buffer", ".", "Reset", "(", ")", "\n", "}", "\n\n", "strings", ".", "Sort", "(", ")", "\n\n", "for", "_", ",", "str", ":=", "range", "strings", "{", "buffer", ".", "WriteString", "(", "str", ")", "\n", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// generates string to use when computing checksum
[ "generates", "string", "to", "use", "when", "computing", "checksum" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist.go#L117-L143
train
uber/ringpop-go
swim/memberlist.go
Member
func (m *memberlist) Member(address string) (*Member, bool) { var memberCopy *Member m.members.RLock() member, ok := m.members.byAddress[address] if member != nil { memberCopy = new(Member) *memberCopy = *member } m.members.RUnlock() return memberCopy, ok }
go
func (m *memberlist) Member(address string) (*Member, bool) { var memberCopy *Member m.members.RLock() member, ok := m.members.byAddress[address] if member != nil { memberCopy = new(Member) *memberCopy = *member } m.members.RUnlock() return memberCopy, ok }
[ "func", "(", "m", "*", "memberlist", ")", "Member", "(", "address", "string", ")", "(", "*", "Member", ",", "bool", ")", "{", "var", "memberCopy", "*", "Member", "\n", "m", ".", "members", ".", "RLock", "(", ")", "\n", "member", ",", "ok", ":=", "m", ".", "members", ".", "byAddress", "[", "address", "]", "\n", "if", "member", "!=", "nil", "{", "memberCopy", "=", "new", "(", "Member", ")", "\n", "*", "memberCopy", "=", "*", "member", "\n", "}", "\n", "m", ".", "members", ".", "RUnlock", "(", ")", "\n\n", "return", "memberCopy", ",", "ok", "\n", "}" ]
// returns the member at a specific address
[ "returns", "the", "member", "at", "a", "specific", "address" ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist.go#L146-L157
train
uber/ringpop-go
swim/memberlist.go
LocalMember
func (m *memberlist) LocalMember() (member Member) { m.members.Lock() // copy local member state member = *m.local m.members.Unlock() return }
go
func (m *memberlist) LocalMember() (member Member) { m.members.Lock() // copy local member state member = *m.local m.members.Unlock() return }
[ "func", "(", "m", "*", "memberlist", ")", "LocalMember", "(", ")", "(", "member", "Member", ")", "{", "m", ".", "members", ".", "Lock", "(", ")", "\n", "// copy local member state", "member", "=", "*", "m", ".", "local", "\n", "m", ".", "members", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// LocalMember returns a copy of the local Member in a thread safe way.
[ "LocalMember", "returns", "a", "copy", "of", "the", "local", "Member", "in", "a", "thread", "safe", "way", "." ]
6475220d53092c8264fc6ce9416a351c960fe9fc
https://github.com/uber/ringpop-go/blob/6475220d53092c8264fc6ce9416a351c960fe9fc/swim/memberlist.go#L160-L166
train