id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
150,400 | 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",
"(",
"buf",
"[",
":",
"n",
"]",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"n",
"=",
"copy",
"(",
"buf",
",",
"t",
")",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // 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 |
150,401 | 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",
"(",
"bufio",
".",
"NewReader",
"(",
"s",
")",
")",
"\n",
"// Parse the main headers",
"hdrs",
",",
"err",
":=",
"tp",
".",
"ReadMIMEHeader",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"e",
",",
"err",
"\n",
"}",
"\n",
"// Set the subject, to, cc, bcc, and from",
"for",
"h",
",",
"v",
":=",
"range",
"hdrs",
"{",
"switch",
"{",
"case",
"h",
"==",
"\"",
"\"",
":",
"e",
".",
"Subject",
"=",
"v",
"[",
"0",
"]",
"\n",
"delete",
"(",
"hdrs",
",",
"h",
")",
"\n",
"case",
"h",
"==",
"\"",
"\"",
":",
"e",
".",
"To",
"=",
"v",
"\n",
"delete",
"(",
"hdrs",
",",
"h",
")",
"\n",
"case",
"h",
"==",
"\"",
"\"",
":",
"e",
".",
"Cc",
"=",
"v",
"\n",
"delete",
"(",
"hdrs",
",",
"h",
")",
"\n",
"case",
"h",
"==",
"\"",
"\"",
":",
"e",
".",
"Bcc",
"=",
"v",
"\n",
"delete",
"(",
"hdrs",
",",
"h",
")",
"\n",
"case",
"h",
"==",
"\"",
"\"",
":",
"e",
".",
"From",
"=",
"v",
"[",
"0",
"]",
"\n",
"delete",
"(",
"hdrs",
",",
"h",
")",
"\n",
"}",
"\n",
"}",
"\n",
"e",
".",
"Headers",
"=",
"hdrs",
"\n",
"body",
":=",
"tp",
".",
"R",
"\n",
"// Recursively parse the MIME parts",
"ps",
",",
"err",
":=",
"parseMIMEParts",
"(",
"e",
".",
"Headers",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"e",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
"{",
"if",
"ct",
":=",
"p",
".",
"header",
".",
"Get",
"(",
"\"",
"\"",
")",
";",
"ct",
"==",
"\"",
"\"",
"{",
"return",
"e",
",",
"ErrMissingContentType",
"\n",
"}",
"\n",
"ct",
",",
"_",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"p",
".",
"header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"e",
",",
"err",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"ct",
"==",
"\"",
"\"",
":",
"e",
".",
"Text",
"=",
"p",
".",
"body",
"\n",
"case",
"ct",
"==",
"\"",
"\"",
":",
"e",
".",
"HTML",
"=",
"p",
".",
"body",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"e",
",",
"nil",
"\n",
"}"
] | // 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",
"format",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L84-L136 |
150,402 | 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",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"&",
"buffer",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"at",
":=",
"&",
"Attachment",
"{",
"Filename",
":",
"filename",
",",
"Header",
":",
"textproto",
".",
"MIMEHeader",
"{",
"}",
",",
"Content",
":",
"buffer",
".",
"Bytes",
"(",
")",
",",
"}",
"\n",
"// Get the Content-Type to be used in the MIMEHeader",
"if",
"c",
"!=",
"\"",
"\"",
"{",
"at",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"}",
"else",
"{",
"// If the Content-Type is blank, set the Content-Type to \"application/octet-stream\"",
"at",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"at",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\r",
"\\n",
"\\\"",
"\\\"",
"\"",
",",
"filename",
")",
")",
"\n",
"at",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"filename",
")",
")",
"\n",
"at",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"e",
".",
"Attachments",
"=",
"append",
"(",
"e",
".",
"Attachments",
",",
"at",
")",
"\n",
"return",
"at",
",",
"nil",
"\n",
"}"
] | // 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",
"Content",
"-",
"Type",
"The",
"function",
"will",
"return",
"the",
"created",
"Attachment",
"for",
"reference",
"as",
"well",
"as",
"nil",
"for",
"the",
"error",
"if",
"successful",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L209-L231 |
150,403 | 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",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"ct",
":=",
"mime",
".",
"TypeByExtension",
"(",
"filepath",
".",
"Ext",
"(",
"filename",
")",
")",
"\n",
"basename",
":=",
"filepath",
".",
"Base",
"(",
"filename",
")",
"\n",
"return",
"e",
".",
"Attach",
"(",
"f",
",",
"basename",
",",
"ct",
")",
"\n",
"}"
] | // 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",
"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",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L237-L247 |
150,404 | 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",
"if",
"e",
".",
"Headers",
"!=",
"nil",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"{",
"if",
"v",
",",
"ok",
":=",
"e",
".",
"Headers",
"[",
"h",
"]",
";",
"ok",
"{",
"res",
"[",
"h",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Set headers if there are values.",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"&&",
"len",
"(",
"e",
".",
"ReplyTo",
")",
">",
"0",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"e",
".",
"ReplyTo",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"&&",
"len",
"(",
"e",
".",
"To",
")",
">",
"0",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"e",
".",
"To",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"&&",
"len",
"(",
"e",
".",
"Cc",
")",
">",
"0",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"e",
".",
"Cc",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"&&",
"e",
".",
"Subject",
"!=",
"\"",
"\"",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"e",
".",
"Subject",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"id",
",",
"err",
":=",
"generateMessageID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"// Date and From are required headers.",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"e",
".",
"From",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"time",
".",
"RFC1123Z",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"res",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"field",
",",
"vals",
":=",
"range",
"e",
".",
"Headers",
"{",
"if",
"_",
",",
"ok",
":=",
"res",
"[",
"field",
"]",
";",
"!",
"ok",
"{",
"res",
"[",
"field",
"]",
"=",
"vals",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] | // 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",
"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",
"."
] | 3ea4d25e7cf84fe656d10353672a0eba4b919b6d | https://github.com/jordan-wright/email/blob/3ea4d25e7cf84fe656d10353672a0eba4b919b6d/email.go#L255-L300 |
150,405 | 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",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"sender",
".",
"Address",
",",
"nil",
"\n",
"}",
"else",
"{",
"from",
",",
"err",
":=",
"mail",
".",
"ParseAddress",
"(",
"e",
".",
"From",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"from",
".",
"Address",
",",
"nil",
"\n",
"}",
"\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 |
150,406 | 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",
",",
"0",
",",
"len",
"(",
"e",
".",
"To",
")",
"+",
"len",
"(",
"e",
".",
"Cc",
")",
"+",
"len",
"(",
"e",
".",
"Bcc",
")",
")",
"\n",
"to",
"=",
"append",
"(",
"append",
"(",
"append",
"(",
"to",
",",
"e",
".",
"To",
"...",
")",
",",
"e",
".",
"Cc",
"...",
")",
",",
"e",
".",
"Bcc",
"...",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"to",
")",
";",
"i",
"++",
"{",
"addr",
",",
"err",
":=",
"mail",
".",
"ParseAddress",
"(",
"to",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"to",
"[",
"i",
"]",
"=",
"addr",
".",
"Address",
"\n",
"}",
"\n",
"// Check to make sure there is at least one recipient and one \"From\" address",
"if",
"e",
".",
"From",
"==",
"\"",
"\"",
"||",
"len",
"(",
"to",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"sender",
",",
"err",
":=",
"e",
".",
"parseSender",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"raw",
",",
"err",
":=",
"e",
".",
"Bytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"tls",
".",
"Dial",
"(",
"\"",
"\"",
",",
"addr",
",",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"c",
",",
"err",
":=",
"smtp",
".",
"NewClient",
"(",
"conn",
",",
"t",
".",
"ServerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"=",
"c",
".",
"Hello",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Use TLS if available",
"if",
"ok",
",",
"_",
":=",
"c",
".",
"Extension",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"err",
"=",
"c",
".",
"StartTLS",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"a",
"!=",
"nil",
"{",
"if",
"ok",
",",
"_",
":=",
"c",
".",
"Extension",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"err",
"=",
"c",
".",
"Auth",
"(",
"a",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"c",
".",
"Mail",
"(",
"sender",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"to",
"{",
"if",
"err",
"=",
"c",
".",
"Rcpt",
"(",
"addr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"w",
",",
"err",
":=",
"c",
".",
"Data",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"w",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"Quit",
"(",
")",
"\n",
"}"
] | // 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 |
150,407 | 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",
",",
"err",
"\n",
"}",
"\n\n",
"// Create an empty file at the mount point.",
"nsPath",
":=",
"filepath",
".",
"Join",
"(",
"persistentNsDir",
",",
"string",
"(",
"namespaceType",
")",
")",
"\n\n",
"mountFd",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"nsPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"mountFd",
".",
"Close",
"(",
")",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n\n",
"go",
"(",
"func",
"(",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"runtime",
".",
"LockOSThread",
"(",
")",
"\n\n",
"var",
"origNsFd",
"*",
"os",
".",
"File",
"\n",
"origNsPath",
":=",
"getCurrentThreadNSPath",
"(",
"namespaceType",
")",
"\n",
"origNsFd",
",",
"err",
"=",
"os",
".",
"Open",
"(",
"origNsPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"origNsFd",
".",
"Close",
"(",
")",
"\n\n",
"// Create a new netns on the current thread.",
"err",
"=",
"unix",
".",
"Unshare",
"(",
"cloneFlagsTable",
"[",
"namespaceType",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Bind mount the new namespace from the current thread onto the mount point to persist it.",
"err",
"=",
"unix",
".",
"Mount",
"(",
"getCurrentThreadNSPath",
"(",
"namespaceType",
")",
",",
"nsPath",
",",
"\"",
"\"",
",",
"unix",
".",
"MS_BIND",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Switch back to original namespace.",
"if",
"err",
"=",
"unix",
".",
"Setns",
"(",
"int",
"(",
"origNsFd",
".",
"Fd",
"(",
")",
")",
",",
"cloneFlagsTable",
"[",
"namespaceType",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"}",
")",
"(",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"unix",
".",
"Unmount",
"(",
"nsPath",
",",
"unix",
".",
"MNT_DETACH",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"namespace",
"{",
"path",
":",
"nsPath",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
150,408 | 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",
"pb",
".",
"RegisterHealthServer",
"(",
"serv",
",",
"mock",
")",
"\n\n",
"return",
"serv",
"\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 |
150,409 | 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\n",
"cpusetListReq",
",",
"err",
":=",
"parsers",
".",
"ParseUintList",
"(",
"cpusetReq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"cpusetGuestList",
",",
"err",
":=",
"parsers",
".",
"ParseUintList",
"(",
"cpusetGuest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"k",
":=",
"range",
"cpusetListReq",
"{",
"if",
"!",
"cpusetGuestList",
"[",
"k",
"]",
"{",
"agentLog",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"cpusetReq",
",",
"\"",
"\"",
":",
"k",
",",
"\"",
"\"",
":",
"cpusetGuest",
",",
"}",
")",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"cpusetGuest",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// All the cpus are valid keep the same cpuset string",
"agentLog",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"cpusetReq",
",",
"}",
")",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"cpusetReq",
",",
"nil",
"\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",
"as",
"they",
"are",
"hotplugged",
"based",
"on",
"cpu",
"and",
"qouta",
".",
"This",
"function",
"return",
"a",
"working",
"cpuset",
"to",
"apply",
"on",
"the",
"guest",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/cgroup.go#L32-L65 |
150,410 | 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",
"\n",
"}"
] | // 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 |
150,411 | 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",
"s",
",",
"err",
"\n",
"}"
] | // 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 |
150,412 | 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",
"s",
",",
"err",
"\n",
"}"
] | // 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 |
150,413 | 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",
")",
"\n\n",
"return",
"s",
",",
"err",
"\n",
"}"
] | // 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 |
150,414 | 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",
")",
"\n\n",
"return",
"s",
",",
"err",
"\n",
"}"
] | // 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 |
150,415 | 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",
",",
"grpcResources",
")",
"\n\n",
"return",
"s",
",",
"err",
"\n",
"}"
] | // 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 |
150,416 | 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",
".",
"Ping",
"(",
")",
"\n\n",
"// 1 Hz heartbeat",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"the",
"Yamux",
"server",
"in",
"the",
"agent",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/protocols/client/client.go#L171-L186 |
150,417 | 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",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"source",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"createDestinationDir",
"(",
"destination",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"destination",
")",
"\n",
"}",
"\n\n",
"if",
"fsType",
"!=",
"\"",
"\"",
"||",
"fileInfo",
".",
"IsDir",
"(",
")",
"{",
"if",
"err",
":=",
"os",
".",
"Mkdir",
"(",
"destination",
",",
"mountPerm",
")",
";",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"file",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"destination",
",",
"os",
".",
"O_CREATE",
",",
"mountPerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"file",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
150,418 | 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 |
150,419 | 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",
":=",
"getPCIDeviceName",
"(",
"s",
",",
"storage",
".",
"Source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"storage",
".",
"Source",
"=",
"devPath",
"\n\n",
"return",
"commonStorageHandler",
"(",
"storage",
")",
"\n",
"}"
] | // 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 |
150,420 | 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",
".",
"Source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"storage",
".",
"Source",
"=",
"devPath",
"\n\n",
"return",
"commonStorageHandler",
"(",
"storage",
")",
"\n",
"}"
] | // 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 |
150,421 | 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",
"}",
"\n\n",
"return",
"mount",
"(",
"storage",
".",
"Source",
",",
"storage",
".",
"MountPoint",
",",
"storage",
".",
"Fstype",
",",
"flags",
",",
"options",
")",
"\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 |
150,422 | 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",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"s",
".",
"id",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"var",
"mountList",
"[",
"]",
"string",
"\n\n",
"for",
"_",
",",
"storage",
":=",
"range",
"storages",
"{",
"if",
"storage",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"devHandler",
",",
"ok",
":=",
"storageHandlerList",
"[",
"storage",
".",
"Driver",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"storage",
".",
"Driver",
")",
"\n",
"}",
"\n\n",
"// 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",
",",
"\"",
"\"",
",",
"storage",
".",
"Driver",
")",
"\n",
"mountPoint",
",",
"err",
":=",
"devHandler",
"(",
"*",
"storage",
",",
"s",
")",
"\n",
"handlerSpan",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"mountPoint",
"!=",
"\"",
"\"",
"{",
"// Prepend mount point to mount list.",
"mountList",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"mountPoint",
"}",
",",
"mountList",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"mountList",
",",
"nil",
"\n",
"}"
] | // 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",
"location",
"according",
"to",
"the",
"type",
"of",
"handler",
"chosen",
"and",
"for",
"each",
"storage",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/mount.go#L320-L356 |
150,423 | 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",
"}",
"\n\n",
"kernelCmdline",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"cmdLineFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"words",
":=",
"strings",
".",
"Fields",
"(",
"string",
"(",
"kernelCmdline",
")",
")",
"\n",
"for",
"_",
",",
"word",
":=",
"range",
"words",
"{",
"if",
"err",
":=",
"c",
".",
"parseCmdlineOption",
"(",
"word",
")",
";",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"err",
",",
"\"",
"\"",
":",
"word",
",",
"}",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\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 |
150,424 | 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",
"==",
"devModeFlag",
"{",
"crashOnError",
"=",
"true",
"\n",
"debug",
"=",
"true",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"option",
"==",
"traceModeFlag",
"{",
"enableTracing",
"(",
"traceModeStatic",
",",
"defaultTraceType",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"split",
":=",
"strings",
".",
"Split",
"(",
"option",
",",
"optionSeparator",
")",
"\n\n",
"if",
"len",
"(",
"split",
")",
"<",
"valuePosition",
"+",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"switch",
"split",
"[",
"optionPosition",
"]",
"{",
"case",
"logLevelFlag",
":",
"level",
",",
"err",
":=",
"logrus",
".",
"ParseLevel",
"(",
"split",
"[",
"valuePosition",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"logLevel",
"=",
"level",
"\n",
"if",
"level",
"==",
"logrus",
".",
"DebugLevel",
"{",
"debug",
"=",
"true",
"\n",
"}",
"\n",
"case",
"traceModeFlag",
":",
"switch",
"split",
"[",
"valuePosition",
"]",
"{",
"case",
"traceTypeIsolated",
":",
"enableTracing",
"(",
"traceModeStatic",
",",
"traceTypeIsolated",
")",
"\n",
"case",
"traceTypeCollated",
":",
"enableTracing",
"(",
"traceModeStatic",
",",
"traceTypeCollated",
")",
"\n",
"}",
"\n",
"case",
"useVsockFlag",
":",
"flag",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"split",
"[",
"valuePosition",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"flag",
"{",
"agentLog",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"commCh",
"=",
"vsockCh",
"\n",
"}",
"else",
"{",
"agentLog",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"commCh",
"=",
"serialCh",
"\n",
"}",
"\n",
"default",
":",
"if",
"strings",
".",
"HasPrefix",
"(",
"split",
"[",
"optionPosition",
"]",
",",
"optionPrefix",
")",
"{",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"split",
"[",
"optionPosition",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"}"
] | //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 |
150,425 | 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. This allows multiple netlink sockets to be used.",
"Pid",
":",
"uint32",
"(",
"0",
")",
",",
"Groups",
":",
"1",
",",
"}",
"\n\n",
"fd",
",",
"err",
":=",
"unix",
".",
"Socket",
"(",
"unix",
".",
"AF_NETLINK",
",",
"unix",
".",
"SOCK_RAW",
",",
"unix",
".",
"NETLINK_KOBJECT_UEVENT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"unix",
".",
"Bind",
"(",
"fd",
",",
"&",
"nl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"ReaderCloser",
"{",
"fd",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
150,426 | 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",
"&&",
"err",
"!=",
"nil",
"{",
"count",
"=",
"0",
"\n",
"}",
"\n",
"return",
"count",
",",
"err",
"\n",
"}"
] | // 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 |
150,427 | 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",
"{",
"readerCloser",
":",
"rdCloser",
",",
"bufioReader",
":",
"bufio",
".",
"NewReader",
"(",
"rdCloser",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
150,428 | 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",
"(",
"paramDelim",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Fill uevent header.",
"uEv",
".",
"Header",
"=",
"header",
"\n\n",
"exitLoop",
":=",
"false",
"\n\n",
"// Read every parameter as \"key=value\".",
"for",
"!",
"exitLoop",
"{",
"keyValue",
",",
"err",
":=",
"h",
".",
"bufioReader",
".",
"ReadString",
"(",
"paramDelim",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"idx",
":=",
"strings",
".",
"Index",
"(",
"keyValue",
",",
"\"",
"\"",
")",
"\n",
"if",
"idx",
"<",
"1",
"{",
"return",
"nil",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"keyValue",
")",
"\n",
"}",
"\n\n",
"// 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",
"]",
"\n\n",
"switch",
"key",
"{",
"case",
"uEventAction",
":",
"uEv",
".",
"Action",
"=",
"val",
"\n",
"case",
"uEventDevPath",
":",
"uEv",
".",
"DevPath",
"=",
"val",
"\n",
"case",
"uEventSubSystem",
":",
"uEv",
".",
"SubSystem",
"=",
"val",
"\n",
"case",
"uEventDevName",
":",
"uEv",
".",
"DevName",
"=",
"val",
"\n",
"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",
"\n",
"case",
"uEventSeqNum",
":",
"uEv",
".",
"SeqNum",
"=",
"val",
"\n\n",
"// \"SEQNUM\" signals the uevent is complete.",
"exitLoop",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"uEv",
",",
"nil",
"\n",
"}"
] | // 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 |
150,429 | 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 warnings and errors",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Warn",
"(",
"message",
")",
"\n\n",
"return",
"l",
",",
"nil",
"\n",
"}"
] | // 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 |
150,430 | 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 happen for a hypervisor with vsock driver",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"// standard driver files that should be ignored",
"driverFiles",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"driverFiles",
"{",
"if",
"file",
".",
"Name",
"(",
")",
"==",
"f",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"fPath",
":=",
"filepath",
".",
"Join",
"(",
"sysVsockPath",
",",
"file",
".",
"Name",
"(",
")",
")",
"\n",
"fInfo",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"fPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"fInfo",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"link",
",",
"err",
":=",
"os",
".",
"Readlink",
"(",
"fPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"link",
",",
"\"",
"\"",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // 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",
"for",
"the",
"vhost",
"-",
"vsock",
"driver",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/channel.go#L274-L316 |
150,431 | 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",
".",
"stdin",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"stdout",
"!=",
"nil",
"{",
"p",
".",
"stdout",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"stderr",
"!=",
"nil",
"{",
"p",
".",
"stderr",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"epoller",
"!=",
"nil",
"{",
"p",
".",
"epoller",
".",
"sockR",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"longer",
"needed",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L204-L224 |
150,432 | 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",
":",
"1",
"}",
"\n",
"s",
".",
"storages",
"[",
"path",
"]",
"=",
"sbs",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"sbs",
":=",
"s",
".",
"storages",
"[",
"path",
"]",
"\n",
"sbs",
".",
"refCount",
"++",
"\n",
"return",
"false",
"\n",
"}"
] | // 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",
"not",
".",
"It",
"will",
"return",
"true",
"if",
"storage",
"is",
"new",
".",
"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#L296-L305 |
150,433 | 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",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"fieldLogger",
":=",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"guestHookPath",
")",
"\n",
"fieldLogger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"s",
".",
"guestHooks",
".",
"Prestart",
"=",
"findHooks",
"(",
"guestHookPath",
",",
"\"",
"\"",
")",
"\n",
"s",
".",
"guestHooks",
".",
"Poststart",
"=",
"findHooks",
"(",
"guestHookPath",
",",
"\"",
"\"",
")",
"\n",
"s",
".",
"guestHooks",
".",
"Poststop",
"=",
"findHooks",
"(",
"guestHookPath",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"len",
"(",
"s",
".",
"guestHooks",
".",
"Prestart",
")",
">",
"0",
"||",
"len",
"(",
"s",
".",
"guestHooks",
".",
"Poststart",
")",
">",
"0",
"||",
"len",
"(",
"s",
".",
"guestHooks",
".",
"Poststop",
")",
">",
"0",
"{",
"s",
".",
"guestHooksPresent",
"=",
"true",
"\n",
"}",
"else",
"{",
"fieldLogger",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
150,434 | 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",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"spec",
".",
"Hooks",
"==",
"nil",
"{",
"spec",
".",
"Hooks",
"=",
"&",
"specs",
".",
"Hooks",
"{",
"}",
"\n",
"}",
"\n\n",
"spec",
".",
"Hooks",
".",
"Prestart",
"=",
"append",
"(",
"spec",
".",
"Hooks",
".",
"Prestart",
",",
"s",
".",
"guestHooks",
".",
"Prestart",
"...",
")",
"\n",
"spec",
".",
"Hooks",
".",
"Poststart",
"=",
"append",
"(",
"spec",
".",
"Hooks",
".",
"Poststart",
",",
"s",
".",
"guestHooks",
".",
"Poststart",
"...",
")",
"\n",
"spec",
".",
"Hooks",
".",
"Poststop",
"=",
"append",
"(",
"spec",
".",
"Hooks",
".",
"Poststop",
",",
"s",
".",
"guestHooks",
".",
"Poststop",
"...",
")",
"\n",
"}"
] | // 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 |
150,435 | 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",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"sbs",
",",
"ok",
":=",
"s",
".",
"storages",
"[",
"path",
"]",
";",
"ok",
"{",
"sbs",
".",
"refCount",
"--",
"\n",
"// If this sandbox storage is not used by any container",
"// then remove it's reference",
"if",
"sbs",
".",
"refCount",
"<",
"1",
"{",
"delete",
"(",
"s",
".",
"storages",
",",
"path",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}"
] | // 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",
"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",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L356-L372 |
150,436 | 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",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"err",
":=",
"removeMounts",
"(",
"[",
"]",
"string",
"{",
"path",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Unknown",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"RemoveAll",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Unknown",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
150,437 | 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",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"storages",
"[",
"path",
"]",
";",
"ok",
"{",
"removeSbs",
",",
"err",
":=",
"s",
".",
"unSetSandboxStorage",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"removeSbs",
"{",
"if",
"err",
":=",
"s",
".",
"removeSandboxStorage",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"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",
"calling",
"this",
"method",
"after",
"acquiring",
"a",
"lock",
"on",
"sandbox",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/agent.go#L401-L421 |
150,438 | 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",
"sig",
"==",
"unix",
".",
"SIGCHLD",
"{",
"if",
"err",
":=",
"s",
".",
"subreaper",
".",
"reap",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"nativeSignal",
",",
"ok",
":=",
"sig",
".",
"(",
"syscall",
".",
"Signal",
")",
"\n",
"if",
"!",
"ok",
"{",
"err",
":=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"logger",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"fatalSignal",
"(",
"nativeSignal",
")",
"{",
"logger",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"die",
"(",
"s",
".",
"ctx",
")",
"\n",
"}",
"\n\n",
"if",
"debug",
"&&",
"nonFatalSignal",
"(",
"nativeSignal",
")",
"{",
"logger",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"backtrace",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"logger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
150,439 | 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",
":=",
"string",
"(",
"bytes",
")",
"\n\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"lines",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"expectedFields",
":=",
"2",
"\n\n",
"fields",
":=",
"strings",
".",
"Split",
"(",
"line",
",",
"\"",
"\"",
")",
"\n",
"count",
":=",
"len",
"(",
"fields",
")",
"\n\n",
"if",
"count",
"!=",
"expectedFields",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expectedFields",
",",
"count",
",",
"line",
")",
"\n",
"}",
"\n\n",
"if",
"fields",
"[",
"1",
"]",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"line",
")",
"\n",
"}",
"\n\n",
"memTotal",
":=",
"strings",
".",
"TrimSpace",
"(",
"fields",
"[",
"1",
"]",
")",
"\n\n",
"return",
"memTotal",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"meminfo",
")",
"\n",
"}"
] | // 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 |
150,440 | 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",
":=",
"formatFields",
"(",
"agentFields",
")",
"\n",
"extraFields",
":=",
"formatFields",
"(",
"announceFields",
")",
"\n\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"extraFields",
"...",
")",
"\n\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"Join",
"(",
"fields",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"{",
"agentLog",
".",
"WithFields",
"(",
"announceFields",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
150,441 | 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",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"syscall",
".",
"Unlink",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"syscall",
".",
"Symlink",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"syscall",
".",
"Setsid",
"(",
")",
"\n",
"syscall",
".",
"Syscall",
"(",
"syscall",
".",
"SYS_IOCTL",
",",
"os",
".",
"Stdin",
".",
"Fd",
"(",
")",
",",
"syscall",
".",
"TIOCSCTTY",
",",
"1",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"announce",
"(",
")",
"\n",
"}"
] | // 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 |
150,442 | 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",
":=",
"ioutil",
".",
"ReadDir",
"(",
"hooksPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"hookType",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"name",
":=",
"file",
".",
"Name",
"(",
")",
"\n",
"if",
"ok",
",",
"err",
":=",
"isValidHook",
"(",
"file",
")",
";",
"!",
"ok",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"name",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"agentLog",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"name",
",",
"\"",
"\"",
":",
"hookType",
",",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"hooksFound",
"=",
"append",
"(",
"hooksFound",
",",
"specs",
".",
"Hook",
"{",
"Path",
":",
"path",
".",
"Join",
"(",
"hooksPath",
",",
"name",
")",
",",
"Args",
":",
"[",
"]",
"string",
"{",
"name",
",",
"hookType",
"}",
",",
"}",
")",
"\n",
"}",
"\n\n",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"hookType",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"len",
"(",
"hooksFound",
")",
")",
"\n\n",
"return",
"\n",
"}"
] | // 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 |
150,443 | 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",
"(",
"ctx",
",",
"name",
")",
"\n\n",
"span",
".",
"SetTag",
"(",
"\"",
"\"",
",",
"subsystem",
")",
"\n\n",
"// 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",
"(",
"\"",
"\"",
",",
"span",
")",
"\n",
"}",
"\n\n",
"return",
"span",
",",
"ctx",
"\n",
"}"
] | // 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 |
150,444 | 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 |
150,445 | 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",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"count",
"uint32",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"matched",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"resource",
".",
"regexpPattern",
",",
"file",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"count",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"matched",
"{",
"continue",
"\n",
"}",
"\n\n",
"onlinePath",
":=",
"filepath",
".",
"Join",
"(",
"resource",
".",
"sysfsOnlinePath",
",",
"file",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"status",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"onlinePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// resource cold plugged",
"continue",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"Trim",
"(",
"string",
"(",
"status",
")",
",",
"\"",
"\\n",
"\\t",
"\"",
")",
"==",
"\"",
"\"",
"{",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"onlinePath",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"0600",
")",
";",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"onlinePath",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"count",
"++",
"\n",
"if",
"nbResources",
">",
"0",
"&&",
"count",
"==",
"uint32",
"(",
"nbResources",
")",
"{",
"return",
"count",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] | // 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",
".",
"Returns",
"the",
"number",
"of",
"resources",
"connected",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L94-L131 |
150,446 | 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",
":=",
"cgroupCpusetPath",
"\n\n",
"cpusetGuest",
",",
"err",
":=",
"getCpusetGuest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// 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",
")",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"cgroupsParentPaths",
"{",
"// Skip if empty.",
"if",
"path",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"cgroupParentPath",
"=",
"filepath",
".",
"Join",
"(",
"cgroupParentPath",
",",
"path",
")",
"\n\n",
"// check if the cgroup was already updated.",
"if",
"cookies",
"[",
"cgroupParentPath",
"]",
"{",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"cgroupParentPath",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"cpusetCpusParentPath",
":=",
"filepath",
".",
"Join",
"(",
"cgroupParentPath",
",",
"\"",
"\"",
")",
"\n\n",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"cpusetCpusParentPath",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"cpusetCpusParentPath",
",",
"[",
"]",
"byte",
"(",
"cpusetGuest",
")",
",",
"cpusetMode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cpusetCpusParentPath",
",",
"cpusetGuest",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// add cgroup path to the cookies.",
"cookies",
"[",
"cgroupParentPath",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"// Finally update group path with requested value.",
"cpusetCpusPath",
":=",
"filepath",
".",
"Join",
"(",
"cgroupCpusetPath",
",",
"cgroupPath",
",",
"\"",
"\"",
")",
"\n\n",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"cpusetCpusPath",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"cpusetCpusPath",
",",
"[",
"]",
"byte",
"(",
"newCpuset",
")",
",",
"cpusetMode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cpusetCpusPath",
",",
"cpusetGuest",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"updated",
"with",
"the",
"requsted",
"value",
".",
"cookies",
"are",
"used",
"for",
"performance",
"reasons",
"in",
"order",
"to",
"don",
"t",
"update",
"a",
"cgroup",
"twice",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L170-L221 |
150,447 | 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",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"proc",
"==",
"nil",
"{",
"return",
"grpcStatus",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"defer",
"a",
".",
"sandbox",
".",
"subreaper",
".",
"unlock",
"(",
")",
"\n\n",
"if",
"createContainer",
"{",
"err",
"=",
"ctr",
".",
"container",
".",
"Start",
"(",
"&",
"proc",
".",
"process",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"ctr",
".",
"container",
".",
"Run",
"(",
"&",
"(",
"proc",
".",
"process",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Get process PID",
"pid",
",",
"err",
":=",
"proc",
".",
"process",
".",
"Pid",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"proc",
".",
"exitCodeCh",
"=",
"make",
"(",
"chan",
"int",
",",
"1",
")",
"\n\n",
"// 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",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
150,448 | 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",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"proc",
"==",
"nil",
"{",
"return",
"grpcStatus",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"defer",
"proc",
".",
"closePostStartFDs",
"(",
")",
"\n\n",
"// Setup terminal if enabled.",
"if",
"proc",
".",
"consoleSock",
"!=",
"nil",
"{",
"termMaster",
",",
"err",
":=",
"utils",
".",
"RecvFd",
"(",
"proc",
".",
"consoleSock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"setConsoleCarriageReturn",
"(",
"int",
"(",
"termMaster",
".",
"Fd",
"(",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"proc",
".",
"termMaster",
"=",
"termMaster",
"\n\n",
"// Get process PID",
"pid",
",",
"err",
":=",
"proc",
".",
"process",
".",
"Pid",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"a",
".",
"sandbox",
".",
"subreaper",
".",
"setEpoller",
"(",
"pid",
",",
"proc",
".",
"epoller",
")",
"\n\n",
"if",
"err",
"=",
"proc",
".",
"epoller",
".",
"add",
"(",
"proc",
".",
"termMaster",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctr",
".",
"setProcess",
"(",
"proc",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 |
150,449 | 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",
"config",
".",
"Namespaces",
"{",
"if",
"ns",
".",
"Type",
"==",
"configs",
".",
"NEWIPC",
"{",
"config",
".",
"Namespaces",
"[",
"idx",
"]",
".",
"Path",
"=",
"a",
".",
"sandbox",
".",
"sharedIPCNs",
".",
"path",
"\n",
"ipcNs",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"ns",
".",
"Type",
"==",
"configs",
".",
"NEWUTS",
"{",
"config",
".",
"Namespaces",
"[",
"idx",
"]",
".",
"Path",
"=",
"a",
".",
"sandbox",
".",
"sharedUTSNs",
".",
"path",
"\n",
"utsNs",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"ipcNs",
"{",
"newIPCNs",
":=",
"configs",
".",
"Namespace",
"{",
"Type",
":",
"configs",
".",
"NEWIPC",
",",
"Path",
":",
"a",
".",
"sandbox",
".",
"sharedIPCNs",
".",
"path",
",",
"}",
"\n",
"config",
".",
"Namespaces",
"=",
"append",
"(",
"config",
".",
"Namespaces",
",",
"newIPCNs",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"utsNs",
"{",
"newUTSNs",
":=",
"configs",
".",
"Namespace",
"{",
"Type",
":",
"configs",
".",
"NEWUTS",
",",
"Path",
":",
"a",
".",
"sandbox",
".",
"sharedUTSNs",
".",
"path",
",",
"}",
"\n",
"config",
".",
"Namespaces",
"=",
"append",
"(",
"config",
".",
"Namespaces",
",",
"newUTSNs",
")",
"\n",
"}",
"\n\n",
"// Update PID namespace.",
"var",
"pidNsPath",
"string",
"\n\n",
"// 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",
"\n",
"}",
"else",
"{",
"pidNsPath",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"newPidNs",
":=",
"configs",
".",
"Namespace",
"{",
"Type",
":",
"configs",
".",
"NEWPID",
",",
"Path",
":",
"pidNsPath",
",",
"}",
"\n",
"config",
".",
"Namespaces",
"=",
"append",
"(",
"config",
".",
"Namespaces",
",",
"newPidNs",
")",
"\n",
"}"
] | // 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",
"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",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L489-L538 |
150,450 | 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",
".",
"sandbox",
".",
"deleteContainer",
"(",
"ctr",
".",
"id",
")",
"\n\n",
"if",
"err",
":=",
"removeMounts",
"(",
"ctr",
".",
"mounts",
")",
";",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"container",
"from",
"the",
"agent",
"internal",
"map",
"-",
"Unmount",
"all",
"mounts",
"related",
"to",
"this",
"container"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L563-L573 |
150,451 | 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",
"isNetworkSysctl",
"(",
"key",
")",
"{",
"if",
"err",
":=",
"writeSystemProperty",
"(",
"key",
",",
"value",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"delete",
"(",
"sysctls",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ociSpec",
".",
"Linux",
".",
"Sysctl",
"=",
"sysctls",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"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",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/grpc.go#L730-L743 |
150,452 | 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",
"(",
"\"",
"\"",
",",
"pid",
")",
"\n",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"procFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"procFile",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"file",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
":=",
"scanner",
".",
"Text",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"",
"\"",
")",
"{",
"maskSlice",
":=",
"strings",
".",
"Split",
"(",
"line",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"maskSlice",
")",
"!=",
"2",
"{",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"procFile",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"sigCgtStr",
":=",
"strings",
".",
"TrimSpace",
"(",
"maskSlice",
"[",
"1",
"]",
")",
"\n",
"sigCgtMask",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"sigCgtStr",
",",
"16",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithField",
"(",
"\"",
"\"",
",",
"sigCgtStr",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"(",
"sigCgtMask",
"&",
"sigMask",
")",
"==",
"sigMask",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // 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 |
150,453 | 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",
"}",
"\n\n",
"if",
"len",
"(",
"files",
")",
"!=",
"1",
"{",
"return",
"\"",
"\"",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"files",
")",
"\n",
"}",
"\n\n",
"return",
"files",
"[",
"0",
"]",
".",
"Name",
"(",
")",
",",
"nil",
"\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",
"need",
"to",
"rescan",
"SCSI",
"bus",
"for",
"this",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/device.go#L383-L396 |
150,454 | 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",
":=",
"filepath",
".",
"Join",
"(",
"scsiDiskPrefix",
"+",
"scsiAddr",
",",
"scsiDiskSuffix",
")",
"\n\n",
"checkUevent",
":=",
"func",
"(",
"uEv",
"*",
"uevent",
".",
"Uevent",
")",
"bool",
"{",
"devSubPath",
":=",
"filepath",
".",
"Join",
"(",
"scsiHostChannel",
"+",
"scsiAddr",
",",
"scsiBlockSuffix",
")",
"\n",
"return",
"(",
"uEv",
".",
"Action",
"==",
"\"",
"\"",
"&&",
"strings",
".",
"Contains",
"(",
"uEv",
".",
"DevPath",
",",
"devSubPath",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"waitForDevice",
"(",
"devPath",
",",
"scsiAddr",
",",
"checkUevent",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"scsiDiskName",
",",
"err",
":=",
"findSCSIDisk",
"(",
"devPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"filepath",
".",
"Join",
"(",
"devPrefix",
",",
"scsiDiskName",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
150,455 | 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",
"iface",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNoIF",
"\n",
"}",
"\n\n",
"s",
".",
"network",
".",
"ifacesLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"network",
".",
"ifacesLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"netHandle",
"==",
"nil",
"{",
"netHandle",
",",
"err",
"=",
"netlink",
".",
"NewHandle",
"(",
"unix",
".",
"NETLINK_ROUTE",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"netHandle",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n\n",
"fieldLogger",
":=",
"agentLog",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"iface",
".",
"HwAddr",
",",
"\"",
"\"",
":",
"iface",
".",
"Device",
",",
"\"",
"\"",
":",
"iface",
".",
"PciAddr",
",",
"}",
")",
"\n\n",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"link",
"netlink",
".",
"Link",
"\n",
"if",
"iface",
".",
"HwAddr",
"!=",
"\"",
"\"",
"{",
"fieldLogger",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Find the interface link from its hardware address.",
"link",
",",
"err",
"=",
"linkByHwAddr",
"(",
"netHandle",
",",
"iface",
".",
"HwAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"Internal",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"grpcStatus",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// 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",
")",
"\n",
"}",
"else",
"{",
"resultingIfc",
"=",
"iface",
"\n",
"}",
"\n",
"//put the link back into the up state",
"retErr",
":=",
"netHandle",
".",
"LinkSetUp",
"(",
"link",
")",
"\n\n",
"//if we failed to setup the link but already are returning",
"//with an error, return the original error",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"retErr",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"fieldLogger",
".",
"WithField",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"link",
")",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"lAttrs",
":=",
"link",
".",
"Attrs",
"(",
")",
"\n",
"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",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
"=",
"updateLink",
"(",
"netHandle",
",",
"link",
",",
"iface",
")",
"\n\n",
"return",
"\n\n",
"}"
] | // 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",
"the",
"state",
"of",
"the",
"interface",
"once",
"the",
"function",
"completes",
"as",
"well",
"an",
"any",
"errors",
"observed",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L199-L277 |
150,456 | 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",
"\n",
"}",
"\n\n",
"if",
"link",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNoLink",
"\n",
"}",
"\n\n",
"var",
"ifc",
"types",
".",
"Interface",
"\n",
"linkAttrs",
":=",
"link",
".",
"Attrs",
"(",
")",
"\n",
"ifc",
".",
"Name",
"=",
"linkAttrs",
".",
"Name",
"\n",
"ifc",
".",
"Mtu",
"=",
"uint64",
"(",
"linkAttrs",
".",
"MTU",
")",
"\n",
"ifc",
".",
"HwAddr",
"=",
"linkAttrs",
".",
"HardwareAddr",
".",
"String",
"(",
")",
"\n\n",
"addrs",
",",
"err",
":=",
"netHandle",
".",
"AddrList",
"(",
"link",
",",
"netlink",
".",
"FAMILY_V4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"netMask",
",",
"_",
":=",
"addr",
".",
"Mask",
".",
"Size",
"(",
")",
"\n",
"m",
":=",
"types",
".",
"IPAddress",
"{",
"Address",
":",
"addr",
".",
"IP",
".",
"String",
"(",
")",
",",
"Mask",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"netMask",
")",
",",
"}",
"\n",
"ifc",
".",
"IPAddresses",
"=",
"append",
"(",
"ifc",
".",
"IPAddresses",
",",
"&",
"m",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"ifc",
",",
"nil",
"\n",
"}"
] | // 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 |
150,457 | 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",
"requestedRoutes",
"==",
"nil",
"{",
"return",
"nil",
",",
"errNoRoutes",
"\n",
"}",
"\n\n",
"if",
"netHandle",
"==",
"nil",
"{",
"netHandle",
",",
"err",
"=",
"netlink",
".",
"NewHandle",
"(",
"unix",
".",
"NETLINK_ROUTE",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"netHandle",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n\n",
"//If we are returning an error, return the current routes on the system",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"resultingRoutes",
",",
"_",
"=",
"getCurrentRoutes",
"(",
"netHandle",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"//",
"// 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",
"\n",
"}",
"\n\n",
"//",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"//If there was an error setting the route, return the error",
"//and the current routes on the system via the defer func",
"return",
"\n",
"}",
"\n\n",
"}",
"\n",
"}",
"\n",
"// 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"agentLog",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"//If there was an error setting the route, return the",
"//error and the current routes on the system via defer",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"requestedRoutes",
",",
"err",
"\n",
"}"
] | //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",
"-",
"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"
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L375-L435 |
150,458 | 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",
".",
"NewHandle",
"(",
"unix",
".",
"NETLINK_ROUTE",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"netHandle",
".",
"Delete",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"routes",
"pb",
".",
"Routes",
"\n\n",
"finalRouteList",
",",
"err",
":=",
"netHandle",
".",
"RouteList",
"(",
"nil",
",",
"netlink",
".",
"FAMILY_ALL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"routes",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"route",
":=",
"range",
"finalRouteList",
"{",
"var",
"r",
"types",
".",
"Route",
"\n",
"if",
"route",
".",
"Dst",
"!=",
"nil",
"{",
"r",
".",
"Dest",
"=",
"route",
".",
"Dst",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"route",
".",
"Gw",
"!=",
"nil",
"{",
"r",
".",
"Gateway",
"=",
"route",
".",
"Gw",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"route",
".",
"Src",
"!=",
"nil",
"{",
"r",
".",
"Source",
"=",
"route",
".",
"Src",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"r",
".",
"Scope",
"=",
"uint32",
"(",
"route",
".",
"Scope",
")",
"\n\n",
"link",
",",
"err",
":=",
"netHandle",
".",
"LinkByIndex",
"(",
"route",
".",
"LinkIndex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"routes",
",",
"err",
"\n",
"}",
"\n",
"r",
".",
"Device",
"=",
"link",
".",
"Attrs",
"(",
")",
".",
"Name",
"\n\n",
"routes",
".",
"Routes",
"=",
"append",
"(",
"routes",
".",
"Routes",
",",
"&",
"r",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"routes",
",",
"nil",
"\n",
"}"
] | //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 |
150,459 | 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 nothing to do as the",
"// localhost interface will already exist.",
"if",
"os",
".",
"Getpid",
"(",
")",
"!=",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"lo",
",",
"err",
":=",
"netlink",
".",
"LinkByName",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"netlink",
".",
"LinkSetUp",
"(",
"lo",
")",
"\n",
"}"
] | // Bring up localhost network interface. | [
"Bring",
"up",
"localhost",
"network",
"interface",
"."
] | 629f90f9ff2065509d46192325e6409bdaacef79 | https://github.com/kata-containers/agent/blob/629f90f9ff2065509d46192325e6409bdaacef79/network.go#L605-L621 |
150,460 | 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",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"r",
".",
"wait",
"(",
"exitCodeCh",
",",
"(",
"*",
"reaperOSProcess",
")",
"(",
"c",
".",
"Process",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // 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 |
150,461 | 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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"Stderr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"c",
".",
"Stdout",
"=",
"&",
"b",
"\n",
"c",
".",
"Stderr",
"=",
"&",
"b",
"\n",
"err",
":=",
"r",
".",
"run",
"(",
"c",
")",
"\n",
"return",
"b",
".",
"Bytes",
"(",
")",
",",
"err",
"\n",
"}"
] | // 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 |
150,462 | 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",
"(",
"stmt",
".",
"stmt",
")",
",",
"C",
".",
"OCI_HTYPE_STMT",
")",
"\n\n",
"stmt",
".",
"stmt",
"=",
"nil",
"\n",
"stmt",
".",
"pbind",
"=",
"nil",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the statement | [
"Close",
"closes",
"the",
"statement"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L19-L31 |
150,463 | 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",
")",
",",
"C",
".",
"OCI_ATTR_BIND_COUNT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n\n",
"return",
"int",
"(",
"bindCount",
")",
"\n",
"}"
] | // 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 |
150,464 | 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",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"args",
"{",
"list",
"[",
"i",
"]",
"=",
"namedValue",
"{",
"Ordinal",
":",
"i",
"+",
"1",
",",
"Value",
":",
"v",
",",
"}",
"\n",
"}",
"\n",
"return",
"stmt",
".",
"query",
"(",
"context",
".",
"Background",
"(",
")",
",",
"list",
",",
"false",
")",
"\n",
"}"
] | // Query runs a query | [
"Query",
"runs",
"a",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L310-L319 |
150,465 | 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",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// OCI_ATTR_ROWID returns the ROWID descriptor allocated with OCIDescriptorAlloc()",
"_",
",",
"err",
"=",
"stmt",
".",
"ociAttrGet",
"(",
"*",
"rowidP",
",",
"C",
".",
"OCI_ATTR_ROWID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"rowid",
":=",
"cStringN",
"(",
"\"",
"\"",
",",
"18",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"rowid",
")",
")",
"\n",
"rowidLength",
":=",
"C",
".",
"ub2",
"(",
"18",
")",
"\n",
"result",
":=",
"C",
".",
"OCIRowidToChar",
"(",
"(",
"*",
"C",
".",
"OCIRowid",
")",
"(",
"*",
"rowidP",
")",
",",
"rowid",
",",
"&",
"rowidLength",
",",
"stmt",
".",
"conn",
".",
"errHandle",
")",
"\n",
"err",
"=",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"cGoStringN",
"(",
"rowid",
",",
"int",
"(",
"rowidLength",
")",
")",
",",
"nil",
"\n",
"}"
] | // getRowid returns the rowid | [
"getRowid",
"returns",
"the",
"rowid"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L579-L601 |
150,466 | 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 processed by the most recent statement. The default value is 1.",
"\n",
"_",
",",
"err",
":=",
"stmt",
".",
"ociAttrGet",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"rowCount",
")",
",",
"C",
".",
"OCI_ATTR_ROW_COUNT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"rowCount",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
150,467 | 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",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"args",
"{",
"list",
"[",
"i",
"]",
"=",
"namedValue",
"{",
"Ordinal",
":",
"i",
"+",
"1",
",",
"Value",
":",
"v",
",",
"}",
"\n",
"}",
"\n",
"return",
"stmt",
".",
"exec",
"(",
"context",
".",
"Background",
"(",
")",
",",
"list",
")",
"\n",
"}"
] | // Exec runs an exec query | [
"Exec",
"runs",
"an",
"exec",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L614-L623 |
150,468 | 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",
",",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"defer",
"freeBinds",
"(",
"binds",
")",
"\n\n",
"mode",
":=",
"C",
".",
"ub4",
"(",
"C",
".",
"OCI_DEFAULT",
")",
"\n",
"if",
"stmt",
".",
"conn",
".",
"inTransaction",
"==",
"false",
"{",
"mode",
"=",
"mode",
"|",
"C",
".",
"OCI_COMMIT_ON_SUCCESS",
"\n",
"}",
"\n\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"stmt",
".",
"ociBreak",
"(",
"ctx",
",",
"done",
")",
"\n",
"err",
"=",
"stmt",
".",
"ociStmtExecute",
"(",
"1",
",",
"mode",
")",
"\n",
"close",
"(",
"done",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"ErrOCISuccessWithInfo",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"result",
":=",
"OCI8Result",
"{",
"stmt",
":",
"stmt",
"}",
"\n\n",
"result",
".",
"rowsAffected",
",",
"result",
".",
"rowsAffectedErr",
"=",
"stmt",
".",
"rowsAffected",
"(",
")",
"\n",
"if",
"result",
".",
"rowsAffectedErr",
"!=",
"nil",
"||",
"result",
".",
"rowsAffected",
"<",
"1",
"{",
"result",
".",
"rowidErr",
"=",
"ErrNoRowid",
"\n",
"}",
"else",
"{",
"result",
".",
"rowid",
",",
"result",
".",
"rowidErr",
"=",
"stmt",
".",
"getRowid",
"(",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"stmt",
".",
"outputBoundParameters",
"(",
"binds",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"result",
",",
"nil",
"\n",
"}"
] | // exec runs an exec query | [
"exec",
"runs",
"an",
"exec",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L626-L662 |
150,469 | 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",
"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.",
")",
"\n\n",
"err",
":=",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"*",
"param",
",",
"nil",
"\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 |
150,470 | 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",
"(",
"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",
")",
"\n\n",
"return",
"size",
",",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // 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 |
150,471 | 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",
".",
"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.",
")",
"\n\n",
"return",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // 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 |
150,472 | 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",
".",
"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.",
")",
"\n\n",
"return",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // 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 |
150,473 | mattn/go-oci8 | statement.go | ociStmtExecute | func (stmt *OCI8Stmt) ociStmtExecute(iters C.ub4, mode C.ub4) error {
result := C.OCIStmtExecute(
stmt.conn.svc, // Service context handle
stmt.stmt, // A statement handle
stmt.conn.errHandle, // An error handle
iters, // For non-SELECT statements, the number of times this statement is executed equals iters - rowoff. For SELECT statements, if iters is nonzero, then defines must have been done for the statement handle.
0, // The starting index from which the data in an array bind is relevant for this multiple row execution
nil, // This parameter is optional. If it is supplied, it must point to a snapshot descriptor of type OCI_DTYPE_SNAP
nil, // This parameter is optional. If it is supplied, it must point to a descriptor of type OCI_DTYPE_SNAP.
mode, // The mode: https://docs.oracle.com/cd/E11882_01/appdev.112/e10646/oci17msc001.htm#LNOCI17163
)
return stmt.conn.getError(result)
} | go | func (stmt *OCI8Stmt) ociStmtExecute(iters C.ub4, mode C.ub4) error {
result := C.OCIStmtExecute(
stmt.conn.svc, // Service context handle
stmt.stmt, // A statement handle
stmt.conn.errHandle, // An error handle
iters, // For non-SELECT statements, the number of times this statement is executed equals iters - rowoff. For SELECT statements, if iters is nonzero, then defines must have been done for the statement handle.
0, // The starting index from which the data in an array bind is relevant for this multiple row execution
nil, // This parameter is optional. If it is supplied, it must point to a snapshot descriptor of type OCI_DTYPE_SNAP
nil, // This parameter is optional. If it is supplied, it must point to a descriptor of type OCI_DTYPE_SNAP.
mode, // The mode: https://docs.oracle.com/cd/E11882_01/appdev.112/e10646/oci17msc001.htm#LNOCI17163
)
return stmt.conn.getError(result)
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociStmtExecute",
"(",
"iters",
"C",
".",
"ub4",
",",
"mode",
"C",
".",
"ub4",
")",
"error",
"{",
"result",
":=",
"C",
".",
"OCIStmtExecute",
"(",
"stmt",
".",
"conn",
".",
"svc",
",",
"// Service context handle",
"stmt",
".",
"stmt",
",",
"// A statement handle",
"stmt",
".",
"conn",
".",
"errHandle",
",",
"// An error handle",
"iters",
",",
"// For non-SELECT statements, the number of times this statement is executed equals iters - rowoff. For SELECT statements, if iters is nonzero, then defines must have been done for the statement handle.",
"0",
",",
"// The starting index from which the data in an array bind is relevant for this multiple row execution",
"nil",
",",
"// This parameter is optional. If it is supplied, it must point to a snapshot descriptor of type OCI_DTYPE_SNAP",
"nil",
",",
"// This parameter is optional. If it is supplied, it must point to a descriptor of type OCI_DTYPE_SNAP.",
"mode",
",",
"// The mode: https://docs.oracle.com/cd/E11882_01/appdev.112/e10646/oci17msc001.htm#LNOCI17163",
")",
"\n\n",
"return",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // ociStmtExecute calls OCIStmtExecute | [
"ociStmtExecute",
"calls",
"OCIStmtExecute"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L898-L911 |
150,474 | mattn/go-oci8 | statement.go | ociBreak | func (stmt *OCI8Stmt) ociBreak(ctx context.Context, done chan struct{}) {
select {
case <-done:
case <-ctx.Done():
// select again to avoid race condition if both are done
select {
case <-done:
default:
result := C.OCIBreak(
unsafe.Pointer(stmt.conn.svc), // The service context handle or the server context handle.
stmt.conn.errHandle, // An error handle
)
err := stmt.conn.getError(result)
if err != nil {
stmt.conn.logger.Print("OCIBreak error: ", err)
}
}
}
} | go | func (stmt *OCI8Stmt) ociBreak(ctx context.Context, done chan struct{}) {
select {
case <-done:
case <-ctx.Done():
// select again to avoid race condition if both are done
select {
case <-done:
default:
result := C.OCIBreak(
unsafe.Pointer(stmt.conn.svc), // The service context handle or the server context handle.
stmt.conn.errHandle, // An error handle
)
err := stmt.conn.getError(result)
if err != nil {
stmt.conn.logger.Print("OCIBreak error: ", err)
}
}
}
} | [
"func",
"(",
"stmt",
"*",
"OCI8Stmt",
")",
"ociBreak",
"(",
"ctx",
"context",
".",
"Context",
",",
"done",
"chan",
"struct",
"{",
"}",
")",
"{",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"// select again to avoid race condition if both are done",
"select",
"{",
"case",
"<-",
"done",
":",
"default",
":",
"result",
":=",
"C",
".",
"OCIBreak",
"(",
"unsafe",
".",
"Pointer",
"(",
"stmt",
".",
"conn",
".",
"svc",
")",
",",
"// The service context handle or the server context handle.",
"stmt",
".",
"conn",
".",
"errHandle",
",",
"// An error handle",
")",
"\n",
"err",
":=",
"stmt",
".",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"stmt",
".",
"conn",
".",
"logger",
".",
"Print",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ociBreak calls OCIBreak if ctx.Done is finished before done chan is closed | [
"ociBreak",
"calls",
"OCIBreak",
"if",
"ctx",
".",
"Done",
"is",
"finished",
"before",
"done",
"chan",
"is",
"closed"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/statement.go#L914-L932 |
150,475 | mattn/go-oci8 | connection.go | Exec | func (conn *OCI8Conn) Exec(query string, args []driver.Value) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return conn.exec(context.Background(), query, list)
} | go | func (conn *OCI8Conn) Exec(query string, args []driver.Value) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return conn.exec(context.Background(), query, list)
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"Exec",
"(",
"query",
"string",
",",
"args",
"[",
"]",
"driver",
".",
"Value",
")",
"(",
"driver",
".",
"Result",
",",
"error",
")",
"{",
"list",
":=",
"make",
"(",
"[",
"]",
"namedValue",
",",
"len",
"(",
"args",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"args",
"{",
"list",
"[",
"i",
"]",
"=",
"namedValue",
"{",
"Ordinal",
":",
"i",
"+",
"1",
",",
"Value",
":",
"v",
",",
"}",
"\n",
"}",
"\n",
"return",
"conn",
".",
"exec",
"(",
"context",
".",
"Background",
"(",
")",
",",
"query",
",",
"list",
")",
"\n",
"}"
] | // Exec executes a query | [
"Exec",
"executes",
"a",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L16-L25 |
150,476 | mattn/go-oci8 | connection.go | Ping | func (conn *OCI8Conn) Ping(ctx context.Context) error {
result := C.OCIPing(conn.svc, conn.errHandle, C.OCI_DEFAULT)
if result == C.OCI_SUCCESS || result == C.OCI_SUCCESS_WITH_INFO {
return nil
}
errorCode, err := conn.ociGetError()
if errorCode == 1010 {
// Older versions of Oracle do not support ping,
// but a response of "ORA-01010: invalid OCI operation" confirms connectivity.
// See https://github.com/rana/ora/issues/224
return nil
}
conn.logger.Print("Ping error: ", err)
return driver.ErrBadConn
} | go | func (conn *OCI8Conn) Ping(ctx context.Context) error {
result := C.OCIPing(conn.svc, conn.errHandle, C.OCI_DEFAULT)
if result == C.OCI_SUCCESS || result == C.OCI_SUCCESS_WITH_INFO {
return nil
}
errorCode, err := conn.ociGetError()
if errorCode == 1010 {
// Older versions of Oracle do not support ping,
// but a response of "ORA-01010: invalid OCI operation" confirms connectivity.
// See https://github.com/rana/ora/issues/224
return nil
}
conn.logger.Print("Ping error: ", err)
return driver.ErrBadConn
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"Ping",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"result",
":=",
"C",
".",
"OCIPing",
"(",
"conn",
".",
"svc",
",",
"conn",
".",
"errHandle",
",",
"C",
".",
"OCI_DEFAULT",
")",
"\n",
"if",
"result",
"==",
"C",
".",
"OCI_SUCCESS",
"||",
"result",
"==",
"C",
".",
"OCI_SUCCESS_WITH_INFO",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"errorCode",
",",
"err",
":=",
"conn",
".",
"ociGetError",
"(",
")",
"\n",
"if",
"errorCode",
"==",
"1010",
"{",
"// Older versions of Oracle do not support ping,",
"// but a response of \"ORA-01010: invalid OCI operation\" confirms connectivity.",
"// See https://github.com/rana/ora/issues/224",
"return",
"nil",
"\n",
"}",
"\n\n",
"conn",
".",
"logger",
".",
"Print",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"driver",
".",
"ErrBadConn",
"\n",
"}"
] | // Ping database connection | [
"Ping",
"database",
"connection"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L54-L69 |
150,477 | mattn/go-oci8 | connection.go | Begin | func (conn *OCI8Conn) Begin() (driver.Tx, error) {
return conn.BeginTx(context.Background(), driver.TxOptions{})
} | go | func (conn *OCI8Conn) Begin() (driver.Tx, error) {
return conn.BeginTx(context.Background(), driver.TxOptions{})
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"Begin",
"(",
")",
"(",
"driver",
".",
"Tx",
",",
"error",
")",
"{",
"return",
"conn",
".",
"BeginTx",
"(",
"context",
".",
"Background",
"(",
")",
",",
"driver",
".",
"TxOptions",
"{",
"}",
")",
"\n",
"}"
] | // Begin starts a transaction | [
"Begin",
"starts",
"a",
"transaction"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L72-L74 |
150,478 | mattn/go-oci8 | connection.go | BeginTx | func (conn *OCI8Conn) BeginTx(ctx context.Context, txOptions driver.TxOptions) (driver.Tx, error) {
if conn.transactionMode != C.OCI_TRANS_READWRITE {
// transaction handle
trans, _, err := conn.ociHandleAlloc(C.OCI_HTYPE_TRANS, 0)
if err != nil {
return nil, fmt.Errorf("allocate transaction handle error: %v", err)
}
// sets the transaction context attribute of the service context
err = conn.ociAttrSet(unsafe.Pointer(conn.svc), C.OCI_HTYPE_SVCCTX, *trans, 0, C.OCI_ATTR_TRANS)
if err != nil {
C.OCIHandleFree(*trans, C.OCI_HTYPE_TRANS)
return nil, err
}
// transaction handle should be freed by something once attached to the service context
// but I cannot find anything in the documentation explicitly calling this out
// going by examples: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci17msc006.htm#i428845
if rv := C.OCITransStart(
conn.svc,
conn.errHandle,
0,
conn.transactionMode, // mode is: C.OCI_TRANS_SERIALIZABLE, C.OCI_TRANS_READWRITE, or C.OCI_TRANS_READONLY
); rv != C.OCI_SUCCESS {
return nil, conn.getError(rv)
}
}
conn.inTransaction = true
return &OCI8Tx{conn}, nil
} | go | func (conn *OCI8Conn) BeginTx(ctx context.Context, txOptions driver.TxOptions) (driver.Tx, error) {
if conn.transactionMode != C.OCI_TRANS_READWRITE {
// transaction handle
trans, _, err := conn.ociHandleAlloc(C.OCI_HTYPE_TRANS, 0)
if err != nil {
return nil, fmt.Errorf("allocate transaction handle error: %v", err)
}
// sets the transaction context attribute of the service context
err = conn.ociAttrSet(unsafe.Pointer(conn.svc), C.OCI_HTYPE_SVCCTX, *trans, 0, C.OCI_ATTR_TRANS)
if err != nil {
C.OCIHandleFree(*trans, C.OCI_HTYPE_TRANS)
return nil, err
}
// transaction handle should be freed by something once attached to the service context
// but I cannot find anything in the documentation explicitly calling this out
// going by examples: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci17msc006.htm#i428845
if rv := C.OCITransStart(
conn.svc,
conn.errHandle,
0,
conn.transactionMode, // mode is: C.OCI_TRANS_SERIALIZABLE, C.OCI_TRANS_READWRITE, or C.OCI_TRANS_READONLY
); rv != C.OCI_SUCCESS {
return nil, conn.getError(rv)
}
}
conn.inTransaction = true
return &OCI8Tx{conn}, nil
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"BeginTx",
"(",
"ctx",
"context",
".",
"Context",
",",
"txOptions",
"driver",
".",
"TxOptions",
")",
"(",
"driver",
".",
"Tx",
",",
"error",
")",
"{",
"if",
"conn",
".",
"transactionMode",
"!=",
"C",
".",
"OCI_TRANS_READWRITE",
"{",
"// transaction handle",
"trans",
",",
"_",
",",
"err",
":=",
"conn",
".",
"ociHandleAlloc",
"(",
"C",
".",
"OCI_HTYPE_TRANS",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// sets the transaction context attribute of the service context",
"err",
"=",
"conn",
".",
"ociAttrSet",
"(",
"unsafe",
".",
"Pointer",
"(",
"conn",
".",
"svc",
")",
",",
"C",
".",
"OCI_HTYPE_SVCCTX",
",",
"*",
"trans",
",",
"0",
",",
"C",
".",
"OCI_ATTR_TRANS",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"C",
".",
"OCIHandleFree",
"(",
"*",
"trans",
",",
"C",
".",
"OCI_HTYPE_TRANS",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// transaction handle should be freed by something once attached to the service context",
"// but I cannot find anything in the documentation explicitly calling this out",
"// going by examples: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci17msc006.htm#i428845",
"if",
"rv",
":=",
"C",
".",
"OCITransStart",
"(",
"conn",
".",
"svc",
",",
"conn",
".",
"errHandle",
",",
"0",
",",
"conn",
".",
"transactionMode",
",",
"// mode is: C.OCI_TRANS_SERIALIZABLE, C.OCI_TRANS_READWRITE, or C.OCI_TRANS_READONLY",
")",
";",
"rv",
"!=",
"C",
".",
"OCI_SUCCESS",
"{",
"return",
"nil",
",",
"conn",
".",
"getError",
"(",
"rv",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"conn",
".",
"inTransaction",
"=",
"true",
"\n\n",
"return",
"&",
"OCI8Tx",
"{",
"conn",
"}",
",",
"nil",
"\n",
"}"
] | // BeginTx starts a transaction | [
"BeginTx",
"starts",
"a",
"transaction"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L77-L110 |
150,479 | mattn/go-oci8 | connection.go | Prepare | func (conn *OCI8Conn) Prepare(query string) (driver.Stmt, error) {
return conn.PrepareContext(context.Background(), query)
} | go | func (conn *OCI8Conn) Prepare(query string) (driver.Stmt, error) {
return conn.PrepareContext(context.Background(), query)
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"Prepare",
"(",
"query",
"string",
")",
"(",
"driver",
".",
"Stmt",
",",
"error",
")",
"{",
"return",
"conn",
".",
"PrepareContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"query",
")",
"\n",
"}"
] | // Prepare prepares a query | [
"Prepare",
"prepares",
"a",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L160-L162 |
150,480 | mattn/go-oci8 | connection.go | PrepareContext | func (conn *OCI8Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if conn.enableQMPlaceholders {
query = placeholders(query)
}
queryP := cString(query)
defer C.free(unsafe.Pointer(queryP))
// statement handle
stmt, _, err := conn.ociHandleAlloc(C.OCI_HTYPE_STMT, 0)
if err != nil {
return nil, fmt.Errorf("allocate statement handle error: %v", err)
}
if rv := C.OCIStmtPrepare(
(*C.OCIStmt)(*stmt),
conn.errHandle,
queryP,
C.ub4(len(query)),
C.ub4(C.OCI_NTV_SYNTAX),
C.ub4(C.OCI_DEFAULT),
); rv != C.OCI_SUCCESS {
C.OCIHandleFree(*stmt, C.OCI_HTYPE_STMT)
return nil, conn.getError(rv)
}
return &OCI8Stmt{conn: conn, stmt: (*C.OCIStmt)(*stmt)}, nil
} | go | func (conn *OCI8Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if conn.enableQMPlaceholders {
query = placeholders(query)
}
queryP := cString(query)
defer C.free(unsafe.Pointer(queryP))
// statement handle
stmt, _, err := conn.ociHandleAlloc(C.OCI_HTYPE_STMT, 0)
if err != nil {
return nil, fmt.Errorf("allocate statement handle error: %v", err)
}
if rv := C.OCIStmtPrepare(
(*C.OCIStmt)(*stmt),
conn.errHandle,
queryP,
C.ub4(len(query)),
C.ub4(C.OCI_NTV_SYNTAX),
C.ub4(C.OCI_DEFAULT),
); rv != C.OCI_SUCCESS {
C.OCIHandleFree(*stmt, C.OCI_HTYPE_STMT)
return nil, conn.getError(rv)
}
return &OCI8Stmt{conn: conn, stmt: (*C.OCIStmt)(*stmt)}, nil
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"PrepareContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"query",
"string",
")",
"(",
"driver",
".",
"Stmt",
",",
"error",
")",
"{",
"if",
"conn",
".",
"enableQMPlaceholders",
"{",
"query",
"=",
"placeholders",
"(",
"query",
")",
"\n",
"}",
"\n\n",
"queryP",
":=",
"cString",
"(",
"query",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"queryP",
")",
")",
"\n\n",
"// statement handle",
"stmt",
",",
"_",
",",
"err",
":=",
"conn",
".",
"ociHandleAlloc",
"(",
"C",
".",
"OCI_HTYPE_STMT",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"rv",
":=",
"C",
".",
"OCIStmtPrepare",
"(",
"(",
"*",
"C",
".",
"OCIStmt",
")",
"(",
"*",
"stmt",
")",
",",
"conn",
".",
"errHandle",
",",
"queryP",
",",
"C",
".",
"ub4",
"(",
"len",
"(",
"query",
")",
")",
",",
"C",
".",
"ub4",
"(",
"C",
".",
"OCI_NTV_SYNTAX",
")",
",",
"C",
".",
"ub4",
"(",
"C",
".",
"OCI_DEFAULT",
")",
",",
")",
";",
"rv",
"!=",
"C",
".",
"OCI_SUCCESS",
"{",
"C",
".",
"OCIHandleFree",
"(",
"*",
"stmt",
",",
"C",
".",
"OCI_HTYPE_STMT",
")",
"\n",
"return",
"nil",
",",
"conn",
".",
"getError",
"(",
"rv",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"OCI8Stmt",
"{",
"conn",
":",
"conn",
",",
"stmt",
":",
"(",
"*",
"C",
".",
"OCIStmt",
")",
"(",
"*",
"stmt",
")",
"}",
",",
"nil",
"\n",
"}"
] | // PrepareContext prepares a query | [
"PrepareContext",
"prepares",
"a",
"query"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L165-L192 |
150,481 | mattn/go-oci8 | connection.go | ociGetError | func (conn *OCI8Conn) ociGetError() (int, error) {
var errorCode C.sb4
errorText := make([]byte, 1024)
result := C.OCIErrorGet(
unsafe.Pointer(conn.errHandle), // error handle
1, // status record number, starts from 1
nil, // sqlstate, not supported in release 8.x or later
&errorCode, // error code
(*C.OraText)(&errorText[0]), // error message text
1024, // size of the buffer provided in number of bytes
C.OCI_HTYPE_ERROR, // type of the handle (OCI_HTYPE_ERR or OCI_HTYPE_ENV)
)
if result != C.OCI_SUCCESS {
return 3114, errors.New("OCIErrorGet failed")
}
index := bytes.IndexByte(errorText, 0)
return int(errorCode), errors.New(string(errorText[:index]))
} | go | func (conn *OCI8Conn) ociGetError() (int, error) {
var errorCode C.sb4
errorText := make([]byte, 1024)
result := C.OCIErrorGet(
unsafe.Pointer(conn.errHandle), // error handle
1, // status record number, starts from 1
nil, // sqlstate, not supported in release 8.x or later
&errorCode, // error code
(*C.OraText)(&errorText[0]), // error message text
1024, // size of the buffer provided in number of bytes
C.OCI_HTYPE_ERROR, // type of the handle (OCI_HTYPE_ERR or OCI_HTYPE_ENV)
)
if result != C.OCI_SUCCESS {
return 3114, errors.New("OCIErrorGet failed")
}
index := bytes.IndexByte(errorText, 0)
return int(errorCode), errors.New(string(errorText[:index]))
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociGetError",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"errorCode",
"C",
".",
"sb4",
"\n",
"errorText",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1024",
")",
"\n\n",
"result",
":=",
"C",
".",
"OCIErrorGet",
"(",
"unsafe",
".",
"Pointer",
"(",
"conn",
".",
"errHandle",
")",
",",
"// error handle",
"1",
",",
"// status record number, starts from 1",
"nil",
",",
"// sqlstate, not supported in release 8.x or later",
"&",
"errorCode",
",",
"// error code",
"(",
"*",
"C",
".",
"OraText",
")",
"(",
"&",
"errorText",
"[",
"0",
"]",
")",
",",
"// error message text",
"1024",
",",
"// size of the buffer provided in number of bytes",
"C",
".",
"OCI_HTYPE_ERROR",
",",
"// type of the handle (OCI_HTYPE_ERR or OCI_HTYPE_ENV)",
")",
"\n",
"if",
"result",
"!=",
"C",
".",
"OCI_SUCCESS",
"{",
"return",
"3114",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"index",
":=",
"bytes",
".",
"IndexByte",
"(",
"errorText",
",",
"0",
")",
"\n\n",
"return",
"int",
"(",
"errorCode",
")",
",",
"errors",
".",
"New",
"(",
"string",
"(",
"errorText",
"[",
":",
"index",
"]",
")",
")",
"\n",
"}"
] | // ociGetError calls OCIErrorGet then returs error code and text | [
"ociGetError",
"calls",
"OCIErrorGet",
"then",
"returs",
"error",
"code",
"and",
"text"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L236-L256 |
150,482 | mattn/go-oci8 | connection.go | ociAttrGet | func (conn *OCI8Conn) ociAttrGet(paramHandle *C.OCIParam, value unsafe.Pointer, attributeType C.ub4) (C.ub4, error) {
var size C.ub4
result := C.OCIAttrGet(
unsafe.Pointer(paramHandle), // Pointer to a handle type
C.OCI_DTYPE_PARAM, // The handle type: OCI_DTYPE_PARAM, for a parameter descriptor
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
conn.errHandle, // An error handle
)
return size, conn.getError(result)
} | go | func (conn *OCI8Conn) ociAttrGet(paramHandle *C.OCIParam, value unsafe.Pointer, attributeType C.ub4) (C.ub4, error) {
var size C.ub4
result := C.OCIAttrGet(
unsafe.Pointer(paramHandle), // Pointer to a handle type
C.OCI_DTYPE_PARAM, // The handle type: OCI_DTYPE_PARAM, for a parameter descriptor
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
conn.errHandle, // An error handle
)
return size, conn.getError(result)
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociAttrGet",
"(",
"paramHandle",
"*",
"C",
".",
"OCIParam",
",",
"value",
"unsafe",
".",
"Pointer",
",",
"attributeType",
"C",
".",
"ub4",
")",
"(",
"C",
".",
"ub4",
",",
"error",
")",
"{",
"var",
"size",
"C",
".",
"ub4",
"\n\n",
"result",
":=",
"C",
".",
"OCIAttrGet",
"(",
"unsafe",
".",
"Pointer",
"(",
"paramHandle",
")",
",",
"// Pointer to a handle type",
"C",
".",
"OCI_DTYPE_PARAM",
",",
"// The handle type: OCI_DTYPE_PARAM, for a parameter descriptor",
"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",
"conn",
".",
"errHandle",
",",
"// An error handle",
")",
"\n\n",
"return",
"size",
",",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // ociAttrGet calls OCIAttrGet with OCIParam then returns attribute size and error.
// The attribute value is stored into passed value. | [
"ociAttrGet",
"calls",
"OCIAttrGet",
"with",
"OCIParam",
"then",
"returns",
"attribute",
"size",
"and",
"error",
".",
"The",
"attribute",
"value",
"is",
"stored",
"into",
"passed",
"value",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L260-L273 |
150,483 | mattn/go-oci8 | connection.go | ociAttrSet | func (conn *OCI8Conn) ociAttrSet(
handle unsafe.Pointer,
handleType C.ub4,
value unsafe.Pointer,
valueSize C.ub4,
attributeType C.ub4,
) error {
result := C.OCIAttrSet(
handle, // Pointer to a handle whose attribute gets modified
handleType, // The handle type
value, // Pointer to an attribute value
valueSize, // The size of an attribute value
attributeType, // The type of attribute being set
conn.errHandle, // An error handle
)
return conn.getError(result)
} | go | func (conn *OCI8Conn) ociAttrSet(
handle unsafe.Pointer,
handleType C.ub4,
value unsafe.Pointer,
valueSize C.ub4,
attributeType C.ub4,
) error {
result := C.OCIAttrSet(
handle, // Pointer to a handle whose attribute gets modified
handleType, // The handle type
value, // Pointer to an attribute value
valueSize, // The size of an attribute value
attributeType, // The type of attribute being set
conn.errHandle, // An error handle
)
return conn.getError(result)
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociAttrSet",
"(",
"handle",
"unsafe",
".",
"Pointer",
",",
"handleType",
"C",
".",
"ub4",
",",
"value",
"unsafe",
".",
"Pointer",
",",
"valueSize",
"C",
".",
"ub4",
",",
"attributeType",
"C",
".",
"ub4",
",",
")",
"error",
"{",
"result",
":=",
"C",
".",
"OCIAttrSet",
"(",
"handle",
",",
"// Pointer to a handle whose attribute gets modified",
"handleType",
",",
"// The handle type",
"value",
",",
"// Pointer to an attribute value",
"valueSize",
",",
"// The size of an attribute value",
"attributeType",
",",
"// The type of attribute being set",
"conn",
".",
"errHandle",
",",
"// An error handle",
")",
"\n\n",
"return",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // ociAttrSet calls OCIAttrSet.
// Only uses errHandle from conn, so can be called in conn setup after errHandle has been set. | [
"ociAttrSet",
"calls",
"OCIAttrSet",
".",
"Only",
"uses",
"errHandle",
"from",
"conn",
"so",
"can",
"be",
"called",
"in",
"conn",
"setup",
"after",
"errHandle",
"has",
"been",
"set",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L277-L294 |
150,484 | mattn/go-oci8 | connection.go | ociHandleAlloc | func (conn *OCI8Conn) ociHandleAlloc(handleType C.ub4, size C.size_t) (*unsafe.Pointer, *unsafe.Pointer, error) {
var handleTemp unsafe.Pointer
handle := &handleTemp
var bufferTemp unsafe.Pointer
var buffer *unsafe.Pointer
if size > 0 {
buffer = &bufferTemp
}
result := C.OCIHandleAlloc(
unsafe.Pointer(conn.env), // An environment handle
handle, // Returns a handle
handleType, // type of handle: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci02bas.htm#LNOCI87581
size, // amount of user memory to be allocated
buffer, // Returns a pointer to the user memory
)
err := conn.getError(result)
if err != nil {
return nil, nil, err
}
if size > 0 {
return handle, buffer, nil
}
return handle, nil, nil
} | go | func (conn *OCI8Conn) ociHandleAlloc(handleType C.ub4, size C.size_t) (*unsafe.Pointer, *unsafe.Pointer, error) {
var handleTemp unsafe.Pointer
handle := &handleTemp
var bufferTemp unsafe.Pointer
var buffer *unsafe.Pointer
if size > 0 {
buffer = &bufferTemp
}
result := C.OCIHandleAlloc(
unsafe.Pointer(conn.env), // An environment handle
handle, // Returns a handle
handleType, // type of handle: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci02bas.htm#LNOCI87581
size, // amount of user memory to be allocated
buffer, // Returns a pointer to the user memory
)
err := conn.getError(result)
if err != nil {
return nil, nil, err
}
if size > 0 {
return handle, buffer, nil
}
return handle, nil, nil
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociHandleAlloc",
"(",
"handleType",
"C",
".",
"ub4",
",",
"size",
"C",
".",
"size_t",
")",
"(",
"*",
"unsafe",
".",
"Pointer",
",",
"*",
"unsafe",
".",
"Pointer",
",",
"error",
")",
"{",
"var",
"handleTemp",
"unsafe",
".",
"Pointer",
"\n",
"handle",
":=",
"&",
"handleTemp",
"\n",
"var",
"bufferTemp",
"unsafe",
".",
"Pointer",
"\n",
"var",
"buffer",
"*",
"unsafe",
".",
"Pointer",
"\n",
"if",
"size",
">",
"0",
"{",
"buffer",
"=",
"&",
"bufferTemp",
"\n",
"}",
"\n\n",
"result",
":=",
"C",
".",
"OCIHandleAlloc",
"(",
"unsafe",
".",
"Pointer",
"(",
"conn",
".",
"env",
")",
",",
"// An environment handle",
"handle",
",",
"// Returns a handle",
"handleType",
",",
"// type of handle: https://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci02bas.htm#LNOCI87581",
"size",
",",
"// amount of user memory to be allocated",
"buffer",
",",
"// Returns a pointer to the user memory",
")",
"\n\n",
"err",
":=",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"size",
">",
"0",
"{",
"return",
"handle",
",",
"buffer",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"handle",
",",
"nil",
",",
"nil",
"\n",
"}"
] | // ociHandleAlloc calls OCIHandleAlloc then returns
// handle pointer to pointer, buffer pointer to pointer, and error | [
"ociHandleAlloc",
"calls",
"OCIHandleAlloc",
"then",
"returns",
"handle",
"pointer",
"to",
"pointer",
"buffer",
"pointer",
"to",
"pointer",
"and",
"error"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L298-L325 |
150,485 | mattn/go-oci8 | connection.go | ociDescriptorAlloc | func (conn *OCI8Conn) ociDescriptorAlloc(descriptorType C.ub4, size C.size_t) (*unsafe.Pointer, *unsafe.Pointer, error) {
var descriptorTemp unsafe.Pointer
descriptor := &descriptorTemp
var bufferTemp unsafe.Pointer
var buffer *unsafe.Pointer
if size > 0 {
buffer = &bufferTemp
}
result := C.OCIDescriptorAlloc(
unsafe.Pointer(conn.env), // An environment handle
descriptor, // Returns a descriptor or LOB locator of desired type
descriptorType, // Specifies the type of descriptor or LOB locator to be allocated
size, // Specifies an amount of user memory to be allocated for use by the application for the lifetime of the descriptor
buffer, // Returns a pointer to the user memory of size xtramem_sz allocated by the call for the user for the lifetime of the descriptor
)
err := conn.getError(result)
if err != nil {
return nil, nil, err
}
if size > 0 {
return descriptor, buffer, nil
}
return descriptor, nil, nil
} | go | func (conn *OCI8Conn) ociDescriptorAlloc(descriptorType C.ub4, size C.size_t) (*unsafe.Pointer, *unsafe.Pointer, error) {
var descriptorTemp unsafe.Pointer
descriptor := &descriptorTemp
var bufferTemp unsafe.Pointer
var buffer *unsafe.Pointer
if size > 0 {
buffer = &bufferTemp
}
result := C.OCIDescriptorAlloc(
unsafe.Pointer(conn.env), // An environment handle
descriptor, // Returns a descriptor or LOB locator of desired type
descriptorType, // Specifies the type of descriptor or LOB locator to be allocated
size, // Specifies an amount of user memory to be allocated for use by the application for the lifetime of the descriptor
buffer, // Returns a pointer to the user memory of size xtramem_sz allocated by the call for the user for the lifetime of the descriptor
)
err := conn.getError(result)
if err != nil {
return nil, nil, err
}
if size > 0 {
return descriptor, buffer, nil
}
return descriptor, nil, nil
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociDescriptorAlloc",
"(",
"descriptorType",
"C",
".",
"ub4",
",",
"size",
"C",
".",
"size_t",
")",
"(",
"*",
"unsafe",
".",
"Pointer",
",",
"*",
"unsafe",
".",
"Pointer",
",",
"error",
")",
"{",
"var",
"descriptorTemp",
"unsafe",
".",
"Pointer",
"\n",
"descriptor",
":=",
"&",
"descriptorTemp",
"\n",
"var",
"bufferTemp",
"unsafe",
".",
"Pointer",
"\n",
"var",
"buffer",
"*",
"unsafe",
".",
"Pointer",
"\n",
"if",
"size",
">",
"0",
"{",
"buffer",
"=",
"&",
"bufferTemp",
"\n",
"}",
"\n\n",
"result",
":=",
"C",
".",
"OCIDescriptorAlloc",
"(",
"unsafe",
".",
"Pointer",
"(",
"conn",
".",
"env",
")",
",",
"// An environment handle",
"descriptor",
",",
"// Returns a descriptor or LOB locator of desired type",
"descriptorType",
",",
"// Specifies the type of descriptor or LOB locator to be allocated",
"size",
",",
"// Specifies an amount of user memory to be allocated for use by the application for the lifetime of the descriptor",
"buffer",
",",
"// Returns a pointer to the user memory of size xtramem_sz allocated by the call for the user for the lifetime of the descriptor",
")",
"\n\n",
"err",
":=",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"size",
">",
"0",
"{",
"return",
"descriptor",
",",
"buffer",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"descriptor",
",",
"nil",
",",
"nil",
"\n",
"}"
] | // ociDescriptorAlloc calls OCIDescriptorAlloc then returns
// descriptor pointer to pointer, buffer pointer to pointer, and error | [
"ociDescriptorAlloc",
"calls",
"OCIDescriptorAlloc",
"then",
"returns",
"descriptor",
"pointer",
"to",
"pointer",
"buffer",
"pointer",
"to",
"pointer",
"and",
"error"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L329-L356 |
150,486 | mattn/go-oci8 | connection.go | ociLobRead | func (conn *OCI8Conn) ociLobRead(lobLocator *C.OCILobLocator, form C.ub1) ([]byte, error) {
readBuffer := make([]byte, lobBufferSize)
buffer := make([]byte, 0)
result := (C.sword)(C.OCI_NEED_DATA)
piece := (C.ub1)(C.OCI_FIRST_PIECE)
for result == C.OCI_NEED_DATA {
readBytes := (C.oraub8)(0)
// If both byte_amtp and char_amtp are set to point to zero and OCI_FIRST_PIECE is passed then polling mode is assumed and data is read till the end of the LOB
result = C.OCILobRead2(
conn.svc, // service context handle
conn.errHandle, // error handle
lobLocator, // LOB or BFILE locator
&readBytes, // number of bytes to read. Used for BLOB and BFILE always. For CLOB and NCLOB, it is used only when char_amtp is zero.
nil, // number of characters to read
1, // the offset in the first call and in subsequent polling calls the offset parameter is ignored
unsafe.Pointer(&readBuffer[0]), // pointer to a buffer into which the piece will be read
lobBufferSize, // length of the buffer
piece, // For polling, pass OCI_FIRST_PIECE the first time and OCI_NEXT_PIECE in subsequent calls.
nil, // context pointer for the callback function
nil, // If this is null, then OCI_NEED_DATA will be returned for each piece.
0, // character set ID of the buffer data. If this value is 0 then csid is set to the client's NLS_LANG or NLS_CHAR value, depending on the value of csfrm.
form, // character set form of the buffer data
)
if piece == C.OCI_FIRST_PIECE {
piece = C.OCI_NEXT_PIECE
}
if result == C.OCI_SUCCESS || result == C.OCI_NEED_DATA {
buffer = append(buffer, readBuffer[:int(readBytes)]...)
}
}
return buffer, conn.getError(result)
} | go | func (conn *OCI8Conn) ociLobRead(lobLocator *C.OCILobLocator, form C.ub1) ([]byte, error) {
readBuffer := make([]byte, lobBufferSize)
buffer := make([]byte, 0)
result := (C.sword)(C.OCI_NEED_DATA)
piece := (C.ub1)(C.OCI_FIRST_PIECE)
for result == C.OCI_NEED_DATA {
readBytes := (C.oraub8)(0)
// If both byte_amtp and char_amtp are set to point to zero and OCI_FIRST_PIECE is passed then polling mode is assumed and data is read till the end of the LOB
result = C.OCILobRead2(
conn.svc, // service context handle
conn.errHandle, // error handle
lobLocator, // LOB or BFILE locator
&readBytes, // number of bytes to read. Used for BLOB and BFILE always. For CLOB and NCLOB, it is used only when char_amtp is zero.
nil, // number of characters to read
1, // the offset in the first call and in subsequent polling calls the offset parameter is ignored
unsafe.Pointer(&readBuffer[0]), // pointer to a buffer into which the piece will be read
lobBufferSize, // length of the buffer
piece, // For polling, pass OCI_FIRST_PIECE the first time and OCI_NEXT_PIECE in subsequent calls.
nil, // context pointer for the callback function
nil, // If this is null, then OCI_NEED_DATA will be returned for each piece.
0, // character set ID of the buffer data. If this value is 0 then csid is set to the client's NLS_LANG or NLS_CHAR value, depending on the value of csfrm.
form, // character set form of the buffer data
)
if piece == C.OCI_FIRST_PIECE {
piece = C.OCI_NEXT_PIECE
}
if result == C.OCI_SUCCESS || result == C.OCI_NEED_DATA {
buffer = append(buffer, readBuffer[:int(readBytes)]...)
}
}
return buffer, conn.getError(result)
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"ociLobRead",
"(",
"lobLocator",
"*",
"C",
".",
"OCILobLocator",
",",
"form",
"C",
".",
"ub1",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"readBuffer",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"lobBufferSize",
")",
"\n",
"buffer",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"result",
":=",
"(",
"C",
".",
"sword",
")",
"(",
"C",
".",
"OCI_NEED_DATA",
")",
"\n",
"piece",
":=",
"(",
"C",
".",
"ub1",
")",
"(",
"C",
".",
"OCI_FIRST_PIECE",
")",
"\n\n",
"for",
"result",
"==",
"C",
".",
"OCI_NEED_DATA",
"{",
"readBytes",
":=",
"(",
"C",
".",
"oraub8",
")",
"(",
"0",
")",
"\n\n",
"// If both byte_amtp and char_amtp are set to point to zero and OCI_FIRST_PIECE is passed then polling mode is assumed and data is read till the end of the LOB",
"result",
"=",
"C",
".",
"OCILobRead2",
"(",
"conn",
".",
"svc",
",",
"// service context handle",
"conn",
".",
"errHandle",
",",
"// error handle",
"lobLocator",
",",
"// LOB or BFILE locator",
"&",
"readBytes",
",",
"// number of bytes to read. Used for BLOB and BFILE always. For CLOB and NCLOB, it is used only when char_amtp is zero.",
"nil",
",",
"// number of characters to read",
"1",
",",
"// the offset in the first call and in subsequent polling calls the offset parameter is ignored",
"unsafe",
".",
"Pointer",
"(",
"&",
"readBuffer",
"[",
"0",
"]",
")",
",",
"// pointer to a buffer into which the piece will be read",
"lobBufferSize",
",",
"// length of the buffer",
"piece",
",",
"// For polling, pass OCI_FIRST_PIECE the first time and OCI_NEXT_PIECE in subsequent calls.",
"nil",
",",
"// context pointer for the callback function",
"nil",
",",
"// If this is null, then OCI_NEED_DATA will be returned for each piece.",
"0",
",",
"// character set ID of the buffer data. If this value is 0 then csid is set to the client's NLS_LANG or NLS_CHAR value, depending on the value of csfrm.",
"form",
",",
"// character set form of the buffer data",
")",
"\n\n",
"if",
"piece",
"==",
"C",
".",
"OCI_FIRST_PIECE",
"{",
"piece",
"=",
"C",
".",
"OCI_NEXT_PIECE",
"\n",
"}",
"\n\n",
"if",
"result",
"==",
"C",
".",
"OCI_SUCCESS",
"||",
"result",
"==",
"C",
".",
"OCI_NEED_DATA",
"{",
"buffer",
"=",
"append",
"(",
"buffer",
",",
"readBuffer",
"[",
":",
"int",
"(",
"readBytes",
")",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buffer",
",",
"conn",
".",
"getError",
"(",
"result",
")",
"\n",
"}"
] | // ociLobRead calls OCILobRead then returns lob bytes and error. | [
"ociLobRead",
"calls",
"OCILobRead",
"then",
"returns",
"lob",
"bytes",
"and",
"error",
"."
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connection.go#L359-L395 |
150,487 | mattn/go-oci8 | connector.go | NewConnector | func NewConnector(hosts ...string) driver.Connector {
return &OCI8Connector{
Logger: log.New(ioutil.Discard, "", 0),
}
} | go | func NewConnector(hosts ...string) driver.Connector {
return &OCI8Connector{
Logger: log.New(ioutil.Discard, "", 0),
}
} | [
"func",
"NewConnector",
"(",
"hosts",
"...",
"string",
")",
"driver",
".",
"Connector",
"{",
"return",
"&",
"OCI8Connector",
"{",
"Logger",
":",
"log",
".",
"New",
"(",
"ioutil",
".",
"Discard",
",",
"\"",
"\"",
",",
"0",
")",
",",
"}",
"\n",
"}"
] | // NewConnector returns a new database connector | [
"NewConnector",
"returns",
"a",
"new",
"database",
"connector"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connector.go#L13-L17 |
150,488 | mattn/go-oci8 | connector.go | Connect | func (oci8Connector *OCI8Connector) Connect(ctx context.Context) (driver.Conn, error) {
oci8Conn := &OCI8Conn{
logger: oci8Connector.Logger,
}
if oci8Conn.logger == nil {
oci8Conn.logger = log.New(ioutil.Discard, "", 0)
}
return oci8Conn, nil
} | go | func (oci8Connector *OCI8Connector) Connect(ctx context.Context) (driver.Conn, error) {
oci8Conn := &OCI8Conn{
logger: oci8Connector.Logger,
}
if oci8Conn.logger == nil {
oci8Conn.logger = log.New(ioutil.Discard, "", 0)
}
return oci8Conn, nil
} | [
"func",
"(",
"oci8Connector",
"*",
"OCI8Connector",
")",
"Connect",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"driver",
".",
"Conn",
",",
"error",
")",
"{",
"oci8Conn",
":=",
"&",
"OCI8Conn",
"{",
"logger",
":",
"oci8Connector",
".",
"Logger",
",",
"}",
"\n",
"if",
"oci8Conn",
".",
"logger",
"==",
"nil",
"{",
"oci8Conn",
".",
"logger",
"=",
"log",
".",
"New",
"(",
"ioutil",
".",
"Discard",
",",
"\"",
"\"",
",",
"0",
")",
"\n",
"}",
"\n",
"return",
"oci8Conn",
",",
"nil",
"\n",
"}"
] | // Connect returns a new database connection | [
"Connect",
"returns",
"a",
"new",
"database",
"connection"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/connector.go#L25-L34 |
150,489 | mattn/go-oci8 | oci8.go | Commit | func (tx *OCI8Tx) Commit() error {
tx.conn.inTransaction = false
if rv := C.OCITransCommit(
tx.conn.svc,
tx.conn.errHandle,
0,
); rv != C.OCI_SUCCESS {
return tx.conn.getError(rv)
}
return nil
} | go | func (tx *OCI8Tx) Commit() error {
tx.conn.inTransaction = false
if rv := C.OCITransCommit(
tx.conn.svc,
tx.conn.errHandle,
0,
); rv != C.OCI_SUCCESS {
return tx.conn.getError(rv)
}
return nil
} | [
"func",
"(",
"tx",
"*",
"OCI8Tx",
")",
"Commit",
"(",
")",
"error",
"{",
"tx",
".",
"conn",
".",
"inTransaction",
"=",
"false",
"\n",
"if",
"rv",
":=",
"C",
".",
"OCITransCommit",
"(",
"tx",
".",
"conn",
".",
"svc",
",",
"tx",
".",
"conn",
".",
"errHandle",
",",
"0",
",",
")",
";",
"rv",
"!=",
"C",
".",
"OCI_SUCCESS",
"{",
"return",
"tx",
".",
"conn",
".",
"getError",
"(",
"rv",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Commit transaction commit | [
"Commit",
"transaction",
"commit"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/oci8.go#L130-L140 |
150,490 | mattn/go-oci8 | oci8.go | Rollback | func (tx *OCI8Tx) Rollback() error {
tx.conn.inTransaction = false
if rv := C.OCITransRollback(
tx.conn.svc,
tx.conn.errHandle,
0,
); rv != C.OCI_SUCCESS {
return tx.conn.getError(rv)
}
return nil
} | go | func (tx *OCI8Tx) Rollback() error {
tx.conn.inTransaction = false
if rv := C.OCITransRollback(
tx.conn.svc,
tx.conn.errHandle,
0,
); rv != C.OCI_SUCCESS {
return tx.conn.getError(rv)
}
return nil
} | [
"func",
"(",
"tx",
"*",
"OCI8Tx",
")",
"Rollback",
"(",
")",
"error",
"{",
"tx",
".",
"conn",
".",
"inTransaction",
"=",
"false",
"\n",
"if",
"rv",
":=",
"C",
".",
"OCITransRollback",
"(",
"tx",
".",
"conn",
".",
"svc",
",",
"tx",
".",
"conn",
".",
"errHandle",
",",
"0",
",",
")",
";",
"rv",
"!=",
"C",
".",
"OCI_SUCCESS",
"{",
"return",
"tx",
".",
"conn",
".",
"getError",
"(",
"rv",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Rollback transaction rollback | [
"Rollback",
"transaction",
"rollback"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/oci8.go#L143-L153 |
150,491 | mattn/go-oci8 | oci8.go | LastInsertId | func (result *OCI8Result) LastInsertId() (int64, error) {
return int64(uintptr(unsafe.Pointer(&result.rowid))), result.rowidErr
} | go | func (result *OCI8Result) LastInsertId() (int64, error) {
return int64(uintptr(unsafe.Pointer(&result.rowid))), result.rowidErr
} | [
"func",
"(",
"result",
"*",
"OCI8Result",
")",
"LastInsertId",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"return",
"int64",
"(",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"result",
".",
"rowid",
")",
")",
")",
",",
"result",
".",
"rowidErr",
"\n",
"}"
] | // LastInsertId returns last inserted ID | [
"LastInsertId",
"returns",
"last",
"inserted",
"ID"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/oci8.go#L364-L366 |
150,492 | mattn/go-oci8 | oci8_go18.go | CheckNamedValue | func (conn *OCI8Conn) CheckNamedValue(nv *driver.NamedValue) error {
switch nv.Value.(type) {
default:
return driver.ErrSkip
case sql.Out:
return nil
}
} | go | func (conn *OCI8Conn) CheckNamedValue(nv *driver.NamedValue) error {
switch nv.Value.(type) {
default:
return driver.ErrSkip
case sql.Out:
return nil
}
} | [
"func",
"(",
"conn",
"*",
"OCI8Conn",
")",
"CheckNamedValue",
"(",
"nv",
"*",
"driver",
".",
"NamedValue",
")",
"error",
"{",
"switch",
"nv",
".",
"Value",
".",
"(",
"type",
")",
"{",
"default",
":",
"return",
"driver",
".",
"ErrSkip",
"\n",
"case",
"sql",
".",
"Out",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // CheckNamedValue checks the named value | [
"CheckNamedValue",
"checks",
"the",
"named",
"value"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/oci8_go18.go#L52-L59 |
150,493 | mattn/go-oci8 | cHelpers.go | cByte | func cByte(b []byte) *C.OraText {
p := C.malloc(C.size_t(len(b)))
pp := (*[1 << 30]byte)(p)
copy(pp[:], b)
return (*C.OraText)(p)
} | go | func cByte(b []byte) *C.OraText {
p := C.malloc(C.size_t(len(b)))
pp := (*[1 << 30]byte)(p)
copy(pp[:], b)
return (*C.OraText)(p)
} | [
"func",
"cByte",
"(",
"b",
"[",
"]",
"byte",
")",
"*",
"C",
".",
"OraText",
"{",
"p",
":=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"pp",
":=",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"p",
")",
"\n",
"copy",
"(",
"pp",
"[",
":",
"]",
",",
"b",
")",
"\n",
"return",
"(",
"*",
"C",
".",
"OraText",
")",
"(",
"p",
")",
"\n",
"}"
] | // cByte comverts byte slice to OraText.
// must be freed | [
"cByte",
"comverts",
"byte",
"slice",
"to",
"OraText",
".",
"must",
"be",
"freed"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L22-L27 |
150,494 | mattn/go-oci8 | cHelpers.go | cByteN | func cByteN(b []byte, size int) *C.OraText {
p := C.malloc(C.size_t(size))
pp := (*[1 << 30]byte)(p)
copy(pp[:], b)
return (*C.OraText)(p)
} | go | func cByteN(b []byte, size int) *C.OraText {
p := C.malloc(C.size_t(size))
pp := (*[1 << 30]byte)(p)
copy(pp[:], b)
return (*C.OraText)(p)
} | [
"func",
"cByteN",
"(",
"b",
"[",
"]",
"byte",
",",
"size",
"int",
")",
"*",
"C",
".",
"OraText",
"{",
"p",
":=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"size",
")",
")",
"\n",
"pp",
":=",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"p",
")",
"\n",
"copy",
"(",
"pp",
"[",
":",
"]",
",",
"b",
")",
"\n",
"return",
"(",
"*",
"C",
".",
"OraText",
")",
"(",
"p",
")",
"\n",
"}"
] | // cByteN comverts byte slice to C OraText with size.
// must be freed | [
"cByteN",
"comverts",
"byte",
"slice",
"to",
"C",
"OraText",
"with",
"size",
".",
"must",
"be",
"freed"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L31-L36 |
150,495 | mattn/go-oci8 | cHelpers.go | cString | func cString(s string) *C.OraText {
p := C.malloc(C.size_t(len(s) + 1))
pp := (*[1 << 30]byte)(p)
copy(pp[:], s)
pp[len(s)] = 0
return (*C.OraText)(p)
} | go | func cString(s string) *C.OraText {
p := C.malloc(C.size_t(len(s) + 1))
pp := (*[1 << 30]byte)(p)
copy(pp[:], s)
pp[len(s)] = 0
return (*C.OraText)(p)
} | [
"func",
"cString",
"(",
"s",
"string",
")",
"*",
"C",
".",
"OraText",
"{",
"p",
":=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"len",
"(",
"s",
")",
"+",
"1",
")",
")",
"\n",
"pp",
":=",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"p",
")",
"\n",
"copy",
"(",
"pp",
"[",
":",
"]",
",",
"s",
")",
"\n",
"pp",
"[",
"len",
"(",
"s",
")",
"]",
"=",
"0",
"\n",
"return",
"(",
"*",
"C",
".",
"OraText",
")",
"(",
"p",
")",
"\n",
"}"
] | // cString coverts string to C OraText.
// must be freed | [
"cString",
"coverts",
"string",
"to",
"C",
"OraText",
".",
"must",
"be",
"freed"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L40-L46 |
150,496 | mattn/go-oci8 | cHelpers.go | cStringN | func cStringN(s string, size int) *C.OraText {
p := C.malloc(C.size_t(size))
pp := (*[1 << 30]byte)(p)
copy(pp[:], s)
if len(s) < size {
pp[len(s)] = 0
} else {
pp[size-1] = 0
}
return (*C.OraText)(p)
} | go | func cStringN(s string, size int) *C.OraText {
p := C.malloc(C.size_t(size))
pp := (*[1 << 30]byte)(p)
copy(pp[:], s)
if len(s) < size {
pp[len(s)] = 0
} else {
pp[size-1] = 0
}
return (*C.OraText)(p)
} | [
"func",
"cStringN",
"(",
"s",
"string",
",",
"size",
"int",
")",
"*",
"C",
".",
"OraText",
"{",
"p",
":=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"size",
")",
")",
"\n",
"pp",
":=",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"p",
")",
"\n",
"copy",
"(",
"pp",
"[",
":",
"]",
",",
"s",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"<",
"size",
"{",
"pp",
"[",
"len",
"(",
"s",
")",
"]",
"=",
"0",
"\n",
"}",
"else",
"{",
"pp",
"[",
"size",
"-",
"1",
"]",
"=",
"0",
"\n",
"}",
"\n",
"return",
"(",
"*",
"C",
".",
"OraText",
")",
"(",
"p",
")",
"\n",
"}"
] | // cStringN coverts string to C OraText with size.
// must be freed | [
"cStringN",
"coverts",
"string",
"to",
"C",
"OraText",
"with",
"size",
".",
"must",
"be",
"freed"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L50-L60 |
150,497 | mattn/go-oci8 | cHelpers.go | cGoStringN | func cGoStringN(s *C.OraText, size int) string {
if size == 0 {
return ""
}
p := (*[1 << 30]byte)(unsafe.Pointer(s))
buf := make([]byte, size)
copy(buf, p[:])
return *(*string)(unsafe.Pointer(&buf))
} | go | func cGoStringN(s *C.OraText, size int) string {
if size == 0 {
return ""
}
p := (*[1 << 30]byte)(unsafe.Pointer(s))
buf := make([]byte, size)
copy(buf, p[:])
return *(*string)(unsafe.Pointer(&buf))
} | [
"func",
"cGoStringN",
"(",
"s",
"*",
"C",
".",
"OraText",
",",
"size",
"int",
")",
"string",
"{",
"if",
"size",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"p",
":=",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"s",
")",
")",
"\n",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
"\n",
"copy",
"(",
"buf",
",",
"p",
"[",
":",
"]",
")",
"\n",
"return",
"*",
"(",
"*",
"string",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"&",
"buf",
")",
")",
"\n",
"}"
] | // CGoStringN coverts C OraText to Go string | [
"CGoStringN",
"coverts",
"C",
"OraText",
"to",
"Go",
"string"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L63-L71 |
150,498 | mattn/go-oci8 | cHelpers.go | freeDefines | func freeDefines(defines []oci8Define) {
for _, define := range defines {
if define.pbuf != nil {
freeBuffer(define.pbuf, define.dataType)
define.pbuf = nil
}
if define.length != nil {
C.free(unsafe.Pointer(define.length))
define.length = nil
}
if define.indicator != nil {
C.free(unsafe.Pointer(define.indicator))
define.indicator = nil
}
define.defineHandle = nil // should be freed by oci statement close
}
} | go | func freeDefines(defines []oci8Define) {
for _, define := range defines {
if define.pbuf != nil {
freeBuffer(define.pbuf, define.dataType)
define.pbuf = nil
}
if define.length != nil {
C.free(unsafe.Pointer(define.length))
define.length = nil
}
if define.indicator != nil {
C.free(unsafe.Pointer(define.indicator))
define.indicator = nil
}
define.defineHandle = nil // should be freed by oci statement close
}
} | [
"func",
"freeDefines",
"(",
"defines",
"[",
"]",
"oci8Define",
")",
"{",
"for",
"_",
",",
"define",
":=",
"range",
"defines",
"{",
"if",
"define",
".",
"pbuf",
"!=",
"nil",
"{",
"freeBuffer",
"(",
"define",
".",
"pbuf",
",",
"define",
".",
"dataType",
")",
"\n",
"define",
".",
"pbuf",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"define",
".",
"length",
"!=",
"nil",
"{",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"define",
".",
"length",
")",
")",
"\n",
"define",
".",
"length",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"define",
".",
"indicator",
"!=",
"nil",
"{",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"define",
".",
"indicator",
")",
")",
"\n",
"define",
".",
"indicator",
"=",
"nil",
"\n",
"}",
"\n",
"define",
".",
"defineHandle",
"=",
"nil",
"// should be freed by oci statement close",
"\n",
"}",
"\n",
"}"
] | // freeDefines frees defines | [
"freeDefines",
"frees",
"defines"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L74-L90 |
150,499 | mattn/go-oci8 | cHelpers.go | freeBinds | func freeBinds(binds []oci8Bind) {
for _, bind := range binds {
if bind.pbuf != nil {
freeBuffer(bind.pbuf, bind.dataType)
bind.pbuf = nil
}
if bind.length != nil {
C.free(unsafe.Pointer(bind.length))
bind.length = nil
}
if bind.indicator != nil {
C.free(unsafe.Pointer(bind.indicator))
bind.indicator = nil
}
bind.bindHandle = nil // freed by oci statement close
}
} | go | func freeBinds(binds []oci8Bind) {
for _, bind := range binds {
if bind.pbuf != nil {
freeBuffer(bind.pbuf, bind.dataType)
bind.pbuf = nil
}
if bind.length != nil {
C.free(unsafe.Pointer(bind.length))
bind.length = nil
}
if bind.indicator != nil {
C.free(unsafe.Pointer(bind.indicator))
bind.indicator = nil
}
bind.bindHandle = nil // freed by oci statement close
}
} | [
"func",
"freeBinds",
"(",
"binds",
"[",
"]",
"oci8Bind",
")",
"{",
"for",
"_",
",",
"bind",
":=",
"range",
"binds",
"{",
"if",
"bind",
".",
"pbuf",
"!=",
"nil",
"{",
"freeBuffer",
"(",
"bind",
".",
"pbuf",
",",
"bind",
".",
"dataType",
")",
"\n",
"bind",
".",
"pbuf",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"bind",
".",
"length",
"!=",
"nil",
"{",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"bind",
".",
"length",
")",
")",
"\n",
"bind",
".",
"length",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"bind",
".",
"indicator",
"!=",
"nil",
"{",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"bind",
".",
"indicator",
")",
")",
"\n",
"bind",
".",
"indicator",
"=",
"nil",
"\n",
"}",
"\n",
"bind",
".",
"bindHandle",
"=",
"nil",
"// freed by oci statement close",
"\n",
"}",
"\n",
"}"
] | // freeBinds frees binds | [
"freeBinds",
"frees",
"binds"
] | b4ff95311f59786a15c0688c8beff047414c098f | https://github.com/mattn/go-oci8/blob/b4ff95311f59786a15c0688c8beff047414c098f/cHelpers.go#L93-L109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.