id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
11,700 | gogs/git-module | repo_commit.go | CommitsAfterDate | func (repo *Repository) CommitsAfterDate(date string) (*list.List, error) {
stdout, err := NewCommand("log", _PRETTY_LOG_FORMAT, "--since="+date).RunInDirBytes(repo.Path)
if err != nil {
return nil, err
}
return repo.parsePrettyFormatLogToList(stdout)
} | go | func (repo *Repository) CommitsAfterDate(date string) (*list.List, error) {
stdout, err := NewCommand("log", _PRETTY_LOG_FORMAT, "--since="+date).RunInDirBytes(repo.Path)
if err != nil {
return nil, err
}
return repo.parsePrettyFormatLogToList(stdout)
} | [
"func",
"(",
"repo",
"*",
"Repository",
")",
"CommitsAfterDate",
"(",
"date",
"string",
")",
"(",
"*",
"list",
".",
"List",
",",
"error",
")",
"{",
"stdout",
",",
"err",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"_PRETTY_LOG_FORMAT",
",",
"\"",
"\"",
"+",
"date",
")",
".",
"RunInDirBytes",
"(",
"repo",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"repo",
".",
"parsePrettyFormatLogToList",
"(",
"stdout",
")",
"\n",
"}"
]
| // CommitsAfterDate returns a list of commits which committed after given date.
// The format of date should be in RFC3339. | [
"CommitsAfterDate",
"returns",
"a",
"list",
"of",
"commits",
"which",
"committed",
"after",
"given",
"date",
".",
"The",
"format",
"of",
"date",
"should",
"be",
"in",
"RFC3339",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo_commit.go#L381-L388 |
11,701 | gogs/git-module | repo_tag.go | GetTag | func (repo *Repository) GetTag(name string) (*Tag, error) {
stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path)
if err != nil {
return nil, err
}
id, err := NewIDFromString(strings.Split(stdout, " ")[0])
if err != nil {
return nil, err
}
tag, err := repo.getTag(id)
if err != nil {
return nil, err
}
tag.Name = name
return tag, nil
} | go | func (repo *Repository) GetTag(name string) (*Tag, error) {
stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path)
if err != nil {
return nil, err
}
id, err := NewIDFromString(strings.Split(stdout, " ")[0])
if err != nil {
return nil, err
}
tag, err := repo.getTag(id)
if err != nil {
return nil, err
}
tag.Name = name
return tag, nil
} | [
"func",
"(",
"repo",
"*",
"Repository",
")",
"GetTag",
"(",
"name",
"string",
")",
"(",
"*",
"Tag",
",",
"error",
")",
"{",
"stdout",
",",
"err",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"name",
")",
".",
"RunInDir",
"(",
"repo",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"id",
",",
"err",
":=",
"NewIDFromString",
"(",
"strings",
".",
"Split",
"(",
"stdout",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"tag",
",",
"err",
":=",
"repo",
".",
"getTag",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tag",
".",
"Name",
"=",
"name",
"\n",
"return",
"tag",
",",
"nil",
"\n",
"}"
]
| // GetTag returns a Git tag by given name. | [
"GetTag",
"returns",
"a",
"Git",
"tag",
"by",
"given",
"name",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo_tag.go#L76-L93 |
11,702 | gogs/git-module | repo_tag.go | GetTags | func (repo *Repository) GetTags() ([]string, error) {
cmd := NewCommand("tag", "-l")
if version.Compare(gitVersion, "2.4.9", ">=") {
cmd.AddArguments("--sort=-creatordate")
}
stdout, err := cmd.RunInDir(repo.Path)
if err != nil {
return nil, err
}
tags := strings.Split(stdout, "\n")
tags = tags[:len(tags)-1]
if version.Compare(gitVersion, "2.4.9", "<") {
version.Sort(tags)
// Reverse order
for i := 0; i < len(tags)/2; i++ {
j := len(tags) - i - 1
tags[i], tags[j] = tags[j], tags[i]
}
}
return tags, nil
} | go | func (repo *Repository) GetTags() ([]string, error) {
cmd := NewCommand("tag", "-l")
if version.Compare(gitVersion, "2.4.9", ">=") {
cmd.AddArguments("--sort=-creatordate")
}
stdout, err := cmd.RunInDir(repo.Path)
if err != nil {
return nil, err
}
tags := strings.Split(stdout, "\n")
tags = tags[:len(tags)-1]
if version.Compare(gitVersion, "2.4.9", "<") {
version.Sort(tags)
// Reverse order
for i := 0; i < len(tags)/2; i++ {
j := len(tags) - i - 1
tags[i], tags[j] = tags[j], tags[i]
}
}
return tags, nil
} | [
"func",
"(",
"repo",
"*",
"Repository",
")",
"GetTags",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"version",
".",
"Compare",
"(",
"gitVersion",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"stdout",
",",
"err",
":=",
"cmd",
".",
"RunInDir",
"(",
"repo",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"tags",
":=",
"strings",
".",
"Split",
"(",
"stdout",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"tags",
"=",
"tags",
"[",
":",
"len",
"(",
"tags",
")",
"-",
"1",
"]",
"\n\n",
"if",
"version",
".",
"Compare",
"(",
"gitVersion",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"{",
"version",
".",
"Sort",
"(",
"tags",
")",
"\n\n",
"// Reverse order",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"tags",
")",
"/",
"2",
";",
"i",
"++",
"{",
"j",
":=",
"len",
"(",
"tags",
")",
"-",
"i",
"-",
"1",
"\n",
"tags",
"[",
"i",
"]",
",",
"tags",
"[",
"j",
"]",
"=",
"tags",
"[",
"j",
"]",
",",
"tags",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"tags",
",",
"nil",
"\n",
"}"
]
| // GetTags returns all tags of the repository. | [
"GetTags",
"returns",
"all",
"tags",
"of",
"the",
"repository",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo_tag.go#L96-L121 |
11,703 | gogs/git-module | repo_tag.go | DeleteTag | func (repo *Repository) DeleteTag(name string) error {
cmd := NewCommand("tag", "-d")
cmd.AddArguments(name)
_, err := cmd.RunInDir(repo.Path)
return err
} | go | func (repo *Repository) DeleteTag(name string) error {
cmd := NewCommand("tag", "-d")
cmd.AddArguments(name)
_, err := cmd.RunInDir(repo.Path)
return err
} | [
"func",
"(",
"repo",
"*",
"Repository",
")",
"DeleteTag",
"(",
"name",
"string",
")",
"error",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"cmd",
".",
"AddArguments",
"(",
"name",
")",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunInDir",
"(",
"repo",
".",
"Path",
")",
"\n\n",
"return",
"err",
"\n",
"}"
]
| // DeleteTag deletes a tag from the repository | [
"DeleteTag",
"deletes",
"a",
"tag",
"from",
"the",
"repository"
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo_tag.go#L202-L209 |
11,704 | gogs/git-module | tree.go | UnescapeChars | func UnescapeChars(in []byte) []byte {
// LEGACY [Go 1.7]: use more expressive bytes.ContainsAny
if bytes.IndexAny(in, "\\\t") == -1 {
return in
}
out := bytes.Replace(in, escapedSlash, regularSlash, -1)
out = bytes.Replace(out, escapedTab, regularTab, -1)
return out
} | go | func UnescapeChars(in []byte) []byte {
// LEGACY [Go 1.7]: use more expressive bytes.ContainsAny
if bytes.IndexAny(in, "\\\t") == -1 {
return in
}
out := bytes.Replace(in, escapedSlash, regularSlash, -1)
out = bytes.Replace(out, escapedTab, regularTab, -1)
return out
} | [
"func",
"UnescapeChars",
"(",
"in",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"// LEGACY [Go 1.7]: use more expressive bytes.ContainsAny",
"if",
"bytes",
".",
"IndexAny",
"(",
"in",
",",
"\"",
"\\\\",
"\\t",
"\"",
")",
"==",
"-",
"1",
"{",
"return",
"in",
"\n",
"}",
"\n\n",
"out",
":=",
"bytes",
".",
"Replace",
"(",
"in",
",",
"escapedSlash",
",",
"regularSlash",
",",
"-",
"1",
")",
"\n",
"out",
"=",
"bytes",
".",
"Replace",
"(",
"out",
",",
"escapedTab",
",",
"regularTab",
",",
"-",
"1",
")",
"\n",
"return",
"out",
"\n",
"}"
]
| // UnescapeChars reverses escaped characters. | [
"UnescapeChars",
"reverses",
"escaped",
"characters",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/tree.go#L41-L50 |
11,705 | gogs/git-module | tree.go | ListEntries | func (t *Tree) ListEntries() (Entries, error) {
if t.entriesParsed {
return t.entries, nil
}
t.entriesParsed = true
stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path)
if err != nil {
return nil, err
}
t.entries, err = parseTreeData(t, stdout)
return t.entries, err
} | go | func (t *Tree) ListEntries() (Entries, error) {
if t.entriesParsed {
return t.entries, nil
}
t.entriesParsed = true
stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path)
if err != nil {
return nil, err
}
t.entries, err = parseTreeData(t, stdout)
return t.entries, err
} | [
"func",
"(",
"t",
"*",
"Tree",
")",
"ListEntries",
"(",
")",
"(",
"Entries",
",",
"error",
")",
"{",
"if",
"t",
".",
"entriesParsed",
"{",
"return",
"t",
".",
"entries",
",",
"nil",
"\n",
"}",
"\n",
"t",
".",
"entriesParsed",
"=",
"true",
"\n\n",
"stdout",
",",
"err",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"t",
".",
"ID",
".",
"String",
"(",
")",
")",
".",
"RunInDirBytes",
"(",
"t",
".",
"repo",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"t",
".",
"entries",
",",
"err",
"=",
"parseTreeData",
"(",
"t",
",",
"stdout",
")",
"\n",
"return",
"t",
".",
"entries",
",",
"err",
"\n",
"}"
]
| // ListEntries returns all entries of current tree. | [
"ListEntries",
"returns",
"all",
"entries",
"of",
"current",
"tree",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/tree.go#L137-L149 |
11,706 | gogs/git-module | repo.go | IsRepoURLAccessible | func IsRepoURLAccessible(opts NetworkOptions) bool {
cmd := NewCommand("ls-remote", "-q", "-h", opts.URL, "HEAD")
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunTimeout(opts.Timeout)
if err != nil {
return false
}
return true
} | go | func IsRepoURLAccessible(opts NetworkOptions) bool {
cmd := NewCommand("ls-remote", "-q", "-h", opts.URL, "HEAD")
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunTimeout(opts.Timeout)
if err != nil {
return false
}
return true
} | [
"func",
"IsRepoURLAccessible",
"(",
"opts",
"NetworkOptions",
")",
"bool",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"opts",
".",
"URL",
",",
"\"",
"\"",
")",
"\n",
"if",
"opts",
".",
"Timeout",
"<=",
"0",
"{",
"opts",
".",
"Timeout",
"=",
"-",
"1",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunTimeout",
"(",
"opts",
".",
"Timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
]
| // IsRepoURLAccessible checks if given repository URL is accessible. | [
"IsRepoURLAccessible",
"checks",
"if",
"given",
"repository",
"URL",
"is",
"accessible",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L55-L65 |
11,707 | gogs/git-module | repo.go | InitRepository | func InitRepository(repoPath string, bare bool) error {
os.MkdirAll(repoPath, os.ModePerm)
cmd := NewCommand("init")
if bare {
cmd.AddArguments("--bare")
}
_, err := cmd.RunInDir(repoPath)
return err
} | go | func InitRepository(repoPath string, bare bool) error {
os.MkdirAll(repoPath, os.ModePerm)
cmd := NewCommand("init")
if bare {
cmd.AddArguments("--bare")
}
_, err := cmd.RunInDir(repoPath)
return err
} | [
"func",
"InitRepository",
"(",
"repoPath",
"string",
",",
"bare",
"bool",
")",
"error",
"{",
"os",
".",
"MkdirAll",
"(",
"repoPath",
",",
"os",
".",
"ModePerm",
")",
"\n\n",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"bare",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunInDir",
"(",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // InitRepository initializes a new Git repository. | [
"InitRepository",
"initializes",
"a",
"new",
"Git",
"repository",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L68-L77 |
11,708 | gogs/git-module | repo.go | OpenRepository | func OpenRepository(repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath)
if err != nil {
return nil, err
} else if !isDir(repoPath) {
return nil, errors.New("no such file or directory")
}
return &Repository{
Path: repoPath,
commitCache: newObjectCache(),
tagCache: newObjectCache(),
}, nil
} | go | func OpenRepository(repoPath string) (*Repository, error) {
repoPath, err := filepath.Abs(repoPath)
if err != nil {
return nil, err
} else if !isDir(repoPath) {
return nil, errors.New("no such file or directory")
}
return &Repository{
Path: repoPath,
commitCache: newObjectCache(),
tagCache: newObjectCache(),
}, nil
} | [
"func",
"OpenRepository",
"(",
"repoPath",
"string",
")",
"(",
"*",
"Repository",
",",
"error",
")",
"{",
"repoPath",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"repoPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"else",
"if",
"!",
"isDir",
"(",
"repoPath",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Repository",
"{",
"Path",
":",
"repoPath",
",",
"commitCache",
":",
"newObjectCache",
"(",
")",
",",
"tagCache",
":",
"newObjectCache",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
]
| // OpenRepository opens the repository at the given path. | [
"OpenRepository",
"opens",
"the",
"repository",
"at",
"the",
"given",
"path",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L80-L93 |
11,709 | gogs/git-module | repo.go | Clone | func Clone(from, to string, opts CloneRepoOptions) (err error) {
toDir := path.Dir(to)
if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
return err
}
cmd := NewCommand("clone")
if opts.Mirror {
cmd.AddArguments("--mirror")
}
if opts.Bare {
cmd.AddArguments("--bare")
}
if opts.Quiet {
cmd.AddArguments("--quiet")
}
if len(opts.Branch) > 0 {
cmd.AddArguments("-b", opts.Branch)
}
cmd.AddArguments(from, to)
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err = cmd.RunTimeout(opts.Timeout)
return err
} | go | func Clone(from, to string, opts CloneRepoOptions) (err error) {
toDir := path.Dir(to)
if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
return err
}
cmd := NewCommand("clone")
if opts.Mirror {
cmd.AddArguments("--mirror")
}
if opts.Bare {
cmd.AddArguments("--bare")
}
if opts.Quiet {
cmd.AddArguments("--quiet")
}
if len(opts.Branch) > 0 {
cmd.AddArguments("-b", opts.Branch)
}
cmd.AddArguments(from, to)
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err = cmd.RunTimeout(opts.Timeout)
return err
} | [
"func",
"Clone",
"(",
"from",
",",
"to",
"string",
",",
"opts",
"CloneRepoOptions",
")",
"(",
"err",
"error",
")",
"{",
"toDir",
":=",
"path",
".",
"Dir",
"(",
"to",
")",
"\n",
"if",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"toDir",
",",
"os",
".",
"ModePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"opts",
".",
"Mirror",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"Bare",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"Quiet",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"opts",
".",
"Branch",
")",
">",
"0",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
",",
"opts",
".",
"Branch",
")",
"\n",
"}",
"\n",
"cmd",
".",
"AddArguments",
"(",
"from",
",",
"to",
")",
"\n\n",
"if",
"opts",
".",
"Timeout",
"<=",
"0",
"{",
"opts",
".",
"Timeout",
"=",
"-",
"1",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"cmd",
".",
"RunTimeout",
"(",
"opts",
".",
"Timeout",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Clone clones original repository to target path. | [
"Clone",
"clones",
"original",
"repository",
"to",
"target",
"path",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L104-L130 |
11,710 | gogs/git-module | repo.go | Fetch | func Fetch(repoPath string, opts FetchRemoteOptions) error {
cmd := NewCommand("fetch")
if opts.Prune {
cmd.AddArguments("--prune")
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | go | func Fetch(repoPath string, opts FetchRemoteOptions) error {
cmd := NewCommand("fetch")
if opts.Prune {
cmd.AddArguments("--prune")
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | [
"func",
"Fetch",
"(",
"repoPath",
"string",
",",
"opts",
"FetchRemoteOptions",
")",
"error",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"opts",
".",
"Prune",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"opts",
".",
"Timeout",
"<=",
"0",
"{",
"opts",
".",
"Timeout",
"=",
"-",
"1",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunInDirTimeout",
"(",
"opts",
".",
"Timeout",
",",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Fetch fetches changes from remotes without merging. | [
"Fetch",
"fetches",
"changes",
"from",
"remotes",
"without",
"merging",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L138-L149 |
11,711 | gogs/git-module | repo.go | Pull | func Pull(repoPath string, opts PullRemoteOptions) error {
cmd := NewCommand("pull")
if opts.Rebase {
cmd.AddArguments("--rebase")
}
if opts.All {
cmd.AddArguments("--all")
} else {
cmd.AddArguments(opts.Remote)
cmd.AddArguments(opts.Branch)
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | go | func Pull(repoPath string, opts PullRemoteOptions) error {
cmd := NewCommand("pull")
if opts.Rebase {
cmd.AddArguments("--rebase")
}
if opts.All {
cmd.AddArguments("--all")
} else {
cmd.AddArguments(opts.Remote)
cmd.AddArguments(opts.Branch)
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | [
"func",
"Pull",
"(",
"repoPath",
"string",
",",
"opts",
"PullRemoteOptions",
")",
"error",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"opts",
".",
"Rebase",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"All",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"cmd",
".",
"AddArguments",
"(",
"opts",
".",
"Remote",
")",
"\n",
"cmd",
".",
"AddArguments",
"(",
"opts",
".",
"Branch",
")",
"\n",
"}",
"\n\n",
"if",
"opts",
".",
"Timeout",
"<=",
"0",
"{",
"opts",
".",
"Timeout",
"=",
"-",
"1",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunInDirTimeout",
"(",
"opts",
".",
"Timeout",
",",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Pull pulls changes from remotes. | [
"Pull",
"pulls",
"changes",
"from",
"remotes",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L160-L177 |
11,712 | gogs/git-module | repo.go | PushWithEnvs | func PushWithEnvs(repoPath, remote, branch string, envs []string) error {
_, err := NewCommand("push", remote, branch).AddEnvs(envs...).RunInDir(repoPath)
return err
} | go | func PushWithEnvs(repoPath, remote, branch string, envs []string) error {
_, err := NewCommand("push", remote, branch).AddEnvs(envs...).RunInDir(repoPath)
return err
} | [
"func",
"PushWithEnvs",
"(",
"repoPath",
",",
"remote",
",",
"branch",
"string",
",",
"envs",
"[",
"]",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"remote",
",",
"branch",
")",
".",
"AddEnvs",
"(",
"envs",
"...",
")",
".",
"RunInDir",
"(",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // PushWithEnvs pushs local commits to given remote branch with given environment variables. | [
"PushWithEnvs",
"pushs",
"local",
"commits",
"to",
"given",
"remote",
"branch",
"with",
"given",
"environment",
"variables",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L180-L183 |
11,713 | gogs/git-module | repo.go | Push | func Push(repoPath, remote, branch string) error {
return PushWithEnvs(repoPath, remote, branch, nil)
} | go | func Push(repoPath, remote, branch string) error {
return PushWithEnvs(repoPath, remote, branch, nil)
} | [
"func",
"Push",
"(",
"repoPath",
",",
"remote",
",",
"branch",
"string",
")",
"error",
"{",
"return",
"PushWithEnvs",
"(",
"repoPath",
",",
"remote",
",",
"branch",
",",
"nil",
")",
"\n",
"}"
]
| // Push pushs local commits to given remote branch. | [
"Push",
"pushs",
"local",
"commits",
"to",
"given",
"remote",
"branch",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L186-L188 |
11,714 | gogs/git-module | repo.go | Checkout | func Checkout(repoPath string, opts CheckoutOptions) error {
cmd := NewCommand("checkout")
if len(opts.OldBranch) > 0 {
cmd.AddArguments("-b")
}
cmd.AddArguments(opts.Branch)
if len(opts.OldBranch) > 0 {
cmd.AddArguments(opts.OldBranch)
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | go | func Checkout(repoPath string, opts CheckoutOptions) error {
cmd := NewCommand("checkout")
if len(opts.OldBranch) > 0 {
cmd.AddArguments("-b")
}
cmd.AddArguments(opts.Branch)
if len(opts.OldBranch) > 0 {
cmd.AddArguments(opts.OldBranch)
}
if opts.Timeout <= 0 {
opts.Timeout = -1
}
_, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
return err
} | [
"func",
"Checkout",
"(",
"repoPath",
"string",
",",
"opts",
"CheckoutOptions",
")",
"error",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"opts",
".",
"OldBranch",
")",
">",
"0",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"cmd",
".",
"AddArguments",
"(",
"opts",
".",
"Branch",
")",
"\n\n",
"if",
"len",
"(",
"opts",
".",
"OldBranch",
")",
">",
"0",
"{",
"cmd",
".",
"AddArguments",
"(",
"opts",
".",
"OldBranch",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"Timeout",
"<=",
"0",
"{",
"opts",
".",
"Timeout",
"=",
"-",
"1",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"RunInDirTimeout",
"(",
"opts",
".",
"Timeout",
",",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Checkout checkouts a branch | [
"Checkout",
"checkouts",
"a",
"branch"
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L197-L213 |
11,715 | gogs/git-module | repo.go | ResetHEAD | func ResetHEAD(repoPath string, hard bool, revision string) error {
cmd := NewCommand("reset")
if hard {
cmd.AddArguments("--hard")
}
_, err := cmd.AddArguments(revision).RunInDir(repoPath)
return err
} | go | func ResetHEAD(repoPath string, hard bool, revision string) error {
cmd := NewCommand("reset")
if hard {
cmd.AddArguments("--hard")
}
_, err := cmd.AddArguments(revision).RunInDir(repoPath)
return err
} | [
"func",
"ResetHEAD",
"(",
"repoPath",
"string",
",",
"hard",
"bool",
",",
"revision",
"string",
")",
"error",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
"\n",
"if",
"hard",
"{",
"cmd",
".",
"AddArguments",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"cmd",
".",
"AddArguments",
"(",
"revision",
")",
".",
"RunInDir",
"(",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // ResetHEAD resets HEAD to given revision or head of branch. | [
"ResetHEAD",
"resets",
"HEAD",
"to",
"given",
"revision",
"or",
"head",
"of",
"branch",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L216-L223 |
11,716 | gogs/git-module | repo.go | MoveFile | func MoveFile(repoPath, oldTreeName, newTreeName string) error {
_, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
return err
} | go | func MoveFile(repoPath, oldTreeName, newTreeName string) error {
_, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
return err
} | [
"func",
"MoveFile",
"(",
"repoPath",
",",
"oldTreeName",
",",
"newTreeName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"NewCommand",
"(",
"\"",
"\"",
")",
".",
"AddArguments",
"(",
"oldTreeName",
",",
"newTreeName",
")",
".",
"RunInDir",
"(",
"repoPath",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // MoveFile moves a file to another file or directory. | [
"MoveFile",
"moves",
"a",
"file",
"to",
"another",
"file",
"or",
"directory",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L226-L229 |
11,717 | gogs/git-module | repo.go | GetRepoSize | func GetRepoSize(repoPath string) (*CountObject, error) {
cmd := NewCommand("count-objects", "-v")
stdout, err := cmd.RunInDir(repoPath)
if err != nil {
return nil, err
}
countObject := new(CountObject)
for _, line := range strings.Split(stdout, "\n") {
switch {
case strings.HasPrefix(line, _STAT_COUNT):
countObject.Count = com.StrTo(line[7:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE):
countObject.Size = com.StrTo(line[6:]).MustInt64() * 1024
case strings.HasPrefix(line, _STAT_IN_PACK):
countObject.InPack = com.StrTo(line[9:]).MustInt64()
case strings.HasPrefix(line, _STAT_PACKS):
countObject.Packs = com.StrTo(line[7:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE_PACK):
countObject.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
case strings.HasPrefix(line, _STAT_PRUNE_PACKABLE):
countObject.PrunePackable = com.StrTo(line[16:]).MustInt64()
case strings.HasPrefix(line, _STAT_GARBAGE):
countObject.Garbage = com.StrTo(line[9:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE_GARBAGE):
countObject.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
}
}
return countObject, nil
} | go | func GetRepoSize(repoPath string) (*CountObject, error) {
cmd := NewCommand("count-objects", "-v")
stdout, err := cmd.RunInDir(repoPath)
if err != nil {
return nil, err
}
countObject := new(CountObject)
for _, line := range strings.Split(stdout, "\n") {
switch {
case strings.HasPrefix(line, _STAT_COUNT):
countObject.Count = com.StrTo(line[7:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE):
countObject.Size = com.StrTo(line[6:]).MustInt64() * 1024
case strings.HasPrefix(line, _STAT_IN_PACK):
countObject.InPack = com.StrTo(line[9:]).MustInt64()
case strings.HasPrefix(line, _STAT_PACKS):
countObject.Packs = com.StrTo(line[7:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE_PACK):
countObject.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
case strings.HasPrefix(line, _STAT_PRUNE_PACKABLE):
countObject.PrunePackable = com.StrTo(line[16:]).MustInt64()
case strings.HasPrefix(line, _STAT_GARBAGE):
countObject.Garbage = com.StrTo(line[9:]).MustInt64()
case strings.HasPrefix(line, _STAT_SIZE_GARBAGE):
countObject.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
}
}
return countObject, nil
} | [
"func",
"GetRepoSize",
"(",
"repoPath",
"string",
")",
"(",
"*",
"CountObject",
",",
"error",
")",
"{",
"cmd",
":=",
"NewCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"stdout",
",",
"err",
":=",
"cmd",
".",
"RunInDir",
"(",
"repoPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"countObject",
":=",
"new",
"(",
"CountObject",
")",
"\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"stdout",
",",
"\"",
"\\n",
"\"",
")",
"{",
"switch",
"{",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_COUNT",
")",
":",
"countObject",
".",
"Count",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"7",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_SIZE",
")",
":",
"countObject",
".",
"Size",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"6",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"*",
"1024",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_IN_PACK",
")",
":",
"countObject",
".",
"InPack",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"9",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_PACKS",
")",
":",
"countObject",
".",
"Packs",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"7",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_SIZE_PACK",
")",
":",
"countObject",
".",
"SizePack",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"11",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"*",
"1024",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_PRUNE_PACKABLE",
")",
":",
"countObject",
".",
"PrunePackable",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"16",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_GARBAGE",
")",
":",
"countObject",
".",
"Garbage",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"9",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"_STAT_SIZE_GARBAGE",
")",
":",
"countObject",
".",
"SizeGarbage",
"=",
"com",
".",
"StrTo",
"(",
"line",
"[",
"14",
":",
"]",
")",
".",
"MustInt64",
"(",
")",
"*",
"1024",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"countObject",
",",
"nil",
"\n",
"}"
]
| // GetRepoSize returns disk usage report of repository in given path. | [
"GetRepoSize",
"returns",
"disk",
"usage",
"report",
"of",
"repository",
"in",
"given",
"path",
"."
]
| d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164 | https://github.com/gogs/git-module/blob/d1773fe06f37f5e2c92d0ed6dd50c11bf1a17164/repo.go#L255-L285 |
11,718 | Landoop/schema-registry | client.go | UsingClient | func UsingClient(httpClient *http.Client) Option {
return func(c *Client) {
if httpClient == nil {
return
}
transport := getTransportLayer(httpClient, 0)
httpClient.Transport = transport
c.client = httpClient
}
} | go | func UsingClient(httpClient *http.Client) Option {
return func(c *Client) {
if httpClient == nil {
return
}
transport := getTransportLayer(httpClient, 0)
httpClient.Transport = transport
c.client = httpClient
}
} | [
"func",
"UsingClient",
"(",
"httpClient",
"*",
"http",
".",
"Client",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"if",
"httpClient",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"transport",
":=",
"getTransportLayer",
"(",
"httpClient",
",",
"0",
")",
"\n",
"httpClient",
".",
"Transport",
"=",
"transport",
"\n\n",
"c",
".",
"client",
"=",
"httpClient",
"\n",
"}",
"\n",
"}"
]
| // UsingClient modifies the underline HTTP Client that schema registry is using for contact with the backend server. | [
"UsingClient",
"modifies",
"the",
"underline",
"HTTP",
"Client",
"that",
"schema",
"registry",
"is",
"using",
"for",
"contact",
"with",
"the",
"backend",
"server",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L42-L53 |
11,719 | Landoop/schema-registry | client.go | NewClient | func NewClient(baseURL string, options ...Option) (*Client, error) {
baseURL = formatBaseURL(baseURL)
if _, err := url.Parse(baseURL); err != nil {
return nil, err
}
c := &Client{baseURL: baseURL}
for _, opt := range options {
opt(c)
}
if c.client == nil {
httpClient := &http.Client{}
UsingClient(httpClient)(c)
}
return c, nil
} | go | func NewClient(baseURL string, options ...Option) (*Client, error) {
baseURL = formatBaseURL(baseURL)
if _, err := url.Parse(baseURL); err != nil {
return nil, err
}
c := &Client{baseURL: baseURL}
for _, opt := range options {
opt(c)
}
if c.client == nil {
httpClient := &http.Client{}
UsingClient(httpClient)(c)
}
return c, nil
} | [
"func",
"NewClient",
"(",
"baseURL",
"string",
",",
"options",
"...",
"Option",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"baseURL",
"=",
"formatBaseURL",
"(",
"baseURL",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"baseURL",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
":=",
"&",
"Client",
"{",
"baseURL",
":",
"baseURL",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"options",
"{",
"opt",
"(",
"c",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"client",
"==",
"nil",
"{",
"httpClient",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"UsingClient",
"(",
"httpClient",
")",
"(",
"c",
")",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}"
]
| // NewClient creates & returns a new Registry Schema Client
// based on the passed url and the options. | [
"NewClient",
"creates",
"&",
"returns",
"a",
"new",
"Registry",
"Schema",
"Client",
"based",
"on",
"the",
"passed",
"url",
"and",
"the",
"options",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L119-L136 |
11,720 | Landoop/schema-registry | client.go | IsSubjectNotFound | func IsSubjectNotFound(err error) bool {
if err == nil {
return false
}
if resErr, ok := err.(ResourceError); ok {
return resErr.ErrorCode == subjectNotFoundCode
}
return false
} | go | func IsSubjectNotFound(err error) bool {
if err == nil {
return false
}
if resErr, ok := err.(ResourceError); ok {
return resErr.ErrorCode == subjectNotFoundCode
}
return false
} | [
"func",
"IsSubjectNotFound",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"resErr",
",",
"ok",
":=",
"err",
".",
"(",
"ResourceError",
")",
";",
"ok",
"{",
"return",
"resErr",
".",
"ErrorCode",
"==",
"subjectNotFoundCode",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
]
| // IsSubjectNotFound checks the returned error to see if it is kind of a subject not found error code. | [
"IsSubjectNotFound",
"checks",
"the",
"returned",
"error",
"to",
"see",
"if",
"it",
"is",
"kind",
"of",
"a",
"subject",
"not",
"found",
"error",
"code",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L179-L189 |
11,721 | Landoop/schema-registry | client.go | IsSchemaNotFound | func IsSchemaNotFound(err error) bool {
if err == nil {
return false
}
if resErr, ok := err.(ResourceError); ok {
return resErr.ErrorCode == schemaNotFoundCode
}
return false
} | go | func IsSchemaNotFound(err error) bool {
if err == nil {
return false
}
if resErr, ok := err.(ResourceError); ok {
return resErr.ErrorCode == schemaNotFoundCode
}
return false
} | [
"func",
"IsSchemaNotFound",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"resErr",
",",
"ok",
":=",
"err",
".",
"(",
"ResourceError",
")",
";",
"ok",
"{",
"return",
"resErr",
".",
"ErrorCode",
"==",
"schemaNotFoundCode",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
]
| // IsSchemaNotFound checks the returned error to see if it is kind of a schema not found error code. | [
"IsSchemaNotFound",
"checks",
"the",
"returned",
"error",
"to",
"see",
"if",
"it",
"is",
"kind",
"of",
"a",
"schema",
"not",
"found",
"error",
"code",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L192-L202 |
11,722 | Landoop/schema-registry | client.go | Versions | func (c *Client) Versions(subject string) (versions []int, err error) {
if subject == "" {
err = errRequired("subject")
return
}
// # List all versions of a particular subject
// GET /subjects/(string: subject)/versions
path := fmt.Sprintf(subjectPath, subject+"/versions")
resp, respErr := c.do(http.MethodGet, path, "", nil)
if respErr != nil {
err = respErr
return
}
err = c.readJSON(resp, &versions)
return
} | go | func (c *Client) Versions(subject string) (versions []int, err error) {
if subject == "" {
err = errRequired("subject")
return
}
// # List all versions of a particular subject
// GET /subjects/(string: subject)/versions
path := fmt.Sprintf(subjectPath, subject+"/versions")
resp, respErr := c.do(http.MethodGet, path, "", nil)
if respErr != nil {
err = respErr
return
}
err = c.readJSON(resp, &versions)
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Versions",
"(",
"subject",
"string",
")",
"(",
"versions",
"[",
"]",
"int",
",",
"err",
"error",
")",
"{",
"if",
"subject",
"==",
"\"",
"\"",
"{",
"err",
"=",
"errRequired",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// # List all versions of a particular subject",
"// GET /subjects/(string: subject)/versions",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"subjectPath",
",",
"subject",
"+",
"\"",
"\"",
")",
"\n",
"resp",
",",
"respErr",
":=",
"c",
".",
"do",
"(",
"http",
".",
"MethodGet",
",",
"path",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"respErr",
"!=",
"nil",
"{",
"err",
"=",
"respErr",
"\n",
"return",
"\n",
"}",
"\n\n",
"err",
"=",
"c",
".",
"readJSON",
"(",
"resp",
",",
"&",
"versions",
")",
"\n",
"return",
"\n",
"}"
]
| // Versions returns all schema version numbers registered for this subject. | [
"Versions",
"returns",
"all",
"schema",
"version",
"numbers",
"registered",
"for",
"this",
"subject",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L374-L391 |
11,723 | Landoop/schema-registry | client.go | IsRegistered | func (c *Client) IsRegistered(subject, schema string) (bool, Schema, error) {
var fs Schema
sc := schemaOnlyJSON{schema}
send, err := json.Marshal(sc)
if err != nil {
return false, fs, err
}
path := fmt.Sprintf(subjectPath, subject)
resp, err := c.do(http.MethodPost, path, "", send)
if err != nil {
// schema not found?
if IsSchemaNotFound(err) {
return false, fs, nil
}
// error?
return false, fs, err
}
if err = c.readJSON(resp, &fs); err != nil {
return true, fs, err // found but error when unmarshal.
}
// so we have a schema.
return true, fs, nil
} | go | func (c *Client) IsRegistered(subject, schema string) (bool, Schema, error) {
var fs Schema
sc := schemaOnlyJSON{schema}
send, err := json.Marshal(sc)
if err != nil {
return false, fs, err
}
path := fmt.Sprintf(subjectPath, subject)
resp, err := c.do(http.MethodPost, path, "", send)
if err != nil {
// schema not found?
if IsSchemaNotFound(err) {
return false, fs, nil
}
// error?
return false, fs, err
}
if err = c.readJSON(resp, &fs); err != nil {
return true, fs, err // found but error when unmarshal.
}
// so we have a schema.
return true, fs, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"IsRegistered",
"(",
"subject",
",",
"schema",
"string",
")",
"(",
"bool",
",",
"Schema",
",",
"error",
")",
"{",
"var",
"fs",
"Schema",
"\n\n",
"sc",
":=",
"schemaOnlyJSON",
"{",
"schema",
"}",
"\n",
"send",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"sc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fs",
",",
"err",
"\n",
"}",
"\n\n",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"subjectPath",
",",
"subject",
")",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"do",
"(",
"http",
".",
"MethodPost",
",",
"path",
",",
"\"",
"\"",
",",
"send",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// schema not found?",
"if",
"IsSchemaNotFound",
"(",
"err",
")",
"{",
"return",
"false",
",",
"fs",
",",
"nil",
"\n",
"}",
"\n",
"// error?",
"return",
"false",
",",
"fs",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"c",
".",
"readJSON",
"(",
"resp",
",",
"&",
"fs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"true",
",",
"fs",
",",
"err",
"// found but error when unmarshal.",
"\n",
"}",
"\n\n",
"// so we have a schema.",
"return",
"true",
",",
"fs",
",",
"nil",
"\n",
"}"
]
| // IsRegistered tells if the given "schema" is registered for this "subject". | [
"IsRegistered",
"tells",
"if",
"the",
"given",
"schema",
"is",
"registered",
"for",
"this",
"subject",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L415-L441 |
11,724 | Landoop/schema-registry | client.go | GetSchemaBySubject | func (c *Client) GetSchemaBySubject(subject string, versionID int) (Schema, error) {
return c.getSubjectSchemaAtVersion(subject, versionID)
} | go | func (c *Client) GetSchemaBySubject(subject string, versionID int) (Schema, error) {
return c.getSubjectSchemaAtVersion(subject, versionID)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetSchemaBySubject",
"(",
"subject",
"string",
",",
"versionID",
"int",
")",
"(",
"Schema",
",",
"error",
")",
"{",
"return",
"c",
".",
"getSubjectSchemaAtVersion",
"(",
"subject",
",",
"versionID",
")",
"\n",
"}"
]
| // GetSchemaBySubject returns the schema for a particular subject and version. | [
"GetSchemaBySubject",
"returns",
"the",
"schema",
"for",
"a",
"particular",
"subject",
"and",
"version",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L596-L598 |
11,725 | Landoop/schema-registry | client.go | getConfigSubject | func (c *Client) getConfigSubject(subject string) (Config, error) {
var err error
var config = Config{}
path := fmt.Sprintf("/config/%s", subject)
resp, respErr := c.do(http.MethodGet, path, "", nil)
if respErr != nil && respErr.(ResourceError).ErrorCode != 404 {
return config, respErr
}
if resp != nil {
err = c.readJSON(resp, &config)
}
return config, err
} | go | func (c *Client) getConfigSubject(subject string) (Config, error) {
var err error
var config = Config{}
path := fmt.Sprintf("/config/%s", subject)
resp, respErr := c.do(http.MethodGet, path, "", nil)
if respErr != nil && respErr.(ResourceError).ErrorCode != 404 {
return config, respErr
}
if resp != nil {
err = c.readJSON(resp, &config)
}
return config, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"getConfigSubject",
"(",
"subject",
"string",
")",
"(",
"Config",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"config",
"=",
"Config",
"{",
"}",
"\n\n",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"subject",
")",
"\n",
"resp",
",",
"respErr",
":=",
"c",
".",
"do",
"(",
"http",
".",
"MethodGet",
",",
"path",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"respErr",
"!=",
"nil",
"&&",
"respErr",
".",
"(",
"ResourceError",
")",
".",
"ErrorCode",
"!=",
"404",
"{",
"return",
"config",
",",
"respErr",
"\n",
"}",
"\n",
"if",
"resp",
"!=",
"nil",
"{",
"err",
"=",
"c",
".",
"readJSON",
"(",
"resp",
",",
"&",
"config",
")",
"\n",
"}",
"\n\n",
"return",
"config",
",",
"err",
"\n",
"}"
]
| // getConfigSubject returns the Config of global or for a given subject. It handles 404 error in a
// different way, since not-found for a subject configuration means it's using global. | [
"getConfigSubject",
"returns",
"the",
"Config",
"of",
"global",
"or",
"for",
"a",
"given",
"subject",
".",
"It",
"handles",
"404",
"error",
"in",
"a",
"different",
"way",
"since",
"not",
"-",
"found",
"for",
"a",
"subject",
"configuration",
"means",
"it",
"s",
"using",
"global",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L608-L622 |
11,726 | Landoop/schema-registry | client.go | IsSchemaCompatible | func (c *Client) IsSchemaCompatible(subject string, avroSchema string, versionID int) (bool, error) {
return c.isSchemaCompatibleAtVersion(subject, avroSchema, versionID)
} | go | func (c *Client) IsSchemaCompatible(subject string, avroSchema string, versionID int) (bool, error) {
return c.isSchemaCompatibleAtVersion(subject, avroSchema, versionID)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"IsSchemaCompatible",
"(",
"subject",
"string",
",",
"avroSchema",
"string",
",",
"versionID",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"c",
".",
"isSchemaCompatibleAtVersion",
"(",
"subject",
",",
"avroSchema",
",",
"versionID",
")",
"\n",
"}"
]
| // IsSchemaCompatible tests compatibility with a specific version of a subject's schema. | [
"IsSchemaCompatible",
"tests",
"compatibility",
"with",
"a",
"specific",
"version",
"of",
"a",
"subject",
"s",
"schema",
"."
]
| 50a5701c1891dabf97cf5904c4b3a6761d7367d9 | https://github.com/Landoop/schema-registry/blob/50a5701c1891dabf97cf5904c4b3a6761d7367d9/client.go#L678-L680 |
11,727 | containous/flaeg | parse/parse.go | Set | func (i *Int64Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = Int64Value(v)
return err
} | go | func (i *Int64Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = Int64Value(v)
return err
} | [
"func",
"(",
"i",
"*",
"Int64Value",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"v",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"s",
",",
"0",
",",
"64",
")",
"\n",
"*",
"i",
"=",
"Int64Value",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Set sets int64 value from the given string value. | [
"Set",
"sets",
"int64",
"value",
"from",
"the",
"given",
"string",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L73-L77 |
11,728 | containous/flaeg | parse/parse.go | Set | func (i *UintValue) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = UintValue(v)
return err
} | go | func (i *UintValue) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = UintValue(v)
return err
} | [
"func",
"(",
"i",
"*",
"UintValue",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"v",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"s",
",",
"0",
",",
"64",
")",
"\n",
"*",
"i",
"=",
"UintValue",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Set sets uint value from the given string value. | [
"Set",
"sets",
"uint",
"value",
"from",
"the",
"given",
"string",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L93-L97 |
11,729 | containous/flaeg | parse/parse.go | Set | func (s *StringValue) Set(val string) error {
*s = StringValue(val)
return nil
} | go | func (s *StringValue) Set(val string) error {
*s = StringValue(val)
return nil
} | [
"func",
"(",
"s",
"*",
"StringValue",
")",
"Set",
"(",
"val",
"string",
")",
"error",
"{",
"*",
"s",
"=",
"StringValue",
"(",
"val",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // Set sets string value from the given string value. | [
"Set",
"sets",
"string",
"value",
"from",
"the",
"given",
"string",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L133-L136 |
11,730 | containous/flaeg | parse/parse.go | Set | func (d *Duration) Set(s string) error {
if v, err := strconv.ParseInt(s, 10, 64); err == nil {
*d = Duration(time.Duration(v) * time.Second)
return nil
}
v, err := time.ParseDuration(s)
*d = Duration(v)
return err
} | go | func (d *Duration) Set(s string) error {
if v, err := strconv.ParseInt(s, 10, 64); err == nil {
*d = Duration(time.Duration(v) * time.Second)
return nil
}
v, err := time.ParseDuration(s)
*d = Duration(v)
return err
} | [
"func",
"(",
"d",
"*",
"Duration",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"if",
"v",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"s",
",",
"10",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"*",
"d",
"=",
"Duration",
"(",
"time",
".",
"Duration",
"(",
"v",
")",
"*",
"time",
".",
"Second",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"s",
")",
"\n",
"*",
"d",
"=",
"Duration",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Set sets the duration from the given string value. | [
"Set",
"sets",
"the",
"duration",
"from",
"the",
"given",
"string",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L174-L183 |
11,731 | containous/flaeg | parse/parse.go | UnmarshalText | func (d *Duration) UnmarshalText(text []byte) error {
return d.Set(string(text))
} | go | func (d *Duration) UnmarshalText(text []byte) error {
return d.Set(string(text))
} | [
"func",
"(",
"d",
"*",
"Duration",
")",
"UnmarshalText",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"d",
".",
"Set",
"(",
"string",
"(",
"text",
")",
")",
"\n",
"}"
]
| // UnmarshalText deserializes the given text into a duration value.
// It is meant to support TOML decoding of durations. | [
"UnmarshalText",
"deserializes",
"the",
"given",
"text",
"into",
"a",
"duration",
"value",
".",
"It",
"is",
"meant",
"to",
"support",
"TOML",
"decoding",
"of",
"durations",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L203-L205 |
11,732 | containous/flaeg | parse/parse.go | MarshalJSON | func (d *Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(*d))
} | go | func (d *Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(*d))
} | [
"func",
"(",
"d",
"*",
"Duration",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"time",
".",
"Duration",
"(",
"*",
"d",
")",
")",
"\n",
"}"
]
| // MarshalJSON serializes the given duration value. | [
"MarshalJSON",
"serializes",
"the",
"given",
"duration",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L208-L210 |
11,733 | containous/flaeg | parse/parse.go | UnmarshalJSON | func (d *Duration) UnmarshalJSON(text []byte) error {
if v, err := strconv.ParseInt(string(text), 10, 64); err == nil {
*d = Duration(time.Duration(v))
return nil
}
// We use json unmarshal on value because we have the quoted version
var value string
err := json.Unmarshal(text, &value)
if err != nil {
return err
}
v, err := time.ParseDuration(value)
*d = Duration(v)
return err
} | go | func (d *Duration) UnmarshalJSON(text []byte) error {
if v, err := strconv.ParseInt(string(text), 10, 64); err == nil {
*d = Duration(time.Duration(v))
return nil
}
// We use json unmarshal on value because we have the quoted version
var value string
err := json.Unmarshal(text, &value)
if err != nil {
return err
}
v, err := time.ParseDuration(value)
*d = Duration(v)
return err
} | [
"func",
"(",
"d",
"*",
"Duration",
")",
"UnmarshalJSON",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"v",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"string",
"(",
"text",
")",
",",
"10",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"*",
"d",
"=",
"Duration",
"(",
"time",
".",
"Duration",
"(",
"v",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// We use json unmarshal on value because we have the quoted version",
"var",
"value",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"text",
",",
"&",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"v",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"value",
")",
"\n",
"*",
"d",
"=",
"Duration",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // UnmarshalJSON deserializes the given text into a duration value. | [
"UnmarshalJSON",
"deserializes",
"the",
"given",
"text",
"into",
"a",
"duration",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L213-L228 |
11,734 | containous/flaeg | parse/parse.go | Set | func (t *TimeValue) Set(s string) error {
v, err := time.Parse(time.RFC3339, s)
*t = TimeValue(v)
return err
} | go | func (t *TimeValue) Set(s string) error {
v, err := time.Parse(time.RFC3339, s)
*t = TimeValue(v)
return err
} | [
"func",
"(",
"t",
"*",
"TimeValue",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"v",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"s",
")",
"\n",
"*",
"t",
"=",
"TimeValue",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
]
| // Set sets time.Time value from the given string value. | [
"Set",
"sets",
"time",
".",
"Time",
"value",
"from",
"the",
"given",
"string",
"value",
"."
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L234-L238 |
11,735 | containous/flaeg | parse/parse.go | Set | func (s *SliceStrings) Set(str string) error {
fargs := func(c rune) bool {
return c == ',' || c == ';'
}
// get function
slice := strings.FieldsFunc(str, fargs)
*s = append(*s, slice...)
return nil
} | go | func (s *SliceStrings) Set(str string) error {
fargs := func(c rune) bool {
return c == ',' || c == ';'
}
// get function
slice := strings.FieldsFunc(str, fargs)
*s = append(*s, slice...)
return nil
} | [
"func",
"(",
"s",
"*",
"SliceStrings",
")",
"Set",
"(",
"str",
"string",
")",
"error",
"{",
"fargs",
":=",
"func",
"(",
"c",
"rune",
")",
"bool",
"{",
"return",
"c",
"==",
"','",
"||",
"c",
"==",
"';'",
"\n",
"}",
"\n",
"// get function",
"slice",
":=",
"strings",
".",
"FieldsFunc",
"(",
"str",
",",
"fargs",
")",
"\n",
"*",
"s",
"=",
"append",
"(",
"*",
"s",
",",
"slice",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
]
| // Set adds strings elem into the the parser.
// It splits str on , and ; | [
"Set",
"adds",
"strings",
"elem",
"into",
"the",
"the",
"parser",
".",
"It",
"splits",
"str",
"on",
"and",
";"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/parse/parse.go#L255-L263 |
11,736 | containous/flaeg | flaeg.go | getTypesRecursive | func getTypesRecursive(objValue reflect.Value, flagMap map[string]reflect.StructField, key string) error {
name := key
switch objValue.Kind() {
case reflect.Struct:
for i := 0; i < objValue.NumField(); i++ {
if objValue.Type().Field(i).Anonymous {
if err := getTypesRecursive(objValue.Field(i), flagMap, name); err != nil {
return err
}
} else if len(objValue.Type().Field(i).Tag.Get("description")) > 0 {
fieldName := objValue.Type().Field(i).Name
if !isExported(fieldName) {
return fmt.Errorf("field %s is an unexported field", fieldName)
}
if tag := objValue.Type().Field(i).Tag.Get("long"); len(tag) > 0 {
fieldName = tag
}
if len(key) == 0 {
name = strings.ToLower(fieldName)
} else {
name = key + "." + strings.ToLower(fieldName)
}
if _, ok := flagMap[name]; ok {
return fmt.Errorf("tag already exists: %s", name)
}
flagMap[name] = objValue.Type().Field(i)
if err := getTypesRecursive(objValue.Field(i), flagMap, name); err != nil {
return err
}
}
}
case reflect.Ptr:
if len(key) > 0 {
field := flagMap[name]
field.Type = reflect.TypeOf(false)
flagMap[name] = field
}
typ := objValue.Type().Elem()
inst := reflect.New(typ).Elem()
if err := getTypesRecursive(inst, flagMap, name); err != nil {
return err
}
default:
return nil
}
return nil
} | go | func getTypesRecursive(objValue reflect.Value, flagMap map[string]reflect.StructField, key string) error {
name := key
switch objValue.Kind() {
case reflect.Struct:
for i := 0; i < objValue.NumField(); i++ {
if objValue.Type().Field(i).Anonymous {
if err := getTypesRecursive(objValue.Field(i), flagMap, name); err != nil {
return err
}
} else if len(objValue.Type().Field(i).Tag.Get("description")) > 0 {
fieldName := objValue.Type().Field(i).Name
if !isExported(fieldName) {
return fmt.Errorf("field %s is an unexported field", fieldName)
}
if tag := objValue.Type().Field(i).Tag.Get("long"); len(tag) > 0 {
fieldName = tag
}
if len(key) == 0 {
name = strings.ToLower(fieldName)
} else {
name = key + "." + strings.ToLower(fieldName)
}
if _, ok := flagMap[name]; ok {
return fmt.Errorf("tag already exists: %s", name)
}
flagMap[name] = objValue.Type().Field(i)
if err := getTypesRecursive(objValue.Field(i), flagMap, name); err != nil {
return err
}
}
}
case reflect.Ptr:
if len(key) > 0 {
field := flagMap[name]
field.Type = reflect.TypeOf(false)
flagMap[name] = field
}
typ := objValue.Type().Elem()
inst := reflect.New(typ).Elem()
if err := getTypesRecursive(inst, flagMap, name); err != nil {
return err
}
default:
return nil
}
return nil
} | [
"func",
"getTypesRecursive",
"(",
"objValue",
"reflect",
".",
"Value",
",",
"flagMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
",",
"key",
"string",
")",
"error",
"{",
"name",
":=",
"key",
"\n",
"switch",
"objValue",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Struct",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"objValue",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"if",
"objValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
".",
"Anonymous",
"{",
"if",
"err",
":=",
"getTypesRecursive",
"(",
"objValue",
".",
"Field",
"(",
"i",
")",
",",
"flagMap",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"len",
"(",
"objValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
">",
"0",
"{",
"fieldName",
":=",
"objValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
".",
"Name",
"\n",
"if",
"!",
"isExported",
"(",
"fieldName",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fieldName",
")",
"\n",
"}",
"\n\n",
"if",
"tag",
":=",
"objValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"len",
"(",
"tag",
")",
">",
"0",
"{",
"fieldName",
"=",
"tag",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"key",
")",
"==",
"0",
"{",
"name",
"=",
"strings",
".",
"ToLower",
"(",
"fieldName",
")",
"\n",
"}",
"else",
"{",
"name",
"=",
"key",
"+",
"\"",
"\"",
"+",
"strings",
".",
"ToLower",
"(",
"fieldName",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"flagMap",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"flagMap",
"[",
"name",
"]",
"=",
"objValue",
".",
"Type",
"(",
")",
".",
"Field",
"(",
"i",
")",
"\n\n",
"if",
"err",
":=",
"getTypesRecursive",
"(",
"objValue",
".",
"Field",
"(",
"i",
")",
",",
"flagMap",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Ptr",
":",
"if",
"len",
"(",
"key",
")",
">",
"0",
"{",
"field",
":=",
"flagMap",
"[",
"name",
"]",
"\n",
"field",
".",
"Type",
"=",
"reflect",
".",
"TypeOf",
"(",
"false",
")",
"\n",
"flagMap",
"[",
"name",
"]",
"=",
"field",
"\n",
"}",
"\n\n",
"typ",
":=",
"objValue",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
"\n",
"inst",
":=",
"reflect",
".",
"New",
"(",
"typ",
")",
".",
"Elem",
"(",
")",
"\n\n",
"if",
"err",
":=",
"getTypesRecursive",
"(",
"inst",
",",
"flagMap",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // GetTypesRecursive links in flagMap a flag with its reflect.StructField
// You can whether provide objValue on a structure or a pointer to structure as first argument
// Flags are generated from field name or from StructTag | [
"GetTypesRecursive",
"links",
"in",
"flagMap",
"a",
"flag",
"with",
"its",
"reflect",
".",
"StructField",
"You",
"can",
"whether",
"provide",
"objValue",
"on",
"a",
"structure",
"or",
"a",
"pointer",
"to",
"structure",
"as",
"first",
"argument",
"Flags",
"are",
"generated",
"from",
"field",
"name",
"or",
"from",
"StructTag"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L26-L78 |
11,737 | containous/flaeg | flaeg.go | GetBoolFlags | func GetBoolFlags(config interface{}) ([]string, error) {
flagMap := make(map[string]reflect.StructField)
if err := getTypesRecursive(reflect.ValueOf(config), flagMap, ""); err != nil {
return []string{}, err
}
flags := make([]string, 0, len(flagMap))
for f, structField := range flagMap {
if structField.Type.Kind() == reflect.Bool {
flags = append(flags, f)
}
}
return flags, nil
} | go | func GetBoolFlags(config interface{}) ([]string, error) {
flagMap := make(map[string]reflect.StructField)
if err := getTypesRecursive(reflect.ValueOf(config), flagMap, ""); err != nil {
return []string{}, err
}
flags := make([]string, 0, len(flagMap))
for f, structField := range flagMap {
if structField.Type.Kind() == reflect.Bool {
flags = append(flags, f)
}
}
return flags, nil
} | [
"func",
"GetBoolFlags",
"(",
"config",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"flagMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
")",
"\n",
"if",
"err",
":=",
"getTypesRecursive",
"(",
"reflect",
".",
"ValueOf",
"(",
"config",
")",
",",
"flagMap",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"flags",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"flagMap",
")",
")",
"\n",
"for",
"f",
",",
"structField",
":=",
"range",
"flagMap",
"{",
"if",
"structField",
".",
"Type",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Bool",
"{",
"flags",
"=",
"append",
"(",
"flags",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"flags",
",",
"nil",
"\n",
"}"
]
| // GetBoolFlags returns flags on pointers | [
"GetBoolFlags",
"returns",
"flags",
"on",
"pointers"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L81-L94 |
11,738 | containous/flaeg | flaeg.go | GetFlags | func GetFlags(config interface{}) ([]string, error) {
flagMap := make(map[string]reflect.StructField)
if err := getTypesRecursive(reflect.ValueOf(config), flagMap, ""); err != nil {
return []string{}, err
}
flags := make([]string, 0, len(flagMap))
for f := range flagMap {
flags = append(flags, f)
}
return flags, nil
} | go | func GetFlags(config interface{}) ([]string, error) {
flagMap := make(map[string]reflect.StructField)
if err := getTypesRecursive(reflect.ValueOf(config), flagMap, ""); err != nil {
return []string{}, err
}
flags := make([]string, 0, len(flagMap))
for f := range flagMap {
flags = append(flags, f)
}
return flags, nil
} | [
"func",
"GetFlags",
"(",
"config",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"flagMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
")",
"\n",
"if",
"err",
":=",
"getTypesRecursive",
"(",
"reflect",
".",
"ValueOf",
"(",
"config",
")",
",",
"flagMap",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n\n",
"flags",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"flagMap",
")",
")",
"\n",
"for",
"f",
":=",
"range",
"flagMap",
"{",
"flags",
"=",
"append",
"(",
"flags",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"flags",
",",
"nil",
"\n",
"}"
]
| // GetFlags returns flags | [
"GetFlags",
"returns",
"flags"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L97-L108 |
11,739 | containous/flaeg | flaeg.go | setPointersNil | func setPointersNil(objValue reflect.Value) (reflect.Value, error) {
switch {
case objValue.Kind() != reflect.Ptr:
return objValue, fmt.Errorf("parameters objValue must be a not-nil pointer on a struct, not a %s", objValue.Kind())
case objValue.IsNil():
return objValue, errors.New("parameters objValue must be a not-nil pointer")
case objValue.Elem().Kind() != reflect.Struct:
// fmt.Printf("Parameters objValue must be a not-nil pointer on a struct, not a pointer on a %s\n", objValue.Elem().Kind().String())
return objValue, nil
}
// Clone
starObjValue := objValue.Elem()
nilPointersObjVal := reflect.New(starObjValue.Type())
starNilPointersObjVal := nilPointersObjVal.Elem()
starNilPointersObjVal.Set(starObjValue)
for i := 0; i < nilPointersObjVal.Elem().NumField(); i++ {
if field := nilPointersObjVal.Elem().Field(i); field.Kind() == reflect.Ptr && field.CanSet() {
field.Set(reflect.Zero(field.Type()))
}
}
return nilPointersObjVal, nil
} | go | func setPointersNil(objValue reflect.Value) (reflect.Value, error) {
switch {
case objValue.Kind() != reflect.Ptr:
return objValue, fmt.Errorf("parameters objValue must be a not-nil pointer on a struct, not a %s", objValue.Kind())
case objValue.IsNil():
return objValue, errors.New("parameters objValue must be a not-nil pointer")
case objValue.Elem().Kind() != reflect.Struct:
// fmt.Printf("Parameters objValue must be a not-nil pointer on a struct, not a pointer on a %s\n", objValue.Elem().Kind().String())
return objValue, nil
}
// Clone
starObjValue := objValue.Elem()
nilPointersObjVal := reflect.New(starObjValue.Type())
starNilPointersObjVal := nilPointersObjVal.Elem()
starNilPointersObjVal.Set(starObjValue)
for i := 0; i < nilPointersObjVal.Elem().NumField(); i++ {
if field := nilPointersObjVal.Elem().Field(i); field.Kind() == reflect.Ptr && field.CanSet() {
field.Set(reflect.Zero(field.Type()))
}
}
return nilPointersObjVal, nil
} | [
"func",
"setPointersNil",
"(",
"objValue",
"reflect",
".",
"Value",
")",
"(",
"reflect",
".",
"Value",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"objValue",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
":",
"return",
"objValue",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"objValue",
".",
"Kind",
"(",
")",
")",
"\n",
"case",
"objValue",
".",
"IsNil",
"(",
")",
":",
"return",
"objValue",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"objValue",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
":",
"// fmt.Printf(\"Parameters objValue must be a not-nil pointer on a struct, not a pointer on a %s\\n\", objValue.Elem().Kind().String())",
"return",
"objValue",
",",
"nil",
"\n",
"}",
"\n\n",
"// Clone",
"starObjValue",
":=",
"objValue",
".",
"Elem",
"(",
")",
"\n",
"nilPointersObjVal",
":=",
"reflect",
".",
"New",
"(",
"starObjValue",
".",
"Type",
"(",
")",
")",
"\n",
"starNilPointersObjVal",
":=",
"nilPointersObjVal",
".",
"Elem",
"(",
")",
"\n",
"starNilPointersObjVal",
".",
"Set",
"(",
"starObjValue",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"nilPointersObjVal",
".",
"Elem",
"(",
")",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"if",
"field",
":=",
"nilPointersObjVal",
".",
"Elem",
"(",
")",
".",
"Field",
"(",
"i",
")",
";",
"field",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"&&",
"field",
".",
"CanSet",
"(",
")",
"{",
"field",
".",
"Set",
"(",
"reflect",
".",
"Zero",
"(",
"field",
".",
"Type",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nilPointersObjVal",
",",
"nil",
"\n",
"}"
]
| // objValue a reflect.Value of a not-nil pointer on a struct | [
"objValue",
"a",
"reflect",
".",
"Value",
"of",
"a",
"not",
"-",
"nil",
"pointer",
"on",
"a",
"struct"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L239-L262 |
11,740 | containous/flaeg | flaeg.go | setFields | func setFields(fieldValue reflect.Value, val parse.Parser) error {
if fieldValue.CanSet() {
fieldValue.Set(reflect.ValueOf(val).Elem().Convert(fieldValue.Type()))
} else {
return fmt.Errorf("%s is not settable", fieldValue.Type().String())
}
return nil
} | go | func setFields(fieldValue reflect.Value, val parse.Parser) error {
if fieldValue.CanSet() {
fieldValue.Set(reflect.ValueOf(val).Elem().Convert(fieldValue.Type()))
} else {
return fmt.Errorf("%s is not settable", fieldValue.Type().String())
}
return nil
} | [
"func",
"setFields",
"(",
"fieldValue",
"reflect",
".",
"Value",
",",
"val",
"parse",
".",
"Parser",
")",
"error",
"{",
"if",
"fieldValue",
".",
"CanSet",
"(",
")",
"{",
"fieldValue",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
".",
"Elem",
"(",
")",
".",
"Convert",
"(",
"fieldValue",
".",
"Type",
"(",
")",
")",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fieldValue",
".",
"Type",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
]
| // SetFields sets value to fieldValue using tag as key in valMap | [
"SetFields",
"sets",
"value",
"to",
"fieldValue",
"using",
"tag",
"as",
"key",
"in",
"valMap"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L346-L353 |
11,741 | containous/flaeg | flaeg.go | PrintHelp | func PrintHelp(flagMap map[string]reflect.StructField, defaultValmap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser) error {
return PrintHelpWithCommand(flagMap, defaultValmap, parsers, nil, nil)
} | go | func PrintHelp(flagMap map[string]reflect.StructField, defaultValmap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser) error {
return PrintHelpWithCommand(flagMap, defaultValmap, parsers, nil, nil)
} | [
"func",
"PrintHelp",
"(",
"flagMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
",",
"defaultValmap",
"map",
"[",
"string",
"]",
"reflect",
".",
"Value",
",",
"parsers",
"map",
"[",
"reflect",
".",
"Type",
"]",
"parse",
".",
"Parser",
")",
"error",
"{",
"return",
"PrintHelpWithCommand",
"(",
"flagMap",
",",
"defaultValmap",
",",
"parsers",
",",
"nil",
",",
"nil",
")",
"\n",
"}"
]
| // PrintHelp generates and prints command line help | [
"PrintHelp",
"generates",
"and",
"prints",
"command",
"line",
"help"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L356-L358 |
11,742 | containous/flaeg | flaeg.go | PrintError | func PrintError(err error, flagMap map[string]reflect.StructField, defaultValmap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser) error {
if err != flag.ErrHelp {
fmt.Printf("Error: %s\n", err)
}
if !strings.Contains(err.Error(), ":No parser for type") {
_ = PrintHelp(flagMap, defaultValmap, parsers)
}
return err
} | go | func PrintError(err error, flagMap map[string]reflect.StructField, defaultValmap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser) error {
if err != flag.ErrHelp {
fmt.Printf("Error: %s\n", err)
}
if !strings.Contains(err.Error(), ":No parser for type") {
_ = PrintHelp(flagMap, defaultValmap, parsers)
}
return err
} | [
"func",
"PrintError",
"(",
"err",
"error",
",",
"flagMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
",",
"defaultValmap",
"map",
"[",
"string",
"]",
"reflect",
".",
"Value",
",",
"parsers",
"map",
"[",
"reflect",
".",
"Type",
"]",
"parse",
".",
"Parser",
")",
"error",
"{",
"if",
"err",
"!=",
"flag",
".",
"ErrHelp",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"_",
"=",
"PrintHelp",
"(",
"flagMap",
",",
"defaultValmap",
",",
"parsers",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
]
| // PrintError takes a not nil error and prints command line help | [
"PrintError",
"takes",
"a",
"not",
"nil",
"error",
"and",
"prints",
"command",
"line",
"help"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L361-L369 |
11,743 | containous/flaeg | flaeg.go | PrintHelpWithCommand | func PrintHelpWithCommand(flagMap map[string]reflect.StructField, defaultValMap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser, cmd *Command, subCmd []*Command) error {
// Hide command from help
if cmd != nil && cmd.HideHelp {
return fmt.Errorf("command %s not found", cmd.Name)
}
// Define a templates
// Using POSXE STD : http://pubs.opengroup.org/onlinepubs/9699919799/
const helper = `{{if .ProgDescription}}{{.ProgDescription}}
{{end}}Usage: {{.ProgName}} [flags] <command> [<arguments>]
Use "{{.ProgName}} <command> --help" for help on any command.
{{if .SubCommands}}
Commands:{{range $subCmdName, $subCmdDesc := .SubCommands}}
{{printf "\t%-50s %s" $subCmdName $subCmdDesc}}{{end}}
{{end}}
Flag's usage: {{.ProgName}} [--flag=flag_argument] [-f[flag_argument]] ... set flag_argument to flag(s)
or: {{.ProgName}} [--flag[=true|false| ]] [-f[true|false| ]] ... set true/false to boolean flag(s)
Flags:
`
// Use a struct to give data to template
type TempStruct struct {
ProgName string
ProgDescription string
SubCommands map[string]string
}
tempStruct := TempStruct{}
if cmd != nil {
tempStruct.ProgName = cmd.Name
tempStruct.ProgDescription = cmd.Description
tempStruct.SubCommands = map[string]string{}
if len(subCmd) > 1 && cmd == subCmd[0] {
for _, c := range subCmd[1:] {
if !c.HideHelp {
tempStruct.SubCommands[c.Name] = c.Description
}
}
}
} else {
_, tempStruct.ProgName = path.Split(os.Args[0])
}
// Run Template
tmplHelper, err := template.New("helper").Parse(helper)
if err != nil {
return err
}
err = tmplHelper.Execute(os.Stdout, tempStruct)
if err != nil {
return err
}
return printFlagsDescriptionsDefaultValues(flagMap, defaultValMap, parsers, os.Stdout)
} | go | func PrintHelpWithCommand(flagMap map[string]reflect.StructField, defaultValMap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser, cmd *Command, subCmd []*Command) error {
// Hide command from help
if cmd != nil && cmd.HideHelp {
return fmt.Errorf("command %s not found", cmd.Name)
}
// Define a templates
// Using POSXE STD : http://pubs.opengroup.org/onlinepubs/9699919799/
const helper = `{{if .ProgDescription}}{{.ProgDescription}}
{{end}}Usage: {{.ProgName}} [flags] <command> [<arguments>]
Use "{{.ProgName}} <command> --help" for help on any command.
{{if .SubCommands}}
Commands:{{range $subCmdName, $subCmdDesc := .SubCommands}}
{{printf "\t%-50s %s" $subCmdName $subCmdDesc}}{{end}}
{{end}}
Flag's usage: {{.ProgName}} [--flag=flag_argument] [-f[flag_argument]] ... set flag_argument to flag(s)
or: {{.ProgName}} [--flag[=true|false| ]] [-f[true|false| ]] ... set true/false to boolean flag(s)
Flags:
`
// Use a struct to give data to template
type TempStruct struct {
ProgName string
ProgDescription string
SubCommands map[string]string
}
tempStruct := TempStruct{}
if cmd != nil {
tempStruct.ProgName = cmd.Name
tempStruct.ProgDescription = cmd.Description
tempStruct.SubCommands = map[string]string{}
if len(subCmd) > 1 && cmd == subCmd[0] {
for _, c := range subCmd[1:] {
if !c.HideHelp {
tempStruct.SubCommands[c.Name] = c.Description
}
}
}
} else {
_, tempStruct.ProgName = path.Split(os.Args[0])
}
// Run Template
tmplHelper, err := template.New("helper").Parse(helper)
if err != nil {
return err
}
err = tmplHelper.Execute(os.Stdout, tempStruct)
if err != nil {
return err
}
return printFlagsDescriptionsDefaultValues(flagMap, defaultValMap, parsers, os.Stdout)
} | [
"func",
"PrintHelpWithCommand",
"(",
"flagMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
",",
"defaultValMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"Value",
",",
"parsers",
"map",
"[",
"reflect",
".",
"Type",
"]",
"parse",
".",
"Parser",
",",
"cmd",
"*",
"Command",
",",
"subCmd",
"[",
"]",
"*",
"Command",
")",
"error",
"{",
"// Hide command from help",
"if",
"cmd",
"!=",
"nil",
"&&",
"cmd",
".",
"HideHelp",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cmd",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"// Define a templates",
"// Using POSXE STD : http://pubs.opengroup.org/onlinepubs/9699919799/",
"const",
"helper",
"=",
"`{{if .ProgDescription}}{{.ProgDescription}}\n\n{{end}}Usage: {{.ProgName}} [flags] <command> [<arguments>]\n\nUse \"{{.ProgName}} <command> --help\" for help on any command.\n{{if .SubCommands}}\nCommands:{{range $subCmdName, $subCmdDesc := .SubCommands}}\n{{printf \"\\t%-50s %s\" $subCmdName $subCmdDesc}}{{end}}\n{{end}}\nFlag's usage: {{.ProgName}} [--flag=flag_argument] [-f[flag_argument]] ... set flag_argument to flag(s)\n or: {{.ProgName}} [--flag[=true|false| ]] [-f[true|false| ]] ... set true/false to boolean flag(s)\n\nFlags:\n`",
"\n",
"// Use a struct to give data to template",
"type",
"TempStruct",
"struct",
"{",
"ProgName",
"string",
"\n",
"ProgDescription",
"string",
"\n",
"SubCommands",
"map",
"[",
"string",
"]",
"string",
"\n",
"}",
"\n",
"tempStruct",
":=",
"TempStruct",
"{",
"}",
"\n",
"if",
"cmd",
"!=",
"nil",
"{",
"tempStruct",
".",
"ProgName",
"=",
"cmd",
".",
"Name",
"\n",
"tempStruct",
".",
"ProgDescription",
"=",
"cmd",
".",
"Description",
"\n",
"tempStruct",
".",
"SubCommands",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"len",
"(",
"subCmd",
")",
">",
"1",
"&&",
"cmd",
"==",
"subCmd",
"[",
"0",
"]",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"subCmd",
"[",
"1",
":",
"]",
"{",
"if",
"!",
"c",
".",
"HideHelp",
"{",
"tempStruct",
".",
"SubCommands",
"[",
"c",
".",
"Name",
"]",
"=",
"c",
".",
"Description",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"_",
",",
"tempStruct",
".",
"ProgName",
"=",
"path",
".",
"Split",
"(",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"}",
"\n\n",
"// Run Template",
"tmplHelper",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"helper",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"tmplHelper",
".",
"Execute",
"(",
"os",
".",
"Stdout",
",",
"tempStruct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"printFlagsDescriptionsDefaultValues",
"(",
"flagMap",
",",
"defaultValMap",
",",
"parsers",
",",
"os",
".",
"Stdout",
")",
"\n",
"}"
]
| // PrintHelpWithCommand generates and prints command line help for a Command | [
"PrintHelpWithCommand",
"generates",
"and",
"prints",
"command",
"line",
"help",
"for",
"a",
"Command"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L437-L492 |
11,744 | containous/flaeg | flaeg.go | PrintErrorWithCommand | func PrintErrorWithCommand(err error, flagMap map[string]reflect.StructField, defaultValMap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser, cmd *Command, subCmd []*Command) error {
if err != flag.ErrHelp {
fmt.Printf("Error here : %s\n", err)
}
if errHelp := PrintHelpWithCommand(flagMap, defaultValMap, parsers, cmd, subCmd); errHelp != nil {
return errHelp
}
return err
} | go | func PrintErrorWithCommand(err error, flagMap map[string]reflect.StructField, defaultValMap map[string]reflect.Value, parsers map[reflect.Type]parse.Parser, cmd *Command, subCmd []*Command) error {
if err != flag.ErrHelp {
fmt.Printf("Error here : %s\n", err)
}
if errHelp := PrintHelpWithCommand(flagMap, defaultValMap, parsers, cmd, subCmd); errHelp != nil {
return errHelp
}
return err
} | [
"func",
"PrintErrorWithCommand",
"(",
"err",
"error",
",",
"flagMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"StructField",
",",
"defaultValMap",
"map",
"[",
"string",
"]",
"reflect",
".",
"Value",
",",
"parsers",
"map",
"[",
"reflect",
".",
"Type",
"]",
"parse",
".",
"Parser",
",",
"cmd",
"*",
"Command",
",",
"subCmd",
"[",
"]",
"*",
"Command",
")",
"error",
"{",
"if",
"err",
"!=",
"flag",
".",
"ErrHelp",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"errHelp",
":=",
"PrintHelpWithCommand",
"(",
"flagMap",
",",
"defaultValMap",
",",
"parsers",
",",
"cmd",
",",
"subCmd",
")",
";",
"errHelp",
"!=",
"nil",
"{",
"return",
"errHelp",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
]
| // PrintErrorWithCommand takes a not nil error and prints command line help | [
"PrintErrorWithCommand",
"takes",
"a",
"not",
"nil",
"error",
"and",
"prints",
"command",
"line",
"help"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L586-L596 |
11,745 | containous/flaeg | flaeg.go | New | func New(rootCommand *Command, args []string) *Flaeg {
var f Flaeg
f.commands = []*Command{rootCommand}
f.args = args
f.customParsers = map[reflect.Type]parse.Parser{}
return &f
} | go | func New(rootCommand *Command, args []string) *Flaeg {
var f Flaeg
f.commands = []*Command{rootCommand}
f.args = args
f.customParsers = map[reflect.Type]parse.Parser{}
return &f
} | [
"func",
"New",
"(",
"rootCommand",
"*",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"*",
"Flaeg",
"{",
"var",
"f",
"Flaeg",
"\n",
"f",
".",
"commands",
"=",
"[",
"]",
"*",
"Command",
"{",
"rootCommand",
"}",
"\n",
"f",
".",
"args",
"=",
"args",
"\n",
"f",
".",
"customParsers",
"=",
"map",
"[",
"reflect",
".",
"Type",
"]",
"parse",
".",
"Parser",
"{",
"}",
"\n",
"return",
"&",
"f",
"\n",
"}"
]
| // New creates and initialize a pointer on Flaeg | [
"New",
"creates",
"and",
"initialize",
"a",
"pointer",
"on",
"Flaeg"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L610-L616 |
11,746 | containous/flaeg | flaeg.go | AddCommand | func (f *Flaeg) AddCommand(command *Command) {
f.commands = append(f.commands, command)
} | go | func (f *Flaeg) AddCommand(command *Command) {
f.commands = append(f.commands, command)
} | [
"func",
"(",
"f",
"*",
"Flaeg",
")",
"AddCommand",
"(",
"command",
"*",
"Command",
")",
"{",
"f",
".",
"commands",
"=",
"append",
"(",
"f",
".",
"commands",
",",
"command",
")",
"\n",
"}"
]
| // AddCommand adds sub-command to the root command | [
"AddCommand",
"adds",
"sub",
"-",
"command",
"to",
"the",
"root",
"command"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L619-L621 |
11,747 | containous/flaeg | flaeg.go | AddParser | func (f *Flaeg) AddParser(typ reflect.Type, parser parse.Parser) {
f.customParsers[typ] = parser
} | go | func (f *Flaeg) AddParser(typ reflect.Type, parser parse.Parser) {
f.customParsers[typ] = parser
} | [
"func",
"(",
"f",
"*",
"Flaeg",
")",
"AddParser",
"(",
"typ",
"reflect",
".",
"Type",
",",
"parser",
"parse",
".",
"Parser",
")",
"{",
"f",
".",
"customParsers",
"[",
"typ",
"]",
"=",
"parser",
"\n",
"}"
]
| // AddParser adds custom parser for a type to the map of custom parsers | [
"AddParser",
"adds",
"custom",
"parser",
"for",
"a",
"type",
"to",
"the",
"map",
"of",
"custom",
"parsers"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L624-L626 |
11,748 | containous/flaeg | flaeg.go | Run | func (f *Flaeg) Run() error {
if f.calledCommand == nil {
if _, _, err := f.findCommandWithCommandArgs(); err != nil {
return err
}
}
if _, err := f.Parse(f.calledCommand); err != nil {
return err
}
return f.calledCommand.Run()
} | go | func (f *Flaeg) Run() error {
if f.calledCommand == nil {
if _, _, err := f.findCommandWithCommandArgs(); err != nil {
return err
}
}
if _, err := f.Parse(f.calledCommand); err != nil {
return err
}
return f.calledCommand.Run()
} | [
"func",
"(",
"f",
"*",
"Flaeg",
")",
"Run",
"(",
")",
"error",
"{",
"if",
"f",
".",
"calledCommand",
"==",
"nil",
"{",
"if",
"_",
",",
"_",
",",
"err",
":=",
"f",
".",
"findCommandWithCommandArgs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"f",
".",
"Parse",
"(",
"f",
".",
"calledCommand",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"f",
".",
"calledCommand",
".",
"Run",
"(",
")",
"\n",
"}"
]
| // Run calls the command with flags given as arguments | [
"Run",
"calls",
"the",
"command",
"with",
"flags",
"given",
"as",
"arguments"
]
| fc90211ce55539242cb80a30f9bb80fa943159fc | https://github.com/containous/flaeg/blob/fc90211ce55539242cb80a30f9bb80fa943159fc/flaeg.go#L629-L640 |
11,749 | newrelic/sidecar | discovery/docker_discovery.go | HealthCheck | func (d *DockerDiscovery) HealthCheck(svc *service.Service) (string, string) {
container, err := d.inspectContainer(svc)
if err != nil {
return "", ""
}
return container.Config.Labels["HealthCheck"], container.Config.Labels["HealthCheckArgs"]
} | go | func (d *DockerDiscovery) HealthCheck(svc *service.Service) (string, string) {
container, err := d.inspectContainer(svc)
if err != nil {
return "", ""
}
return container.Config.Labels["HealthCheck"], container.Config.Labels["HealthCheckArgs"]
} | [
"func",
"(",
"d",
"*",
"DockerDiscovery",
")",
"HealthCheck",
"(",
"svc",
"*",
"service",
".",
"Service",
")",
"(",
"string",
",",
"string",
")",
"{",
"container",
",",
"err",
":=",
"d",
".",
"inspectContainer",
"(",
"svc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"container",
".",
"Config",
".",
"Labels",
"[",
"\"",
"\"",
"]",
",",
"container",
".",
"Config",
".",
"Labels",
"[",
"\"",
"\"",
"]",
"\n",
"}"
]
| // HealthCheck looks up a health check using Docker container labels to
// pass the type of check and the arguments to pass to it. | [
"HealthCheck",
"looks",
"up",
"a",
"health",
"check",
"using",
"Docker",
"container",
"labels",
"to",
"pass",
"the",
"type",
"of",
"check",
"and",
"the",
"arguments",
"to",
"pass",
"to",
"it",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L75-L82 |
11,750 | newrelic/sidecar | discovery/docker_discovery.go | Run | func (d *DockerDiscovery) Run(looper director.Looper) {
connQuitChan := make(chan bool)
go d.manageConnection(connQuitChan)
go func() {
// Loop around, process any events which came in, and
// periodically fetch the whole container list
looper.Loop(func() error {
select {
case event := <-d.events:
if event == nil {
// This usually happens because of a Docker restart.
// Sleep, let us reconnect in the background, then loop.
return nil
}
log.Debugf("Event: %#v\n", event)
d.handleEvent(*event)
case <-time.After(d.sleepInterval):
d.getContainers()
case <-time.After(CacheDrainInterval):
d.containerCache.Drain(len(d.services))
}
return nil
})
// Propagate quit channel message
close(connQuitChan)
}()
} | go | func (d *DockerDiscovery) Run(looper director.Looper) {
connQuitChan := make(chan bool)
go d.manageConnection(connQuitChan)
go func() {
// Loop around, process any events which came in, and
// periodically fetch the whole container list
looper.Loop(func() error {
select {
case event := <-d.events:
if event == nil {
// This usually happens because of a Docker restart.
// Sleep, let us reconnect in the background, then loop.
return nil
}
log.Debugf("Event: %#v\n", event)
d.handleEvent(*event)
case <-time.After(d.sleepInterval):
d.getContainers()
case <-time.After(CacheDrainInterval):
d.containerCache.Drain(len(d.services))
}
return nil
})
// Propagate quit channel message
close(connQuitChan)
}()
} | [
"func",
"(",
"d",
"*",
"DockerDiscovery",
")",
"Run",
"(",
"looper",
"director",
".",
"Looper",
")",
"{",
"connQuitChan",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n\n",
"go",
"d",
".",
"manageConnection",
"(",
"connQuitChan",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"// Loop around, process any events which came in, and",
"// periodically fetch the whole container list",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"select",
"{",
"case",
"event",
":=",
"<-",
"d",
".",
"events",
":",
"if",
"event",
"==",
"nil",
"{",
"// This usually happens because of a Docker restart.",
"// Sleep, let us reconnect in the background, then loop.",
"return",
"nil",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"event",
")",
"\n",
"d",
".",
"handleEvent",
"(",
"*",
"event",
")",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"d",
".",
"sleepInterval",
")",
":",
"d",
".",
"getContainers",
"(",
")",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"CacheDrainInterval",
")",
":",
"d",
".",
"containerCache",
".",
"Drain",
"(",
"len",
"(",
"d",
".",
"services",
")",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"// Propagate quit channel message",
"close",
"(",
"connQuitChan",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
]
| // The main loop, poll for containers continuously. | [
"The",
"main",
"loop",
"poll",
"for",
"containers",
"continuously",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L111-L141 |
11,751 | newrelic/sidecar | discovery/docker_discovery.go | Services | func (d *DockerDiscovery) Services() []service.Service {
d.RLock()
defer d.RUnlock()
svcList := make([]service.Service, len(d.services))
for i, svc := range d.services {
svcList[i] = *svc
}
return svcList
} | go | func (d *DockerDiscovery) Services() []service.Service {
d.RLock()
defer d.RUnlock()
svcList := make([]service.Service, len(d.services))
for i, svc := range d.services {
svcList[i] = *svc
}
return svcList
} | [
"func",
"(",
"d",
"*",
"DockerDiscovery",
")",
"Services",
"(",
")",
"[",
"]",
"service",
".",
"Service",
"{",
"d",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"RUnlock",
"(",
")",
"\n\n",
"svcList",
":=",
"make",
"(",
"[",
"]",
"service",
".",
"Service",
",",
"len",
"(",
"d",
".",
"services",
")",
")",
"\n\n",
"for",
"i",
",",
"svc",
":=",
"range",
"d",
".",
"services",
"{",
"svcList",
"[",
"i",
"]",
"=",
"*",
"svc",
"\n",
"}",
"\n\n",
"return",
"svcList",
"\n",
"}"
]
| // Services returns the slice of services we found running | [
"Services",
"returns",
"the",
"slice",
"of",
"services",
"we",
"found",
"running"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L144-L155 |
11,752 | newrelic/sidecar | discovery/docker_discovery.go | Listeners | func (d *DockerDiscovery) Listeners() []ChangeListener {
var listeners []ChangeListener
for _, cntnr := range d.services {
container, err := d.inspectContainer(cntnr)
if err != nil {
continue
}
listener := d.listenerForContainer(container)
if listener != nil {
listeners = append(listeners, *listener)
}
}
return listeners
} | go | func (d *DockerDiscovery) Listeners() []ChangeListener {
var listeners []ChangeListener
for _, cntnr := range d.services {
container, err := d.inspectContainer(cntnr)
if err != nil {
continue
}
listener := d.listenerForContainer(container)
if listener != nil {
listeners = append(listeners, *listener)
}
}
return listeners
} | [
"func",
"(",
"d",
"*",
"DockerDiscovery",
")",
"Listeners",
"(",
")",
"[",
"]",
"ChangeListener",
"{",
"var",
"listeners",
"[",
"]",
"ChangeListener",
"\n\n",
"for",
"_",
",",
"cntnr",
":=",
"range",
"d",
".",
"services",
"{",
"container",
",",
"err",
":=",
"d",
".",
"inspectContainer",
"(",
"cntnr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"listener",
":=",
"d",
".",
"listenerForContainer",
"(",
"container",
")",
"\n",
"if",
"listener",
"!=",
"nil",
"{",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"*",
"listener",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"listeners",
"\n",
"}"
]
| // Listeners returns any containers we found that had the
// SidecarListener label set to a valid ServicePort. | [
"Listeners",
"returns",
"any",
"containers",
"we",
"found",
"that",
"had",
"the",
"SidecarListener",
"label",
"set",
"to",
"a",
"valid",
"ServicePort",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L159-L175 |
11,753 | newrelic/sidecar | discovery/docker_discovery.go | listenerForContainer | func (d *DockerDiscovery) listenerForContainer(cntnr *docker.Container) *ChangeListener {
// See if the container has the SidecarListener label, which
// will tell us the ServicePort of the port that should be
// subscribed to Sidecar events.
svcPortStr, ok := cntnr.Config.Labels["SidecarListener"]
if !ok {
return nil
}
// Be careful about ID matching
id := cntnr.ID
if len(id) > 12 {
id = id[:12]
}
svc := d.findServiceByID(id)
if svc == nil {
return nil
}
listenPort := portForServicePort(svc, svcPortStr, "tcp") // We only do HTTP (TCP)
// -1 is returned when there is no match
if listenPort == nil {
log.Warnf(
"SidecarListener label found on %s, but no matching ServicePort! '%s'",
svc.ID, svcPortStr,
)
return nil
}
return &ChangeListener{
Name: svc.ListenerName(),
Url: fmt.Sprintf("http://%s:%d/sidecar/update", listenPort.IP, listenPort.Port),
}
} | go | func (d *DockerDiscovery) listenerForContainer(cntnr *docker.Container) *ChangeListener {
// See if the container has the SidecarListener label, which
// will tell us the ServicePort of the port that should be
// subscribed to Sidecar events.
svcPortStr, ok := cntnr.Config.Labels["SidecarListener"]
if !ok {
return nil
}
// Be careful about ID matching
id := cntnr.ID
if len(id) > 12 {
id = id[:12]
}
svc := d.findServiceByID(id)
if svc == nil {
return nil
}
listenPort := portForServicePort(svc, svcPortStr, "tcp") // We only do HTTP (TCP)
// -1 is returned when there is no match
if listenPort == nil {
log.Warnf(
"SidecarListener label found on %s, but no matching ServicePort! '%s'",
svc.ID, svcPortStr,
)
return nil
}
return &ChangeListener{
Name: svc.ListenerName(),
Url: fmt.Sprintf("http://%s:%d/sidecar/update", listenPort.IP, listenPort.Port),
}
} | [
"func",
"(",
"d",
"*",
"DockerDiscovery",
")",
"listenerForContainer",
"(",
"cntnr",
"*",
"docker",
".",
"Container",
")",
"*",
"ChangeListener",
"{",
"// See if the container has the SidecarListener label, which",
"// will tell us the ServicePort of the port that should be",
"// subscribed to Sidecar events.",
"svcPortStr",
",",
"ok",
":=",
"cntnr",
".",
"Config",
".",
"Labels",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Be careful about ID matching",
"id",
":=",
"cntnr",
".",
"ID",
"\n",
"if",
"len",
"(",
"id",
")",
">",
"12",
"{",
"id",
"=",
"id",
"[",
":",
"12",
"]",
"\n",
"}",
"\n\n",
"svc",
":=",
"d",
".",
"findServiceByID",
"(",
"id",
")",
"\n",
"if",
"svc",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"listenPort",
":=",
"portForServicePort",
"(",
"svc",
",",
"svcPortStr",
",",
"\"",
"\"",
")",
"// We only do HTTP (TCP)",
"\n",
"// -1 is returned when there is no match",
"if",
"listenPort",
"==",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"svc",
".",
"ID",
",",
"svcPortStr",
",",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"&",
"ChangeListener",
"{",
"Name",
":",
"svc",
".",
"ListenerName",
"(",
")",
",",
"Url",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"listenPort",
".",
"IP",
",",
"listenPort",
".",
"Port",
")",
",",
"}",
"\n",
"}"
]
| // listenerForContainer returns a ChangeListener for a container if one
// is configured. | [
"listenerForContainer",
"returns",
"a",
"ChangeListener",
"for",
"a",
"container",
"if",
"one",
"is",
"configured",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L189-L223 |
11,754 | newrelic/sidecar | discovery/docker_discovery.go | portForServicePort | func portForServicePort(svc *service.Service, portStr string, pType string) *service.Port {
// Look up the ServicePort and translate to Docker port
svcPort, err := strconv.ParseInt(portStr, 10, 64)
if err != nil {
log.Warnf(
"SidecarListener label found on %s, can't decode port '%s'",
svc.ID, portStr,
)
return nil
}
for _, port := range svc.Ports {
if port.ServicePort == svcPort && port.Type == pType {
return &port
}
}
return nil
} | go | func portForServicePort(svc *service.Service, portStr string, pType string) *service.Port {
// Look up the ServicePort and translate to Docker port
svcPort, err := strconv.ParseInt(portStr, 10, 64)
if err != nil {
log.Warnf(
"SidecarListener label found on %s, can't decode port '%s'",
svc.ID, portStr,
)
return nil
}
for _, port := range svc.Ports {
if port.ServicePort == svcPort && port.Type == pType {
return &port
}
}
return nil
} | [
"func",
"portForServicePort",
"(",
"svc",
"*",
"service",
".",
"Service",
",",
"portStr",
"string",
",",
"pType",
"string",
")",
"*",
"service",
".",
"Port",
"{",
"// Look up the ServicePort and translate to Docker port",
"svcPort",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"portStr",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"svc",
".",
"ID",
",",
"portStr",
",",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"if",
"port",
".",
"ServicePort",
"==",
"svcPort",
"&&",
"port",
".",
"Type",
"==",
"pType",
"{",
"return",
"&",
"port",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
]
| // portForServicePort is similar to service.PortForServicePort, but takes a string
// and returns a full service.Port, not just the integer. | [
"portForServicePort",
"is",
"similar",
"to",
"service",
".",
"PortForServicePort",
"but",
"takes",
"a",
"string",
"and",
"returns",
"a",
"full",
"service",
".",
"Port",
"not",
"just",
"the",
"integer",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L227-L245 |
11,755 | newrelic/sidecar | discovery/docker_discovery.go | Drain | func (c *ContainerCache) Drain(newSize int) {
c.Lock()
defer c.Unlock()
// Make a new one, leave the old one for GC
c.cache = make(map[string]*docker.Container, newSize)
} | go | func (c *ContainerCache) Drain(newSize int) {
c.Lock()
defer c.Unlock()
// Make a new one, leave the old one for GC
c.cache = make(map[string]*docker.Container, newSize)
} | [
"func",
"(",
"c",
"*",
"ContainerCache",
")",
"Drain",
"(",
"newSize",
"int",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n",
"// Make a new one, leave the old one for GC",
"c",
".",
"cache",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"docker",
".",
"Container",
",",
"newSize",
")",
"\n",
"}"
]
| // On a timed basis, drain the containerCache | [
"On",
"a",
"timed",
"basis",
"drain",
"the",
"containerCache"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L363-L368 |
11,756 | newrelic/sidecar | discovery/docker_discovery.go | Prune | func (c *ContainerCache) Prune(liveContainers map[string]interface{}) {
c.Lock()
defer c.Unlock()
for id := range c.cache {
if _, ok := liveContainers[id]; !ok {
delete(c.cache, id)
}
}
} | go | func (c *ContainerCache) Prune(liveContainers map[string]interface{}) {
c.Lock()
defer c.Unlock()
for id := range c.cache {
if _, ok := liveContainers[id]; !ok {
delete(c.cache, id)
}
}
} | [
"func",
"(",
"c",
"*",
"ContainerCache",
")",
"Prune",
"(",
"liveContainers",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"id",
":=",
"range",
"c",
".",
"cache",
"{",
"if",
"_",
",",
"ok",
":=",
"liveContainers",
"[",
"id",
"]",
";",
"!",
"ok",
"{",
"delete",
"(",
"c",
".",
"cache",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // Loop through the current cache and remove anything that has disappeared | [
"Loop",
"through",
"the",
"current",
"cache",
"and",
"remove",
"anything",
"that",
"has",
"disappeared"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L371-L380 |
11,757 | newrelic/sidecar | discovery/docker_discovery.go | Get | func (c *ContainerCache) Get(svcID string) *docker.Container {
c.RLock()
defer c.RUnlock()
if container, ok := c.cache[svcID]; ok {
return container
}
return nil
} | go | func (c *ContainerCache) Get(svcID string) *docker.Container {
c.RLock()
defer c.RUnlock()
if container, ok := c.cache[svcID]; ok {
return container
}
return nil
} | [
"func",
"(",
"c",
"*",
"ContainerCache",
")",
"Get",
"(",
"svcID",
"string",
")",
"*",
"docker",
".",
"Container",
"{",
"c",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"container",
",",
"ok",
":=",
"c",
".",
"cache",
"[",
"svcID",
"]",
";",
"ok",
"{",
"return",
"container",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
]
| // Get locks the cache, try to get a service if we have it | [
"Get",
"locks",
"the",
"cache",
"try",
"to",
"get",
"a",
"service",
"if",
"we",
"have",
"it"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/docker_discovery.go#L383-L392 |
11,758 | newrelic/sidecar | discovery/discovery.go | HealthCheck | func (d *MultiDiscovery) HealthCheck(svc *service.Service) (string, string) {
for _, disco := range d.Discoverers {
if healthCheck, healthCheckArgs := disco.HealthCheck(svc); healthCheck != "" {
return healthCheck, healthCheckArgs
}
}
return "", ""
} | go | func (d *MultiDiscovery) HealthCheck(svc *service.Service) (string, string) {
for _, disco := range d.Discoverers {
if healthCheck, healthCheckArgs := disco.HealthCheck(svc); healthCheck != "" {
return healthCheck, healthCheckArgs
}
}
return "", ""
} | [
"func",
"(",
"d",
"*",
"MultiDiscovery",
")",
"HealthCheck",
"(",
"svc",
"*",
"service",
".",
"Service",
")",
"(",
"string",
",",
"string",
")",
"{",
"for",
"_",
",",
"disco",
":=",
"range",
"d",
".",
"Discoverers",
"{",
"if",
"healthCheck",
",",
"healthCheckArgs",
":=",
"disco",
".",
"HealthCheck",
"(",
"svc",
")",
";",
"healthCheck",
"!=",
"\"",
"\"",
"{",
"return",
"healthCheck",
",",
"healthCheckArgs",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
"\n",
"}"
]
| // Get the health check and health check args for a service | [
"Get",
"the",
"health",
"check",
"and",
"health",
"check",
"args",
"for",
"a",
"service"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/discovery.go#L46-L54 |
11,759 | newrelic/sidecar | discovery/discovery.go | Services | func (d *MultiDiscovery) Services() []service.Service {
var aggregate []service.Service
for _, disco := range d.Discoverers {
services := disco.Services()
if len(services) > 0 {
aggregate = append(aggregate, services...)
}
}
return aggregate
} | go | func (d *MultiDiscovery) Services() []service.Service {
var aggregate []service.Service
for _, disco := range d.Discoverers {
services := disco.Services()
if len(services) > 0 {
aggregate = append(aggregate, services...)
}
}
return aggregate
} | [
"func",
"(",
"d",
"*",
"MultiDiscovery",
")",
"Services",
"(",
")",
"[",
"]",
"service",
".",
"Service",
"{",
"var",
"aggregate",
"[",
"]",
"service",
".",
"Service",
"\n\n",
"for",
"_",
",",
"disco",
":=",
"range",
"d",
".",
"Discoverers",
"{",
"services",
":=",
"disco",
".",
"Services",
"(",
")",
"\n",
"if",
"len",
"(",
"services",
")",
">",
"0",
"{",
"aggregate",
"=",
"append",
"(",
"aggregate",
",",
"services",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"aggregate",
"\n",
"}"
]
| // Aggregates all the service slices from the discoverers | [
"Aggregates",
"all",
"the",
"service",
"slices",
"from",
"the",
"discoverers"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/discovery.go#L57-L68 |
11,760 | newrelic/sidecar | receiver/receiver.go | ShouldNotify | func ShouldNotify(oldStatus int, newStatus int) bool {
log.Debugf("Checking event. OldStatus: %s NewStatus: %s",
service.StatusString(oldStatus), service.StatusString(newStatus),
)
// Compare old and new states to find significant changes only
switch newStatus {
case service.ALIVE:
return true
case service.TOMBSTONE:
return true
case service.UNKNOWN:
if oldStatus == service.ALIVE {
return true
}
case service.UNHEALTHY:
if oldStatus == service.ALIVE {
return true
}
default:
log.Errorf("Got unknown service change status: %d", newStatus)
return false
}
log.Debugf("Skipped HAproxy update due to state machine check")
return false
} | go | func ShouldNotify(oldStatus int, newStatus int) bool {
log.Debugf("Checking event. OldStatus: %s NewStatus: %s",
service.StatusString(oldStatus), service.StatusString(newStatus),
)
// Compare old and new states to find significant changes only
switch newStatus {
case service.ALIVE:
return true
case service.TOMBSTONE:
return true
case service.UNKNOWN:
if oldStatus == service.ALIVE {
return true
}
case service.UNHEALTHY:
if oldStatus == service.ALIVE {
return true
}
default:
log.Errorf("Got unknown service change status: %d", newStatus)
return false
}
log.Debugf("Skipped HAproxy update due to state machine check")
return false
} | [
"func",
"ShouldNotify",
"(",
"oldStatus",
"int",
",",
"newStatus",
"int",
")",
"bool",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"service",
".",
"StatusString",
"(",
"oldStatus",
")",
",",
"service",
".",
"StatusString",
"(",
"newStatus",
")",
",",
")",
"\n\n",
"// Compare old and new states to find significant changes only",
"switch",
"newStatus",
"{",
"case",
"service",
".",
"ALIVE",
":",
"return",
"true",
"\n",
"case",
"service",
".",
"TOMBSTONE",
":",
"return",
"true",
"\n",
"case",
"service",
".",
"UNKNOWN",
":",
"if",
"oldStatus",
"==",
"service",
".",
"ALIVE",
"{",
"return",
"true",
"\n",
"}",
"\n",
"case",
"service",
".",
"UNHEALTHY",
":",
"if",
"oldStatus",
"==",
"service",
".",
"ALIVE",
"{",
"return",
"true",
"\n",
"}",
"\n",
"default",
":",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"newStatus",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
"\n",
"}"
]
| // Check all the state transitions and only update HAproxy when a change
// will affect service availability. | [
"Check",
"all",
"the",
"state",
"transitions",
"and",
"only",
"update",
"HAproxy",
"when",
"a",
"change",
"will",
"affect",
"service",
"availability",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L41-L67 |
11,761 | newrelic/sidecar | receiver/receiver.go | FetchState | func FetchState(url string) (*catalog.ServicesState, error) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("Bad status code on state fetch: %d", resp.StatusCode)
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
state, err := catalog.Decode(bytes)
if err != nil {
return nil, err
}
return state, nil
} | go | func FetchState(url string) (*catalog.ServicesState, error) {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("Bad status code on state fetch: %d", resp.StatusCode)
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
state, err := catalog.Decode(bytes)
if err != nil {
return nil, err
}
return state, nil
} | [
"func",
"FetchState",
"(",
"url",
"string",
")",
"(",
"*",
"catalog",
".",
"ServicesState",
",",
"error",
")",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"5",
"*",
"time",
".",
"Second",
"}",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"<",
"200",
"||",
"resp",
".",
"StatusCode",
">",
"299",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n\n",
"bytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"state",
",",
"err",
":=",
"catalog",
".",
"Decode",
"(",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"state",
",",
"nil",
"\n",
"}"
]
| // Used to fetch the current state from a Sidecar endpoint, usually
// on startup of this process, when the currentState is empty. | [
"Used",
"to",
"fetch",
"the",
"current",
"state",
"from",
"a",
"Sidecar",
"endpoint",
"usually",
"on",
"startup",
"of",
"this",
"process",
"when",
"the",
"currentState",
"is",
"empty",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L71-L93 |
11,762 | newrelic/sidecar | receiver/receiver.go | IsSubscribed | func (rcvr *Receiver) IsSubscribed(svcName string) bool {
// If we didn't specify any specifically, then we want them all
if len(rcvr.Subscriptions) < 1 {
return true
}
for _, subName := range rcvr.Subscriptions {
if subName == svcName {
return true
}
}
return false
} | go | func (rcvr *Receiver) IsSubscribed(svcName string) bool {
// If we didn't specify any specifically, then we want them all
if len(rcvr.Subscriptions) < 1 {
return true
}
for _, subName := range rcvr.Subscriptions {
if subName == svcName {
return true
}
}
return false
} | [
"func",
"(",
"rcvr",
"*",
"Receiver",
")",
"IsSubscribed",
"(",
"svcName",
"string",
")",
"bool",
"{",
"// If we didn't specify any specifically, then we want them all",
"if",
"len",
"(",
"rcvr",
".",
"Subscriptions",
")",
"<",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"subName",
":=",
"range",
"rcvr",
".",
"Subscriptions",
"{",
"if",
"subName",
"==",
"svcName",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
]
| // IsSubscribed allows a receiver to filter incoming events by service name | [
"IsSubscribed",
"allows",
"a",
"receiver",
"to",
"filter",
"incoming",
"events",
"by",
"service",
"name"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L96-L109 |
11,763 | newrelic/sidecar | receiver/receiver.go | Subscribe | func (rcvr *Receiver) Subscribe(svcName string) {
for _, subName := range rcvr.Subscriptions {
if subName == svcName {
return
}
}
rcvr.Subscriptions = append(rcvr.Subscriptions, svcName)
} | go | func (rcvr *Receiver) Subscribe(svcName string) {
for _, subName := range rcvr.Subscriptions {
if subName == svcName {
return
}
}
rcvr.Subscriptions = append(rcvr.Subscriptions, svcName)
} | [
"func",
"(",
"rcvr",
"*",
"Receiver",
")",
"Subscribe",
"(",
"svcName",
"string",
")",
"{",
"for",
"_",
",",
"subName",
":=",
"range",
"rcvr",
".",
"Subscriptions",
"{",
"if",
"subName",
"==",
"svcName",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"rcvr",
".",
"Subscriptions",
"=",
"append",
"(",
"rcvr",
".",
"Subscriptions",
",",
"svcName",
")",
"\n",
"}"
]
| // Subscribe is not synchronized and should not be called dynamically. This
// is generally used at setup of the Receiver, before any events begin arriving. | [
"Subscribe",
"is",
"not",
"synchronized",
"and",
"should",
"not",
"be",
"called",
"dynamically",
".",
"This",
"is",
"generally",
"used",
"at",
"setup",
"of",
"the",
"Receiver",
"before",
"any",
"events",
"begin",
"arriving",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L113-L121 |
11,764 | newrelic/sidecar | receiver/receiver.go | ProcessUpdates | func (rcvr *Receiver) ProcessUpdates() {
if rcvr.Looper == nil {
log.Error("Unable to ProcessUpdates(), Looper is nil in receiver!")
return
}
rcvr.Looper.Loop(func() error {
// Batch up to RELOAD_BUFFER number updates into a
// single update.
first := <-rcvr.ReloadChan
pending := len(rcvr.ReloadChan)
// Call the callback
if rcvr.OnUpdate == nil {
log.Error("OnUpdate() callback not defined!")
} else {
rcvr.StateLock.Lock()
// Copy the state while locked so we don't have it change
// under us while writing and we don't hold onto the lock the
// whole time we're writing to disk (e.g. in haproxy-api).
var tmpState *catalog.ServicesState
tmpState = deepcopy.Copy(rcvr.CurrentState).(*catalog.ServicesState)
rcvr.StateLock.Unlock()
rcvr.OnUpdate(tmpState)
}
// We just flushed the most recent state, dump all the
// pending items up to that point.
var reload time.Time
for i := 0; i < pending; i++ {
reload = <-rcvr.ReloadChan
}
if pending > 0 {
log.Infof("Skipped %d messages between %s and %s", pending, first, reload)
}
// Don't notify more frequently than every RELOAD_HOLD_DOWN period. When a
// deployment rolls across the cluster it can trigger a bunch of groupable
// updates. The Looper handles the sleep after the return nil.
log.Debug("Holding down...")
return nil
})
} | go | func (rcvr *Receiver) ProcessUpdates() {
if rcvr.Looper == nil {
log.Error("Unable to ProcessUpdates(), Looper is nil in receiver!")
return
}
rcvr.Looper.Loop(func() error {
// Batch up to RELOAD_BUFFER number updates into a
// single update.
first := <-rcvr.ReloadChan
pending := len(rcvr.ReloadChan)
// Call the callback
if rcvr.OnUpdate == nil {
log.Error("OnUpdate() callback not defined!")
} else {
rcvr.StateLock.Lock()
// Copy the state while locked so we don't have it change
// under us while writing and we don't hold onto the lock the
// whole time we're writing to disk (e.g. in haproxy-api).
var tmpState *catalog.ServicesState
tmpState = deepcopy.Copy(rcvr.CurrentState).(*catalog.ServicesState)
rcvr.StateLock.Unlock()
rcvr.OnUpdate(tmpState)
}
// We just flushed the most recent state, dump all the
// pending items up to that point.
var reload time.Time
for i := 0; i < pending; i++ {
reload = <-rcvr.ReloadChan
}
if pending > 0 {
log.Infof("Skipped %d messages between %s and %s", pending, first, reload)
}
// Don't notify more frequently than every RELOAD_HOLD_DOWN period. When a
// deployment rolls across the cluster it can trigger a bunch of groupable
// updates. The Looper handles the sleep after the return nil.
log.Debug("Holding down...")
return nil
})
} | [
"func",
"(",
"rcvr",
"*",
"Receiver",
")",
"ProcessUpdates",
"(",
")",
"{",
"if",
"rcvr",
".",
"Looper",
"==",
"nil",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"rcvr",
".",
"Looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"// Batch up to RELOAD_BUFFER number updates into a",
"// single update.",
"first",
":=",
"<-",
"rcvr",
".",
"ReloadChan",
"\n",
"pending",
":=",
"len",
"(",
"rcvr",
".",
"ReloadChan",
")",
"\n\n",
"// Call the callback",
"if",
"rcvr",
".",
"OnUpdate",
"==",
"nil",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"rcvr",
".",
"StateLock",
".",
"Lock",
"(",
")",
"\n",
"// Copy the state while locked so we don't have it change",
"// under us while writing and we don't hold onto the lock the",
"// whole time we're writing to disk (e.g. in haproxy-api).",
"var",
"tmpState",
"*",
"catalog",
".",
"ServicesState",
"\n",
"tmpState",
"=",
"deepcopy",
".",
"Copy",
"(",
"rcvr",
".",
"CurrentState",
")",
".",
"(",
"*",
"catalog",
".",
"ServicesState",
")",
"\n",
"rcvr",
".",
"StateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"rcvr",
".",
"OnUpdate",
"(",
"tmpState",
")",
"\n",
"}",
"\n\n",
"// We just flushed the most recent state, dump all the",
"// pending items up to that point.",
"var",
"reload",
"time",
".",
"Time",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"pending",
";",
"i",
"++",
"{",
"reload",
"=",
"<-",
"rcvr",
".",
"ReloadChan",
"\n",
"}",
"\n\n",
"if",
"pending",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"pending",
",",
"first",
",",
"reload",
")",
"\n",
"}",
"\n\n",
"// Don't notify more frequently than every RELOAD_HOLD_DOWN period. When a",
"// deployment rolls across the cluster it can trigger a bunch of groupable",
"// updates. The Looper handles the sleep after the return nil.",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // ProcessUpdates loops forever, processing updates to the state.
// By the time we get here, the HTTP UpdateHandler has already set the
// CurrentState to the newest state we know about. Here we'll try to group
// updates together to prevent repeatedly updating on a series of events that
// arrive in a row. | [
"ProcessUpdates",
"loops",
"forever",
"processing",
"updates",
"to",
"the",
"state",
".",
"By",
"the",
"time",
"we",
"get",
"here",
"the",
"HTTP",
"UpdateHandler",
"has",
"already",
"set",
"the",
"CurrentState",
"to",
"the",
"newest",
"state",
"we",
"know",
"about",
".",
"Here",
"we",
"ll",
"try",
"to",
"group",
"updates",
"together",
"to",
"prevent",
"repeatedly",
"updating",
"on",
"a",
"series",
"of",
"events",
"that",
"arrive",
"in",
"a",
"row",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L128-L173 |
11,765 | newrelic/sidecar | receiver/receiver.go | FetchInitialState | func (rcvr *Receiver) FetchInitialState(stateUrl string) error {
rcvr.StateLock.Lock()
defer rcvr.StateLock.Unlock()
log.Info("Fetching initial state on startup...")
state, err := FetchState(stateUrl)
if err != nil {
return err
} else {
log.Info("Successfully retrieved state")
rcvr.CurrentState = state
if rcvr.OnUpdate == nil {
log.Error("OnUpdate() callback not defined!")
} else {
rcvr.OnUpdate(state)
}
}
return nil
} | go | func (rcvr *Receiver) FetchInitialState(stateUrl string) error {
rcvr.StateLock.Lock()
defer rcvr.StateLock.Unlock()
log.Info("Fetching initial state on startup...")
state, err := FetchState(stateUrl)
if err != nil {
return err
} else {
log.Info("Successfully retrieved state")
rcvr.CurrentState = state
if rcvr.OnUpdate == nil {
log.Error("OnUpdate() callback not defined!")
} else {
rcvr.OnUpdate(state)
}
}
return nil
} | [
"func",
"(",
"rcvr",
"*",
"Receiver",
")",
"FetchInitialState",
"(",
"stateUrl",
"string",
")",
"error",
"{",
"rcvr",
".",
"StateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rcvr",
".",
"StateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"state",
",",
"err",
":=",
"FetchState",
"(",
"stateUrl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"rcvr",
".",
"CurrentState",
"=",
"state",
"\n",
"if",
"rcvr",
".",
"OnUpdate",
"==",
"nil",
"{",
"log",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"rcvr",
".",
"OnUpdate",
"(",
"state",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
]
| // FetchInitialState is used at startup to bootstrap initial state from Sidecar. | [
"FetchInitialState",
"is",
"used",
"at",
"startup",
"to",
"bootstrap",
"initial",
"state",
"from",
"Sidecar",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/receiver.go#L182-L201 |
11,766 | newrelic/sidecar | main.go | configureOverrides | func configureOverrides(config *Config, opts *CliOpts) {
if len(*opts.AdvertiseIP) > 0 {
config.Sidecar.AdvertiseIP = *opts.AdvertiseIP
}
if len(*opts.ClusterIPs) > 0 {
config.Sidecar.Seeds = *opts.ClusterIPs
}
if len(*opts.ClusterName) > 0 {
config.Sidecar.ClusterName = *opts.ClusterName
}
if len(*opts.Discover) > 0 {
config.Sidecar.Discovery = *opts.Discover
}
if len(*opts.LoggingLevel) > 0 {
config.Sidecar.LoggingLevel = *opts.LoggingLevel
}
} | go | func configureOverrides(config *Config, opts *CliOpts) {
if len(*opts.AdvertiseIP) > 0 {
config.Sidecar.AdvertiseIP = *opts.AdvertiseIP
}
if len(*opts.ClusterIPs) > 0 {
config.Sidecar.Seeds = *opts.ClusterIPs
}
if len(*opts.ClusterName) > 0 {
config.Sidecar.ClusterName = *opts.ClusterName
}
if len(*opts.Discover) > 0 {
config.Sidecar.Discovery = *opts.Discover
}
if len(*opts.LoggingLevel) > 0 {
config.Sidecar.LoggingLevel = *opts.LoggingLevel
}
} | [
"func",
"configureOverrides",
"(",
"config",
"*",
"Config",
",",
"opts",
"*",
"CliOpts",
")",
"{",
"if",
"len",
"(",
"*",
"opts",
".",
"AdvertiseIP",
")",
">",
"0",
"{",
"config",
".",
"Sidecar",
".",
"AdvertiseIP",
"=",
"*",
"opts",
".",
"AdvertiseIP",
"\n",
"}",
"\n",
"if",
"len",
"(",
"*",
"opts",
".",
"ClusterIPs",
")",
">",
"0",
"{",
"config",
".",
"Sidecar",
".",
"Seeds",
"=",
"*",
"opts",
".",
"ClusterIPs",
"\n",
"}",
"\n",
"if",
"len",
"(",
"*",
"opts",
".",
"ClusterName",
")",
">",
"0",
"{",
"config",
".",
"Sidecar",
".",
"ClusterName",
"=",
"*",
"opts",
".",
"ClusterName",
"\n",
"}",
"\n",
"if",
"len",
"(",
"*",
"opts",
".",
"Discover",
")",
">",
"0",
"{",
"config",
".",
"Sidecar",
".",
"Discovery",
"=",
"*",
"opts",
".",
"Discover",
"\n",
"}",
"\n",
"if",
"len",
"(",
"*",
"opts",
".",
"LoggingLevel",
")",
">",
"0",
"{",
"config",
".",
"Sidecar",
".",
"LoggingLevel",
"=",
"*",
"opts",
".",
"LoggingLevel",
"\n",
"}",
"\n",
"}"
]
| // configureOverrides takes CLI opts and applies them over the top of settings
// taken from the environment variables and stored in config. | [
"configureOverrides",
"takes",
"CLI",
"opts",
"and",
"applies",
"them",
"over",
"the",
"top",
"of",
"settings",
"taken",
"from",
"the",
"environment",
"variables",
"and",
"stored",
"in",
"config",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/main.go#L40-L56 |
11,767 | newrelic/sidecar | main.go | configureDelegate | func configureDelegate(state *catalog.ServicesState, config *Config) *servicesDelegate {
delegate := NewServicesDelegate(state)
delegate.Metadata = NodeMetadata{
ClusterName: config.Sidecar.ClusterName,
State: "Running",
}
delegate.Start()
return delegate
} | go | func configureDelegate(state *catalog.ServicesState, config *Config) *servicesDelegate {
delegate := NewServicesDelegate(state)
delegate.Metadata = NodeMetadata{
ClusterName: config.Sidecar.ClusterName,
State: "Running",
}
delegate.Start()
return delegate
} | [
"func",
"configureDelegate",
"(",
"state",
"*",
"catalog",
".",
"ServicesState",
",",
"config",
"*",
"Config",
")",
"*",
"servicesDelegate",
"{",
"delegate",
":=",
"NewServicesDelegate",
"(",
"state",
")",
"\n",
"delegate",
".",
"Metadata",
"=",
"NodeMetadata",
"{",
"ClusterName",
":",
"config",
".",
"Sidecar",
".",
"ClusterName",
",",
"State",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"delegate",
".",
"Start",
"(",
")",
"\n\n",
"return",
"delegate",
"\n",
"}"
]
| // configureDelegate sets up the Memberlist delegate we'll use | [
"configureDelegate",
"sets",
"up",
"the",
"Memberlist",
"delegate",
"we",
"ll",
"use"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/main.go#L155-L165 |
11,768 | newrelic/sidecar | main.go | configureCpuProfiler | func configureCpuProfiler(opts *CliOpts) {
if !*opts.CpuProfile {
return
}
var profilerFile os.File
// Capture CTRL-C and stop the CPU profiler
sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, os.Interrupt)
go func() {
for sig := range sigChannel {
log.Printf("Captured %v, stopping profiler and exiting..", sig)
pprof.StopCPUProfile()
profilerFile.Close()
os.Exit(0)
}
}()
// Enable CPU profiling support if requested
if *opts.CpuProfile {
profilerFile, err := os.Create("sidecar.cpu.prof")
exitWithError(err, "Can't write profiling file")
pprof.StartCPUProfile(profilerFile)
log.Debug("Profiling!")
}
} | go | func configureCpuProfiler(opts *CliOpts) {
if !*opts.CpuProfile {
return
}
var profilerFile os.File
// Capture CTRL-C and stop the CPU profiler
sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, os.Interrupt)
go func() {
for sig := range sigChannel {
log.Printf("Captured %v, stopping profiler and exiting..", sig)
pprof.StopCPUProfile()
profilerFile.Close()
os.Exit(0)
}
}()
// Enable CPU profiling support if requested
if *opts.CpuProfile {
profilerFile, err := os.Create("sidecar.cpu.prof")
exitWithError(err, "Can't write profiling file")
pprof.StartCPUProfile(profilerFile)
log.Debug("Profiling!")
}
} | [
"func",
"configureCpuProfiler",
"(",
"opts",
"*",
"CliOpts",
")",
"{",
"if",
"!",
"*",
"opts",
".",
"CpuProfile",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"profilerFile",
"os",
".",
"File",
"\n\n",
"// Capture CTRL-C and stop the CPU profiler",
"sigChannel",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"sigChannel",
",",
"os",
".",
"Interrupt",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"sig",
":=",
"range",
"sigChannel",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"sig",
")",
"\n",
"pprof",
".",
"StopCPUProfile",
"(",
")",
"\n",
"profilerFile",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Enable CPU profiling support if requested",
"if",
"*",
"opts",
".",
"CpuProfile",
"{",
"profilerFile",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"\"",
"\"",
")",
"\n",
"exitWithError",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"pprof",
".",
"StartCPUProfile",
"(",
"profilerFile",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
]
| // configureCpuProfiler sets of the CPU profiler and a signal handler to
// stop it if we have been told to run the CPU profiler. | [
"configureCpuProfiler",
"sets",
"of",
"the",
"CPU",
"profiler",
"and",
"a",
"signal",
"handler",
"to",
"stop",
"it",
"if",
"we",
"have",
"been",
"told",
"to",
"run",
"the",
"CPU",
"profiler",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/main.go#L169-L195 |
11,769 | newrelic/sidecar | main.go | configureLoggingFormat | func configureLoggingFormat(config *Config) {
if config.Sidecar.LoggingFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// Default to verbose timestamping
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})
}
} | go | func configureLoggingFormat(config *Config) {
if config.Sidecar.LoggingFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// Default to verbose timestamping
log.SetFormatter(&log.TextFormatter{FullTimestamp: true})
}
} | [
"func",
"configureLoggingFormat",
"(",
"config",
"*",
"Config",
")",
"{",
"if",
"config",
".",
"Sidecar",
".",
"LoggingFormat",
"==",
"\"",
"\"",
"{",
"log",
".",
"SetFormatter",
"(",
"&",
"log",
".",
"JSONFormatter",
"{",
"}",
")",
"\n",
"}",
"else",
"{",
"// Default to verbose timestamping",
"log",
".",
"SetFormatter",
"(",
"&",
"log",
".",
"TextFormatter",
"{",
"FullTimestamp",
":",
"true",
"}",
")",
"\n",
"}",
"\n",
"}"
]
| // configureLoggingFormat switches between text and JSON log format | [
"configureLoggingFormat",
"switches",
"between",
"text",
"and",
"JSON",
"log",
"format"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/main.go#L215-L222 |
11,770 | newrelic/sidecar | main.go | configureListeners | func configureListeners(config *Config, state *catalog.ServicesState) {
for _, url := range config.Listeners.Urls {
listener := catalog.NewUrlListener(url, false)
listener.Watch(state)
}
} | go | func configureListeners(config *Config, state *catalog.ServicesState) {
for _, url := range config.Listeners.Urls {
listener := catalog.NewUrlListener(url, false)
listener.Watch(state)
}
} | [
"func",
"configureListeners",
"(",
"config",
"*",
"Config",
",",
"state",
"*",
"catalog",
".",
"ServicesState",
")",
"{",
"for",
"_",
",",
"url",
":=",
"range",
"config",
".",
"Listeners",
".",
"Urls",
"{",
"listener",
":=",
"catalog",
".",
"NewUrlListener",
"(",
"url",
",",
"false",
")",
"\n",
"listener",
".",
"Watch",
"(",
"state",
")",
"\n",
"}",
"\n",
"}"
]
| // configureListeners sets up any statically configured state change event listeners. | [
"configureListeners",
"sets",
"up",
"any",
"statically",
"configured",
"state",
"change",
"event",
"listeners",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/main.go#L260-L265 |
11,771 | newrelic/sidecar | catalog/services_state.go | NewServer | func NewServer(name string) *Server {
server := &Server{
Name: name,
// Pre-create for 5 services per host
Services: make(map[string]*service.Service, 5),
LastUpdated: time.Unix(0, 0),
LastChanged: time.Unix(0, 0),
}
return server
} | go | func NewServer(name string) *Server {
server := &Server{
Name: name,
// Pre-create for 5 services per host
Services: make(map[string]*service.Service, 5),
LastUpdated: time.Unix(0, 0),
LastChanged: time.Unix(0, 0),
}
return server
} | [
"func",
"NewServer",
"(",
"name",
"string",
")",
"*",
"Server",
"{",
"server",
":=",
"&",
"Server",
"{",
"Name",
":",
"name",
",",
"// Pre-create for 5 services per host",
"Services",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"service",
".",
"Service",
",",
"5",
")",
",",
"LastUpdated",
":",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"LastChanged",
":",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"}",
"\n\n",
"return",
"server",
"\n",
"}"
]
| // Returns a pointer to a properly configured Server | [
"Returns",
"a",
"pointer",
"to",
"a",
"properly",
"configured",
"Server"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L55-L65 |
11,772 | newrelic/sidecar | catalog/services_state.go | NewServicesState | func NewServicesState() *ServicesState {
var err error
state := &ServicesState{
Servers: make(map[string]*Server, 5),
Broadcasts: make(chan [][]byte),
LastChanged: time.Unix(0, 0),
tombstoneRetransmit: TOMBSTONE_RETRANSMIT,
ServiceMsgs: make(chan service.Service, 25),
listeners: make(map[string]Listener),
}
state.Hostname, err = os.Hostname()
if err != nil {
log.Errorf("Error getting hostname! %s", err.Error())
}
return state
} | go | func NewServicesState() *ServicesState {
var err error
state := &ServicesState{
Servers: make(map[string]*Server, 5),
Broadcasts: make(chan [][]byte),
LastChanged: time.Unix(0, 0),
tombstoneRetransmit: TOMBSTONE_RETRANSMIT,
ServiceMsgs: make(chan service.Service, 25),
listeners: make(map[string]Listener),
}
state.Hostname, err = os.Hostname()
if err != nil {
log.Errorf("Error getting hostname! %s", err.Error())
}
return state
} | [
"func",
"NewServicesState",
"(",
")",
"*",
"ServicesState",
"{",
"var",
"err",
"error",
"\n",
"state",
":=",
"&",
"ServicesState",
"{",
"Servers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Server",
",",
"5",
")",
",",
"Broadcasts",
":",
"make",
"(",
"chan",
"[",
"]",
"[",
"]",
"byte",
")",
",",
"LastChanged",
":",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"tombstoneRetransmit",
":",
"TOMBSTONE_RETRANSMIT",
",",
"ServiceMsgs",
":",
"make",
"(",
"chan",
"service",
".",
"Service",
",",
"25",
")",
",",
"listeners",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Listener",
")",
",",
"}",
"\n",
"state",
".",
"Hostname",
",",
"err",
"=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"state",
"\n",
"}"
]
| // Returns a pointer to a properly configured ServicesState | [
"Returns",
"a",
"pointer",
"to",
"a",
"properly",
"configured",
"ServicesState"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L88-L104 |
11,773 | newrelic/sidecar | catalog/services_state.go | ProcessServiceMsgs | func (state *ServicesState) ProcessServiceMsgs(looper director.Looper) {
looper.Loop(func() error {
service := <-state.ServiceMsgs
state.AddServiceEntry(service)
return nil
})
} | go | func (state *ServicesState) ProcessServiceMsgs(looper director.Looper) {
looper.Loop(func() error {
service := <-state.ServiceMsgs
state.AddServiceEntry(service)
return nil
})
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"ProcessServiceMsgs",
"(",
"looper",
"director",
".",
"Looper",
")",
"{",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"service",
":=",
"<-",
"state",
".",
"ServiceMsgs",
"\n",
"state",
".",
"AddServiceEntry",
"(",
"service",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // ProcessNewServiceMsgs is to be run in a goroutine, and processes incoming
// service notices. | [
"ProcessNewServiceMsgs",
"is",
"to",
"be",
"run",
"in",
"a",
"goroutine",
"and",
"processes",
"incoming",
"service",
"notices",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L127-L133 |
11,774 | newrelic/sidecar | catalog/services_state.go | HasServer | func (state *ServicesState) HasServer(hostname string) bool {
_, ok := state.Servers[hostname]
return ok
} | go | func (state *ServicesState) HasServer(hostname string) bool {
_, ok := state.Servers[hostname]
return ok
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"HasServer",
"(",
"hostname",
"string",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"state",
".",
"Servers",
"[",
"hostname",
"]",
"\n",
"return",
"ok",
"\n",
"}"
]
| // Shortcut for checking if the Servers map has an entry for this
// hostname. | [
"Shortcut",
"for",
"checking",
"if",
"the",
"Servers",
"map",
"has",
"an",
"entry",
"for",
"this",
"hostname",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L137-L140 |
11,775 | newrelic/sidecar | catalog/services_state.go | ExpireServer | func (state *ServicesState) ExpireServer(hostname string) {
if !state.HasServer(hostname) || len(state.Servers[hostname].Services) == 0 {
log.Infof("No records to expire for %s", hostname)
return
}
hasLiveServices := false
for _, svc := range state.Servers[hostname].Services {
if !svc.IsTombstone() {
hasLiveServices = true
break
}
}
if !hasLiveServices {
log.Infof("No records to expire for %s (no live services)", hostname)
return
}
log.Infof("Expiring %s", hostname)
var tombstones []service.Service
for _, svc := range state.Servers[hostname].Services {
previousStatus := svc.Status
state.ServiceChanged(svc, previousStatus, svc.Updated)
svc.Tombstone()
tombstones = append(tombstones, *svc)
}
if len(tombstones) < 1 {
log.Warn("Tried to announce a zero length list of tombstones")
return
}
state.SendServices(
tombstones,
director.NewTimedLooper(TOMBSTONE_COUNT, state.tombstoneRetransmit, nil),
)
} | go | func (state *ServicesState) ExpireServer(hostname string) {
if !state.HasServer(hostname) || len(state.Servers[hostname].Services) == 0 {
log.Infof("No records to expire for %s", hostname)
return
}
hasLiveServices := false
for _, svc := range state.Servers[hostname].Services {
if !svc.IsTombstone() {
hasLiveServices = true
break
}
}
if !hasLiveServices {
log.Infof("No records to expire for %s (no live services)", hostname)
return
}
log.Infof("Expiring %s", hostname)
var tombstones []service.Service
for _, svc := range state.Servers[hostname].Services {
previousStatus := svc.Status
state.ServiceChanged(svc, previousStatus, svc.Updated)
svc.Tombstone()
tombstones = append(tombstones, *svc)
}
if len(tombstones) < 1 {
log.Warn("Tried to announce a zero length list of tombstones")
return
}
state.SendServices(
tombstones,
director.NewTimedLooper(TOMBSTONE_COUNT, state.tombstoneRetransmit, nil),
)
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"ExpireServer",
"(",
"hostname",
"string",
")",
"{",
"if",
"!",
"state",
".",
"HasServer",
"(",
"hostname",
")",
"||",
"len",
"(",
"state",
".",
"Servers",
"[",
"hostname",
"]",
".",
"Services",
")",
"==",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hostname",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"hasLiveServices",
":=",
"false",
"\n",
"for",
"_",
",",
"svc",
":=",
"range",
"state",
".",
"Servers",
"[",
"hostname",
"]",
".",
"Services",
"{",
"if",
"!",
"svc",
".",
"IsTombstone",
"(",
")",
"{",
"hasLiveServices",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"hasLiveServices",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hostname",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hostname",
")",
"\n\n",
"var",
"tombstones",
"[",
"]",
"service",
".",
"Service",
"\n\n",
"for",
"_",
",",
"svc",
":=",
"range",
"state",
".",
"Servers",
"[",
"hostname",
"]",
".",
"Services",
"{",
"previousStatus",
":=",
"svc",
".",
"Status",
"\n",
"state",
".",
"ServiceChanged",
"(",
"svc",
",",
"previousStatus",
",",
"svc",
".",
"Updated",
")",
"\n",
"svc",
".",
"Tombstone",
"(",
")",
"\n",
"tombstones",
"=",
"append",
"(",
"tombstones",
",",
"*",
"svc",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"tombstones",
")",
"<",
"1",
"{",
"log",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"state",
".",
"SendServices",
"(",
"tombstones",
",",
"director",
".",
"NewTimedLooper",
"(",
"TOMBSTONE_COUNT",
",",
"state",
".",
"tombstoneRetransmit",
",",
"nil",
")",
",",
")",
"\n",
"}"
]
| // A server has left the cluster, so tombstone all of its records | [
"A",
"server",
"has",
"left",
"the",
"cluster",
"so",
"tombstone",
"all",
"of",
"its",
"records"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L143-L182 |
11,776 | newrelic/sidecar | catalog/services_state.go | ServiceChanged | func (state *ServicesState) ServiceChanged(svc *service.Service, previousStatus int, updated time.Time) {
state.serverChanged(svc.Hostname, updated)
state.NotifyListeners(svc, previousStatus, state.LastChanged)
} | go | func (state *ServicesState) ServiceChanged(svc *service.Service, previousStatus int, updated time.Time) {
state.serverChanged(svc.Hostname, updated)
state.NotifyListeners(svc, previousStatus, state.LastChanged)
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"ServiceChanged",
"(",
"svc",
"*",
"service",
".",
"Service",
",",
"previousStatus",
"int",
",",
"updated",
"time",
".",
"Time",
")",
"{",
"state",
".",
"serverChanged",
"(",
"svc",
".",
"Hostname",
",",
"updated",
")",
"\n",
"state",
".",
"NotifyListeners",
"(",
"svc",
",",
"previousStatus",
",",
"state",
".",
"LastChanged",
")",
"\n",
"}"
]
| // Tell the state that a particular service transitioned from one state to another. | [
"Tell",
"the",
"state",
"that",
"a",
"particular",
"service",
"transitioned",
"from",
"one",
"state",
"to",
"another",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L185-L188 |
11,777 | newrelic/sidecar | catalog/services_state.go | AddListener | func (state *ServicesState) AddListener(listener Listener) {
if listener.Chan() == nil {
log.Errorf("Refusing to add listener %s with nil channel!", listener.Name())
return
}
if cap(listener.Chan()) < 1 {
log.Errorf("Refusing to add blocking channel as listener: %s", listener.Name())
return
}
state.Lock()
defer state.Unlock()
state.listeners[listener.Name()] = listener
log.Debugf("AddListener(): added %s, new count %d", listener.Name(), len(state.listeners))
} | go | func (state *ServicesState) AddListener(listener Listener) {
if listener.Chan() == nil {
log.Errorf("Refusing to add listener %s with nil channel!", listener.Name())
return
}
if cap(listener.Chan()) < 1 {
log.Errorf("Refusing to add blocking channel as listener: %s", listener.Name())
return
}
state.Lock()
defer state.Unlock()
state.listeners[listener.Name()] = listener
log.Debugf("AddListener(): added %s, new count %d", listener.Name(), len(state.listeners))
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"AddListener",
"(",
"listener",
"Listener",
")",
"{",
"if",
"listener",
".",
"Chan",
"(",
")",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"cap",
"(",
"listener",
".",
"Chan",
"(",
")",
")",
"<",
"1",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"state",
".",
"Lock",
"(",
")",
"\n",
"defer",
"state",
".",
"Unlock",
"(",
")",
"\n\n",
"state",
".",
"listeners",
"[",
"listener",
".",
"Name",
"(",
")",
"]",
"=",
"listener",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
",",
"len",
"(",
"state",
".",
"listeners",
")",
")",
"\n",
"}"
]
| // Add an event listener channel to the list that will be notified on
// major state change events. Channels must be buffered by at least 1
// or they will block. Channels must be ready to receive input. | [
"Add",
"an",
"event",
"listener",
"channel",
"to",
"the",
"list",
"that",
"will",
"be",
"notified",
"on",
"major",
"state",
"change",
"events",
".",
"Channels",
"must",
"be",
"buffered",
"by",
"at",
"least",
"1",
"or",
"they",
"will",
"block",
".",
"Channels",
"must",
"be",
"ready",
"to",
"receive",
"input",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L235-L250 |
11,778 | newrelic/sidecar | catalog/services_state.go | RemoveListener | func (state *ServicesState) RemoveListener(name string) error {
state.Lock()
defer state.Unlock()
if _, ok := state.listeners[name]; ok {
delete(state.listeners, name)
log.Debugf("RemoveListener(): removed %s, new count %d", name, len(state.listeners))
return nil
}
return fmt.Errorf("No listener found with the name: %s", name)
} | go | func (state *ServicesState) RemoveListener(name string) error {
state.Lock()
defer state.Unlock()
if _, ok := state.listeners[name]; ok {
delete(state.listeners, name)
log.Debugf("RemoveListener(): removed %s, new count %d", name, len(state.listeners))
return nil
}
return fmt.Errorf("No listener found with the name: %s", name)
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"RemoveListener",
"(",
"name",
"string",
")",
"error",
"{",
"state",
".",
"Lock",
"(",
")",
"\n",
"defer",
"state",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"state",
".",
"listeners",
"[",
"name",
"]",
";",
"ok",
"{",
"delete",
"(",
"state",
".",
"listeners",
",",
"name",
")",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"len",
"(",
"state",
".",
"listeners",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}"
]
| // Remove an event listener channel by name. This will find the first
// listener in the list with the specified name and will remove it. | [
"Remove",
"an",
"event",
"listener",
"channel",
"by",
"name",
".",
"This",
"will",
"find",
"the",
"first",
"listener",
"in",
"the",
"list",
"with",
"the",
"specified",
"name",
"and",
"will",
"remove",
"it",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L254-L265 |
11,779 | newrelic/sidecar | catalog/services_state.go | GetListeners | func (state *ServicesState) GetListeners() []Listener {
state.RLock()
var listeners []Listener
for _, listener := range state.listeners {
listeners = append(listeners, listener)
}
state.RUnlock()
return listeners
} | go | func (state *ServicesState) GetListeners() []Listener {
state.RLock()
var listeners []Listener
for _, listener := range state.listeners {
listeners = append(listeners, listener)
}
state.RUnlock()
return listeners
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"GetListeners",
"(",
")",
"[",
"]",
"Listener",
"{",
"state",
".",
"RLock",
"(",
")",
"\n",
"var",
"listeners",
"[",
"]",
"Listener",
"\n",
"for",
"_",
",",
"listener",
":=",
"range",
"state",
".",
"listeners",
"{",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"listeners",
"\n",
"}"
]
| // GetListeners returns a slice containing all the current listeners | [
"GetListeners",
"returns",
"a",
"slice",
"containing",
"all",
"the",
"current",
"listeners"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L268-L277 |
11,780 | newrelic/sidecar | catalog/services_state.go | AddServiceEntry | func (state *ServicesState) AddServiceEntry(newSvc service.Service) {
defer metrics.MeasureSince([]string{"services_state", "AddServiceEntry"}, time.Now())
state.Lock()
defer state.Unlock()
if !state.HasServer(newSvc.Hostname) {
state.Servers[newSvc.Hostname] = NewServer(newSvc.Hostname)
}
server := state.Servers[newSvc.Hostname]
// Only apply changes that are newer or services are missing
if !server.HasService(newSvc.ID) {
server.Services[newSvc.ID] = &newSvc
state.ServiceChanged(&newSvc, service.UNKNOWN, newSvc.Updated)
state.retransmit(newSvc)
} else if newSvc.Invalidates(server.Services[newSvc.ID]) {
// We have to set these even if the status did not change
server.LastUpdated = newSvc.Updated
// Store the previous newSvc so we can compare it
oldEntry := server.Services[newSvc.ID]
// Update the new one
server.Services[newSvc.ID] = &newSvc
// When the status changes, the SeviceChanged() method will
// update all the accounting fields in the state and Server newSvc.
if oldEntry.Status != newSvc.Status {
state.ServiceChanged(&newSvc, oldEntry.Status, newSvc.Updated)
}
// We tell our gossip peers about the updated service
// by sending them the record. We're saved from an endless
// retransmit loop by the Invalidates() call above.
state.retransmit(newSvc)
}
} | go | func (state *ServicesState) AddServiceEntry(newSvc service.Service) {
defer metrics.MeasureSince([]string{"services_state", "AddServiceEntry"}, time.Now())
state.Lock()
defer state.Unlock()
if !state.HasServer(newSvc.Hostname) {
state.Servers[newSvc.Hostname] = NewServer(newSvc.Hostname)
}
server := state.Servers[newSvc.Hostname]
// Only apply changes that are newer or services are missing
if !server.HasService(newSvc.ID) {
server.Services[newSvc.ID] = &newSvc
state.ServiceChanged(&newSvc, service.UNKNOWN, newSvc.Updated)
state.retransmit(newSvc)
} else if newSvc.Invalidates(server.Services[newSvc.ID]) {
// We have to set these even if the status did not change
server.LastUpdated = newSvc.Updated
// Store the previous newSvc so we can compare it
oldEntry := server.Services[newSvc.ID]
// Update the new one
server.Services[newSvc.ID] = &newSvc
// When the status changes, the SeviceChanged() method will
// update all the accounting fields in the state and Server newSvc.
if oldEntry.Status != newSvc.Status {
state.ServiceChanged(&newSvc, oldEntry.Status, newSvc.Updated)
}
// We tell our gossip peers about the updated service
// by sending them the record. We're saved from an endless
// retransmit loop by the Invalidates() call above.
state.retransmit(newSvc)
}
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"AddServiceEntry",
"(",
"newSvc",
"service",
".",
"Service",
")",
"{",
"defer",
"metrics",
".",
"MeasureSince",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"state",
".",
"Lock",
"(",
")",
"\n",
"defer",
"state",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"state",
".",
"HasServer",
"(",
"newSvc",
".",
"Hostname",
")",
"{",
"state",
".",
"Servers",
"[",
"newSvc",
".",
"Hostname",
"]",
"=",
"NewServer",
"(",
"newSvc",
".",
"Hostname",
")",
"\n",
"}",
"\n\n",
"server",
":=",
"state",
".",
"Servers",
"[",
"newSvc",
".",
"Hostname",
"]",
"\n\n",
"// Only apply changes that are newer or services are missing",
"if",
"!",
"server",
".",
"HasService",
"(",
"newSvc",
".",
"ID",
")",
"{",
"server",
".",
"Services",
"[",
"newSvc",
".",
"ID",
"]",
"=",
"&",
"newSvc",
"\n",
"state",
".",
"ServiceChanged",
"(",
"&",
"newSvc",
",",
"service",
".",
"UNKNOWN",
",",
"newSvc",
".",
"Updated",
")",
"\n",
"state",
".",
"retransmit",
"(",
"newSvc",
")",
"\n",
"}",
"else",
"if",
"newSvc",
".",
"Invalidates",
"(",
"server",
".",
"Services",
"[",
"newSvc",
".",
"ID",
"]",
")",
"{",
"// We have to set these even if the status did not change",
"server",
".",
"LastUpdated",
"=",
"newSvc",
".",
"Updated",
"\n\n",
"// Store the previous newSvc so we can compare it",
"oldEntry",
":=",
"server",
".",
"Services",
"[",
"newSvc",
".",
"ID",
"]",
"\n\n",
"// Update the new one",
"server",
".",
"Services",
"[",
"newSvc",
".",
"ID",
"]",
"=",
"&",
"newSvc",
"\n\n",
"// When the status changes, the SeviceChanged() method will",
"// update all the accounting fields in the state and Server newSvc.",
"if",
"oldEntry",
".",
"Status",
"!=",
"newSvc",
".",
"Status",
"{",
"state",
".",
"ServiceChanged",
"(",
"&",
"newSvc",
",",
"oldEntry",
".",
"Status",
",",
"newSvc",
".",
"Updated",
")",
"\n",
"}",
"\n\n",
"// We tell our gossip peers about the updated service",
"// by sending them the record. We're saved from an endless",
"// retransmit loop by the Invalidates() call above.",
"state",
".",
"retransmit",
"(",
"newSvc",
")",
"\n",
"}",
"\n",
"}"
]
| // Take a service and merge it into our state. Correctly handle
// timestamps so we only add things newer than what we already
// know about. Retransmits updates to cluster peers. | [
"Take",
"a",
"service",
"and",
"merge",
"it",
"into",
"our",
"state",
".",
"Correctly",
"handle",
"timestamps",
"so",
"we",
"only",
"add",
"things",
"newer",
"than",
"what",
"we",
"already",
"know",
"about",
".",
"Retransmits",
"updates",
"to",
"cluster",
"peers",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L282-L320 |
11,781 | newrelic/sidecar | catalog/services_state.go | Merge | func (state *ServicesState) Merge(otherState *ServicesState) {
for _, server := range otherState.Servers {
for _, service := range server.Services {
state.ServiceMsgs <- *service
}
}
} | go | func (state *ServicesState) Merge(otherState *ServicesState) {
for _, server := range otherState.Servers {
for _, service := range server.Services {
state.ServiceMsgs <- *service
}
}
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"Merge",
"(",
"otherState",
"*",
"ServicesState",
")",
"{",
"for",
"_",
",",
"server",
":=",
"range",
"otherState",
".",
"Servers",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"server",
".",
"Services",
"{",
"state",
".",
"ServiceMsgs",
"<-",
"*",
"service",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // Merge a complete state struct into this one. Usually used on
// node startup and during anti-entropy operations. | [
"Merge",
"a",
"complete",
"state",
"struct",
"into",
"this",
"one",
".",
"Usually",
"used",
"on",
"node",
"startup",
"and",
"during",
"anti",
"-",
"entropy",
"operations",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L324-L330 |
11,782 | newrelic/sidecar | catalog/services_state.go | retransmit | func (state *ServicesState) retransmit(svc service.Service) {
// We don't retransmit our own events! We're already
// transmitting them.
if svc.Hostname == state.Hostname {
return
}
go func() {
encoded, err := svc.Encode()
if err != nil {
log.Errorf("ERROR encoding message to forward: (%s)", err.Error())
return
}
state.Broadcasts <- [][]byte{encoded}
}()
} | go | func (state *ServicesState) retransmit(svc service.Service) {
// We don't retransmit our own events! We're already
// transmitting them.
if svc.Hostname == state.Hostname {
return
}
go func() {
encoded, err := svc.Encode()
if err != nil {
log.Errorf("ERROR encoding message to forward: (%s)", err.Error())
return
}
state.Broadcasts <- [][]byte{encoded}
}()
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"retransmit",
"(",
"svc",
"service",
".",
"Service",
")",
"{",
"// We don't retransmit our own events! We're already",
"// transmitting them.",
"if",
"svc",
".",
"Hostname",
"==",
"state",
".",
"Hostname",
"{",
"return",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"encoded",
",",
"err",
":=",
"svc",
".",
"Encode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"state",
".",
"Broadcasts",
"<-",
"[",
"]",
"[",
"]",
"byte",
"{",
"encoded",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
]
| // Take a service we already handled, and drop it back into the
// channel. Backgrounded to not block the caller. | [
"Take",
"a",
"service",
"we",
"already",
"handled",
"and",
"drop",
"it",
"back",
"into",
"the",
"channel",
".",
"Backgrounded",
"to",
"not",
"block",
"the",
"caller",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L334-L349 |
11,783 | newrelic/sidecar | catalog/services_state.go | Print | func (state *ServicesState) Print(list *memberlist.Memberlist) {
log.Println(state.Format(list))
} | go | func (state *ServicesState) Print(list *memberlist.Memberlist) {
log.Println(state.Format(list))
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"Print",
"(",
"list",
"*",
"memberlist",
".",
"Memberlist",
")",
"{",
"log",
".",
"Println",
"(",
"state",
".",
"Format",
"(",
"list",
")",
")",
"\n",
"}"
]
| // Print the formatted struct | [
"Print",
"the",
"formatted",
"struct"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L397-L399 |
11,784 | newrelic/sidecar | catalog/services_state.go | TrackNewServices | func (state *ServicesState) TrackNewServices(fn func() []service.Service, looper director.Looper) {
looper.Loop(func() error {
for _, container := range fn() {
state.ServiceMsgs <- container
}
return nil
})
} | go | func (state *ServicesState) TrackNewServices(fn func() []service.Service, looper director.Looper) {
looper.Loop(func() error {
for _, container := range fn() {
state.ServiceMsgs <- container
}
return nil
})
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"TrackNewServices",
"(",
"fn",
"func",
"(",
")",
"[",
"]",
"service",
".",
"Service",
",",
"looper",
"director",
".",
"Looper",
")",
"{",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"for",
"_",
",",
"container",
":=",
"range",
"fn",
"(",
")",
"{",
"state",
".",
"ServiceMsgs",
"<-",
"container",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // TrackNewServices talks to the discovery mechanism and tracks any services we
// don't already know about. | [
"TrackNewServices",
"talks",
"to",
"the",
"discovery",
"mechanism",
"and",
"tracks",
"any",
"services",
"we",
"don",
"t",
"already",
"know",
"about",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L403-L410 |
11,785 | newrelic/sidecar | catalog/services_state.go | TrackLocalListeners | func (state *ServicesState) TrackLocalListeners(fn func() []Listener, looper director.Looper) {
looper.Loop(func() error {
discovered := fn()
// Add new listeners
for _, listener := range discovered {
state.RLock()
_, ok := state.listeners[listener.Name()]
state.RUnlock()
if !ok {
log.Infof("Adding listener %s because it was just discovered", listener.Name())
urlListener, ok := listener.(*UrlListener)
if ok {
urlListener.Watch(state)
} else {
state.AddListener(listener)
}
}
}
// Remove old ones
listeners := state.listeners
for _, listener := range listeners {
if listener.Managed() && !containsListener(discovered, listener.Name()) {
log.Infof("Removing listener %s because the service appears to be gone", listener.Name())
urlListener, ok := listener.(*UrlListener)
if ok {
log.Infof("Stopping UrlListener %s", listener.Name())
urlListener.Stop()
}
state.RemoveListener(listener.Name())
}
}
return nil
})
} | go | func (state *ServicesState) TrackLocalListeners(fn func() []Listener, looper director.Looper) {
looper.Loop(func() error {
discovered := fn()
// Add new listeners
for _, listener := range discovered {
state.RLock()
_, ok := state.listeners[listener.Name()]
state.RUnlock()
if !ok {
log.Infof("Adding listener %s because it was just discovered", listener.Name())
urlListener, ok := listener.(*UrlListener)
if ok {
urlListener.Watch(state)
} else {
state.AddListener(listener)
}
}
}
// Remove old ones
listeners := state.listeners
for _, listener := range listeners {
if listener.Managed() && !containsListener(discovered, listener.Name()) {
log.Infof("Removing listener %s because the service appears to be gone", listener.Name())
urlListener, ok := listener.(*UrlListener)
if ok {
log.Infof("Stopping UrlListener %s", listener.Name())
urlListener.Stop()
}
state.RemoveListener(listener.Name())
}
}
return nil
})
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"TrackLocalListeners",
"(",
"fn",
"func",
"(",
")",
"[",
"]",
"Listener",
",",
"looper",
"director",
".",
"Looper",
")",
"{",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"discovered",
":=",
"fn",
"(",
")",
"\n",
"// Add new listeners",
"for",
"_",
",",
"listener",
":=",
"range",
"discovered",
"{",
"state",
".",
"RLock",
"(",
")",
"\n",
"_",
",",
"ok",
":=",
"state",
".",
"listeners",
"[",
"listener",
".",
"Name",
"(",
")",
"]",
"\n",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"urlListener",
",",
"ok",
":=",
"listener",
".",
"(",
"*",
"UrlListener",
")",
"\n",
"if",
"ok",
"{",
"urlListener",
".",
"Watch",
"(",
"state",
")",
"\n",
"}",
"else",
"{",
"state",
".",
"AddListener",
"(",
"listener",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Remove old ones",
"listeners",
":=",
"state",
".",
"listeners",
"\n",
"for",
"_",
",",
"listener",
":=",
"range",
"listeners",
"{",
"if",
"listener",
".",
"Managed",
"(",
")",
"&&",
"!",
"containsListener",
"(",
"discovered",
",",
"listener",
".",
"Name",
"(",
")",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"urlListener",
",",
"ok",
":=",
"listener",
".",
"(",
"*",
"UrlListener",
")",
"\n",
"if",
"ok",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"urlListener",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"state",
".",
"RemoveListener",
"(",
"listener",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // TrackLocalListeners runs in the background and repeatedly calls
// a discovery function to return a list of event listeners. These will
// then be added to to the listener list. Managed listeners no longer
// reported from discovery will be removed. | [
"TrackLocalListeners",
"runs",
"in",
"the",
"background",
"and",
"repeatedly",
"calls",
"a",
"discovery",
"function",
"to",
"return",
"a",
"list",
"of",
"event",
"listeners",
".",
"These",
"will",
"then",
"be",
"added",
"to",
"to",
"the",
"listener",
"list",
".",
"Managed",
"listeners",
"no",
"longer",
"reported",
"from",
"discovery",
"will",
"be",
"removed",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L416-L451 |
11,786 | newrelic/sidecar | catalog/services_state.go | IsNewService | func (state *ServicesState) IsNewService(svc *service.Service) bool {
var found *service.Service
if state.HasServer(svc.Hostname) {
found = state.Servers[svc.Hostname].Services[svc.ID]
}
if found == nil || (!svc.IsTombstone() && svc.Status != found.Status) {
return true
}
return false
} | go | func (state *ServicesState) IsNewService(svc *service.Service) bool {
var found *service.Service
if state.HasServer(svc.Hostname) {
found = state.Servers[svc.Hostname].Services[svc.ID]
}
if found == nil || (!svc.IsTombstone() && svc.Status != found.Status) {
return true
}
return false
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"IsNewService",
"(",
"svc",
"*",
"service",
".",
"Service",
")",
"bool",
"{",
"var",
"found",
"*",
"service",
".",
"Service",
"\n\n",
"if",
"state",
".",
"HasServer",
"(",
"svc",
".",
"Hostname",
")",
"{",
"found",
"=",
"state",
".",
"Servers",
"[",
"svc",
".",
"Hostname",
"]",
".",
"Services",
"[",
"svc",
".",
"ID",
"]",
"\n",
"}",
"\n\n",
"if",
"found",
"==",
"nil",
"||",
"(",
"!",
"svc",
".",
"IsTombstone",
"(",
")",
"&&",
"svc",
".",
"Status",
"!=",
"found",
".",
"Status",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
]
| // Do we know about this service already? If we do, is it a tombstone? | [
"Do",
"we",
"know",
"about",
"this",
"service",
"already?",
"If",
"we",
"do",
"is",
"it",
"a",
"tombstone?"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L463-L475 |
11,787 | newrelic/sidecar | catalog/services_state.go | BroadcastServices | func (state *ServicesState) BroadcastServices(fn func() []service.Service, looper director.Looper) {
lastTime := time.Unix(0, 0)
looper.Loop(func() error {
defer metrics.MeasureSince([]string{"services_state", "BroadcastServices"}, time.Now())
var services []service.Service
haveNewServices := false
servicesList := fn()
state.RLock()
defer state.RUnlock()
for _, svc := range servicesList {
isNew := state.IsNewService(&svc)
// We'll broadcast it now if it's new or we've hit refresh window
if isNew {
log.Debug("Found service changes in BroadcastServices()")
haveNewServices = true
services = append(services, svc)
// Check that refresh window... is it time?
} else if time.Now().UTC().Add(0 - ALIVE_BROADCAST_INTERVAL).After(lastTime) {
services = append(services, svc)
}
}
if len(services) > 0 {
log.Debug("Starting to broadcast")
// Figure out how many times to announce the service. New services get more announcements.
runCount := 1
if haveNewServices {
runCount = ALIVE_COUNT
}
lastTime = time.Now().UTC()
state.SendServices(
services,
director.NewTimedLooper(runCount, state.tombstoneRetransmit, nil),
)
log.Debug("Completing broadcast")
} else {
// We expect there to always be _something_ in the channel
// once we've run.
state.Broadcasts <- nil
}
return nil
})
} | go | func (state *ServicesState) BroadcastServices(fn func() []service.Service, looper director.Looper) {
lastTime := time.Unix(0, 0)
looper.Loop(func() error {
defer metrics.MeasureSince([]string{"services_state", "BroadcastServices"}, time.Now())
var services []service.Service
haveNewServices := false
servicesList := fn()
state.RLock()
defer state.RUnlock()
for _, svc := range servicesList {
isNew := state.IsNewService(&svc)
// We'll broadcast it now if it's new or we've hit refresh window
if isNew {
log.Debug("Found service changes in BroadcastServices()")
haveNewServices = true
services = append(services, svc)
// Check that refresh window... is it time?
} else if time.Now().UTC().Add(0 - ALIVE_BROADCAST_INTERVAL).After(lastTime) {
services = append(services, svc)
}
}
if len(services) > 0 {
log.Debug("Starting to broadcast")
// Figure out how many times to announce the service. New services get more announcements.
runCount := 1
if haveNewServices {
runCount = ALIVE_COUNT
}
lastTime = time.Now().UTC()
state.SendServices(
services,
director.NewTimedLooper(runCount, state.tombstoneRetransmit, nil),
)
log.Debug("Completing broadcast")
} else {
// We expect there to always be _something_ in the channel
// once we've run.
state.Broadcasts <- nil
}
return nil
})
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"BroadcastServices",
"(",
"fn",
"func",
"(",
")",
"[",
"]",
"service",
".",
"Service",
",",
"looper",
"director",
".",
"Looper",
")",
"{",
"lastTime",
":=",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
"\n\n",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"defer",
"metrics",
".",
"MeasureSince",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"var",
"services",
"[",
"]",
"service",
".",
"Service",
"\n",
"haveNewServices",
":=",
"false",
"\n\n",
"servicesList",
":=",
"fn",
"(",
")",
"\n\n",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"svc",
":=",
"range",
"servicesList",
"{",
"isNew",
":=",
"state",
".",
"IsNewService",
"(",
"&",
"svc",
")",
"\n\n",
"// We'll broadcast it now if it's new or we've hit refresh window",
"if",
"isNew",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"haveNewServices",
"=",
"true",
"\n",
"services",
"=",
"append",
"(",
"services",
",",
"svc",
")",
"\n",
"// Check that refresh window... is it time?",
"}",
"else",
"if",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Add",
"(",
"0",
"-",
"ALIVE_BROADCAST_INTERVAL",
")",
".",
"After",
"(",
"lastTime",
")",
"{",
"services",
"=",
"append",
"(",
"services",
",",
"svc",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"services",
")",
">",
"0",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"// Figure out how many times to announce the service. New services get more announcements.",
"runCount",
":=",
"1",
"\n",
"if",
"haveNewServices",
"{",
"runCount",
"=",
"ALIVE_COUNT",
"\n",
"}",
"\n\n",
"lastTime",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"state",
".",
"SendServices",
"(",
"services",
",",
"director",
".",
"NewTimedLooper",
"(",
"runCount",
",",
"state",
".",
"tombstoneRetransmit",
",",
"nil",
")",
",",
")",
"\n",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"// We expect there to always be _something_ in the channel",
"// once we've run.",
"state",
".",
"Broadcasts",
"<-",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
]
| // BroadcastServices loops forever, transmitting info about our containers on the
// broadcast channel. Intended to run as a background goroutine. | [
"BroadcastServices",
"loops",
"forever",
"transmitting",
"info",
"about",
"our",
"containers",
"on",
"the",
"broadcast",
"channel",
".",
"Intended",
"to",
"run",
"as",
"a",
"background",
"goroutine",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L479-L528 |
11,788 | newrelic/sidecar | catalog/services_state.go | SendServices | func (state *ServicesState) SendServices(services []service.Service, looper director.Looper) {
// Announce these every second for awhile
go func() {
defer metrics.MeasureSince([]string{"services_state", "SendServices"}, time.Now())
additionalTime := 0 * time.Second
looper.Loop(func() error {
var prepared [][]byte
for _, svc := range services {
svc.Updated = svc.Updated.Add(additionalTime)
encoded, err := svc.Encode()
if err != nil {
log.Errorf("ERROR encoding container: (%s)", err.Error())
}
prepared = append(prepared, encoded)
}
// We add time to make sure that these get retransmitted by peers.
// Otherwise they aren't "new" messages and don't get retransmitted.
additionalTime = additionalTime + 50*time.Nanosecond
state.Broadcasts <- prepared // Put it on the wire
return nil
})
}()
} | go | func (state *ServicesState) SendServices(services []service.Service, looper director.Looper) {
// Announce these every second for awhile
go func() {
defer metrics.MeasureSince([]string{"services_state", "SendServices"}, time.Now())
additionalTime := 0 * time.Second
looper.Loop(func() error {
var prepared [][]byte
for _, svc := range services {
svc.Updated = svc.Updated.Add(additionalTime)
encoded, err := svc.Encode()
if err != nil {
log.Errorf("ERROR encoding container: (%s)", err.Error())
}
prepared = append(prepared, encoded)
}
// We add time to make sure that these get retransmitted by peers.
// Otherwise they aren't "new" messages and don't get retransmitted.
additionalTime = additionalTime + 50*time.Nanosecond
state.Broadcasts <- prepared // Put it on the wire
return nil
})
}()
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"SendServices",
"(",
"services",
"[",
"]",
"service",
".",
"Service",
",",
"looper",
"director",
".",
"Looper",
")",
"{",
"// Announce these every second for awhile",
"go",
"func",
"(",
")",
"{",
"defer",
"metrics",
".",
"MeasureSince",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"additionalTime",
":=",
"0",
"*",
"time",
".",
"Second",
"\n",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"var",
"prepared",
"[",
"]",
"[",
"]",
"byte",
"\n\n",
"for",
"_",
",",
"svc",
":=",
"range",
"services",
"{",
"svc",
".",
"Updated",
"=",
"svc",
".",
"Updated",
".",
"Add",
"(",
"additionalTime",
")",
"\n",
"encoded",
",",
"err",
":=",
"svc",
".",
"Encode",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"prepared",
"=",
"append",
"(",
"prepared",
",",
"encoded",
")",
"\n",
"}",
"\n\n",
"// We add time to make sure that these get retransmitted by peers.",
"// Otherwise they aren't \"new\" messages and don't get retransmitted.",
"additionalTime",
"=",
"additionalTime",
"+",
"50",
"*",
"time",
".",
"Nanosecond",
"\n",
"state",
".",
"Broadcasts",
"<-",
"prepared",
"// Put it on the wire",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
]
| // Actually transmit an encoded service record into the channel. Runs a
// background goroutine that continues the broadcast for 10 seconds so we
// have a pretty good idea that it was delivered. | [
"Actually",
"transmit",
"an",
"encoded",
"service",
"record",
"into",
"the",
"channel",
".",
"Runs",
"a",
"background",
"goroutine",
"that",
"continues",
"the",
"broadcast",
"for",
"10",
"seconds",
"so",
"we",
"have",
"a",
"pretty",
"good",
"idea",
"that",
"it",
"was",
"delivered",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L533-L558 |
11,789 | newrelic/sidecar | catalog/services_state.go | ByService | func (state *ServicesState) ByService() map[string][]*service.Service {
serviceMap := make(map[string][]*service.Service)
state.EachServiceSorted(
func(hostname *string, serviceId *string, svc *service.Service) {
serviceMap[svc.Name] = append(serviceMap[svc.Name], svc)
},
)
return serviceMap
} | go | func (state *ServicesState) ByService() map[string][]*service.Service {
serviceMap := make(map[string][]*service.Service)
state.EachServiceSorted(
func(hostname *string, serviceId *string, svc *service.Service) {
serviceMap[svc.Name] = append(serviceMap[svc.Name], svc)
},
)
return serviceMap
} | [
"func",
"(",
"state",
"*",
"ServicesState",
")",
"ByService",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"service",
".",
"Service",
"{",
"serviceMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"service",
".",
"Service",
")",
"\n\n",
"state",
".",
"EachServiceSorted",
"(",
"func",
"(",
"hostname",
"*",
"string",
",",
"serviceId",
"*",
"string",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"{",
"serviceMap",
"[",
"svc",
".",
"Name",
"]",
"=",
"append",
"(",
"serviceMap",
"[",
"svc",
".",
"Name",
"]",
",",
"svc",
")",
"\n",
"}",
",",
")",
"\n\n",
"return",
"serviceMap",
"\n",
"}"
]
| // Group the services into a map by service name rather than by the
// hosts they run on. | [
"Group",
"the",
"services",
"into",
"a",
"map",
"by",
"service",
"name",
"rather",
"than",
"by",
"the",
"hosts",
"they",
"run",
"on",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L688-L698 |
11,790 | newrelic/sidecar | catalog/services_state.go | Decode | func Decode(data []byte) (*ServicesState, error) {
newState := NewServicesState()
err := newState.UnmarshalJSON(data)
if err != nil {
log.Errorf("Error decoding state! (%s)", err.Error())
}
return newState, err
} | go | func Decode(data []byte) (*ServicesState, error) {
newState := NewServicesState()
err := newState.UnmarshalJSON(data)
if err != nil {
log.Errorf("Error decoding state! (%s)", err.Error())
}
return newState, err
} | [
"func",
"Decode",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"ServicesState",
",",
"error",
")",
"{",
"newState",
":=",
"NewServicesState",
"(",
")",
"\n",
"err",
":=",
"newState",
".",
"UnmarshalJSON",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"newState",
",",
"err",
"\n",
"}"
]
| // Take a byte slice and return a properly reconstituted state struct | [
"Take",
"a",
"byte",
"slice",
"and",
"return",
"a",
"properly",
"reconstituted",
"state",
"struct"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/catalog/services_state.go#L724-L732 |
11,791 | newrelic/sidecar | haproxy/haproxy.go | New | func New(configFile string, pidFile string) *HAproxy {
reloadCmd := "haproxy -f " + configFile + " -p " + pidFile + " `[[ -f " + pidFile + " ]] && echo \"-sf $(cat " + pidFile + ")\"]]`"
verifyCmd := "haproxy -c -f " + configFile
proxy := HAproxy{
ReloadCmd: reloadCmd,
VerifyCmd: verifyCmd,
Template: "views/haproxy.cfg",
ConfigFile: configFile,
PidFile: pidFile,
}
return &proxy
} | go | func New(configFile string, pidFile string) *HAproxy {
reloadCmd := "haproxy -f " + configFile + " -p " + pidFile + " `[[ -f " + pidFile + " ]] && echo \"-sf $(cat " + pidFile + ")\"]]`"
verifyCmd := "haproxy -c -f " + configFile
proxy := HAproxy{
ReloadCmd: reloadCmd,
VerifyCmd: verifyCmd,
Template: "views/haproxy.cfg",
ConfigFile: configFile,
PidFile: pidFile,
}
return &proxy
} | [
"func",
"New",
"(",
"configFile",
"string",
",",
"pidFile",
"string",
")",
"*",
"HAproxy",
"{",
"reloadCmd",
":=",
"\"",
"\"",
"+",
"configFile",
"+",
"\"",
"\"",
"+",
"pidFile",
"+",
"\"",
"\"",
"+",
"pidFile",
"+",
"\"",
"\\\"",
"\"",
"+",
"pidFile",
"+",
"\"",
"\\\"",
"\"",
"\n",
"verifyCmd",
":=",
"\"",
"\"",
"+",
"configFile",
"\n\n",
"proxy",
":=",
"HAproxy",
"{",
"ReloadCmd",
":",
"reloadCmd",
",",
"VerifyCmd",
":",
"verifyCmd",
",",
"Template",
":",
"\"",
"\"",
",",
"ConfigFile",
":",
"configFile",
",",
"PidFile",
":",
"pidFile",
",",
"}",
"\n\n",
"return",
"&",
"proxy",
"\n",
"}"
]
| // Constructs a properly configured HAProxy and returns a pointer to it | [
"Constructs",
"a",
"properly",
"configured",
"HAProxy",
"and",
"returns",
"a",
"pointer",
"to",
"it"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L45-L58 |
11,792 | newrelic/sidecar | haproxy/haproxy.go | sanitizeName | func sanitizeName(image string) string {
replace := regexp.MustCompile("[^a-z0-9-]")
return replace.ReplaceAllString(image, "-")
} | go | func sanitizeName(image string) string {
replace := regexp.MustCompile("[^a-z0-9-]")
return replace.ReplaceAllString(image, "-")
} | [
"func",
"sanitizeName",
"(",
"image",
"string",
")",
"string",
"{",
"replace",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"return",
"replace",
".",
"ReplaceAllString",
"(",
"image",
",",
"\"",
"\"",
")",
"\n",
"}"
]
| // Clean up image names for writing as HAproxy frontend and backend entries | [
"Clean",
"up",
"image",
"names",
"for",
"writing",
"as",
"HAproxy",
"frontend",
"and",
"backend",
"entries"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L86-L89 |
11,793 | newrelic/sidecar | haproxy/haproxy.go | findPortForService | func findPortForService(svcPort string, svc *service.Service) string {
matchPort, err := strconv.ParseInt(svcPort, 10, 64)
if err != nil {
log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
return "-1"
}
for _, port := range svc.Ports {
if port.ServicePort == matchPort {
internalPort := strconv.FormatInt(port.Port, 10)
return internalPort
}
}
return "-1"
} | go | func findPortForService(svcPort string, svc *service.Service) string {
matchPort, err := strconv.ParseInt(svcPort, 10, 64)
if err != nil {
log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
return "-1"
}
for _, port := range svc.Ports {
if port.ServicePort == matchPort {
internalPort := strconv.FormatInt(port.Port, 10)
return internalPort
}
}
return "-1"
} | [
"func",
"findPortForService",
"(",
"svcPort",
"string",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"string",
"{",
"matchPort",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"svcPort",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"svcPort",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"if",
"port",
".",
"ServicePort",
"==",
"matchPort",
"{",
"internalPort",
":=",
"strconv",
".",
"FormatInt",
"(",
"port",
".",
"Port",
",",
"10",
")",
"\n",
"return",
"internalPort",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
]
| // Find a matching Port when given a ServicePort | [
"Find",
"a",
"matching",
"Port",
"when",
"given",
"a",
"ServicePort"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L92-L107 |
11,794 | newrelic/sidecar | haproxy/haproxy.go | findIpForService | func (h *HAproxy) findIpForService(svcPort string, svc *service.Service) string {
// We can turn off using IP addresses in the config, which is sometimes
// necessary (e.g. w/Docker for Mac).
if h.UseHostnames {
return svc.Hostname
}
matchPort, err := strconv.ParseInt(svcPort, 10, 64)
if err != nil {
log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
return "-1"
}
for _, port := range svc.Ports {
if port.ServicePort == matchPort {
return port.IP
}
}
// This defaults to the previous behavior of templating the hostname
// instead of the IP address. This relies on haproxy being able to
// resolve the hostname (which means non-FQDN hostnames are a hazard).
// Ideally this never happens for clusters that have IP addresses defined.
return svc.Hostname
} | go | func (h *HAproxy) findIpForService(svcPort string, svc *service.Service) string {
// We can turn off using IP addresses in the config, which is sometimes
// necessary (e.g. w/Docker for Mac).
if h.UseHostnames {
return svc.Hostname
}
matchPort, err := strconv.ParseInt(svcPort, 10, 64)
if err != nil {
log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
return "-1"
}
for _, port := range svc.Ports {
if port.ServicePort == matchPort {
return port.IP
}
}
// This defaults to the previous behavior of templating the hostname
// instead of the IP address. This relies on haproxy being able to
// resolve the hostname (which means non-FQDN hostnames are a hazard).
// Ideally this never happens for clusters that have IP addresses defined.
return svc.Hostname
} | [
"func",
"(",
"h",
"*",
"HAproxy",
")",
"findIpForService",
"(",
"svcPort",
"string",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"string",
"{",
"// We can turn off using IP addresses in the config, which is sometimes",
"// necessary (e.g. w/Docker for Mac).",
"if",
"h",
".",
"UseHostnames",
"{",
"return",
"svc",
".",
"Hostname",
"\n",
"}",
"\n\n",
"matchPort",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"svcPort",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"svcPort",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"if",
"port",
".",
"ServicePort",
"==",
"matchPort",
"{",
"return",
"port",
".",
"IP",
"\n",
"}",
"\n",
"}",
"\n\n",
"// This defaults to the previous behavior of templating the hostname",
"// instead of the IP address. This relies on haproxy being able to",
"// resolve the hostname (which means non-FQDN hostnames are a hazard).",
"// Ideally this never happens for clusters that have IP addresses defined.",
"return",
"svc",
".",
"Hostname",
"\n",
"}"
]
| // Find the matching IP address when given a ServicePort | [
"Find",
"the",
"matching",
"IP",
"address",
"when",
"given",
"a",
"ServicePort"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L110-L134 |
11,795 | newrelic/sidecar | haproxy/haproxy.go | swallowSignals | func (h *HAproxy) swallowSignals() {
// from HAproxy which propagate.
sigChan := make(chan os.Signal, 10)
// Used to stop the goroutine
h.sigStopChan = make(chan struct{})
go func() {
for {
select {
case <-sigChan:
// swallow signal
case <-h.sigStopChan:
break
}
}
}()
signal.Notify(sigChan, syscall.SIGSTOP, syscall.SIGTSTP, syscall.SIGTTIN, syscall.SIGTTOU)
} | go | func (h *HAproxy) swallowSignals() {
// from HAproxy which propagate.
sigChan := make(chan os.Signal, 10)
// Used to stop the goroutine
h.sigStopChan = make(chan struct{})
go func() {
for {
select {
case <-sigChan:
// swallow signal
case <-h.sigStopChan:
break
}
}
}()
signal.Notify(sigChan, syscall.SIGSTOP, syscall.SIGTSTP, syscall.SIGTTIN, syscall.SIGTTOU)
} | [
"func",
"(",
"h",
"*",
"HAproxy",
")",
"swallowSignals",
"(",
")",
"{",
"// from HAproxy which propagate.",
"sigChan",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"10",
")",
"\n\n",
"// Used to stop the goroutine",
"h",
".",
"sigStopChan",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"sigChan",
":",
"// swallow signal",
"case",
"<-",
"h",
".",
"sigStopChan",
":",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"signal",
".",
"Notify",
"(",
"sigChan",
",",
"syscall",
".",
"SIGSTOP",
",",
"syscall",
".",
"SIGTSTP",
",",
"syscall",
".",
"SIGTTIN",
",",
"syscall",
".",
"SIGTTOU",
")",
"\n",
"}"
]
| // notifySignals swallows a bunch of signals that get sent to us when running into
// an error from HAproxy. If we didn't swallow these, the process would potentially
// stop when the signals are propagated by the sub-shell. | [
"notifySignals",
"swallows",
"a",
"bunch",
"of",
"signals",
"that",
"get",
"sent",
"to",
"us",
"when",
"running",
"into",
"an",
"error",
"from",
"HAproxy",
".",
"If",
"we",
"didn",
"t",
"swallow",
"these",
"the",
"process",
"would",
"potentially",
"stop",
"when",
"the",
"signals",
"are",
"propagated",
"by",
"the",
"sub",
"-",
"shell",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L195-L214 |
11,796 | newrelic/sidecar | haproxy/haproxy.go | ResetSignals | func (h *HAproxy) ResetSignals() {
h.sigLock.Lock()
signal.Reset(syscall.SIGSTOP, syscall.SIGTSTP, syscall.SIGTTIN, syscall.SIGTTOU)
select {
case h.sigStopChan <- struct{}{}: // nothing
default:
}
h.sigLock.Unlock()
} | go | func (h *HAproxy) ResetSignals() {
h.sigLock.Lock()
signal.Reset(syscall.SIGSTOP, syscall.SIGTSTP, syscall.SIGTTIN, syscall.SIGTTOU)
select {
case h.sigStopChan <- struct{}{}: // nothing
default:
}
h.sigLock.Unlock()
} | [
"func",
"(",
"h",
"*",
"HAproxy",
")",
"ResetSignals",
"(",
")",
"{",
"h",
".",
"sigLock",
".",
"Lock",
"(",
")",
"\n",
"signal",
".",
"Reset",
"(",
"syscall",
".",
"SIGSTOP",
",",
"syscall",
".",
"SIGTSTP",
",",
"syscall",
".",
"SIGTTIN",
",",
"syscall",
".",
"SIGTTOU",
")",
"\n",
"select",
"{",
"case",
"h",
".",
"sigStopChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"// nothing",
"default",
":",
"}",
"\n\n",
"h",
".",
"sigLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
]
| // ResetSignals unhooks our signal handler from the signals the sub-commands
// initiate. This is potentially destructive if other places in the program have
// hooked to the same signals! Affected signals are SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU. | [
"ResetSignals",
"unhooks",
"our",
"signal",
"handler",
"from",
"the",
"signals",
"the",
"sub",
"-",
"commands",
"initiate",
".",
"This",
"is",
"potentially",
"destructive",
"if",
"other",
"places",
"in",
"the",
"program",
"have",
"hooked",
"to",
"the",
"same",
"signals!",
"Affected",
"signals",
"are",
"SIGSTOP",
"SIGTSTP",
"SIGTTIN",
"SIGTTOU",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L219-L228 |
11,797 | newrelic/sidecar | haproxy/haproxy.go | run | func (h *HAproxy) run(command string) error {
cmd := exec.Command("/bin/bash", "-c", command)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
// The end effect of this signal handling requirement is that we can only run _one_
// command at a time. This is totally fine for HAproxy.
h.sigLock.Lock()
defer h.sigLock.Unlock()
if !h.signalsHandled {
log.Info("Setting up signal handlers")
h.swallowSignals()
h.signalsHandled = true
}
err := cmd.Run()
if err != nil {
err = fmt.Errorf("Error running '%s': %s\n%s\n%s", command, err, stdout, stderr)
}
return err
} | go | func (h *HAproxy) run(command string) error {
cmd := exec.Command("/bin/bash", "-c", command)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
cmd.Stdout = stdout
cmd.Stderr = stderr
// The end effect of this signal handling requirement is that we can only run _one_
// command at a time. This is totally fine for HAproxy.
h.sigLock.Lock()
defer h.sigLock.Unlock()
if !h.signalsHandled {
log.Info("Setting up signal handlers")
h.swallowSignals()
h.signalsHandled = true
}
err := cmd.Run()
if err != nil {
err = fmt.Errorf("Error running '%s': %s\n%s\n%s", command, err, stdout, stderr)
}
return err
} | [
"func",
"(",
"h",
"*",
"HAproxy",
")",
"run",
"(",
"command",
"string",
")",
"error",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"command",
")",
"\n",
"stdout",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"stderr",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"cmd",
".",
"Stdout",
"=",
"stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"stderr",
"\n\n",
"// The end effect of this signal handling requirement is that we can only run _one_",
"// command at a time. This is totally fine for HAproxy.",
"h",
".",
"sigLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"sigLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"h",
".",
"signalsHandled",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"h",
".",
"swallowSignals",
"(",
")",
"\n",
"h",
".",
"signalsHandled",
"=",
"true",
"\n",
"}",
"\n\n",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"command",
",",
"err",
",",
"stdout",
",",
"stderr",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
]
| // Execute a command and bubble up the error. Includes locking behavior which means
// that only one of these can be running at once. | [
"Execute",
"a",
"command",
"and",
"bubble",
"up",
"the",
"error",
".",
"Includes",
"locking",
"behavior",
"which",
"means",
"that",
"only",
"one",
"of",
"these",
"can",
"be",
"running",
"at",
"once",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L232-L258 |
11,798 | newrelic/sidecar | haproxy/haproxy.go | WriteAndReload | func (h *HAproxy) WriteAndReload(state *catalog.ServicesState) error {
if h.ConfigFile == "" {
return fmt.Errorf("Trying to write HAproxy config, but no filename specified!")
}
outfile, err := os.Create(h.ConfigFile)
if err != nil {
return fmt.Errorf("Unable to write to %s! (%s)", h.ConfigFile, err.Error())
}
if err := h.WriteConfig(state, outfile); err != nil {
return err
}
if err = h.Verify(); err != nil {
return fmt.Errorf("Failed to verify HAproxy config! (%s)", err.Error())
}
return h.Reload()
} | go | func (h *HAproxy) WriteAndReload(state *catalog.ServicesState) error {
if h.ConfigFile == "" {
return fmt.Errorf("Trying to write HAproxy config, but no filename specified!")
}
outfile, err := os.Create(h.ConfigFile)
if err != nil {
return fmt.Errorf("Unable to write to %s! (%s)", h.ConfigFile, err.Error())
}
if err := h.WriteConfig(state, outfile); err != nil {
return err
}
if err = h.Verify(); err != nil {
return fmt.Errorf("Failed to verify HAproxy config! (%s)", err.Error())
}
return h.Reload()
} | [
"func",
"(",
"h",
"*",
"HAproxy",
")",
"WriteAndReload",
"(",
"state",
"*",
"catalog",
".",
"ServicesState",
")",
"error",
"{",
"if",
"h",
".",
"ConfigFile",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"outfile",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"h",
".",
"ConfigFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"h",
".",
"ConfigFile",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"h",
".",
"WriteConfig",
"(",
"state",
",",
"outfile",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"h",
".",
"Verify",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"return",
"h",
".",
"Reload",
"(",
")",
"\n",
"}"
]
| // Write out the the HAproxy config and reload the service. | [
"Write",
"out",
"the",
"the",
"HAproxy",
"config",
"and",
"reload",
"the",
"service",
"."
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/haproxy/haproxy.go#L293-L312 |
11,799 | newrelic/sidecar | receiver/http.go | UpdateHandler | func UpdateHandler(response http.ResponseWriter, req *http.Request, rcvr *Receiver) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
data, err := ioutil.ReadAll(req.Body)
if err != nil {
message, _ := json.Marshal(ApiErrors{[]string{err.Error()}})
response.WriteHeader(http.StatusInternalServerError)
response.Write(message)
return
}
var evt catalog.StateChangedEvent
err = json.Unmarshal(data, &evt)
if err != nil {
message, _ := json.Marshal(ApiErrors{[]string{err.Error()}})
response.WriteHeader(http.StatusInternalServerError)
response.Write(message)
return
}
rcvr.StateLock.Lock()
defer rcvr.StateLock.Unlock()
if rcvr.CurrentState == nil || rcvr.CurrentState.LastChanged.Before(evt.State.LastChanged) {
rcvr.CurrentState = &evt.State
rcvr.LastSvcChanged = &evt.ChangeEvent.Service
if ShouldNotify(evt.ChangeEvent.PreviousStatus, evt.ChangeEvent.Service.Status) {
if !rcvr.IsSubscribed(evt.ChangeEvent.Service.Name) {
return
}
if rcvr.OnUpdate == nil {
log.Errorf("No OnUpdate() callback registered!")
return
}
rcvr.EnqueueUpdate()
}
}
} | go | func UpdateHandler(response http.ResponseWriter, req *http.Request, rcvr *Receiver) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
data, err := ioutil.ReadAll(req.Body)
if err != nil {
message, _ := json.Marshal(ApiErrors{[]string{err.Error()}})
response.WriteHeader(http.StatusInternalServerError)
response.Write(message)
return
}
var evt catalog.StateChangedEvent
err = json.Unmarshal(data, &evt)
if err != nil {
message, _ := json.Marshal(ApiErrors{[]string{err.Error()}})
response.WriteHeader(http.StatusInternalServerError)
response.Write(message)
return
}
rcvr.StateLock.Lock()
defer rcvr.StateLock.Unlock()
if rcvr.CurrentState == nil || rcvr.CurrentState.LastChanged.Before(evt.State.LastChanged) {
rcvr.CurrentState = &evt.State
rcvr.LastSvcChanged = &evt.ChangeEvent.Service
if ShouldNotify(evt.ChangeEvent.PreviousStatus, evt.ChangeEvent.Service.Status) {
if !rcvr.IsSubscribed(evt.ChangeEvent.Service.Name) {
return
}
if rcvr.OnUpdate == nil {
log.Errorf("No OnUpdate() callback registered!")
return
}
rcvr.EnqueueUpdate()
}
}
} | [
"func",
"UpdateHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"rcvr",
"*",
"Receiver",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"req",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"message",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"ApiErrors",
"{",
"[",
"]",
"string",
"{",
"err",
".",
"Error",
"(",
")",
"}",
"}",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"response",
".",
"Write",
"(",
"message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"evt",
"catalog",
".",
"StateChangedEvent",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"evt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"message",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"ApiErrors",
"{",
"[",
"]",
"string",
"{",
"err",
".",
"Error",
"(",
")",
"}",
"}",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"response",
".",
"Write",
"(",
"message",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"rcvr",
".",
"StateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rcvr",
".",
"StateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"rcvr",
".",
"CurrentState",
"==",
"nil",
"||",
"rcvr",
".",
"CurrentState",
".",
"LastChanged",
".",
"Before",
"(",
"evt",
".",
"State",
".",
"LastChanged",
")",
"{",
"rcvr",
".",
"CurrentState",
"=",
"&",
"evt",
".",
"State",
"\n",
"rcvr",
".",
"LastSvcChanged",
"=",
"&",
"evt",
".",
"ChangeEvent",
".",
"Service",
"\n\n",
"if",
"ShouldNotify",
"(",
"evt",
".",
"ChangeEvent",
".",
"PreviousStatus",
",",
"evt",
".",
"ChangeEvent",
".",
"Service",
".",
"Status",
")",
"{",
"if",
"!",
"rcvr",
".",
"IsSubscribed",
"(",
"evt",
".",
"ChangeEvent",
".",
"Service",
".",
"Name",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"rcvr",
".",
"OnUpdate",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"rcvr",
".",
"EnqueueUpdate",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
]
| // Receives POSTed state updates from a Sidecar instance | [
"Receives",
"POSTed",
"state",
"updates",
"from",
"a",
"Sidecar",
"instance"
]
| 8327834c20bca8a155ccac8bc42ab2f42ca925a6 | https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/receiver/http.go#L17-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.