repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
derekparker/trie | trie.go | PrefixSearch | func (t Trie) PrefixSearch(pre string) []string {
node := findNode(t.Root(), []rune(pre))
if node == nil {
return nil
}
return collect(node)
} | go | func (t Trie) PrefixSearch(pre string) []string {
node := findNode(t.Root(), []rune(pre))
if node == nil {
return nil
}
return collect(node)
} | [
"func",
"(",
"t",
"Trie",
")",
"PrefixSearch",
"(",
"pre",
"string",
")",
"[",
"]",
"string",
"{",
"node",
":=",
"findNode",
"(",
"t",
".",
"Root",
"(",
")",
",",
"[",
"]",
"rune",
"(",
"pre",
")",
")",
"\n",
"if",
"node",
"==",
"nil",
"{",
"... | // Performs a prefix search against the keys in the trie. | [
"Performs",
"a",
"prefix",
"search",
"against",
"the",
"keys",
"in",
"the",
"trie",
"."
] | 1ce4922c7ad906a094c6298977755068ba76ad31 | https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L133-L140 | train |
derekparker/trie | trie.go | NewChild | func (n *Node) NewChild(val rune, bitmask uint64, meta interface{}, term bool) *Node {
node := &Node{
val: val,
mask: bitmask,
term: term,
meta: meta,
parent: n,
children: make(map[rune]*Node),
depth: n.depth + 1,
}
n.children[val] = node
n.mask |= bitmask
return node
} | go | func (n *Node) NewChild(val rune, bitmask uint64, meta interface{}, term bool) *Node {
node := &Node{
val: val,
mask: bitmask,
term: term,
meta: meta,
parent: n,
children: make(map[rune]*Node),
depth: n.depth + 1,
}
n.children[val] = node
n.mask |= bitmask
return node
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"NewChild",
"(",
"val",
"rune",
",",
"bitmask",
"uint64",
",",
"meta",
"interface",
"{",
"}",
",",
"term",
"bool",
")",
"*",
"Node",
"{",
"node",
":=",
"&",
"Node",
"{",
"val",
":",
"val",
",",
"mask",
":",
"... | // Creates and returns a pointer to a new child for the node. | [
"Creates",
"and",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"child",
"for",
"the",
"node",
"."
] | 1ce4922c7ad906a094c6298977755068ba76ad31 | https://github.com/derekparker/trie/blob/1ce4922c7ad906a094c6298977755068ba76ad31/trie.go#L143-L156 | train |
tidwall/sjson | sjson.go | appendStringify | func appendStringify(buf []byte, s string) []byte {
if mustMarshalString(s) {
b, _ := jsongo.Marshal(s)
return append(buf, b...)
}
buf = append(buf, '"')
buf = append(buf, s...)
buf = append(buf, '"')
return buf
} | go | func appendStringify(buf []byte, s string) []byte {
if mustMarshalString(s) {
b, _ := jsongo.Marshal(s)
return append(buf, b...)
}
buf = append(buf, '"')
buf = append(buf, s...)
buf = append(buf, '"')
return buf
} | [
"func",
"appendStringify",
"(",
"buf",
"[",
"]",
"byte",
",",
"s",
"string",
")",
"[",
"]",
"byte",
"{",
"if",
"mustMarshalString",
"(",
"s",
")",
"{",
"b",
",",
"_",
":=",
"jsongo",
".",
"Marshal",
"(",
"s",
")",
"\n",
"return",
"append",
"(",
"... | // appendStringify makes a json string and appends to buf. | [
"appendStringify",
"makes",
"a",
"json",
"string",
"and",
"appends",
"to",
"buf",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L119-L128 | train |
tidwall/sjson | sjson.go | appendBuild | func appendBuild(buf []byte, array bool, paths []pathResult, raw string,
stringify bool) []byte {
if !array {
buf = appendStringify(buf, paths[0].part)
buf = append(buf, ':')
}
if len(paths) > 1 {
n, numeric := atoui(paths[1])
if numeric || (!paths[1].force && paths[1].part == "-1") {
buf = append(buf, '[')
buf = appendRepeat(buf, "null,", n)
buf = appendBuild(buf, true, paths[1:], raw, stringify)
buf = append(buf, ']')
} else {
buf = append(buf, '{')
buf = appendBuild(buf, false, paths[1:], raw, stringify)
buf = append(buf, '}')
}
} else {
if stringify {
buf = appendStringify(buf, raw)
} else {
buf = append(buf, raw...)
}
}
return buf
} | go | func appendBuild(buf []byte, array bool, paths []pathResult, raw string,
stringify bool) []byte {
if !array {
buf = appendStringify(buf, paths[0].part)
buf = append(buf, ':')
}
if len(paths) > 1 {
n, numeric := atoui(paths[1])
if numeric || (!paths[1].force && paths[1].part == "-1") {
buf = append(buf, '[')
buf = appendRepeat(buf, "null,", n)
buf = appendBuild(buf, true, paths[1:], raw, stringify)
buf = append(buf, ']')
} else {
buf = append(buf, '{')
buf = appendBuild(buf, false, paths[1:], raw, stringify)
buf = append(buf, '}')
}
} else {
if stringify {
buf = appendStringify(buf, raw)
} else {
buf = append(buf, raw...)
}
}
return buf
} | [
"func",
"appendBuild",
"(",
"buf",
"[",
"]",
"byte",
",",
"array",
"bool",
",",
"paths",
"[",
"]",
"pathResult",
",",
"raw",
"string",
",",
"stringify",
"bool",
")",
"[",
"]",
"byte",
"{",
"if",
"!",
"array",
"{",
"buf",
"=",
"appendStringify",
"(",
... | // appendBuild builds a json block from a json path. | [
"appendBuild",
"builds",
"a",
"json",
"block",
"from",
"a",
"json",
"path",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L131-L157 | train |
tidwall/sjson | sjson.go | atoui | func atoui(r pathResult) (n int, ok bool) {
if r.force {
return 0, false
}
for i := 0; i < len(r.part); i++ {
if r.part[i] < '0' || r.part[i] > '9' {
return 0, false
}
n = n*10 + int(r.part[i]-'0')
}
return n, true
} | go | func atoui(r pathResult) (n int, ok bool) {
if r.force {
return 0, false
}
for i := 0; i < len(r.part); i++ {
if r.part[i] < '0' || r.part[i] > '9' {
return 0, false
}
n = n*10 + int(r.part[i]-'0')
}
return n, true
} | [
"func",
"atoui",
"(",
"r",
"pathResult",
")",
"(",
"n",
"int",
",",
"ok",
"bool",
")",
"{",
"if",
"r",
".",
"force",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"r",
".",
"part",
")",... | // atoui does a rip conversion of string -> unigned int. | [
"atoui",
"does",
"a",
"rip",
"conversion",
"of",
"string",
"-",
">",
"unigned",
"int",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L160-L171 | train |
tidwall/sjson | sjson.go | appendRepeat | func appendRepeat(buf []byte, s string, n int) []byte {
for i := 0; i < n; i++ {
buf = append(buf, s...)
}
return buf
} | go | func appendRepeat(buf []byte, s string, n int) []byte {
for i := 0; i < n; i++ {
buf = append(buf, s...)
}
return buf
} | [
"func",
"appendRepeat",
"(",
"buf",
"[",
"]",
"byte",
",",
"s",
"string",
",",
"n",
"int",
")",
"[",
"]",
"byte",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"s",
"...",
")",
... | // appendRepeat repeats string "n" times and appends to buf. | [
"appendRepeat",
"repeats",
"string",
"n",
"times",
"and",
"appends",
"to",
"buf",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L174-L179 | train |
tidwall/sjson | sjson.go | trim | func trim(s string) string {
for len(s) > 0 {
if s[0] <= ' ' {
s = s[1:]
continue
}
break
}
for len(s) > 0 {
if s[len(s)-1] <= ' ' {
s = s[:len(s)-1]
continue
}
break
}
return s
} | go | func trim(s string) string {
for len(s) > 0 {
if s[0] <= ' ' {
s = s[1:]
continue
}
break
}
for len(s) > 0 {
if s[len(s)-1] <= ' ' {
s = s[:len(s)-1]
continue
}
break
}
return s
} | [
"func",
"trim",
"(",
"s",
"string",
")",
"string",
"{",
"for",
"len",
"(",
"s",
")",
">",
"0",
"{",
"if",
"s",
"[",
"0",
"]",
"<=",
"' '",
"{",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n"... | // trim does a rip trim | [
"trim",
"does",
"a",
"rip",
"trim"
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L182-L198 | train |
tidwall/sjson | sjson.go | deleteTailItem | func deleteTailItem(buf []byte) ([]byte, bool) {
loop:
for i := len(buf) - 1; i >= 0; i-- {
// look for either a ',',':','['
switch buf[i] {
case '[':
return buf, true
case ',':
return buf[:i], false
case ':':
// delete tail string
i--
for ; i >= 0; i-- {
if buf[i] == '"' {
i--
for ; i >= 0; i-- {
if buf[i] == '"' {
i--
if i >= 0 && buf[i] == '\\' {
i--
continue
}
for ; i >= 0; i-- {
// look for either a ',','{'
switch buf[i] {
case '{':
return buf[:i+1], true
case ',':
return buf[:i], false
}
}
}
}
break
}
}
break loop
}
}
return buf, false
} | go | func deleteTailItem(buf []byte) ([]byte, bool) {
loop:
for i := len(buf) - 1; i >= 0; i-- {
// look for either a ',',':','['
switch buf[i] {
case '[':
return buf, true
case ',':
return buf[:i], false
case ':':
// delete tail string
i--
for ; i >= 0; i-- {
if buf[i] == '"' {
i--
for ; i >= 0; i-- {
if buf[i] == '"' {
i--
if i >= 0 && buf[i] == '\\' {
i--
continue
}
for ; i >= 0; i-- {
// look for either a ',','{'
switch buf[i] {
case '{':
return buf[:i+1], true
case ',':
return buf[:i], false
}
}
}
}
break
}
}
break loop
}
}
return buf, false
} | [
"func",
"deleteTailItem",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
")",
"{",
"loop",
":",
"for",
"i",
":=",
"len",
"(",
"buf",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"// look for either a ',',':','[... | // deleteTailItem deletes the previous key or comma. | [
"deleteTailItem",
"deletes",
"the",
"previous",
"key",
"or",
"comma",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L201-L241 | train |
tidwall/sjson | sjson.go | SetRaw | func SetRaw(json, path, value string) (string, error) {
return SetRawOptions(json, path, value, nil)
} | go | func SetRaw(json, path, value string) (string, error) {
return SetRawOptions(json, path, value, nil)
} | [
"func",
"SetRaw",
"(",
"json",
",",
"path",
",",
"value",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"SetRawOptions",
"(",
"json",
",",
"path",
",",
"value",
",",
"nil",
")",
"\n",
"}"
] | // SetRaw sets a raw json value for the specified path.
// This function works the same as Set except that the value is set as a
// raw block of json. This allows for setting premarshalled json objects. | [
"SetRaw",
"sets",
"a",
"raw",
"json",
"value",
"for",
"the",
"specified",
"path",
".",
"This",
"function",
"works",
"the",
"same",
"as",
"Set",
"except",
"that",
"the",
"value",
"is",
"set",
"as",
"a",
"raw",
"block",
"of",
"json",
".",
"This",
"allows... | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L446-L448 | train |
tidwall/sjson | sjson.go | SetRawOptions | func SetRawOptions(json, path, value string, opts *Options) (string, error) {
var optimistic bool
if opts != nil {
optimistic = opts.Optimistic
}
res, err := set(json, path, value, false, false, optimistic, false)
if err == errNoChange {
return json, nil
}
return string(res), err
} | go | func SetRawOptions(json, path, value string, opts *Options) (string, error) {
var optimistic bool
if opts != nil {
optimistic = opts.Optimistic
}
res, err := set(json, path, value, false, false, optimistic, false)
if err == errNoChange {
return json, nil
}
return string(res), err
} | [
"func",
"SetRawOptions",
"(",
"json",
",",
"path",
",",
"value",
"string",
",",
"opts",
"*",
"Options",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"optimistic",
"bool",
"\n",
"if",
"opts",
"!=",
"nil",
"{",
"optimistic",
"=",
"opts",
".",
"Op... | // SetRawOptions sets a raw json value for the specified path with options.
// This furnction works the same as SetOptions except that the value is set
// as a raw block of json. This allows for setting premarshalled json objects. | [
"SetRawOptions",
"sets",
"a",
"raw",
"json",
"value",
"for",
"the",
"specified",
"path",
"with",
"options",
".",
"This",
"furnction",
"works",
"the",
"same",
"as",
"SetOptions",
"except",
"that",
"the",
"value",
"is",
"set",
"as",
"a",
"raw",
"block",
"of"... | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L453-L463 | train |
tidwall/sjson | sjson.go | Delete | func Delete(json, path string) (string, error) {
return Set(json, path, dtype{})
} | go | func Delete(json, path string) (string, error) {
return Set(json, path, dtype{})
} | [
"func",
"Delete",
"(",
"json",
",",
"path",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"Set",
"(",
"json",
",",
"path",
",",
"dtype",
"{",
"}",
")",
"\n",
"}"
] | // Delete deletes a value from json for the specified path. | [
"Delete",
"deletes",
"a",
"value",
"from",
"json",
"for",
"the",
"specified",
"path",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L475-L477 | train |
tidwall/sjson | sjson.go | DeleteBytes | func DeleteBytes(json []byte, path string) ([]byte, error) {
return SetBytes(json, path, dtype{})
} | go | func DeleteBytes(json []byte, path string) ([]byte, error) {
return SetBytes(json, path, dtype{})
} | [
"func",
"DeleteBytes",
"(",
"json",
"[",
"]",
"byte",
",",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"SetBytes",
"(",
"json",
",",
"path",
",",
"dtype",
"{",
"}",
")",
"\n",
"}"
] | // DeleteBytes deletes a value from json for the specified path. | [
"DeleteBytes",
"deletes",
"a",
"value",
"from",
"json",
"for",
"the",
"specified",
"path",
"."
] | 25fb082a20e29e83fb7b7ef5f5919166aad1f084 | https://github.com/tidwall/sjson/blob/25fb082a20e29e83fb7b7ef5f5919166aad1f084/sjson.go#L480-L482 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | NewPageReader | func NewPageReader(input io.Reader) *PageReader {
return &PageReader{
Input: input,
PageOptions: NewPageOptions(),
}
} | go | func NewPageReader(input io.Reader) *PageReader {
return &PageReader{
Input: input,
PageOptions: NewPageOptions(),
}
} | [
"func",
"NewPageReader",
"(",
"input",
"io",
".",
"Reader",
")",
"*",
"PageReader",
"{",
"return",
"&",
"PageReader",
"{",
"Input",
":",
"input",
",",
"PageOptions",
":",
"NewPageOptions",
"(",
")",
",",
"}",
"\n",
"}"
] | // NewPageReader creates a new PageReader from an io.Reader | [
"NewPageReader",
"creates",
"a",
"new",
"PageReader",
"from",
"an",
"io",
".",
"Reader"
] | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L99-L104 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | Args | func (po *PageOptions) Args() []string {
return append(append([]string{}, po.pageOptions.Args()...), po.headerAndFooterOptions.Args()...)
} | go | func (po *PageOptions) Args() []string {
return append(append([]string{}, po.pageOptions.Args()...), po.headerAndFooterOptions.Args()...)
} | [
"func",
"(",
"po",
"*",
"PageOptions",
")",
"Args",
"(",
")",
"[",
"]",
"string",
"{",
"return",
"append",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"po",
".",
"pageOptions",
".",
"Args",
"(",
")",
"...",
")",
",",
"po",
".",
"head... | // Args returns the argument slice | [
"Args",
"returns",
"the",
"argument",
"slice"
] | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L119-L121 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | Args | func (pdfg *PDFGenerator) Args() []string {
args := append([]string{}, pdfg.globalOptions.Args()...)
args = append(args, pdfg.outlineOptions.Args()...)
if pdfg.Cover.Input != "" {
args = append(args, "cover")
args = append(args, pdfg.Cover.Input)
args = append(args, pdfg.Cover.pageOptions.Args()...)
}
if pdfg.TOC.Include {
args = append(args, "toc")
args = append(args, pdfg.TOC.pageOptions.Args()...)
args = append(args, pdfg.TOC.tocOptions.Args()...)
}
for _, page := range pdfg.pages {
args = append(args, "page")
args = append(args, page.InputFile())
args = append(args, page.Args()...)
}
if pdfg.OutputFile != "" {
args = append(args, pdfg.OutputFile)
} else {
args = append(args, "-")
}
return args
} | go | func (pdfg *PDFGenerator) Args() []string {
args := append([]string{}, pdfg.globalOptions.Args()...)
args = append(args, pdfg.outlineOptions.Args()...)
if pdfg.Cover.Input != "" {
args = append(args, "cover")
args = append(args, pdfg.Cover.Input)
args = append(args, pdfg.Cover.pageOptions.Args()...)
}
if pdfg.TOC.Include {
args = append(args, "toc")
args = append(args, pdfg.TOC.pageOptions.Args()...)
args = append(args, pdfg.TOC.tocOptions.Args()...)
}
for _, page := range pdfg.pages {
args = append(args, "page")
args = append(args, page.InputFile())
args = append(args, page.Args()...)
}
if pdfg.OutputFile != "" {
args = append(args, pdfg.OutputFile)
} else {
args = append(args, "-")
}
return args
} | [
"func",
"(",
"pdfg",
"*",
"PDFGenerator",
")",
"Args",
"(",
")",
"[",
"]",
"string",
"{",
"args",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"pdfg",
".",
"globalOptions",
".",
"Args",
"(",
")",
"...",
")",
"\n",
"args",
"=",
"append"... | //Args returns the commandline arguments as a string slice | [
"Args",
"returns",
"the",
"commandline",
"arguments",
"as",
"a",
"string",
"slice"
] | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L164-L188 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | AddPage | func (pdfg *PDFGenerator) AddPage(p page) {
pdfg.pages = append(pdfg.pages, p)
} | go | func (pdfg *PDFGenerator) AddPage(p page) {
pdfg.pages = append(pdfg.pages, p)
} | [
"func",
"(",
"pdfg",
"*",
"PDFGenerator",
")",
"AddPage",
"(",
"p",
"page",
")",
"{",
"pdfg",
".",
"pages",
"=",
"append",
"(",
"pdfg",
".",
"pages",
",",
"p",
")",
"\n",
"}"
] | // AddPage adds a new input page to the document.
// A page is an input HTML page, it can span multiple pages in the output document.
// It is a Page when read from file or URL or a PageReader when read from memory. | [
"AddPage",
"adds",
"a",
"new",
"input",
"page",
"to",
"the",
"document",
".",
"A",
"page",
"is",
"an",
"input",
"HTML",
"page",
"it",
"can",
"span",
"multiple",
"pages",
"in",
"the",
"output",
"document",
".",
"It",
"is",
"a",
"Page",
"when",
"read",
... | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L198-L200 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | WriteFile | func (pdfg *PDFGenerator) WriteFile(filename string) error {
return ioutil.WriteFile(filename, pdfg.Bytes(), 0666)
} | go | func (pdfg *PDFGenerator) WriteFile(filename string) error {
return ioutil.WriteFile(filename, pdfg.Bytes(), 0666)
} | [
"func",
"(",
"pdfg",
"*",
"PDFGenerator",
")",
"WriteFile",
"(",
"filename",
"string",
")",
"error",
"{",
"return",
"ioutil",
".",
"WriteFile",
"(",
"filename",
",",
"pdfg",
".",
"Bytes",
"(",
")",
",",
"0666",
")",
"\n",
"}"
] | // WriteFile writes the contents of the output buffer to a file | [
"WriteFile",
"writes",
"the",
"contents",
"of",
"the",
"output",
"buffer",
"to",
"a",
"file"
] | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L230-L232 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | findPath | func (pdfg *PDFGenerator) findPath() error {
const exe = "wkhtmltopdf"
pdfg.binPath = GetPath()
if pdfg.binPath != "" {
// wkhtmltopdf has already already found, return
return nil
}
exeDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
path, err := exec.LookPath(filepath.Join(exeDir, exe))
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
path, err = exec.LookPath(exe)
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
dir := os.Getenv("WKHTMLTOPDF_PATH")
if dir == "" {
return fmt.Errorf("%s not found", exe)
}
path, err = exec.LookPath(filepath.Join(dir, exe))
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
return fmt.Errorf("%s not found", exe)
} | go | func (pdfg *PDFGenerator) findPath() error {
const exe = "wkhtmltopdf"
pdfg.binPath = GetPath()
if pdfg.binPath != "" {
// wkhtmltopdf has already already found, return
return nil
}
exeDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
path, err := exec.LookPath(filepath.Join(exeDir, exe))
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
path, err = exec.LookPath(exe)
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
dir := os.Getenv("WKHTMLTOPDF_PATH")
if dir == "" {
return fmt.Errorf("%s not found", exe)
}
path, err = exec.LookPath(filepath.Join(dir, exe))
if err == nil && path != "" {
binPath.Set(path)
pdfg.binPath = path
return nil
}
return fmt.Errorf("%s not found", exe)
} | [
"func",
"(",
"pdfg",
"*",
"PDFGenerator",
")",
"findPath",
"(",
")",
"error",
"{",
"const",
"exe",
"=",
"\"",
"\"",
"\n",
"pdfg",
".",
"binPath",
"=",
"GetPath",
"(",
")",
"\n",
"if",
"pdfg",
".",
"binPath",
"!=",
"\"",
"\"",
"{",
"// wkhtmltopdf has... | //findPath finds the path to wkhtmltopdf by
//- first looking in the current dir
//- looking in the PATH and PATHEXT environment dirs
//- using the WKHTMLTOPDF_PATH environment dir
//The path is cached, meaning you can not change the location of wkhtmltopdf in
//a running program once it has been found | [
"findPath",
"finds",
"the",
"path",
"to",
"wkhtmltopdf",
"by",
"-",
"first",
"looking",
"in",
"the",
"current",
"dir",
"-",
"looking",
"in",
"the",
"PATH",
"and",
"PATHEXT",
"environment",
"dirs",
"-",
"using",
"the",
"WKHTMLTOPDF_PATH",
"environment",
"dir",
... | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L240-L274 | train |
SebastiaanKlippert/go-wkhtmltopdf | wkhtmltopdf.go | NewPDFGenerator | func NewPDFGenerator() (*PDFGenerator, error) {
pdfg := &PDFGenerator{
globalOptions: newGlobalOptions(),
outlineOptions: newOutlineOptions(),
Cover: cover{
pageOptions: newPageOptions(),
},
TOC: toc{
allTocOptions: allTocOptions{
tocOptions: newTocOptions(),
pageOptions: newPageOptions(),
},
},
}
err := pdfg.findPath()
return pdfg, err
} | go | func NewPDFGenerator() (*PDFGenerator, error) {
pdfg := &PDFGenerator{
globalOptions: newGlobalOptions(),
outlineOptions: newOutlineOptions(),
Cover: cover{
pageOptions: newPageOptions(),
},
TOC: toc{
allTocOptions: allTocOptions{
tocOptions: newTocOptions(),
pageOptions: newPageOptions(),
},
},
}
err := pdfg.findPath()
return pdfg, err
} | [
"func",
"NewPDFGenerator",
"(",
")",
"(",
"*",
"PDFGenerator",
",",
"error",
")",
"{",
"pdfg",
":=",
"&",
"PDFGenerator",
"{",
"globalOptions",
":",
"newGlobalOptions",
"(",
")",
",",
"outlineOptions",
":",
"newOutlineOptions",
"(",
")",
",",
"Cover",
":",
... | // NewPDFGenerator returns a new PDFGenerator struct with all options created and
// checks if wkhtmltopdf can be found on the system | [
"NewPDFGenerator",
"returns",
"a",
"new",
"PDFGenerator",
"struct",
"with",
"all",
"options",
"created",
"and",
"checks",
"if",
"wkhtmltopdf",
"can",
"be",
"found",
"on",
"the",
"system"
] | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/wkhtmltopdf.go#L316-L332 | train |
SebastiaanKlippert/go-wkhtmltopdf | json.go | ToJSON | func (pdfg *PDFGenerator) ToJSON() ([]byte, error) {
jpdf := &jsonPDFGenerator{
TOC: pdfg.TOC,
Cover: pdfg.Cover,
GlobalOptions: pdfg.globalOptions,
OutlineOptions: pdfg.outlineOptions,
}
for _, p := range pdfg.pages {
jp := jsonPage{
InputFile: p.InputFile(),
}
switch tp := p.(type) {
case *Page:
jp.PageOptions = tp.PageOptions
case *PageReader:
jp.PageOptions = tp.PageOptions
}
if p.Reader() != nil {
buf, err := ioutil.ReadAll(p.Reader())
if err != nil {
return nil, err
}
jp.Base64PageData = base64.StdEncoding.EncodeToString(buf)
}
jpdf.Pages = append(jpdf.Pages, jp)
}
return json.Marshal(jpdf)
} | go | func (pdfg *PDFGenerator) ToJSON() ([]byte, error) {
jpdf := &jsonPDFGenerator{
TOC: pdfg.TOC,
Cover: pdfg.Cover,
GlobalOptions: pdfg.globalOptions,
OutlineOptions: pdfg.outlineOptions,
}
for _, p := range pdfg.pages {
jp := jsonPage{
InputFile: p.InputFile(),
}
switch tp := p.(type) {
case *Page:
jp.PageOptions = tp.PageOptions
case *PageReader:
jp.PageOptions = tp.PageOptions
}
if p.Reader() != nil {
buf, err := ioutil.ReadAll(p.Reader())
if err != nil {
return nil, err
}
jp.Base64PageData = base64.StdEncoding.EncodeToString(buf)
}
jpdf.Pages = append(jpdf.Pages, jp)
}
return json.Marshal(jpdf)
} | [
"func",
"(",
"pdfg",
"*",
"PDFGenerator",
")",
"ToJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"jpdf",
":=",
"&",
"jsonPDFGenerator",
"{",
"TOC",
":",
"pdfg",
".",
"TOC",
",",
"Cover",
":",
"pdfg",
".",
"Cover",
",",
"GlobalOptio... | // ToJSON creates JSON of the complete representation of the PDFGenerator.
// It also saves all pages, for a PageReader page, the content is stored as a Base64 string in the JSON. | [
"ToJSON",
"creates",
"JSON",
"of",
"the",
"complete",
"representation",
"of",
"the",
"PDFGenerator",
".",
"It",
"also",
"saves",
"all",
"pages",
"for",
"a",
"PageReader",
"page",
"the",
"content",
"is",
"stored",
"as",
"a",
"Base64",
"string",
"in",
"the",
... | 72a7793efd38728796273861bb27d590cc33d9d4 | https://github.com/SebastiaanKlippert/go-wkhtmltopdf/blob/72a7793efd38728796273861bb27d590cc33d9d4/json.go#L28-L57 | train |
matcornic/hermes | examples/main.go | send | func send(smtpConfig smtpAuthentication, options sendOptions, htmlBody string, txtBody string) error {
if smtpConfig.Server == "" {
return errors.New("SMTP server config is empty")
}
if smtpConfig.Port == 0 {
return errors.New("SMTP port config is empty")
}
if smtpConfig.SMTPUser == "" {
return errors.New("SMTP user is empty")
}
if smtpConfig.SenderIdentity == "" {
return errors.New("SMTP sender identity is empty")
}
if smtpConfig.SenderEmail == "" {
return errors.New("SMTP sender email is empty")
}
if options.To == "" {
return errors.New("no receiver emails configured")
}
from := mail.Address{
Name: smtpConfig.SenderIdentity,
Address: smtpConfig.SenderEmail,
}
m := gomail.NewMessage()
m.SetHeader("From", from.String())
m.SetHeader("To", options.To)
m.SetHeader("Subject", options.Subject)
m.SetBody("text/plain", txtBody)
m.AddAlternative("text/html", htmlBody)
d := gomail.NewDialer(smtpConfig.Server, smtpConfig.Port, smtpConfig.SMTPUser, smtpConfig.SMTPPassword)
return d.DialAndSend(m)
} | go | func send(smtpConfig smtpAuthentication, options sendOptions, htmlBody string, txtBody string) error {
if smtpConfig.Server == "" {
return errors.New("SMTP server config is empty")
}
if smtpConfig.Port == 0 {
return errors.New("SMTP port config is empty")
}
if smtpConfig.SMTPUser == "" {
return errors.New("SMTP user is empty")
}
if smtpConfig.SenderIdentity == "" {
return errors.New("SMTP sender identity is empty")
}
if smtpConfig.SenderEmail == "" {
return errors.New("SMTP sender email is empty")
}
if options.To == "" {
return errors.New("no receiver emails configured")
}
from := mail.Address{
Name: smtpConfig.SenderIdentity,
Address: smtpConfig.SenderEmail,
}
m := gomail.NewMessage()
m.SetHeader("From", from.String())
m.SetHeader("To", options.To)
m.SetHeader("Subject", options.Subject)
m.SetBody("text/plain", txtBody)
m.AddAlternative("text/html", htmlBody)
d := gomail.NewDialer(smtpConfig.Server, smtpConfig.Port, smtpConfig.SMTPUser, smtpConfig.SMTPPassword)
return d.DialAndSend(m)
} | [
"func",
"send",
"(",
"smtpConfig",
"smtpAuthentication",
",",
"options",
"sendOptions",
",",
"htmlBody",
"string",
",",
"txtBody",
"string",
")",
"error",
"{",
"if",
"smtpConfig",
".",
"Server",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"... | // send sends the email | [
"send",
"sends",
"the",
"email"
] | 2f49bb14de85f0ec4940c93252d0e3289a59d5bd | https://github.com/matcornic/hermes/blob/2f49bb14de85f0ec4940c93252d0e3289a59d5bd/examples/main.go#L136-L177 | train |
matcornic/hermes | hermes.go | ToHTML | func (c Markdown) ToHTML() template.HTML {
return template.HTML(blackfriday.Run([]byte(string(c))))
} | go | func (c Markdown) ToHTML() template.HTML {
return template.HTML(blackfriday.Run([]byte(string(c))))
} | [
"func",
"(",
"c",
"Markdown",
")",
"ToHTML",
"(",
")",
"template",
".",
"HTML",
"{",
"return",
"template",
".",
"HTML",
"(",
"blackfriday",
".",
"Run",
"(",
"[",
"]",
"byte",
"(",
"string",
"(",
"c",
")",
")",
")",
")",
"\n",
"}"
] | // ToHTML converts Markdown to HTML | [
"ToHTML",
"converts",
"Markdown",
"to",
"HTML"
] | 2f49bb14de85f0ec4940c93252d0e3289a59d5bd | https://github.com/matcornic/hermes/blob/2f49bb14de85f0ec4940c93252d0e3289a59d5bd/hermes.go#L76-L78 | train |
matcornic/hermes | hermes.go | setDefaultHermesValues | func setDefaultHermesValues(h *Hermes) error {
defaultTextDirection := TDLeftToRight
defaultHermes := Hermes{
Theme: new(Default),
TextDirection: defaultTextDirection,
Product: Product{
Name: "Hermes",
Copyright: "Copyright © 2019 Hermes. All rights reserved.",
TroubleText: "If you’re having trouble with the button '{ACTION}', copy and paste the URL below into your web browser.",
},
}
// Merge the given hermes engine configuration with default one
// Default one overrides all zero values
err := mergo.Merge(h, defaultHermes)
if err != nil {
return err
}
if h.TextDirection != TDLeftToRight && h.TextDirection != TDRightToLeft {
h.TextDirection = defaultTextDirection
}
return nil
} | go | func setDefaultHermesValues(h *Hermes) error {
defaultTextDirection := TDLeftToRight
defaultHermes := Hermes{
Theme: new(Default),
TextDirection: defaultTextDirection,
Product: Product{
Name: "Hermes",
Copyright: "Copyright © 2019 Hermes. All rights reserved.",
TroubleText: "If you’re having trouble with the button '{ACTION}', copy and paste the URL below into your web browser.",
},
}
// Merge the given hermes engine configuration with default one
// Default one overrides all zero values
err := mergo.Merge(h, defaultHermes)
if err != nil {
return err
}
if h.TextDirection != TDLeftToRight && h.TextDirection != TDRightToLeft {
h.TextDirection = defaultTextDirection
}
return nil
} | [
"func",
"setDefaultHermesValues",
"(",
"h",
"*",
"Hermes",
")",
"error",
"{",
"defaultTextDirection",
":=",
"TDLeftToRight",
"\n",
"defaultHermes",
":=",
"Hermes",
"{",
"Theme",
":",
"new",
"(",
"Default",
")",
",",
"TextDirection",
":",
"defaultTextDirection",
... | // default values of the engine | [
"default",
"values",
"of",
"the",
"engine"
] | 2f49bb14de85f0ec4940c93252d0e3289a59d5bd | https://github.com/matcornic/hermes/blob/2f49bb14de85f0ec4940c93252d0e3289a59d5bd/hermes.go#L138-L159 | train |
matcornic/hermes | hermes.go | GenerateHTML | func (h *Hermes) GenerateHTML(email Email) (string, error) {
err := setDefaultHermesValues(h)
if err != nil {
return "", err
}
return h.generateTemplate(email, h.Theme.HTMLTemplate())
} | go | func (h *Hermes) GenerateHTML(email Email) (string, error) {
err := setDefaultHermesValues(h)
if err != nil {
return "", err
}
return h.generateTemplate(email, h.Theme.HTMLTemplate())
} | [
"func",
"(",
"h",
"*",
"Hermes",
")",
"GenerateHTML",
"(",
"email",
"Email",
")",
"(",
"string",
",",
"error",
")",
"{",
"err",
":=",
"setDefaultHermesValues",
"(",
"h",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\... | // GenerateHTML generates the email body from data to an HTML Reader
// This is for modern email clients | [
"GenerateHTML",
"generates",
"the",
"email",
"body",
"from",
"data",
"to",
"an",
"HTML",
"Reader",
"This",
"is",
"for",
"modern",
"email",
"clients"
] | 2f49bb14de85f0ec4940c93252d0e3289a59d5bd | https://github.com/matcornic/hermes/blob/2f49bb14de85f0ec4940c93252d0e3289a59d5bd/hermes.go#L163-L169 | train |
matcornic/hermes | hermes.go | GeneratePlainText | func (h *Hermes) GeneratePlainText(email Email) (string, error) {
err := setDefaultHermesValues(h)
if err != nil {
return "", err
}
template, err := h.generateTemplate(email, h.Theme.PlainTextTemplate())
if err != nil {
return "", err
}
return html2text.FromString(template, html2text.Options{PrettyTables: true})
} | go | func (h *Hermes) GeneratePlainText(email Email) (string, error) {
err := setDefaultHermesValues(h)
if err != nil {
return "", err
}
template, err := h.generateTemplate(email, h.Theme.PlainTextTemplate())
if err != nil {
return "", err
}
return html2text.FromString(template, html2text.Options{PrettyTables: true})
} | [
"func",
"(",
"h",
"*",
"Hermes",
")",
"GeneratePlainText",
"(",
"email",
"Email",
")",
"(",
"string",
",",
"error",
")",
"{",
"err",
":=",
"setDefaultHermesValues",
"(",
"h",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",... | // GeneratePlainText generates the email body from data
// This is for old email clients | [
"GeneratePlainText",
"generates",
"the",
"email",
"body",
"from",
"data",
"This",
"is",
"for",
"old",
"email",
"clients"
] | 2f49bb14de85f0ec4940c93252d0e3289a59d5bd | https://github.com/matcornic/hermes/blob/2f49bb14de85f0ec4940c93252d0e3289a59d5bd/hermes.go#L173-L183 | train |
jordan-wright/email | pool.go | Send | func (p *Pool) Send(e *Email, timeout time.Duration) (err error) {
start := time.Now()
c := p.get(timeout)
if c == nil {
return p.failedToGet(start)
}
defer func() {
p.maybeReplace(err, c)
}()
recipients, err := addressLists(e.To, e.Cc, e.Bcc)
if err != nil {
return
}
msg, err := e.Bytes()
if err != nil {
return
}
from, err := emailOnly(e.From)
if err != nil {
return
}
if err = c.Mail(from); err != nil {
return
}
for _, recip := range recipients {
if err = c.Rcpt(recip); err != nil {
return
}
}
w, err := c.Data()
if err != nil {
return
}
if _, err = w.Write(msg); err != nil {
return
}
err = w.Close()
return
} | go | func (p *Pool) Send(e *Email, timeout time.Duration) (err error) {
start := time.Now()
c := p.get(timeout)
if c == nil {
return p.failedToGet(start)
}
defer func() {
p.maybeReplace(err, c)
}()
recipients, err := addressLists(e.To, e.Cc, e.Bcc)
if err != nil {
return
}
msg, err := e.Bytes()
if err != nil {
return
}
from, err := emailOnly(e.From)
if err != nil {
return
}
if err = c.Mail(from); err != nil {
return
}
for _, recip := range recipients {
if err = c.Rcpt(recip); err != nil {
return
}
}
w, err := c.Data()
if err != nil {
return
}
if _, err = w.Write(msg); err != nil {
return
}
err = w.Close()
return
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Send",
"(",
"e",
"*",
"Email",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"err",
"error",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"c",
":=",
"p",
".",
"get",
"(",
"timeout",
")... | // Send sends an email via a connection pulled from the Pool. The timeout may
// be <0 to indicate no timeout. Otherwise reaching the timeout will produce
// and error building a connection that occurred while we were waiting, or
// otherwise ErrTimeout. | [
"Send",
"sends",
"an",
"email",
"via",
"a",
"connection",
"pulled",
"from",
"the",
"Pool",
".",
"The",
"timeout",
"may",
"be",
"<0",
"to",
"indicate",
"no",
"timeout",
".",
"Otherwise",
"reaching",
"the",
"timeout",
"will",
"produce",
"and",
"error",
"buil... | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/pool.go#L266-L312 | train |
jordan-wright/email | pool.go | Close | func (p *Pool) Close() {
close(p.closing)
for p.created > 0 {
c := <-p.clients
c.Quit()
p.dec()
}
} | go | func (p *Pool) Close() {
close(p.closing)
for p.created > 0 {
c := <-p.clients
c.Quit()
p.dec()
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Close",
"(",
")",
"{",
"close",
"(",
"p",
".",
"closing",
")",
"\n\n",
"for",
"p",
".",
"created",
">",
"0",
"{",
"c",
":=",
"<-",
"p",
".",
"clients",
"\n",
"c",
".",
"Quit",
"(",
")",
"\n",
"p",
".",
... | // Close immediately changes the pool's state so no new connections will be
// created, then gets and closes the existing ones as they become available. | [
"Close",
"immediately",
"changes",
"the",
"pool",
"s",
"state",
"so",
"no",
"new",
"connections",
"will",
"be",
"created",
"then",
"gets",
"and",
"closes",
"the",
"existing",
"ones",
"as",
"they",
"become",
"available",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/pool.go#L344-L352 | train |
jordan-wright/email | email.go | Read | func (tr trimReader) Read(buf []byte) (int, error) {
n, err := tr.rd.Read(buf)
t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
n = copy(buf, t)
return n, err
} | go | func (tr trimReader) Read(buf []byte) (int, error) {
n, err := tr.rd.Read(buf)
t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
n = copy(buf, t)
return n, err
} | [
"func",
"(",
"tr",
"trimReader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"tr",
".",
"rd",
".",
"Read",
"(",
"buf",
")",
"\n",
"t",
":=",
"bytes",
".",
"TrimLeftFunc",
"(",
"bu... | // Read trims off any unicode whitespace from the originating reader | [
"Read",
"trims",
"off",
"any",
"unicode",
"whitespace",
"from",
"the",
"originating",
"reader"
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L74-L79 | train |
jordan-wright/email | email.go | NewEmailFromReader | func NewEmailFromReader(r io.Reader) (*Email, error) {
e := NewEmail()
s := trimReader{rd: r}
tp := textproto.NewReader(bufio.NewReader(s))
// Parse the main headers
hdrs, err := tp.ReadMIMEHeader()
if err != nil {
return e, err
}
// Set the subject, to, cc, bcc, and from
for h, v := range hdrs {
switch {
case h == "Subject":
e.Subject = v[0]
delete(hdrs, h)
case h == "To":
e.To = v
delete(hdrs, h)
case h == "Cc":
e.Cc = v
delete(hdrs, h)
case h == "Bcc":
e.Bcc = v
delete(hdrs, h)
case h == "From":
e.From = v[0]
delete(hdrs, h)
}
}
e.Headers = hdrs
body := tp.R
// Recursively parse the MIME parts
ps, err := parseMIMEParts(e.Headers, body)
if err != nil {
return e, err
}
for _, p := range ps {
if ct := p.header.Get("Content-Type"); ct == "" {
return e, ErrMissingContentType
}
ct, _, err := mime.ParseMediaType(p.header.Get("Content-Type"))
if err != nil {
return e, err
}
switch {
case ct == "text/plain":
e.Text = p.body
case ct == "text/html":
e.HTML = p.body
}
}
return e, nil
} | go | func NewEmailFromReader(r io.Reader) (*Email, error) {
e := NewEmail()
s := trimReader{rd: r}
tp := textproto.NewReader(bufio.NewReader(s))
// Parse the main headers
hdrs, err := tp.ReadMIMEHeader()
if err != nil {
return e, err
}
// Set the subject, to, cc, bcc, and from
for h, v := range hdrs {
switch {
case h == "Subject":
e.Subject = v[0]
delete(hdrs, h)
case h == "To":
e.To = v
delete(hdrs, h)
case h == "Cc":
e.Cc = v
delete(hdrs, h)
case h == "Bcc":
e.Bcc = v
delete(hdrs, h)
case h == "From":
e.From = v[0]
delete(hdrs, h)
}
}
e.Headers = hdrs
body := tp.R
// Recursively parse the MIME parts
ps, err := parseMIMEParts(e.Headers, body)
if err != nil {
return e, err
}
for _, p := range ps {
if ct := p.header.Get("Content-Type"); ct == "" {
return e, ErrMissingContentType
}
ct, _, err := mime.ParseMediaType(p.header.Get("Content-Type"))
if err != nil {
return e, err
}
switch {
case ct == "text/plain":
e.Text = p.body
case ct == "text/html":
e.HTML = p.body
}
}
return e, nil
} | [
"func",
"NewEmailFromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Email",
",",
"error",
")",
"{",
"e",
":=",
"NewEmail",
"(",
")",
"\n",
"s",
":=",
"trimReader",
"{",
"rd",
":",
"r",
"}",
"\n",
"tp",
":=",
"textproto",
".",
"NewReader",
... | // NewEmailFromReader reads a stream of bytes from an io.Reader, r,
// and returns an email struct containing the parsed data.
// This function expects the data in RFC 5322 format. | [
"NewEmailFromReader",
"reads",
"a",
"stream",
"of",
"bytes",
"from",
"an",
"io",
".",
"Reader",
"r",
"and",
"returns",
"an",
"email",
"struct",
"containing",
"the",
"parsed",
"data",
".",
"This",
"function",
"expects",
"the",
"data",
"in",
"RFC",
"5322",
"... | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L84-L136 | train |
jordan-wright/email | email.go | Attach | func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, r); err != nil {
return
}
at := &Attachment{
Filename: filename,
Header: textproto.MIMEHeader{},
Content: buffer.Bytes(),
}
// Get the Content-Type to be used in the MIMEHeader
if c != "" {
at.Header.Set("Content-Type", c)
} else {
// If the Content-Type is blank, set the Content-Type to "application/octet-stream"
at.Header.Set("Content-Type", "application/octet-stream")
}
at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
at.Header.Set("Content-Transfer-Encoding", "base64")
e.Attachments = append(e.Attachments, at)
return at, nil
} | go | func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, r); err != nil {
return
}
at := &Attachment{
Filename: filename,
Header: textproto.MIMEHeader{},
Content: buffer.Bytes(),
}
// Get the Content-Type to be used in the MIMEHeader
if c != "" {
at.Header.Set("Content-Type", c)
} else {
// If the Content-Type is blank, set the Content-Type to "application/octet-stream"
at.Header.Set("Content-Type", "application/octet-stream")
}
at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
at.Header.Set("Content-Transfer-Encoding", "base64")
e.Attachments = append(e.Attachments, at)
return at, nil
} | [
"func",
"(",
"e",
"*",
"Email",
")",
"Attach",
"(",
"r",
"io",
".",
"Reader",
",",
"filename",
"string",
",",
"c",
"string",
")",
"(",
"a",
"*",
"Attachment",
",",
"err",
"error",
")",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"if",
"_"... | // Attach is used to attach content from an io.Reader to the email.
// Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
// The function will return the created Attachment for reference, as well as nil for the error, if successful. | [
"Attach",
"is",
"used",
"to",
"attach",
"content",
"from",
"an",
"io",
".",
"Reader",
"to",
"the",
"email",
".",
"Required",
"parameters",
"include",
"an",
"io",
".",
"Reader",
"the",
"desired",
"filename",
"for",
"the",
"attachment",
"and",
"the",
"Conten... | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L209-L231 | train |
jordan-wright/email | email.go | AttachFile | func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
f, err := os.Open(filename)
if err != nil {
return
}
defer f.Close()
ct := mime.TypeByExtension(filepath.Ext(filename))
basename := filepath.Base(filename)
return e.Attach(f, basename, ct)
} | go | func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
f, err := os.Open(filename)
if err != nil {
return
}
defer f.Close()
ct := mime.TypeByExtension(filepath.Ext(filename))
basename := filepath.Base(filename)
return e.Attach(f, basename, ct)
} | [
"func",
"(",
"e",
"*",
"Email",
")",
"AttachFile",
"(",
"filename",
"string",
")",
"(",
"a",
"*",
"Attachment",
",",
"err",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // AttachFile is used to attach content to the email.
// It attempts to open the file referenced by filename and, if successful, creates an Attachment.
// This Attachment is then appended to the slice of Email.Attachments.
// The function will then return the Attachment for reference, as well as nil for the error, if successful. | [
"AttachFile",
"is",
"used",
"to",
"attach",
"content",
"to",
"the",
"email",
".",
"It",
"attempts",
"to",
"open",
"the",
"file",
"referenced",
"by",
"filename",
"and",
"if",
"successful",
"creates",
"an",
"Attachment",
".",
"This",
"Attachment",
"is",
"then"... | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L237-L247 | train |
jordan-wright/email | email.go | msgHeaders | func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
res := make(textproto.MIMEHeader, len(e.Headers)+4)
if e.Headers != nil {
for _, h := range []string{"Reply-To", "To", "Cc", "From", "Subject", "Date", "Message-Id", "MIME-Version"} {
if v, ok := e.Headers[h]; ok {
res[h] = v
}
}
}
// Set headers if there are values.
if _, ok := res["Reply-To"]; !ok && len(e.ReplyTo) > 0 {
res.Set("Reply-To", strings.Join(e.ReplyTo, ", "))
}
if _, ok := res["To"]; !ok && len(e.To) > 0 {
res.Set("To", strings.Join(e.To, ", "))
}
if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
res.Set("Cc", strings.Join(e.Cc, ", "))
}
if _, ok := res["Subject"]; !ok && e.Subject != "" {
res.Set("Subject", e.Subject)
}
if _, ok := res["Message-Id"]; !ok {
id, err := generateMessageID()
if err != nil {
return nil, err
}
res.Set("Message-Id", id)
}
// Date and From are required headers.
if _, ok := res["From"]; !ok {
res.Set("From", e.From)
}
if _, ok := res["Date"]; !ok {
res.Set("Date", time.Now().Format(time.RFC1123Z))
}
if _, ok := res["MIME-Version"]; !ok {
res.Set("MIME-Version", "1.0")
}
for field, vals := range e.Headers {
if _, ok := res[field]; !ok {
res[field] = vals
}
}
return res, nil
} | go | func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
res := make(textproto.MIMEHeader, len(e.Headers)+4)
if e.Headers != nil {
for _, h := range []string{"Reply-To", "To", "Cc", "From", "Subject", "Date", "Message-Id", "MIME-Version"} {
if v, ok := e.Headers[h]; ok {
res[h] = v
}
}
}
// Set headers if there are values.
if _, ok := res["Reply-To"]; !ok && len(e.ReplyTo) > 0 {
res.Set("Reply-To", strings.Join(e.ReplyTo, ", "))
}
if _, ok := res["To"]; !ok && len(e.To) > 0 {
res.Set("To", strings.Join(e.To, ", "))
}
if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
res.Set("Cc", strings.Join(e.Cc, ", "))
}
if _, ok := res["Subject"]; !ok && e.Subject != "" {
res.Set("Subject", e.Subject)
}
if _, ok := res["Message-Id"]; !ok {
id, err := generateMessageID()
if err != nil {
return nil, err
}
res.Set("Message-Id", id)
}
// Date and From are required headers.
if _, ok := res["From"]; !ok {
res.Set("From", e.From)
}
if _, ok := res["Date"]; !ok {
res.Set("Date", time.Now().Format(time.RFC1123Z))
}
if _, ok := res["MIME-Version"]; !ok {
res.Set("MIME-Version", "1.0")
}
for field, vals := range e.Headers {
if _, ok := res[field]; !ok {
res[field] = vals
}
}
return res, nil
} | [
"func",
"(",
"e",
"*",
"Email",
")",
"msgHeaders",
"(",
")",
"(",
"textproto",
".",
"MIMEHeader",
",",
"error",
")",
"{",
"res",
":=",
"make",
"(",
"textproto",
".",
"MIMEHeader",
",",
"len",
"(",
"e",
".",
"Headers",
")",
"+",
"4",
")",
"\n",
"i... | // msgHeaders merges the Email's various fields and custom headers together in a
// standards compliant way to create a MIMEHeader to be used in the resulting
// message. It does not alter e.Headers.
//
// "e"'s fields To, Cc, From, Subject will be used unless they are present in
// e.Headers. Unless set in e.Headers, "Date" will filled with the current time. | [
"msgHeaders",
"merges",
"the",
"Email",
"s",
"various",
"fields",
"and",
"custom",
"headers",
"together",
"in",
"a",
"standards",
"compliant",
"way",
"to",
"create",
"a",
"MIMEHeader",
"to",
"be",
"used",
"in",
"the",
"resulting",
"message",
".",
"It",
"does... | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L255-L300 | train |
jordan-wright/email | email.go | parseSender | func (e *Email) parseSender() (string, error) {
if e.Sender != "" {
sender, err := mail.ParseAddress(e.Sender)
if err != nil {
return "", err
}
return sender.Address, nil
} else {
from, err := mail.ParseAddress(e.From)
if err != nil {
return "", err
}
return from.Address, nil
}
} | go | func (e *Email) parseSender() (string, error) {
if e.Sender != "" {
sender, err := mail.ParseAddress(e.Sender)
if err != nil {
return "", err
}
return sender.Address, nil
} else {
from, err := mail.ParseAddress(e.From)
if err != nil {
return "", err
}
return from.Address, nil
}
} | [
"func",
"(",
"e",
"*",
"Email",
")",
"parseSender",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"e",
".",
"Sender",
"!=",
"\"",
"\"",
"{",
"sender",
",",
"err",
":=",
"mail",
".",
"ParseAddress",
"(",
"e",
".",
"Sender",
")",
"\n",
"... | // Select and parse an SMTP envelope sender address. Choose Email.Sender if set, or fallback to Email.From. | [
"Select",
"and",
"parse",
"an",
"SMTP",
"envelope",
"sender",
"address",
".",
"Choose",
"Email",
".",
"Sender",
"if",
"set",
"or",
"fallback",
"to",
"Email",
".",
"From",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L439-L453 | train |
jordan-wright/email | email.go | SendWithTLS | func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
// Merge the To, Cc, and Bcc fields
to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
for i := 0; i < len(to); i++ {
addr, err := mail.ParseAddress(to[i])
if err != nil {
return err
}
to[i] = addr.Address
}
// Check to make sure there is at least one recipient and one "From" address
if e.From == "" || len(to) == 0 {
return errors.New("Must specify at least one From address and one To address")
}
sender, err := e.parseSender()
if err != nil {
return err
}
raw, err := e.Bytes()
if err != nil {
return err
}
conn, err := tls.Dial("tcp", addr, t)
if err != nil {
return err
}
c, err := smtp.NewClient(conn, t.ServerName)
if err != nil {
return err
}
defer c.Close()
if err = c.Hello("localhost"); err != nil {
return err
}
// Use TLS if available
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(t); err != nil {
return err
}
}
if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return err
}
}
}
if err = c.Mail(sender); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(raw)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
} | go | func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
// Merge the To, Cc, and Bcc fields
to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
for i := 0; i < len(to); i++ {
addr, err := mail.ParseAddress(to[i])
if err != nil {
return err
}
to[i] = addr.Address
}
// Check to make sure there is at least one recipient and one "From" address
if e.From == "" || len(to) == 0 {
return errors.New("Must specify at least one From address and one To address")
}
sender, err := e.parseSender()
if err != nil {
return err
}
raw, err := e.Bytes()
if err != nil {
return err
}
conn, err := tls.Dial("tcp", addr, t)
if err != nil {
return err
}
c, err := smtp.NewClient(conn, t.ServerName)
if err != nil {
return err
}
defer c.Close()
if err = c.Hello("localhost"); err != nil {
return err
}
// Use TLS if available
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(t); err != nil {
return err
}
}
if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return err
}
}
}
if err = c.Mail(sender); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(raw)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
} | [
"func",
"(",
"e",
"*",
"Email",
")",
"SendWithTLS",
"(",
"addr",
"string",
",",
"a",
"smtp",
".",
"Auth",
",",
"t",
"*",
"tls",
".",
"Config",
")",
"error",
"{",
"// Merge the To, Cc, and Bcc fields",
"to",
":=",
"make",
"(",
"[",
"]",
"string",
",",
... | // SendWithTLS sends an email with an optional TLS config.
// This is helpful if you need to connect to a host that is used an untrusted
// certificate. | [
"SendWithTLS",
"sends",
"an",
"email",
"with",
"an",
"optional",
"TLS",
"config",
".",
"This",
"is",
"helpful",
"if",
"you",
"need",
"to",
"connect",
"to",
"a",
"host",
"that",
"is",
"used",
"an",
"untrusted",
"certificate",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L458-L530 | train |
kata-containers/agent | namespace.go | setupPersistentNs | func setupPersistentNs(namespaceType nsType) (*namespace, error) {
err := os.MkdirAll(persistentNsDir, 0755)
if err != nil {
return nil, err
}
// Create an empty file at the mount point.
nsPath := filepath.Join(persistentNsDir, string(namespaceType))
mountFd, err := os.Create(nsPath)
if err != nil {
return nil, err
}
mountFd.Close()
var wg sync.WaitGroup
wg.Add(1)
go (func() {
defer wg.Done()
runtime.LockOSThread()
var origNsFd *os.File
origNsPath := getCurrentThreadNSPath(namespaceType)
origNsFd, err = os.Open(origNsPath)
if err != nil {
return
}
defer origNsFd.Close()
// Create a new netns on the current thread.
err = unix.Unshare(cloneFlagsTable[namespaceType])
if err != nil {
return
}
// Bind mount the new namespace from the current thread onto the mount point to persist it.
err = unix.Mount(getCurrentThreadNSPath(namespaceType), nsPath, "none", unix.MS_BIND, "")
if err != nil {
return
}
// Switch back to original namespace.
if err = unix.Setns(int(origNsFd.Fd()), cloneFlagsTable[namespaceType]); err != nil {
return
}
})()
wg.Wait()
if err != nil {
unix.Unmount(nsPath, unix.MNT_DETACH)
return nil, fmt.Errorf("failed to create namespace: %v", err)
}
return &namespace{path: nsPath}, nil
} | go | func setupPersistentNs(namespaceType nsType) (*namespace, error) {
err := os.MkdirAll(persistentNsDir, 0755)
if err != nil {
return nil, err
}
// Create an empty file at the mount point.
nsPath := filepath.Join(persistentNsDir, string(namespaceType))
mountFd, err := os.Create(nsPath)
if err != nil {
return nil, err
}
mountFd.Close()
var wg sync.WaitGroup
wg.Add(1)
go (func() {
defer wg.Done()
runtime.LockOSThread()
var origNsFd *os.File
origNsPath := getCurrentThreadNSPath(namespaceType)
origNsFd, err = os.Open(origNsPath)
if err != nil {
return
}
defer origNsFd.Close()
// Create a new netns on the current thread.
err = unix.Unshare(cloneFlagsTable[namespaceType])
if err != nil {
return
}
// Bind mount the new namespace from the current thread onto the mount point to persist it.
err = unix.Mount(getCurrentThreadNSPath(namespaceType), nsPath, "none", unix.MS_BIND, "")
if err != nil {
return
}
// Switch back to original namespace.
if err = unix.Setns(int(origNsFd.Fd()), cloneFlagsTable[namespaceType]); err != nil {
return
}
})()
wg.Wait()
if err != nil {
unix.Unmount(nsPath, unix.MNT_DETACH)
return nil, fmt.Errorf("failed to create namespace: %v", err)
}
return &namespace{path: nsPath}, nil
} | [
"func",
"setupPersistentNs",
"(",
"namespaceType",
"nsType",
")",
"(",
"*",
"namespace",
",",
"error",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"persistentNsDir",
",",
"0755",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"e... | // setupPersistentNs creates persistent namespace without switchin to it.
// Note, pid namespaces cannot be persisted. | [
"setupPersistentNs",
"creates",
"persistent",
"namespace",
"without",
"switchin",
"to",
"it",
".",
"Note",
"pid",
"namespaces",
"cannot",
"be",
"persisted",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/namespace.go#L49-L106 | train |
kata-containers/agent | protocols/mockserver/mockserver.go | NewMockServer | func NewMockServer() *grpc.Server {
mock := &mockServer{}
serv := grpc.NewServer()
pb.RegisterAgentServiceServer(serv, mock)
pb.RegisterHealthServer(serv, mock)
return serv
} | go | func NewMockServer() *grpc.Server {
mock := &mockServer{}
serv := grpc.NewServer()
pb.RegisterAgentServiceServer(serv, mock)
pb.RegisterHealthServer(serv, mock)
return serv
} | [
"func",
"NewMockServer",
"(",
")",
"*",
"grpc",
".",
"Server",
"{",
"mock",
":=",
"&",
"mockServer",
"{",
"}",
"\n",
"serv",
":=",
"grpc",
".",
"NewServer",
"(",
")",
"\n",
"pb",
".",
"RegisterAgentServiceServer",
"(",
"serv",
",",
"mock",
")",
"\n",
... | // NewMockServer creates a new gRPC server | [
"NewMockServer",
"creates",
"a",
"new",
"gRPC",
"server"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/mockserver/mockserver.go#L51-L58 | train |
kata-containers/agent | cgroup.go | getAvailableCpusetList | func getAvailableCpusetList(cpusetReq string) (string, error) {
cpusetGuest, err := getCpusetGuest()
if err != nil {
return "", err
}
cpusetListReq, err := parsers.ParseUintList(cpusetReq)
if err != nil {
return "", err
}
cpusetGuestList, err := parsers.ParseUintList(cpusetGuest)
if err != nil {
return "", err
}
for k := range cpusetListReq {
if !cpusetGuestList[k] {
agentLog.WithFields(logrus.Fields{
"cpuset": cpusetReq,
"cpu": k,
"guest-cpus": cpusetGuest,
}).Warnf("cpu is not in guest cpu list, using guest cpus")
return cpusetGuest, nil
}
}
// All the cpus are valid keep the same cpuset string
agentLog.WithFields(logrus.Fields{
"cpuset": cpusetReq,
}).Debugf("the requested cpuset is valid, using it")
return cpusetReq, nil
} | go | func getAvailableCpusetList(cpusetReq string) (string, error) {
cpusetGuest, err := getCpusetGuest()
if err != nil {
return "", err
}
cpusetListReq, err := parsers.ParseUintList(cpusetReq)
if err != nil {
return "", err
}
cpusetGuestList, err := parsers.ParseUintList(cpusetGuest)
if err != nil {
return "", err
}
for k := range cpusetListReq {
if !cpusetGuestList[k] {
agentLog.WithFields(logrus.Fields{
"cpuset": cpusetReq,
"cpu": k,
"guest-cpus": cpusetGuest,
}).Warnf("cpu is not in guest cpu list, using guest cpus")
return cpusetGuest, nil
}
}
// All the cpus are valid keep the same cpuset string
agentLog.WithFields(logrus.Fields{
"cpuset": cpusetReq,
}).Debugf("the requested cpuset is valid, using it")
return cpusetReq, nil
} | [
"func",
"getAvailableCpusetList",
"(",
"cpusetReq",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"cpusetGuest",
",",
"err",
":=",
"getCpusetGuest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n... | // Return the best match for cpuset list in the guest.
// The runtime caller may apply cpuset for specific CPUs in the host.
// The CPUs may not exist on the guest as they are hotplugged based
// on cpu and qouta.
// This function return a working cpuset to apply on the guest. | [
"Return",
"the",
"best",
"match",
"for",
"cpuset",
"list",
"in",
"the",
"guest",
".",
"The",
"runtime",
"caller",
"may",
"apply",
"cpuset",
"for",
"specific",
"CPUs",
"in",
"the",
"host",
".",
"The",
"CPUs",
"may",
"not",
"exist",
"on",
"the",
"guest",
... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/cgroup.go#L32-L65 | train |
kata-containers/agent | protocols/grpc/utils.go | OCItoGRPC | func OCItoGRPC(ociSpec *specs.Spec) (*Spec, error) {
s := &Spec{}
err := copyStruct(s, ociSpec)
return s, err
} | go | func OCItoGRPC(ociSpec *specs.Spec) (*Spec, error) {
s := &Spec{}
err := copyStruct(s, ociSpec)
return s, err
} | [
"func",
"OCItoGRPC",
"(",
"ociSpec",
"*",
"specs",
".",
"Spec",
")",
"(",
"*",
"Spec",
",",
"error",
")",
"{",
"s",
":=",
"&",
"Spec",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
"ociSpec",
")",
"\n\n",
"return",
"s",
",",
"err",
... | // OCItoGRPC converts an OCI specification to its gRPC representation | [
"OCItoGRPC",
"converts",
"an",
"OCI",
"specification",
"to",
"its",
"gRPC",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L234-L240 | train |
kata-containers/agent | protocols/grpc/utils.go | GRPCtoOCI | func GRPCtoOCI(grpcSpec *Spec) (*specs.Spec, error) {
s := &specs.Spec{}
err := copyStruct(s, grpcSpec)
return s, err
} | go | func GRPCtoOCI(grpcSpec *Spec) (*specs.Spec, error) {
s := &specs.Spec{}
err := copyStruct(s, grpcSpec)
return s, err
} | [
"func",
"GRPCtoOCI",
"(",
"grpcSpec",
"*",
"Spec",
")",
"(",
"*",
"specs",
".",
"Spec",
",",
"error",
")",
"{",
"s",
":=",
"&",
"specs",
".",
"Spec",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
"grpcSpec",
")",
"\n\n",
"return",
"... | // GRPCtoOCI converts a gRPC specification back into an OCI representation | [
"GRPCtoOCI",
"converts",
"a",
"gRPC",
"specification",
"back",
"into",
"an",
"OCI",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L243-L249 | train |
kata-containers/agent | protocols/grpc/utils.go | ProcessOCItoGRPC | func ProcessOCItoGRPC(ociProcess *specs.Process) (*Process, error) {
s := &Process{}
err := copyStruct(s, ociProcess)
return s, err
} | go | func ProcessOCItoGRPC(ociProcess *specs.Process) (*Process, error) {
s := &Process{}
err := copyStruct(s, ociProcess)
return s, err
} | [
"func",
"ProcessOCItoGRPC",
"(",
"ociProcess",
"*",
"specs",
".",
"Process",
")",
"(",
"*",
"Process",
",",
"error",
")",
"{",
"s",
":=",
"&",
"Process",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
"ociProcess",
")",
"\n\n",
"return",
... | // ProcessOCItoGRPC converts an OCI process specification into its gRPC
// representation | [
"ProcessOCItoGRPC",
"converts",
"an",
"OCI",
"process",
"specification",
"into",
"its",
"gRPC",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L253-L259 | train |
kata-containers/agent | protocols/grpc/utils.go | ProcessGRPCtoOCI | func ProcessGRPCtoOCI(grpcProcess *Process) (*specs.Process, error) {
s := &specs.Process{}
err := copyStruct(s, grpcProcess)
return s, err
} | go | func ProcessGRPCtoOCI(grpcProcess *Process) (*specs.Process, error) {
s := &specs.Process{}
err := copyStruct(s, grpcProcess)
return s, err
} | [
"func",
"ProcessGRPCtoOCI",
"(",
"grpcProcess",
"*",
"Process",
")",
"(",
"*",
"specs",
".",
"Process",
",",
"error",
")",
"{",
"s",
":=",
"&",
"specs",
".",
"Process",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
"grpcProcess",
")",
"... | // ProcessGRPCtoOCI converts a gRPC specification back into an OCI
// representation | [
"ProcessGRPCtoOCI",
"converts",
"a",
"gRPC",
"specification",
"back",
"into",
"an",
"OCI",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L263-L269 | train |
kata-containers/agent | protocols/grpc/utils.go | ResourcesOCItoGRPC | func ResourcesOCItoGRPC(ociResources *specs.LinuxResources) (*LinuxResources, error) {
s := &LinuxResources{}
err := copyStruct(s, ociResources)
return s, err
} | go | func ResourcesOCItoGRPC(ociResources *specs.LinuxResources) (*LinuxResources, error) {
s := &LinuxResources{}
err := copyStruct(s, ociResources)
return s, err
} | [
"func",
"ResourcesOCItoGRPC",
"(",
"ociResources",
"*",
"specs",
".",
"LinuxResources",
")",
"(",
"*",
"LinuxResources",
",",
"error",
")",
"{",
"s",
":=",
"&",
"LinuxResources",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
"ociResources",
"... | // ResourcesOCItoGRPC converts an OCI LinuxResources specification into its gRPC
// representation | [
"ResourcesOCItoGRPC",
"converts",
"an",
"OCI",
"LinuxResources",
"specification",
"into",
"its",
"gRPC",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L273-L279 | train |
kata-containers/agent | protocols/grpc/utils.go | ResourcesGRPCtoOCI | func ResourcesGRPCtoOCI(grpcResources *LinuxResources) (*specs.LinuxResources, error) {
s := &specs.LinuxResources{}
err := copyStruct(s, grpcResources)
return s, err
} | go | func ResourcesGRPCtoOCI(grpcResources *LinuxResources) (*specs.LinuxResources, error) {
s := &specs.LinuxResources{}
err := copyStruct(s, grpcResources)
return s, err
} | [
"func",
"ResourcesGRPCtoOCI",
"(",
"grpcResources",
"*",
"LinuxResources",
")",
"(",
"*",
"specs",
".",
"LinuxResources",
",",
"error",
")",
"{",
"s",
":=",
"&",
"specs",
".",
"LinuxResources",
"{",
"}",
"\n\n",
"err",
":=",
"copyStruct",
"(",
"s",
",",
... | // ResourcesGRPCtoOCI converts an gRPC LinuxResources specification into its OCI
// representation | [
"ResourcesGRPCtoOCI",
"converts",
"an",
"gRPC",
"LinuxResources",
"specification",
"into",
"its",
"OCI",
"representation"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/grpc/utils.go#L283-L289 | train |
kata-containers/agent | protocols/client/client.go | heartBeat | func heartBeat(session *yamux.Session) {
if session == nil {
return
}
for {
if session.IsClosed() {
break
}
session.Ping()
// 1 Hz heartbeat
time.Sleep(time.Second)
}
} | go | func heartBeat(session *yamux.Session) {
if session == nil {
return
}
for {
if session.IsClosed() {
break
}
session.Ping()
// 1 Hz heartbeat
time.Sleep(time.Second)
}
} | [
"func",
"heartBeat",
"(",
"session",
"*",
"yamux",
".",
"Session",
")",
"{",
"if",
"session",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"{",
"if",
"session",
".",
"IsClosed",
"(",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"session",
".",
"P... | // This function is meant to run in a go routine since it will send ping
// commands every second. It behaves as a heartbeat to maintain a proper
// communication state with the Yamux server in the agent. | [
"This",
"function",
"is",
"meant",
"to",
"run",
"in",
"a",
"go",
"routine",
"since",
"it",
"will",
"send",
"ping",
"commands",
"every",
"second",
".",
"It",
"behaves",
"as",
"a",
"heartbeat",
"to",
"maintain",
"a",
"proper",
"communication",
"state",
"with... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/client/client.go#L171-L186 | train |
kata-containers/agent | mount.go | ensureDestinationExists | func ensureDestinationExists(source, destination string, fsType string) error {
fileInfo, err := os.Stat(source)
if err != nil {
return grpcStatus.Errorf(codes.Internal, "could not stat source location: %v",
source)
}
if err := createDestinationDir(destination); err != nil {
return grpcStatus.Errorf(codes.Internal, "could not create parent directory: %v",
destination)
}
if fsType != "bind" || fileInfo.IsDir() {
if err := os.Mkdir(destination, mountPerm); !os.IsExist(err) {
return err
}
} else {
file, err := os.OpenFile(destination, os.O_CREATE, mountPerm)
if err != nil {
return err
}
file.Close()
}
return nil
} | go | func ensureDestinationExists(source, destination string, fsType string) error {
fileInfo, err := os.Stat(source)
if err != nil {
return grpcStatus.Errorf(codes.Internal, "could not stat source location: %v",
source)
}
if err := createDestinationDir(destination); err != nil {
return grpcStatus.Errorf(codes.Internal, "could not create parent directory: %v",
destination)
}
if fsType != "bind" || fileInfo.IsDir() {
if err := os.Mkdir(destination, mountPerm); !os.IsExist(err) {
return err
}
} else {
file, err := os.OpenFile(destination, os.O_CREATE, mountPerm)
if err != nil {
return err
}
file.Close()
}
return nil
} | [
"func",
"ensureDestinationExists",
"(",
"source",
",",
"destination",
"string",
",",
"fsType",
"string",
")",
"error",
"{",
"fileInfo",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"grpcStatus",
... | // ensureDestinationExists will recursively create a given mountpoint. If directories
// are created, their permissions are initialized to mountPerm | [
"ensureDestinationExists",
"will",
"recursively",
"create",
"a",
"given",
"mountpoint",
".",
"If",
"directories",
"are",
"created",
"their",
"permissions",
"are",
"initialized",
"to",
"mountPerm"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L134-L159 | train |
kata-containers/agent | mount.go | virtio9pStorageHandler | func virtio9pStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
return commonStorageHandler(storage)
} | go | func virtio9pStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
return commonStorageHandler(storage)
} | [
"func",
"virtio9pStorageHandler",
"(",
"storage",
"pb",
".",
"Storage",
",",
"s",
"*",
"sandbox",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"commonStorageHandler",
"(",
"storage",
")",
"\n",
"}"
] | // virtio9pStorageHandler handles the storage for 9p driver. | [
"virtio9pStorageHandler",
"handles",
"the",
"storage",
"for",
"9p",
"driver",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L257-L259 | train |
kata-containers/agent | mount.go | virtioBlkStorageHandler | func virtioBlkStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
// Get the device node path based on the PCI address provided
// in Storage Source
devPath, err := getPCIDeviceName(s, storage.Source)
if err != nil {
return "", err
}
storage.Source = devPath
return commonStorageHandler(storage)
} | go | func virtioBlkStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
// Get the device node path based on the PCI address provided
// in Storage Source
devPath, err := getPCIDeviceName(s, storage.Source)
if err != nil {
return "", err
}
storage.Source = devPath
return commonStorageHandler(storage)
} | [
"func",
"virtioBlkStorageHandler",
"(",
"storage",
"pb",
".",
"Storage",
",",
"s",
"*",
"sandbox",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Get the device node path based on the PCI address provided",
"// in Storage Source",
"devPath",
",",
"err",
":=",
"getPCI... | // virtioBlkStorageHandler handles the storage for blk driver. | [
"virtioBlkStorageHandler",
"handles",
"the",
"storage",
"for",
"blk",
"driver",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L273-L283 | train |
kata-containers/agent | mount.go | virtioSCSIStorageHandler | func virtioSCSIStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
// Retrieve the device path from SCSI address.
devPath, err := getSCSIDevPath(storage.Source)
if err != nil {
return "", err
}
storage.Source = devPath
return commonStorageHandler(storage)
} | go | func virtioSCSIStorageHandler(storage pb.Storage, s *sandbox) (string, error) {
// Retrieve the device path from SCSI address.
devPath, err := getSCSIDevPath(storage.Source)
if err != nil {
return "", err
}
storage.Source = devPath
return commonStorageHandler(storage)
} | [
"func",
"virtioSCSIStorageHandler",
"(",
"storage",
"pb",
".",
"Storage",
",",
"s",
"*",
"sandbox",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Retrieve the device path from SCSI address.",
"devPath",
",",
"err",
":=",
"getSCSIDevPath",
"(",
"storage",
".",
... | // virtioSCSIStorageHandler handles the storage for scsi driver. | [
"virtioSCSIStorageHandler",
"handles",
"the",
"storage",
"for",
"scsi",
"driver",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L286-L295 | train |
kata-containers/agent | mount.go | mountStorage | func mountStorage(storage pb.Storage) error {
flags, options, err := parseMountFlagsAndOptions(storage.Options)
if err != nil {
return err
}
return mount(storage.Source, storage.MountPoint, storage.Fstype, flags, options)
} | go | func mountStorage(storage pb.Storage) error {
flags, options, err := parseMountFlagsAndOptions(storage.Options)
if err != nil {
return err
}
return mount(storage.Source, storage.MountPoint, storage.Fstype, flags, options)
} | [
"func",
"mountStorage",
"(",
"storage",
"pb",
".",
"Storage",
")",
"error",
"{",
"flags",
",",
"options",
",",
"err",
":=",
"parseMountFlagsAndOptions",
"(",
"storage",
".",
"Options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",... | // mountStorage performs the mount described by the storage structure. | [
"mountStorage",
"performs",
"the",
"mount",
"described",
"by",
"the",
"storage",
"structure",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L307-L314 | train |
kata-containers/agent | mount.go | addStorages | func addStorages(ctx context.Context, storages []*pb.Storage, s *sandbox) ([]string, error) {
span, ctx := trace(ctx, "mount", "addStorages")
span.SetTag("sandbox", s.id)
defer span.Finish()
var mountList []string
for _, storage := range storages {
if storage == nil {
continue
}
devHandler, ok := storageHandlerList[storage.Driver]
if !ok {
return nil, grpcStatus.Errorf(codes.InvalidArgument,
"Unknown storage driver %q", storage.Driver)
}
// Wrap the span around the handler call to avoid modifying
// the handler interface but also to avoid having to add trace
// code to each driver.
handlerSpan, _ := trace(ctx, "mount", storage.Driver)
mountPoint, err := devHandler(*storage, s)
handlerSpan.Finish()
if err != nil {
return nil, err
}
if mountPoint != "" {
// Prepend mount point to mount list.
mountList = append([]string{mountPoint}, mountList...)
}
}
return mountList, nil
} | go | func addStorages(ctx context.Context, storages []*pb.Storage, s *sandbox) ([]string, error) {
span, ctx := trace(ctx, "mount", "addStorages")
span.SetTag("sandbox", s.id)
defer span.Finish()
var mountList []string
for _, storage := range storages {
if storage == nil {
continue
}
devHandler, ok := storageHandlerList[storage.Driver]
if !ok {
return nil, grpcStatus.Errorf(codes.InvalidArgument,
"Unknown storage driver %q", storage.Driver)
}
// Wrap the span around the handler call to avoid modifying
// the handler interface but also to avoid having to add trace
// code to each driver.
handlerSpan, _ := trace(ctx, "mount", storage.Driver)
mountPoint, err := devHandler(*storage, s)
handlerSpan.Finish()
if err != nil {
return nil, err
}
if mountPoint != "" {
// Prepend mount point to mount list.
mountList = append([]string{mountPoint}, mountList...)
}
}
return mountList, nil
} | [
"func",
"addStorages",
"(",
"ctx",
"context",
".",
"Context",
",",
"storages",
"[",
"]",
"*",
"pb",
".",
"Storage",
",",
"s",
"*",
"sandbox",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"trace",
"(",
"ctx",
","... | // addStorages takes a list of storages passed by the caller, and perform the
// associated operations such as waiting for the device to show up, and mount
// it to a specific location, according to the type of handler chosen, and for
// each storage. | [
"addStorages",
"takes",
"a",
"list",
"of",
"storages",
"passed",
"by",
"the",
"caller",
"and",
"perform",
"the",
"associated",
"operations",
"such",
"as",
"waiting",
"for",
"the",
"device",
"to",
"show",
"up",
"and",
"mount",
"it",
"to",
"a",
"specific",
"... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L320-L356 | train |
kata-containers/agent | config.go | getConfig | func (c *agentConfig) getConfig(cmdLineFile string) error {
if cmdLineFile == "" {
return grpcStatus.Error(codes.FailedPrecondition, "Kernel cmdline file cannot be empty")
}
kernelCmdline, err := ioutil.ReadFile(cmdLineFile)
if err != nil {
return err
}
words := strings.Fields(string(kernelCmdline))
for _, word := range words {
if err := c.parseCmdlineOption(word); err != nil {
agentLog.WithFields(logrus.Fields{
"error": err,
"option": word,
}).Warn("Failed to parse kernel option")
}
}
return nil
} | go | func (c *agentConfig) getConfig(cmdLineFile string) error {
if cmdLineFile == "" {
return grpcStatus.Error(codes.FailedPrecondition, "Kernel cmdline file cannot be empty")
}
kernelCmdline, err := ioutil.ReadFile(cmdLineFile)
if err != nil {
return err
}
words := strings.Fields(string(kernelCmdline))
for _, word := range words {
if err := c.parseCmdlineOption(word); err != nil {
agentLog.WithFields(logrus.Fields{
"error": err,
"option": word,
}).Warn("Failed to parse kernel option")
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"agentConfig",
")",
"getConfig",
"(",
"cmdLineFile",
"string",
")",
"error",
"{",
"if",
"cmdLineFile",
"==",
"\"",
"\"",
"{",
"return",
"grpcStatus",
".",
"Error",
"(",
"codes",
".",
"FailedPrecondition",
",",
"\"",
"\"",
")",
"\n"... | //Get the agent configuration from kernel cmdline | [
"Get",
"the",
"agent",
"configuration",
"from",
"kernel",
"cmdline"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/config.go#L44-L65 | train |
kata-containers/agent | config.go | parseCmdlineOption | func (c *agentConfig) parseCmdlineOption(option string) error {
const (
optionPosition = iota
valuePosition
optionSeparator = "="
)
if option == devModeFlag {
crashOnError = true
debug = true
return nil
}
if option == traceModeFlag {
enableTracing(traceModeStatic, defaultTraceType)
return nil
}
split := strings.Split(option, optionSeparator)
if len(split) < valuePosition+1 {
return nil
}
switch split[optionPosition] {
case logLevelFlag:
level, err := logrus.ParseLevel(split[valuePosition])
if err != nil {
return err
}
c.logLevel = level
if level == logrus.DebugLevel {
debug = true
}
case traceModeFlag:
switch split[valuePosition] {
case traceTypeIsolated:
enableTracing(traceModeStatic, traceTypeIsolated)
case traceTypeCollated:
enableTracing(traceModeStatic, traceTypeCollated)
}
case useVsockFlag:
flag, err := strconv.ParseBool(split[valuePosition])
if err != nil {
return err
}
if flag {
agentLog.Debug("Param passed to use vsock channel")
commCh = vsockCh
} else {
agentLog.Debug("Param passed to NOT use vsock channel")
commCh = serialCh
}
default:
if strings.HasPrefix(split[optionPosition], optionPrefix) {
return grpcStatus.Errorf(codes.NotFound, "Unknown option %s", split[optionPosition])
}
}
return nil
} | go | func (c *agentConfig) parseCmdlineOption(option string) error {
const (
optionPosition = iota
valuePosition
optionSeparator = "="
)
if option == devModeFlag {
crashOnError = true
debug = true
return nil
}
if option == traceModeFlag {
enableTracing(traceModeStatic, defaultTraceType)
return nil
}
split := strings.Split(option, optionSeparator)
if len(split) < valuePosition+1 {
return nil
}
switch split[optionPosition] {
case logLevelFlag:
level, err := logrus.ParseLevel(split[valuePosition])
if err != nil {
return err
}
c.logLevel = level
if level == logrus.DebugLevel {
debug = true
}
case traceModeFlag:
switch split[valuePosition] {
case traceTypeIsolated:
enableTracing(traceModeStatic, traceTypeIsolated)
case traceTypeCollated:
enableTracing(traceModeStatic, traceTypeCollated)
}
case useVsockFlag:
flag, err := strconv.ParseBool(split[valuePosition])
if err != nil {
return err
}
if flag {
agentLog.Debug("Param passed to use vsock channel")
commCh = vsockCh
} else {
agentLog.Debug("Param passed to NOT use vsock channel")
commCh = serialCh
}
default:
if strings.HasPrefix(split[optionPosition], optionPrefix) {
return grpcStatus.Errorf(codes.NotFound, "Unknown option %s", split[optionPosition])
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"agentConfig",
")",
"parseCmdlineOption",
"(",
"option",
"string",
")",
"error",
"{",
"const",
"(",
"optionPosition",
"=",
"iota",
"\n",
"valuePosition",
"\n",
"optionSeparator",
"=",
"\"",
"\"",
"\n",
")",
"\n\n",
"if",
"option",
"=... | //Parse a string that represents a kernel cmdline option | [
"Parse",
"a",
"string",
"that",
"represents",
"a",
"kernel",
"cmdline",
"option"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/config.go#L68-L130 | train |
kata-containers/agent | pkg/uevent/uevent.go | NewReaderCloser | func NewReaderCloser() (io.ReadCloser, error) {
nl := unix.SockaddrNetlink{
Family: unix.AF_NETLINK,
// Passing Pid as 0 here allows the kernel to take care of assigning
// it. This allows multiple netlink sockets to be used.
Pid: uint32(0),
Groups: 1,
}
fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW, unix.NETLINK_KOBJECT_UEVENT)
if err != nil {
return nil, err
}
if err := unix.Bind(fd, &nl); err != nil {
return nil, err
}
return &ReaderCloser{fd}, nil
} | go | func NewReaderCloser() (io.ReadCloser, error) {
nl := unix.SockaddrNetlink{
Family: unix.AF_NETLINK,
// Passing Pid as 0 here allows the kernel to take care of assigning
// it. This allows multiple netlink sockets to be used.
Pid: uint32(0),
Groups: 1,
}
fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW, unix.NETLINK_KOBJECT_UEVENT)
if err != nil {
return nil, err
}
if err := unix.Bind(fd, &nl); err != nil {
return nil, err
}
return &ReaderCloser{fd}, nil
} | [
"func",
"NewReaderCloser",
"(",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"nl",
":=",
"unix",
".",
"SockaddrNetlink",
"{",
"Family",
":",
"unix",
".",
"AF_NETLINK",
",",
"// Passing Pid as 0 here allows the kernel to take care of assigning",
"// it.... | // NewReaderCloser returns an io.ReadCloser handle for uevent. | [
"NewReaderCloser",
"returns",
"an",
"io",
".",
"ReadCloser",
"handle",
"for",
"uevent",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/pkg/uevent/uevent.go#L36-L55 | train |
kata-containers/agent | pkg/uevent/uevent.go | Read | func (r *ReaderCloser) Read(p []byte) (int, error) {
count, err := unix.Read(r.fd, p)
if count < 0 && err != nil {
count = 0
}
return count, err
} | go | func (r *ReaderCloser) Read(p []byte) (int, error) {
count, err := unix.Read(r.fd, p)
if count < 0 && err != nil {
count = 0
}
return count, err
} | [
"func",
"(",
"r",
"*",
"ReaderCloser",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"unix",
".",
"Read",
"(",
"r",
".",
"fd",
",",
"p",
")",
"\n",
"if",
"count",
"<",
"0",
"&&"... | // Read implements reading function for uevent. | [
"Read",
"implements",
"reading",
"function",
"for",
"uevent",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/pkg/uevent/uevent.go#L58-L64 | train |
kata-containers/agent | pkg/uevent/uevent.go | NewHandler | func NewHandler() (*Handler, error) {
rdCloser, err := NewReaderCloser()
if err != nil {
return nil, err
}
return &Handler{
readerCloser: rdCloser,
bufioReader: bufio.NewReader(rdCloser),
}, nil
} | go | func NewHandler() (*Handler, error) {
rdCloser, err := NewReaderCloser()
if err != nil {
return nil, err
}
return &Handler{
readerCloser: rdCloser,
bufioReader: bufio.NewReader(rdCloser),
}, nil
} | [
"func",
"NewHandler",
"(",
")",
"(",
"*",
"Handler",
",",
"error",
")",
"{",
"rdCloser",
",",
"err",
":=",
"NewReaderCloser",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Handler",
"... | // NewHandler returns a uevent handler. | [
"NewHandler",
"returns",
"a",
"uevent",
"handler",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/pkg/uevent/uevent.go#L88-L98 | train |
kata-containers/agent | pkg/uevent/uevent.go | Read | func (h *Handler) Read() (*Uevent, error) {
uEv := &Uevent{}
// Read header first.
header, err := h.bufioReader.ReadString(paramDelim)
if err != nil {
return nil, err
}
// Fill uevent header.
uEv.Header = header
exitLoop := false
// Read every parameter as "key=value".
for !exitLoop {
keyValue, err := h.bufioReader.ReadString(paramDelim)
if err != nil {
return nil, err
}
idx := strings.Index(keyValue, "=")
if idx < 1 {
return nil, grpcStatus.Errorf(codes.InvalidArgument, "Could not decode uevent: Wrong format %q", keyValue)
}
// The key is the first parameter, and the value is the rest
// without the "=" sign, and without the last character since
// it is the delimiter.
key, val := keyValue[:idx], keyValue[idx+1:len(keyValue)-1]
switch key {
case uEventAction:
uEv.Action = val
case uEventDevPath:
uEv.DevPath = val
case uEventSubSystem:
uEv.SubSystem = val
case uEventDevName:
uEv.DevName = val
case uEventInterface:
// In case of network interfaces, DevName will be empty since a device node
// is not created. Instead store the "INTERFACE" field as devName
uEv.DevName = val
case uEventSeqNum:
uEv.SeqNum = val
// "SEQNUM" signals the uevent is complete.
exitLoop = true
}
}
return uEv, nil
} | go | func (h *Handler) Read() (*Uevent, error) {
uEv := &Uevent{}
// Read header first.
header, err := h.bufioReader.ReadString(paramDelim)
if err != nil {
return nil, err
}
// Fill uevent header.
uEv.Header = header
exitLoop := false
// Read every parameter as "key=value".
for !exitLoop {
keyValue, err := h.bufioReader.ReadString(paramDelim)
if err != nil {
return nil, err
}
idx := strings.Index(keyValue, "=")
if idx < 1 {
return nil, grpcStatus.Errorf(codes.InvalidArgument, "Could not decode uevent: Wrong format %q", keyValue)
}
// The key is the first parameter, and the value is the rest
// without the "=" sign, and without the last character since
// it is the delimiter.
key, val := keyValue[:idx], keyValue[idx+1:len(keyValue)-1]
switch key {
case uEventAction:
uEv.Action = val
case uEventDevPath:
uEv.DevPath = val
case uEventSubSystem:
uEv.SubSystem = val
case uEventDevName:
uEv.DevName = val
case uEventInterface:
// In case of network interfaces, DevName will be empty since a device node
// is not created. Instead store the "INTERFACE" field as devName
uEv.DevName = val
case uEventSeqNum:
uEv.SeqNum = val
// "SEQNUM" signals the uevent is complete.
exitLoop = true
}
}
return uEv, nil
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"Read",
"(",
")",
"(",
"*",
"Uevent",
",",
"error",
")",
"{",
"uEv",
":=",
"&",
"Uevent",
"{",
"}",
"\n\n",
"// Read header first.",
"header",
",",
"err",
":=",
"h",
".",
"bufioReader",
".",
"ReadString",
"(",
... | // Read blocks and returns the next uevent when available. | [
"Read",
"blocks",
"and",
"returns",
"the",
"next",
"uevent",
"when",
"available",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/pkg/uevent/uevent.go#L101-L154 | train |
kata-containers/agent | channel.go | Write | func (yw yamuxWriter) Write(bytes []byte) (int, error) {
message := string(bytes)
l := len(message)
// yamux messages are all warnings and errors
agentLog.WithField("component", "yamux").Warn(message)
return l, nil
} | go | func (yw yamuxWriter) Write(bytes []byte) (int, error) {
message := string(bytes)
l := len(message)
// yamux messages are all warnings and errors
agentLog.WithField("component", "yamux").Warn(message)
return l, nil
} | [
"func",
"(",
"yw",
"yamuxWriter",
")",
"Write",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"message",
":=",
"string",
"(",
"bytes",
")",
"\n\n",
"l",
":=",
"len",
"(",
"message",
")",
"\n\n",
"// yamux messages are all war... | // Write implements the Writer interface for the yamuxWriter. | [
"Write",
"implements",
"the",
"Writer",
"interface",
"for",
"the",
"yamuxWriter",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/channel.go#L226-L235 | train |
kata-containers/agent | channel.go | isAFVSockSupported | func isAFVSockSupported() (bool, error) {
// Driver path for virtio-vsock
sysVsockPath := "/sys/bus/virtio/drivers/vmw_vsock_virtio_transport/"
files, err := ioutil.ReadDir(sysVsockPath)
// This should not happen for a hypervisor with vsock driver
if err != nil {
return false, err
}
// standard driver files that should be ignored
driverFiles := []string{"bind", "uevent", "unbind"}
for _, file := range files {
for _, f := range driverFiles {
if file.Name() == f {
continue
}
}
fPath := filepath.Join(sysVsockPath, file.Name())
fInfo, err := os.Lstat(fPath)
if err != nil {
return false, err
}
if fInfo.Mode()&os.ModeSymlink == 0 {
continue
}
link, err := os.Readlink(fPath)
if err != nil {
return false, err
}
if strings.Contains(link, "devices") {
return true, nil
}
}
return false, nil
} | go | func isAFVSockSupported() (bool, error) {
// Driver path for virtio-vsock
sysVsockPath := "/sys/bus/virtio/drivers/vmw_vsock_virtio_transport/"
files, err := ioutil.ReadDir(sysVsockPath)
// This should not happen for a hypervisor with vsock driver
if err != nil {
return false, err
}
// standard driver files that should be ignored
driverFiles := []string{"bind", "uevent", "unbind"}
for _, file := range files {
for _, f := range driverFiles {
if file.Name() == f {
continue
}
}
fPath := filepath.Join(sysVsockPath, file.Name())
fInfo, err := os.Lstat(fPath)
if err != nil {
return false, err
}
if fInfo.Mode()&os.ModeSymlink == 0 {
continue
}
link, err := os.Readlink(fPath)
if err != nil {
return false, err
}
if strings.Contains(link, "devices") {
return true, nil
}
}
return false, nil
} | [
"func",
"isAFVSockSupported",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Driver path for virtio-vsock",
"sysVsockPath",
":=",
"\"",
"\"",
"\n\n",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"sysVsockPath",
")",
"\n\n",
"// This should not h... | // isAFVSockSupported checks if vsock channel is used by the runtime
// by checking for devices under the vhost-vsock driver path.
// It returns true if a device is found for the vhost-vsock driver. | [
"isAFVSockSupported",
"checks",
"if",
"vsock",
"channel",
"is",
"used",
"by",
"the",
"runtime",
"by",
"checking",
"for",
"devices",
"under",
"the",
"vhost",
"-",
"vsock",
"driver",
"path",
".",
"It",
"returns",
"true",
"if",
"a",
"device",
"is",
"found",
"... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/channel.go#L274-L316 | train |
kata-containers/agent | agent.go | closePostExitFDs | func (p *process) closePostExitFDs() {
if p.termMaster != nil {
p.termMaster.Close()
}
if p.stdin != nil {
p.stdin.Close()
}
if p.stdout != nil {
p.stdout.Close()
}
if p.stderr != nil {
p.stderr.Close()
}
if p.epoller != nil {
p.epoller.sockR.Close()
}
} | go | func (p *process) closePostExitFDs() {
if p.termMaster != nil {
p.termMaster.Close()
}
if p.stdin != nil {
p.stdin.Close()
}
if p.stdout != nil {
p.stdout.Close()
}
if p.stderr != nil {
p.stderr.Close()
}
if p.epoller != nil {
p.epoller.sockR.Close()
}
} | [
"func",
"(",
"p",
"*",
"process",
")",
"closePostExitFDs",
"(",
")",
"{",
"if",
"p",
".",
"termMaster",
"!=",
"nil",
"{",
"p",
".",
"termMaster",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"stdin",
"!=",
"nil",
"{",
"p",
".",
"s... | // This is the list of file descriptors we can properly close after the process
// has exited. These are the remaining file descriptors that we have opened and
// are no longer needed. | [
"This",
"is",
"the",
"list",
"of",
"file",
"descriptors",
"we",
"can",
"properly",
"close",
"after",
"the",
"process",
"has",
"exited",
".",
"These",
"are",
"the",
"remaining",
"file",
"descriptors",
"that",
"we",
"have",
"opened",
"and",
"are",
"no",
"lon... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L204-L224 | train |
kata-containers/agent | agent.go | setSandboxStorage | func (s *sandbox) setSandboxStorage(path string) bool {
if _, ok := s.storages[path]; !ok {
sbs := &sandboxStorage{refCount: 1}
s.storages[path] = sbs
return true
}
sbs := s.storages[path]
sbs.refCount++
return false
} | go | func (s *sandbox) setSandboxStorage(path string) bool {
if _, ok := s.storages[path]; !ok {
sbs := &sandboxStorage{refCount: 1}
s.storages[path] = sbs
return true
}
sbs := s.storages[path]
sbs.refCount++
return false
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"setSandboxStorage",
"(",
"path",
"string",
")",
"bool",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"storages",
"[",
"path",
"]",
";",
"!",
"ok",
"{",
"sbs",
":=",
"&",
"sandboxStorage",
"{",
"refCount",
":",
... | // setSandboxStorage sets the sandbox level reference
// counter for the sandbox storage.
// This method also returns a boolean to let
// callers know if the storage already existed or not.
// It will return true if storage is new.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox. | [
"setSandboxStorage",
"sets",
"the",
"sandbox",
"level",
"reference",
"counter",
"for",
"the",
"sandbox",
"storage",
".",
"This",
"method",
"also",
"returns",
"a",
"boolean",
"to",
"let",
"callers",
"know",
"if",
"the",
"storage",
"already",
"existed",
"or",
"n... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L296-L305 | train |
kata-containers/agent | agent.go | scanGuestHooks | func (s *sandbox) scanGuestHooks(guestHookPath string) {
span, _ := s.trace("scanGuestHooks")
span.SetTag("guest-hook-path", guestHookPath)
defer span.Finish()
fieldLogger := agentLog.WithField("oci-hook-path", guestHookPath)
fieldLogger.Info("Scanning guest filesystem for OCI hooks")
s.guestHooks.Prestart = findHooks(guestHookPath, "prestart")
s.guestHooks.Poststart = findHooks(guestHookPath, "poststart")
s.guestHooks.Poststop = findHooks(guestHookPath, "poststop")
if len(s.guestHooks.Prestart) > 0 || len(s.guestHooks.Poststart) > 0 || len(s.guestHooks.Poststop) > 0 {
s.guestHooksPresent = true
} else {
fieldLogger.Warn("Guest hooks were requested but none were found")
}
} | go | func (s *sandbox) scanGuestHooks(guestHookPath string) {
span, _ := s.trace("scanGuestHooks")
span.SetTag("guest-hook-path", guestHookPath)
defer span.Finish()
fieldLogger := agentLog.WithField("oci-hook-path", guestHookPath)
fieldLogger.Info("Scanning guest filesystem for OCI hooks")
s.guestHooks.Prestart = findHooks(guestHookPath, "prestart")
s.guestHooks.Poststart = findHooks(guestHookPath, "poststart")
s.guestHooks.Poststop = findHooks(guestHookPath, "poststop")
if len(s.guestHooks.Prestart) > 0 || len(s.guestHooks.Poststart) > 0 || len(s.guestHooks.Poststop) > 0 {
s.guestHooksPresent = true
} else {
fieldLogger.Warn("Guest hooks were requested but none were found")
}
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"scanGuestHooks",
"(",
"guestHookPath",
"string",
")",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"guestHookPath",
")",
"\n",
"defe... | // scanGuestHooks will search the given guestHookPath
// for any OCI hooks | [
"scanGuestHooks",
"will",
"search",
"the",
"given",
"guestHookPath",
"for",
"any",
"OCI",
"hooks"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L309-L326 | train |
kata-containers/agent | agent.go | addGuestHooks | func (s *sandbox) addGuestHooks(spec *specs.Spec) {
span, _ := s.trace("addGuestHooks")
defer span.Finish()
if spec == nil {
return
}
if spec.Hooks == nil {
spec.Hooks = &specs.Hooks{}
}
spec.Hooks.Prestart = append(spec.Hooks.Prestart, s.guestHooks.Prestart...)
spec.Hooks.Poststart = append(spec.Hooks.Poststart, s.guestHooks.Poststart...)
spec.Hooks.Poststop = append(spec.Hooks.Poststop, s.guestHooks.Poststop...)
} | go | func (s *sandbox) addGuestHooks(spec *specs.Spec) {
span, _ := s.trace("addGuestHooks")
defer span.Finish()
if spec == nil {
return
}
if spec.Hooks == nil {
spec.Hooks = &specs.Hooks{}
}
spec.Hooks.Prestart = append(spec.Hooks.Prestart, s.guestHooks.Prestart...)
spec.Hooks.Poststart = append(spec.Hooks.Poststart, s.guestHooks.Poststart...)
spec.Hooks.Poststop = append(spec.Hooks.Poststop, s.guestHooks.Poststop...)
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"addGuestHooks",
"(",
"spec",
"*",
"specs",
".",
"Spec",
")",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"spec",
"==... | // addGuestHooks will add any guest OCI hooks that were
// found to the OCI spec | [
"addGuestHooks",
"will",
"add",
"any",
"guest",
"OCI",
"hooks",
"that",
"were",
"found",
"to",
"the",
"OCI",
"spec"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L330-L345 | train |
kata-containers/agent | agent.go | unSetSandboxStorage | func (s *sandbox) unSetSandboxStorage(path string) (bool, error) {
span, _ := s.trace("unSetSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
if sbs, ok := s.storages[path]; ok {
sbs.refCount--
// If this sandbox storage is not used by any container
// then remove it's reference
if sbs.refCount < 1 {
delete(s.storages, path)
return true, nil
}
return false, nil
}
return false, grpcStatus.Errorf(codes.NotFound, "Sandbox storage with path %s not found", path)
} | go | func (s *sandbox) unSetSandboxStorage(path string) (bool, error) {
span, _ := s.trace("unSetSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
if sbs, ok := s.storages[path]; ok {
sbs.refCount--
// If this sandbox storage is not used by any container
// then remove it's reference
if sbs.refCount < 1 {
delete(s.storages, path)
return true, nil
}
return false, nil
}
return false, grpcStatus.Errorf(codes.NotFound, "Sandbox storage with path %s not found", path)
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"unSetSandboxStorage",
"(",
"path",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"... | // unSetSandboxStorage will decrement the sandbox storage
// reference counter. If there aren't any containers using
// that sandbox storage, this method will remove the
// storage reference from the sandbox and return 'true, nil' to
// let the caller know that they can clean up the storage
// related directories by calling removeSandboxStorage
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox. | [
"unSetSandboxStorage",
"will",
"decrement",
"the",
"sandbox",
"storage",
"reference",
"counter",
".",
"If",
"there",
"aren",
"t",
"any",
"containers",
"using",
"that",
"sandbox",
"storage",
"this",
"method",
"will",
"remove",
"the",
"storage",
"reference",
"from",... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L356-L372 | train |
kata-containers/agent | agent.go | removeSandboxStorage | func (s *sandbox) removeSandboxStorage(path string) error {
span, _ := s.trace("removeSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
err := removeMounts([]string{path})
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to unmount sandbox storage path %s", path)
}
err = os.RemoveAll(path)
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to delete sandbox storage path %s", path)
}
return nil
} | go | func (s *sandbox) removeSandboxStorage(path string) error {
span, _ := s.trace("removeSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
err := removeMounts([]string{path})
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to unmount sandbox storage path %s", path)
}
err = os.RemoveAll(path)
if err != nil {
return grpcStatus.Errorf(codes.Unknown, "Unable to delete sandbox storage path %s", path)
}
return nil
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"removeSandboxStorage",
"(",
"path",
"string",
")",
"error",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"defer... | // removeSandboxStorage removes the sandbox storage if no
// containers are using that storage.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox. | [
"removeSandboxStorage",
"removes",
"the",
"sandbox",
"storage",
"if",
"no",
"containers",
"are",
"using",
"that",
"storage",
".",
"It",
"s",
"assumed",
"that",
"caller",
"is",
"calling",
"this",
"method",
"after",
"acquiring",
"a",
"lock",
"on",
"sandbox",
"."... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L379-L393 | train |
kata-containers/agent | agent.go | unsetAndRemoveSandboxStorage | func (s *sandbox) unsetAndRemoveSandboxStorage(path string) error {
span, _ := s.trace("unsetAndRemoveSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
if _, ok := s.storages[path]; ok {
removeSbs, err := s.unSetSandboxStorage(path)
if err != nil {
return err
}
if removeSbs {
if err := s.removeSandboxStorage(path); err != nil {
return err
}
}
return nil
}
return grpcStatus.Errorf(codes.NotFound, "Sandbox storage with path %s not found", path)
} | go | func (s *sandbox) unsetAndRemoveSandboxStorage(path string) error {
span, _ := s.trace("unsetAndRemoveSandboxStorage")
span.SetTag("path", path)
defer span.Finish()
if _, ok := s.storages[path]; ok {
removeSbs, err := s.unSetSandboxStorage(path)
if err != nil {
return err
}
if removeSbs {
if err := s.removeSandboxStorage(path); err != nil {
return err
}
}
return nil
}
return grpcStatus.Errorf(codes.NotFound, "Sandbox storage with path %s not found", path)
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"unsetAndRemoveSandboxStorage",
"(",
"path",
"string",
")",
"error",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
... | // unsetAndRemoveSandboxStorage unsets the storage from sandbox
// and if there are no containers using this storage it will
// remove it from the sandbox.
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox. | [
"unsetAndRemoveSandboxStorage",
"unsets",
"the",
"storage",
"from",
"sandbox",
"and",
"if",
"there",
"are",
"no",
"containers",
"using",
"this",
"storage",
"it",
"will",
"remove",
"it",
"from",
"the",
"sandbox",
".",
"It",
"s",
"assumed",
"that",
"caller",
"is... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L401-L421 | train |
kata-containers/agent | agent.go | signalHandlerLoop | func (s *sandbox) signalHandlerLoop(sigCh chan os.Signal) {
for sig := range sigCh {
logger := agentLog.WithField("signal", sig)
if sig == unix.SIGCHLD {
if err := s.subreaper.reap(); err != nil {
logger.WithError(err).Error("failed to reap")
continue
}
}
nativeSignal, ok := sig.(syscall.Signal)
if !ok {
err := errors.New("unknown signal")
logger.WithError(err).Error("failed to handle signal")
continue
}
if fatalSignal(nativeSignal) {
logger.Error("received fatal signal")
die(s.ctx)
}
if debug && nonFatalSignal(nativeSignal) {
logger.Debug("handling signal")
backtrace()
continue
}
logger.Info("ignoring unexpected signal")
}
} | go | func (s *sandbox) signalHandlerLoop(sigCh chan os.Signal) {
for sig := range sigCh {
logger := agentLog.WithField("signal", sig)
if sig == unix.SIGCHLD {
if err := s.subreaper.reap(); err != nil {
logger.WithError(err).Error("failed to reap")
continue
}
}
nativeSignal, ok := sig.(syscall.Signal)
if !ok {
err := errors.New("unknown signal")
logger.WithError(err).Error("failed to handle signal")
continue
}
if fatalSignal(nativeSignal) {
logger.Error("received fatal signal")
die(s.ctx)
}
if debug && nonFatalSignal(nativeSignal) {
logger.Debug("handling signal")
backtrace()
continue
}
logger.Info("ignoring unexpected signal")
}
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"signalHandlerLoop",
"(",
"sigCh",
"chan",
"os",
".",
"Signal",
")",
"{",
"for",
"sig",
":=",
"range",
"sigCh",
"{",
"logger",
":=",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"sig",
")",
"\n\n",
"if",
... | // This loop is meant to be run inside a separate Go routine. | [
"This",
"loop",
"is",
"meant",
"to",
"be",
"run",
"inside",
"a",
"separate",
"Go",
"routine",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L749-L780 | train |
kata-containers/agent | agent.go | getMemory | func getMemory() (string, error) {
bytes, err := ioutil.ReadFile(meminfo)
if err != nil {
return "", err
}
lines := string(bytes)
for _, line := range strings.Split(lines, "\n") {
if !strings.HasPrefix(line, "MemTotal") {
continue
}
expectedFields := 2
fields := strings.Split(line, ":")
count := len(fields)
if count != expectedFields {
return "", fmt.Errorf("expected %d fields, got %d in line %q", expectedFields, count, line)
}
if fields[1] == "" {
return "", fmt.Errorf("cannot determine total memory from line %q", line)
}
memTotal := strings.TrimSpace(fields[1])
return memTotal, nil
}
return "", fmt.Errorf("no lines in file %q", meminfo)
} | go | func getMemory() (string, error) {
bytes, err := ioutil.ReadFile(meminfo)
if err != nil {
return "", err
}
lines := string(bytes)
for _, line := range strings.Split(lines, "\n") {
if !strings.HasPrefix(line, "MemTotal") {
continue
}
expectedFields := 2
fields := strings.Split(line, ":")
count := len(fields)
if count != expectedFields {
return "", fmt.Errorf("expected %d fields, got %d in line %q", expectedFields, count, line)
}
if fields[1] == "" {
return "", fmt.Errorf("cannot determine total memory from line %q", line)
}
memTotal := strings.TrimSpace(fields[1])
return memTotal, nil
}
return "", fmt.Errorf("no lines in file %q", meminfo)
} | [
"func",
"getMemory",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"meminfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"lines",
":... | // getMemory returns a string containing the total amount of memory reported
// by the kernel. The string includes a suffix denoting the units the memory
// is measured in. | [
"getMemory",
"returns",
"a",
"string",
"containing",
"the",
"total",
"amount",
"of",
"memory",
"reported",
"by",
"the",
"kernel",
".",
"The",
"string",
"includes",
"a",
"suffix",
"denoting",
"the",
"units",
"the",
"memory",
"is",
"measured",
"in",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L807-L839 | train |
kata-containers/agent | agent.go | announce | func announce() error {
announceFields, err := getAnnounceFields()
if err != nil {
return err
}
if os.Getpid() == 1 {
fields := formatFields(agentFields)
extraFields := formatFields(announceFields)
fields = append(fields, extraFields...)
fmt.Printf("announce: %s\n", strings.Join(fields, ","))
} else {
agentLog.WithFields(announceFields).Info("announce")
}
return nil
} | go | func announce() error {
announceFields, err := getAnnounceFields()
if err != nil {
return err
}
if os.Getpid() == 1 {
fields := formatFields(agentFields)
extraFields := formatFields(announceFields)
fields = append(fields, extraFields...)
fmt.Printf("announce: %s\n", strings.Join(fields, ","))
} else {
agentLog.WithFields(announceFields).Info("announce")
}
return nil
} | [
"func",
"announce",
"(",
")",
"error",
"{",
"announceFields",
",",
"err",
":=",
"getAnnounceFields",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getpid",
"(",
")",
"==",
"1",
"{",
"fields",
"... | // announce logs details of the agents version and capabilities. | [
"announce",
"logs",
"details",
"of",
"the",
"agents",
"version",
"and",
"capabilities",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L884-L902 | train |
kata-containers/agent | agent.go | initAgentAsInit | func initAgentAsInit() error {
if err := generalMount(); err != nil {
return err
}
if err := cgroupsMount(); err != nil {
return err
}
if err := syscall.Unlink("/dev/ptmx"); err != nil {
return err
}
if err := syscall.Symlink("/dev/pts/ptmx", "/dev/ptmx"); err != nil {
return err
}
syscall.Setsid()
syscall.Syscall(syscall.SYS_IOCTL, os.Stdin.Fd(), syscall.TIOCSCTTY, 1)
os.Setenv("PATH", "/bin:/sbin/:/usr/bin/:/usr/sbin/")
return announce()
} | go | func initAgentAsInit() error {
if err := generalMount(); err != nil {
return err
}
if err := cgroupsMount(); err != nil {
return err
}
if err := syscall.Unlink("/dev/ptmx"); err != nil {
return err
}
if err := syscall.Symlink("/dev/pts/ptmx", "/dev/ptmx"); err != nil {
return err
}
syscall.Setsid()
syscall.Syscall(syscall.SYS_IOCTL, os.Stdin.Fd(), syscall.TIOCSCTTY, 1)
os.Setenv("PATH", "/bin:/sbin/:/usr/bin/:/usr/sbin/")
return announce()
} | [
"func",
"initAgentAsInit",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"generalMount",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cgroupsMount",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"er... | // initAgentAsInit will do the initializations such as setting up the rootfs
// when this agent has been run as the init process. | [
"initAgentAsInit",
"will",
"do",
"the",
"initializations",
"such",
"as",
"setting",
"up",
"the",
"rootfs",
"when",
"this",
"agent",
"has",
"been",
"run",
"as",
"the",
"init",
"process",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L1201-L1219 | train |
kata-containers/agent | oci.go | findHooks | func findHooks(guestHookPath, hookType string) (hooksFound []specs.Hook) {
hooksPath := path.Join(guestHookPath, hookType)
files, err := ioutil.ReadDir(hooksPath)
if err != nil {
agentLog.WithError(err).WithField("oci-hook-type", hookType).Info("Skipping hook type")
return
}
for _, file := range files {
name := file.Name()
if ok, err := isValidHook(file); !ok {
agentLog.WithError(err).WithField("oci-hook-name", name).Warn("Skipping hook")
continue
}
agentLog.WithFields(logrus.Fields{
"oci-hook-name": name,
"oci-hook-type": hookType,
}).Info("Adding hook")
hooksFound = append(hooksFound, specs.Hook{
Path: path.Join(hooksPath, name),
Args: []string{name, hookType},
})
}
agentLog.WithField("oci-hook-type", hookType).Infof("Added %d hooks", len(hooksFound))
return
} | go | func findHooks(guestHookPath, hookType string) (hooksFound []specs.Hook) {
hooksPath := path.Join(guestHookPath, hookType)
files, err := ioutil.ReadDir(hooksPath)
if err != nil {
agentLog.WithError(err).WithField("oci-hook-type", hookType).Info("Skipping hook type")
return
}
for _, file := range files {
name := file.Name()
if ok, err := isValidHook(file); !ok {
agentLog.WithError(err).WithField("oci-hook-name", name).Warn("Skipping hook")
continue
}
agentLog.WithFields(logrus.Fields{
"oci-hook-name": name,
"oci-hook-type": hookType,
}).Info("Adding hook")
hooksFound = append(hooksFound, specs.Hook{
Path: path.Join(hooksPath, name),
Args: []string{name, hookType},
})
}
agentLog.WithField("oci-hook-type", hookType).Infof("Added %d hooks", len(hooksFound))
return
} | [
"func",
"findHooks",
"(",
"guestHookPath",
",",
"hookType",
"string",
")",
"(",
"hooksFound",
"[",
"]",
"specs",
".",
"Hook",
")",
"{",
"hooksPath",
":=",
"path",
".",
"Join",
"(",
"guestHookPath",
",",
"hookType",
")",
"\n\n",
"files",
",",
"err",
":=",... | // findHooks searches guestHookPath for any OCI hooks for a given hookType | [
"findHooks",
"searches",
"guestHookPath",
"for",
"any",
"OCI",
"hooks",
"for",
"a",
"given",
"hookType"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/oci.go#L83-L112 | train |
kata-containers/agent | tracing.go | trace | func trace(ctx context.Context, subsystem, name string) (opentracing.Span, context.Context) {
span, ctx := opentracing.StartSpanFromContext(ctx, name)
span.SetTag("subsystem", subsystem)
// This is slightly confusing: when tracing is disabled, trace spans
// are still created - but the tracer used is a NOP. Therefore, only
// display the message when tracing is really enabled.
if tracing {
agentLog.Debugf("created span %v", span)
}
return span, ctx
} | go | func trace(ctx context.Context, subsystem, name string) (opentracing.Span, context.Context) {
span, ctx := opentracing.StartSpanFromContext(ctx, name)
span.SetTag("subsystem", subsystem)
// This is slightly confusing: when tracing is disabled, trace spans
// are still created - but the tracer used is a NOP. Therefore, only
// display the message when tracing is really enabled.
if tracing {
agentLog.Debugf("created span %v", span)
}
return span, ctx
} | [
"func",
"trace",
"(",
"ctx",
"context",
".",
"Context",
",",
"subsystem",
",",
"name",
"string",
")",
"(",
"opentracing",
".",
"Span",
",",
"context",
".",
"Context",
")",
"{",
"span",
",",
"ctx",
":=",
"opentracing",
".",
"StartSpanFromContext",
"(",
"c... | // trace creates a new tracing span based on the specified contex, subsystem
// and name. | [
"trace",
"creates",
"a",
"new",
"tracing",
"span",
"based",
"on",
"the",
"specified",
"contex",
"subsystem",
"and",
"name",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/tracing.go#L135-L148 | train |
kata-containers/agent | grpc.go | handleError | func handleError(wait bool, err error) error {
if !wait {
agentLog.WithError(err).Error()
}
return err
} | go | func handleError(wait bool, err error) error {
if !wait {
agentLog.WithError(err).Error()
}
return err
} | [
"func",
"handleError",
"(",
"wait",
"bool",
",",
"err",
"error",
")",
"error",
"{",
"if",
"!",
"wait",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // handleError will log the specified error if wait is false | [
"handleError",
"will",
"log",
"the",
"specified",
"error",
"if",
"wait",
"is",
"false"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L83-L89 | train |
kata-containers/agent | grpc.go | onlineResources | func onlineResources(resource onlineResource, nbResources int32) (uint32, error) {
files, err := ioutil.ReadDir(resource.sysfsOnlinePath)
if err != nil {
return 0, err
}
var count uint32
for _, file := range files {
matched, err := regexp.MatchString(resource.regexpPattern, file.Name())
if err != nil {
return count, err
}
if !matched {
continue
}
onlinePath := filepath.Join(resource.sysfsOnlinePath, file.Name(), "online")
status, err := ioutil.ReadFile(onlinePath)
if err != nil {
// resource cold plugged
continue
}
if strings.Trim(string(status), "\n\t ") == "0" {
if err := ioutil.WriteFile(onlinePath, []byte("1"), 0600); err != nil {
agentLog.WithField("online-path", onlinePath).WithError(err).Errorf("Could not online resource")
continue
}
count++
if nbResources > 0 && count == uint32(nbResources) {
return count, nil
}
}
}
return count, nil
} | go | func onlineResources(resource onlineResource, nbResources int32) (uint32, error) {
files, err := ioutil.ReadDir(resource.sysfsOnlinePath)
if err != nil {
return 0, err
}
var count uint32
for _, file := range files {
matched, err := regexp.MatchString(resource.regexpPattern, file.Name())
if err != nil {
return count, err
}
if !matched {
continue
}
onlinePath := filepath.Join(resource.sysfsOnlinePath, file.Name(), "online")
status, err := ioutil.ReadFile(onlinePath)
if err != nil {
// resource cold plugged
continue
}
if strings.Trim(string(status), "\n\t ") == "0" {
if err := ioutil.WriteFile(onlinePath, []byte("1"), 0600); err != nil {
agentLog.WithField("online-path", onlinePath).WithError(err).Errorf("Could not online resource")
continue
}
count++
if nbResources > 0 && count == uint32(nbResources) {
return count, nil
}
}
}
return count, nil
} | [
"func",
"onlineResources",
"(",
"resource",
"onlineResource",
",",
"nbResources",
"int32",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"resource",
".",
"sysfsOnlinePath",
")",
"\n",
"if",
"err",
"!=... | // Online resources, nbResources specifies the maximum number of resources to online.
// If nbResources is <= 0 then there is no limit and all resources are connected.
// Returns the number of resources connected. | [
"Online",
"resources",
"nbResources",
"specifies",
"the",
"maximum",
"number",
"of",
"resources",
"to",
"online",
".",
"If",
"nbResources",
"is",
"<",
"=",
"0",
"then",
"there",
"is",
"no",
"limit",
"and",
"all",
"resources",
"are",
"connected",
".",
"Return... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L94-L131 | train |
kata-containers/agent | grpc.go | updateCpusetPath | func updateCpusetPath(cgroupPath string, newCpuset string, cookies cookie) error {
// Each cpuset cgroup parent MUST BE updated with the actual number of vCPUs.
//Start to update from cgroup system root.
cgroupParentPath := cgroupCpusetPath
cpusetGuest, err := getCpusetGuest()
if err != nil {
return err
}
// Update parents with max set of current cpus
//Iterate all parent dirs in order.
//This is needed to ensure the cgroup parent has cpus on needed needed
//by the request.
cgroupsParentPaths := strings.Split(filepath.Dir(cgroupPath), "/")
for _, path := range cgroupsParentPaths {
// Skip if empty.
if path == "" {
continue
}
cgroupParentPath = filepath.Join(cgroupParentPath, path)
// check if the cgroup was already updated.
if cookies[cgroupParentPath] {
agentLog.WithField("path", cgroupParentPath).Debug("cpuset cgroup already updated")
continue
}
cpusetCpusParentPath := filepath.Join(cgroupParentPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusParentPath).Debug("updating cpuset parent cgroup")
if err := ioutil.WriteFile(cpusetCpusParentPath, []byte(cpusetGuest), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusParentPath, cpusetGuest, err)
}
// add cgroup path to the cookies.
cookies[cgroupParentPath] = true
}
// Finally update group path with requested value.
cpusetCpusPath := filepath.Join(cgroupCpusetPath, cgroupPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusPath).Debug("updating cpuset cgroup")
if err := ioutil.WriteFile(cpusetCpusPath, []byte(newCpuset), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusPath, cpusetGuest, err)
}
return nil
} | go | func updateCpusetPath(cgroupPath string, newCpuset string, cookies cookie) error {
// Each cpuset cgroup parent MUST BE updated with the actual number of vCPUs.
//Start to update from cgroup system root.
cgroupParentPath := cgroupCpusetPath
cpusetGuest, err := getCpusetGuest()
if err != nil {
return err
}
// Update parents with max set of current cpus
//Iterate all parent dirs in order.
//This is needed to ensure the cgroup parent has cpus on needed needed
//by the request.
cgroupsParentPaths := strings.Split(filepath.Dir(cgroupPath), "/")
for _, path := range cgroupsParentPaths {
// Skip if empty.
if path == "" {
continue
}
cgroupParentPath = filepath.Join(cgroupParentPath, path)
// check if the cgroup was already updated.
if cookies[cgroupParentPath] {
agentLog.WithField("path", cgroupParentPath).Debug("cpuset cgroup already updated")
continue
}
cpusetCpusParentPath := filepath.Join(cgroupParentPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusParentPath).Debug("updating cpuset parent cgroup")
if err := ioutil.WriteFile(cpusetCpusParentPath, []byte(cpusetGuest), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusParentPath, cpusetGuest, err)
}
// add cgroup path to the cookies.
cookies[cgroupParentPath] = true
}
// Finally update group path with requested value.
cpusetCpusPath := filepath.Join(cgroupCpusetPath, cgroupPath, "cpuset.cpus")
agentLog.WithField("path", cpusetCpusPath).Debug("updating cpuset cgroup")
if err := ioutil.WriteFile(cpusetCpusPath, []byte(newCpuset), cpusetMode); err != nil {
return fmt.Errorf("Could not update parent cpuset cgroup (%s) cpuset:'%s': %v", cpusetCpusPath, cpusetGuest, err)
}
return nil
} | [
"func",
"updateCpusetPath",
"(",
"cgroupPath",
"string",
",",
"newCpuset",
"string",
",",
"cookies",
"cookie",
")",
"error",
"{",
"// Each cpuset cgroup parent MUST BE updated with the actual number of vCPUs.",
"//Start to update from cgroup system root.",
"cgroupParentPath",
":=",... | // updates a cpuset cgroups path visiting each sub-directory in cgroupPath parent and writing
// the maximal set of cpus in cpuset.cpus file, finally the cgroupPath is updated with the requsted
//value.
// cookies are used for performance reasons in order to
// don't update a cgroup twice. | [
"updates",
"a",
"cpuset",
"cgroups",
"path",
"visiting",
"each",
"sub",
"-",
"directory",
"in",
"cgroupPath",
"parent",
"and",
"writing",
"the",
"maximal",
"set",
"of",
"cpus",
"in",
"cpuset",
".",
"cpus",
"file",
"finally",
"the",
"cgroupPath",
"is",
"updat... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L170-L221 | train |
kata-containers/agent | grpc.go | execProcess | func (a *agentGRPC) execProcess(ctr *container, proc *process, createContainer bool) (err error) {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
// This lock is very important to avoid any race with reaper.reap().
// Indeed, if we don't lock this here, we could potentially get the
// SIGCHLD signal before the channel has been created, meaning we will
// miss the opportunity to get the exit code, leading WaitProcess() to
// wait forever on the new channel.
// This lock has to be taken before we run the new process.
a.sandbox.subreaper.lock()
defer a.sandbox.subreaper.unlock()
if createContainer {
err = ctr.container.Start(&proc.process)
} else {
err = ctr.container.Run(&(proc.process))
}
if err != nil {
return grpcStatus.Errorf(codes.Internal, "Could not run process: %v", err)
}
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
proc.exitCodeCh = make(chan int, 1)
// Create process channel to allow WaitProcess to wait on it.
// This channel is buffered so that reaper.reap() will not
// block until WaitProcess listen onto this channel.
a.sandbox.subreaper.setExitCodeCh(pid, proc.exitCodeCh)
return nil
} | go | func (a *agentGRPC) execProcess(ctr *container, proc *process, createContainer bool) (err error) {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
// This lock is very important to avoid any race with reaper.reap().
// Indeed, if we don't lock this here, we could potentially get the
// SIGCHLD signal before the channel has been created, meaning we will
// miss the opportunity to get the exit code, leading WaitProcess() to
// wait forever on the new channel.
// This lock has to be taken before we run the new process.
a.sandbox.subreaper.lock()
defer a.sandbox.subreaper.unlock()
if createContainer {
err = ctr.container.Start(&proc.process)
} else {
err = ctr.container.Run(&(proc.process))
}
if err != nil {
return grpcStatus.Errorf(codes.Internal, "Could not run process: %v", err)
}
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
proc.exitCodeCh = make(chan int, 1)
// Create process channel to allow WaitProcess to wait on it.
// This channel is buffered so that reaper.reap() will not
// block until WaitProcess listen onto this channel.
a.sandbox.subreaper.setExitCodeCh(pid, proc.exitCodeCh)
return nil
} | [
"func",
"(",
"a",
"*",
"agentGRPC",
")",
"execProcess",
"(",
"ctr",
"*",
"container",
",",
"proc",
"*",
"process",
",",
"createContainer",
"bool",
")",
"(",
"err",
"error",
")",
"{",
"if",
"ctr",
"==",
"nil",
"{",
"return",
"grpcStatus",
".",
"Error",
... | // Shared function between CreateContainer and ExecProcess, because those expect
// a process to be run. | [
"Shared",
"function",
"between",
"CreateContainer",
"and",
"ExecProcess",
"because",
"those",
"expect",
"a",
"process",
"to",
"be",
"run",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L392-L433 | train |
kata-containers/agent | grpc.go | postExecProcess | func (a *agentGRPC) postExecProcess(ctr *container, proc *process) error {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
defer proc.closePostStartFDs()
// Setup terminal if enabled.
if proc.consoleSock != nil {
termMaster, err := utils.RecvFd(proc.consoleSock)
if err != nil {
return err
}
if err := setConsoleCarriageReturn(int(termMaster.Fd())); err != nil {
return err
}
proc.termMaster = termMaster
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
a.sandbox.subreaper.setEpoller(pid, proc.epoller)
if err = proc.epoller.add(proc.termMaster); err != nil {
return err
}
}
ctr.setProcess(proc)
return nil
} | go | func (a *agentGRPC) postExecProcess(ctr *container, proc *process) error {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
defer proc.closePostStartFDs()
// Setup terminal if enabled.
if proc.consoleSock != nil {
termMaster, err := utils.RecvFd(proc.consoleSock)
if err != nil {
return err
}
if err := setConsoleCarriageReturn(int(termMaster.Fd())); err != nil {
return err
}
proc.termMaster = termMaster
// Get process PID
pid, err := proc.process.Pid()
if err != nil {
return err
}
a.sandbox.subreaper.setEpoller(pid, proc.epoller)
if err = proc.epoller.add(proc.termMaster); err != nil {
return err
}
}
ctr.setProcess(proc)
return nil
} | [
"func",
"(",
"a",
"*",
"agentGRPC",
")",
"postExecProcess",
"(",
"ctr",
"*",
"container",
",",
"proc",
"*",
"process",
")",
"error",
"{",
"if",
"ctr",
"==",
"nil",
"{",
"return",
"grpcStatus",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\... | // Shared function between CreateContainer and ExecProcess, because those expect
// the console to be properly setup after the process has been started. | [
"Shared",
"function",
"between",
"CreateContainer",
"and",
"ExecProcess",
"because",
"those",
"expect",
"the",
"console",
"to",
"be",
"properly",
"setup",
"after",
"the",
"process",
"has",
"been",
"started",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L437-L476 | train |
kata-containers/agent | grpc.go | updateContainerConfigNamespaces | func (a *agentGRPC) updateContainerConfigNamespaces(config *configs.Config, ctr *container) {
var ipcNs, utsNs bool
for idx, ns := range config.Namespaces {
if ns.Type == configs.NEWIPC {
config.Namespaces[idx].Path = a.sandbox.sharedIPCNs.path
ipcNs = true
}
if ns.Type == configs.NEWUTS {
config.Namespaces[idx].Path = a.sandbox.sharedUTSNs.path
utsNs = true
}
}
if !ipcNs {
newIPCNs := configs.Namespace{
Type: configs.NEWIPC,
Path: a.sandbox.sharedIPCNs.path,
}
config.Namespaces = append(config.Namespaces, newIPCNs)
}
if !utsNs {
newUTSNs := configs.Namespace{
Type: configs.NEWUTS,
Path: a.sandbox.sharedUTSNs.path,
}
config.Namespaces = append(config.Namespaces, newUTSNs)
}
// Update PID namespace.
var pidNsPath string
// Use shared pid ns if useSandboxPidns has been set in either
// the CreateSandbox request or CreateContainer request.
// Else set this to empty string so that a new pid namespace is
// created for the container.
if ctr.useSandboxPidNs || a.sandbox.sandboxPidNs {
pidNsPath = a.sandbox.sharedPidNs.path
} else {
pidNsPath = ""
}
newPidNs := configs.Namespace{
Type: configs.NEWPID,
Path: pidNsPath,
}
config.Namespaces = append(config.Namespaces, newPidNs)
} | go | func (a *agentGRPC) updateContainerConfigNamespaces(config *configs.Config, ctr *container) {
var ipcNs, utsNs bool
for idx, ns := range config.Namespaces {
if ns.Type == configs.NEWIPC {
config.Namespaces[idx].Path = a.sandbox.sharedIPCNs.path
ipcNs = true
}
if ns.Type == configs.NEWUTS {
config.Namespaces[idx].Path = a.sandbox.sharedUTSNs.path
utsNs = true
}
}
if !ipcNs {
newIPCNs := configs.Namespace{
Type: configs.NEWIPC,
Path: a.sandbox.sharedIPCNs.path,
}
config.Namespaces = append(config.Namespaces, newIPCNs)
}
if !utsNs {
newUTSNs := configs.Namespace{
Type: configs.NEWUTS,
Path: a.sandbox.sharedUTSNs.path,
}
config.Namespaces = append(config.Namespaces, newUTSNs)
}
// Update PID namespace.
var pidNsPath string
// Use shared pid ns if useSandboxPidns has been set in either
// the CreateSandbox request or CreateContainer request.
// Else set this to empty string so that a new pid namespace is
// created for the container.
if ctr.useSandboxPidNs || a.sandbox.sandboxPidNs {
pidNsPath = a.sandbox.sharedPidNs.path
} else {
pidNsPath = ""
}
newPidNs := configs.Namespace{
Type: configs.NEWPID,
Path: pidNsPath,
}
config.Namespaces = append(config.Namespaces, newPidNs)
} | [
"func",
"(",
"a",
"*",
"agentGRPC",
")",
"updateContainerConfigNamespaces",
"(",
"config",
"*",
"configs",
".",
"Config",
",",
"ctr",
"*",
"container",
")",
"{",
"var",
"ipcNs",
",",
"utsNs",
"bool",
"\n\n",
"for",
"idx",
",",
"ns",
":=",
"range",
"confi... | // This function updates the container namespaces configuration based on the
// sandbox information. When the sandbox is created, it can be setup in a way
// that all containers will share some specific namespaces. This is the agent
// responsibility to create those namespaces so that they can be shared across
// several containers.
// If the sandbox has not been setup to share namespaces, then we assume all
// containers will be started in their own new namespace.
// The value of a.sandbox.sharedPidNs.path will always override the namespace
// path set by the spec, since we will always ignore it. Indeed, it makes no
// sense to rely on the namespace path provided by the host since namespaces
// are different inside the guest. | [
"This",
"function",
"updates",
"the",
"container",
"namespaces",
"configuration",
"based",
"on",
"the",
"sandbox",
"information",
".",
"When",
"the",
"sandbox",
"is",
"created",
"it",
"can",
"be",
"setup",
"in",
"a",
"way",
"that",
"all",
"containers",
"will",... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L489-L538 | train |
kata-containers/agent | grpc.go | rollbackFailingContainerCreation | func (a *agentGRPC) rollbackFailingContainerCreation(ctr *container) {
if ctr.container != nil {
ctr.container.Destroy()
}
a.sandbox.deleteContainer(ctr.id)
if err := removeMounts(ctr.mounts); err != nil {
agentLog.WithError(err).Error("rollback failed removeMounts()")
}
} | go | func (a *agentGRPC) rollbackFailingContainerCreation(ctr *container) {
if ctr.container != nil {
ctr.container.Destroy()
}
a.sandbox.deleteContainer(ctr.id)
if err := removeMounts(ctr.mounts); err != nil {
agentLog.WithError(err).Error("rollback failed removeMounts()")
}
} | [
"func",
"(",
"a",
"*",
"agentGRPC",
")",
"rollbackFailingContainerCreation",
"(",
"ctr",
"*",
"container",
")",
"{",
"if",
"ctr",
".",
"container",
"!=",
"nil",
"{",
"ctr",
".",
"container",
".",
"Destroy",
"(",
")",
"\n",
"}",
"\n\n",
"a",
".",
"sandb... | // rollbackFailingContainerCreation rolls back important steps that might have
// been performed before the container creation failed.
// - Destroy the container created by libcontainer
// - Delete the container from the agent internal map
// - Unmount all mounts related to this container | [
"rollbackFailingContainerCreation",
"rolls",
"back",
"important",
"steps",
"that",
"might",
"have",
"been",
"performed",
"before",
"the",
"container",
"creation",
"failed",
".",
"-",
"Destroy",
"the",
"container",
"created",
"by",
"libcontainer",
"-",
"Delete",
"the... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L563-L573 | train |
kata-containers/agent | grpc.go | applyNetworkSysctls | func (a *agentGRPC) applyNetworkSysctls(ociSpec *specs.Spec) error {
sysctls := ociSpec.Linux.Sysctl
for key, value := range sysctls {
if isNetworkSysctl(key) {
if err := writeSystemProperty(key, value); err != nil {
return err
}
delete(sysctls, key)
}
}
ociSpec.Linux.Sysctl = sysctls
return nil
} | go | func (a *agentGRPC) applyNetworkSysctls(ociSpec *specs.Spec) error {
sysctls := ociSpec.Linux.Sysctl
for key, value := range sysctls {
if isNetworkSysctl(key) {
if err := writeSystemProperty(key, value); err != nil {
return err
}
delete(sysctls, key)
}
}
ociSpec.Linux.Sysctl = sysctls
return nil
} | [
"func",
"(",
"a",
"*",
"agentGRPC",
")",
"applyNetworkSysctls",
"(",
"ociSpec",
"*",
"specs",
".",
"Spec",
")",
"error",
"{",
"sysctls",
":=",
"ociSpec",
".",
"Linux",
".",
"Sysctl",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"sysctls",
"{",
"if"... | // libcontainer checks if the container is running in a separate network namespace
// before applying the network related sysctls. If it sees that the network namespace of the container
// is the same as the "host", it errors out. Since we do no create a new net namespace inside the guest,
// libcontainer would error out while verifying network sysctls. To overcome this, we dont pass
// network sysctls to libcontainer, we instead have the agent directly apply them. All other namespaced
// sysctls are applied by libcontainer. | [
"libcontainer",
"checks",
"if",
"the",
"container",
"is",
"running",
"in",
"a",
"separate",
"network",
"namespace",
"before",
"applying",
"the",
"network",
"related",
"sysctls",
".",
"If",
"it",
"sees",
"that",
"the",
"network",
"namespace",
"of",
"the",
"cont... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L730-L743 | train |
kata-containers/agent | grpc.go | isSignalHandled | func isSignalHandled(pid int, signum syscall.Signal) bool {
var sigMask uint64 = 1 << (uint(signum) - 1)
procFile := fmt.Sprintf("/proc/%d/status", pid)
file, err := os.Open(procFile)
if err != nil {
agentLog.WithField("procFile", procFile).Warn("Open proc file failed")
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "SigCgt:") {
maskSlice := strings.Split(line, ":")
if len(maskSlice) != 2 {
agentLog.WithField("procFile", procFile).Warn("Parse the SigCgt field failed")
return false
}
sigCgtStr := strings.TrimSpace(maskSlice[1])
sigCgtMask, err := strconv.ParseUint(sigCgtStr, 16, 64)
if err != nil {
agentLog.WithField("sigCgt", sigCgtStr).Warn("parse the SigCgt to hex failed")
return false
}
return (sigCgtMask & sigMask) == sigMask
}
}
return false
} | go | func isSignalHandled(pid int, signum syscall.Signal) bool {
var sigMask uint64 = 1 << (uint(signum) - 1)
procFile := fmt.Sprintf("/proc/%d/status", pid)
file, err := os.Open(procFile)
if err != nil {
agentLog.WithField("procFile", procFile).Warn("Open proc file failed")
return false
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "SigCgt:") {
maskSlice := strings.Split(line, ":")
if len(maskSlice) != 2 {
agentLog.WithField("procFile", procFile).Warn("Parse the SigCgt field failed")
return false
}
sigCgtStr := strings.TrimSpace(maskSlice[1])
sigCgtMask, err := strconv.ParseUint(sigCgtStr, 16, 64)
if err != nil {
agentLog.WithField("sigCgt", sigCgtStr).Warn("parse the SigCgt to hex failed")
return false
}
return (sigCgtMask & sigMask) == sigMask
}
}
return false
} | [
"func",
"isSignalHandled",
"(",
"pid",
"int",
",",
"signum",
"syscall",
".",
"Signal",
")",
"bool",
"{",
"var",
"sigMask",
"uint64",
"=",
"1",
"<<",
"(",
"uint",
"(",
"signum",
")",
"-",
"1",
")",
"\n",
"procFile",
":=",
"fmt",
".",
"Sprintf",
"(",
... | // Check is the container process installed the
// handler for specific signal. | [
"Check",
"is",
"the",
"container",
"process",
"installed",
"the",
"handler",
"for",
"specific",
"signal",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L951-L980 | train |
kata-containers/agent | device.go | findSCSIDisk | func findSCSIDisk(scsiPath string) (string, error) {
files, err := ioutil.ReadDir(scsiPath)
if err != nil {
return "", err
}
if len(files) != 1 {
return "", grpcStatus.Errorf(codes.Internal,
"Expecting a single SCSI device, found %v",
files)
}
return files[0].Name(), nil
} | go | func findSCSIDisk(scsiPath string) (string, error) {
files, err := ioutil.ReadDir(scsiPath)
if err != nil {
return "", err
}
if len(files) != 1 {
return "", grpcStatus.Errorf(codes.Internal,
"Expecting a single SCSI device, found %v",
files)
}
return files[0].Name(), nil
} | [
"func",
"findSCSIDisk",
"(",
"scsiPath",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"scsiPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"... | // findSCSIDisk finds the SCSI disk name associated with the given SCSI path.
// This approach eliminates the need to predict the disk name on the host side,
// but we do need to rescan SCSI bus for this. | [
"findSCSIDisk",
"finds",
"the",
"SCSI",
"disk",
"name",
"associated",
"with",
"the",
"given",
"SCSI",
"path",
".",
"This",
"approach",
"eliminates",
"the",
"need",
"to",
"predict",
"the",
"disk",
"name",
"on",
"the",
"host",
"side",
"but",
"we",
"do",
"nee... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/device.go#L383-L396 | train |
kata-containers/agent | device.go | getSCSIDevPath | func getSCSIDevPath(scsiAddr string) (string, error) {
if err := scanSCSIBus(scsiAddr); err != nil {
return "", err
}
devPath := filepath.Join(scsiDiskPrefix+scsiAddr, scsiDiskSuffix)
checkUevent := func(uEv *uevent.Uevent) bool {
devSubPath := filepath.Join(scsiHostChannel+scsiAddr, scsiBlockSuffix)
return (uEv.Action == "add" &&
strings.Contains(uEv.DevPath, devSubPath))
}
if err := waitForDevice(devPath, scsiAddr, checkUevent); err != nil {
return "", err
}
scsiDiskName, err := findSCSIDisk(devPath)
if err != nil {
return "", err
}
return filepath.Join(devPrefix, scsiDiskName), nil
} | go | func getSCSIDevPath(scsiAddr string) (string, error) {
if err := scanSCSIBus(scsiAddr); err != nil {
return "", err
}
devPath := filepath.Join(scsiDiskPrefix+scsiAddr, scsiDiskSuffix)
checkUevent := func(uEv *uevent.Uevent) bool {
devSubPath := filepath.Join(scsiHostChannel+scsiAddr, scsiBlockSuffix)
return (uEv.Action == "add" &&
strings.Contains(uEv.DevPath, devSubPath))
}
if err := waitForDevice(devPath, scsiAddr, checkUevent); err != nil {
return "", err
}
scsiDiskName, err := findSCSIDisk(devPath)
if err != nil {
return "", err
}
return filepath.Join(devPrefix, scsiDiskName), nil
} | [
"func",
"getSCSIDevPath",
"(",
"scsiAddr",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"err",
":=",
"scanSCSIBus",
"(",
"scsiAddr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"devPath",
":=... | // getSCSIDevPath scans SCSI bus looking for the provided SCSI address, then
// it waits for the SCSI disk to become available and returns the device path
// associated with the disk. | [
"getSCSIDevPath",
"scans",
"SCSI",
"bus",
"looking",
"for",
"the",
"provided",
"SCSI",
"address",
"then",
"it",
"waits",
"for",
"the",
"SCSI",
"disk",
"to",
"become",
"available",
"and",
"returns",
"the",
"device",
"path",
"associated",
"with",
"the",
"disk",
... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/device.go#L401-L423 | train |
kata-containers/agent | network.go | updateInterface | func (s *sandbox) updateInterface(netHandle *netlink.Handle, iface *types.Interface) (resultingIfc *types.Interface, err error) {
if iface == nil {
return nil, errNoIF
}
s.network.ifacesLock.Lock()
defer s.network.ifacesLock.Unlock()
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
fieldLogger := agentLog.WithFields(logrus.Fields{
"mac-address": iface.HwAddr,
"interface-name": iface.Device,
"pci-address": iface.PciAddr,
})
// If the PCI address of the network device is provided, wait/check for the device
// to be available first
if iface.PciAddr != "" {
// iface.PciAddr is in the format bridgeAddr/deviceAddr eg. 05/06
_, err := getPCIDeviceName(s, iface.PciAddr)
if err != nil {
return nil, err
}
}
var link netlink.Link
if iface.HwAddr != "" {
fieldLogger.Info("Getting interface from MAC address")
// Find the interface link from its hardware address.
link, err = linkByHwAddr(netHandle, iface.HwAddr)
if err != nil {
return nil, grpcStatus.Errorf(codes.Internal, "updateInterface: %v", err)
}
} else {
return nil, grpcStatus.Errorf(codes.InvalidArgument, "Interface HwAddr empty")
}
// Use defer function to create and return the interface's state in
// gRPC agent protocol format in the event that an error is observed
defer func() {
if err != nil {
resultingIfc, _ = getInterface(netHandle, link)
} else {
resultingIfc = iface
}
//put the link back into the up state
retErr := netHandle.LinkSetUp(link)
//if we failed to setup the link but already are returning
//with an error, return the original error
if err == nil {
err = retErr
}
}()
fieldLogger.WithField("link", fmt.Sprintf("%+v", link)).Info("Link found")
lAttrs := link.Attrs()
if lAttrs != nil && (lAttrs.Flags&net.FlagUp) == net.FlagUp {
// The link is up, makes sure we get it down before
// doing any modification.
if err = netHandle.LinkSetDown(link); err != nil {
return
}
}
err = updateLink(netHandle, link, iface)
return
} | go | func (s *sandbox) updateInterface(netHandle *netlink.Handle, iface *types.Interface) (resultingIfc *types.Interface, err error) {
if iface == nil {
return nil, errNoIF
}
s.network.ifacesLock.Lock()
defer s.network.ifacesLock.Unlock()
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
fieldLogger := agentLog.WithFields(logrus.Fields{
"mac-address": iface.HwAddr,
"interface-name": iface.Device,
"pci-address": iface.PciAddr,
})
// If the PCI address of the network device is provided, wait/check for the device
// to be available first
if iface.PciAddr != "" {
// iface.PciAddr is in the format bridgeAddr/deviceAddr eg. 05/06
_, err := getPCIDeviceName(s, iface.PciAddr)
if err != nil {
return nil, err
}
}
var link netlink.Link
if iface.HwAddr != "" {
fieldLogger.Info("Getting interface from MAC address")
// Find the interface link from its hardware address.
link, err = linkByHwAddr(netHandle, iface.HwAddr)
if err != nil {
return nil, grpcStatus.Errorf(codes.Internal, "updateInterface: %v", err)
}
} else {
return nil, grpcStatus.Errorf(codes.InvalidArgument, "Interface HwAddr empty")
}
// Use defer function to create and return the interface's state in
// gRPC agent protocol format in the event that an error is observed
defer func() {
if err != nil {
resultingIfc, _ = getInterface(netHandle, link)
} else {
resultingIfc = iface
}
//put the link back into the up state
retErr := netHandle.LinkSetUp(link)
//if we failed to setup the link but already are returning
//with an error, return the original error
if err == nil {
err = retErr
}
}()
fieldLogger.WithField("link", fmt.Sprintf("%+v", link)).Info("Link found")
lAttrs := link.Attrs()
if lAttrs != nil && (lAttrs.Flags&net.FlagUp) == net.FlagUp {
// The link is up, makes sure we get it down before
// doing any modification.
if err = netHandle.LinkSetDown(link); err != nil {
return
}
}
err = updateLink(netHandle, link, iface)
return
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"updateInterface",
"(",
"netHandle",
"*",
"netlink",
".",
"Handle",
",",
"iface",
"*",
"types",
".",
"Interface",
")",
"(",
"resultingIfc",
"*",
"types",
".",
"Interface",
",",
"err",
"error",
")",
"{",
"if",
"ifa... | // updateInterface will update an existing interface with the values provided in the types.Interface. It will identify the
// existing interface via MAC address and will return the state of the interface once the function completes as well an any
// errors observed. | [
"updateInterface",
"will",
"update",
"an",
"existing",
"interface",
"with",
"the",
"values",
"provided",
"in",
"the",
"types",
".",
"Interface",
".",
"It",
"will",
"identify",
"the",
"existing",
"interface",
"via",
"MAC",
"address",
"and",
"will",
"return",
"t... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L199-L277 | train |
kata-containers/agent | network.go | getInterface | func getInterface(netHandle *netlink.Handle, link netlink.Link) (*types.Interface, error) {
if netHandle == nil {
return nil, errNoHandle
}
if link == nil {
return nil, errNoLink
}
var ifc types.Interface
linkAttrs := link.Attrs()
ifc.Name = linkAttrs.Name
ifc.Mtu = uint64(linkAttrs.MTU)
ifc.HwAddr = linkAttrs.HardwareAddr.String()
addrs, err := netHandle.AddrList(link, netlink.FAMILY_V4)
if err != nil {
agentLog.WithError(err).Error("getInterface() failed")
return nil, err
}
for _, addr := range addrs {
netMask, _ := addr.Mask.Size()
m := types.IPAddress{
Address: addr.IP.String(),
Mask: fmt.Sprintf("%d", netMask),
}
ifc.IPAddresses = append(ifc.IPAddresses, &m)
}
return &ifc, nil
} | go | func getInterface(netHandle *netlink.Handle, link netlink.Link) (*types.Interface, error) {
if netHandle == nil {
return nil, errNoHandle
}
if link == nil {
return nil, errNoLink
}
var ifc types.Interface
linkAttrs := link.Attrs()
ifc.Name = linkAttrs.Name
ifc.Mtu = uint64(linkAttrs.MTU)
ifc.HwAddr = linkAttrs.HardwareAddr.String()
addrs, err := netHandle.AddrList(link, netlink.FAMILY_V4)
if err != nil {
agentLog.WithError(err).Error("getInterface() failed")
return nil, err
}
for _, addr := range addrs {
netMask, _ := addr.Mask.Size()
m := types.IPAddress{
Address: addr.IP.String(),
Mask: fmt.Sprintf("%d", netMask),
}
ifc.IPAddresses = append(ifc.IPAddresses, &m)
}
return &ifc, nil
} | [
"func",
"getInterface",
"(",
"netHandle",
"*",
"netlink",
".",
"Handle",
",",
"link",
"netlink",
".",
"Link",
")",
"(",
"*",
"types",
".",
"Interface",
",",
"error",
")",
"{",
"if",
"netHandle",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNoHandle",
"\... | // getInterface will retrieve interface details from the provided link | [
"getInterface",
"will",
"retrieve",
"interface",
"details",
"from",
"the",
"provided",
"link"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L280-L310 | train |
kata-containers/agent | network.go | updateRoutes | func (s *sandbox) updateRoutes(netHandle *netlink.Handle, requestedRoutes *pb.Routes) (resultingRoutes *pb.Routes, err error) {
if requestedRoutes == nil {
return nil, errNoRoutes
}
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
//If we are returning an error, return the current routes on the system
defer func() {
if err != nil {
resultingRoutes, _ = getCurrentRoutes(netHandle)
}
}()
//
// First things first, let's blow away all the existing routes. The updateRoutes function
// is designed to be declarative, so we will attempt to create state matching what is
// requested, and in the event that we fail to do so, will return the error and final state.
//
if err = s.deleteRoutes(netHandle); err != nil {
return nil, err
}
//
// Set each of the requested routes
//
// First make sure we set the interfaces initial routes, as otherwise we
// won't be able to access the gateway
for _, reqRoute := range requestedRoutes.Routes {
if reqRoute.Gateway == "" {
err = s.updateRoute(netHandle, reqRoute, true)
if err != nil {
agentLog.WithError(err).Error("update Route failed")
//If there was an error setting the route, return the error
//and the current routes on the system via the defer func
return
}
}
}
// Take a second pass and apply the routes which include a gateway
for _, reqRoute := range requestedRoutes.Routes {
if reqRoute.Gateway != "" {
err = s.updateRoute(netHandle, reqRoute, true)
if err != nil {
agentLog.WithError(err).Error("update Route failed")
//If there was an error setting the route, return the
//error and the current routes on the system via defer
return
}
}
}
return requestedRoutes, err
} | go | func (s *sandbox) updateRoutes(netHandle *netlink.Handle, requestedRoutes *pb.Routes) (resultingRoutes *pb.Routes, err error) {
if requestedRoutes == nil {
return nil, errNoRoutes
}
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
//If we are returning an error, return the current routes on the system
defer func() {
if err != nil {
resultingRoutes, _ = getCurrentRoutes(netHandle)
}
}()
//
// First things first, let's blow away all the existing routes. The updateRoutes function
// is designed to be declarative, so we will attempt to create state matching what is
// requested, and in the event that we fail to do so, will return the error and final state.
//
if err = s.deleteRoutes(netHandle); err != nil {
return nil, err
}
//
// Set each of the requested routes
//
// First make sure we set the interfaces initial routes, as otherwise we
// won't be able to access the gateway
for _, reqRoute := range requestedRoutes.Routes {
if reqRoute.Gateway == "" {
err = s.updateRoute(netHandle, reqRoute, true)
if err != nil {
agentLog.WithError(err).Error("update Route failed")
//If there was an error setting the route, return the error
//and the current routes on the system via the defer func
return
}
}
}
// Take a second pass and apply the routes which include a gateway
for _, reqRoute := range requestedRoutes.Routes {
if reqRoute.Gateway != "" {
err = s.updateRoute(netHandle, reqRoute, true)
if err != nil {
agentLog.WithError(err).Error("update Route failed")
//If there was an error setting the route, return the
//error and the current routes on the system via defer
return
}
}
}
return requestedRoutes, err
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"updateRoutes",
"(",
"netHandle",
"*",
"netlink",
".",
"Handle",
",",
"requestedRoutes",
"*",
"pb",
".",
"Routes",
")",
"(",
"resultingRoutes",
"*",
"pb",
".",
"Routes",
",",
"err",
"error",
")",
"{",
"if",
"reque... | //updateRoutes will take requestedRoutes and create netlink routes, with a goal of creating a final
// state which matches the requested routes. In doing this, preesxisting non-loopback routes will be
// removed from the network. If an error occurs, this function returns the list of routes in
// gRPC-route format at the time of failure | [
"updateRoutes",
"will",
"take",
"requestedRoutes",
"and",
"create",
"netlink",
"routes",
"with",
"a",
"goal",
"of",
"creating",
"a",
"final",
"state",
"which",
"matches",
"the",
"requested",
"routes",
".",
"In",
"doing",
"this",
"preesxisting",
"non",
"-",
"lo... | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L375-L435 | train |
kata-containers/agent | network.go | getCurrentRoutes | func getCurrentRoutes(netHandle *netlink.Handle) (*pb.Routes, error) {
var err error
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
var routes pb.Routes
finalRouteList, err := netHandle.RouteList(nil, netlink.FAMILY_ALL)
if err != nil {
return &routes, err
}
for _, route := range finalRouteList {
var r types.Route
if route.Dst != nil {
r.Dest = route.Dst.String()
}
if route.Gw != nil {
r.Gateway = route.Gw.String()
}
if route.Src != nil {
r.Source = route.Src.String()
}
r.Scope = uint32(route.Scope)
link, err := netHandle.LinkByIndex(route.LinkIndex)
if err != nil {
return &routes, err
}
r.Device = link.Attrs().Name
routes.Routes = append(routes.Routes, &r)
}
return &routes, nil
} | go | func getCurrentRoutes(netHandle *netlink.Handle) (*pb.Routes, error) {
var err error
if netHandle == nil {
netHandle, err = netlink.NewHandle(unix.NETLINK_ROUTE)
if err != nil {
return nil, err
}
defer netHandle.Delete()
}
var routes pb.Routes
finalRouteList, err := netHandle.RouteList(nil, netlink.FAMILY_ALL)
if err != nil {
return &routes, err
}
for _, route := range finalRouteList {
var r types.Route
if route.Dst != nil {
r.Dest = route.Dst.String()
}
if route.Gw != nil {
r.Gateway = route.Gw.String()
}
if route.Src != nil {
r.Source = route.Src.String()
}
r.Scope = uint32(route.Scope)
link, err := netHandle.LinkByIndex(route.LinkIndex)
if err != nil {
return &routes, err
}
r.Device = link.Attrs().Name
routes.Routes = append(routes.Routes, &r)
}
return &routes, nil
} | [
"func",
"getCurrentRoutes",
"(",
"netHandle",
"*",
"netlink",
".",
"Handle",
")",
"(",
"*",
"pb",
".",
"Routes",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"netHandle",
"==",
"nil",
"{",
"netHandle",
",",
"err",
"=",
"netlink",
".",
"... | //getCurrentRoutes is a helper to gather existing routes in gRPC protocol format | [
"getCurrentRoutes",
"is",
"a",
"helper",
"to",
"gather",
"existing",
"routes",
"in",
"gRPC",
"protocol",
"format"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L442-L485 | train |
kata-containers/agent | network.go | handleLocalhost | func (s *sandbox) handleLocalhost() error {
span, _ := s.trace("handleLocalhost")
defer span.Finish()
// If not running as the init daemon, there is nothing to do as the
// localhost interface will already exist.
if os.Getpid() != 1 {
return nil
}
lo, err := netlink.LinkByName("lo")
if err != nil {
return err
}
return netlink.LinkSetUp(lo)
} | go | func (s *sandbox) handleLocalhost() error {
span, _ := s.trace("handleLocalhost")
defer span.Finish()
// If not running as the init daemon, there is nothing to do as the
// localhost interface will already exist.
if os.Getpid() != 1 {
return nil
}
lo, err := netlink.LinkByName("lo")
if err != nil {
return err
}
return netlink.LinkSetUp(lo)
} | [
"func",
"(",
"s",
"*",
"sandbox",
")",
"handleLocalhost",
"(",
")",
"error",
"{",
"span",
",",
"_",
":=",
"s",
".",
"trace",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"// If not running as the init daemon, there is nothi... | // Bring up localhost network interface. | [
"Bring",
"up",
"localhost",
"network",
"interface",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L605-L621 | train |
kata-containers/agent | reaper.go | run | func (r *agentReaper) run(c *exec.Cmd) error {
exitCodeCh, err := r.start(c)
if err != nil {
return fmt.Errorf("reaper: Could not start process: %v", err)
}
_, err = r.wait(exitCodeCh, (*reaperOSProcess)(c.Process))
return err
} | go | func (r *agentReaper) run(c *exec.Cmd) error {
exitCodeCh, err := r.start(c)
if err != nil {
return fmt.Errorf("reaper: Could not start process: %v", err)
}
_, err = r.wait(exitCodeCh, (*reaperOSProcess)(c.Process))
return err
} | [
"func",
"(",
"r",
"*",
"agentReaper",
")",
"run",
"(",
"c",
"*",
"exec",
".",
"Cmd",
")",
"error",
"{",
"exitCodeCh",
",",
"err",
":=",
"r",
".",
"start",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
... | // run runs the exec command and waits for it, returns once the command
// has been reaped | [
"run",
"runs",
"the",
"exec",
"command",
"and",
"waits",
"for",
"it",
"returns",
"once",
"the",
"command",
"has",
"been",
"reaped"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/reaper.go#L228-L235 | train |
kata-containers/agent | reaper.go | combinedOutput | func (r *agentReaper) combinedOutput(c *exec.Cmd) ([]byte, error) {
if c.Stdout != nil {
return nil, errors.New("reaper: Stdout already set")
}
if c.Stderr != nil {
return nil, errors.New("reaper: Stderr already set")
}
var b bytes.Buffer
c.Stdout = &b
c.Stderr = &b
err := r.run(c)
return b.Bytes(), err
} | go | func (r *agentReaper) combinedOutput(c *exec.Cmd) ([]byte, error) {
if c.Stdout != nil {
return nil, errors.New("reaper: Stdout already set")
}
if c.Stderr != nil {
return nil, errors.New("reaper: Stderr already set")
}
var b bytes.Buffer
c.Stdout = &b
c.Stderr = &b
err := r.run(c)
return b.Bytes(), err
} | [
"func",
"(",
"r",
"*",
"agentReaper",
")",
"combinedOutput",
"(",
"c",
"*",
"exec",
".",
"Cmd",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"c",
".",
"Stdout",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"... | // combinedOutput combines command's stdout and stderr in one buffer,
// returns once the command has been reaped | [
"combinedOutput",
"combines",
"command",
"s",
"stdout",
"and",
"stderr",
"in",
"one",
"buffer",
"returns",
"once",
"the",
"command",
"has",
"been",
"reaped"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/reaper.go#L239-L252 | train |
mattn/go-oci8 | statement.go | Close | func (stmt *OCI8Stmt) Close() error {
if stmt.closed {
return nil
}
stmt.closed = true
C.OCIHandleFree(unsafe.Pointer(stmt.stmt), C.OCI_HTYPE_STMT)
stmt.stmt = nil
stmt.pbind = nil
return nil
} | go | func (stmt *OCI8Stmt) Close() error {
if stmt.closed {
return nil
}
stmt.closed = true
C.OCIHandleFree(unsafe.Pointer(stmt.stmt), C.OCI_HTYPE_STMT)
stmt.stmt = nil
stmt.pbind = nil
return nil
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"stmt",
".",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"stmt",
".",
"closed",
"=",
"true",
"\n\n",
"C",
".",
"OCIHandleFree",
"(",
"unsafe",
".",
"Pointer",
"(... | // Close closes the statement | [
"Close",
"closes",
"the",
"statement"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L19-L31 | train |
mattn/go-oci8 | statement.go | NumInput | func (stmt *OCI8Stmt) NumInput() int {
var bindCount C.ub4 // number of bind position
_, err := stmt.ociAttrGet(unsafe.Pointer(&bindCount), C.OCI_ATTR_BIND_COUNT)
if err != nil {
return -1
}
return int(bindCount)
} | go | func (stmt *OCI8Stmt) NumInput() int {
var bindCount C.ub4 // number of bind position
_, err := stmt.ociAttrGet(unsafe.Pointer(&bindCount), C.OCI_ATTR_BIND_COUNT)
if err != nil {
return -1
}
return int(bindCount)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"NumInput",
"(",
")",
"int",
"{",
"var",
"bindCount",
"C",
".",
"ub4",
"// number of bind position",
"\n",
"_",
",",
"err",
":=",
"stmt",
".",
"ociAttrGet",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"bindCount",
... | // NumInput returns the number of input | [
"NumInput",
"returns",
"the",
"number",
"of",
"input"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L34-L42 | train |
mattn/go-oci8 | statement.go | Query | func (stmt *OCI8Stmt) Query(args []driver.Value) (rows driver.Rows, err error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return stmt.query(context.Background(), list, false)
} | go | func (stmt *OCI8Stmt) Query(args []driver.Value) (rows driver.Rows, err error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return stmt.query(context.Background(), list, false)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"Query",
"(",
"args",
"[",
"]",
"driver",
".",
"Value",
")",
"(",
"rows",
"driver",
".",
"Rows",
",",
"err",
"error",
")",
"{",
"list",
":=",
"make",
"(",
"[",
"]",
"namedValue",
",",
"len",
"(",
"args",... | // Query runs a query | [
"Query",
"runs",
"a",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L310-L319 | train |
mattn/go-oci8 | statement.go | getRowid | func (stmt *OCI8Stmt) getRowid() (string, error) {
rowidP, _, err := stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_ROWID, 0)
if err != nil {
return "", err
}
// OCI_ATTR_ROWID returns the ROWID descriptor allocated with OCIDescriptorAlloc()
_, err = stmt.ociAttrGet(*rowidP, C.OCI_ATTR_ROWID)
if err != nil {
return "", err
}
rowid := cStringN("", 18)
defer C.free(unsafe.Pointer(rowid))
rowidLength := C.ub2(18)
result := C.OCIRowidToChar((*C.OCIRowid)(*rowidP), rowid, &rowidLength, stmt.conn.errHandle)
err = stmt.conn.getError(result)
if err != nil {
return "", err
}
return cGoStringN(rowid, int(rowidLength)), nil
} | go | func (stmt *OCI8Stmt) getRowid() (string, error) {
rowidP, _, err := stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_ROWID, 0)
if err != nil {
return "", err
}
// OCI_ATTR_ROWID returns the ROWID descriptor allocated with OCIDescriptorAlloc()
_, err = stmt.ociAttrGet(*rowidP, C.OCI_ATTR_ROWID)
if err != nil {
return "", err
}
rowid := cStringN("", 18)
defer C.free(unsafe.Pointer(rowid))
rowidLength := C.ub2(18)
result := C.OCIRowidToChar((*C.OCIRowid)(*rowidP), rowid, &rowidLength, stmt.conn.errHandle)
err = stmt.conn.getError(result)
if err != nil {
return "", err
}
return cGoStringN(rowid, int(rowidLength)), nil
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"getRowid",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"rowidP",
",",
"_",
",",
"err",
":=",
"stmt",
".",
"conn",
".",
"ociDescriptorAlloc",
"(",
"C",
".",
"OCI_DTYPE_ROWID",
",",
"0",
")",
"\n",
"if... | // getRowid returns the rowid | [
"getRowid",
"returns",
"the",
"rowid"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L579-L601 | train |
mattn/go-oci8 | statement.go | rowsAffected | func (stmt *OCI8Stmt) rowsAffected() (int64, error) {
var rowCount C.ub4 // Number of rows processed so far after SELECT statements. For INSERT, UPDATE, and DELETE statements, it is the number of rows processed by the most recent statement. The default value is 1.
_, err := stmt.ociAttrGet(unsafe.Pointer(&rowCount), C.OCI_ATTR_ROW_COUNT)
if err != nil {
return -1, err
}
return int64(rowCount), nil
} | go | func (stmt *OCI8Stmt) rowsAffected() (int64, error) {
var rowCount C.ub4 // Number of rows processed so far after SELECT statements. For INSERT, UPDATE, and DELETE statements, it is the number of rows processed by the most recent statement. The default value is 1.
_, err := stmt.ociAttrGet(unsafe.Pointer(&rowCount), C.OCI_ATTR_ROW_COUNT)
if err != nil {
return -1, err
}
return int64(rowCount), nil
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"rowsAffected",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"rowCount",
"C",
".",
"ub4",
"// Number of rows processed so far after SELECT statements. For INSERT, UPDATE, and DELETE statements, it is the number of rows proc... | // rowsAffected returns the number of rows affected | [
"rowsAffected",
"returns",
"the",
"number",
"of",
"rows",
"affected"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L604-L611 | train |
mattn/go-oci8 | statement.go | Exec | func (stmt *OCI8Stmt) Exec(args []driver.Value) (r driver.Result, err error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return stmt.exec(context.Background(), list)
} | go | func (stmt *OCI8Stmt) Exec(args []driver.Value) (r driver.Result, err error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return stmt.exec(context.Background(), list)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"Exec",
"(",
"args",
"[",
"]",
"driver",
".",
"Value",
")",
"(",
"r",
"driver",
".",
"Result",
",",
"err",
"error",
")",
"{",
"list",
":=",
"make",
"(",
"[",
"]",
"namedValue",
",",
"len",
"(",
"args",
... | // Exec runs an exec query | [
"Exec",
"runs",
"an",
"exec",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L614-L623 | train |
mattn/go-oci8 | statement.go | exec | func (stmt *OCI8Stmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
binds, err := stmt.bind(ctx, args)
if err != nil {
return nil, err
}
defer freeBinds(binds)
mode := C.ub4(C.OCI_DEFAULT)
if stmt.conn.inTransaction == false {
mode = mode | C.OCI_COMMIT_ON_SUCCESS
}
done := make(chan struct{})
go stmt.ociBreak(ctx, done)
err = stmt.ociStmtExecute(1, mode)
close(done)
if err != nil && err != ErrOCISuccessWithInfo {
return nil, err
}
result := OCI8Result{stmt: stmt}
result.rowsAffected, result.rowsAffectedErr = stmt.rowsAffected()
if result.rowsAffectedErr != nil || result.rowsAffected < 1 {
result.rowidErr = ErrNoRowid
} else {
result.rowid, result.rowidErr = stmt.getRowid()
}
err = stmt.outputBoundParameters(binds)
if err != nil {
return nil, err
}
return &result, nil
} | go | func (stmt *OCI8Stmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
binds, err := stmt.bind(ctx, args)
if err != nil {
return nil, err
}
defer freeBinds(binds)
mode := C.ub4(C.OCI_DEFAULT)
if stmt.conn.inTransaction == false {
mode = mode | C.OCI_COMMIT_ON_SUCCESS
}
done := make(chan struct{})
go stmt.ociBreak(ctx, done)
err = stmt.ociStmtExecute(1, mode)
close(done)
if err != nil && err != ErrOCISuccessWithInfo {
return nil, err
}
result := OCI8Result{stmt: stmt}
result.rowsAffected, result.rowsAffectedErr = stmt.rowsAffected()
if result.rowsAffectedErr != nil || result.rowsAffected < 1 {
result.rowidErr = ErrNoRowid
} else {
result.rowid, result.rowidErr = stmt.getRowid()
}
err = stmt.outputBoundParameters(binds)
if err != nil {
return nil, err
}
return &result, nil
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"exec",
"(",
"ctx",
"context",
".",
"Context",
",",
"args",
"[",
"]",
"namedValue",
")",
"(",
"driver",
".",
"Result",
",",
"error",
")",
"{",
"binds",
",",
"err",
":=",
"stmt",
".",
"bind",
"(",
"ctx",
... | // exec runs an exec query | [
"exec",
"runs",
"an",
"exec",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L626-L662 | train |
mattn/go-oci8 | statement.go | ociParamGet | func (stmt *OCI8Stmt) ociParamGet(position C.ub4) (*C.OCIParam, error) {
var paramTemp *C.OCIParam
param := ¶mTemp
result := C.OCIParamGet(
unsafe.Pointer(stmt.stmt), // A statement handle or describe handle
C.OCI_HTYPE_STMT, // Handle type: OCI_HTYPE_STMT, for a statement handle
stmt.conn.errHandle, // An error handle
(*unsafe.Pointer)(unsafe.Pointer(param)), // A descriptor of the parameter at the position
position, // Position number in the statement handle or describe handle. A parameter descriptor will be returned for this position.
)
err := stmt.conn.getError(result)
if err != nil {
return nil, err
}
return *param, nil
} | go | func (stmt *OCI8Stmt) ociParamGet(position C.ub4) (*C.OCIParam, error) {
var paramTemp *C.OCIParam
param := ¶mTemp
result := C.OCIParamGet(
unsafe.Pointer(stmt.stmt), // A statement handle or describe handle
C.OCI_HTYPE_STMT, // Handle type: OCI_HTYPE_STMT, for a statement handle
stmt.conn.errHandle, // An error handle
(*unsafe.Pointer)(unsafe.Pointer(param)), // A descriptor of the parameter at the position
position, // Position number in the statement handle or describe handle. A parameter descriptor will be returned for this position.
)
err := stmt.conn.getError(result)
if err != nil {
return nil, err
}
return *param, nil
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociParamGet",
"(",
"position",
"C",
".",
"ub4",
")",
"(",
"*",
"C",
".",
"OCIParam",
",",
"error",
")",
"{",
"var",
"paramTemp",
"*",
"C",
".",
"OCIParam",
"\n",
"param",
":=",
"&",
"paramTemp",
"\n\n",
"... | // ociParamGet calls OCIParamGet then returns OCIParam and error.
// OCIDescriptorFree must be called on returned OCIParam. | [
"ociParamGet",
"calls",
"OCIParamGet",
"then",
"returns",
"OCIParam",
"and",
"error",
".",
"OCIDescriptorFree",
"must",
"be",
"called",
"on",
"returned",
"OCIParam",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L817-L835 | train |
mattn/go-oci8 | statement.go | ociAttrGet | func (stmt *OCI8Stmt) ociAttrGet(value unsafe.Pointer, attributeType C.ub4) (C.ub4, error) {
var size C.ub4
result := C.OCIAttrGet(
unsafe.Pointer(stmt.stmt), // Pointer to a handle type
C.OCI_HTYPE_STMT, // The handle type: OCI_HTYPE_STMT, for a statement handle
value, // Pointer to the storage for an attribute value
&size, // The size of the attribute value
attributeType, // The attribute type: https://docs.oracle.com/cd/B19306_01/appdev.102/b14250/ociaahan.htm
stmt.conn.errHandle, // An error handle
)
return size, stmt.conn.getError(result)
} | go | func (stmt *OCI8Stmt) ociAttrGet(value unsafe.Pointer, attributeType C.ub4) (C.ub4, error) {
var size C.ub4
result := C.OCIAttrGet(
unsafe.Pointer(stmt.stmt), // Pointer to a handle type
C.OCI_HTYPE_STMT, // The handle type: OCI_HTYPE_STMT, for a statement handle
value, // Pointer to the storage for an attribute value
&size, // The size of the attribute value
attributeType, // The attribute type: https://docs.oracle.com/cd/B19306_01/appdev.102/b14250/ociaahan.htm
stmt.conn.errHandle, // An error handle
)
return size, stmt.conn.getError(result)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociAttrGet",
"(",
"value",
"unsafe",
".",
"Pointer",
",",
"attributeType",
"C",
".",
"ub4",
")",
"(",
"C",
".",
"ub4",
",",
"error",
")",
"{",
"var",
"size",
"C",
".",
"ub4",
"\n\n",
"result",
":=",
"C",
... | // ociAttrGet calls OCIAttrGet with OCIStmt then returns attribute size and error.
// The attribute value is stored into passed value. | [
"ociAttrGet",
"calls",
"OCIAttrGet",
"with",
"OCIStmt",
"then",
"returns",
"attribute",
"size",
"and",
"error",
".",
"The",
"attribute",
"value",
"is",
"stored",
"into",
"passed",
"value",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L839-L852 | train |
mattn/go-oci8 | statement.go | ociBindByName | func (stmt *OCI8Stmt) ociBindByName(name []byte, bind *oci8Bind) error {
result := C.OCIBindByName(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.
stmt.conn.errHandle, // An error handle
(*C.OraText)(&name[0]), // The placeholder, specified by its name, that maps to a variable in the statement associated with the statement handle.
C.sb4(len(name)), // The length of the name specified in placeholder, in number of bytes regardless of the encoding.
bind.pbuf, // The pointer to a data value or an array of data values of type specified in the dty parameter
bind.maxSize, // The maximum size possible in bytes of any data value for this bind variable
bind.dataType, // The data type of the values being bound
unsafe.Pointer(bind.indicator), // Pointer to an indicator variable or array
bind.length, // lengths are in bytes in general
nil, // Pointer to the array of column-level return codes
0, // A maximum array length parameter
nil, // Current array length parameter
C.OCI_DEFAULT, // The mode. Recommended to set to OCI_DEFAULT, which makes the bind variable have the same encoding as its statement.
)
return stmt.conn.getError(result)
} | go | func (stmt *OCI8Stmt) ociBindByName(name []byte, bind *oci8Bind) error {
result := C.OCIBindByName(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.
stmt.conn.errHandle, // An error handle
(*C.OraText)(&name[0]), // The placeholder, specified by its name, that maps to a variable in the statement associated with the statement handle.
C.sb4(len(name)), // The length of the name specified in placeholder, in number of bytes regardless of the encoding.
bind.pbuf, // The pointer to a data value or an array of data values of type specified in the dty parameter
bind.maxSize, // The maximum size possible in bytes of any data value for this bind variable
bind.dataType, // The data type of the values being bound
unsafe.Pointer(bind.indicator), // Pointer to an indicator variable or array
bind.length, // lengths are in bytes in general
nil, // Pointer to the array of column-level return codes
0, // A maximum array length parameter
nil, // Current array length parameter
C.OCI_DEFAULT, // The mode. Recommended to set to OCI_DEFAULT, which makes the bind variable have the same encoding as its statement.
)
return stmt.conn.getError(result)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociBindByName",
"(",
"name",
"[",
"]",
"byte",
",",
"bind",
"*",
"oci8Bind",
")",
"error",
"{",
"result",
":=",
"C",
".",
"OCIBindByName",
"(",
"stmt",
".",
"stmt",
",",
"// The statement handle",
"&",
"bind",
... | // ociBindByName calls OCIBindByName, then returns bind handle and error. | [
"ociBindByName",
"calls",
"OCIBindByName",
"then",
"returns",
"bind",
"handle",
"and",
"error",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L855-L874 | train |
mattn/go-oci8 | statement.go | ociBindByPos | func (stmt *OCI8Stmt) ociBindByPos(position C.ub4, bind *oci8Bind) error {
result := C.OCIBindByPos(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.
stmt.conn.errHandle, // An error handle
position, // The placeholder attributes are specified by position if OCIBindByPos() is being called.
bind.pbuf, // An address of a data value or an array of data values
bind.maxSize, // The maximum size possible in bytes of any data value for this bind variable
bind.dataType, // The data type of the values being bound
unsafe.Pointer(bind.indicator), // Pointer to an indicator variable or array
bind.length, // lengths are in bytes in general
nil, // Pointer to the array of column-level return codes
0, // A maximum array length parameter
nil, // Current array length parameter
C.OCI_DEFAULT, // The mode. Recommended to set to OCI_DEFAULT, which makes the bind variable have the same encoding as its statement.
)
return stmt.conn.getError(result)
} | go | func (stmt *OCI8Stmt) ociBindByPos(position C.ub4, bind *oci8Bind) error {
result := C.OCIBindByPos(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.
stmt.conn.errHandle, // An error handle
position, // The placeholder attributes are specified by position if OCIBindByPos() is being called.
bind.pbuf, // An address of a data value or an array of data values
bind.maxSize, // The maximum size possible in bytes of any data value for this bind variable
bind.dataType, // The data type of the values being bound
unsafe.Pointer(bind.indicator), // Pointer to an indicator variable or array
bind.length, // lengths are in bytes in general
nil, // Pointer to the array of column-level return codes
0, // A maximum array length parameter
nil, // Current array length parameter
C.OCI_DEFAULT, // The mode. Recommended to set to OCI_DEFAULT, which makes the bind variable have the same encoding as its statement.
)
return stmt.conn.getError(result)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociBindByPos",
"(",
"position",
"C",
".",
"ub4",
",",
"bind",
"*",
"oci8Bind",
")",
"error",
"{",
"result",
":=",
"C",
".",
"OCIBindByPos",
"(",
"stmt",
".",
"stmt",
",",
"// The statement handle",
"&",
"bind",... | // ociBindByPos calls OCIBindByPos, then returns bind handle and error. | [
"ociBindByPos",
"calls",
"OCIBindByPos",
"then",
"returns",
"bind",
"handle",
"and",
"error",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L877-L895 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.