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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
10,700 | go-chef/chef | cookbook.go | versionParams | func versionParams(path, numVersions string) string {
if numVersions == "0" {
numVersions = "all"
}
// need to optionally add numVersion args to the request
if len(numVersions) > 0 {
path = fmt.Sprintf("%s?num_versions=%s", path, numVersions)
}
return path
} | go | func versionParams(path, numVersions string) string {
if numVersions == "0" {
numVersions = "all"
}
// need to optionally add numVersion args to the request
if len(numVersions) > 0 {
path = fmt.Sprintf("%s?num_versions=%s", path, numVersions)
}
return path
} | [
"func",
"versionParams",
"(",
"path",
",",
"numVersions",
"string",
")",
"string",
"{",
"if",
"numVersions",
"==",
"\"",
"\"",
"{",
"numVersions",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// need to optionally add numVersion args to the request",
"if",
"len",
"(",
"numVersions",
")",
">",
"0",
"{",
"path",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"numVersions",
")",
"\n",
"}",
"\n",
"return",
"path",
"\n",
"}"
] | // versionParams assembles a querystring for the chef api's num_versions
// This is used to restrict the number of versions returned in the reponse | [
"versionParams",
"assembles",
"a",
"querystring",
"for",
"the",
"chef",
"api",
"s",
"num_versions",
"This",
"is",
"used",
"to",
"restrict",
"the",
"number",
"of",
"versions",
"returned",
"in",
"the",
"reponse"
] | cfd55cf96411cfa6ea658a3904fbcb8e40843e68 | https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/cookbook.go#L93-L103 |
10,701 | go-chef/chef | cookbook.go | GetAvailableVersions | func (c *CookbookService) GetAvailableVersions(name, numVersions string) (data CookbookListResult, err error) {
path := versionParams(fmt.Sprintf("cookbooks/%s", name), numVersions)
err = c.client.magicRequestDecoder("GET", path, nil, &data)
return
} | go | func (c *CookbookService) GetAvailableVersions(name, numVersions string) (data CookbookListResult, err error) {
path := versionParams(fmt.Sprintf("cookbooks/%s", name), numVersions)
err = c.client.magicRequestDecoder("GET", path, nil, &data)
return
} | [
"func",
"(",
"c",
"*",
"CookbookService",
")",
"GetAvailableVersions",
"(",
"name",
",",
"numVersions",
"string",
")",
"(",
"data",
"CookbookListResult",
",",
"err",
"error",
")",
"{",
"path",
":=",
"versionParams",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
",",
"numVersions",
")",
"\n",
"err",
"=",
"c",
".",
"client",
".",
"magicRequestDecoder",
"(",
"\"",
"\"",
",",
"path",
",",
"nil",
",",
"&",
"data",
")",
"\n",
"return",
"\n",
"}"
] | // GetAvailable returns the versions of a coookbook available on a server | [
"GetAvailable",
"returns",
"the",
"versions",
"of",
"a",
"coookbook",
"available",
"on",
"a",
"server"
] | cfd55cf96411cfa6ea658a3904fbcb8e40843e68 | https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/cookbook.go#L114-L118 |
10,702 | go-chef/chef | cookbook.go | Delete | func (c *CookbookService) Delete(name, version string) (err error) {
path := fmt.Sprintf("cookbooks/%s/%s", name, version)
err = c.client.magicRequestDecoder("DELETE", path, nil, nil)
return
} | go | func (c *CookbookService) Delete(name, version string) (err error) {
path := fmt.Sprintf("cookbooks/%s/%s", name, version)
err = c.client.magicRequestDecoder("DELETE", path, nil, nil)
return
} | [
"func",
"(",
"c",
"*",
"CookbookService",
")",
"Delete",
"(",
"name",
",",
"version",
"string",
")",
"(",
"err",
"error",
")",
"{",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"version",
")",
"\n",
"err",
"=",
"c",
".",
"client",
".",
"magicRequestDecoder",
"(",
"\"",
"\"",
",",
"path",
",",
"nil",
",",
"nil",
")",
"\n",
"return",
"\n",
"}"
] | // DeleteVersion removes a version of a cook from a server | [
"DeleteVersion",
"removes",
"a",
"version",
"of",
"a",
"cook",
"from",
"a",
"server"
] | cfd55cf96411cfa6ea658a3904fbcb8e40843e68 | https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/cookbook.go#L152-L156 |
10,703 | go-chef/chef | databag.go | String | func (d DataBagListResult) String() (out string) {
for k, v := range d {
out += fmt.Sprintf("%s => %s\n", k, v)
}
return out
} | go | func (d DataBagListResult) String() (out string) {
for k, v := range d {
out += fmt.Sprintf("%s => %s\n", k, v)
}
return out
} | [
"func",
"(",
"d",
"DataBagListResult",
")",
"String",
"(",
")",
"(",
"out",
"string",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"d",
"{",
"out",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // String makes DataBagListResult implement the string result | [
"String",
"makes",
"DataBagListResult",
"implement",
"the",
"string",
"result"
] | cfd55cf96411cfa6ea658a3904fbcb8e40843e68 | https://github.com/go-chef/chef/blob/cfd55cf96411cfa6ea658a3904fbcb8e40843e68/databag.go#L29-L34 |
10,704 | mndrix/ps | list.go | ForEach | func (self *list) ForEach(f func(interface{})) {
if self.IsNil() {
return
}
f(self.Head())
self.Tail().ForEach(f)
} | go | func (self *list) ForEach(f func(interface{})) {
if self.IsNil() {
return
}
f(self.Head())
self.Tail().ForEach(f)
} | [
"func",
"(",
"self",
"*",
"list",
")",
"ForEach",
"(",
"f",
"func",
"(",
"interface",
"{",
"}",
")",
")",
"{",
"if",
"self",
".",
"IsNil",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"f",
"(",
"self",
".",
"Head",
"(",
")",
")",
"\n",
"self",
".",
"Tail",
"(",
")",
".",
"ForEach",
"(",
"f",
")",
"\n",
"}"
] | // ForEach executes a callback for each value in the list | [
"ForEach",
"executes",
"a",
"callback",
"for",
"each",
"value",
"in",
"the",
"list"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/list.go#L80-L86 |
10,705 | mndrix/ps | list.go | Reverse | func (self *list) Reverse() List {
reversed := NewList()
self.ForEach(func(v interface{}) { reversed = reversed.Cons(v) })
return reversed
} | go | func (self *list) Reverse() List {
reversed := NewList()
self.ForEach(func(v interface{}) { reversed = reversed.Cons(v) })
return reversed
} | [
"func",
"(",
"self",
"*",
"list",
")",
"Reverse",
"(",
")",
"List",
"{",
"reversed",
":=",
"NewList",
"(",
")",
"\n",
"self",
".",
"ForEach",
"(",
"func",
"(",
"v",
"interface",
"{",
"}",
")",
"{",
"reversed",
"=",
"reversed",
".",
"Cons",
"(",
"v",
")",
"}",
")",
"\n",
"return",
"reversed",
"\n",
"}"
] | // Reverse returns a list with elements in opposite order as this list | [
"Reverse",
"returns",
"a",
"list",
"with",
"elements",
"in",
"opposite",
"order",
"as",
"this",
"list"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/list.go#L89-L93 |
10,706 | mndrix/ps | map.go | hashKey | func hashKey(key string) uint64 {
hash := offset64
for _, b := range bytesView(key) {
hash ^= uint64(b)
hash *= prime64
}
return hash
} | go | func hashKey(key string) uint64 {
hash := offset64
for _, b := range bytesView(key) {
hash ^= uint64(b)
hash *= prime64
}
return hash
} | [
"func",
"hashKey",
"(",
"key",
"string",
")",
"uint64",
"{",
"hash",
":=",
"offset64",
"\n\n",
"for",
"_",
",",
"b",
":=",
"range",
"bytesView",
"(",
"key",
")",
"{",
"hash",
"^=",
"uint64",
"(",
"b",
")",
"\n",
"hash",
"*=",
"prime64",
"\n",
"}",
"\n",
"return",
"hash",
"\n",
"}"
] | // hashKey returns a hash code for a given string | [
"hashKey",
"returns",
"a",
"hash",
"code",
"for",
"a",
"given",
"string"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L134-L142 |
10,707 | mndrix/ps | map.go | Set | func (self *tree) Set(key string, value interface{}) Map {
hash := hashKey(key)
return setLowLevel(self, hash, hash, key, value)
} | go | func (self *tree) Set(key string, value interface{}) Map {
hash := hashKey(key)
return setLowLevel(self, hash, hash, key, value)
} | [
"func",
"(",
"self",
"*",
"tree",
")",
"Set",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"Map",
"{",
"hash",
":=",
"hashKey",
"(",
"key",
")",
"\n",
"return",
"setLowLevel",
"(",
"self",
",",
"hash",
",",
"hash",
",",
"key",
",",
"value",
")",
"\n",
"}"
] | // Set returns a new map similar to this one but with key and value
// associated. If the key didn't exist, it's created; otherwise, the
// associated value is changed. | [
"Set",
"returns",
"a",
"new",
"map",
"similar",
"to",
"this",
"one",
"but",
"with",
"key",
"and",
"value",
"associated",
".",
"If",
"the",
"key",
"didn",
"t",
"exist",
"it",
"s",
"created",
";",
"otherwise",
"the",
"associated",
"value",
"is",
"changed",
"."
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L147-L150 |
10,708 | mndrix/ps | map.go | UnsafeMutableSet | func (self *tree) UnsafeMutableSet(key string, value interface{}) Map {
hash := hashKey(key)
return mutableSetLowLevel(self, hash, hash, key, value)
} | go | func (self *tree) UnsafeMutableSet(key string, value interface{}) Map {
hash := hashKey(key)
return mutableSetLowLevel(self, hash, hash, key, value)
} | [
"func",
"(",
"self",
"*",
"tree",
")",
"UnsafeMutableSet",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"Map",
"{",
"hash",
":=",
"hashKey",
"(",
"key",
")",
"\n",
"return",
"mutableSetLowLevel",
"(",
"self",
",",
"hash",
",",
"hash",
",",
"key",
",",
"value",
")",
"\n",
"}"
] | // UnsafeMutableSet is the in-place mutable version of Set. Only use if
// you are the only reference-holder of the Map. | [
"UnsafeMutableSet",
"is",
"the",
"in",
"-",
"place",
"mutable",
"version",
"of",
"Set",
".",
"Only",
"use",
"if",
"you",
"are",
"the",
"only",
"reference",
"-",
"holder",
"of",
"the",
"Map",
"."
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L187-L190 |
10,709 | mndrix/ps | map.go | recalculateCount | func recalculateCount(m *tree) {
count := 0
for _, t := range m.children {
count += t.Size()
}
m.count = count + 1 // add one to count ourself
} | go | func recalculateCount(m *tree) {
count := 0
for _, t := range m.children {
count += t.Size()
}
m.count = count + 1 // add one to count ourself
} | [
"func",
"recalculateCount",
"(",
"m",
"*",
"tree",
")",
"{",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"m",
".",
"children",
"{",
"count",
"+=",
"t",
".",
"Size",
"(",
")",
"\n",
"}",
"\n",
"m",
".",
"count",
"=",
"count",
"+",
"1",
"// add one to count ourself",
"\n",
"}"
] | // modifies a map by recalculating its key count based on the counts
// of its subtrees | [
"modifies",
"a",
"map",
"by",
"recalculating",
"its",
"key",
"count",
"based",
"on",
"the",
"counts",
"of",
"its",
"subtrees"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L226-L232 |
10,710 | mndrix/ps | map.go | deleteLeftmost | func (m *tree) deleteLeftmost() (*tree, *tree) {
if m.isLeaf() {
return m, nilMap
}
for i, t := range m.children {
if t != nilMap {
deleted, child := t.deleteLeftmost()
newMap := m.clone()
newMap.children[i] = child
recalculateCount(newMap)
return deleted, newMap
}
}
panic("Tree isn't a leaf but also had no children. How does that happen?")
} | go | func (m *tree) deleteLeftmost() (*tree, *tree) {
if m.isLeaf() {
return m, nilMap
}
for i, t := range m.children {
if t != nilMap {
deleted, child := t.deleteLeftmost()
newMap := m.clone()
newMap.children[i] = child
recalculateCount(newMap)
return deleted, newMap
}
}
panic("Tree isn't a leaf but also had no children. How does that happen?")
} | [
"func",
"(",
"m",
"*",
"tree",
")",
"deleteLeftmost",
"(",
")",
"(",
"*",
"tree",
",",
"*",
"tree",
")",
"{",
"if",
"m",
".",
"isLeaf",
"(",
")",
"{",
"return",
"m",
",",
"nilMap",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"t",
":=",
"range",
"m",
".",
"children",
"{",
"if",
"t",
"!=",
"nilMap",
"{",
"deleted",
",",
"child",
":=",
"t",
".",
"deleteLeftmost",
"(",
")",
"\n",
"newMap",
":=",
"m",
".",
"clone",
"(",
")",
"\n",
"newMap",
".",
"children",
"[",
"i",
"]",
"=",
"child",
"\n",
"recalculateCount",
"(",
"newMap",
")",
"\n",
"return",
"deleted",
",",
"newMap",
"\n",
"}",
"\n",
"}",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // delete the leftmost node in a tree returning the node that
// was deleted and the tree left over after its deletion | [
"delete",
"the",
"leftmost",
"node",
"in",
"a",
"tree",
"returning",
"the",
"node",
"that",
"was",
"deleted",
"and",
"the",
"tree",
"left",
"over",
"after",
"its",
"deletion"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L299-L314 |
10,711 | mndrix/ps | map.go | subtreeCount | func (m *tree) subtreeCount() int {
count := 0
for _, t := range m.children {
if t != nilMap {
count++
}
}
return count
} | go | func (m *tree) subtreeCount() int {
count := 0
for _, t := range m.children {
if t != nilMap {
count++
}
}
return count
} | [
"func",
"(",
"m",
"*",
"tree",
")",
"subtreeCount",
"(",
")",
"int",
"{",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"m",
".",
"children",
"{",
"if",
"t",
"!=",
"nilMap",
"{",
"count",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"count",
"\n",
"}"
] | // returns the number of child subtrees we have | [
"returns",
"the",
"number",
"of",
"child",
"subtrees",
"we",
"have"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L322-L330 |
10,712 | mndrix/ps | map.go | String | func (m *tree) String() string {
keys := m.Keys()
buf := bytes.NewBufferString("{")
for _, key := range keys {
val, _ := m.Lookup(key)
fmt.Fprintf(buf, "%s: %s, ", key, val)
}
fmt.Fprintf(buf, "}\n")
return buf.String()
} | go | func (m *tree) String() string {
keys := m.Keys()
buf := bytes.NewBufferString("{")
for _, key := range keys {
val, _ := m.Lookup(key)
fmt.Fprintf(buf, "%s: %s, ", key, val)
}
fmt.Fprintf(buf, "}\n")
return buf.String()
} | [
"func",
"(",
"m",
"*",
"tree",
")",
"String",
"(",
")",
"string",
"{",
"keys",
":=",
"m",
".",
"Keys",
"(",
")",
"\n",
"buf",
":=",
"bytes",
".",
"NewBufferString",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"val",
",",
"_",
":=",
"m",
".",
"Lookup",
"(",
"key",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\"",
",",
"key",
",",
"val",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // make it easier to display maps for debugging | [
"make",
"it",
"easier",
"to",
"display",
"maps",
"for",
"debugging"
] | 18e65badd6ab498ebf91777d2123a17d5f6b08b6 | https://github.com/mndrix/ps/blob/18e65badd6ab498ebf91777d2123a17d5f6b08b6/map.go#L382-L391 |
10,713 | osamingo/indigo | indigo.go | New | func New(enc Encoder, options ...func(*sonyflake.Settings)) *Generator {
if enc == nil {
enc = base58.MustNewEncoder(base58.StdSource())
}
s := sonyflake.Settings{}
for i := range options {
options[i](&s)
}
return &Generator{
sf: sonyflake.NewSonyflake(s),
enc: enc,
}
} | go | func New(enc Encoder, options ...func(*sonyflake.Settings)) *Generator {
if enc == nil {
enc = base58.MustNewEncoder(base58.StdSource())
}
s := sonyflake.Settings{}
for i := range options {
options[i](&s)
}
return &Generator{
sf: sonyflake.NewSonyflake(s),
enc: enc,
}
} | [
"func",
"New",
"(",
"enc",
"Encoder",
",",
"options",
"...",
"func",
"(",
"*",
"sonyflake",
".",
"Settings",
")",
")",
"*",
"Generator",
"{",
"if",
"enc",
"==",
"nil",
"{",
"enc",
"=",
"base58",
".",
"MustNewEncoder",
"(",
"base58",
".",
"StdSource",
"(",
")",
")",
"\n",
"}",
"\n",
"s",
":=",
"sonyflake",
".",
"Settings",
"{",
"}",
"\n",
"for",
"i",
":=",
"range",
"options",
"{",
"options",
"[",
"i",
"]",
"(",
"&",
"s",
")",
"\n",
"}",
"\n",
"return",
"&",
"Generator",
"{",
"sf",
":",
"sonyflake",
".",
"NewSonyflake",
"(",
"s",
")",
",",
"enc",
":",
"enc",
",",
"}",
"\n",
"}"
] | // New settings new a indigo.Generator. | [
"New",
"settings",
"new",
"a",
"indigo",
".",
"Generator",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L29-L41 |
10,714 | osamingo/indigo | indigo.go | StartTime | func StartTime(t time.Time) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.StartTime = t
}
} | go | func StartTime(t time.Time) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.StartTime = t
}
} | [
"func",
"StartTime",
"(",
"t",
"time",
".",
"Time",
")",
"func",
"(",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"return",
"func",
"(",
"s",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"s",
".",
"StartTime",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // StartTime is optional function for indigo.Generator. | [
"StartTime",
"is",
"optional",
"function",
"for",
"indigo",
".",
"Generator",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L44-L48 |
10,715 | osamingo/indigo | indigo.go | MachineID | func MachineID(f func() (uint16, error)) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.MachineID = f
}
} | go | func MachineID(f func() (uint16, error)) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.MachineID = f
}
} | [
"func",
"MachineID",
"(",
"f",
"func",
"(",
")",
"(",
"uint16",
",",
"error",
")",
")",
"func",
"(",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"return",
"func",
"(",
"s",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"s",
".",
"MachineID",
"=",
"f",
"\n",
"}",
"\n",
"}"
] | // MachineID is optional function for indigo.Generator. | [
"MachineID",
"is",
"optional",
"function",
"for",
"indigo",
".",
"Generator",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L51-L55 |
10,716 | osamingo/indigo | indigo.go | CheckMachineID | func CheckMachineID(f func(uint16) bool) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.CheckMachineID = f
}
} | go | func CheckMachineID(f func(uint16) bool) func(*sonyflake.Settings) {
return func(s *sonyflake.Settings) {
s.CheckMachineID = f
}
} | [
"func",
"CheckMachineID",
"(",
"f",
"func",
"(",
"uint16",
")",
"bool",
")",
"func",
"(",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"return",
"func",
"(",
"s",
"*",
"sonyflake",
".",
"Settings",
")",
"{",
"s",
".",
"CheckMachineID",
"=",
"f",
"\n",
"}",
"\n",
"}"
] | // CheckMachineID is optional function for indigo.Generator. | [
"CheckMachineID",
"is",
"optional",
"function",
"for",
"indigo",
".",
"Generator",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L58-L62 |
10,717 | osamingo/indigo | indigo.go | NextID | func (g *Generator) NextID() (string, error) {
n, err := g.sf.NextID()
if err != nil {
return "", err
}
return g.enc.Encode(n), nil
} | go | func (g *Generator) NextID() (string, error) {
n, err := g.sf.NextID()
if err != nil {
return "", err
}
return g.enc.Encode(n), nil
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"NextID",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"g",
".",
"sf",
".",
"NextID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"g",
".",
"enc",
".",
"Encode",
"(",
"n",
")",
",",
"nil",
"\n",
"}"
] | // NextID generates a next unique ID. | [
"NextID",
"generates",
"a",
"next",
"unique",
"ID",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L65-L71 |
10,718 | osamingo/indigo | indigo.go | Decompose | func (g *Generator) Decompose(id string) (map[string]uint64, error) {
b, err := g.enc.Decode(id)
if err != nil {
return nil, err
}
return sonyflake.Decompose(b), nil
} | go | func (g *Generator) Decompose(id string) (map[string]uint64, error) {
b, err := g.enc.Decode(id)
if err != nil {
return nil, err
}
return sonyflake.Decompose(b), nil
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"Decompose",
"(",
"id",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"uint64",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"g",
".",
"enc",
".",
"Decode",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"sonyflake",
".",
"Decompose",
"(",
"b",
")",
",",
"nil",
"\n",
"}"
] | // Decompose returns a set of sonyflake ID parts. | [
"Decompose",
"returns",
"a",
"set",
"of",
"sonyflake",
"ID",
"parts",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/indigo.go#L74-L80 |
10,719 | osamingo/indigo | base58/base58.go | MustNewEncoder | func MustNewEncoder(source string) *Encoder {
enc, err := NewEncoder(source)
if err != nil {
panic(err)
}
return enc
} | go | func MustNewEncoder(source string) *Encoder {
enc, err := NewEncoder(source)
if err != nil {
panic(err)
}
return enc
} | [
"func",
"MustNewEncoder",
"(",
"source",
"string",
")",
"*",
"Encoder",
"{",
"enc",
",",
"err",
":=",
"NewEncoder",
"(",
"source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"enc",
"\n",
"}"
] | // MustNewEncoder returns new base58.Encoder. | [
"MustNewEncoder",
"returns",
"new",
"base58",
".",
"Encoder",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/base58/base58.go#L23-L29 |
10,720 | osamingo/indigo | base58/base58.go | NewEncoder | func NewEncoder(source string) (*Encoder, error) {
if len(source) != 58 {
return nil, errors.New("base58: encoding source is not 58-bytes long")
}
enc := new(Encoder)
for i := range enc.decodeMap {
enc.decodeMap[i] = -1
}
for i := range source {
enc.encode[i] = source[i]
enc.decodeMap[enc.encode[i]] = i
}
return enc, nil
} | go | func NewEncoder(source string) (*Encoder, error) {
if len(source) != 58 {
return nil, errors.New("base58: encoding source is not 58-bytes long")
}
enc := new(Encoder)
for i := range enc.decodeMap {
enc.decodeMap[i] = -1
}
for i := range source {
enc.encode[i] = source[i]
enc.decodeMap[enc.encode[i]] = i
}
return enc, nil
} | [
"func",
"NewEncoder",
"(",
"source",
"string",
")",
"(",
"*",
"Encoder",
",",
"error",
")",
"{",
"if",
"len",
"(",
"source",
")",
"!=",
"58",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"enc",
":=",
"new",
"(",
"Encoder",
")",
"\n\n",
"for",
"i",
":=",
"range",
"enc",
".",
"decodeMap",
"{",
"enc",
".",
"decodeMap",
"[",
"i",
"]",
"=",
"-",
"1",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"source",
"{",
"enc",
".",
"encode",
"[",
"i",
"]",
"=",
"source",
"[",
"i",
"]",
"\n",
"enc",
".",
"decodeMap",
"[",
"enc",
".",
"encode",
"[",
"i",
"]",
"]",
"=",
"i",
"\n",
"}",
"\n\n",
"return",
"enc",
",",
"nil",
"\n",
"}"
] | // NewEncoder returns new base58.Encoder. | [
"NewEncoder",
"returns",
"new",
"base58",
".",
"Encoder",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/base58/base58.go#L32-L50 |
10,721 | osamingo/indigo | base58/base58.go | Encode | func (enc *Encoder) Encode(id uint64) string {
if id == 0 {
return string(enc.encode[:1])
}
bin := make([]byte, 0, binary.MaxVarintLen64)
for id > 0 {
bin = append(bin, enc.encode[id%58])
id /= 58
}
for i, j := 0, len(bin)-1; i < j; i, j = i+1, j-1 {
bin[i], bin[j] = bin[j], bin[i]
}
return string(bin)
} | go | func (enc *Encoder) Encode(id uint64) string {
if id == 0 {
return string(enc.encode[:1])
}
bin := make([]byte, 0, binary.MaxVarintLen64)
for id > 0 {
bin = append(bin, enc.encode[id%58])
id /= 58
}
for i, j := 0, len(bin)-1; i < j; i, j = i+1, j-1 {
bin[i], bin[j] = bin[j], bin[i]
}
return string(bin)
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"Encode",
"(",
"id",
"uint64",
")",
"string",
"{",
"if",
"id",
"==",
"0",
"{",
"return",
"string",
"(",
"enc",
".",
"encode",
"[",
":",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"bin",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"binary",
".",
"MaxVarintLen64",
")",
"\n",
"for",
"id",
">",
"0",
"{",
"bin",
"=",
"append",
"(",
"bin",
",",
"enc",
".",
"encode",
"[",
"id",
"%",
"58",
"]",
")",
"\n",
"id",
"/=",
"58",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"j",
":=",
"0",
",",
"len",
"(",
"bin",
")",
"-",
"1",
";",
"i",
"<",
"j",
";",
"i",
",",
"j",
"=",
"i",
"+",
"1",
",",
"j",
"-",
"1",
"{",
"bin",
"[",
"i",
"]",
",",
"bin",
"[",
"j",
"]",
"=",
"bin",
"[",
"j",
"]",
",",
"bin",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"bin",
")",
"\n",
"}"
] | // Encode returns encoded string by Base58. | [
"Encode",
"returns",
"encoded",
"string",
"by",
"Base58",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/base58/base58.go#L53-L70 |
10,722 | osamingo/indigo | base58/base58.go | Decode | func (enc *Encoder) Decode(id string) (uint64, error) {
if id == "" {
return 0, errors.New("base58: id should not be empty")
}
var n uint64
for i := range id {
u := enc.decodeMap[id[i]]
if u < 0 {
return 0, errors.New("base58: invalid character - " + string(id[i]))
}
n = n*58 + uint64(u)
}
return n, nil
} | go | func (enc *Encoder) Decode(id string) (uint64, error) {
if id == "" {
return 0, errors.New("base58: id should not be empty")
}
var n uint64
for i := range id {
u := enc.decodeMap[id[i]]
if u < 0 {
return 0, errors.New("base58: invalid character - " + string(id[i]))
}
n = n*58 + uint64(u)
}
return n, nil
} | [
"func",
"(",
"enc",
"*",
"Encoder",
")",
"Decode",
"(",
"id",
"string",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"if",
"id",
"==",
"\"",
"\"",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"n",
"uint64",
"\n",
"for",
"i",
":=",
"range",
"id",
"{",
"u",
":=",
"enc",
".",
"decodeMap",
"[",
"id",
"[",
"i",
"]",
"]",
"\n",
"if",
"u",
"<",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"string",
"(",
"id",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"n",
"=",
"n",
"*",
"58",
"+",
"uint64",
"(",
"u",
")",
"\n",
"}",
"\n\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // Decode returns decoded unsigned int64 by Base58. | [
"Decode",
"returns",
"decoded",
"unsigned",
"int64",
"by",
"Base58",
"."
] | 2d5843fcd458e87b90758a69b3659f78920f2c11 | https://github.com/osamingo/indigo/blob/2d5843fcd458e87b90758a69b3659f78920f2c11/base58/base58.go#L73-L89 |
10,723 | bitrise-io/stepman | stepman/paths.go | GetStepCacheDirPath | func GetStepCacheDirPath(route SteplibRoute, id, version string) string {
return path.Join(GetCacheBaseDir(route), id, version)
} | go | func GetStepCacheDirPath(route SteplibRoute, id, version string) string {
return path.Join(GetCacheBaseDir(route), id, version)
} | [
"func",
"GetStepCacheDirPath",
"(",
"route",
"SteplibRoute",
",",
"id",
",",
"version",
"string",
")",
"string",
"{",
"return",
"path",
".",
"Join",
"(",
"GetCacheBaseDir",
"(",
"route",
")",
",",
"id",
",",
"version",
")",
"\n",
"}"
] | // GetStepCacheDirPath ...
// Step's Cache dir path, where it's code lives. | [
"GetStepCacheDirPath",
"...",
"Step",
"s",
"Cache",
"dir",
"path",
"where",
"it",
"s",
"code",
"lives",
"."
] | 8cd3398fab6c211eef53502b65ec7ad5510f556a | https://github.com/bitrise-io/stepman/blob/8cd3398fab6c211eef53502b65ec7ad5510f556a/stepman/paths.go#L221-L223 |
10,724 | dcos/dcos-metrics | config.go | newConfig | func newConfig() Config {
return Config{
Collector: CollectorConfig{
HTTPProfiler: false,
Framework: &framework.Collector{
ListenEndpointFlag: "127.0.0.1:8124",
RecordInputLogFlag: false,
InputLimitAmountKBytesFlag: 20480,
InputLimitPeriodFlag: 60,
},
MesosAgent: &mesosAgent.Collector{
PollPeriod: time.Duration(60 * time.Second),
Port: 5051,
RequestProtocol: "http",
RequestTimeout: time.Duration(5 * time.Second),
},
Node: &node.Collector{
PollPeriod: time.Duration(60 * time.Second),
},
},
Producers: ProducersConfig{
HTTPProducerConfig: httpProducer.Config{
CacheExpiry: time.Duration(120 * time.Second),
Port: 9000,
},
PrometheusProducerConfig: promProducer.Config{
CacheExpiry: time.Duration(60 * time.Second),
Port: 9273,
},
},
LogLevel: "info",
}
} | go | func newConfig() Config {
return Config{
Collector: CollectorConfig{
HTTPProfiler: false,
Framework: &framework.Collector{
ListenEndpointFlag: "127.0.0.1:8124",
RecordInputLogFlag: false,
InputLimitAmountKBytesFlag: 20480,
InputLimitPeriodFlag: 60,
},
MesosAgent: &mesosAgent.Collector{
PollPeriod: time.Duration(60 * time.Second),
Port: 5051,
RequestProtocol: "http",
RequestTimeout: time.Duration(5 * time.Second),
},
Node: &node.Collector{
PollPeriod: time.Duration(60 * time.Second),
},
},
Producers: ProducersConfig{
HTTPProducerConfig: httpProducer.Config{
CacheExpiry: time.Duration(120 * time.Second),
Port: 9000,
},
PrometheusProducerConfig: promProducer.Config{
CacheExpiry: time.Duration(60 * time.Second),
Port: 9273,
},
},
LogLevel: "info",
}
} | [
"func",
"newConfig",
"(",
")",
"Config",
"{",
"return",
"Config",
"{",
"Collector",
":",
"CollectorConfig",
"{",
"HTTPProfiler",
":",
"false",
",",
"Framework",
":",
"&",
"framework",
".",
"Collector",
"{",
"ListenEndpointFlag",
":",
"\"",
"\"",
",",
"RecordInputLogFlag",
":",
"false",
",",
"InputLimitAmountKBytesFlag",
":",
"20480",
",",
"InputLimitPeriodFlag",
":",
"60",
",",
"}",
",",
"MesosAgent",
":",
"&",
"mesosAgent",
".",
"Collector",
"{",
"PollPeriod",
":",
"time",
".",
"Duration",
"(",
"60",
"*",
"time",
".",
"Second",
")",
",",
"Port",
":",
"5051",
",",
"RequestProtocol",
":",
"\"",
"\"",
",",
"RequestTimeout",
":",
"time",
".",
"Duration",
"(",
"5",
"*",
"time",
".",
"Second",
")",
",",
"}",
",",
"Node",
":",
"&",
"node",
".",
"Collector",
"{",
"PollPeriod",
":",
"time",
".",
"Duration",
"(",
"60",
"*",
"time",
".",
"Second",
")",
",",
"}",
",",
"}",
",",
"Producers",
":",
"ProducersConfig",
"{",
"HTTPProducerConfig",
":",
"httpProducer",
".",
"Config",
"{",
"CacheExpiry",
":",
"time",
".",
"Duration",
"(",
"120",
"*",
"time",
".",
"Second",
")",
",",
"Port",
":",
"9000",
",",
"}",
",",
"PrometheusProducerConfig",
":",
"promProducer",
".",
"Config",
"{",
"CacheExpiry",
":",
"time",
".",
"Duration",
"(",
"60",
"*",
"time",
".",
"Second",
")",
",",
"Port",
":",
"9273",
",",
"}",
",",
"}",
",",
"LogLevel",
":",
"\"",
"\"",
",",
"}",
"\n",
"}"
] | // newConfig establishes our default, base configuration. | [
"newConfig",
"establishes",
"our",
"default",
"base",
"configuration",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/config.go#L180-L212 |
10,725 | dcos/dcos-metrics | producers/http/http.go | Run | func (p *producerImpl) Run() error {
httpLog.Info("Starting HTTP producer garbage collection service")
go p.janitor()
go func() {
httpLog.Debug("HTTP producer listening for incoming messages on metricsChan")
for {
// read messages off the channel,
// and give them a unique name in the store
message := <-p.metricsChan
httpLog.Debugf("Received message '%+v' with timestamp %s",
message, time.Unix(message.Timestamp, 0).Format(time.RFC3339))
var name string
switch message.Name {
case producers.NodeMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.MesosID)
case producers.ContainerMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.ContainerID)
case producers.AppMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.ContainerID)
}
for _, d := range message.Datapoints {
p.writeObjectToStore(d, message, name)
}
}
}()
r := newRouter(p)
// If a listener was provided directly in config, use it.
if p.config.Listener != nil {
httpLog.Infof("http producer serving requests on: %s", p.config.Listener.Addr().String())
return http.Serve(p.config.Listener, r)
}
// If a listener from systemd is available, use it.
listeners, err := getListener()
if err != nil {
return fmt.Errorf("Unable to get listeners: %s", err)
}
if len(listeners) == 1 {
httpLog.Infof("http producer serving requests on systemd socket: %s", listeners[0].Addr().String())
return http.Serve(listeners[0], r)
}
// Listen on the configured TCP port.
httpLog.Infof("http producer serving requests on tcp socket: %s", net.JoinHostPort(p.config.IP, strconv.Itoa(p.config.Port)))
return http.ListenAndServe(fmt.Sprintf("%s:%d", p.config.IP, p.config.Port), r)
} | go | func (p *producerImpl) Run() error {
httpLog.Info("Starting HTTP producer garbage collection service")
go p.janitor()
go func() {
httpLog.Debug("HTTP producer listening for incoming messages on metricsChan")
for {
// read messages off the channel,
// and give them a unique name in the store
message := <-p.metricsChan
httpLog.Debugf("Received message '%+v' with timestamp %s",
message, time.Unix(message.Timestamp, 0).Format(time.RFC3339))
var name string
switch message.Name {
case producers.NodeMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.MesosID)
case producers.ContainerMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.ContainerID)
case producers.AppMetricPrefix:
name = joinMetricName(message.Name, message.Dimensions.ContainerID)
}
for _, d := range message.Datapoints {
p.writeObjectToStore(d, message, name)
}
}
}()
r := newRouter(p)
// If a listener was provided directly in config, use it.
if p.config.Listener != nil {
httpLog.Infof("http producer serving requests on: %s", p.config.Listener.Addr().String())
return http.Serve(p.config.Listener, r)
}
// If a listener from systemd is available, use it.
listeners, err := getListener()
if err != nil {
return fmt.Errorf("Unable to get listeners: %s", err)
}
if len(listeners) == 1 {
httpLog.Infof("http producer serving requests on systemd socket: %s", listeners[0].Addr().String())
return http.Serve(listeners[0], r)
}
// Listen on the configured TCP port.
httpLog.Infof("http producer serving requests on tcp socket: %s", net.JoinHostPort(p.config.IP, strconv.Itoa(p.config.Port)))
return http.ListenAndServe(fmt.Sprintf("%s:%d", p.config.IP, p.config.Port), r)
} | [
"func",
"(",
"p",
"*",
"producerImpl",
")",
"Run",
"(",
")",
"error",
"{",
"httpLog",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"go",
"p",
".",
"janitor",
"(",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"httpLog",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"for",
"{",
"// read messages off the channel,",
"// and give them a unique name in the store",
"message",
":=",
"<-",
"p",
".",
"metricsChan",
"\n",
"httpLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"message",
",",
"time",
".",
"Unix",
"(",
"message",
".",
"Timestamp",
",",
"0",
")",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n\n",
"var",
"name",
"string",
"\n",
"switch",
"message",
".",
"Name",
"{",
"case",
"producers",
".",
"NodeMetricPrefix",
":",
"name",
"=",
"joinMetricName",
"(",
"message",
".",
"Name",
",",
"message",
".",
"Dimensions",
".",
"MesosID",
")",
"\n\n",
"case",
"producers",
".",
"ContainerMetricPrefix",
":",
"name",
"=",
"joinMetricName",
"(",
"message",
".",
"Name",
",",
"message",
".",
"Dimensions",
".",
"ContainerID",
")",
"\n\n",
"case",
"producers",
".",
"AppMetricPrefix",
":",
"name",
"=",
"joinMetricName",
"(",
"message",
".",
"Name",
",",
"message",
".",
"Dimensions",
".",
"ContainerID",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"d",
":=",
"range",
"message",
".",
"Datapoints",
"{",
"p",
".",
"writeObjectToStore",
"(",
"d",
",",
"message",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"r",
":=",
"newRouter",
"(",
"p",
")",
"\n\n",
"// If a listener was provided directly in config, use it.",
"if",
"p",
".",
"config",
".",
"Listener",
"!=",
"nil",
"{",
"httpLog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"p",
".",
"config",
".",
"Listener",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"http",
".",
"Serve",
"(",
"p",
".",
"config",
".",
"Listener",
",",
"r",
")",
"\n",
"}",
"\n\n",
"// If a listener from systemd is available, use it.",
"listeners",
",",
"err",
":=",
"getListener",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"listeners",
")",
"==",
"1",
"{",
"httpLog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"listeners",
"[",
"0",
"]",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"return",
"http",
".",
"Serve",
"(",
"listeners",
"[",
"0",
"]",
",",
"r",
")",
"\n",
"}",
"\n\n",
"// Listen on the configured TCP port.",
"httpLog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"net",
".",
"JoinHostPort",
"(",
"p",
".",
"config",
".",
"IP",
",",
"strconv",
".",
"Itoa",
"(",
"p",
".",
"config",
".",
"Port",
")",
")",
")",
"\n",
"return",
"http",
".",
"ListenAndServe",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"config",
".",
"IP",
",",
"p",
".",
"config",
".",
"Port",
")",
",",
"r",
")",
"\n",
"}"
] | // Run a HTTP server and serve the various metrics API endpoints.
// This function should be run in its own goroutine. | [
"Run",
"a",
"HTTP",
"server",
"and",
"serve",
"the",
"various",
"metrics",
"API",
"endpoints",
".",
"This",
"function",
"should",
"be",
"run",
"in",
"its",
"own",
"goroutine",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/http/http.go#L65-L117 |
10,726 | dcos/dcos-metrics | producers/http/http.go | writeObjectToStore | func (p *producerImpl) writeObjectToStore(d producers.Datapoint, m producers.MetricsMessage, prefix string) {
newMessage := producers.MetricsMessage{
Name: m.Name,
Datapoints: []producers.Datapoint{d},
Dimensions: m.Dimensions,
Timestamp: m.Timestamp,
}
// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag
qualifiedName := joinMetricName(prefix, d.Name)
for _, pair := range prodHelpers.SortTags(d.Tags) {
k, v := pair[0], pair[1]
// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0
serializedTag := fmt.Sprintf("#%s:%s", k, v)
qualifiedName = joinMetricName(qualifiedName, serializedTag)
}
httpLog.Debugf("Setting store object '%s' with timestamp %s",
qualifiedName, time.Unix(newMessage.Timestamp, 0).Format(time.RFC3339))
p.store.Set(qualifiedName, newMessage)
} | go | func (p *producerImpl) writeObjectToStore(d producers.Datapoint, m producers.MetricsMessage, prefix string) {
newMessage := producers.MetricsMessage{
Name: m.Name,
Datapoints: []producers.Datapoint{d},
Dimensions: m.Dimensions,
Timestamp: m.Timestamp,
}
// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag
qualifiedName := joinMetricName(prefix, d.Name)
for _, pair := range prodHelpers.SortTags(d.Tags) {
k, v := pair[0], pair[1]
// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0
serializedTag := fmt.Sprintf("#%s:%s", k, v)
qualifiedName = joinMetricName(qualifiedName, serializedTag)
}
httpLog.Debugf("Setting store object '%s' with timestamp %s",
qualifiedName, time.Unix(newMessage.Timestamp, 0).Format(time.RFC3339))
p.store.Set(qualifiedName, newMessage)
} | [
"func",
"(",
"p",
"*",
"producerImpl",
")",
"writeObjectToStore",
"(",
"d",
"producers",
".",
"Datapoint",
",",
"m",
"producers",
".",
"MetricsMessage",
",",
"prefix",
"string",
")",
"{",
"newMessage",
":=",
"producers",
".",
"MetricsMessage",
"{",
"Name",
":",
"m",
".",
"Name",
",",
"Datapoints",
":",
"[",
"]",
"producers",
".",
"Datapoint",
"{",
"d",
"}",
",",
"Dimensions",
":",
"m",
".",
"Dimensions",
",",
"Timestamp",
":",
"m",
".",
"Timestamp",
",",
"}",
"\n",
"// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag",
"qualifiedName",
":=",
"joinMetricName",
"(",
"prefix",
",",
"d",
".",
"Name",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"prodHelpers",
".",
"SortTags",
"(",
"d",
".",
"Tags",
")",
"{",
"k",
",",
"v",
":=",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
"\n",
"// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0",
"serializedTag",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"qualifiedName",
"=",
"joinMetricName",
"(",
"qualifiedName",
",",
"serializedTag",
")",
"\n",
"}",
"\n",
"httpLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"qualifiedName",
",",
"time",
".",
"Unix",
"(",
"newMessage",
".",
"Timestamp",
",",
"0",
")",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"p",
".",
"store",
".",
"Set",
"(",
"qualifiedName",
",",
"newMessage",
")",
"\n",
"}"
] | // writeObjectToStore writes a prefixed datapoint into the store. | [
"writeObjectToStore",
"writes",
"a",
"prefixed",
"datapoint",
"into",
"the",
"store",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/http/http.go#L120-L138 |
10,727 | dcos/dcos-metrics | producers/http/http.go | janitor | func (p *producerImpl) janitor() {
ticker := time.NewTicker(p.janitorRunInterval)
for {
select {
case _ = <-ticker.C:
for k, v := range p.store.Objects() {
o := v.(producers.MetricsMessage)
age := time.Now().Sub(time.Unix(o.Timestamp, 0))
if age > p.config.CacheExpiry {
httpLog.Debugf("Removing stale object %s; last updated %d seconds ago", k, age/time.Second)
p.store.Delete(k)
}
}
}
}
} | go | func (p *producerImpl) janitor() {
ticker := time.NewTicker(p.janitorRunInterval)
for {
select {
case _ = <-ticker.C:
for k, v := range p.store.Objects() {
o := v.(producers.MetricsMessage)
age := time.Now().Sub(time.Unix(o.Timestamp, 0))
if age > p.config.CacheExpiry {
httpLog.Debugf("Removing stale object %s; last updated %d seconds ago", k, age/time.Second)
p.store.Delete(k)
}
}
}
}
} | [
"func",
"(",
"p",
"*",
"producerImpl",
")",
"janitor",
"(",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"p",
".",
"janitorRunInterval",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"_",
"=",
"<-",
"ticker",
".",
"C",
":",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"store",
".",
"Objects",
"(",
")",
"{",
"o",
":=",
"v",
".",
"(",
"producers",
".",
"MetricsMessage",
")",
"\n\n",
"age",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"time",
".",
"Unix",
"(",
"o",
".",
"Timestamp",
",",
"0",
")",
")",
"\n",
"if",
"age",
">",
"p",
".",
"config",
".",
"CacheExpiry",
"{",
"httpLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"k",
",",
"age",
"/",
"time",
".",
"Second",
")",
"\n",
"p",
".",
"store",
".",
"Delete",
"(",
"k",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // janitor analyzes the objects in the store and removes stale objects. An
// object is considered stale when the top-level timestamp of its MetricsMessage
// has exceeded the CacheExpiry, which is calculated as a multiple of the
// collector's polling period. This function should be run in its own goroutine. | [
"janitor",
"analyzes",
"the",
"objects",
"in",
"the",
"store",
"and",
"removes",
"stale",
"objects",
".",
"An",
"object",
"is",
"considered",
"stale",
"when",
"the",
"top",
"-",
"level",
"timestamp",
"of",
"its",
"MetricsMessage",
"has",
"exceeded",
"the",
"CacheExpiry",
"which",
"is",
"calculated",
"as",
"a",
"multiple",
"of",
"the",
"collector",
"s",
"polling",
"period",
".",
"This",
"function",
"should",
"be",
"run",
"in",
"its",
"own",
"goroutine",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/http/http.go#L149-L165 |
10,728 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | Get | func (ctr *ContainerTaskRels) Get(containerID string) *TaskInfo {
ctr.Lock()
defer ctr.Unlock()
return ctr.rels[containerID]
} | go | func (ctr *ContainerTaskRels) Get(containerID string) *TaskInfo {
ctr.Lock()
defer ctr.Unlock()
return ctr.rels[containerID]
} | [
"func",
"(",
"ctr",
"*",
"ContainerTaskRels",
")",
"Get",
"(",
"containerID",
"string",
")",
"*",
"TaskInfo",
"{",
"ctr",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ctr",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ctr",
".",
"rels",
"[",
"containerID",
"]",
"\n",
"}"
] | // Get is a utility method which handles the mutex lock and abstracts the inner
// map in ContainerTaskRels away. If no task info is available for the supplied
// containerID, returns nil. | [
"Get",
"is",
"a",
"utility",
"method",
"which",
"handles",
"the",
"mutex",
"lock",
"and",
"abstracts",
"the",
"inner",
"map",
"in",
"ContainerTaskRels",
"away",
".",
"If",
"no",
"task",
"info",
"is",
"available",
"for",
"the",
"supplied",
"containerID",
"returns",
"nil",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L89-L93 |
10,729 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | Set | func (ctr *ContainerTaskRels) Set(containerID string, info *TaskInfo) {
ctr.Lock()
defer ctr.Unlock()
ctr.rels[containerID] = info
} | go | func (ctr *ContainerTaskRels) Set(containerID string, info *TaskInfo) {
ctr.Lock()
defer ctr.Unlock()
ctr.rels[containerID] = info
} | [
"func",
"(",
"ctr",
"*",
"ContainerTaskRels",
")",
"Set",
"(",
"containerID",
"string",
",",
"info",
"*",
"TaskInfo",
")",
"{",
"ctr",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ctr",
".",
"Unlock",
"(",
")",
"\n",
"ctr",
".",
"rels",
"[",
"containerID",
"]",
"=",
"info",
"\n",
"}"
] | // Set adds or updates an entry to ContainerTaskRels and, if necessary,
// initiates the inner map. It is only currently used in tests. | [
"Set",
"adds",
"or",
"updates",
"an",
"entry",
"to",
"ContainerTaskRels",
"and",
"if",
"necessary",
"initiates",
"the",
"inner",
"map",
".",
"It",
"is",
"only",
"currently",
"used",
"in",
"tests",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L97-L101 |
10,730 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | RunPoller | func (c *Collector) RunPoller() {
for {
c.pollMesosAgent()
for _, m := range c.metricsMessages() {
c.log.Debugf("Sending container metrics to metric chan:\n%+v", m)
c.metricsChan <- m
}
time.Sleep(c.PollPeriod)
}
} | go | func (c *Collector) RunPoller() {
for {
c.pollMesosAgent()
for _, m := range c.metricsMessages() {
c.log.Debugf("Sending container metrics to metric chan:\n%+v", m)
c.metricsChan <- m
}
time.Sleep(c.PollPeriod)
}
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"RunPoller",
"(",
")",
"{",
"for",
"{",
"c",
".",
"pollMesosAgent",
"(",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"c",
".",
"metricsMessages",
"(",
")",
"{",
"c",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"m",
")",
"\n",
"c",
".",
"metricsChan",
"<-",
"m",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"c",
".",
"PollPeriod",
")",
"\n",
"}",
"\n",
"}"
] | // RunPoller continually polls the agent on a set interval. This should be run in its own goroutine. | [
"RunPoller",
"continually",
"polls",
"the",
"agent",
"on",
"a",
"set",
"interval",
".",
"This",
"should",
"be",
"run",
"in",
"its",
"own",
"goroutine",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L136-L145 |
10,731 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | getFrameworkInfoByFrameworkID | func getFrameworkInfoByFrameworkID(frameworkID string, frameworks []frameworkInfo) *frameworkInfo {
for _, framework := range frameworks {
if framework.ID == frameworkID {
return &framework
}
}
return nil
} | go | func getFrameworkInfoByFrameworkID(frameworkID string, frameworks []frameworkInfo) *frameworkInfo {
for _, framework := range frameworks {
if framework.ID == frameworkID {
return &framework
}
}
return nil
} | [
"func",
"getFrameworkInfoByFrameworkID",
"(",
"frameworkID",
"string",
",",
"frameworks",
"[",
"]",
"frameworkInfo",
")",
"*",
"frameworkInfo",
"{",
"for",
"_",
",",
"framework",
":=",
"range",
"frameworks",
"{",
"if",
"framework",
".",
"ID",
"==",
"frameworkID",
"{",
"return",
"&",
"framework",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // getFrameworkInfoByFrameworkID returns the FrameworkInfo struct given its ID. | [
"getFrameworkInfoByFrameworkID",
"returns",
"the",
"FrameworkInfo",
"struct",
"given",
"its",
"ID",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L233-L240 |
10,732 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | getExecutorInfoByExecutorID | func getExecutorInfoByExecutorID(executorID string, executors []executorInfo) *executorInfo {
for _, executor := range executors {
if executor.ID == executorID {
return &executor
}
}
return nil
} | go | func getExecutorInfoByExecutorID(executorID string, executors []executorInfo) *executorInfo {
for _, executor := range executors {
if executor.ID == executorID {
return &executor
}
}
return nil
} | [
"func",
"getExecutorInfoByExecutorID",
"(",
"executorID",
"string",
",",
"executors",
"[",
"]",
"executorInfo",
")",
"*",
"executorInfo",
"{",
"for",
"_",
",",
"executor",
":=",
"range",
"executors",
"{",
"if",
"executor",
".",
"ID",
"==",
"executorID",
"{",
"return",
"&",
"executor",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // getExecutorInfoByExecutorID returns the executorInfo struct given its ID. | [
"getExecutorInfoByExecutorID",
"returns",
"the",
"executorInfo",
"struct",
"given",
"its",
"ID",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L243-L250 |
10,733 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | getTaskInfoByContainerID | func getTaskInfoByContainerID(containerID string, tasks []TaskInfo) *TaskInfo {
for _, task := range tasks {
if len(task.Statuses) > 0 && task.Statuses[0].ContainerStatusInfo.ID.Value == containerID {
return &task
}
}
return nil
} | go | func getTaskInfoByContainerID(containerID string, tasks []TaskInfo) *TaskInfo {
for _, task := range tasks {
if len(task.Statuses) > 0 && task.Statuses[0].ContainerStatusInfo.ID.Value == containerID {
return &task
}
}
return nil
} | [
"func",
"getTaskInfoByContainerID",
"(",
"containerID",
"string",
",",
"tasks",
"[",
"]",
"TaskInfo",
")",
"*",
"TaskInfo",
"{",
"for",
"_",
",",
"task",
":=",
"range",
"tasks",
"{",
"if",
"len",
"(",
"task",
".",
"Statuses",
")",
">",
"0",
"&&",
"task",
".",
"Statuses",
"[",
"0",
"]",
".",
"ContainerStatusInfo",
".",
"ID",
".",
"Value",
"==",
"containerID",
"{",
"return",
"&",
"task",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // getTaskInfoByContainerID returns the TaskInfo struct matching the given cID. | [
"getTaskInfoByContainerID",
"returns",
"the",
"TaskInfo",
"struct",
"matching",
"the",
"given",
"cID",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L253-L260 |
10,734 | dcos/dcos-metrics | collectors/mesos/agent/agent.go | getLabelsByContainerID | func getLabelsByContainerID(containerID string, frameworks []frameworkInfo, log *logrus.Entry) map[string]string {
labels := map[string]string{}
for _, framework := range frameworks {
log.Debugf("Attempting to add labels to %v framework", framework)
for _, executor := range framework.Executors {
log.Debugf("Found executor %v for framework %v", framework, executor)
if executor.Container == containerID {
log.Debugf("ContainerID %v for executor %v is a match, adding labels", containerID, executor)
for _, pair := range executor.Labels {
if _, inSlice := cosmosLabels[pair.Key]; inSlice {
continue
}
if len(pair.Value) > maxLabelLength {
log.Warnf("Label %s is longer than %d chars; discarding label", pair.Key, maxLabelLength)
log.Debugf("Discarded label value: %s", pair.Value)
continue
}
log.Debugf("Adding label for containerID %v: %v = %+v", containerID, pair.Key, pair.Value)
labels[pair.Key] = pair.Value
}
return labels
}
}
}
return labels
} | go | func getLabelsByContainerID(containerID string, frameworks []frameworkInfo, log *logrus.Entry) map[string]string {
labels := map[string]string{}
for _, framework := range frameworks {
log.Debugf("Attempting to add labels to %v framework", framework)
for _, executor := range framework.Executors {
log.Debugf("Found executor %v for framework %v", framework, executor)
if executor.Container == containerID {
log.Debugf("ContainerID %v for executor %v is a match, adding labels", containerID, executor)
for _, pair := range executor.Labels {
if _, inSlice := cosmosLabels[pair.Key]; inSlice {
continue
}
if len(pair.Value) > maxLabelLength {
log.Warnf("Label %s is longer than %d chars; discarding label", pair.Key, maxLabelLength)
log.Debugf("Discarded label value: %s", pair.Value)
continue
}
log.Debugf("Adding label for containerID %v: %v = %+v", containerID, pair.Key, pair.Value)
labels[pair.Key] = pair.Value
}
return labels
}
}
}
return labels
} | [
"func",
"getLabelsByContainerID",
"(",
"containerID",
"string",
",",
"frameworks",
"[",
"]",
"frameworkInfo",
",",
"log",
"*",
"logrus",
".",
"Entry",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"labels",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"framework",
":=",
"range",
"frameworks",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"framework",
")",
"\n",
"for",
"_",
",",
"executor",
":=",
"range",
"framework",
".",
"Executors",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"framework",
",",
"executor",
")",
"\n",
"if",
"executor",
".",
"Container",
"==",
"containerID",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"containerID",
",",
"executor",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"executor",
".",
"Labels",
"{",
"if",
"_",
",",
"inSlice",
":=",
"cosmosLabels",
"[",
"pair",
".",
"Key",
"]",
";",
"inSlice",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"pair",
".",
"Value",
")",
">",
"maxLabelLength",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"pair",
".",
"Key",
",",
"maxLabelLength",
")",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"pair",
".",
"Value",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"containerID",
",",
"pair",
".",
"Key",
",",
"pair",
".",
"Value",
")",
"\n",
"labels",
"[",
"pair",
".",
"Key",
"]",
"=",
"pair",
".",
"Value",
"\n",
"}",
"\n",
"return",
"labels",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"labels",
"\n",
"}"
] | // getLabelsByContainerID returns a map of labels, as specified by the framework
// that created the executor. In the case of Marathon, the framework allows the
// user to specify their own arbitrary labels per application. | [
"getLabelsByContainerID",
"returns",
"a",
"map",
"of",
"labels",
"as",
"specified",
"by",
"the",
"framework",
"that",
"created",
"the",
"executor",
".",
"In",
"the",
"case",
"of",
"Marathon",
"the",
"framework",
"allows",
"the",
"user",
"to",
"specify",
"their",
"own",
"arbitrary",
"labels",
"per",
"application",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/agent.go#L265-L290 |
10,735 | dcos/dcos-metrics | plugins/stdout/stdout.go | stdoutConnector | func stdoutConnector(metrics []producers.MetricsMessage, c *cli.Context) error {
if len(metrics) == 0 {
log.Info("No messages received from metrics service")
return nil
}
for _, message := range metrics {
dimensions := &message.Dimensions
// we print a few potentially interesting dimensions
log.Infof("Metrics from task %s, framework %s, host %s", dimensions.ExecutorID, dimensions.FrameworkName, dimensions.Hostname)
if len(dimensions.Labels) > 0 {
log.Infof("Labels: %v", dimensions.Labels)
}
log.Info("Datapoints:")
for _, datapoint := range message.Datapoints {
// For clarity, we don't print timestamp or tags here.
log.Infof(" %s: %v", datapoint.Name, datapoint.Value)
}
}
return nil
} | go | func stdoutConnector(metrics []producers.MetricsMessage, c *cli.Context) error {
if len(metrics) == 0 {
log.Info("No messages received from metrics service")
return nil
}
for _, message := range metrics {
dimensions := &message.Dimensions
// we print a few potentially interesting dimensions
log.Infof("Metrics from task %s, framework %s, host %s", dimensions.ExecutorID, dimensions.FrameworkName, dimensions.Hostname)
if len(dimensions.Labels) > 0 {
log.Infof("Labels: %v", dimensions.Labels)
}
log.Info("Datapoints:")
for _, datapoint := range message.Datapoints {
// For clarity, we don't print timestamp or tags here.
log.Infof(" %s: %v", datapoint.Name, datapoint.Value)
}
}
return nil
} | [
"func",
"stdoutConnector",
"(",
"metrics",
"[",
"]",
"producers",
".",
"MetricsMessage",
",",
"c",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"if",
"len",
"(",
"metrics",
")",
"==",
"0",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"message",
":=",
"range",
"metrics",
"{",
"dimensions",
":=",
"&",
"message",
".",
"Dimensions",
"\n\n",
"// we print a few potentially interesting dimensions",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"dimensions",
".",
"ExecutorID",
",",
"dimensions",
".",
"FrameworkName",
",",
"dimensions",
".",
"Hostname",
")",
"\n",
"if",
"len",
"(",
"dimensions",
".",
"Labels",
")",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"dimensions",
".",
"Labels",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"datapoint",
":=",
"range",
"message",
".",
"Datapoints",
"{",
"// For clarity, we don't print timestamp or tags here.",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"datapoint",
".",
"Name",
",",
"datapoint",
".",
"Value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // stdoutConnector will be called each time a new set of metrics messages
// is received. It simply prints each message. | [
"stdoutConnector",
"will",
"be",
"called",
"each",
"time",
"a",
"new",
"set",
"of",
"metrics",
"messages",
"is",
"received",
".",
"It",
"simply",
"prints",
"each",
"message",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/stdout/stdout.go#L43-L65 |
10,736 | dcos/dcos-metrics | collectors/mesos/agent/container.go | getContainerMetrics | func (c *Collector) getContainerMetrics() error {
u := url.URL{
Scheme: c.RequestProtocol,
Host: net.JoinHostPort(c.nodeInfo.IPAddress, strconv.Itoa(c.Port)),
Path: "/containers",
}
c.HTTPClient.Timeout = c.RequestTimeout
return client.Fetch(c.HTTPClient, u, &c.containerMetrics)
} | go | func (c *Collector) getContainerMetrics() error {
u := url.URL{
Scheme: c.RequestProtocol,
Host: net.JoinHostPort(c.nodeInfo.IPAddress, strconv.Itoa(c.Port)),
Path: "/containers",
}
c.HTTPClient.Timeout = c.RequestTimeout
return client.Fetch(c.HTTPClient, u, &c.containerMetrics)
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"getContainerMetrics",
"(",
")",
"error",
"{",
"u",
":=",
"url",
".",
"URL",
"{",
"Scheme",
":",
"c",
".",
"RequestProtocol",
",",
"Host",
":",
"net",
".",
"JoinHostPort",
"(",
"c",
".",
"nodeInfo",
".",
"IPAddress",
",",
"strconv",
".",
"Itoa",
"(",
"c",
".",
"Port",
")",
")",
",",
"Path",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"c",
".",
"HTTPClient",
".",
"Timeout",
"=",
"c",
".",
"RequestTimeout",
"\n\n",
"return",
"client",
".",
"Fetch",
"(",
"c",
".",
"HTTPClient",
",",
"u",
",",
"&",
"c",
".",
"containerMetrics",
")",
"\n",
"}"
] | // poll queries an agent for container-level metrics, such as
// CPU, memory, disk, and network usage. | [
"poll",
"queries",
"an",
"agent",
"for",
"container",
"-",
"level",
"metrics",
"such",
"as",
"CPU",
"memory",
"disk",
"and",
"network",
"usage",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/container.go#L130-L140 |
10,737 | dcos/dcos-metrics | collectors/framework/record.go | convertLabels | func convertLabels(newLabels []mesosAgent.KeyValue) map[string]string {
result := map[string]string{}
for _, l := range newLabels {
// Remove blacklisted cosmos labels
if _, inSlice := cosmosLabels[l.Key]; inSlice {
continue
}
result[l.Key] = l.Value
}
return result
} | go | func convertLabels(newLabels []mesosAgent.KeyValue) map[string]string {
result := map[string]string{}
for _, l := range newLabels {
// Remove blacklisted cosmos labels
if _, inSlice := cosmosLabels[l.Key]; inSlice {
continue
}
result[l.Key] = l.Value
}
return result
} | [
"func",
"convertLabels",
"(",
"newLabels",
"[",
"]",
"mesosAgent",
".",
"KeyValue",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"result",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"newLabels",
"{",
"// Remove blacklisted cosmos labels",
"if",
"_",
",",
"inSlice",
":=",
"cosmosLabels",
"[",
"l",
".",
"Key",
"]",
";",
"inSlice",
"{",
"continue",
"\n",
"}",
"\n",
"result",
"[",
"l",
".",
"Key",
"]",
"=",
"l",
".",
"Value",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // convertLabels converts each keyValue to an entry in a map | [
"convertLabels",
"converts",
"each",
"keyValue",
"to",
"an",
"entry",
"in",
"a",
"map"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/framework/record.go#L134-L145 |
10,738 | dcos/dcos-metrics | util/http/helpers/helpers.go | loadCAPool | func loadCAPool(path string) (*x509.CertPool, error) {
caPool := x509.NewCertPool()
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
if !caPool.AppendCertsFromPEM(b) {
return nil, errors.New("CACertFile parsing failed")
}
return caPool, nil
} | go | func loadCAPool(path string) (*x509.CertPool, error) {
caPool := x509.NewCertPool()
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
if !caPool.AppendCertsFromPEM(b) {
return nil, errors.New("CACertFile parsing failed")
}
return caPool, nil
} | [
"func",
"loadCAPool",
"(",
"path",
"string",
")",
"(",
"*",
"x509",
".",
"CertPool",
",",
"error",
")",
"{",
"caPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"caPool",
".",
"AppendCertsFromPEM",
"(",
"b",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"caPool",
",",
"nil",
"\n",
"}"
] | // loadCAPool will load a valid x509 cert. | [
"loadCAPool",
"will",
"load",
"a",
"valid",
"x509",
"cert",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/util/http/helpers/helpers.go#L30-L48 |
10,739 | dcos/dcos-metrics | plugins/plugin.go | New | func New(options ...Option) (*Plugin, error) {
newPlugin := &Plugin{
Name: "default",
PollingInterval: 10,
}
newPlugin.App = cli.NewApp()
newPlugin.App.Version = version
newPlugin.App.Flags = []cli.Flag{
cli.IntFlag{
Name: "polling-interval",
Value: newPlugin.PollingInterval,
Usage: "Polling interval for metrics in seconds",
Destination: &newPlugin.PollingInterval,
},
cli.StringFlag{
Name: "dcos-role",
Value: newPlugin.Role,
Usage: "DC/OS role, either master or agent",
Destination: &newPlugin.Role,
},
}
for _, o := range options {
if err := o(newPlugin); err != nil {
return newPlugin, err
}
}
newPlugin.Log = logrus.WithFields(logrus.Fields{"plugin": newPlugin.Name})
return newPlugin, nil
} | go | func New(options ...Option) (*Plugin, error) {
newPlugin := &Plugin{
Name: "default",
PollingInterval: 10,
}
newPlugin.App = cli.NewApp()
newPlugin.App.Version = version
newPlugin.App.Flags = []cli.Flag{
cli.IntFlag{
Name: "polling-interval",
Value: newPlugin.PollingInterval,
Usage: "Polling interval for metrics in seconds",
Destination: &newPlugin.PollingInterval,
},
cli.StringFlag{
Name: "dcos-role",
Value: newPlugin.Role,
Usage: "DC/OS role, either master or agent",
Destination: &newPlugin.Role,
},
}
for _, o := range options {
if err := o(newPlugin); err != nil {
return newPlugin, err
}
}
newPlugin.Log = logrus.WithFields(logrus.Fields{"plugin": newPlugin.Name})
return newPlugin, nil
} | [
"func",
"New",
"(",
"options",
"...",
"Option",
")",
"(",
"*",
"Plugin",
",",
"error",
")",
"{",
"newPlugin",
":=",
"&",
"Plugin",
"{",
"Name",
":",
"\"",
"\"",
",",
"PollingInterval",
":",
"10",
",",
"}",
"\n\n",
"newPlugin",
".",
"App",
"=",
"cli",
".",
"NewApp",
"(",
")",
"\n",
"newPlugin",
".",
"App",
".",
"Version",
"=",
"version",
"\n",
"newPlugin",
".",
"App",
".",
"Flags",
"=",
"[",
"]",
"cli",
".",
"Flag",
"{",
"cli",
".",
"IntFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"newPlugin",
".",
"PollingInterval",
",",
"Usage",
":",
"\"",
"\"",
",",
"Destination",
":",
"&",
"newPlugin",
".",
"PollingInterval",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"newPlugin",
".",
"Role",
",",
"Usage",
":",
"\"",
"\"",
",",
"Destination",
":",
"&",
"newPlugin",
".",
"Role",
",",
"}",
",",
"}",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"if",
"err",
":=",
"o",
"(",
"newPlugin",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"newPlugin",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"newPlugin",
".",
"Log",
"=",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"newPlugin",
".",
"Name",
"}",
")",
"\n\n",
"return",
"newPlugin",
",",
"nil",
"\n",
"}"
] | // New returns a mandatory plugin config which every plugin for
// metrics will need | [
"New",
"returns",
"a",
"mandatory",
"plugin",
"config",
"which",
"every",
"plugin",
"for",
"metrics",
"will",
"need"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/plugin.go#L54-L86 |
10,740 | dcos/dcos-metrics | plugins/plugin.go | Metrics | func (p *Plugin) Metrics() ([]producers.MetricsMessage, error) {
var messages []producers.MetricsMessage
// Fetch node metrics
nodeMetrics, err := p.getNodeMetrics()
if err != nil {
return nil, err
}
messages = append(messages, nodeMetrics)
// Master only collects node metrics; return without checking containers
if p.Role == dcos.RoleMaster {
return messages, nil
}
// Fetch container metrics
containerMetrics, err := p.getContainerMetrics()
if err != nil {
return nil, err
}
messages = append(messages, containerMetrics...)
return messages, nil
} | go | func (p *Plugin) Metrics() ([]producers.MetricsMessage, error) {
var messages []producers.MetricsMessage
// Fetch node metrics
nodeMetrics, err := p.getNodeMetrics()
if err != nil {
return nil, err
}
messages = append(messages, nodeMetrics)
// Master only collects node metrics; return without checking containers
if p.Role == dcos.RoleMaster {
return messages, nil
}
// Fetch container metrics
containerMetrics, err := p.getContainerMetrics()
if err != nil {
return nil, err
}
messages = append(messages, containerMetrics...)
return messages, nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Metrics",
"(",
")",
"(",
"[",
"]",
"producers",
".",
"MetricsMessage",
",",
"error",
")",
"{",
"var",
"messages",
"[",
"]",
"producers",
".",
"MetricsMessage",
"\n\n",
"// Fetch node metrics",
"nodeMetrics",
",",
"err",
":=",
"p",
".",
"getNodeMetrics",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"messages",
"=",
"append",
"(",
"messages",
",",
"nodeMetrics",
")",
"\n\n",
"// Master only collects node metrics; return without checking containers",
"if",
"p",
".",
"Role",
"==",
"dcos",
".",
"RoleMaster",
"{",
"return",
"messages",
",",
"nil",
"\n",
"}",
"\n\n",
"// Fetch container metrics",
"containerMetrics",
",",
"err",
":=",
"p",
".",
"getContainerMetrics",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"messages",
"=",
"append",
"(",
"messages",
",",
"containerMetrics",
"...",
")",
"\n",
"return",
"messages",
",",
"nil",
"\n",
"}"
] | // Metrics queries the local dcos-metrics API and returns a slice of
// producers.MetricsMessage. | [
"Metrics",
"queries",
"the",
"local",
"dcos",
"-",
"metrics",
"API",
"and",
"returns",
"a",
"slice",
"of",
"producers",
".",
"MetricsMessage",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/plugin.go#L134-L156 |
10,741 | dcos/dcos-metrics | plugins/plugin.go | createClient | func (p *Plugin) createClient() error {
network := "unix"
address := "/run/dcos/dcos-metrics-agent.sock"
if runtime.GOOS == "windows" {
network = "tcp"
address = "localhost:9000"
}
if p.Role == dcos.RoleMaster {
address = "/run/dcos/dcos-metrics-master.sock"
}
p.Log.Infof("Creating metrics API client via %s", address)
p.Client = &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial(network, address)
},
},
}
return nil
} | go | func (p *Plugin) createClient() error {
network := "unix"
address := "/run/dcos/dcos-metrics-agent.sock"
if runtime.GOOS == "windows" {
network = "tcp"
address = "localhost:9000"
}
if p.Role == dcos.RoleMaster {
address = "/run/dcos/dcos-metrics-master.sock"
}
p.Log.Infof("Creating metrics API client via %s", address)
p.Client = &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial(network, address)
},
},
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"createClient",
"(",
")",
"error",
"{",
"network",
":=",
"\"",
"\"",
"\n",
"address",
":=",
"\"",
"\"",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"network",
"=",
"\"",
"\"",
"\n",
"address",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"p",
".",
"Role",
"==",
"dcos",
".",
"RoleMaster",
"{",
"address",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"address",
")",
"\n\n",
"p",
".",
"Client",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"DialContext",
":",
"func",
"(",
"_",
"context",
".",
"Context",
",",
"_",
",",
"_",
"string",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"net",
".",
"Dial",
"(",
"network",
",",
"address",
")",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // createClient creates an HTTP Client which uses the unix file socket
// appropriate to the plugin's role | [
"createClient",
"creates",
"an",
"HTTP",
"Client",
"which",
"uses",
"the",
"unix",
"file",
"socket",
"appropriate",
"to",
"the",
"plugin",
"s",
"role"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/plugin.go#L231-L252 |
10,742 | dcos/dcos-metrics | plugins/prometheus/prometheus.go | messageToPromText | func messageToPromText(message producers.MetricsMessage) string {
var buffer bytes.Buffer
for _, d := range message.Datapoints {
name := sanitizeName(d.Name)
labels := getLabelsForDatapoint(message.Dimensions, d.Tags)
t, err := time.Parse(time.RFC3339, d.Timestamp)
if err != nil {
log.Warnf("Encountered bad timestamp, %q: %s", d.Timestamp, err)
continue
}
timestampMs := int(t.UnixNano() / 1000000)
buffer.WriteString(fmt.Sprintf("%s%s %v %d\n", name, labels, d.Value, timestampMs))
}
return buffer.String()
} | go | func messageToPromText(message producers.MetricsMessage) string {
var buffer bytes.Buffer
for _, d := range message.Datapoints {
name := sanitizeName(d.Name)
labels := getLabelsForDatapoint(message.Dimensions, d.Tags)
t, err := time.Parse(time.RFC3339, d.Timestamp)
if err != nil {
log.Warnf("Encountered bad timestamp, %q: %s", d.Timestamp, err)
continue
}
timestampMs := int(t.UnixNano() / 1000000)
buffer.WriteString(fmt.Sprintf("%s%s %v %d\n", name, labels, d.Value, timestampMs))
}
return buffer.String()
} | [
"func",
"messageToPromText",
"(",
"message",
"producers",
".",
"MetricsMessage",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n\n",
"for",
"_",
",",
"d",
":=",
"range",
"message",
".",
"Datapoints",
"{",
"name",
":=",
"sanitizeName",
"(",
"d",
".",
"Name",
")",
"\n",
"labels",
":=",
"getLabelsForDatapoint",
"(",
"message",
".",
"Dimensions",
",",
"d",
".",
"Tags",
")",
"\n",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"d",
".",
"Timestamp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"d",
".",
"Timestamp",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"timestampMs",
":=",
"int",
"(",
"t",
".",
"UnixNano",
"(",
")",
"/",
"1000000",
")",
"\n",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
",",
"labels",
",",
"d",
".",
"Value",
",",
"timestampMs",
")",
")",
"\n",
"}",
"\n\n",
"return",
"buffer",
".",
"String",
"(",
")",
"\n",
"}"
] | // messageToPromText converts a single metrics message to prometheus-formatted
// newline-separate strings | [
"messageToPromText",
"converts",
"a",
"single",
"metrics",
"message",
"to",
"prometheus",
"-",
"formatted",
"newline",
"-",
"separate",
"strings"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/prometheus/prometheus.go#L129-L145 |
10,743 | dcos/dcos-metrics | plugins/prometheus/prometheus.go | getLabelsForDatapoint | func getLabelsForDatapoint(dimensions producers.Dimensions, tags map[string]string) string {
allDimensions := map[string]string{}
if dimensions.Labels != nil {
allDimensions = dimensions.Labels
}
allDimensions["mesos_id"] = dimensions.MesosID
allDimensions["cluster_id"] = dimensions.ClusterID
allDimensions["container_id"] = dimensions.ContainerID
allDimensions["framework_name"] = dimensions.FrameworkName
allDimensions["framework_id"] = dimensions.FrameworkID
allDimensions["framework_role"] = dimensions.FrameworkRole
allDimensions["framework_principal"] = dimensions.FrameworkPrincipal
allDimensions["task_name"] = dimensions.TaskName
allDimensions["task_id"] = dimensions.TaskID
allDimensions["hostname"] = dimensions.Hostname
labels := []string{}
for k, v := range allDimensions {
if len(v) > 0 {
labels = append(labels, fmt.Sprintf("%s=%q", k, v))
}
}
// Sorting tags ensures consistent order
for _, pair := range prodHelpers.SortTags(tags) {
k, v := pair[0], pair[1]
labels = append(labels, fmt.Sprintf("%s=%q", sanitizeName(k), v))
}
if len(labels) > 0 {
return "{" + strings.Join(labels, ",") + "}"
}
return ""
} | go | func getLabelsForDatapoint(dimensions producers.Dimensions, tags map[string]string) string {
allDimensions := map[string]string{}
if dimensions.Labels != nil {
allDimensions = dimensions.Labels
}
allDimensions["mesos_id"] = dimensions.MesosID
allDimensions["cluster_id"] = dimensions.ClusterID
allDimensions["container_id"] = dimensions.ContainerID
allDimensions["framework_name"] = dimensions.FrameworkName
allDimensions["framework_id"] = dimensions.FrameworkID
allDimensions["framework_role"] = dimensions.FrameworkRole
allDimensions["framework_principal"] = dimensions.FrameworkPrincipal
allDimensions["task_name"] = dimensions.TaskName
allDimensions["task_id"] = dimensions.TaskID
allDimensions["hostname"] = dimensions.Hostname
labels := []string{}
for k, v := range allDimensions {
if len(v) > 0 {
labels = append(labels, fmt.Sprintf("%s=%q", k, v))
}
}
// Sorting tags ensures consistent order
for _, pair := range prodHelpers.SortTags(tags) {
k, v := pair[0], pair[1]
labels = append(labels, fmt.Sprintf("%s=%q", sanitizeName(k), v))
}
if len(labels) > 0 {
return "{" + strings.Join(labels, ",") + "}"
}
return ""
} | [
"func",
"getLabelsForDatapoint",
"(",
"dimensions",
"producers",
".",
"Dimensions",
",",
"tags",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"allDimensions",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"dimensions",
".",
"Labels",
"!=",
"nil",
"{",
"allDimensions",
"=",
"dimensions",
".",
"Labels",
"\n",
"}",
"\n\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"MesosID",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"ClusterID",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"ContainerID",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"FrameworkName",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"FrameworkID",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"FrameworkRole",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"FrameworkPrincipal",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"TaskName",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"TaskID",
"\n",
"allDimensions",
"[",
"\"",
"\"",
"]",
"=",
"dimensions",
".",
"Hostname",
"\n\n",
"labels",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"allDimensions",
"{",
"if",
"len",
"(",
"v",
")",
">",
"0",
"{",
"labels",
"=",
"append",
"(",
"labels",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Sorting tags ensures consistent order",
"for",
"_",
",",
"pair",
":=",
"range",
"prodHelpers",
".",
"SortTags",
"(",
"tags",
")",
"{",
"k",
",",
"v",
":=",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
"\n",
"labels",
"=",
"append",
"(",
"labels",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sanitizeName",
"(",
"k",
")",
",",
"v",
")",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"labels",
")",
">",
"0",
"{",
"return",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"labels",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // getLabelsForDatapoint returns prometheus-formatted labels from a
// datapoint's dimensions and tags | [
"getLabelsForDatapoint",
"returns",
"prometheus",
"-",
"formatted",
"labels",
"from",
"a",
"datapoint",
"s",
"dimensions",
"and",
"tags"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/prometheus/prometheus.go#L149-L182 |
10,744 | dcos/dcos-metrics | plugins/prometheus/prometheus.go | sanitizeName | func sanitizeName(name string) string {
output := strings.ToLower(illegalChars.ReplaceAllString(name, "_"))
if legalLabel.MatchString(output) {
return output
}
// Prefix name with _ if it begins with a number
return "_" + output
} | go | func sanitizeName(name string) string {
output := strings.ToLower(illegalChars.ReplaceAllString(name, "_"))
if legalLabel.MatchString(output) {
return output
}
// Prefix name with _ if it begins with a number
return "_" + output
} | [
"func",
"sanitizeName",
"(",
"name",
"string",
")",
"string",
"{",
"output",
":=",
"strings",
".",
"ToLower",
"(",
"illegalChars",
".",
"ReplaceAllString",
"(",
"name",
",",
"\"",
"\"",
")",
")",
"\n\n",
"if",
"legalLabel",
".",
"MatchString",
"(",
"output",
")",
"{",
"return",
"output",
"\n",
"}",
"\n",
"// Prefix name with _ if it begins with a number",
"return",
"\"",
"\"",
"+",
"output",
"\n",
"}"
] | // sanitizeName returns a metric or label name which is safe for use
// in prometheus output | [
"sanitizeName",
"returns",
"a",
"metric",
"or",
"label",
"name",
"which",
"is",
"safe",
"for",
"use",
"in",
"prometheus",
"output"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/prometheus/prometheus.go#L186-L194 |
10,745 | dcos/dcos-metrics | util/http/profiler/profiler.go | RunHTTPProfAccess | func RunHTTPProfAccess() {
// listen on an ephemeral port, then print the port
listener, err := net.Listen("tcp", ":0")
if err != nil {
log.Printf("Unable to open profile access listener: %s\n", err)
} else {
log.Printf("Enabling profile access at http://%s/debug/pprof\n", listener.Addr())
log.Println(http.Serve(listener, nil)) // blocks
}
} | go | func RunHTTPProfAccess() {
// listen on an ephemeral port, then print the port
listener, err := net.Listen("tcp", ":0")
if err != nil {
log.Printf("Unable to open profile access listener: %s\n", err)
} else {
log.Printf("Enabling profile access at http://%s/debug/pprof\n", listener.Addr())
log.Println(http.Serve(listener, nil)) // blocks
}
} | [
"func",
"RunHTTPProfAccess",
"(",
")",
"{",
"// listen on an ephemeral port, then print the port",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"listener",
".",
"Addr",
"(",
")",
")",
"\n",
"log",
".",
"Println",
"(",
"http",
".",
"Serve",
"(",
"listener",
",",
"nil",
")",
")",
"// blocks",
"\n",
"}",
"\n",
"}"
] | // RunHTTPProfAccess runs an HTTP listener on a random ephemeral port which allows pprof access.
// This function should be run as a gofunc. | [
"RunHTTPProfAccess",
"runs",
"an",
"HTTP",
"listener",
"on",
"a",
"random",
"ephemeral",
"port",
"which",
"allows",
"pprof",
"access",
".",
"This",
"function",
"should",
"be",
"run",
"as",
"a",
"gofunc",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/util/http/profiler/profiler.go#L27-L36 |
10,746 | dcos/dcos-metrics | producers/prometheus/prometheus.go | New | func New(cfg Config) (producers.MetricsProducer, chan producers.MetricsMessage) {
p := promProducer{
config: cfg,
store: store.New(),
metricsChan: make(chan producers.MetricsMessage),
janitorRunInterval: 60 * time.Second,
}
return &p, p.metricsChan
} | go | func New(cfg Config) (producers.MetricsProducer, chan producers.MetricsMessage) {
p := promProducer{
config: cfg,
store: store.New(),
metricsChan: make(chan producers.MetricsMessage),
janitorRunInterval: 60 * time.Second,
}
return &p, p.metricsChan
} | [
"func",
"New",
"(",
"cfg",
"Config",
")",
"(",
"producers",
".",
"MetricsProducer",
",",
"chan",
"producers",
".",
"MetricsMessage",
")",
"{",
"p",
":=",
"promProducer",
"{",
"config",
":",
"cfg",
",",
"store",
":",
"store",
".",
"New",
"(",
")",
",",
"metricsChan",
":",
"make",
"(",
"chan",
"producers",
".",
"MetricsMessage",
")",
",",
"janitorRunInterval",
":",
"60",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"return",
"&",
"p",
",",
"p",
".",
"metricsChan",
"\n",
"}"
] | // New returns a prometheus producer and a channel for passing in metrics | [
"New",
"returns",
"a",
"prometheus",
"producer",
"and",
"a",
"channel",
"for",
"passing",
"in",
"metrics"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L64-L72 |
10,747 | dcos/dcos-metrics | producers/prometheus/prometheus.go | Collect | func (p *promProducer) Collect(ch chan<- prometheus.Metric) {
for name, datapointsLabels := range datapointLabelsByName(p.store) {
variableLabels := getLabelNames(datapointsLabels)
desc := prometheus.NewDesc(sanitize(name), "DC/OS Metrics Datapoint", sanitizeSlice(variableLabels), nil)
// Publish a metric for each datapoint.
for _, dpLabels := range datapointsLabels {
// Collect this datapoint's variable label values.
var variableLabelVals []string
for _, labelName := range variableLabels {
if val, ok := dpLabels.labels[labelName]; ok {
variableLabelVals = append(variableLabelVals, val)
} else {
variableLabelVals = append(variableLabelVals, "")
}
}
val, err := coerceToFloat(dpLabels.datapoint.Value)
if err != nil {
promLog.Debugf("Bad datapoint value %q: (%s) %s", dpLabels.datapoint.Value, dpLabels.datapoint.Name, err)
continue
}
metric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, variableLabelVals...)
if err != nil {
promLog.Warnf("Could not create Prometheus metric %s: %s", name, err)
continue
}
promLog.Debugf("Emitting datapoint %s", name)
ch <- metric
}
}
} | go | func (p *promProducer) Collect(ch chan<- prometheus.Metric) {
for name, datapointsLabels := range datapointLabelsByName(p.store) {
variableLabels := getLabelNames(datapointsLabels)
desc := prometheus.NewDesc(sanitize(name), "DC/OS Metrics Datapoint", sanitizeSlice(variableLabels), nil)
// Publish a metric for each datapoint.
for _, dpLabels := range datapointsLabels {
// Collect this datapoint's variable label values.
var variableLabelVals []string
for _, labelName := range variableLabels {
if val, ok := dpLabels.labels[labelName]; ok {
variableLabelVals = append(variableLabelVals, val)
} else {
variableLabelVals = append(variableLabelVals, "")
}
}
val, err := coerceToFloat(dpLabels.datapoint.Value)
if err != nil {
promLog.Debugf("Bad datapoint value %q: (%s) %s", dpLabels.datapoint.Value, dpLabels.datapoint.Name, err)
continue
}
metric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, variableLabelVals...)
if err != nil {
promLog.Warnf("Could not create Prometheus metric %s: %s", name, err)
continue
}
promLog.Debugf("Emitting datapoint %s", name)
ch <- metric
}
}
} | [
"func",
"(",
"p",
"*",
"promProducer",
")",
"Collect",
"(",
"ch",
"chan",
"<-",
"prometheus",
".",
"Metric",
")",
"{",
"for",
"name",
",",
"datapointsLabels",
":=",
"range",
"datapointLabelsByName",
"(",
"p",
".",
"store",
")",
"{",
"variableLabels",
":=",
"getLabelNames",
"(",
"datapointsLabels",
")",
"\n",
"desc",
":=",
"prometheus",
".",
"NewDesc",
"(",
"sanitize",
"(",
"name",
")",
",",
"\"",
"\"",
",",
"sanitizeSlice",
"(",
"variableLabels",
")",
",",
"nil",
")",
"\n\n",
"// Publish a metric for each datapoint.",
"for",
"_",
",",
"dpLabels",
":=",
"range",
"datapointsLabels",
"{",
"// Collect this datapoint's variable label values.",
"var",
"variableLabelVals",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"labelName",
":=",
"range",
"variableLabels",
"{",
"if",
"val",
",",
"ok",
":=",
"dpLabels",
".",
"labels",
"[",
"labelName",
"]",
";",
"ok",
"{",
"variableLabelVals",
"=",
"append",
"(",
"variableLabelVals",
",",
"val",
")",
"\n",
"}",
"else",
"{",
"variableLabelVals",
"=",
"append",
"(",
"variableLabelVals",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"val",
",",
"err",
":=",
"coerceToFloat",
"(",
"dpLabels",
".",
"datapoint",
".",
"Value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"promLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"dpLabels",
".",
"datapoint",
".",
"Value",
",",
"dpLabels",
".",
"datapoint",
".",
"Name",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"metric",
",",
"err",
":=",
"prometheus",
".",
"NewConstMetric",
"(",
"desc",
",",
"prometheus",
".",
"GaugeValue",
",",
"val",
",",
"variableLabelVals",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"promLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"promLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"ch",
"<-",
"metric",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Collect iterates over all the metrics available in the store, converting
// them to prometheus.Metric and passing them into the prometheus producer
// channel, where they will be served to consumers. | [
"Collect",
"iterates",
"over",
"all",
"the",
"metrics",
"available",
"in",
"the",
"store",
"converting",
"them",
"to",
"prometheus",
".",
"Metric",
"and",
"passing",
"them",
"into",
"the",
"prometheus",
"producer",
"channel",
"where",
"they",
"will",
"be",
"served",
"to",
"consumers",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L136-L169 |
10,748 | dcos/dcos-metrics | producers/prometheus/prometheus.go | writeObjectToStore | func (p *promProducer) writeObjectToStore(d producers.Datapoint, m producers.MetricsMessage, prefix string) {
newMessage := producers.MetricsMessage{
Name: m.Name,
Datapoints: []producers.Datapoint{d},
Dimensions: m.Dimensions,
Timestamp: m.Timestamp,
}
// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag
qualifiedName := joinMetricName(prefix, d.Name)
for _, pair := range prodHelpers.SortTags(d.Tags) {
k, v := pair[0], pair[1]
// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0
serializedTag := fmt.Sprintf("#%s:%s", k, v)
qualifiedName = joinMetricName(qualifiedName, serializedTag)
}
p.store.Set(qualifiedName, newMessage)
} | go | func (p *promProducer) writeObjectToStore(d producers.Datapoint, m producers.MetricsMessage, prefix string) {
newMessage := producers.MetricsMessage{
Name: m.Name,
Datapoints: []producers.Datapoint{d},
Dimensions: m.Dimensions,
Timestamp: m.Timestamp,
}
// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag
qualifiedName := joinMetricName(prefix, d.Name)
for _, pair := range prodHelpers.SortTags(d.Tags) {
k, v := pair[0], pair[1]
// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0
serializedTag := fmt.Sprintf("#%s:%s", k, v)
qualifiedName = joinMetricName(qualifiedName, serializedTag)
}
p.store.Set(qualifiedName, newMessage)
} | [
"func",
"(",
"p",
"*",
"promProducer",
")",
"writeObjectToStore",
"(",
"d",
"producers",
".",
"Datapoint",
",",
"m",
"producers",
".",
"MetricsMessage",
",",
"prefix",
"string",
")",
"{",
"newMessage",
":=",
"producers",
".",
"MetricsMessage",
"{",
"Name",
":",
"m",
".",
"Name",
",",
"Datapoints",
":",
"[",
"]",
"producers",
".",
"Datapoint",
"{",
"d",
"}",
",",
"Dimensions",
":",
"m",
".",
"Dimensions",
",",
"Timestamp",
":",
"m",
".",
"Timestamp",
",",
"}",
"\n",
"// e.g. dcos.metrics.app.[ContainerId].kafka.server.ReplicaFetcherManager.MaxLag",
"qualifiedName",
":=",
"joinMetricName",
"(",
"prefix",
",",
"d",
".",
"Name",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"prodHelpers",
".",
"SortTags",
"(",
"d",
".",
"Tags",
")",
"{",
"k",
",",
"v",
":=",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
"\n",
"// e.g. dcos.metrics.node.[MesosId].network.out.errors.#interface:eth0",
"serializedTag",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"qualifiedName",
"=",
"joinMetricName",
"(",
"qualifiedName",
",",
"serializedTag",
")",
"\n",
"}",
"\n",
"p",
".",
"store",
".",
"Set",
"(",
"qualifiedName",
",",
"newMessage",
")",
"\n",
"}"
] | // - helpers -
// writeObjectToStore writes a prefixed datapoint into the store. | [
"-",
"helpers",
"-",
"writeObjectToStore",
"writes",
"a",
"prefixed",
"datapoint",
"into",
"the",
"store",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L174-L190 |
10,749 | dcos/dcos-metrics | producers/prometheus/prometheus.go | coerceToFloat | func coerceToFloat(unk interface{}) (float64, error) {
switch i := unk.(type) {
case float64:
if math.IsNaN(i) {
return i, errors.New("value was NaN")
}
return i, nil
case float32:
return float64(i), nil
case int:
return float64(i), nil
case int32:
return float64(i), nil
case int64:
return float64(i), nil
case uint:
return float64(i), nil
case uint32:
return float64(i), nil
case uint64:
return float64(i), nil
default:
return math.NaN(), fmt.Errorf("value %q could not be coerced to float64", i)
}
} | go | func coerceToFloat(unk interface{}) (float64, error) {
switch i := unk.(type) {
case float64:
if math.IsNaN(i) {
return i, errors.New("value was NaN")
}
return i, nil
case float32:
return float64(i), nil
case int:
return float64(i), nil
case int32:
return float64(i), nil
case int64:
return float64(i), nil
case uint:
return float64(i), nil
case uint32:
return float64(i), nil
case uint64:
return float64(i), nil
default:
return math.NaN(), fmt.Errorf("value %q could not be coerced to float64", i)
}
} | [
"func",
"coerceToFloat",
"(",
"unk",
"interface",
"{",
"}",
")",
"(",
"float64",
",",
"error",
")",
"{",
"switch",
"i",
":=",
"unk",
".",
"(",
"type",
")",
"{",
"case",
"float64",
":",
"if",
"math",
".",
"IsNaN",
"(",
"i",
")",
"{",
"return",
"i",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"case",
"float32",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"int",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"int32",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"int64",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"uint",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"uint32",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"case",
"uint64",
":",
"return",
"float64",
"(",
"i",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"math",
".",
"NaN",
"(",
")",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"}",
"\n",
"}"
] | // coerceToFloat attempts to convert an interface to float64. It should succeed
// with any numeric input. | [
"coerceToFloat",
"attempts",
"to",
"convert",
"an",
"interface",
"to",
"float64",
".",
"It",
"should",
"succeed",
"with",
"any",
"numeric",
"input",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L242-L266 |
10,750 | dcos/dcos-metrics | producers/prometheus/prometheus.go | dimsToMap | func dimsToMap(dims producers.Dimensions) map[string]string {
results := map[string]string{
"mesos_id": dims.MesosID,
"cluster_id": dims.ClusterID,
"container_id": dims.ContainerID,
"executor_id": dims.ExecutorID,
"framework_name": dims.FrameworkName,
"framework_id": dims.FrameworkID,
"framework_role": dims.FrameworkRole,
"framework_principal": dims.FrameworkPrincipal,
"task_name": dims.TaskName,
"task_id": dims.TaskID,
"hostname": dims.Hostname,
}
for k, v := range dims.Labels {
results[k] = v
}
return results
} | go | func dimsToMap(dims producers.Dimensions) map[string]string {
results := map[string]string{
"mesos_id": dims.MesosID,
"cluster_id": dims.ClusterID,
"container_id": dims.ContainerID,
"executor_id": dims.ExecutorID,
"framework_name": dims.FrameworkName,
"framework_id": dims.FrameworkID,
"framework_role": dims.FrameworkRole,
"framework_principal": dims.FrameworkPrincipal,
"task_name": dims.TaskName,
"task_id": dims.TaskID,
"hostname": dims.Hostname,
}
for k, v := range dims.Labels {
results[k] = v
}
return results
} | [
"func",
"dimsToMap",
"(",
"dims",
"producers",
".",
"Dimensions",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"results",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"dims",
".",
"MesosID",
",",
"\"",
"\"",
":",
"dims",
".",
"ClusterID",
",",
"\"",
"\"",
":",
"dims",
".",
"ContainerID",
",",
"\"",
"\"",
":",
"dims",
".",
"ExecutorID",
",",
"\"",
"\"",
":",
"dims",
".",
"FrameworkName",
",",
"\"",
"\"",
":",
"dims",
".",
"FrameworkID",
",",
"\"",
"\"",
":",
"dims",
".",
"FrameworkRole",
",",
"\"",
"\"",
":",
"dims",
".",
"FrameworkPrincipal",
",",
"\"",
"\"",
":",
"dims",
".",
"TaskName",
",",
"\"",
"\"",
":",
"dims",
".",
"TaskID",
",",
"\"",
"\"",
":",
"dims",
".",
"Hostname",
",",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"dims",
".",
"Labels",
"{",
"results",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] | // dimsToMap converts a Dimensions object to a flat map of strings to strings | [
"dimsToMap",
"converts",
"a",
"Dimensions",
"object",
"to",
"a",
"flat",
"map",
"of",
"strings",
"to",
"strings"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L269-L287 |
10,751 | dcos/dcos-metrics | producers/prometheus/prometheus.go | datapointLabelsByName | func datapointLabelsByName(s store.Store) map[string][]datapointLabels {
rval := map[string][]datapointLabels{}
for _, obj := range s.Objects() {
m, ok := obj.(producers.MetricsMessage)
if !ok {
promLog.Warnf("Unsupported message type %T", obj)
continue
}
// For each datapoint, collect its labels and add an entry to rval.
dims := dimsToMap(m.Dimensions)
for _, d := range m.Datapoints {
labels := map[string]string{}
for k, v := range dims {
labels[k] = v
}
for k, v := range d.Tags {
labels[k] = v
}
rval[d.Name] = append(rval[d.Name], datapointLabels{&d, labels})
}
}
return rval
} | go | func datapointLabelsByName(s store.Store) map[string][]datapointLabels {
rval := map[string][]datapointLabels{}
for _, obj := range s.Objects() {
m, ok := obj.(producers.MetricsMessage)
if !ok {
promLog.Warnf("Unsupported message type %T", obj)
continue
}
// For each datapoint, collect its labels and add an entry to rval.
dims := dimsToMap(m.Dimensions)
for _, d := range m.Datapoints {
labels := map[string]string{}
for k, v := range dims {
labels[k] = v
}
for k, v := range d.Tags {
labels[k] = v
}
rval[d.Name] = append(rval[d.Name], datapointLabels{&d, labels})
}
}
return rval
} | [
"func",
"datapointLabelsByName",
"(",
"s",
"store",
".",
"Store",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"datapointLabels",
"{",
"rval",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"datapointLabels",
"{",
"}",
"\n\n",
"for",
"_",
",",
"obj",
":=",
"range",
"s",
".",
"Objects",
"(",
")",
"{",
"m",
",",
"ok",
":=",
"obj",
".",
"(",
"producers",
".",
"MetricsMessage",
")",
"\n",
"if",
"!",
"ok",
"{",
"promLog",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"obj",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// For each datapoint, collect its labels and add an entry to rval.",
"dims",
":=",
"dimsToMap",
"(",
"m",
".",
"Dimensions",
")",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"m",
".",
"Datapoints",
"{",
"labels",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"dims",
"{",
"labels",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"d",
".",
"Tags",
"{",
"labels",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"rval",
"[",
"d",
".",
"Name",
"]",
"=",
"append",
"(",
"rval",
"[",
"d",
".",
"Name",
"]",
",",
"datapointLabels",
"{",
"&",
"d",
",",
"labels",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"rval",
"\n",
"}"
] | // datapointLabelsByName returns a mapping of datapoint names to a slice of structs pairing producers.Datapoints by that
// name with their corresponding labels. Labels are derived from MetricsMessage dimensions and Datapoint tags. | [
"datapointLabelsByName",
"returns",
"a",
"mapping",
"of",
"datapoint",
"names",
"to",
"a",
"slice",
"of",
"structs",
"pairing",
"producers",
".",
"Datapoints",
"by",
"that",
"name",
"with",
"their",
"corresponding",
"labels",
".",
"Labels",
"are",
"derived",
"from",
"MetricsMessage",
"dimensions",
"and",
"Datapoint",
"tags",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L291-L316 |
10,752 | dcos/dcos-metrics | producers/prometheus/prometheus.go | getLabelNames | func getLabelNames(datapointsLabels []datapointLabels) []string {
// Collect all label names used among datapointsLabels.
nameMap := map[string]bool{}
for _, kv := range datapointsLabels {
for k := range kv.labels {
nameMap[k] = true
}
}
// Return a slice of nameMap keys.
names := []string{}
for n := range nameMap {
names = append(names, n)
}
return names
} | go | func getLabelNames(datapointsLabels []datapointLabels) []string {
// Collect all label names used among datapointsLabels.
nameMap := map[string]bool{}
for _, kv := range datapointsLabels {
for k := range kv.labels {
nameMap[k] = true
}
}
// Return a slice of nameMap keys.
names := []string{}
for n := range nameMap {
names = append(names, n)
}
return names
} | [
"func",
"getLabelNames",
"(",
"datapointsLabels",
"[",
"]",
"datapointLabels",
")",
"[",
"]",
"string",
"{",
"// Collect all label names used among datapointsLabels.",
"nameMap",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"kv",
":=",
"range",
"datapointsLabels",
"{",
"for",
"k",
":=",
"range",
"kv",
".",
"labels",
"{",
"nameMap",
"[",
"k",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Return a slice of nameMap keys.",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"n",
":=",
"range",
"nameMap",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"names",
"\n",
"}"
] | // getLabelNames returns the names of all labels among datapointsLabels. | [
"getLabelNames",
"returns",
"the",
"names",
"of",
"all",
"labels",
"among",
"datapointsLabels",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/producers/prometheus/prometheus.go#L319-L334 |
10,753 | dcos/dcos-metrics | collectors/node/node.go | New | func New(cfg Collector, nodeInfo collectors.NodeInfo) (Collector, chan producers.MetricsMessage) {
c := Collector{
PollPeriod: cfg.PollPeriod,
MetricsChan: make(chan producers.MetricsMessage),
log: log.WithFields(log.Fields{"collector": "node"}),
nodeInfo: nodeInfo,
}
return c, c.MetricsChan
} | go | func New(cfg Collector, nodeInfo collectors.NodeInfo) (Collector, chan producers.MetricsMessage) {
c := Collector{
PollPeriod: cfg.PollPeriod,
MetricsChan: make(chan producers.MetricsMessage),
log: log.WithFields(log.Fields{"collector": "node"}),
nodeInfo: nodeInfo,
}
return c, c.MetricsChan
} | [
"func",
"New",
"(",
"cfg",
"Collector",
",",
"nodeInfo",
"collectors",
".",
"NodeInfo",
")",
"(",
"Collector",
",",
"chan",
"producers",
".",
"MetricsMessage",
")",
"{",
"c",
":=",
"Collector",
"{",
"PollPeriod",
":",
"cfg",
".",
"PollPeriod",
",",
"MetricsChan",
":",
"make",
"(",
"chan",
"producers",
".",
"MetricsMessage",
")",
",",
"log",
":",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
",",
"nodeInfo",
":",
"nodeInfo",
",",
"}",
"\n",
"return",
"c",
",",
"c",
".",
"MetricsChan",
"\n",
"}"
] | // New returns a new instance of the node metrics collector and a metrics chan. | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"the",
"node",
"metrics",
"collector",
"and",
"a",
"metrics",
"chan",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/node/node.go#L44-L52 |
10,754 | dcos/dcos-metrics | collectors/node/node.go | RunPoller | func (c *Collector) RunPoller() {
for {
c.pollHost()
for _, m := range c.transform() {
c.MetricsChan <- m
}
time.Sleep(c.PollPeriod)
}
} | go | func (c *Collector) RunPoller() {
for {
c.pollHost()
for _, m := range c.transform() {
c.MetricsChan <- m
}
time.Sleep(c.PollPeriod)
}
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"RunPoller",
"(",
")",
"{",
"for",
"{",
"c",
".",
"pollHost",
"(",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"c",
".",
"transform",
"(",
")",
"{",
"c",
".",
"MetricsChan",
"<-",
"m",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"c",
".",
"PollPeriod",
")",
"\n",
"}",
"\n",
"}"
] | // RunPoller periodiclly polls the HTTP APIs of a Mesos agent. This function
// should be run in its own goroutine. | [
"RunPoller",
"periodiclly",
"polls",
"the",
"HTTP",
"APIs",
"of",
"a",
"Mesos",
"agent",
".",
"This",
"function",
"should",
"be",
"run",
"in",
"its",
"own",
"goroutine",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/node/node.go#L56-L64 |
10,755 | dcos/dcos-metrics | collectors/node/node.go | transform | func (c *Collector) transform() (out []producers.MetricsMessage) {
var msg producers.MetricsMessage
t := time.Unix(c.timestamp, 0)
// Produce node metrics
msg = producers.MetricsMessage{
Name: producers.NodeMetricPrefix,
Datapoints: c.nodeMetrics,
Dimensions: producers.Dimensions{
MesosID: c.nodeInfo.MesosID,
ClusterID: c.nodeInfo.ClusterID,
Hostname: c.nodeInfo.Hostname,
},
Timestamp: t.UTC().Unix(),
}
out = append(out, msg)
return out
} | go | func (c *Collector) transform() (out []producers.MetricsMessage) {
var msg producers.MetricsMessage
t := time.Unix(c.timestamp, 0)
// Produce node metrics
msg = producers.MetricsMessage{
Name: producers.NodeMetricPrefix,
Datapoints: c.nodeMetrics,
Dimensions: producers.Dimensions{
MesosID: c.nodeInfo.MesosID,
ClusterID: c.nodeInfo.ClusterID,
Hostname: c.nodeInfo.Hostname,
},
Timestamp: t.UTC().Unix(),
}
out = append(out, msg)
return out
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"transform",
"(",
")",
"(",
"out",
"[",
"]",
"producers",
".",
"MetricsMessage",
")",
"{",
"var",
"msg",
"producers",
".",
"MetricsMessage",
"\n",
"t",
":=",
"time",
".",
"Unix",
"(",
"c",
".",
"timestamp",
",",
"0",
")",
"\n\n",
"// Produce node metrics",
"msg",
"=",
"producers",
".",
"MetricsMessage",
"{",
"Name",
":",
"producers",
".",
"NodeMetricPrefix",
",",
"Datapoints",
":",
"c",
".",
"nodeMetrics",
",",
"Dimensions",
":",
"producers",
".",
"Dimensions",
"{",
"MesosID",
":",
"c",
".",
"nodeInfo",
".",
"MesosID",
",",
"ClusterID",
":",
"c",
".",
"nodeInfo",
".",
"ClusterID",
",",
"Hostname",
":",
"c",
".",
"nodeInfo",
".",
"Hostname",
",",
"}",
",",
"Timestamp",
":",
"t",
".",
"UTC",
"(",
")",
".",
"Unix",
"(",
")",
",",
"}",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"msg",
")",
"\n\n",
"return",
"out",
"\n",
"}"
] | // transform will take metrics retrieved from the agent and perform any
// transformations necessary to make the data fit the output expected by
// producers.MetricsMessage. | [
"transform",
"will",
"take",
"metrics",
"retrieved",
"from",
"the",
"agent",
"and",
"perform",
"any",
"transformations",
"necessary",
"to",
"make",
"the",
"data",
"fit",
"the",
"output",
"expected",
"by",
"producers",
".",
"MetricsMessage",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/node/node.go#L86-L104 |
10,756 | dcos/dcos-metrics | plugins/statsd/statsd.go | statsdConnector | func statsdConnector(metrics []producers.MetricsMessage, c *cli.Context) error {
once.Do(func() {
statsdHost := c.String("statsd-udp-host")
statsdPort := c.Int("statsd-udp-port")
log.Infof("Setting up new statsd client %s:%d", statsdHost, statsdPort)
statsdClient = statsd.New(statsdHost, statsdPort)
})
if len(metrics) == 0 {
log.Info("No messages received from metrics service")
return nil
}
for _, message := range metrics {
log.Debugf("Sending %d datapoints to statsd server...", len(message.Datapoints))
emitDatapointsOverStatsd(message.Datapoints, statsdClient)
}
return nil
} | go | func statsdConnector(metrics []producers.MetricsMessage, c *cli.Context) error {
once.Do(func() {
statsdHost := c.String("statsd-udp-host")
statsdPort := c.Int("statsd-udp-port")
log.Infof("Setting up new statsd client %s:%d", statsdHost, statsdPort)
statsdClient = statsd.New(statsdHost, statsdPort)
})
if len(metrics) == 0 {
log.Info("No messages received from metrics service")
return nil
}
for _, message := range metrics {
log.Debugf("Sending %d datapoints to statsd server...", len(message.Datapoints))
emitDatapointsOverStatsd(message.Datapoints, statsdClient)
}
return nil
} | [
"func",
"statsdConnector",
"(",
"metrics",
"[",
"]",
"producers",
".",
"MetricsMessage",
",",
"c",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"statsdHost",
":=",
"c",
".",
"String",
"(",
"\"",
"\"",
")",
"\n",
"statsdPort",
":=",
"c",
".",
"Int",
"(",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"statsdHost",
",",
"statsdPort",
")",
"\n",
"statsdClient",
"=",
"statsd",
".",
"New",
"(",
"statsdHost",
",",
"statsdPort",
")",
"\n",
"}",
")",
"\n\n",
"if",
"len",
"(",
"metrics",
")",
"==",
"0",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"message",
":=",
"range",
"metrics",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"len",
"(",
"message",
".",
"Datapoints",
")",
")",
"\n",
"emitDatapointsOverStatsd",
"(",
"message",
".",
"Datapoints",
",",
"statsdClient",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // statsdConnector is the method called by the plugin every time it retrieves
// metrics from the API. | [
"statsdConnector",
"is",
"the",
"method",
"called",
"by",
"the",
"plugin",
"every",
"time",
"it",
"retrieves",
"metrics",
"from",
"the",
"API",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/statsd/statsd.go#L67-L86 |
10,757 | dcos/dcos-metrics | plugins/statsd/statsd.go | emitDatapointsOverStatsd | func emitDatapointsOverStatsd(datapoints []producers.Datapoint, client *statsd.StatsdClient) error {
data := make(map[string]string)
for _, dp := range datapoints {
name, val, ok := convertDatapointToStatsd(dp)
// we silently drop metrics which could not be converted
if ok {
data[name] = val
}
}
client.Send(data, 1)
return nil
} | go | func emitDatapointsOverStatsd(datapoints []producers.Datapoint, client *statsd.StatsdClient) error {
data := make(map[string]string)
for _, dp := range datapoints {
name, val, ok := convertDatapointToStatsd(dp)
// we silently drop metrics which could not be converted
if ok {
data[name] = val
}
}
client.Send(data, 1)
return nil
} | [
"func",
"emitDatapointsOverStatsd",
"(",
"datapoints",
"[",
"]",
"producers",
".",
"Datapoint",
",",
"client",
"*",
"statsd",
".",
"StatsdClient",
")",
"error",
"{",
"data",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"dp",
":=",
"range",
"datapoints",
"{",
"name",
",",
"val",
",",
"ok",
":=",
"convertDatapointToStatsd",
"(",
"dp",
")",
"\n",
"// we silently drop metrics which could not be converted",
"if",
"ok",
"{",
"data",
"[",
"name",
"]",
"=",
"val",
"\n",
"}",
"\n",
"}",
"\n",
"client",
".",
"Send",
"(",
"data",
",",
"1",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // emitDatapointsOverStatsd converts datapoints to statsd format and dispatches
// them in a batch to the statsd server | [
"emitDatapointsOverStatsd",
"converts",
"datapoints",
"to",
"statsd",
"format",
"and",
"dispatches",
"them",
"in",
"a",
"batch",
"to",
"the",
"statsd",
"server"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/statsd/statsd.go#L90-L101 |
10,758 | dcos/dcos-metrics | plugins/statsd/statsd.go | convertDatapointToStatsd | func convertDatapointToStatsd(datapoint producers.Datapoint) (string, string, bool) {
val, err := normalize(datapoint.Value)
if err != nil {
// This is only debug-level because we expect many NaNs in regular usage
log.Debugf("Metric %s failed to convert: %q", datapoint.Name, err)
return "", "", false
}
return datapoint.Name, fmt.Sprintf("%d|g", val), true
} | go | func convertDatapointToStatsd(datapoint producers.Datapoint) (string, string, bool) {
val, err := normalize(datapoint.Value)
if err != nil {
// This is only debug-level because we expect many NaNs in regular usage
log.Debugf("Metric %s failed to convert: %q", datapoint.Name, err)
return "", "", false
}
return datapoint.Name, fmt.Sprintf("%d|g", val), true
} | [
"func",
"convertDatapointToStatsd",
"(",
"datapoint",
"producers",
".",
"Datapoint",
")",
"(",
"string",
",",
"string",
",",
"bool",
")",
"{",
"val",
",",
"err",
":=",
"normalize",
"(",
"datapoint",
".",
"Value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// This is only debug-level because we expect many NaNs in regular usage",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"datapoint",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"return",
"datapoint",
".",
"Name",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"val",
")",
",",
"true",
"\n",
"}"
] | // convertDatapointToStatsd attempts to convert a datapoint to a statsd format
// name + value, returning a false ok flag if the conversion failed. | [
"convertDatapointToStatsd",
"attempts",
"to",
"convert",
"a",
"datapoint",
"to",
"a",
"statsd",
"format",
"name",
"+",
"value",
"returning",
"a",
"false",
"ok",
"flag",
"if",
"the",
"conversion",
"failed",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/statsd/statsd.go#L105-L113 |
10,759 | dcos/dcos-metrics | plugins/statsd/statsd.go | normalize | func normalize(i interface{}) (int, error) {
switch v := i.(type) {
case int:
return v, nil
case int32:
return int(v), nil
case int64:
return int(v), nil
case float32:
return int(v + 0.5), nil
case float64:
// We need this check here because NaN can be a float. Casting NaN to
// int results in a large negative number. Even after you add 0.5.
if math.IsNaN(v) {
return -1, fmt.Errorf("Could not normalize NaN %v", v)
}
return int(v + 0.5), nil
case string:
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return -1, err
}
return normalize(f)
default:
return -1, fmt.Errorf("Could not normalize %q", v)
}
} | go | func normalize(i interface{}) (int, error) {
switch v := i.(type) {
case int:
return v, nil
case int32:
return int(v), nil
case int64:
return int(v), nil
case float32:
return int(v + 0.5), nil
case float64:
// We need this check here because NaN can be a float. Casting NaN to
// int results in a large negative number. Even after you add 0.5.
if math.IsNaN(v) {
return -1, fmt.Errorf("Could not normalize NaN %v", v)
}
return int(v + 0.5), nil
case string:
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return -1, err
}
return normalize(f)
default:
return -1, fmt.Errorf("Could not normalize %q", v)
}
} | [
"func",
"normalize",
"(",
"i",
"interface",
"{",
"}",
")",
"(",
"int",
",",
"error",
")",
"{",
"switch",
"v",
":=",
"i",
".",
"(",
"type",
")",
"{",
"case",
"int",
":",
"return",
"v",
",",
"nil",
"\n",
"case",
"int32",
":",
"return",
"int",
"(",
"v",
")",
",",
"nil",
"\n",
"case",
"int64",
":",
"return",
"int",
"(",
"v",
")",
",",
"nil",
"\n",
"case",
"float32",
":",
"return",
"int",
"(",
"v",
"+",
"0.5",
")",
",",
"nil",
"\n",
"case",
"float64",
":",
"// We need this check here because NaN can be a float. Casting NaN to",
"// int results in a large negative number. Even after you add 0.5.",
"if",
"math",
".",
"IsNaN",
"(",
"v",
")",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"int",
"(",
"v",
"+",
"0.5",
")",
",",
"nil",
"\n",
"case",
"string",
":",
"f",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"v",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"return",
"normalize",
"(",
"f",
")",
"\n",
"default",
":",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"}"
] | // normalize converts ints, floats and strings to rounded ints
// It errors on other types and NaNs. | [
"normalize",
"converts",
"ints",
"floats",
"and",
"strings",
"to",
"rounded",
"ints",
"It",
"errors",
"on",
"other",
"types",
"and",
"NaNs",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/statsd/statsd.go#L117-L143 |
10,760 | dcos/dcos-metrics | collectors/framework/framework.go | New | func New(cfg Collector, nodeInfo collectors.NodeInfo, ctr *mesosAgent.ContainerTaskRels) (Collector, chan producers.MetricsMessage) {
c := cfg
c.nodeInfo = nodeInfo
c.metricsChan = make(chan producers.MetricsMessage)
c.containerTaskRels = ctr
return c, c.metricsChan
} | go | func New(cfg Collector, nodeInfo collectors.NodeInfo, ctr *mesosAgent.ContainerTaskRels) (Collector, chan producers.MetricsMessage) {
c := cfg
c.nodeInfo = nodeInfo
c.metricsChan = make(chan producers.MetricsMessage)
c.containerTaskRels = ctr
return c, c.metricsChan
} | [
"func",
"New",
"(",
"cfg",
"Collector",
",",
"nodeInfo",
"collectors",
".",
"NodeInfo",
",",
"ctr",
"*",
"mesosAgent",
".",
"ContainerTaskRels",
")",
"(",
"Collector",
",",
"chan",
"producers",
".",
"MetricsMessage",
")",
"{",
"c",
":=",
"cfg",
"\n",
"c",
".",
"nodeInfo",
"=",
"nodeInfo",
"\n",
"c",
".",
"metricsChan",
"=",
"make",
"(",
"chan",
"producers",
".",
"MetricsMessage",
")",
"\n",
"c",
".",
"containerTaskRels",
"=",
"ctr",
"\n",
"return",
"c",
",",
"c",
".",
"metricsChan",
"\n",
"}"
] | // New returns a new instance of the framework collector. | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"the",
"framework",
"collector",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/framework/framework.go#L71-L77 |
10,761 | dcos/dcos-metrics | collectors/framework/framework.go | RunFrameworkTCPListener | func (c *Collector) RunFrameworkTCPListener() {
fwColLog.Info("Starting TCP listener for framework metric collection")
addr, err := net.ResolveTCPAddr("tcp", c.ListenEndpointFlag)
if err != nil {
fwColLog.Errorf("Failed to parse TCP endpoint '%s': %s", c.ListenEndpointFlag, err)
}
fwColLog.Debugf("Attempting to bind on %+v", addr)
sock, err := net.ListenTCP("tcp", addr)
if err != nil {
fwColLog.Errorf("Failed to listen on TCP endpoint '%s': %s", c.ListenEndpointFlag, err)
}
for {
fwColLog.Debug("Waiting for connections from Mesos Metrics Module...")
conn, err := sock.Accept()
if err != nil {
fwColLog.Errorf("Failed to accept connection on TCP endpoint '%s': %s\n", c.ListenEndpointFlag, err)
continue
}
fwColLog.Infof("Launching handler for TCP connection from: %+v", conn.RemoteAddr())
go c.handleConnection(conn)
}
} | go | func (c *Collector) RunFrameworkTCPListener() {
fwColLog.Info("Starting TCP listener for framework metric collection")
addr, err := net.ResolveTCPAddr("tcp", c.ListenEndpointFlag)
if err != nil {
fwColLog.Errorf("Failed to parse TCP endpoint '%s': %s", c.ListenEndpointFlag, err)
}
fwColLog.Debugf("Attempting to bind on %+v", addr)
sock, err := net.ListenTCP("tcp", addr)
if err != nil {
fwColLog.Errorf("Failed to listen on TCP endpoint '%s': %s", c.ListenEndpointFlag, err)
}
for {
fwColLog.Debug("Waiting for connections from Mesos Metrics Module...")
conn, err := sock.Accept()
if err != nil {
fwColLog.Errorf("Failed to accept connection on TCP endpoint '%s': %s\n", c.ListenEndpointFlag, err)
continue
}
fwColLog.Infof("Launching handler for TCP connection from: %+v", conn.RemoteAddr())
go c.handleConnection(conn)
}
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"RunFrameworkTCPListener",
"(",
")",
"{",
"fwColLog",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"addr",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"\"",
"\"",
",",
"c",
".",
"ListenEndpointFlag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"ListenEndpointFlag",
",",
"err",
")",
"\n",
"}",
"\n",
"fwColLog",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"sock",
",",
"err",
":=",
"net",
".",
"ListenTCP",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"ListenEndpointFlag",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"{",
"fwColLog",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"conn",
",",
"err",
":=",
"sock",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"c",
".",
"ListenEndpointFlag",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"fwColLog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"go",
"c",
".",
"handleConnection",
"(",
"conn",
")",
"\n",
"}",
"\n",
"}"
] | // RunFrameworkTCPListener runs a TCP socket listener which produces Avro
// records sent to that socket. Expects input which has been formatted in the
// Avro ODF standard. This function should be run as a gofunc. | [
"RunFrameworkTCPListener",
"runs",
"a",
"TCP",
"socket",
"listener",
"which",
"produces",
"Avro",
"records",
"sent",
"to",
"that",
"socket",
".",
"Expects",
"input",
"which",
"has",
"been",
"formatted",
"in",
"the",
"Avro",
"ODF",
"standard",
".",
"This",
"function",
"should",
"be",
"run",
"as",
"a",
"gofunc",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/framework/framework.go#L82-L103 |
10,762 | dcos/dcos-metrics | collectors/framework/framework.go | handleConnection | func (c *Collector) handleConnection(conn net.Conn) {
defer conn.Close()
reader := &countingReader{conn, 0}
avroReader, err := goavro.NewReader(goavro.FromReader(reader))
if err != nil {
fwColLog.Errorf("Failed to create avro reader: %s", err)
return // close connection
}
defer func() {
if err := avroReader.Close(); err != nil {
fwColLog.Errorf("Failed to close avro reader: %s", err)
}
}()
nextInputResetTime := time.Now().Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
var lastBytesCount int64
var recordCount int64
for {
lastBytesCount = reader.inputBytes
// Wait for records to be available:
if !avroReader.Scan() {
// Stream closed, exit
break
}
datum, err := avroReader.Read()
if err != nil {
fwColLog.Errorf("Cannot read avro record from %+v: %s\n", conn.RemoteAddr(), err)
continue
}
// TODO(roger): !ok
topic, _ := getTopic(datum)
// increment counters before reader.inputBytes is modified too much
// NOTE: inputBytes is effectively being modified by a gofunc in avroReader, so it's not a perfect measurement
recordCount++
approxBytesRead := reader.inputBytes - lastBytesCount
// reset throttle counter if needed, before enforcing it below
// ideally we'd use a ticker for this, but the goavro api already requires we use manual polling
now := time.Now()
if now.After(nextInputResetTime) {
// Limit period has transpired, reset limit count before continuing
// TODO(MALNICK) Don't case like this...
if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds. "+
"Of this, ~%d KB was dropped due to throttling.\n",
recordCount,
reader.inputBytes/1024,
conn.RemoteAddr(),
c.InputLimitPeriodFlag,
// TODO (MALNICK) don't cast like this..
reader.inputBytes/1024-int64(c.InputLimitAmountKBytesFlag))
} else {
fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds\n",
recordCount, reader.inputBytes/1024, conn.RemoteAddr(), c.InputLimitPeriodFlag)
}
recordCount = 0
reader.inputBytes = 0
nextInputResetTime = now.Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
}
// TODO (MALNICK) Don't cast like this
if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
// input limit reached, skip
continue
}
ad := &AvroDatum{datum, topic, approxBytesRead}
pmm, err := ad.transform(c.nodeInfo, c.containerTaskRels)
if err != nil {
fwColLog.Error(err)
}
c.metricsChan <- pmm
}
} | go | func (c *Collector) handleConnection(conn net.Conn) {
defer conn.Close()
reader := &countingReader{conn, 0}
avroReader, err := goavro.NewReader(goavro.FromReader(reader))
if err != nil {
fwColLog.Errorf("Failed to create avro reader: %s", err)
return // close connection
}
defer func() {
if err := avroReader.Close(); err != nil {
fwColLog.Errorf("Failed to close avro reader: %s", err)
}
}()
nextInputResetTime := time.Now().Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
var lastBytesCount int64
var recordCount int64
for {
lastBytesCount = reader.inputBytes
// Wait for records to be available:
if !avroReader.Scan() {
// Stream closed, exit
break
}
datum, err := avroReader.Read()
if err != nil {
fwColLog.Errorf("Cannot read avro record from %+v: %s\n", conn.RemoteAddr(), err)
continue
}
// TODO(roger): !ok
topic, _ := getTopic(datum)
// increment counters before reader.inputBytes is modified too much
// NOTE: inputBytes is effectively being modified by a gofunc in avroReader, so it's not a perfect measurement
recordCount++
approxBytesRead := reader.inputBytes - lastBytesCount
// reset throttle counter if needed, before enforcing it below
// ideally we'd use a ticker for this, but the goavro api already requires we use manual polling
now := time.Now()
if now.After(nextInputResetTime) {
// Limit period has transpired, reset limit count before continuing
// TODO(MALNICK) Don't case like this...
if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds. "+
"Of this, ~%d KB was dropped due to throttling.\n",
recordCount,
reader.inputBytes/1024,
conn.RemoteAddr(),
c.InputLimitPeriodFlag,
// TODO (MALNICK) don't cast like this..
reader.inputBytes/1024-int64(c.InputLimitAmountKBytesFlag))
} else {
fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds\n",
recordCount, reader.inputBytes/1024, conn.RemoteAddr(), c.InputLimitPeriodFlag)
}
recordCount = 0
reader.inputBytes = 0
nextInputResetTime = now.Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
}
// TODO (MALNICK) Don't cast like this
if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
// input limit reached, skip
continue
}
ad := &AvroDatum{datum, topic, approxBytesRead}
pmm, err := ad.transform(c.nodeInfo, c.containerTaskRels)
if err != nil {
fwColLog.Error(err)
}
c.metricsChan <- pmm
}
} | [
"func",
"(",
"c",
"*",
"Collector",
")",
"handleConnection",
"(",
"conn",
"net",
".",
"Conn",
")",
"{",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"reader",
":=",
"&",
"countingReader",
"{",
"conn",
",",
"0",
"}",
"\n",
"avroReader",
",",
"err",
":=",
"goavro",
".",
"NewReader",
"(",
"goavro",
".",
"FromReader",
"(",
"reader",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"// close connection",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"avroReader",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"nextInputResetTime",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"c",
".",
"InputLimitPeriodFlag",
")",
")",
"\n",
"var",
"lastBytesCount",
"int64",
"\n",
"var",
"recordCount",
"int64",
"\n",
"for",
"{",
"lastBytesCount",
"=",
"reader",
".",
"inputBytes",
"\n",
"// Wait for records to be available:",
"if",
"!",
"avroReader",
".",
"Scan",
"(",
")",
"{",
"// Stream closed, exit",
"break",
"\n",
"}",
"\n",
"datum",
",",
"err",
":=",
"avroReader",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// TODO(roger): !ok",
"topic",
",",
"_",
":=",
"getTopic",
"(",
"datum",
")",
"\n\n",
"// increment counters before reader.inputBytes is modified too much",
"// NOTE: inputBytes is effectively being modified by a gofunc in avroReader, so it's not a perfect measurement",
"recordCount",
"++",
"\n",
"approxBytesRead",
":=",
"reader",
".",
"inputBytes",
"-",
"lastBytesCount",
"\n\n",
"// reset throttle counter if needed, before enforcing it below",
"// ideally we'd use a ticker for this, but the goavro api already requires we use manual polling",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"now",
".",
"After",
"(",
"nextInputResetTime",
")",
"{",
"// Limit period has transpired, reset limit count before continuing",
"// TODO(MALNICK) Don't case like this...",
"if",
"reader",
".",
"inputBytes",
">",
"int64",
"(",
"c",
".",
"InputLimitAmountKBytesFlag",
")",
"*",
"1024",
"{",
"fwColLog",
".",
"Debugf",
"(",
"\"",
"\"",
"+",
"\"",
"\\n",
"\"",
",",
"recordCount",
",",
"reader",
".",
"inputBytes",
"/",
"1024",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
",",
"c",
".",
"InputLimitPeriodFlag",
",",
"// TODO (MALNICK) don't cast like this..",
"reader",
".",
"inputBytes",
"/",
"1024",
"-",
"int64",
"(",
"c",
".",
"InputLimitAmountKBytesFlag",
")",
")",
"\n",
"}",
"else",
"{",
"fwColLog",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"recordCount",
",",
"reader",
".",
"inputBytes",
"/",
"1024",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
",",
"c",
".",
"InputLimitPeriodFlag",
")",
"\n",
"}",
"\n",
"recordCount",
"=",
"0",
"\n",
"reader",
".",
"inputBytes",
"=",
"0",
"\n",
"nextInputResetTime",
"=",
"now",
".",
"Add",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"c",
".",
"InputLimitPeriodFlag",
")",
")",
"\n",
"}",
"\n\n",
"// TODO (MALNICK) Don't cast like this",
"if",
"reader",
".",
"inputBytes",
">",
"int64",
"(",
"c",
".",
"InputLimitAmountKBytesFlag",
")",
"*",
"1024",
"{",
"// input limit reached, skip",
"continue",
"\n",
"}",
"\n\n",
"ad",
":=",
"&",
"AvroDatum",
"{",
"datum",
",",
"topic",
",",
"approxBytesRead",
"}",
"\n",
"pmm",
",",
"err",
":=",
"ad",
".",
"transform",
"(",
"c",
".",
"nodeInfo",
",",
"c",
".",
"containerTaskRels",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fwColLog",
".",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"c",
".",
"metricsChan",
"<-",
"pmm",
"\n",
"}",
"\n",
"}"
] | // handleConnection reads records from a TCP session.
// This function should be run as a gofunc. | [
"handleConnection",
"reads",
"records",
"from",
"a",
"TCP",
"session",
".",
"This",
"function",
"should",
"be",
"run",
"as",
"a",
"gofunc",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/framework/framework.go#L107-L182 |
10,763 | dcos/dcos-metrics | collectors/framework/framework.go | getTopic | func getTopic(obj interface{}) (string, bool) {
record, ok := obj.(*goavro.Record)
if !ok {
return "UNKNOWN_RECORD_TYPE", false
}
topicObj, err := record.Get("topic")
if err != nil {
return "UNKNOWN_TOPIC_VAL", false
}
topicStr, ok := topicObj.(string)
if !ok {
return "UNKNOWN_TOPIC_TYPE", false
}
return topicStr, true
} | go | func getTopic(obj interface{}) (string, bool) {
record, ok := obj.(*goavro.Record)
if !ok {
return "UNKNOWN_RECORD_TYPE", false
}
topicObj, err := record.Get("topic")
if err != nil {
return "UNKNOWN_TOPIC_VAL", false
}
topicStr, ok := topicObj.(string)
if !ok {
return "UNKNOWN_TOPIC_TYPE", false
}
return topicStr, true
} | [
"func",
"getTopic",
"(",
"obj",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"bool",
")",
"{",
"record",
",",
"ok",
":=",
"obj",
".",
"(",
"*",
"goavro",
".",
"Record",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"topicObj",
",",
"err",
":=",
"record",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"topicStr",
",",
"ok",
":=",
"topicObj",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}",
"\n",
"return",
"topicStr",
",",
"true",
"\n",
"}"
] | // getTopic returns the requested topic from an Avro record. | [
"getTopic",
"returns",
"the",
"requested",
"topic",
"from",
"an",
"Avro",
"record",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/framework/framework.go#L292-L306 |
10,764 | dcos/dcos-metrics | plugins/option.go | ExtraFlags | func ExtraFlags(extraFlags []cli.Flag) Option {
return func(p *Plugin) error {
for _, f := range extraFlags {
p.App.Flags = append(p.App.Flags, f)
}
return nil
}
} | go | func ExtraFlags(extraFlags []cli.Flag) Option {
return func(p *Plugin) error {
for _, f := range extraFlags {
p.App.Flags = append(p.App.Flags, f)
}
return nil
}
} | [
"func",
"ExtraFlags",
"(",
"extraFlags",
"[",
"]",
"cli",
".",
"Flag",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"error",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"extraFlags",
"{",
"p",
".",
"App",
".",
"Flags",
"=",
"append",
"(",
"p",
".",
"App",
".",
"Flags",
",",
"f",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // ExtraFlags sets additional cli.Flag's on the Plugin | [
"ExtraFlags",
"sets",
"additional",
"cli",
".",
"Flag",
"s",
"on",
"the",
"Plugin"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/option.go#L28-L35 |
10,765 | dcos/dcos-metrics | plugins/option.go | PollingInterval | func PollingInterval(i int) Option {
return func(p *Plugin) error {
p.PollingInterval = i
return nil
}
} | go | func PollingInterval(i int) Option {
return func(p *Plugin) error {
p.PollingInterval = i
return nil
}
} | [
"func",
"PollingInterval",
"(",
"i",
"int",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"error",
"{",
"p",
".",
"PollingInterval",
"=",
"i",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // PollingInterval sets the polling interval to the supplied value. | [
"PollingInterval",
"sets",
"the",
"polling",
"interval",
"to",
"the",
"supplied",
"value",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/option.go#L38-L43 |
10,766 | dcos/dcos-metrics | plugins/option.go | ConnectorFunc | func ConnectorFunc(connect func([]producers.MetricsMessage, *cli.Context) error) Option {
return func(p *Plugin) error {
p.ConnectorFunc = connect
return nil
}
} | go | func ConnectorFunc(connect func([]producers.MetricsMessage, *cli.Context) error) Option {
return func(p *Plugin) error {
p.ConnectorFunc = connect
return nil
}
} | [
"func",
"ConnectorFunc",
"(",
"connect",
"func",
"(",
"[",
"]",
"producers",
".",
"MetricsMessage",
",",
"*",
"cli",
".",
"Context",
")",
"error",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"error",
"{",
"p",
".",
"ConnectorFunc",
"=",
"connect",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // ConnectorFunc is what the plugin framework will call once it has gathered
// metrics. It is expected that this function will convert these messages to
// a 3rd party format and then send the metrics to that service. | [
"ConnectorFunc",
"is",
"what",
"the",
"plugin",
"framework",
"will",
"call",
"once",
"it",
"has",
"gathered",
"metrics",
".",
"It",
"is",
"expected",
"that",
"this",
"function",
"will",
"convert",
"these",
"messages",
"to",
"a",
"3rd",
"party",
"format",
"and",
"then",
"send",
"the",
"metrics",
"to",
"that",
"service",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/option.go#L48-L53 |
10,767 | dcos/dcos-metrics | plugins/option.go | Name | func Name(n string) Option {
return func(p *Plugin) error {
p.Name = n
return nil
}
} | go | func Name(n string) Option {
return func(p *Plugin) error {
p.Name = n
return nil
}
} | [
"func",
"Name",
"(",
"n",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"error",
"{",
"p",
".",
"Name",
"=",
"n",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Name allows the plugin to set a custom name for itself. | [
"Name",
"allows",
"the",
"plugin",
"to",
"set",
"a",
"custom",
"name",
"for",
"itself",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/plugins/option.go#L56-L61 |
10,768 | dcos/dcos-metrics | dcos-metrics.go | broadcast | func broadcast(msg producers.MetricsMessage, producers []chan<- producers.MetricsMessage) {
for _, producer := range producers {
producer <- msg
}
} | go | func broadcast(msg producers.MetricsMessage, producers []chan<- producers.MetricsMessage) {
for _, producer := range producers {
producer <- msg
}
} | [
"func",
"broadcast",
"(",
"msg",
"producers",
".",
"MetricsMessage",
",",
"producers",
"[",
"]",
"chan",
"<-",
"producers",
".",
"MetricsMessage",
")",
"{",
"for",
"_",
",",
"producer",
":=",
"range",
"producers",
"{",
"producer",
"<-",
"msg",
"\n",
"}",
"\n",
"}"
] | // broadcast sends a MetricsMessage to a range of producer chans | [
"broadcast",
"sends",
"a",
"MetricsMessage",
"to",
"a",
"range",
"of",
"producer",
"chans"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/dcos-metrics.go#L110-L114 |
10,769 | dcos/dcos-metrics | collectors/node/cpu.go | calculatePcts | func calculatePcts(lastTimes cpu.TimesStat, curTimes cpu.TimesStat) cpu.TimesStat {
totalDelta := curTimes.Total() - lastTimes.Total()
return cpu.TimesStat{
User: formatPct(curTimes.User-lastTimes.User, totalDelta),
System: formatPct(curTimes.System-lastTimes.System, totalDelta),
Idle: formatPct(curTimes.Idle-lastTimes.Idle, totalDelta),
Nice: formatPct(curTimes.Nice-lastTimes.Nice, totalDelta),
Iowait: formatPct(curTimes.Iowait-lastTimes.Iowait, totalDelta),
Irq: formatPct(curTimes.Irq-lastTimes.Irq, totalDelta),
Softirq: formatPct(curTimes.Softirq-lastTimes.Softirq, totalDelta),
Steal: formatPct(curTimes.Steal-lastTimes.Steal, totalDelta),
Guest: formatPct(curTimes.Guest-lastTimes.Guest, totalDelta),
GuestNice: formatPct(curTimes.GuestNice-lastTimes.GuestNice, totalDelta),
Stolen: formatPct(curTimes.Stolen-lastTimes.Stolen, totalDelta),
}
} | go | func calculatePcts(lastTimes cpu.TimesStat, curTimes cpu.TimesStat) cpu.TimesStat {
totalDelta := curTimes.Total() - lastTimes.Total()
return cpu.TimesStat{
User: formatPct(curTimes.User-lastTimes.User, totalDelta),
System: formatPct(curTimes.System-lastTimes.System, totalDelta),
Idle: formatPct(curTimes.Idle-lastTimes.Idle, totalDelta),
Nice: formatPct(curTimes.Nice-lastTimes.Nice, totalDelta),
Iowait: formatPct(curTimes.Iowait-lastTimes.Iowait, totalDelta),
Irq: formatPct(curTimes.Irq-lastTimes.Irq, totalDelta),
Softirq: formatPct(curTimes.Softirq-lastTimes.Softirq, totalDelta),
Steal: formatPct(curTimes.Steal-lastTimes.Steal, totalDelta),
Guest: formatPct(curTimes.Guest-lastTimes.Guest, totalDelta),
GuestNice: formatPct(curTimes.GuestNice-lastTimes.GuestNice, totalDelta),
Stolen: formatPct(curTimes.Stolen-lastTimes.Stolen, totalDelta),
}
} | [
"func",
"calculatePcts",
"(",
"lastTimes",
"cpu",
".",
"TimesStat",
",",
"curTimes",
"cpu",
".",
"TimesStat",
")",
"cpu",
".",
"TimesStat",
"{",
"totalDelta",
":=",
"curTimes",
".",
"Total",
"(",
")",
"-",
"lastTimes",
".",
"Total",
"(",
")",
"\n",
"return",
"cpu",
".",
"TimesStat",
"{",
"User",
":",
"formatPct",
"(",
"curTimes",
".",
"User",
"-",
"lastTimes",
".",
"User",
",",
"totalDelta",
")",
",",
"System",
":",
"formatPct",
"(",
"curTimes",
".",
"System",
"-",
"lastTimes",
".",
"System",
",",
"totalDelta",
")",
",",
"Idle",
":",
"formatPct",
"(",
"curTimes",
".",
"Idle",
"-",
"lastTimes",
".",
"Idle",
",",
"totalDelta",
")",
",",
"Nice",
":",
"formatPct",
"(",
"curTimes",
".",
"Nice",
"-",
"lastTimes",
".",
"Nice",
",",
"totalDelta",
")",
",",
"Iowait",
":",
"formatPct",
"(",
"curTimes",
".",
"Iowait",
"-",
"lastTimes",
".",
"Iowait",
",",
"totalDelta",
")",
",",
"Irq",
":",
"formatPct",
"(",
"curTimes",
".",
"Irq",
"-",
"lastTimes",
".",
"Irq",
",",
"totalDelta",
")",
",",
"Softirq",
":",
"formatPct",
"(",
"curTimes",
".",
"Softirq",
"-",
"lastTimes",
".",
"Softirq",
",",
"totalDelta",
")",
",",
"Steal",
":",
"formatPct",
"(",
"curTimes",
".",
"Steal",
"-",
"lastTimes",
".",
"Steal",
",",
"totalDelta",
")",
",",
"Guest",
":",
"formatPct",
"(",
"curTimes",
".",
"Guest",
"-",
"lastTimes",
".",
"Guest",
",",
"totalDelta",
")",
",",
"GuestNice",
":",
"formatPct",
"(",
"curTimes",
".",
"GuestNice",
"-",
"lastTimes",
".",
"GuestNice",
",",
"totalDelta",
")",
",",
"Stolen",
":",
"formatPct",
"(",
"curTimes",
".",
"Stolen",
"-",
"lastTimes",
".",
"Stolen",
",",
"totalDelta",
")",
",",
"}",
"\n",
"}"
] | // calculatePct returns the percent utilization for CPU states. 100.00 => 100.00% | [
"calculatePct",
"returns",
"the",
"percent",
"utilization",
"for",
"CPU",
"states",
".",
"100",
".",
"00",
"=",
">",
"100",
".",
"00%"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/node/cpu.go#L145-L160 |
10,770 | dcos/dcos-metrics | collectors/mesos/agent/metrics.go | deviceStatsToDatapoints | func deviceStatsToDatapoints(stats []IODeviceStats, prefix string, baseTags map[string]string, ts string) []producers.Datapoint {
var datapoints []producers.Datapoint
for _, stat := range stats {
dev := devTotal
if stat.Device.Major > 0 {
dev = fmt.Sprintf("%d:%d", stat.Device.Major, stat.Device.Minor)
}
// Create a new tags map for these datapoints
tags := map[string]string{blkioDevice: dev}
for k, v := range baseTags {
tags[k] = v
}
datapoints = append(datapoints, statValuesToDatapoints(stat.Serviced, prefix+"."+serviced, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.ServiceBytes, prefix+"."+serviceBytes, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.ServiceTime, prefix+"."+serviceTime, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.Merged, prefix+"."+merged, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.Queued, prefix+"."+queued, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.WaitTime, prefix+"."+waitTime, tags, ts)...)
}
return datapoints
} | go | func deviceStatsToDatapoints(stats []IODeviceStats, prefix string, baseTags map[string]string, ts string) []producers.Datapoint {
var datapoints []producers.Datapoint
for _, stat := range stats {
dev := devTotal
if stat.Device.Major > 0 {
dev = fmt.Sprintf("%d:%d", stat.Device.Major, stat.Device.Minor)
}
// Create a new tags map for these datapoints
tags := map[string]string{blkioDevice: dev}
for k, v := range baseTags {
tags[k] = v
}
datapoints = append(datapoints, statValuesToDatapoints(stat.Serviced, prefix+"."+serviced, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.ServiceBytes, prefix+"."+serviceBytes, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.ServiceTime, prefix+"."+serviceTime, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.Merged, prefix+"."+merged, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.Queued, prefix+"."+queued, tags, ts)...)
datapoints = append(datapoints, statValuesToDatapoints(stat.WaitTime, prefix+"."+waitTime, tags, ts)...)
}
return datapoints
} | [
"func",
"deviceStatsToDatapoints",
"(",
"stats",
"[",
"]",
"IODeviceStats",
",",
"prefix",
"string",
",",
"baseTags",
"map",
"[",
"string",
"]",
"string",
",",
"ts",
"string",
")",
"[",
"]",
"producers",
".",
"Datapoint",
"{",
"var",
"datapoints",
"[",
"]",
"producers",
".",
"Datapoint",
"\n\n",
"for",
"_",
",",
"stat",
":=",
"range",
"stats",
"{",
"dev",
":=",
"devTotal",
"\n",
"if",
"stat",
".",
"Device",
".",
"Major",
">",
"0",
"{",
"dev",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"stat",
".",
"Device",
".",
"Major",
",",
"stat",
".",
"Device",
".",
"Minor",
")",
"\n",
"}",
"\n",
"// Create a new tags map for these datapoints",
"tags",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"blkioDevice",
":",
"dev",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"baseTags",
"{",
"tags",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"Serviced",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"serviced",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"ServiceBytes",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"serviceBytes",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"ServiceTime",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"serviceTime",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"Merged",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"merged",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"Queued",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"queued",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"statValuesToDatapoints",
"(",
"stat",
".",
"WaitTime",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"waitTime",
",",
"tags",
",",
"ts",
")",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"datapoints",
"\n",
"}"
] | // deviceStatsToDatapoints flattens the nested blkio stats into a list of
// clearly-named datapoints. All units are bytes, therefore all values are
// integers. Datapoints from throttled devices are tagged with their origin. | [
"deviceStatsToDatapoints",
"flattens",
"the",
"nested",
"blkio",
"stats",
"into",
"a",
"list",
"of",
"clearly",
"-",
"named",
"datapoints",
".",
"All",
"units",
"are",
"bytes",
"therefore",
"all",
"values",
"are",
"integers",
".",
"Datapoints",
"from",
"throttled",
"devices",
"are",
"tagged",
"with",
"their",
"origin",
"."
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/metrics.go#L294-L316 |
10,771 | dcos/dcos-metrics | collectors/mesos/agent/metrics.go | statValuesToDatapoints | func statValuesToDatapoints(vals []IOStatValue, prefix string, tags map[string]string, ts string) []producers.Datapoint {
var datapoints []producers.Datapoint
for _, s := range vals {
op := strings.ToLower(s.Operation)
d := producers.Datapoint{
Name: prefix + "." + op,
Value: s.Value,
Tags: tags,
Timestamp: ts,
Unit: bytes,
}
datapoints = append(datapoints, d)
}
return datapoints
} | go | func statValuesToDatapoints(vals []IOStatValue, prefix string, tags map[string]string, ts string) []producers.Datapoint {
var datapoints []producers.Datapoint
for _, s := range vals {
op := strings.ToLower(s.Operation)
d := producers.Datapoint{
Name: prefix + "." + op,
Value: s.Value,
Tags: tags,
Timestamp: ts,
Unit: bytes,
}
datapoints = append(datapoints, d)
}
return datapoints
} | [
"func",
"statValuesToDatapoints",
"(",
"vals",
"[",
"]",
"IOStatValue",
",",
"prefix",
"string",
",",
"tags",
"map",
"[",
"string",
"]",
"string",
",",
"ts",
"string",
")",
"[",
"]",
"producers",
".",
"Datapoint",
"{",
"var",
"datapoints",
"[",
"]",
"producers",
".",
"Datapoint",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"vals",
"{",
"op",
":=",
"strings",
".",
"ToLower",
"(",
"s",
".",
"Operation",
")",
"\n",
"d",
":=",
"producers",
".",
"Datapoint",
"{",
"Name",
":",
"prefix",
"+",
"\"",
"\"",
"+",
"op",
",",
"Value",
":",
"s",
".",
"Value",
",",
"Tags",
":",
"tags",
",",
"Timestamp",
":",
"ts",
",",
"Unit",
":",
"bytes",
",",
"}",
"\n",
"datapoints",
"=",
"append",
"(",
"datapoints",
",",
"d",
")",
"\n",
"}",
"\n",
"return",
"datapoints",
"\n",
"}"
] | // statValuesToDatapoints converts a list of IO stats to a list of datapoints | [
"statValuesToDatapoints",
"converts",
"a",
"list",
"of",
"IO",
"stats",
"to",
"a",
"list",
"of",
"datapoints"
] | d56806e5335baf0f12fec2278f9526d77ec0bb1e | https://github.com/dcos/dcos-metrics/blob/d56806e5335baf0f12fec2278f9526d77ec0bb1e/collectors/mesos/agent/metrics.go#L319-L333 |
10,772 | jdxcode/netrc | netrc.go | Parse | func Parse(path string) (*Netrc, error) {
file, err := read(path)
if err != nil {
return nil, err
}
netrc, err := parse(lex(file))
if err != nil {
return nil, err
}
netrc.Path = path
return netrc, nil
} | go | func Parse(path string) (*Netrc, error) {
file, err := read(path)
if err != nil {
return nil, err
}
netrc, err := parse(lex(file))
if err != nil {
return nil, err
}
netrc.Path = path
return netrc, nil
} | [
"func",
"Parse",
"(",
"path",
"string",
")",
"(",
"*",
"Netrc",
",",
"error",
")",
"{",
"file",
",",
"err",
":=",
"read",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"netrc",
",",
"err",
":=",
"parse",
"(",
"lex",
"(",
"file",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"netrc",
".",
"Path",
"=",
"path",
"\n",
"return",
"netrc",
",",
"nil",
"\n",
"}"
] | // Parse the netrc file at the given path
// It returns a Netrc instance | [
"Parse",
"the",
"netrc",
"file",
"at",
"the",
"given",
"path",
"It",
"returns",
"a",
"Netrc",
"instance"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L35-L46 |
10,773 | jdxcode/netrc | netrc.go | Machine | func (n *Netrc) Machine(name string) *Machine {
for _, m := range n.machines {
if m.Name == name {
return m
}
}
return nil
} | go | func (n *Netrc) Machine(name string) *Machine {
for _, m := range n.machines {
if m.Name == name {
return m
}
}
return nil
} | [
"func",
"(",
"n",
"*",
"Netrc",
")",
"Machine",
"(",
"name",
"string",
")",
"*",
"Machine",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"n",
".",
"machines",
"{",
"if",
"m",
".",
"Name",
"==",
"name",
"{",
"return",
"m",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Machine gets a machine by name | [
"Machine",
"gets",
"a",
"machine",
"by",
"name"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L49-L56 |
10,774 | jdxcode/netrc | netrc.go | AddMachine | func (n *Netrc) AddMachine(name, login, password string) {
machine := n.Machine(name)
if machine == nil {
machine = &Machine{}
n.machines = append(n.machines, machine)
}
machine.Name = name
machine.tokens = []string{"machine ", name, "\n"}
machine.Set("login", login)
machine.Set("password", password)
} | go | func (n *Netrc) AddMachine(name, login, password string) {
machine := n.Machine(name)
if machine == nil {
machine = &Machine{}
n.machines = append(n.machines, machine)
}
machine.Name = name
machine.tokens = []string{"machine ", name, "\n"}
machine.Set("login", login)
machine.Set("password", password)
} | [
"func",
"(",
"n",
"*",
"Netrc",
")",
"AddMachine",
"(",
"name",
",",
"login",
",",
"password",
"string",
")",
"{",
"machine",
":=",
"n",
".",
"Machine",
"(",
"name",
")",
"\n",
"if",
"machine",
"==",
"nil",
"{",
"machine",
"=",
"&",
"Machine",
"{",
"}",
"\n",
"n",
".",
"machines",
"=",
"append",
"(",
"n",
".",
"machines",
",",
"machine",
")",
"\n",
"}",
"\n",
"machine",
".",
"Name",
"=",
"name",
"\n",
"machine",
".",
"tokens",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"name",
",",
"\"",
"\\n",
"\"",
"}",
"\n",
"machine",
".",
"Set",
"(",
"\"",
"\"",
",",
"login",
")",
"\n",
"machine",
".",
"Set",
"(",
"\"",
"\"",
",",
"password",
")",
"\n",
"}"
] | // AddMachine adds a machine | [
"AddMachine",
"adds",
"a",
"machine"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L59-L69 |
10,775 | jdxcode/netrc | netrc.go | RemoveMachine | func (n *Netrc) RemoveMachine(name string) {
for i, machine := range n.machines {
if machine.Name == name {
n.machines = append(n.machines[:i], n.machines[i+1:]...)
// continue removing but start over since the indexes changed
n.RemoveMachine(name)
return
}
}
} | go | func (n *Netrc) RemoveMachine(name string) {
for i, machine := range n.machines {
if machine.Name == name {
n.machines = append(n.machines[:i], n.machines[i+1:]...)
// continue removing but start over since the indexes changed
n.RemoveMachine(name)
return
}
}
} | [
"func",
"(",
"n",
"*",
"Netrc",
")",
"RemoveMachine",
"(",
"name",
"string",
")",
"{",
"for",
"i",
",",
"machine",
":=",
"range",
"n",
".",
"machines",
"{",
"if",
"machine",
".",
"Name",
"==",
"name",
"{",
"n",
".",
"machines",
"=",
"append",
"(",
"n",
".",
"machines",
"[",
":",
"i",
"]",
",",
"n",
".",
"machines",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"// continue removing but start over since the indexes changed",
"n",
".",
"RemoveMachine",
"(",
"name",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // RemoveMachine remove a machine | [
"RemoveMachine",
"remove",
"a",
"machine"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L72-L81 |
10,776 | jdxcode/netrc | netrc.go | Render | func (n *Netrc) Render() string {
var b bytes.Buffer
for _, token := range n.tokens {
b.WriteString(token)
}
for _, machine := range n.machines {
for _, token := range machine.tokens {
b.WriteString(token)
}
}
return b.String()
} | go | func (n *Netrc) Render() string {
var b bytes.Buffer
for _, token := range n.tokens {
b.WriteString(token)
}
for _, machine := range n.machines {
for _, token := range machine.tokens {
b.WriteString(token)
}
}
return b.String()
} | [
"func",
"(",
"n",
"*",
"Netrc",
")",
"Render",
"(",
")",
"string",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"token",
":=",
"range",
"n",
".",
"tokens",
"{",
"b",
".",
"WriteString",
"(",
"token",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"machine",
":=",
"range",
"n",
".",
"machines",
"{",
"for",
"_",
",",
"token",
":=",
"range",
"machine",
".",
"tokens",
"{",
"b",
".",
"WriteString",
"(",
"token",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"b",
".",
"String",
"(",
")",
"\n",
"}"
] | // Render out the netrc file to a string | [
"Render",
"out",
"the",
"netrc",
"file",
"to",
"a",
"string"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L84-L95 |
10,777 | jdxcode/netrc | netrc.go | Save | func (n *Netrc) Save() error {
body := []byte(n.Render())
if filepath.Ext(n.Path) == ".gpg" {
cmd := exec.Command("gpg", "-a", "--batch", "--default-recipient-self", "-e")
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdin.Write(body)
stdin.Close()
cmd.Stderr = os.Stderr
body, err = cmd.Output()
if err != nil {
return err
}
}
return ioutil.WriteFile(n.Path, body, 0600)
} | go | func (n *Netrc) Save() error {
body := []byte(n.Render())
if filepath.Ext(n.Path) == ".gpg" {
cmd := exec.Command("gpg", "-a", "--batch", "--default-recipient-self", "-e")
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdin.Write(body)
stdin.Close()
cmd.Stderr = os.Stderr
body, err = cmd.Output()
if err != nil {
return err
}
}
return ioutil.WriteFile(n.Path, body, 0600)
} | [
"func",
"(",
"n",
"*",
"Netrc",
")",
"Save",
"(",
")",
"error",
"{",
"body",
":=",
"[",
"]",
"byte",
"(",
"n",
".",
"Render",
"(",
")",
")",
"\n",
"if",
"filepath",
".",
"Ext",
"(",
"n",
".",
"Path",
")",
"==",
"\"",
"\"",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"stdin",
",",
"err",
":=",
"cmd",
".",
"StdinPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"stdin",
".",
"Write",
"(",
"body",
")",
"\n",
"stdin",
".",
"Close",
"(",
")",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"body",
",",
"err",
"=",
"cmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"n",
".",
"Path",
",",
"body",
",",
"0600",
")",
"\n",
"}"
] | // Save the file to disk | [
"Save",
"the",
"file",
"to",
"disk"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L98-L115 |
10,778 | jdxcode/netrc | netrc.go | Get | func (m *Machine) Get(name string) string {
i := 4
if m.IsDefault {
i = 2
}
for {
if i+2 >= len(m.tokens) {
return ""
}
if m.tokens[i] == name {
return m.tokens[i+2]
}
i = i + 4
}
} | go | func (m *Machine) Get(name string) string {
i := 4
if m.IsDefault {
i = 2
}
for {
if i+2 >= len(m.tokens) {
return ""
}
if m.tokens[i] == name {
return m.tokens[i+2]
}
i = i + 4
}
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Get",
"(",
"name",
"string",
")",
"string",
"{",
"i",
":=",
"4",
"\n",
"if",
"m",
".",
"IsDefault",
"{",
"i",
"=",
"2",
"\n",
"}",
"\n",
"for",
"{",
"if",
"i",
"+",
"2",
">=",
"len",
"(",
"m",
".",
"tokens",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"m",
".",
"tokens",
"[",
"i",
"]",
"==",
"name",
"{",
"return",
"m",
".",
"tokens",
"[",
"i",
"+",
"2",
"]",
"\n",
"}",
"\n",
"i",
"=",
"i",
"+",
"4",
"\n",
"}",
"\n",
"}"
] | // Get a property from a machine | [
"Get",
"a",
"property",
"from",
"a",
"machine"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L208-L222 |
10,779 | jdxcode/netrc | netrc.go | Set | func (m *Machine) Set(name, value string) {
i := 4
if m.IsDefault {
i = 2
}
for i+2 < len(m.tokens) {
if m.tokens[i] == name {
m.tokens[i+2] = value
return
}
i = i + 4
}
m.tokens = append(m.tokens, " ", name, " ", value, "\n")
} | go | func (m *Machine) Set(name, value string) {
i := 4
if m.IsDefault {
i = 2
}
for i+2 < len(m.tokens) {
if m.tokens[i] == name {
m.tokens[i+2] = value
return
}
i = i + 4
}
m.tokens = append(m.tokens, " ", name, " ", value, "\n")
} | [
"func",
"(",
"m",
"*",
"Machine",
")",
"Set",
"(",
"name",
",",
"value",
"string",
")",
"{",
"i",
":=",
"4",
"\n",
"if",
"m",
".",
"IsDefault",
"{",
"i",
"=",
"2",
"\n",
"}",
"\n",
"for",
"i",
"+",
"2",
"<",
"len",
"(",
"m",
".",
"tokens",
")",
"{",
"if",
"m",
".",
"tokens",
"[",
"i",
"]",
"==",
"name",
"{",
"m",
".",
"tokens",
"[",
"i",
"+",
"2",
"]",
"=",
"value",
"\n",
"return",
"\n",
"}",
"\n",
"i",
"=",
"i",
"+",
"4",
"\n",
"}",
"\n",
"m",
".",
"tokens",
"=",
"append",
"(",
"m",
".",
"tokens",
",",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
",",
"value",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] | // Set a property on the machine | [
"Set",
"a",
"property",
"on",
"the",
"machine"
] | b36f1c51d91d72f03887952fff1a6be7f700da0d | https://github.com/jdxcode/netrc/blob/b36f1c51d91d72f03887952fff1a6be7f700da0d/netrc.go#L225-L238 |
10,780 | cloudfoundry/cfhttp | v2/client.go | WithStreamingDefaults | func WithStreamingDefaults() Option {
return func(c *config) {
c.tcpKeepAliveTimeout = 30 * time.Second
c.disableKeepAlives = false
c.requestTimeout = 0
}
} | go | func WithStreamingDefaults() Option {
return func(c *config) {
c.tcpKeepAliveTimeout = 30 * time.Second
c.disableKeepAlives = false
c.requestTimeout = 0
}
} | [
"func",
"WithStreamingDefaults",
"(",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"tcpKeepAliveTimeout",
"=",
"30",
"*",
"time",
".",
"Second",
"\n",
"c",
".",
"disableKeepAlives",
"=",
"false",
"\n",
"c",
".",
"requestTimeout",
"=",
"0",
"\n",
"}",
"\n",
"}"
] | // WithStreamingDefaults modifies the HTTP client with defaults that are more
// suitable for consuming server-sent events on persistent connections. | [
"WithStreamingDefaults",
"modifies",
"the",
"HTTP",
"client",
"with",
"defaults",
"that",
"are",
"more",
"suitable",
"for",
"consuming",
"server",
"-",
"sent",
"events",
"on",
"persistent",
"connections",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L29-L35 |
10,781 | cloudfoundry/cfhttp | v2/client.go | WithRequestTimeout | func WithRequestTimeout(t time.Duration) Option {
return func(c *config) {
c.requestTimeout = t
}
} | go | func WithRequestTimeout(t time.Duration) Option {
return func(c *config) {
c.requestTimeout = t
}
} | [
"func",
"WithRequestTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"requestTimeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithRequestTimeout sets the total time limit for requests made by this Client.
//
// A setting of 0 means no timeout. | [
"WithRequestTimeout",
"sets",
"the",
"total",
"time",
"limit",
"for",
"requests",
"made",
"by",
"this",
"Client",
".",
"A",
"setting",
"of",
"0",
"means",
"no",
"timeout",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L40-L44 |
10,782 | cloudfoundry/cfhttp | v2/client.go | WithDialTimeout | func WithDialTimeout(t time.Duration) Option {
return func(c *config) {
c.dialTimeout = t
}
} | go | func WithDialTimeout(t time.Duration) Option {
return func(c *config) {
c.dialTimeout = t
}
} | [
"func",
"WithDialTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"dialTimeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithDialTimeout sets the time limit for connecting to the remote address. This
// includes DNS resolution and retries on multiple IP addresses.
//
// A setting of 0 means no timeout. | [
"WithDialTimeout",
"sets",
"the",
"time",
"limit",
"for",
"connecting",
"to",
"the",
"remote",
"address",
".",
"This",
"includes",
"DNS",
"resolution",
"and",
"retries",
"on",
"multiple",
"IP",
"addresses",
".",
"A",
"setting",
"of",
"0",
"means",
"no",
"timeout",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L50-L54 |
10,783 | cloudfoundry/cfhttp | v2/client.go | WithTCPKeepAliveTimeout | func WithTCPKeepAliveTimeout(t time.Duration) Option {
return func(c *config) {
c.tcpKeepAliveTimeout = t
}
} | go | func WithTCPKeepAliveTimeout(t time.Duration) Option {
return func(c *config) {
c.tcpKeepAliveTimeout = t
}
} | [
"func",
"WithTCPKeepAliveTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"tcpKeepAliveTimeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithTCPKeepAliveTimeout sets the keep-alive period for an active TCP
// connection.
//
// A setting of 0 disables TCP keep-alives. | [
"WithTCPKeepAliveTimeout",
"sets",
"the",
"keep",
"-",
"alive",
"period",
"for",
"an",
"active",
"TCP",
"connection",
".",
"A",
"setting",
"of",
"0",
"disables",
"TCP",
"keep",
"-",
"alives",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L60-L64 |
10,784 | cloudfoundry/cfhttp | v2/client.go | WithIdleConnTimeout | func WithIdleConnTimeout(t time.Duration) Option {
return func(c *config) {
c.idleConnTimeout = t
}
} | go | func WithIdleConnTimeout(t time.Duration) Option {
return func(c *config) {
c.idleConnTimeout = t
}
} | [
"func",
"WithIdleConnTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"idleConnTimeout",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithIdleConnTimeout sets the maximum amount of time a keep-alive
// connection can be idle before it closes itself.
//
// A setting of 0 means no timeout. | [
"WithIdleConnTimeout",
"sets",
"the",
"maximum",
"amount",
"of",
"time",
"a",
"keep",
"-",
"alive",
"connection",
"can",
"be",
"idle",
"before",
"it",
"closes",
"itself",
".",
"A",
"setting",
"of",
"0",
"means",
"no",
"timeout",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L70-L74 |
10,785 | cloudfoundry/cfhttp | v2/client.go | WithTLSConfig | func WithTLSConfig(t *tls.Config) Option {
return func(c *config) {
c.tlsConfig = t
}
} | go | func WithTLSConfig(t *tls.Config) Option {
return func(c *config) {
c.tlsConfig = t
}
} | [
"func",
"WithTLSConfig",
"(",
"t",
"*",
"tls",
".",
"Config",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"config",
")",
"{",
"c",
".",
"tlsConfig",
"=",
"t",
"\n",
"}",
"\n",
"}"
] | // WithTLSConfig sets the TLS configuration on the HTTP client. | [
"WithTLSConfig",
"sets",
"the",
"TLS",
"configuration",
"on",
"the",
"HTTP",
"client",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L96-L100 |
10,786 | cloudfoundry/cfhttp | v2/client.go | NewClient | func NewClient(options ...Option) *http.Client {
cfg := config{
dialTimeout: 5 * time.Second,
tcpKeepAliveTimeout: 0,
idleConnTimeout: 90 * time.Second,
}
for _, v := range options {
v(&cfg)
}
return &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: cfg.dialTimeout,
KeepAlive: cfg.tcpKeepAliveTimeout,
}).DialContext,
IdleConnTimeout: cfg.idleConnTimeout,
DisableKeepAlives: cfg.disableKeepAlives,
MaxIdleConnsPerHost: cfg.maxIdleConnsPerHost,
TLSClientConfig: cfg.tlsConfig,
},
Timeout: cfg.requestTimeout,
}
} | go | func NewClient(options ...Option) *http.Client {
cfg := config{
dialTimeout: 5 * time.Second,
tcpKeepAliveTimeout: 0,
idleConnTimeout: 90 * time.Second,
}
for _, v := range options {
v(&cfg)
}
return &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: cfg.dialTimeout,
KeepAlive: cfg.tcpKeepAliveTimeout,
}).DialContext,
IdleConnTimeout: cfg.idleConnTimeout,
DisableKeepAlives: cfg.disableKeepAlives,
MaxIdleConnsPerHost: cfg.maxIdleConnsPerHost,
TLSClientConfig: cfg.tlsConfig,
},
Timeout: cfg.requestTimeout,
}
} | [
"func",
"NewClient",
"(",
"options",
"...",
"Option",
")",
"*",
"http",
".",
"Client",
"{",
"cfg",
":=",
"config",
"{",
"dialTimeout",
":",
"5",
"*",
"time",
".",
"Second",
",",
"tcpKeepAliveTimeout",
":",
"0",
",",
"idleConnTimeout",
":",
"90",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"options",
"{",
"v",
"(",
"&",
"cfg",
")",
"\n",
"}",
"\n",
"return",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"DialContext",
":",
"(",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"cfg",
".",
"dialTimeout",
",",
"KeepAlive",
":",
"cfg",
".",
"tcpKeepAliveTimeout",
",",
"}",
")",
".",
"DialContext",
",",
"IdleConnTimeout",
":",
"cfg",
".",
"idleConnTimeout",
",",
"DisableKeepAlives",
":",
"cfg",
".",
"disableKeepAlives",
",",
"MaxIdleConnsPerHost",
":",
"cfg",
".",
"maxIdleConnsPerHost",
",",
"TLSClientConfig",
":",
"cfg",
".",
"tlsConfig",
",",
"}",
",",
"Timeout",
":",
"cfg",
".",
"requestTimeout",
",",
"}",
"\n",
"}"
] | // NewClient builds a HTTP client with suitable defaults.
// The Options can optionally set configuration options on the
// HTTP client, transport, or net dialer. Options are applied
// in the order that they are passed in, so it is possible for
// later Options previous ones. | [
"NewClient",
"builds",
"a",
"HTTP",
"client",
"with",
"suitable",
"defaults",
".",
"The",
"Options",
"can",
"optionally",
"set",
"configuration",
"options",
"on",
"the",
"HTTP",
"client",
"transport",
"or",
"net",
"dialer",
".",
"Options",
"are",
"applied",
"in",
"the",
"order",
"that",
"they",
"are",
"passed",
"in",
"so",
"it",
"is",
"possible",
"for",
"later",
"Options",
"previous",
"ones",
"."
] | 1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71 | https://github.com/cloudfoundry/cfhttp/blob/1f526aa7822e788b7e8b9dd097b0cf8c5b2fdb71/v2/client.go#L107-L129 |
10,787 | jzelinskie/geddit | login_session.go | NewLoginSession | func NewLoginSession(username, password, useragent string) (*LoginSession, error) {
session := &LoginSession{
username: username,
password: password,
useragent: useragent,
Session: Session{useragent},
}
loginURL := fmt.Sprintf("https://www.reddit.com/api/login/%s", username)
postValues := url.Values{
"user": {username},
"passwd": {password},
"api_type": {"json"},
}
req, err := http.NewRequest("POST", loginURL, strings.NewReader(postValues.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", useragent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
// Get the session cookie.
for _, cookie := range resp.Cookies() {
if cookie.Name == "reddit_session" {
session.cookie = cookie
}
}
// Get the modhash from the JSON.
type Response struct {
JSON struct {
Errors [][]string
Data struct {
Modhash string
}
}
}
r := &Response{}
err = json.NewDecoder(resp.Body).Decode(r)
if err != nil {
return nil, err
}
if len(r.JSON.Errors) != 0 {
var msg []string
for _, k := range r.JSON.Errors {
msg = append(msg, k[1])
}
return nil, errors.New(strings.Join(msg, ", "))
}
session.modhash = r.JSON.Data.Modhash
return session, nil
} | go | func NewLoginSession(username, password, useragent string) (*LoginSession, error) {
session := &LoginSession{
username: username,
password: password,
useragent: useragent,
Session: Session{useragent},
}
loginURL := fmt.Sprintf("https://www.reddit.com/api/login/%s", username)
postValues := url.Values{
"user": {username},
"passwd": {password},
"api_type": {"json"},
}
req, err := http.NewRequest("POST", loginURL, strings.NewReader(postValues.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", useragent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
// Get the session cookie.
for _, cookie := range resp.Cookies() {
if cookie.Name == "reddit_session" {
session.cookie = cookie
}
}
// Get the modhash from the JSON.
type Response struct {
JSON struct {
Errors [][]string
Data struct {
Modhash string
}
}
}
r := &Response{}
err = json.NewDecoder(resp.Body).Decode(r)
if err != nil {
return nil, err
}
if len(r.JSON.Errors) != 0 {
var msg []string
for _, k := range r.JSON.Errors {
msg = append(msg, k[1])
}
return nil, errors.New(strings.Join(msg, ", "))
}
session.modhash = r.JSON.Data.Modhash
return session, nil
} | [
"func",
"NewLoginSession",
"(",
"username",
",",
"password",
",",
"useragent",
"string",
")",
"(",
"*",
"LoginSession",
",",
"error",
")",
"{",
"session",
":=",
"&",
"LoginSession",
"{",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"useragent",
":",
"useragent",
",",
"Session",
":",
"Session",
"{",
"useragent",
"}",
",",
"}",
"\n\n",
"loginURL",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"username",
")",
"\n",
"postValues",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"username",
"}",
",",
"\"",
"\"",
":",
"{",
"password",
"}",
",",
"\"",
"\"",
":",
"{",
"\"",
"\"",
"}",
",",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"loginURL",
",",
"strings",
".",
"NewReader",
"(",
"postValues",
".",
"Encode",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"useragent",
")",
"\n\n",
"resp",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"// Get the session cookie.",
"for",
"_",
",",
"cookie",
":=",
"range",
"resp",
".",
"Cookies",
"(",
")",
"{",
"if",
"cookie",
".",
"Name",
"==",
"\"",
"\"",
"{",
"session",
".",
"cookie",
"=",
"cookie",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get the modhash from the JSON.",
"type",
"Response",
"struct",
"{",
"JSON",
"struct",
"{",
"Errors",
"[",
"]",
"[",
"]",
"string",
"\n",
"Data",
"struct",
"{",
"Modhash",
"string",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
":=",
"&",
"Response",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"r",
".",
"JSON",
".",
"Errors",
")",
"!=",
"0",
"{",
"var",
"msg",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"r",
".",
"JSON",
".",
"Errors",
"{",
"msg",
"=",
"append",
"(",
"msg",
",",
"k",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"strings",
".",
"Join",
"(",
"msg",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"session",
".",
"modhash",
"=",
"r",
".",
"JSON",
".",
"Data",
".",
"Modhash",
"\n\n",
"return",
"session",
",",
"nil",
"\n",
"}"
] | // NewLoginSession creates a new session for those who want to log into a
// reddit account. | [
"NewLoginSession",
"creates",
"a",
"new",
"session",
"for",
"those",
"who",
"want",
"to",
"log",
"into",
"a",
"reddit",
"account",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L33-L98 |
10,788 | jzelinskie/geddit | login_session.go | Clear | func (s LoginSession) Clear() error {
req := &request{
url: "https://www.reddit.com/api/clear_sessions",
values: &url.Values{
"curpass": {s.password},
"uh": {s.modhash},
},
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "all other sessions have been logged out") {
return errors.New("failed to clear session")
}
return nil
} | go | func (s LoginSession) Clear() error {
req := &request{
url: "https://www.reddit.com/api/clear_sessions",
values: &url.Values{
"curpass": {s.password},
"uh": {s.modhash},
},
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "all other sessions have been logged out") {
return errors.New("failed to clear session")
}
return nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Clear",
"(",
")",
"error",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"values",
":",
"&",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"s",
".",
"password",
"}",
",",
"\"",
"\"",
":",
"{",
"s",
".",
"modhash",
"}",
",",
"}",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"body",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Clear clears all session cookies and updates the current session with a new one. | [
"Clear",
"clears",
"all",
"session",
"cookies",
"and",
"updates",
"the",
"current",
"session",
"with",
"a",
"new",
"one",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L101-L119 |
10,789 | jzelinskie/geddit | login_session.go | Frontpage | func (s LoginSession) Frontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error) {
v, err := query.Values(params)
if err != nil {
return nil, err
}
var redditUrl string
if sort == DefaultPopularity {
redditUrl = fmt.Sprintf("https://www.reddit.com/.json?%s", v.Encode())
} else {
redditUrl = fmt.Sprintf("https://www.reddit.com/%s/.json?%s", sort, v.Encode())
}
req := request{
url: redditUrl,
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | go | func (s LoginSession) Frontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error) {
v, err := query.Values(params)
if err != nil {
return nil, err
}
var redditUrl string
if sort == DefaultPopularity {
redditUrl = fmt.Sprintf("https://www.reddit.com/.json?%s", v.Encode())
} else {
redditUrl = fmt.Sprintf("https://www.reddit.com/%s/.json?%s", sort, v.Encode())
}
req := request{
url: redditUrl,
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Frontpage",
"(",
"sort",
"PopularitySort",
",",
"params",
"ListingOptions",
")",
"(",
"[",
"]",
"*",
"Submission",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"query",
".",
"Values",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"redditUrl",
"string",
"\n\n",
"if",
"sort",
"==",
"DefaultPopularity",
"{",
"redditUrl",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"redditUrl",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sort",
",",
"v",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"\n\n",
"req",
":=",
"request",
"{",
"url",
":",
"redditUrl",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"type",
"Response",
"struct",
"{",
"Data",
"struct",
"{",
"Children",
"[",
"]",
"struct",
"{",
"Data",
"*",
"Submission",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"r",
":=",
"&",
"Response",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"submissions",
":=",
"make",
"(",
"[",
"]",
"*",
"Submission",
",",
"len",
"(",
"r",
".",
"Data",
".",
"Children",
")",
")",
"\n",
"for",
"i",
",",
"child",
":=",
"range",
"r",
".",
"Data",
".",
"Children",
"{",
"submissions",
"[",
"i",
"]",
"=",
"child",
".",
"Data",
"\n",
"}",
"\n\n",
"return",
"submissions",
",",
"nil",
"\n",
"}"
] | // Frontpage returns the submissions on the logged-in user's personal frontpage. | [
"Frontpage",
"returns",
"the",
"submissions",
"on",
"the",
"logged",
"-",
"in",
"user",
"s",
"personal",
"frontpage",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L122-L165 |
10,790 | jzelinskie/geddit | login_session.go | Me | func (s LoginSession) Me() (*Redditor, error) {
req := &request{
url: "https://www.reddit.com/api/me.json",
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data Redditor
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
return &r.Data, nil
} | go | func (s LoginSession) Me() (*Redditor, error) {
req := &request{
url: "https://www.reddit.com/api/me.json",
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data Redditor
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
return &r.Data, nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Me",
"(",
")",
"(",
"*",
"Redditor",
",",
"error",
")",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"type",
"Response",
"struct",
"{",
"Data",
"Redditor",
"\n",
"}",
"\n",
"r",
":=",
"&",
"Response",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"r",
".",
"Data",
",",
"nil",
"\n",
"}"
] | // Me returns an up-to-date redditor object of the logged-in user. | [
"Me",
"returns",
"an",
"up",
"-",
"to",
"-",
"date",
"redditor",
"object",
"of",
"the",
"logged",
"-",
"in",
"user",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L168-L189 |
10,791 | jzelinskie/geddit | login_session.go | Vote | func (s LoginSession) Vote(v Voter, vote Vote) error {
req := &request{
url: "https://www.reddit.com/api/vote",
values: &url.Values{
"id": {v.voteID()},
"dir": {string(vote)},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if body.String() != "{}" {
return errors.New("failed to vote")
}
return nil
} | go | func (s LoginSession) Vote(v Voter, vote Vote) error {
req := &request{
url: "https://www.reddit.com/api/vote",
values: &url.Values{
"id": {v.voteID()},
"dir": {string(vote)},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if body.String() != "{}" {
return errors.New("failed to vote")
}
return nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Vote",
"(",
"v",
"Voter",
",",
"vote",
"Vote",
")",
"error",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"values",
":",
"&",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"v",
".",
"voteID",
"(",
")",
"}",
",",
"\"",
"\"",
":",
"{",
"string",
"(",
"vote",
")",
"}",
",",
"\"",
"\"",
":",
"{",
"s",
".",
"modhash",
"}",
",",
"}",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"body",
".",
"String",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Vote either votes or rescinds a vote for a Submission or Comment. | [
"Vote",
"either",
"votes",
"or",
"rescinds",
"a",
"vote",
"for",
"a",
"Submission",
"or",
"Comment",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L231-L250 |
10,792 | jzelinskie/geddit | login_session.go | Reply | func (s LoginSession) Reply(r Replier, comment string) error {
req := &request{
url: "https://www.reddit.com/api/comment",
values: &url.Values{
"thing_id": {r.replyID()},
"text": {comment},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "data") {
return errors.New("failed to post comment")
}
return nil
} | go | func (s LoginSession) Reply(r Replier, comment string) error {
req := &request{
url: "https://www.reddit.com/api/comment",
values: &url.Values{
"thing_id": {r.replyID()},
"text": {comment},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "data") {
return errors.New("failed to post comment")
}
return nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Reply",
"(",
"r",
"Replier",
",",
"comment",
"string",
")",
"error",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"values",
":",
"&",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"r",
".",
"replyID",
"(",
")",
"}",
",",
"\"",
"\"",
":",
"{",
"comment",
"}",
",",
"\"",
"\"",
":",
"{",
"s",
".",
"modhash",
"}",
",",
"}",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"body",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Reply posts a comment as a response to a Submission or Comment. | [
"Reply",
"posts",
"a",
"comment",
"as",
"a",
"response",
"to",
"a",
"Submission",
"or",
"Comment",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L253-L275 |
10,793 | jzelinskie/geddit | login_session.go | Delete | func (s LoginSession) Delete(d Deleter) error {
req := &request{
url: "https://www.reddit.com/api/del",
values: &url.Values{
"id": {d.deleteID()},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "data") {
return errors.New("failed to delete item")
}
return nil
} | go | func (s LoginSession) Delete(d Deleter) error {
req := &request{
url: "https://www.reddit.com/api/del",
values: &url.Values{
"id": {d.deleteID()},
"uh": {s.modhash},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return err
}
if !strings.Contains(body.String(), "data") {
return errors.New("failed to delete item")
}
return nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Delete",
"(",
"d",
"Deleter",
")",
"error",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"values",
":",
"&",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"d",
".",
"deleteID",
"(",
")",
"}",
",",
"\"",
"\"",
":",
"{",
"s",
".",
"modhash",
"}",
",",
"}",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"body",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Delete deletes a Submission or Comment. | [
"Delete",
"deletes",
"a",
"Submission",
"or",
"Comment",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L278-L299 |
10,794 | jzelinskie/geddit | login_session.go | NeedsCaptcha | func (s LoginSession) NeedsCaptcha() (bool, error) {
req := &request{
url: "https://www.reddit.com/api/needs_captcha.json",
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return false, err
}
need, err := strconv.ParseBool(body.String())
if err != nil {
return false, err
}
return need, nil
} | go | func (s LoginSession) NeedsCaptcha() (bool, error) {
req := &request{
url: "https://www.reddit.com/api/needs_captcha.json",
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return false, err
}
need, err := strconv.ParseBool(body.String())
if err != nil {
return false, err
}
return need, nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"NeedsCaptcha",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"need",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"body",
".",
"String",
"(",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"need",
",",
"nil",
"\n",
"}"
] | // NeedsCaptcha returns true if captcha is required, false if it isn't | [
"NeedsCaptcha",
"returns",
"true",
"if",
"captcha",
"is",
"required",
"false",
"if",
"it",
"isn",
"t"
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L302-L322 |
10,795 | jzelinskie/geddit | login_session.go | NewCaptchaIden | func (s LoginSession) NewCaptchaIden() (string, error) {
req := &request{
url: "https://www.reddit.com/api/new_captcha",
values: &url.Values{
"api_type": {"json"},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return "", err
}
// Get the CAPTCHA iden from the JSON.
type Response struct {
JSON struct {
Errors [][]string
Data struct {
Iden string
}
}
}
r := new(Response)
err = json.NewDecoder(body).Decode(r)
if err != nil {
return "", err
}
return r.JSON.Data.Iden, nil
} | go | func (s LoginSession) NewCaptchaIden() (string, error) {
req := &request{
url: "https://www.reddit.com/api/new_captcha",
values: &url.Values{
"api_type": {"json"},
},
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return "", err
}
// Get the CAPTCHA iden from the JSON.
type Response struct {
JSON struct {
Errors [][]string
Data struct {
Iden string
}
}
}
r := new(Response)
err = json.NewDecoder(body).Decode(r)
if err != nil {
return "", err
}
return r.JSON.Data.Iden, nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"NewCaptchaIden",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"\"",
"\"",
",",
"values",
":",
"&",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"\"",
"\"",
"}",
",",
"}",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// Get the CAPTCHA iden from the JSON.",
"type",
"Response",
"struct",
"{",
"JSON",
"struct",
"{",
"Errors",
"[",
"]",
"[",
"]",
"string",
"\n",
"Data",
"struct",
"{",
"Iden",
"string",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
":=",
"new",
"(",
"Response",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"JSON",
".",
"Data",
".",
"Iden",
",",
"nil",
"\n",
"}"
] | // NewCaptchaIden gets a new captcha iden from reddit | [
"NewCaptchaIden",
"gets",
"a",
"new",
"captcha",
"iden",
"from",
"reddit"
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L325-L356 |
10,796 | jzelinskie/geddit | login_session.go | Listing | func (s LoginSession) Listing(username, listing string, sort PopularitySort, after string) ([]*Submission, error) {
values := &url.Values{}
if sort != "" {
values.Set("sort", string(sort))
}
if after != "" {
values.Set("after", after)
}
url := fmt.Sprintf("https://www.reddit.com/user/%s/%s.json?%s", username, listing, values.Encode())
req := &request{
url: url,
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | go | func (s LoginSession) Listing(username, listing string, sort PopularitySort, after string) ([]*Submission, error) {
values := &url.Values{}
if sort != "" {
values.Set("sort", string(sort))
}
if after != "" {
values.Set("after", after)
}
url := fmt.Sprintf("https://www.reddit.com/user/%s/%s.json?%s", username, listing, values.Encode())
req := &request{
url: url,
cookie: s.cookie,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := &Response{}
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | [
"func",
"(",
"s",
"LoginSession",
")",
"Listing",
"(",
"username",
",",
"listing",
"string",
",",
"sort",
"PopularitySort",
",",
"after",
"string",
")",
"(",
"[",
"]",
"*",
"Submission",
",",
"error",
")",
"{",
"values",
":=",
"&",
"url",
".",
"Values",
"{",
"}",
"\n",
"if",
"sort",
"!=",
"\"",
"\"",
"{",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"string",
"(",
"sort",
")",
")",
"\n",
"}",
"\n",
"if",
"after",
"!=",
"\"",
"\"",
"{",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"after",
")",
"\n",
"}",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"username",
",",
"listing",
",",
"values",
".",
"Encode",
"(",
")",
")",
"\n",
"req",
":=",
"&",
"request",
"{",
"url",
":",
"url",
",",
"cookie",
":",
"s",
".",
"cookie",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"type",
"Response",
"struct",
"{",
"Data",
"struct",
"{",
"Children",
"[",
"]",
"struct",
"{",
"Data",
"*",
"Submission",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
":=",
"&",
"Response",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"submissions",
":=",
"make",
"(",
"[",
"]",
"*",
"Submission",
",",
"len",
"(",
"r",
".",
"Data",
".",
"Children",
")",
")",
"\n",
"for",
"i",
",",
"child",
":=",
"range",
"r",
".",
"Data",
".",
"Children",
"{",
"submissions",
"[",
"i",
"]",
"=",
"child",
".",
"Data",
"\n",
"}",
"\n\n",
"return",
"submissions",
",",
"nil",
"\n",
"}"
] | // Listing returns a listing for an user | [
"Listing",
"returns",
"a",
"listing",
"for",
"an",
"user"
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L359-L399 |
10,797 | jzelinskie/geddit | login_session.go | MyOverview | func (s LoginSession) MyOverview(sort PopularitySort, after string) ([]*Submission, error) {
return s.Listing(s.username, "overview", sort, after)
} | go | func (s LoginSession) MyOverview(sort PopularitySort, after string) ([]*Submission, error) {
return s.Listing(s.username, "overview", sort, after)
} | [
"func",
"(",
"s",
"LoginSession",
")",
"MyOverview",
"(",
"sort",
"PopularitySort",
",",
"after",
"string",
")",
"(",
"[",
"]",
"*",
"Submission",
",",
"error",
")",
"{",
"return",
"s",
".",
"Listing",
"(",
"s",
".",
"username",
",",
"\"",
"\"",
",",
"sort",
",",
"after",
")",
"\n",
"}"
] | // Fetch the Overview listing for the logged-in user | [
"Fetch",
"the",
"Overview",
"listing",
"for",
"the",
"logged",
"-",
"in",
"user"
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/login_session.go#L402-L404 |
10,798 | jzelinskie/geddit | session.go | DefaultFrontpage | func (s Session) DefaultFrontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error) {
return s.SubredditSubmissions("", sort, params)
} | go | func (s Session) DefaultFrontpage(sort PopularitySort, params ListingOptions) ([]*Submission, error) {
return s.SubredditSubmissions("", sort, params)
} | [
"func",
"(",
"s",
"Session",
")",
"DefaultFrontpage",
"(",
"sort",
"PopularitySort",
",",
"params",
"ListingOptions",
")",
"(",
"[",
"]",
"*",
"Submission",
",",
"error",
")",
"{",
"return",
"s",
".",
"SubredditSubmissions",
"(",
"\"",
"\"",
",",
"sort",
",",
"params",
")",
"\n",
"}"
] | // DefaultFrontpage returns the submissions on the default reddit frontpage. | [
"DefaultFrontpage",
"returns",
"the",
"submissions",
"on",
"the",
"default",
"reddit",
"frontpage",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/session.go#L30-L32 |
10,799 | jzelinskie/geddit | session.go | SubredditSubmissions | func (s Session) SubredditSubmissions(subreddit string, sort PopularitySort, params ListingOptions) ([]*Submission, error) {
v, err := query.Values(params)
if err != nil {
return nil, err
}
baseUrl := "https://www.reddit.com"
// If subbreddit given, add to URL
if subreddit != "" {
baseUrl += "/r/" + subreddit
}
redditUrl := fmt.Sprintf(baseUrl+"/%s.json?%s", sort, v.Encode())
req := request{
url: redditUrl,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := new(Response)
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | go | func (s Session) SubredditSubmissions(subreddit string, sort PopularitySort, params ListingOptions) ([]*Submission, error) {
v, err := query.Values(params)
if err != nil {
return nil, err
}
baseUrl := "https://www.reddit.com"
// If subbreddit given, add to URL
if subreddit != "" {
baseUrl += "/r/" + subreddit
}
redditUrl := fmt.Sprintf(baseUrl+"/%s.json?%s", sort, v.Encode())
req := request{
url: redditUrl,
useragent: s.useragent,
}
body, err := req.getResponse()
if err != nil {
return nil, err
}
type Response struct {
Data struct {
Children []struct {
Data *Submission
}
}
}
r := new(Response)
err = json.NewDecoder(body).Decode(r)
if err != nil {
return nil, err
}
submissions := make([]*Submission, len(r.Data.Children))
for i, child := range r.Data.Children {
submissions[i] = child.Data
}
return submissions, nil
} | [
"func",
"(",
"s",
"Session",
")",
"SubredditSubmissions",
"(",
"subreddit",
"string",
",",
"sort",
"PopularitySort",
",",
"params",
"ListingOptions",
")",
"(",
"[",
"]",
"*",
"Submission",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"query",
".",
"Values",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"baseUrl",
":=",
"\"",
"\"",
"\n\n",
"// If subbreddit given, add to URL",
"if",
"subreddit",
"!=",
"\"",
"\"",
"{",
"baseUrl",
"+=",
"\"",
"\"",
"+",
"subreddit",
"\n",
"}",
"\n\n",
"redditUrl",
":=",
"fmt",
".",
"Sprintf",
"(",
"baseUrl",
"+",
"\"",
"\"",
",",
"sort",
",",
"v",
".",
"Encode",
"(",
")",
")",
"\n\n",
"req",
":=",
"request",
"{",
"url",
":",
"redditUrl",
",",
"useragent",
":",
"s",
".",
"useragent",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"req",
".",
"getResponse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"type",
"Response",
"struct",
"{",
"Data",
"struct",
"{",
"Children",
"[",
"]",
"struct",
"{",
"Data",
"*",
"Submission",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"r",
":=",
"new",
"(",
"Response",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"body",
")",
".",
"Decode",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"submissions",
":=",
"make",
"(",
"[",
"]",
"*",
"Submission",
",",
"len",
"(",
"r",
".",
"Data",
".",
"Children",
")",
")",
"\n",
"for",
"i",
",",
"child",
":=",
"range",
"r",
".",
"Data",
".",
"Children",
"{",
"submissions",
"[",
"i",
"]",
"=",
"child",
".",
"Data",
"\n",
"}",
"\n\n",
"return",
"submissions",
",",
"nil",
"\n",
"}"
] | // SubredditSubmissions returns the submissions on the given subreddit. | [
"SubredditSubmissions",
"returns",
"the",
"submissions",
"on",
"the",
"given",
"subreddit",
"."
] | a9d9445ed681c9bc2df9cce08998891b44efd806 | https://github.com/jzelinskie/geddit/blob/a9d9445ed681c9bc2df9cce08998891b44efd806/session.go#L35-L79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.