repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
cri-o/cri-o
utils/io/container_io.go
NewContainerIO
func NewContainerIO(id string, opts ...ContainerIOOpts) (_ *ContainerIO, err error) { c := &ContainerIO{ id: id, stdoutGroup: cioutil.NewWriterGroup(), stderrGroup: cioutil.NewWriterGroup(), } for _, opt := range opts { if err := opt(c); err != nil { return nil, err } } if c.fifos == nil { return nil, errors.New("fifos are not set") } // Create actual fifos. stdio, closer, err := newStdioPipes(c.fifos) if err != nil { return nil, err } c.stdioPipes = stdio c.closer = closer return c, nil }
go
func NewContainerIO(id string, opts ...ContainerIOOpts) (_ *ContainerIO, err error) { c := &ContainerIO{ id: id, stdoutGroup: cioutil.NewWriterGroup(), stderrGroup: cioutil.NewWriterGroup(), } for _, opt := range opts { if err := opt(c); err != nil { return nil, err } } if c.fifos == nil { return nil, errors.New("fifos are not set") } // Create actual fifos. stdio, closer, err := newStdioPipes(c.fifos) if err != nil { return nil, err } c.stdioPipes = stdio c.closer = closer return c, nil }
[ "func", "NewContainerIO", "(", "id", "string", ",", "opts", "...", "ContainerIOOpts", ")", "(", "_", "*", "ContainerIO", ",", "err", "error", ")", "{", "c", ":=", "&", "ContainerIO", "{", "id", ":", "id", ",", "stdoutGroup", ":", "cioutil", ".", "NewWriterGroup", "(", ")", ",", "stderrGroup", ":", "cioutil", ".", "NewWriterGroup", "(", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "err", ":=", "opt", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "c", ".", "fifos", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"fifos are not set\"", ")", "\n", "}", "\n", "stdio", ",", "closer", ",", "err", ":=", "newStdioPipes", "(", "c", ".", "fifos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "stdioPipes", "=", "stdio", "\n", "c", ".", "closer", "=", "closer", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewContainerIO creates container io.
[ "NewContainerIO", "creates", "container", "io", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L75-L97
train
cri-o/cri-o
utils/io/container_io.go
Pipe
func (c *ContainerIO) Pipe() { wg := c.closer.wg wg.Add(1) go func() { if _, err := io.Copy(c.stdoutGroup, c.stdout); err != nil { logrus.WithError(err).Errorf("Failed to pipe stdout of container %q", c.id) } c.stdout.Close() c.stdoutGroup.Close() wg.Done() logrus.Infof("Finish piping stdout of container %q", c.id) }() if !c.fifos.Terminal { wg.Add(1) go func() { if _, err := io.Copy(c.stderrGroup, c.stderr); err != nil { logrus.WithError(err).Errorf("Failed to pipe stderr of container %q", c.id) } c.stderr.Close() c.stderrGroup.Close() wg.Done() logrus.Infof("Finish piping stderr of container %q", c.id) }() } }
go
func (c *ContainerIO) Pipe() { wg := c.closer.wg wg.Add(1) go func() { if _, err := io.Copy(c.stdoutGroup, c.stdout); err != nil { logrus.WithError(err).Errorf("Failed to pipe stdout of container %q", c.id) } c.stdout.Close() c.stdoutGroup.Close() wg.Done() logrus.Infof("Finish piping stdout of container %q", c.id) }() if !c.fifos.Terminal { wg.Add(1) go func() { if _, err := io.Copy(c.stderrGroup, c.stderr); err != nil { logrus.WithError(err).Errorf("Failed to pipe stderr of container %q", c.id) } c.stderr.Close() c.stderrGroup.Close() wg.Done() logrus.Infof("Finish piping stderr of container %q", c.id) }() } }
[ "func", "(", "c", "*", "ContainerIO", ")", "Pipe", "(", ")", "{", "wg", ":=", "c", ".", "closer", ".", "wg", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "c", ".", "stdoutGroup", ",", "c", ".", "stdout", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"Failed to pipe stdout of container %q\"", ",", "c", ".", "id", ")", "\n", "}", "\n", "c", ".", "stdout", ".", "Close", "(", ")", "\n", "c", ".", "stdoutGroup", ".", "Close", "(", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "logrus", ".", "Infof", "(", "\"Finish piping stdout of container %q\"", ",", "c", ".", "id", ")", "\n", "}", "(", ")", "\n", "if", "!", "c", ".", "fifos", ".", "Terminal", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "c", ".", "stderrGroup", ",", "c", ".", "stderr", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"Failed to pipe stderr of container %q\"", ",", "c", ".", "id", ")", "\n", "}", "\n", "c", ".", "stderr", ".", "Close", "(", ")", "\n", "c", ".", "stderrGroup", ".", "Close", "(", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "logrus", ".", "Infof", "(", "\"Finish piping stderr of container %q\"", ",", "c", ".", "id", ")", "\n", "}", "(", ")", "\n", "}", "\n", "}" ]
// Pipe creates container fifos and pipe container output // to output stream.
[ "Pipe", "creates", "container", "fifos", "and", "pipe", "container", "output", "to", "output", "stream", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L106-L131
train
cri-o/cri-o
utils/io/container_io.go
AddOutput
func (c *ContainerIO) AddOutput(name string, stdout, stderr io.WriteCloser) (io.WriteCloser, io.WriteCloser) { var oldStdout, oldStderr io.WriteCloser if stdout != nil { key := streamKey(c.id, name, Stdout) oldStdout = c.stdoutGroup.Get(key) c.stdoutGroup.Add(key, stdout) } if stderr != nil { key := streamKey(c.id, name, Stderr) oldStderr = c.stderrGroup.Get(key) c.stderrGroup.Add(key, stderr) } return oldStdout, oldStderr }
go
func (c *ContainerIO) AddOutput(name string, stdout, stderr io.WriteCloser) (io.WriteCloser, io.WriteCloser) { var oldStdout, oldStderr io.WriteCloser if stdout != nil { key := streamKey(c.id, name, Stdout) oldStdout = c.stdoutGroup.Get(key) c.stdoutGroup.Add(key, stdout) } if stderr != nil { key := streamKey(c.id, name, Stderr) oldStderr = c.stderrGroup.Get(key) c.stderrGroup.Add(key, stderr) } return oldStdout, oldStderr }
[ "func", "(", "c", "*", "ContainerIO", ")", "AddOutput", "(", "name", "string", ",", "stdout", ",", "stderr", "io", ".", "WriteCloser", ")", "(", "io", ".", "WriteCloser", ",", "io", ".", "WriteCloser", ")", "{", "var", "oldStdout", ",", "oldStderr", "io", ".", "WriteCloser", "\n", "if", "stdout", "!=", "nil", "{", "key", ":=", "streamKey", "(", "c", ".", "id", ",", "name", ",", "Stdout", ")", "\n", "oldStdout", "=", "c", ".", "stdoutGroup", ".", "Get", "(", "key", ")", "\n", "c", ".", "stdoutGroup", ".", "Add", "(", "key", ",", "stdout", ")", "\n", "}", "\n", "if", "stderr", "!=", "nil", "{", "key", ":=", "streamKey", "(", "c", ".", "id", ",", "name", ",", "Stderr", ")", "\n", "oldStderr", "=", "c", ".", "stderrGroup", ".", "Get", "(", "key", ")", "\n", "c", ".", "stderrGroup", ".", "Add", "(", "key", ",", "stderr", ")", "\n", "}", "\n", "return", "oldStdout", ",", "oldStderr", "\n", "}" ]
// AddOutput adds new write closers to the container stream, and returns existing // write closers if there are any.
[ "AddOutput", "adds", "new", "write", "closers", "to", "the", "container", "stream", "and", "returns", "existing", "write", "closers", "if", "there", "are", "any", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L202-L215
train
cri-o/cri-o
lib/logs.go
GetLogs
func (c *ContainerServer) GetLogs(container string, logChan chan string, opts LogOptions) error { defer close(logChan) // Get the full ID of the container ctr, err := c.LookupContainer(container) if err != nil { return err } containerID := ctr.ID() sandbox := ctr.Sandbox() if sandbox == "" { sandbox = containerID } // Read the log line by line and pass it into the pipe logsFile := path.Join(c.config.LogDir, sandbox, containerID+".log") seekInfo := &tail.SeekInfo{Offset: 0, Whence: 0} if opts.Tail > 0 { // seek to correct position in logs files seekInfo.Offset = int64(opts.Tail) seekInfo.Whence = 2 } t, err := tail.TailFile(logsFile, tail.Config{Follow: false, ReOpen: false, Location: seekInfo}) for line := range t.Lines { if since, err := logSinceTime(opts.SinceTime, line.Text); err != nil || !since { continue } logMessage := line.Text[secondSpaceIndex(line.Text):] logChan <- logMessage } return err }
go
func (c *ContainerServer) GetLogs(container string, logChan chan string, opts LogOptions) error { defer close(logChan) // Get the full ID of the container ctr, err := c.LookupContainer(container) if err != nil { return err } containerID := ctr.ID() sandbox := ctr.Sandbox() if sandbox == "" { sandbox = containerID } // Read the log line by line and pass it into the pipe logsFile := path.Join(c.config.LogDir, sandbox, containerID+".log") seekInfo := &tail.SeekInfo{Offset: 0, Whence: 0} if opts.Tail > 0 { // seek to correct position in logs files seekInfo.Offset = int64(opts.Tail) seekInfo.Whence = 2 } t, err := tail.TailFile(logsFile, tail.Config{Follow: false, ReOpen: false, Location: seekInfo}) for line := range t.Lines { if since, err := logSinceTime(opts.SinceTime, line.Text); err != nil || !since { continue } logMessage := line.Text[secondSpaceIndex(line.Text):] logChan <- logMessage } return err }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetLogs", "(", "container", "string", ",", "logChan", "chan", "string", ",", "opts", "LogOptions", ")", "error", "{", "defer", "close", "(", "logChan", ")", "\n", "ctr", ",", "err", ":=", "c", ".", "LookupContainer", "(", "container", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "containerID", ":=", "ctr", ".", "ID", "(", ")", "\n", "sandbox", ":=", "ctr", ".", "Sandbox", "(", ")", "\n", "if", "sandbox", "==", "\"\"", "{", "sandbox", "=", "containerID", "\n", "}", "\n", "logsFile", ":=", "path", ".", "Join", "(", "c", ".", "config", ".", "LogDir", ",", "sandbox", ",", "containerID", "+", "\".log\"", ")", "\n", "seekInfo", ":=", "&", "tail", ".", "SeekInfo", "{", "Offset", ":", "0", ",", "Whence", ":", "0", "}", "\n", "if", "opts", ".", "Tail", ">", "0", "{", "seekInfo", ".", "Offset", "=", "int64", "(", "opts", ".", "Tail", ")", "\n", "seekInfo", ".", "Whence", "=", "2", "\n", "}", "\n", "t", ",", "err", ":=", "tail", ".", "TailFile", "(", "logsFile", ",", "tail", ".", "Config", "{", "Follow", ":", "false", ",", "ReOpen", ":", "false", ",", "Location", ":", "seekInfo", "}", ")", "\n", "for", "line", ":=", "range", "t", ".", "Lines", "{", "if", "since", ",", "err", ":=", "logSinceTime", "(", "opts", ".", "SinceTime", ",", "line", ".", "Text", ")", ";", "err", "!=", "nil", "||", "!", "since", "{", "continue", "\n", "}", "\n", "logMessage", ":=", "line", ".", "Text", "[", "secondSpaceIndex", "(", "line", ".", "Text", ")", ":", "]", "\n", "logChan", "<-", "logMessage", "\n", "}", "\n", "return", "err", "\n", "}" ]
// GetLogs gets each line of a log file and, if it matches the criteria in logOptions, sends it down logChan
[ "GetLogs", "gets", "each", "line", "of", "a", "log", "file", "and", "if", "it", "matches", "the", "criteria", "in", "logOptions", "sends", "it", "down", "logChan" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/logs.go#L20-L52
train
cri-o/cri-o
oci/container.go
NewContainer
func NewContainer(id string, name string, bundlePath string, logPath string, netns string, labels map[string]string, crioAnnotations map[string]string, annotations map[string]string, image string, imageName string, imageRef string, metadata *pb.ContainerMetadata, sandbox string, terminal bool, stdin bool, stdinOnce bool, privileged bool, runtimeHandler string, dir string, created time.Time, stopSignal string) (*Container, error) { state := &ContainerState{} state.Created = created c := &Container{ id: id, name: name, bundlePath: bundlePath, logPath: logPath, labels: labels, sandbox: sandbox, netns: netns, terminal: terminal, stdin: stdin, stdinOnce: stdinOnce, privileged: privileged, runtimeHandler: runtimeHandler, metadata: metadata, annotations: annotations, crioAnnotations: crioAnnotations, image: image, imageName: imageName, imageRef: imageRef, dir: dir, state: state, stopSignal: stopSignal, } return c, nil }
go
func NewContainer(id string, name string, bundlePath string, logPath string, netns string, labels map[string]string, crioAnnotations map[string]string, annotations map[string]string, image string, imageName string, imageRef string, metadata *pb.ContainerMetadata, sandbox string, terminal bool, stdin bool, stdinOnce bool, privileged bool, runtimeHandler string, dir string, created time.Time, stopSignal string) (*Container, error) { state := &ContainerState{} state.Created = created c := &Container{ id: id, name: name, bundlePath: bundlePath, logPath: logPath, labels: labels, sandbox: sandbox, netns: netns, terminal: terminal, stdin: stdin, stdinOnce: stdinOnce, privileged: privileged, runtimeHandler: runtimeHandler, metadata: metadata, annotations: annotations, crioAnnotations: crioAnnotations, image: image, imageName: imageName, imageRef: imageRef, dir: dir, state: state, stopSignal: stopSignal, } return c, nil }
[ "func", "NewContainer", "(", "id", "string", ",", "name", "string", ",", "bundlePath", "string", ",", "logPath", "string", ",", "netns", "string", ",", "labels", "map", "[", "string", "]", "string", ",", "crioAnnotations", "map", "[", "string", "]", "string", ",", "annotations", "map", "[", "string", "]", "string", ",", "image", "string", ",", "imageName", "string", ",", "imageRef", "string", ",", "metadata", "*", "pb", ".", "ContainerMetadata", ",", "sandbox", "string", ",", "terminal", "bool", ",", "stdin", "bool", ",", "stdinOnce", "bool", ",", "privileged", "bool", ",", "runtimeHandler", "string", ",", "dir", "string", ",", "created", "time", ".", "Time", ",", "stopSignal", "string", ")", "(", "*", "Container", ",", "error", ")", "{", "state", ":=", "&", "ContainerState", "{", "}", "\n", "state", ".", "Created", "=", "created", "\n", "c", ":=", "&", "Container", "{", "id", ":", "id", ",", "name", ":", "name", ",", "bundlePath", ":", "bundlePath", ",", "logPath", ":", "logPath", ",", "labels", ":", "labels", ",", "sandbox", ":", "sandbox", ",", "netns", ":", "netns", ",", "terminal", ":", "terminal", ",", "stdin", ":", "stdin", ",", "stdinOnce", ":", "stdinOnce", ",", "privileged", ":", "privileged", ",", "runtimeHandler", ":", "runtimeHandler", ",", "metadata", ":", "metadata", ",", "annotations", ":", "annotations", ",", "crioAnnotations", ":", "crioAnnotations", ",", "image", ":", "image", ",", "imageName", ":", "imageName", ",", "imageRef", ":", "imageRef", ",", "dir", ":", "dir", ",", "state", ":", "state", ",", "stopSignal", ":", "stopSignal", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewContainer creates a container object.
[ "NewContainer", "creates", "a", "container", "object", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L79-L106
train
cri-o/cri-o
oci/container.go
GetStopSignal
func (c *Container) GetStopSignal() string { if c.stopSignal == "" { return defaultStopSignal } cleanSignal := strings.TrimPrefix(strings.ToUpper(c.stopSignal), "SIG") _, ok := signal.SignalMap[cleanSignal] if !ok { return defaultStopSignal } return cleanSignal }
go
func (c *Container) GetStopSignal() string { if c.stopSignal == "" { return defaultStopSignal } cleanSignal := strings.TrimPrefix(strings.ToUpper(c.stopSignal), "SIG") _, ok := signal.SignalMap[cleanSignal] if !ok { return defaultStopSignal } return cleanSignal }
[ "func", "(", "c", "*", "Container", ")", "GetStopSignal", "(", ")", "string", "{", "if", "c", ".", "stopSignal", "==", "\"\"", "{", "return", "defaultStopSignal", "\n", "}", "\n", "cleanSignal", ":=", "strings", ".", "TrimPrefix", "(", "strings", ".", "ToUpper", "(", "c", ".", "stopSignal", ")", ",", "\"SIG\"", ")", "\n", "_", ",", "ok", ":=", "signal", ".", "SignalMap", "[", "cleanSignal", "]", "\n", "if", "!", "ok", "{", "return", "defaultStopSignal", "\n", "}", "\n", "return", "cleanSignal", "\n", "}" ]
// GetStopSignal returns the container's own stop signal configured from the // image configuration or the default one.
[ "GetStopSignal", "returns", "the", "container", "s", "own", "stop", "signal", "configured", "from", "the", "image", "configuration", "or", "the", "default", "one", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L120-L130
train
cri-o/cri-o
oci/container.go
StopSignal
func (c *Container) StopSignal() syscall.Signal { if c.stopSignal == "" { return defaultStopSignalInt } cleanSignal := strings.TrimPrefix(strings.ToUpper(c.stopSignal), "SIG") sig, ok := signal.SignalMap[cleanSignal] if !ok { return defaultStopSignalInt } return sig }
go
func (c *Container) StopSignal() syscall.Signal { if c.stopSignal == "" { return defaultStopSignalInt } cleanSignal := strings.TrimPrefix(strings.ToUpper(c.stopSignal), "SIG") sig, ok := signal.SignalMap[cleanSignal] if !ok { return defaultStopSignalInt } return sig }
[ "func", "(", "c", "*", "Container", ")", "StopSignal", "(", ")", "syscall", ".", "Signal", "{", "if", "c", ".", "stopSignal", "==", "\"\"", "{", "return", "defaultStopSignalInt", "\n", "}", "\n", "cleanSignal", ":=", "strings", ".", "TrimPrefix", "(", "strings", ".", "ToUpper", "(", "c", ".", "stopSignal", ")", ",", "\"SIG\"", ")", "\n", "sig", ",", "ok", ":=", "signal", ".", "SignalMap", "[", "cleanSignal", "]", "\n", "if", "!", "ok", "{", "return", "defaultStopSignalInt", "\n", "}", "\n", "return", "sig", "\n", "}" ]
// StopSignal returns the container's own stop signal configured from // the image configuration or the default one.
[ "StopSignal", "returns", "the", "container", "s", "own", "stop", "signal", "configured", "from", "the", "image", "configuration", "or", "the", "default", "one", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L134-L144
train
cri-o/cri-o
oci/container.go
FromDisk
func (c *Container) FromDisk() error { jsonSource, err := os.Open(c.StatePath()) if err != nil { return err } defer jsonSource.Close() dec := json.NewDecoder(jsonSource) return dec.Decode(c.state) }
go
func (c *Container) FromDisk() error { jsonSource, err := os.Open(c.StatePath()) if err != nil { return err } defer jsonSource.Close() dec := json.NewDecoder(jsonSource) return dec.Decode(c.state) }
[ "func", "(", "c", "*", "Container", ")", "FromDisk", "(", ")", "error", "{", "jsonSource", ",", "err", ":=", "os", ".", "Open", "(", "c", ".", "StatePath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "jsonSource", ".", "Close", "(", ")", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "jsonSource", ")", "\n", "return", "dec", ".", "Decode", "(", "c", ".", "state", ")", "\n", "}" ]
// FromDisk restores container's state from disk
[ "FromDisk", "restores", "container", "s", "state", "from", "disk" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L147-L156
train
cri-o/cri-o
oci/container.go
NetNsPath
func (c *Container) NetNsPath() (string, error) { if c.state == nil { return "", fmt.Errorf("container state is not populated") } if c.netns == "" { return fmt.Sprintf("/proc/%d/ns/net", c.state.Pid), nil } return c.netns, nil }
go
func (c *Container) NetNsPath() (string, error) { if c.state == nil { return "", fmt.Errorf("container state is not populated") } if c.netns == "" { return fmt.Sprintf("/proc/%d/ns/net", c.state.Pid), nil } return c.netns, nil }
[ "func", "(", "c", "*", "Container", ")", "NetNsPath", "(", ")", "(", "string", ",", "error", ")", "{", "if", "c", ".", "state", "==", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"container state is not populated\"", ")", "\n", "}", "\n", "if", "c", ".", "netns", "==", "\"\"", "{", "return", "fmt", ".", "Sprintf", "(", "\"/proc/%d/ns/net\"", ",", "c", ".", "state", ".", "Pid", ")", ",", "nil", "\n", "}", "\n", "return", "c", ".", "netns", ",", "nil", "\n", "}" ]
// NetNsPath returns the path to the network namespace of the container.
[ "NetNsPath", "returns", "the", "path", "to", "the", "network", "namespace", "of", "the", "container", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L239-L249
train
cri-o/cri-o
oci/container.go
State
func (c *Container) State() *ContainerState { c.opLock.RLock() defer c.opLock.RUnlock() return c.state }
go
func (c *Container) State() *ContainerState { c.opLock.RLock() defer c.opLock.RUnlock() return c.state }
[ "func", "(", "c", "*", "Container", ")", "State", "(", ")", "*", "ContainerState", "{", "c", ".", "opLock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "opLock", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "state", "\n", "}" ]
// State returns the state of the running container
[ "State", "returns", "the", "state", "of", "the", "running", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L257-L261
train
cri-o/cri-o
oci/container.go
AddVolume
func (c *Container) AddVolume(v ContainerVolume) { c.volumes = append(c.volumes, v) }
go
func (c *Container) AddVolume(v ContainerVolume) { c.volumes = append(c.volumes, v) }
[ "func", "(", "c", "*", "Container", ")", "AddVolume", "(", "v", "ContainerVolume", ")", "{", "c", ".", "volumes", "=", "append", "(", "c", ".", "volumes", ",", "v", ")", "\n", "}" ]
// AddVolume adds a volume to list of container volumes.
[ "AddVolume", "adds", "a", "volume", "to", "list", "of", "container", "volumes", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L269-L271
train
cri-o/cri-o
oci/container.go
SetStartFailed
func (c *Container) SetStartFailed(err error) { c.opLock.Lock() defer c.opLock.Unlock() // adjust finished and started times c.state.Finished, c.state.Started = c.state.Created, c.state.Created if err != nil { c.state.Error = err.Error() } }
go
func (c *Container) SetStartFailed(err error) { c.opLock.Lock() defer c.opLock.Unlock() // adjust finished and started times c.state.Finished, c.state.Started = c.state.Created, c.state.Created if err != nil { c.state.Error = err.Error() } }
[ "func", "(", "c", "*", "Container", ")", "SetStartFailed", "(", "err", "error", ")", "{", "c", ".", "opLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "opLock", ".", "Unlock", "(", ")", "\n", "c", ".", "state", ".", "Finished", ",", "c", ".", "state", ".", "Started", "=", "c", ".", "state", ".", "Created", ",", "c", ".", "state", ".", "Created", "\n", "if", "err", "!=", "nil", "{", "c", ".", "state", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "}" ]
// SetStartFailed sets the container state appropriately after a start failure
[ "SetStartFailed", "sets", "the", "container", "state", "appropriately", "after", "a", "start", "failure" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L310-L318
train
cri-o/cri-o
oci/container.go
Description
func (c *Container) Description() string { return fmt.Sprintf("%s/%s/%s", c.Labels()[types.KubernetesPodNamespaceLabel], c.Labels()[types.KubernetesPodNameLabel], c.Labels()[types.KubernetesContainerNameLabel]) }
go
func (c *Container) Description() string { return fmt.Sprintf("%s/%s/%s", c.Labels()[types.KubernetesPodNamespaceLabel], c.Labels()[types.KubernetesPodNameLabel], c.Labels()[types.KubernetesContainerNameLabel]) }
[ "func", "(", "c", "*", "Container", ")", "Description", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s/%s/%s\"", ",", "c", ".", "Labels", "(", ")", "[", "types", ".", "KubernetesPodNamespaceLabel", "]", ",", "c", ".", "Labels", "(", ")", "[", "types", ".", "KubernetesPodNameLabel", "]", ",", "c", ".", "Labels", "(", ")", "[", "types", ".", "KubernetesContainerNameLabel", "]", ")", "\n", "}" ]
// Description returns a description for the container
[ "Description", "returns", "a", "description", "for", "the", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/container.go#L321-L323
train
cri-o/cri-o
utils/ioutil/write_closer.go
NewWriteCloseInformer
func NewWriteCloseInformer(wc io.WriteCloser) (io.WriteCloser, <-chan struct{}) { close := make(chan struct{}) return &writeCloseInformer{ close: close, wc: wc, }, close }
go
func NewWriteCloseInformer(wc io.WriteCloser) (io.WriteCloser, <-chan struct{}) { close := make(chan struct{}) return &writeCloseInformer{ close: close, wc: wc, }, close }
[ "func", "NewWriteCloseInformer", "(", "wc", "io", ".", "WriteCloser", ")", "(", "io", ".", "WriteCloser", ",", "<-", "chan", "struct", "{", "}", ")", "{", "close", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "return", "&", "writeCloseInformer", "{", "close", ":", "close", ",", "wc", ":", "wc", ",", "}", ",", "close", "\n", "}" ]
// NewWriteCloseInformer creates the writeCloseInformer from a write closer.
[ "NewWriteCloseInformer", "creates", "the", "writeCloseInformer", "from", "a", "write", "closer", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L33-L39
train
cri-o/cri-o
utils/ioutil/write_closer.go
Write
func (w *writeCloseInformer) Write(p []byte) (int, error) { return w.wc.Write(p) }
go
func (w *writeCloseInformer) Write(p []byte) (int, error) { return w.wc.Write(p) }
[ "func", "(", "w", "*", "writeCloseInformer", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "w", ".", "wc", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write passes through the data into the internal write closer.
[ "Write", "passes", "through", "the", "data", "into", "the", "internal", "write", "closer", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L42-L44
train
cri-o/cri-o
utils/ioutil/write_closer.go
Close
func (w *writeCloseInformer) Close() error { err := w.wc.Close() close(w.close) return err }
go
func (w *writeCloseInformer) Close() error { err := w.wc.Close() close(w.close) return err }
[ "func", "(", "w", "*", "writeCloseInformer", ")", "Close", "(", ")", "error", "{", "err", ":=", "w", ".", "wc", ".", "Close", "(", ")", "\n", "close", "(", "w", ".", "close", ")", "\n", "return", "err", "\n", "}" ]
// Close closes the internal write closer and inform the close channel.
[ "Close", "closes", "the", "internal", "write", "closer", "and", "inform", "the", "close", "channel", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L47-L51
train
cri-o/cri-o
utils/ioutil/write_closer.go
Write
func (n *nopWriteCloser) Write(p []byte) (int, error) { return n.w.Write(p) }
go
func (n *nopWriteCloser) Write(p []byte) (int, error) { return n.w.Write(p) }
[ "func", "(", "n", "*", "nopWriteCloser", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "n", ".", "w", ".", "Write", "(", "p", ")", "\n", "}" ]
// Write passes through the data into the internal writer.
[ "Write", "passes", "through", "the", "data", "into", "the", "internal", "writer", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L64-L66
train
cri-o/cri-o
utils/ioutil/write_closer.go
Write
func (s *serialWriteCloser) Write(data []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() return s.wc.Write(data) }
go
func (s *serialWriteCloser) Write(data []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() return s.wc.Write(data) }
[ "func", "(", "s", "*", "serialWriteCloser", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "wc", ".", "Write", "(", "data", ")", "\n", "}" ]
// Write writes a group of byte arrays in order atomically.
[ "Write", "writes", "a", "group", "of", "byte", "arrays", "in", "order", "atomically", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L91-L95
train
cri-o/cri-o
utils/ioutil/write_closer.go
Close
func (s *serialWriteCloser) Close() error { s.mu.Lock() defer s.mu.Unlock() return s.wc.Close() }
go
func (s *serialWriteCloser) Close() error { s.mu.Lock() defer s.mu.Unlock() return s.wc.Close() }
[ "func", "(", "s", "*", "serialWriteCloser", ")", "Close", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "wc", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the write closer.
[ "Close", "closes", "the", "write", "closer", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/write_closer.go#L98-L102
train
cri-o/cri-o
pkg/seccomp/seccomp.go
IsEnabled
func IsEnabled() bool { enabled := false // Check if Seccomp is supported, via CONFIG_SECCOMP. if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { // Make sure the kernel has CONFIG_SECCOMP_FILTER. if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { enabled = true } } logrus.Debugf("seccomp status: %v", enabled) return enabled }
go
func IsEnabled() bool { enabled := false // Check if Seccomp is supported, via CONFIG_SECCOMP. if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { // Make sure the kernel has CONFIG_SECCOMP_FILTER. if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { enabled = true } } logrus.Debugf("seccomp status: %v", enabled) return enabled }
[ "func", "IsEnabled", "(", ")", "bool", "{", "enabled", ":=", "false", "\n", "if", "err", ":=", "unix", ".", "Prctl", "(", "unix", ".", "PR_GET_SECCOMP", ",", "0", ",", "0", ",", "0", ",", "0", ")", ";", "err", "!=", "unix", ".", "EINVAL", "{", "if", "err", ":=", "unix", ".", "Prctl", "(", "unix", ".", "PR_SET_SECCOMP", ",", "unix", ".", "SECCOMP_MODE_FILTER", ",", "0", ",", "0", ",", "0", ")", ";", "err", "!=", "unix", ".", "EINVAL", "{", "enabled", "=", "true", "\n", "}", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"seccomp status: %v\"", ",", "enabled", ")", "\n", "return", "enabled", "\n", "}" ]
// IsEnabled returns true if seccomp is enabled for the host.
[ "IsEnabled", "returns", "true", "if", "seccomp", "is", "enabled", "for", "the", "host", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/pkg/seccomp/seccomp.go#L19-L30
train
cri-o/cri-o
pkg/seccomp/seccomp.go
LoadProfileFromStruct
func LoadProfileFromStruct(config *Seccomp, specgen *generate.Generator) error { return setupSeccomp(config, specgen) }
go
func LoadProfileFromStruct(config *Seccomp, specgen *generate.Generator) error { return setupSeccomp(config, specgen) }
[ "func", "LoadProfileFromStruct", "(", "config", "*", "Seccomp", ",", "specgen", "*", "generate", ".", "Generator", ")", "error", "{", "return", "setupSeccomp", "(", "config", ",", "specgen", ")", "\n", "}" ]
// LoadProfileFromStruct takes a Seccomp struct and setup seccomp in the spec.
[ "LoadProfileFromStruct", "takes", "a", "Seccomp", "struct", "and", "setup", "seccomp", "in", "the", "spec", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/pkg/seccomp/seccomp.go#L33-L35
train
cri-o/cri-o
pkg/seccomp/seccomp.go
LoadProfileFromBytes
func LoadProfileFromBytes(body []byte, specgen *generate.Generator) error { config := &Seccomp{} if err := json.Unmarshal(body, config); err != nil { return fmt.Errorf("decoding seccomp profile failed: %v", err) } return setupSeccomp(config, specgen) }
go
func LoadProfileFromBytes(body []byte, specgen *generate.Generator) error { config := &Seccomp{} if err := json.Unmarshal(body, config); err != nil { return fmt.Errorf("decoding seccomp profile failed: %v", err) } return setupSeccomp(config, specgen) }
[ "func", "LoadProfileFromBytes", "(", "body", "[", "]", "byte", ",", "specgen", "*", "generate", ".", "Generator", ")", "error", "{", "config", ":=", "&", "Seccomp", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "config", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"decoding seccomp profile failed: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "setupSeccomp", "(", "config", ",", "specgen", ")", "\n", "}" ]
// LoadProfileFromBytes takes a byte slice and decodes the seccomp profile.
[ "LoadProfileFromBytes", "takes", "a", "byte", "slice", "and", "decodes", "the", "seccomp", "profile", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/pkg/seccomp/seccomp.go#L38-L44
train
cri-o/cri-o
lib/remove.go
Remove
func (c *ContainerServer) Remove(ctx context.Context, container string, force bool) (string, error) { ctr, err := c.LookupContainer(container) if err != nil { return "", err } ctrID := ctr.ID() cStatus := ctr.State() switch cStatus.Status { case oci.ContainerStatePaused: return "", errors.Errorf("cannot remove paused container %s", ctrID) case oci.ContainerStateCreated, oci.ContainerStateRunning: if force { _, err = c.ContainerStop(ctx, container, 10) if err != nil { return "", errors.Wrapf(err, "unable to stop container %s", ctrID) } } else { return "", errors.Errorf("cannot remove running container %s", ctrID) } } if err := c.runtime.DeleteContainer(ctr); err != nil { return "", errors.Wrapf(err, "failed to delete container %s", ctrID) } if err := os.Remove(filepath.Join(c.Config().RuntimeConfig.ContainerExitsDir, ctrID)); err != nil && !os.IsNotExist(err) { return "", errors.Wrapf(err, "failed to remove container exit file %s", ctrID) } c.RemoveContainer(ctr) if err := c.storageRuntimeServer.DeleteContainer(ctrID); err != nil { return "", errors.Wrapf(err, "failed to delete storage for container %s", ctrID) } c.ReleaseContainerName(ctr.Name()) if err := c.ctrIDIndex.Delete(ctrID); err != nil { return "", err } return ctrID, nil }
go
func (c *ContainerServer) Remove(ctx context.Context, container string, force bool) (string, error) { ctr, err := c.LookupContainer(container) if err != nil { return "", err } ctrID := ctr.ID() cStatus := ctr.State() switch cStatus.Status { case oci.ContainerStatePaused: return "", errors.Errorf("cannot remove paused container %s", ctrID) case oci.ContainerStateCreated, oci.ContainerStateRunning: if force { _, err = c.ContainerStop(ctx, container, 10) if err != nil { return "", errors.Wrapf(err, "unable to stop container %s", ctrID) } } else { return "", errors.Errorf("cannot remove running container %s", ctrID) } } if err := c.runtime.DeleteContainer(ctr); err != nil { return "", errors.Wrapf(err, "failed to delete container %s", ctrID) } if err := os.Remove(filepath.Join(c.Config().RuntimeConfig.ContainerExitsDir, ctrID)); err != nil && !os.IsNotExist(err) { return "", errors.Wrapf(err, "failed to remove container exit file %s", ctrID) } c.RemoveContainer(ctr) if err := c.storageRuntimeServer.DeleteContainer(ctrID); err != nil { return "", errors.Wrapf(err, "failed to delete storage for container %s", ctrID) } c.ReleaseContainerName(ctr.Name()) if err := c.ctrIDIndex.Delete(ctrID); err != nil { return "", err } return ctrID, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "Remove", "(", "ctx", "context", ".", "Context", ",", "container", "string", ",", "force", "bool", ")", "(", "string", ",", "error", ")", "{", "ctr", ",", "err", ":=", "c", ".", "LookupContainer", "(", "container", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "ctrID", ":=", "ctr", ".", "ID", "(", ")", "\n", "cStatus", ":=", "ctr", ".", "State", "(", ")", "\n", "switch", "cStatus", ".", "Status", "{", "case", "oci", ".", "ContainerStatePaused", ":", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"cannot remove paused container %s\"", ",", "ctrID", ")", "\n", "case", "oci", ".", "ContainerStateCreated", ",", "oci", ".", "ContainerStateRunning", ":", "if", "force", "{", "_", ",", "err", "=", "c", ".", "ContainerStop", "(", "ctx", ",", "container", ",", "10", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"unable to stop container %s\"", ",", "ctrID", ")", "\n", "}", "\n", "}", "else", "{", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"cannot remove running container %s\"", ",", "ctrID", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "c", ".", "runtime", ".", "DeleteContainer", "(", "ctr", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"failed to delete container %s\"", ",", "ctrID", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "filepath", ".", "Join", "(", "c", ".", "Config", "(", ")", ".", "RuntimeConfig", ".", "ContainerExitsDir", ",", "ctrID", ")", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"failed to remove container exit file %s\"", ",", "ctrID", ")", "\n", "}", "\n", "c", ".", "RemoveContainer", "(", "ctr", ")", "\n", "if", "err", ":=", "c", ".", "storageRuntimeServer", ".", "DeleteContainer", "(", "ctrID", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"failed to delete storage for container %s\"", ",", "ctrID", ")", "\n", "}", "\n", "c", ".", "ReleaseContainerName", "(", "ctr", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "c", ".", "ctrIDIndex", ".", "Delete", "(", "ctrID", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "ctrID", ",", "nil", "\n", "}" ]
// Remove removes a container
[ "Remove", "removes", "a", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/remove.go#L13-L53
train
cri-o/cri-o
utils/typeurl/types.go
Register
func Register(v interface{}, args ...string) { var ( t = tryDereference(v) p = path.Join(args...) ) mu.Lock() defer mu.Unlock() if et, ok := registry[t]; ok { if et != p { panic(errors.Errorf("type registred with alternate path %q != %q", et, p)) } return } registry[t] = p }
go
func Register(v interface{}, args ...string) { var ( t = tryDereference(v) p = path.Join(args...) ) mu.Lock() defer mu.Unlock() if et, ok := registry[t]; ok { if et != p { panic(errors.Errorf("type registred with alternate path %q != %q", et, p)) } return } registry[t] = p }
[ "func", "Register", "(", "v", "interface", "{", "}", ",", "args", "...", "string", ")", "{", "var", "(", "t", "=", "tryDereference", "(", "v", ")", "\n", "p", "=", "path", ".", "Join", "(", "args", "...", ")", "\n", ")", "\n", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "if", "et", ",", "ok", ":=", "registry", "[", "t", "]", ";", "ok", "{", "if", "et", "!=", "p", "{", "panic", "(", "errors", ".", "Errorf", "(", "\"type registred with alternate path %q != %q\"", ",", "et", ",", "p", ")", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "registry", "[", "t", "]", "=", "p", "\n", "}" ]
// Register a type with the base url of the type
[ "Register", "a", "type", "with", "the", "base", "url", "of", "the", "type" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/typeurl/types.go#L38-L52
train
cri-o/cri-o
utils/typeurl/types.go
Is
func Is(any *types.Any, v interface{}) bool { // call to check that v is a pointer tryDereference(v) url, err := TypeURL(v) if err != nil { return false } return any.TypeUrl == url }
go
func Is(any *types.Any, v interface{}) bool { // call to check that v is a pointer tryDereference(v) url, err := TypeURL(v) if err != nil { return false } return any.TypeUrl == url }
[ "func", "Is", "(", "any", "*", "types", ".", "Any", ",", "v", "interface", "{", "}", ")", "bool", "{", "tryDereference", "(", "v", ")", "\n", "url", ",", "err", ":=", "TypeURL", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "any", ".", "TypeUrl", "==", "url", "\n", "}" ]
// Is returns true if the type of the Any is the same as v
[ "Is", "returns", "true", "if", "the", "type", "of", "the", "Any", "is", "the", "same", "as", "v" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/typeurl/types.go#L71-L79
train
cri-o/cri-o
utils/typeurl/types.go
MarshalAny
func MarshalAny(v interface{}) (*types.Any, error) { var marshal func(v interface{}) ([]byte, error) switch t := v.(type) { case *types.Any: // avoid reserializing the type if we have an any. return t, nil case proto.Message: marshal = func(v interface{}) ([]byte, error) { return proto.Marshal(t) } default: marshal = json.Marshal } url, err := TypeURL(v) if err != nil { return nil, err } data, err := marshal(v) if err != nil { return nil, err } return &types.Any{ TypeUrl: url, Value: data, }, nil }
go
func MarshalAny(v interface{}) (*types.Any, error) { var marshal func(v interface{}) ([]byte, error) switch t := v.(type) { case *types.Any: // avoid reserializing the type if we have an any. return t, nil case proto.Message: marshal = func(v interface{}) ([]byte, error) { return proto.Marshal(t) } default: marshal = json.Marshal } url, err := TypeURL(v) if err != nil { return nil, err } data, err := marshal(v) if err != nil { return nil, err } return &types.Any{ TypeUrl: url, Value: data, }, nil }
[ "func", "MarshalAny", "(", "v", "interface", "{", "}", ")", "(", "*", "types", ".", "Any", ",", "error", ")", "{", "var", "marshal", "func", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "\n", "switch", "t", ":=", "v", ".", "(", "type", ")", "{", "case", "*", "types", ".", "Any", ":", "return", "t", ",", "nil", "\n", "case", "proto", ".", "Message", ":", "marshal", "=", "func", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "proto", ".", "Marshal", "(", "t", ")", "\n", "}", "\n", "default", ":", "marshal", "=", "json", ".", "Marshal", "\n", "}", "\n", "url", ",", "err", ":=", "TypeURL", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "data", ",", "err", ":=", "marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "types", ".", "Any", "{", "TypeUrl", ":", "url", ",", "Value", ":", "data", ",", "}", ",", "nil", "\n", "}" ]
// MarshalAny marshals the value v into an any with the correct TypeUrl
[ "MarshalAny", "marshals", "the", "value", "v", "into", "an", "any", "with", "the", "correct", "TypeUrl" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/typeurl/types.go#L82-L109
train
cri-o/cri-o
utils/typeurl/types.go
UnmarshalAny
func UnmarshalAny(any *types.Any) (interface{}, error) { t, err := getTypeByURL(any.TypeUrl) if err != nil { return nil, err } v := reflect.New(t.t).Interface() if t.isProto { err = proto.Unmarshal(any.Value, v.(proto.Message)) } else { err = json.Unmarshal(any.Value, v) } return v, err }
go
func UnmarshalAny(any *types.Any) (interface{}, error) { t, err := getTypeByURL(any.TypeUrl) if err != nil { return nil, err } v := reflect.New(t.t).Interface() if t.isProto { err = proto.Unmarshal(any.Value, v.(proto.Message)) } else { err = json.Unmarshal(any.Value, v) } return v, err }
[ "func", "UnmarshalAny", "(", "any", "*", "types", ".", "Any", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "t", ",", "err", ":=", "getTypeByURL", "(", "any", ".", "TypeUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "v", ":=", "reflect", ".", "New", "(", "t", ".", "t", ")", ".", "Interface", "(", ")", "\n", "if", "t", ".", "isProto", "{", "err", "=", "proto", ".", "Unmarshal", "(", "any", ".", "Value", ",", "v", ".", "(", "proto", ".", "Message", ")", ")", "\n", "}", "else", "{", "err", "=", "json", ".", "Unmarshal", "(", "any", ".", "Value", ",", "v", ")", "\n", "}", "\n", "return", "v", ",", "err", "\n", "}" ]
// UnmarshalAny unmarshals the any type into a concrete type
[ "UnmarshalAny", "unmarshals", "the", "any", "type", "into", "a", "concrete", "type" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/typeurl/types.go#L112-L124
train
cri-o/cri-o
server/container_create.go
resolveSymbolicLink
func resolveSymbolicLink(path, scope string) (string, error) { info, err := os.Lstat(path) if err != nil { return "", err } if info.Mode()&os.ModeSymlink != os.ModeSymlink { return path, nil } if scope == "" { scope = "/" } return symlink.FollowSymlinkInScope(path, scope) }
go
func resolveSymbolicLink(path, scope string) (string, error) { info, err := os.Lstat(path) if err != nil { return "", err } if info.Mode()&os.ModeSymlink != os.ModeSymlink { return path, nil } if scope == "" { scope = "/" } return symlink.FollowSymlinkInScope(path, scope) }
[ "func", "resolveSymbolicLink", "(", "path", ",", "scope", "string", ")", "(", "string", ",", "error", ")", "{", "info", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "if", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "os", ".", "ModeSymlink", "{", "return", "path", ",", "nil", "\n", "}", "\n", "if", "scope", "==", "\"\"", "{", "scope", "=", "\"/\"", "\n", "}", "\n", "return", "symlink", ".", "FollowSymlinkInScope", "(", "path", ",", "scope", ")", "\n", "}" ]
// resolveSymbolicLink resolves a possbile symlink path. If the path is a symlink, returns resolved // path; if not, returns the original path.
[ "resolveSymbolicLink", "resolves", "a", "possbile", "symlink", "path", ".", "If", "the", "path", "is", "a", "symlink", "returns", "resolved", "path", ";", "if", "not", "returns", "the", "original", "path", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L202-L214
train
cri-o/cri-o
server/container_create.go
buildOCIProcessArgs
func buildOCIProcessArgs(containerKubeConfig *pb.ContainerConfig, imageOCIConfig *v1.Image) ([]string, error) { // # Start the nginx container using the default command, but use custom // arguments (arg1 .. argN) for that command. // kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN> // # Start the nginx container using a different command and custom arguments. // kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN> kubeCommands := containerKubeConfig.Command kubeArgs := containerKubeConfig.Args // merge image config and kube config // same as docker does today... if imageOCIConfig != nil { if len(kubeCommands) == 0 { if len(kubeArgs) == 0 { kubeArgs = imageOCIConfig.Config.Cmd } if kubeCommands == nil { kubeCommands = imageOCIConfig.Config.Entrypoint } } } if len(kubeCommands) == 0 && len(kubeArgs) == 0 { return nil, fmt.Errorf("no command specified") } // create entrypoint and args var entrypoint string var args []string if len(kubeCommands) != 0 { entrypoint = kubeCommands[0] args = append(kubeCommands[1:], kubeArgs...) } else { entrypoint = kubeArgs[0] args = kubeArgs[1:] } processArgs := append([]string{entrypoint}, args...) logrus.Debugf("OCI process args %v", processArgs) return processArgs, nil }
go
func buildOCIProcessArgs(containerKubeConfig *pb.ContainerConfig, imageOCIConfig *v1.Image) ([]string, error) { // # Start the nginx container using the default command, but use custom // arguments (arg1 .. argN) for that command. // kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN> // # Start the nginx container using a different command and custom arguments. // kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN> kubeCommands := containerKubeConfig.Command kubeArgs := containerKubeConfig.Args // merge image config and kube config // same as docker does today... if imageOCIConfig != nil { if len(kubeCommands) == 0 { if len(kubeArgs) == 0 { kubeArgs = imageOCIConfig.Config.Cmd } if kubeCommands == nil { kubeCommands = imageOCIConfig.Config.Entrypoint } } } if len(kubeCommands) == 0 && len(kubeArgs) == 0 { return nil, fmt.Errorf("no command specified") } // create entrypoint and args var entrypoint string var args []string if len(kubeCommands) != 0 { entrypoint = kubeCommands[0] args = append(kubeCommands[1:], kubeArgs...) } else { entrypoint = kubeArgs[0] args = kubeArgs[1:] } processArgs := append([]string{entrypoint}, args...) logrus.Debugf("OCI process args %v", processArgs) return processArgs, nil }
[ "func", "buildOCIProcessArgs", "(", "containerKubeConfig", "*", "pb", ".", "ContainerConfig", ",", "imageOCIConfig", "*", "v1", ".", "Image", ")", "(", "[", "]", "string", ",", "error", ")", "{", "kubeCommands", ":=", "containerKubeConfig", ".", "Command", "\n", "kubeArgs", ":=", "containerKubeConfig", ".", "Args", "\n", "if", "imageOCIConfig", "!=", "nil", "{", "if", "len", "(", "kubeCommands", ")", "==", "0", "{", "if", "len", "(", "kubeArgs", ")", "==", "0", "{", "kubeArgs", "=", "imageOCIConfig", ".", "Config", ".", "Cmd", "\n", "}", "\n", "if", "kubeCommands", "==", "nil", "{", "kubeCommands", "=", "imageOCIConfig", ".", "Config", ".", "Entrypoint", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "kubeCommands", ")", "==", "0", "&&", "len", "(", "kubeArgs", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no command specified\"", ")", "\n", "}", "\n", "var", "entrypoint", "string", "\n", "var", "args", "[", "]", "string", "\n", "if", "len", "(", "kubeCommands", ")", "!=", "0", "{", "entrypoint", "=", "kubeCommands", "[", "0", "]", "\n", "args", "=", "append", "(", "kubeCommands", "[", "1", ":", "]", ",", "kubeArgs", "...", ")", "\n", "}", "else", "{", "entrypoint", "=", "kubeArgs", "[", "0", "]", "\n", "args", "=", "kubeArgs", "[", "1", ":", "]", "\n", "}", "\n", "processArgs", ":=", "append", "(", "[", "]", "string", "{", "entrypoint", "}", ",", "args", "...", ")", "\n", "logrus", ".", "Debugf", "(", "\"OCI process args %v\"", ",", "processArgs", ")", "\n", "return", "processArgs", ",", "nil", "\n", "}" ]
// buildOCIProcessArgs build an OCI compatible process arguments slice.
[ "buildOCIProcessArgs", "build", "an", "OCI", "compatible", "process", "arguments", "slice", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L221-L265
train
cri-o/cri-o
server/container_create.go
setupContainerUser
func setupContainerUser(specgen *generate.Generator, rootfs, mountLabel, ctrRunDir string, sc *pb.LinuxContainerSecurityContext, imageConfig *v1.Image) error { if sc == nil { return nil } if sc.GetRunAsGroup() != nil && sc.GetRunAsUser() == nil && sc.GetRunAsUsername() == "" { return fmt.Errorf("user group is specified without user or username") } imageUser := "" if imageConfig != nil { imageUser = imageConfig.Config.User } containerUser := generateUserString( sc.GetRunAsUsername(), imageUser, sc.GetRunAsUser(), ) logrus.Debugf("CONTAINER USER: %+v", containerUser) // Add uid, gid and groups from user uid, gid, addGroups, err := utils.GetUserInfo(rootfs, containerUser) if err != nil { return err } // verify uid exists in containers /etc/passwd, else generate a passwd with the user entry passwdPath, err := utils.GeneratePasswd(uid, gid, rootfs, ctrRunDir) if err != nil { return err } if passwdPath != "" { if err := securityLabel(passwdPath, mountLabel, false); err != nil { return err } mnt := rspec.Mount{ Type: "bind", Source: passwdPath, Destination: "/etc/passwd", Options: []string{"ro", "bind", "nodev", "nosuid", "noexec"}, } specgen.AddMount(mnt) } specgen.SetProcessUID(uid) specgen.SetProcessGID(gid) if sc.GetRunAsGroup() != nil { specgen.SetProcessGID(uint32(sc.GetRunAsGroup().GetValue())) } for _, group := range addGroups { specgen.AddProcessAdditionalGid(group) } // Add groups from CRI groups := sc.GetSupplementalGroups() for _, group := range groups { specgen.AddProcessAdditionalGid(uint32(group)) } return nil }
go
func setupContainerUser(specgen *generate.Generator, rootfs, mountLabel, ctrRunDir string, sc *pb.LinuxContainerSecurityContext, imageConfig *v1.Image) error { if sc == nil { return nil } if sc.GetRunAsGroup() != nil && sc.GetRunAsUser() == nil && sc.GetRunAsUsername() == "" { return fmt.Errorf("user group is specified without user or username") } imageUser := "" if imageConfig != nil { imageUser = imageConfig.Config.User } containerUser := generateUserString( sc.GetRunAsUsername(), imageUser, sc.GetRunAsUser(), ) logrus.Debugf("CONTAINER USER: %+v", containerUser) // Add uid, gid and groups from user uid, gid, addGroups, err := utils.GetUserInfo(rootfs, containerUser) if err != nil { return err } // verify uid exists in containers /etc/passwd, else generate a passwd with the user entry passwdPath, err := utils.GeneratePasswd(uid, gid, rootfs, ctrRunDir) if err != nil { return err } if passwdPath != "" { if err := securityLabel(passwdPath, mountLabel, false); err != nil { return err } mnt := rspec.Mount{ Type: "bind", Source: passwdPath, Destination: "/etc/passwd", Options: []string{"ro", "bind", "nodev", "nosuid", "noexec"}, } specgen.AddMount(mnt) } specgen.SetProcessUID(uid) specgen.SetProcessGID(gid) if sc.GetRunAsGroup() != nil { specgen.SetProcessGID(uint32(sc.GetRunAsGroup().GetValue())) } for _, group := range addGroups { specgen.AddProcessAdditionalGid(group) } // Add groups from CRI groups := sc.GetSupplementalGroups() for _, group := range groups { specgen.AddProcessAdditionalGid(uint32(group)) } return nil }
[ "func", "setupContainerUser", "(", "specgen", "*", "generate", ".", "Generator", ",", "rootfs", ",", "mountLabel", ",", "ctrRunDir", "string", ",", "sc", "*", "pb", ".", "LinuxContainerSecurityContext", ",", "imageConfig", "*", "v1", ".", "Image", ")", "error", "{", "if", "sc", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "sc", ".", "GetRunAsGroup", "(", ")", "!=", "nil", "&&", "sc", ".", "GetRunAsUser", "(", ")", "==", "nil", "&&", "sc", ".", "GetRunAsUsername", "(", ")", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"user group is specified without user or username\"", ")", "\n", "}", "\n", "imageUser", ":=", "\"\"", "\n", "if", "imageConfig", "!=", "nil", "{", "imageUser", "=", "imageConfig", ".", "Config", ".", "User", "\n", "}", "\n", "containerUser", ":=", "generateUserString", "(", "sc", ".", "GetRunAsUsername", "(", ")", ",", "imageUser", ",", "sc", ".", "GetRunAsUser", "(", ")", ",", ")", "\n", "logrus", ".", "Debugf", "(", "\"CONTAINER USER: %+v\"", ",", "containerUser", ")", "\n", "uid", ",", "gid", ",", "addGroups", ",", "err", ":=", "utils", ".", "GetUserInfo", "(", "rootfs", ",", "containerUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "passwdPath", ",", "err", ":=", "utils", ".", "GeneratePasswd", "(", "uid", ",", "gid", ",", "rootfs", ",", "ctrRunDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "passwdPath", "!=", "\"\"", "{", "if", "err", ":=", "securityLabel", "(", "passwdPath", ",", "mountLabel", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "mnt", ":=", "rspec", ".", "Mount", "{", "Type", ":", "\"bind\"", ",", "Source", ":", "passwdPath", ",", "Destination", ":", "\"/etc/passwd\"", ",", "Options", ":", "[", "]", "string", "{", "\"ro\"", ",", "\"bind\"", ",", "\"nodev\"", ",", "\"nosuid\"", ",", "\"noexec\"", "}", ",", "}", "\n", "specgen", ".", "AddMount", "(", "mnt", ")", "\n", "}", "\n", "specgen", ".", "SetProcessUID", "(", "uid", ")", "\n", "specgen", ".", "SetProcessGID", "(", "gid", ")", "\n", "if", "sc", ".", "GetRunAsGroup", "(", ")", "!=", "nil", "{", "specgen", ".", "SetProcessGID", "(", "uint32", "(", "sc", ".", "GetRunAsGroup", "(", ")", ".", "GetValue", "(", ")", ")", ")", "\n", "}", "\n", "for", "_", ",", "group", ":=", "range", "addGroups", "{", "specgen", ".", "AddProcessAdditionalGid", "(", "group", ")", "\n", "}", "\n", "groups", ":=", "sc", ".", "GetSupplementalGroups", "(", ")", "\n", "for", "_", ",", "group", ":=", "range", "groups", "{", "specgen", ".", "AddProcessAdditionalGid", "(", "uint32", "(", "group", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setupContainerUser sets the UID, GID and supplemental groups in OCI runtime config
[ "setupContainerUser", "sets", "the", "UID", "GID", "and", "supplemental", "groups", "in", "OCI", "runtime", "config" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L268-L327
train
cri-o/cri-o
server/container_create.go
generateUserString
func generateUserString(username, imageUser string, uid *pb.Int64Value) string { var userstr string if uid != nil { userstr = strconv.FormatInt(uid.GetValue(), 10) } if username != "" { userstr = username } // We use the user from the image config if nothing is provided if userstr == "" { userstr = imageUser } if userstr == "" { return "" } return userstr }
go
func generateUserString(username, imageUser string, uid *pb.Int64Value) string { var userstr string if uid != nil { userstr = strconv.FormatInt(uid.GetValue(), 10) } if username != "" { userstr = username } // We use the user from the image config if nothing is provided if userstr == "" { userstr = imageUser } if userstr == "" { return "" } return userstr }
[ "func", "generateUserString", "(", "username", ",", "imageUser", "string", ",", "uid", "*", "pb", ".", "Int64Value", ")", "string", "{", "var", "userstr", "string", "\n", "if", "uid", "!=", "nil", "{", "userstr", "=", "strconv", ".", "FormatInt", "(", "uid", ".", "GetValue", "(", ")", ",", "10", ")", "\n", "}", "\n", "if", "username", "!=", "\"\"", "{", "userstr", "=", "username", "\n", "}", "\n", "if", "userstr", "==", "\"\"", "{", "userstr", "=", "imageUser", "\n", "}", "\n", "if", "userstr", "==", "\"\"", "{", "return", "\"\"", "\n", "}", "\n", "return", "userstr", "\n", "}" ]
// generateUserString generates valid user string based on OCI Image Spec v1.0.0.
[ "generateUserString", "generates", "valid", "user", "string", "based", "on", "OCI", "Image", "Spec", "v1", ".", "0", ".", "0", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L330-L346
train
cri-o/cri-o
server/container_create.go
addSecretsBindMounts
func addSecretsBindMounts(mountLabel, ctrRunDir string, defaultMounts []string, specgen generate.Generator) ([]rspec.Mount, error) { containerMounts := specgen.Config.Mounts mounts, err := secretMounts(defaultMounts, mountLabel, ctrRunDir, containerMounts) if err != nil { return nil, err } return mounts, nil }
go
func addSecretsBindMounts(mountLabel, ctrRunDir string, defaultMounts []string, specgen generate.Generator) ([]rspec.Mount, error) { containerMounts := specgen.Config.Mounts mounts, err := secretMounts(defaultMounts, mountLabel, ctrRunDir, containerMounts) if err != nil { return nil, err } return mounts, nil }
[ "func", "addSecretsBindMounts", "(", "mountLabel", ",", "ctrRunDir", "string", ",", "defaultMounts", "[", "]", "string", ",", "specgen", "generate", ".", "Generator", ")", "(", "[", "]", "rspec", ".", "Mount", ",", "error", ")", "{", "containerMounts", ":=", "specgen", ".", "Config", ".", "Mounts", "\n", "mounts", ",", "err", ":=", "secretMounts", "(", "defaultMounts", ",", "mountLabel", ",", "ctrRunDir", ",", "containerMounts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mounts", ",", "nil", "\n", "}" ]
// addSecretsBindMounts mounts user defined secrets to the container
[ "addSecretsBindMounts", "mounts", "user", "defined", "secrets", "to", "the", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L482-L489
train
cri-o/cri-o
server/container_create.go
getAppArmorProfileName
func (s *Server) getAppArmorProfileName(profile string) string { if profile == "" { return "" } if profile == apparmorRuntimeDefault { // If the value is runtime/default, then return default profile. return s.appArmorProfile } return strings.TrimPrefix(profile, apparmorLocalHostPrefix) }
go
func (s *Server) getAppArmorProfileName(profile string) string { if profile == "" { return "" } if profile == apparmorRuntimeDefault { // If the value is runtime/default, then return default profile. return s.appArmorProfile } return strings.TrimPrefix(profile, apparmorLocalHostPrefix) }
[ "func", "(", "s", "*", "Server", ")", "getAppArmorProfileName", "(", "profile", "string", ")", "string", "{", "if", "profile", "==", "\"\"", "{", "return", "\"\"", "\n", "}", "\n", "if", "profile", "==", "apparmorRuntimeDefault", "{", "return", "s", ".", "appArmorProfile", "\n", "}", "\n", "return", "strings", ".", "TrimPrefix", "(", "profile", ",", "apparmorLocalHostPrefix", ")", "\n", "}" ]
// getAppArmorProfileName gets the profile name for the given container.
[ "getAppArmorProfileName", "gets", "the", "profile", "name", "for", "the", "given", "container", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_create.go#L640-L651
train
cri-o/cri-o
pkg/storage/runtime.go
GetRuntimeService
func GetRuntimeService(ctx context.Context, storageImageServer ImageServer, pauseImage, pauseImageAuthFile string) RuntimeServer { return &runtimeService{ storageImageServer: storageImageServer, pauseImage: pauseImage, pauseImageAuthFile: pauseImageAuthFile, ctx: ctx, } }
go
func GetRuntimeService(ctx context.Context, storageImageServer ImageServer, pauseImage, pauseImageAuthFile string) RuntimeServer { return &runtimeService{ storageImageServer: storageImageServer, pauseImage: pauseImage, pauseImageAuthFile: pauseImageAuthFile, ctx: ctx, } }
[ "func", "GetRuntimeService", "(", "ctx", "context", ".", "Context", ",", "storageImageServer", "ImageServer", ",", "pauseImage", ",", "pauseImageAuthFile", "string", ")", "RuntimeServer", "{", "return", "&", "runtimeService", "{", "storageImageServer", ":", "storageImageServer", ",", "pauseImage", ":", "pauseImage", ",", "pauseImageAuthFile", ":", "pauseImageAuthFile", ",", "ctx", ":", "ctx", ",", "}", "\n", "}" ]
// GetRuntimeService returns a RuntimeServer that uses the passed-in image // service to pull and manage images, and its store to manage containers based // on those images.
[ "GetRuntimeService", "returns", "a", "RuntimeServer", "that", "uses", "the", "passed", "-", "in", "image", "service", "to", "pull", "and", "manage", "images", "and", "its", "store", "to", "manage", "containers", "based", "on", "those", "images", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/pkg/storage/runtime.go#L469-L476
train
cri-o/cri-o
lib/sandbox/memory_store.go
List
func (c *memoryStore) List() []*Sandbox { sandboxes := History(c.all()) sandboxes.sort() return sandboxes }
go
func (c *memoryStore) List() []*Sandbox { sandboxes := History(c.all()) sandboxes.sort() return sandboxes }
[ "func", "(", "c", "*", "memoryStore", ")", "List", "(", ")", "[", "]", "*", "Sandbox", "{", "sandboxes", ":=", "History", "(", "c", ".", "all", "(", ")", ")", "\n", "sandboxes", ".", "sort", "(", ")", "\n", "return", "sandboxes", "\n", "}" ]
// List returns a sorted list of sandboxes from the store. // The sandboxes are ordered by creation date.
[ "List", "returns", "a", "sorted", "list", "of", "sandboxes", "from", "the", "store", ".", "The", "sandboxes", "are", "ordered", "by", "creation", "date", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/memory_store.go#L44-L48
train
cri-o/cri-o
lib/sandbox/memory_store.go
First
func (c *memoryStore) First(filter StoreFilter) *Sandbox { for _, cont := range c.all() { if filter(cont) { return cont } } return nil }
go
func (c *memoryStore) First(filter StoreFilter) *Sandbox { for _, cont := range c.all() { if filter(cont) { return cont } } return nil }
[ "func", "(", "c", "*", "memoryStore", ")", "First", "(", "filter", "StoreFilter", ")", "*", "Sandbox", "{", "for", "_", ",", "cont", ":=", "range", "c", ".", "all", "(", ")", "{", "if", "filter", "(", "cont", ")", "{", "return", "cont", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// First returns the first sandbox found in the store by a given filter.
[ "First", "returns", "the", "first", "sandbox", "found", "in", "the", "store", "by", "a", "given", "filter", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/memory_store.go#L58-L65
train
cri-o/cri-o
lib/rename.go
ContainerRename
func (c *ContainerServer) ContainerRename(container, name string) error { ctr, err := c.LookupContainer(container) if err != nil { return err } oldName := ctr.Name() _, err = c.ReserveContainerName(ctr.ID(), name) if err != nil { return err } defer func() { if err != nil { c.ReleaseContainerName(name) } else { c.ReleaseContainerName(oldName) } }() // Update state.json if err = c.updateStateName(ctr, name); err != nil { return err } // Update config.json configRuntimePath := filepath.Join(ctr.BundlePath(), configFile) if err = updateConfigName(configRuntimePath, name); err != nil { return err } configStoragePath := filepath.Join(ctr.Dir(), configFile) if err = updateConfigName(configStoragePath, name); err != nil { return err } // Update containers.json if err = c.store.SetNames(ctr.ID(), []string{name}); err != nil { return err } return nil }
go
func (c *ContainerServer) ContainerRename(container, name string) error { ctr, err := c.LookupContainer(container) if err != nil { return err } oldName := ctr.Name() _, err = c.ReserveContainerName(ctr.ID(), name) if err != nil { return err } defer func() { if err != nil { c.ReleaseContainerName(name) } else { c.ReleaseContainerName(oldName) } }() // Update state.json if err = c.updateStateName(ctr, name); err != nil { return err } // Update config.json configRuntimePath := filepath.Join(ctr.BundlePath(), configFile) if err = updateConfigName(configRuntimePath, name); err != nil { return err } configStoragePath := filepath.Join(ctr.Dir(), configFile) if err = updateConfigName(configStoragePath, name); err != nil { return err } // Update containers.json if err = c.store.SetNames(ctr.ID(), []string{name}); err != nil { return err } return nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ContainerRename", "(", "container", ",", "name", "string", ")", "error", "{", "ctr", ",", "err", ":=", "c", ".", "LookupContainer", "(", "container", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "oldName", ":=", "ctr", ".", "Name", "(", ")", "\n", "_", ",", "err", "=", "c", ".", "ReserveContainerName", "(", "ctr", ".", "ID", "(", ")", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "c", ".", "ReleaseContainerName", "(", "name", ")", "\n", "}", "else", "{", "c", ".", "ReleaseContainerName", "(", "oldName", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", "=", "c", ".", "updateStateName", "(", "ctr", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "configRuntimePath", ":=", "filepath", ".", "Join", "(", "ctr", ".", "BundlePath", "(", ")", ",", "configFile", ")", "\n", "if", "err", "=", "updateConfigName", "(", "configRuntimePath", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "configStoragePath", ":=", "filepath", ".", "Join", "(", "ctr", ".", "Dir", "(", ")", ",", "configFile", ")", "\n", "if", "err", "=", "updateConfigName", "(", "configStoragePath", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "c", ".", "store", ".", "SetNames", "(", "ctr", ".", "ID", "(", ")", ",", "[", "]", "string", "{", "name", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ContainerRename renames the given container
[ "ContainerRename", "renames", "the", "given", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/rename.go#L18-L57
train
cri-o/cri-o
lib/rename.go
updateMetadata
func updateMetadata(specAnnotations map[string]string, name string) string { oldMetadata := specAnnotations[annotations.Metadata] containerType := specAnnotations[annotations.ContainerType] switch containerType { case "container": metadata := runtime.ContainerMetadata{} err := json.Unmarshal([]byte(oldMetadata), &metadata) if err != nil { return oldMetadata } metadata.Name = name m, err := json.Marshal(metadata) if err != nil { return oldMetadata } return string(m) case "sandbox": metadata := runtime.PodSandboxMetadata{} err := json.Unmarshal([]byte(oldMetadata), &metadata) if err != nil { return oldMetadata } metadata.Name = name m, err := json.Marshal(metadata) if err != nil { return oldMetadata } return string(m) default: return specAnnotations[annotations.Metadata] } }
go
func updateMetadata(specAnnotations map[string]string, name string) string { oldMetadata := specAnnotations[annotations.Metadata] containerType := specAnnotations[annotations.ContainerType] switch containerType { case "container": metadata := runtime.ContainerMetadata{} err := json.Unmarshal([]byte(oldMetadata), &metadata) if err != nil { return oldMetadata } metadata.Name = name m, err := json.Marshal(metadata) if err != nil { return oldMetadata } return string(m) case "sandbox": metadata := runtime.PodSandboxMetadata{} err := json.Unmarshal([]byte(oldMetadata), &metadata) if err != nil { return oldMetadata } metadata.Name = name m, err := json.Marshal(metadata) if err != nil { return oldMetadata } return string(m) default: return specAnnotations[annotations.Metadata] } }
[ "func", "updateMetadata", "(", "specAnnotations", "map", "[", "string", "]", "string", ",", "name", "string", ")", "string", "{", "oldMetadata", ":=", "specAnnotations", "[", "annotations", ".", "Metadata", "]", "\n", "containerType", ":=", "specAnnotations", "[", "annotations", ".", "ContainerType", "]", "\n", "switch", "containerType", "{", "case", "\"container\"", ":", "metadata", ":=", "runtime", ".", "ContainerMetadata", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "oldMetadata", ")", ",", "&", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "oldMetadata", "\n", "}", "\n", "metadata", ".", "Name", "=", "name", "\n", "m", ",", "err", ":=", "json", ".", "Marshal", "(", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "oldMetadata", "\n", "}", "\n", "return", "string", "(", "m", ")", "\n", "case", "\"sandbox\"", ":", "metadata", ":=", "runtime", ".", "PodSandboxMetadata", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "oldMetadata", ")", ",", "&", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "oldMetadata", "\n", "}", "\n", "metadata", ".", "Name", "=", "name", "\n", "m", ",", "err", ":=", "json", ".", "Marshal", "(", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "oldMetadata", "\n", "}", "\n", "return", "string", "(", "m", ")", "\n", "default", ":", "return", "specAnnotations", "[", "annotations", ".", "Metadata", "]", "\n", "}", "\n", "}" ]
// Attempts to update a metadata annotation
[ "Attempts", "to", "update", "a", "metadata", "annotation" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/rename.go#L86-L119
train
cri-o/cri-o
utils/filesystem.go
GetDiskUsageStats
func GetDiskUsageStats(path string) (dirSize, inodeCount uint64, err error) { err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error { // Walk does not follow symbolic links if err != nil { return err } dirSize += uint64(info.Size()) inodeCount++ return nil }) if err != nil { return 0, 0, err } return dirSize, inodeCount, err }
go
func GetDiskUsageStats(path string) (dirSize, inodeCount uint64, err error) { err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error { // Walk does not follow symbolic links if err != nil { return err } dirSize += uint64(info.Size()) inodeCount++ return nil }) if err != nil { return 0, 0, err } return dirSize, inodeCount, err }
[ "func", "GetDiskUsageStats", "(", "path", "string", ")", "(", "dirSize", ",", "inodeCount", "uint64", ",", "err", "error", ")", "{", "err", "=", "filepath", ".", "Walk", "(", "path", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dirSize", "+=", "uint64", "(", "info", ".", "Size", "(", ")", ")", "\n", "inodeCount", "++", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "return", "dirSize", ",", "inodeCount", ",", "err", "\n", "}" ]
// GetDiskUsageStats accepts a path to a directory or file // and returns the number of bytes and inodes used by the path
[ "GetDiskUsageStats", "accepts", "a", "path", "to", "a", "directory", "or", "file", "and", "returns", "the", "number", "of", "bytes", "and", "inodes", "used", "by", "the", "path" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/filesystem.go#L10-L28
train
cri-o/cri-o
lib/kill.go
ContainerKill
func (c *ContainerServer) ContainerKill(container string, killSignal syscall.Signal) (string, error) { ctr, err := c.LookupContainer(container) if err != nil { return "", errors.Wrapf(err, "failed to find container %s", container) } c.runtime.UpdateContainerStatus(ctr) cStatus := ctr.State() // If the container is not running, error and move on. if cStatus.Status != oci.ContainerStateRunning { return "", errors.Errorf("cannot kill container %s: it is not running", container) } if err = c.runtime.SignalContainer(ctr, killSignal); err != nil { return "", err } c.ContainerStateToDisk(ctr) return ctr.ID(), nil }
go
func (c *ContainerServer) ContainerKill(container string, killSignal syscall.Signal) (string, error) { ctr, err := c.LookupContainer(container) if err != nil { return "", errors.Wrapf(err, "failed to find container %s", container) } c.runtime.UpdateContainerStatus(ctr) cStatus := ctr.State() // If the container is not running, error and move on. if cStatus.Status != oci.ContainerStateRunning { return "", errors.Errorf("cannot kill container %s: it is not running", container) } if err = c.runtime.SignalContainer(ctr, killSignal); err != nil { return "", err } c.ContainerStateToDisk(ctr) return ctr.ID(), nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ContainerKill", "(", "container", "string", ",", "killSignal", "syscall", ".", "Signal", ")", "(", "string", ",", "error", ")", "{", "ctr", ",", "err", ":=", "c", ".", "LookupContainer", "(", "container", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"failed to find container %s\"", ",", "container", ")", "\n", "}", "\n", "c", ".", "runtime", ".", "UpdateContainerStatus", "(", "ctr", ")", "\n", "cStatus", ":=", "ctr", ".", "State", "(", ")", "\n", "if", "cStatus", ".", "Status", "!=", "oci", ".", "ContainerStateRunning", "{", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"cannot kill container %s: it is not running\"", ",", "container", ")", "\n", "}", "\n", "if", "err", "=", "c", ".", "runtime", ".", "SignalContainer", "(", "ctr", ",", "killSignal", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "c", ".", "ContainerStateToDisk", "(", "ctr", ")", "\n", "return", "ctr", ".", "ID", "(", ")", ",", "nil", "\n", "}" ]
// ContainerKill sends the user provided signal to the containers primary process.
[ "ContainerKill", "sends", "the", "user", "provided", "signal", "to", "the", "containers", "primary", "process", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/kill.go#L11-L30
train
cri-o/cri-o
lib/sandbox/sandbox_linux.go
Initialize
func (n *NetNs) Initialize() (NetNsIface, error) { netNS, err := ns.NewNS() if err != nil { return nil, err } n.netNS = netNS n.closed = false n.initialized = true return n, nil }
go
func (n *NetNs) Initialize() (NetNsIface, error) { netNS, err := ns.NewNS() if err != nil { return nil, err } n.netNS = netNS n.closed = false n.initialized = true return n, nil }
[ "func", "(", "n", "*", "NetNs", ")", "Initialize", "(", ")", "(", "NetNsIface", ",", "error", ")", "{", "netNS", ",", "err", ":=", "ns", ".", "NewNS", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "n", ".", "netNS", "=", "netNS", "\n", "n", ".", "closed", "=", "false", "\n", "n", ".", "initialized", "=", "true", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Initialize does the necessary setup for a NetNs
[ "Initialize", "does", "the", "necessary", "setup", "for", "a", "NetNs" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox_linux.go#L30-L39
train
cri-o/cri-o
lib/sandbox/sandbox_linux.go
SymlinkCreate
func (n *NetNs) SymlinkCreate(name string) error { if n.netNS == nil { return errors.New("no netns set up") } b := make([]byte, 4) _, randErr := rand.Reader.Read(b) if randErr != nil { return randErr } nsName := fmt.Sprintf("%s-%x", name, b) symlinkPath := filepath.Join(NsRunDir, nsName) if err := os.Symlink(n.Path(), symlinkPath); err != nil { return err } fd, err := os.Open(symlinkPath) if err != nil { if removeErr := os.RemoveAll(symlinkPath); removeErr != nil { return removeErr } return err } n.symlink = fd return nil }
go
func (n *NetNs) SymlinkCreate(name string) error { if n.netNS == nil { return errors.New("no netns set up") } b := make([]byte, 4) _, randErr := rand.Reader.Read(b) if randErr != nil { return randErr } nsName := fmt.Sprintf("%s-%x", name, b) symlinkPath := filepath.Join(NsRunDir, nsName) if err := os.Symlink(n.Path(), symlinkPath); err != nil { return err } fd, err := os.Open(symlinkPath) if err != nil { if removeErr := os.RemoveAll(symlinkPath); removeErr != nil { return removeErr } return err } n.symlink = fd return nil }
[ "func", "(", "n", "*", "NetNs", ")", "SymlinkCreate", "(", "name", "string", ")", "error", "{", "if", "n", ".", "netNS", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"no netns set up\"", ")", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "_", ",", "randErr", ":=", "rand", ".", "Reader", ".", "Read", "(", "b", ")", "\n", "if", "randErr", "!=", "nil", "{", "return", "randErr", "\n", "}", "\n", "nsName", ":=", "fmt", ".", "Sprintf", "(", "\"%s-%x\"", ",", "name", ",", "b", ")", "\n", "symlinkPath", ":=", "filepath", ".", "Join", "(", "NsRunDir", ",", "nsName", ")", "\n", "if", "err", ":=", "os", ".", "Symlink", "(", "n", ".", "Path", "(", ")", ",", "symlinkPath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fd", ",", "err", ":=", "os", ".", "Open", "(", "symlinkPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "removeErr", ":=", "os", ".", "RemoveAll", "(", "symlinkPath", ")", ";", "removeErr", "!=", "nil", "{", "return", "removeErr", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "n", ".", "symlink", "=", "fd", "\n", "return", "nil", "\n", "}" ]
// SymlinkCreate creates the necessary symlinks for the NetNs
[ "SymlinkCreate", "creates", "the", "necessary", "symlinks", "for", "the", "NetNs" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox_linux.go#L61-L90
train
cri-o/cri-o
lib/sandbox/sandbox_linux.go
Path
func (n *NetNs) Path() string { if n == nil || n.netNS == nil { return "" } return n.netNS.Path() }
go
func (n *NetNs) Path() string { if n == nil || n.netNS == nil { return "" } return n.netNS.Path() }
[ "func", "(", "n", "*", "NetNs", ")", "Path", "(", ")", "string", "{", "if", "n", "==", "nil", "||", "n", ".", "netNS", "==", "nil", "{", "return", "\"\"", "\n", "}", "\n", "return", "n", ".", "netNS", ".", "Path", "(", ")", "\n", "}" ]
// Path returns the path of the network namespace handle
[ "Path", "returns", "the", "path", "of", "the", "network", "namespace", "handle" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox_linux.go#L93-L98
train
cri-o/cri-o
lib/sandbox/sandbox_linux.go
Close
func (n *NetNs) Close() error { if n == nil || n.netNS == nil { return nil } return n.netNS.Close() }
go
func (n *NetNs) Close() error { if n == nil || n.netNS == nil { return nil } return n.netNS.Close() }
[ "func", "(", "n", "*", "NetNs", ")", "Close", "(", ")", "error", "{", "if", "n", "==", "nil", "||", "n", ".", "netNS", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "n", ".", "netNS", ".", "Close", "(", ")", "\n", "}" ]
// Close closes this network namespace
[ "Close", "closes", "this", "network", "namespace" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox_linux.go#L101-L106
train
cri-o/cri-o
lib/sandbox/sandbox_linux.go
Remove
func (n *NetNs) Remove() error { n.Lock() defer n.Unlock() if n.closed { // netNsRemove() can be called multiple // times without returning an error. return nil } if err := n.symlinkRemove(); err != nil { return err } if err := n.Close(); err != nil { return err } n.closed = true if n.restored { // we got namespaces in the form of // /var/run/netns/cni-0d08effa-06eb-a963-f51a-e2b0eceffc5d // but /var/run on most system is symlinked to /run so we first resolve // the symlink and then try and see if it's mounted fp, err := symlink.FollowSymlinkInScope(n.Path(), "/") if err != nil { return err } if mounted, err := mount.Mounted(fp); err == nil && mounted { if err := unix.Unmount(fp, unix.MNT_DETACH); err != nil { return err } } if n.Path() != "" { if err := os.RemoveAll(n.Path()); err != nil { return err } } } return nil }
go
func (n *NetNs) Remove() error { n.Lock() defer n.Unlock() if n.closed { // netNsRemove() can be called multiple // times without returning an error. return nil } if err := n.symlinkRemove(); err != nil { return err } if err := n.Close(); err != nil { return err } n.closed = true if n.restored { // we got namespaces in the form of // /var/run/netns/cni-0d08effa-06eb-a963-f51a-e2b0eceffc5d // but /var/run on most system is symlinked to /run so we first resolve // the symlink and then try and see if it's mounted fp, err := symlink.FollowSymlinkInScope(n.Path(), "/") if err != nil { return err } if mounted, err := mount.Mounted(fp); err == nil && mounted { if err := unix.Unmount(fp, unix.MNT_DETACH); err != nil { return err } } if n.Path() != "" { if err := os.RemoveAll(n.Path()); err != nil { return err } } } return nil }
[ "func", "(", "n", "*", "NetNs", ")", "Remove", "(", ")", "error", "{", "n", ".", "Lock", "(", ")", "\n", "defer", "n", ".", "Unlock", "(", ")", "\n", "if", "n", ".", "closed", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "n", ".", "symlinkRemove", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "n", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "n", ".", "closed", "=", "true", "\n", "if", "n", ".", "restored", "{", "fp", ",", "err", ":=", "symlink", ".", "FollowSymlinkInScope", "(", "n", ".", "Path", "(", ")", ",", "\"/\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "mounted", ",", "err", ":=", "mount", ".", "Mounted", "(", "fp", ")", ";", "err", "==", "nil", "&&", "mounted", "{", "if", "err", ":=", "unix", ".", "Unmount", "(", "fp", ",", "unix", ".", "MNT_DETACH", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "n", ".", "Path", "(", ")", "!=", "\"\"", "{", "if", "err", ":=", "os", ".", "RemoveAll", "(", "n", ".", "Path", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Remove ensures this network namespace handle is closed and removed
[ "Remove", "ensures", "this", "network", "namespace", "handle", "is", "closed", "and", "removed" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox_linux.go#L109-L152
train
cri-o/cri-o
utils/io/helpers.go
newFifos
func newFifos(root, id string, tty, stdin bool) (*cio.FIFOSet, error) { root = filepath.Join(root, "io") if err := os.MkdirAll(root, 0700); err != nil { return nil, err } fifos, err := cio.NewFIFOSetInDir(root, id, tty) if err != nil { return nil, err } if !stdin { fifos.Stdin = "" } return fifos, nil }
go
func newFifos(root, id string, tty, stdin bool) (*cio.FIFOSet, error) { root = filepath.Join(root, "io") if err := os.MkdirAll(root, 0700); err != nil { return nil, err } fifos, err := cio.NewFIFOSetInDir(root, id, tty) if err != nil { return nil, err } if !stdin { fifos.Stdin = "" } return fifos, nil }
[ "func", "newFifos", "(", "root", ",", "id", "string", ",", "tty", ",", "stdin", "bool", ")", "(", "*", "cio", ".", "FIFOSet", ",", "error", ")", "{", "root", "=", "filepath", ".", "Join", "(", "root", ",", "\"io\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "root", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fifos", ",", "err", ":=", "cio", ".", "NewFIFOSetInDir", "(", "root", ",", "id", ",", "tty", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "stdin", "{", "fifos", ".", "Stdin", "=", "\"\"", "\n", "}", "\n", "return", "fifos", ",", "nil", "\n", "}" ]
// newFifos creates fifos directory for a container.
[ "newFifos", "creates", "fifos", "directory", "for", "a", "container", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/helpers.go#L77-L90
train
cri-o/cri-o
server/container_update_resources.go
toOCIResources
func toOCIResources(r *pb.LinuxContainerResources) *rspec.LinuxResources { return &rspec.LinuxResources{ CPU: &rspec.LinuxCPU{ Shares: proto.Uint64(uint64(r.GetCpuShares())), Quota: proto.Int64(r.GetCpuQuota()), Period: proto.Uint64(uint64(r.GetCpuPeriod())), Cpus: r.GetCpusetCpus(), Mems: r.GetCpusetMems(), }, Memory: &rspec.LinuxMemory{ Limit: proto.Int64(r.GetMemoryLimitInBytes()), }, // TODO(runcom): OOMScoreAdj is missing } }
go
func toOCIResources(r *pb.LinuxContainerResources) *rspec.LinuxResources { return &rspec.LinuxResources{ CPU: &rspec.LinuxCPU{ Shares: proto.Uint64(uint64(r.GetCpuShares())), Quota: proto.Int64(r.GetCpuQuota()), Period: proto.Uint64(uint64(r.GetCpuPeriod())), Cpus: r.GetCpusetCpus(), Mems: r.GetCpusetMems(), }, Memory: &rspec.LinuxMemory{ Limit: proto.Int64(r.GetMemoryLimitInBytes()), }, // TODO(runcom): OOMScoreAdj is missing } }
[ "func", "toOCIResources", "(", "r", "*", "pb", ".", "LinuxContainerResources", ")", "*", "rspec", ".", "LinuxResources", "{", "return", "&", "rspec", ".", "LinuxResources", "{", "CPU", ":", "&", "rspec", ".", "LinuxCPU", "{", "Shares", ":", "proto", ".", "Uint64", "(", "uint64", "(", "r", ".", "GetCpuShares", "(", ")", ")", ")", ",", "Quota", ":", "proto", ".", "Int64", "(", "r", ".", "GetCpuQuota", "(", ")", ")", ",", "Period", ":", "proto", ".", "Uint64", "(", "uint64", "(", "r", ".", "GetCpuPeriod", "(", ")", ")", ")", ",", "Cpus", ":", "r", ".", "GetCpusetCpus", "(", ")", ",", "Mems", ":", "r", ".", "GetCpusetMems", "(", ")", ",", "}", ",", "Memory", ":", "&", "rspec", ".", "LinuxMemory", "{", "Limit", ":", "proto", ".", "Int64", "(", "r", ".", "GetMemoryLimitInBytes", "(", ")", ")", ",", "}", ",", "}", "\n", "}" ]
// toOCIResources converts CRI resource constraints to OCI.
[ "toOCIResources", "converts", "CRI", "resource", "constraints", "to", "OCI", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_update_resources.go#L41-L55
train
cri-o/cri-o
server/inspect.go
GetInfoMux
func (s *Server) GetInfoMux() *bone.Mux { mux := bone.New() mux.Get("/info", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ci := s.getInfo() js, err := json.Marshal(ci) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) })) mux.Get("/containers/:id", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { containerID := bone.GetValue(req, "id") ci, err := s.getContainerInfo(containerID, s.GetContainer, s.getInfraContainer, s.getSandbox) if err != nil { switch err { case errCtrNotFound: http.Error(w, fmt.Sprintf("can't find the container with id %s", containerID), http.StatusNotFound) case errCtrStateNil: http.Error(w, fmt.Sprintf("can't find container state for container with id %s", containerID), http.StatusInternalServerError) case errSandboxNotFound: http.Error(w, fmt.Sprintf("can't find the sandbox for container id %s", containerID), http.StatusNotFound) default: http.Error(w, err.Error(), http.StatusInternalServerError) } return } js, err := json.Marshal(ci) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) })) return mux }
go
func (s *Server) GetInfoMux() *bone.Mux { mux := bone.New() mux.Get("/info", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ci := s.getInfo() js, err := json.Marshal(ci) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) })) mux.Get("/containers/:id", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { containerID := bone.GetValue(req, "id") ci, err := s.getContainerInfo(containerID, s.GetContainer, s.getInfraContainer, s.getSandbox) if err != nil { switch err { case errCtrNotFound: http.Error(w, fmt.Sprintf("can't find the container with id %s", containerID), http.StatusNotFound) case errCtrStateNil: http.Error(w, fmt.Sprintf("can't find container state for container with id %s", containerID), http.StatusInternalServerError) case errSandboxNotFound: http.Error(w, fmt.Sprintf("can't find the sandbox for container id %s", containerID), http.StatusNotFound) default: http.Error(w, err.Error(), http.StatusInternalServerError) } return } js, err := json.Marshal(ci) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) })) return mux }
[ "func", "(", "s", "*", "Server", ")", "GetInfoMux", "(", ")", "*", "bone", ".", "Mux", "{", "mux", ":=", "bone", ".", "New", "(", ")", "\n", "mux", ".", "Get", "(", "\"/info\"", ",", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ci", ":=", "s", ".", "getInfo", "(", ")", "\n", "js", ",", "err", ":=", "json", ".", "Marshal", "(", "ci", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "w", ".", "Write", "(", "js", ")", "\n", "}", ")", ")", "\n", "mux", ".", "Get", "(", "\"/containers/:id\"", ",", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "containerID", ":=", "bone", ".", "GetValue", "(", "req", ",", "\"id\"", ")", "\n", "ci", ",", "err", ":=", "s", ".", "getContainerInfo", "(", "containerID", ",", "s", ".", "GetContainer", ",", "s", ".", "getInfraContainer", ",", "s", ".", "getSandbox", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", "{", "case", "errCtrNotFound", ":", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"can't find the container with id %s\"", ",", "containerID", ")", ",", "http", ".", "StatusNotFound", ")", "\n", "case", "errCtrStateNil", ":", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"can't find container state for container with id %s\"", ",", "containerID", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "case", "errSandboxNotFound", ":", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"can't find the sandbox for container id %s\"", ",", "containerID", ")", ",", "http", ".", "StatusNotFound", ")", "\n", "default", ":", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "js", ",", "err", ":=", "json", ".", "Marshal", "(", "ci", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "w", ".", "Write", "(", "js", ")", "\n", "}", ")", ")", "\n", "return", "mux", "\n", "}" ]
// GetInfoMux returns the mux used to serve info requests
[ "GetInfoMux", "returns", "the", "mux", "used", "to", "serve", "info", "requests" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/inspect.go#L99-L139
train
cri-o/cri-o
server/server.go
GetConfigForClient
func (cc *certConfigCache) GetConfigForClient(hello *tls.ClientHelloInfo) (*tls.Config, error) { if cc.config != nil && time.Now().Before(cc.expires) { return cc.config, nil } config := new(tls.Config) cert, err := tls.LoadX509KeyPair(cc.tlsCert, cc.tlsKey) if err != nil { return nil, err } config.Certificates = []tls.Certificate{cert} if len(cc.tlsCA) > 0 { caBytes, err := ioutil.ReadFile(cc.tlsCA) if err != nil { return nil, err } certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(caBytes) config.ClientCAs = certPool config.ClientAuth = tls.RequireAndVerifyClientCert } cc.config = config cc.expires = time.Now().Add(certRefreshInterval) return config, nil }
go
func (cc *certConfigCache) GetConfigForClient(hello *tls.ClientHelloInfo) (*tls.Config, error) { if cc.config != nil && time.Now().Before(cc.expires) { return cc.config, nil } config := new(tls.Config) cert, err := tls.LoadX509KeyPair(cc.tlsCert, cc.tlsKey) if err != nil { return nil, err } config.Certificates = []tls.Certificate{cert} if len(cc.tlsCA) > 0 { caBytes, err := ioutil.ReadFile(cc.tlsCA) if err != nil { return nil, err } certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(caBytes) config.ClientCAs = certPool config.ClientAuth = tls.RequireAndVerifyClientCert } cc.config = config cc.expires = time.Now().Add(certRefreshInterval) return config, nil }
[ "func", "(", "cc", "*", "certConfigCache", ")", "GetConfigForClient", "(", "hello", "*", "tls", ".", "ClientHelloInfo", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "if", "cc", ".", "config", "!=", "nil", "&&", "time", ".", "Now", "(", ")", ".", "Before", "(", "cc", ".", "expires", ")", "{", "return", "cc", ".", "config", ",", "nil", "\n", "}", "\n", "config", ":=", "new", "(", "tls", ".", "Config", ")", "\n", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "cc", ".", "tlsCert", ",", "cc", ".", "tlsKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "config", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", "\n", "if", "len", "(", "cc", ".", "tlsCA", ")", ">", "0", "{", "caBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "cc", ".", "tlsCA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "certPool", ".", "AppendCertsFromPEM", "(", "caBytes", ")", "\n", "config", ".", "ClientCAs", "=", "certPool", "\n", "config", ".", "ClientAuth", "=", "tls", ".", "RequireAndVerifyClientCert", "\n", "}", "\n", "cc", ".", "config", "=", "config", "\n", "cc", ".", "expires", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "certRefreshInterval", ")", "\n", "return", "config", ",", "nil", "\n", "}" ]
// GetConfigForClient gets the tlsConfig for the streaming server. // This allows the certs to be swapped, without shutting down crio.
[ "GetConfigForClient", "gets", "the", "tlsConfig", "for", "the", "streaming", "server", ".", "This", "allows", "the", "certs", "to", "be", "swapped", "without", "shutting", "down", "crio", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L94-L117
train
cri-o/cri-o
server/server.go
getExec
func (s *Server) getExec(req *pb.ExecRequest) (*pb.ExecResponse, error) { return s.stream.streamServer.GetExec(req) }
go
func (s *Server) getExec(req *pb.ExecRequest) (*pb.ExecResponse, error) { return s.stream.streamServer.GetExec(req) }
[ "func", "(", "s", "*", "Server", ")", "getExec", "(", "req", "*", "pb", ".", "ExecRequest", ")", "(", "*", "pb", ".", "ExecResponse", ",", "error", ")", "{", "return", "s", ".", "stream", ".", "streamServer", ".", "GetExec", "(", "req", ")", "\n", "}" ]
// getExec returns exec stream request
[ "getExec", "returns", "exec", "stream", "request" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L130-L132
train
cri-o/cri-o
server/server.go
getAttach
func (s *Server) getAttach(req *pb.AttachRequest) (*pb.AttachResponse, error) { return s.stream.streamServer.GetAttach(req) }
go
func (s *Server) getAttach(req *pb.AttachRequest) (*pb.AttachResponse, error) { return s.stream.streamServer.GetAttach(req) }
[ "func", "(", "s", "*", "Server", ")", "getAttach", "(", "req", "*", "pb", ".", "AttachRequest", ")", "(", "*", "pb", ".", "AttachResponse", ",", "error", ")", "{", "return", "s", ".", "stream", ".", "streamServer", ".", "GetAttach", "(", "req", ")", "\n", "}" ]
// getAttach returns attach stream request
[ "getAttach", "returns", "attach", "stream", "request" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L135-L137
train
cri-o/cri-o
server/server.go
getPortForward
func (s *Server) getPortForward(req *pb.PortForwardRequest) (*pb.PortForwardResponse, error) { return s.stream.streamServer.GetPortForward(req) }
go
func (s *Server) getPortForward(req *pb.PortForwardRequest) (*pb.PortForwardResponse, error) { return s.stream.streamServer.GetPortForward(req) }
[ "func", "(", "s", "*", "Server", ")", "getPortForward", "(", "req", "*", "pb", ".", "PortForwardRequest", ")", "(", "*", "pb", ".", "PortForwardResponse", ",", "error", ")", "{", "return", "s", ".", "stream", ".", "streamServer", ".", "GetPortForward", "(", "req", ")", "\n", "}" ]
// getPortForward returns port forward stream request
[ "getPortForward", "returns", "port", "forward", "stream", "request" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L140-L142
train
cri-o/cri-o
server/server.go
cleanupSandboxesOnShutdown
func (s *Server) cleanupSandboxesOnShutdown(ctx context.Context) { _, err := os.Stat(shutdownFile) if err == nil || !os.IsNotExist(err) { logrus.Debugf("shutting down all sandboxes, on shutdown") s.stopAllPodSandboxes(ctx) err = os.Remove(shutdownFile) if err != nil { logrus.Warnf("Failed to remove %q", shutdownFile) } } }
go
func (s *Server) cleanupSandboxesOnShutdown(ctx context.Context) { _, err := os.Stat(shutdownFile) if err == nil || !os.IsNotExist(err) { logrus.Debugf("shutting down all sandboxes, on shutdown") s.stopAllPodSandboxes(ctx) err = os.Remove(shutdownFile) if err != nil { logrus.Warnf("Failed to remove %q", shutdownFile) } } }
[ "func", "(", "s", "*", "Server", ")", "cleanupSandboxesOnShutdown", "(", "ctx", "context", ".", "Context", ")", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "shutdownFile", ")", "\n", "if", "err", "==", "nil", "||", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "logrus", ".", "Debugf", "(", "\"shutting down all sandboxes, on shutdown\"", ")", "\n", "s", ".", "stopAllPodSandboxes", "(", "ctx", ")", "\n", "err", "=", "os", ".", "Remove", "(", "shutdownFile", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"Failed to remove %q\"", ",", "shutdownFile", ")", "\n", "}", "\n", "}", "\n", "}" ]
// cleanupSandboxesOnShutdown Remove all running Sandboxes on system shutdown
[ "cleanupSandboxesOnShutdown", "Remove", "all", "running", "Sandboxes", "on", "system", "shutdown" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L193-L204
train
cri-o/cri-o
server/server.go
StartExitMonitor
func (s *Server) StartExitMonitor() { watcher, err := fsnotify.NewWatcher() if err != nil { logrus.Fatalf("Failed to create new watch: %v", err) } defer watcher.Close() done := make(chan struct{}) go func() { for { select { case event := <-watcher.Events: logrus.Debugf("event: %v", event) if event.Op&fsnotify.Create == fsnotify.Create { containerID := filepath.Base(event.Name) logrus.Debugf("container or sandbox exited: %v", containerID) c := s.GetContainer(containerID) if c != nil { logrus.Debugf("container exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(c) if err != nil { logrus.Warnf("Failed to update container status %s: %v", containerID, err) } else { s.ContainerStateToDisk(c) } } else { sb := s.GetSandbox(containerID) if sb != nil { c := sb.InfraContainer() if c == nil { logrus.Warnf("no infra container set for sandbox: %v", containerID) continue } logrus.Debugf("sandbox exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(c) if err != nil { logrus.Warnf("Failed to update sandbox infra container status %s: %v", c.ID(), err) } else { s.ContainerStateToDisk(c) } } } } case err := <-watcher.Errors: logrus.Debugf("watch error: %v", err) return case <-s.monitorsChan: logrus.Debug("closing exit monitor...") close(done) return } } }() if err := watcher.Add(s.config.ContainerExitsDir); err != nil { logrus.Errorf("watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err) close(done) } <-done }
go
func (s *Server) StartExitMonitor() { watcher, err := fsnotify.NewWatcher() if err != nil { logrus.Fatalf("Failed to create new watch: %v", err) } defer watcher.Close() done := make(chan struct{}) go func() { for { select { case event := <-watcher.Events: logrus.Debugf("event: %v", event) if event.Op&fsnotify.Create == fsnotify.Create { containerID := filepath.Base(event.Name) logrus.Debugf("container or sandbox exited: %v", containerID) c := s.GetContainer(containerID) if c != nil { logrus.Debugf("container exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(c) if err != nil { logrus.Warnf("Failed to update container status %s: %v", containerID, err) } else { s.ContainerStateToDisk(c) } } else { sb := s.GetSandbox(containerID) if sb != nil { c := sb.InfraContainer() if c == nil { logrus.Warnf("no infra container set for sandbox: %v", containerID) continue } logrus.Debugf("sandbox exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(c) if err != nil { logrus.Warnf("Failed to update sandbox infra container status %s: %v", c.ID(), err) } else { s.ContainerStateToDisk(c) } } } } case err := <-watcher.Errors: logrus.Debugf("watch error: %v", err) return case <-s.monitorsChan: logrus.Debug("closing exit monitor...") close(done) return } } }() if err := watcher.Add(s.config.ContainerExitsDir); err != nil { logrus.Errorf("watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err) close(done) } <-done }
[ "func", "(", "s", "*", "Server", ")", "StartExitMonitor", "(", ")", "{", "watcher", ",", "err", ":=", "fsnotify", ".", "NewWatcher", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Fatalf", "(", "\"Failed to create new watch: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "watcher", ".", "Close", "(", ")", "\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "event", ":=", "<-", "watcher", ".", "Events", ":", "logrus", ".", "Debugf", "(", "\"event: %v\"", ",", "event", ")", "\n", "if", "event", ".", "Op", "&", "fsnotify", ".", "Create", "==", "fsnotify", ".", "Create", "{", "containerID", ":=", "filepath", ".", "Base", "(", "event", ".", "Name", ")", "\n", "logrus", ".", "Debugf", "(", "\"container or sandbox exited: %v\"", ",", "containerID", ")", "\n", "c", ":=", "s", ".", "GetContainer", "(", "containerID", ")", "\n", "if", "c", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"container exited and found: %v\"", ",", "containerID", ")", "\n", "err", ":=", "s", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"Failed to update container status %s: %v\"", ",", "containerID", ",", "err", ")", "\n", "}", "else", "{", "s", ".", "ContainerStateToDisk", "(", "c", ")", "\n", "}", "\n", "}", "else", "{", "sb", ":=", "s", ".", "GetSandbox", "(", "containerID", ")", "\n", "if", "sb", "!=", "nil", "{", "c", ":=", "sb", ".", "InfraContainer", "(", ")", "\n", "if", "c", "==", "nil", "{", "logrus", ".", "Warnf", "(", "\"no infra container set for sandbox: %v\"", ",", "containerID", ")", "\n", "continue", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"sandbox exited and found: %v\"", ",", "containerID", ")", "\n", "err", ":=", "s", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"Failed to update sandbox infra container status %s: %v\"", ",", "c", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "else", "{", "s", ".", "ContainerStateToDisk", "(", "c", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "case", "err", ":=", "<-", "watcher", ".", "Errors", ":", "logrus", ".", "Debugf", "(", "\"watch error: %v\"", ",", "err", ")", "\n", "return", "\n", "case", "<-", "s", ".", "monitorsChan", ":", "logrus", ".", "Debug", "(", "\"closing exit monitor...\"", ")", "\n", "close", "(", "done", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", ":=", "watcher", ".", "Add", "(", "s", ".", "config", ".", "ContainerExitsDir", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"watcher.Add(%q) failed: %s\"", ",", "s", ".", "config", ".", "ContainerExitsDir", ",", "err", ")", "\n", "close", "(", "done", ")", "\n", "}", "\n", "<-", "done", "\n", "}" ]
// StartExitMonitor start a routine that monitors container exits // and updates the container status
[ "StartExitMonitor", "start", "a", "routine", "that", "monitors", "container", "exits", "and", "updates", "the", "container", "status" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/server.go#L448-L506
train
cri-o/cri-o
server/container_list.go
filterContainer
func filterContainer(c *pb.Container, filter *pb.ContainerFilter) bool { if filter != nil { if filter.State != nil { if c.State != filter.State.State { return false } } if filter.LabelSelector != nil { sel := fields.SelectorFromSet(filter.LabelSelector) if !sel.Matches(fields.Set(c.Labels)) { return false } } } return true }
go
func filterContainer(c *pb.Container, filter *pb.ContainerFilter) bool { if filter != nil { if filter.State != nil { if c.State != filter.State.State { return false } } if filter.LabelSelector != nil { sel := fields.SelectorFromSet(filter.LabelSelector) if !sel.Matches(fields.Set(c.Labels)) { return false } } } return true }
[ "func", "filterContainer", "(", "c", "*", "pb", ".", "Container", ",", "filter", "*", "pb", ".", "ContainerFilter", ")", "bool", "{", "if", "filter", "!=", "nil", "{", "if", "filter", ".", "State", "!=", "nil", "{", "if", "c", ".", "State", "!=", "filter", ".", "State", ".", "State", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "filter", ".", "LabelSelector", "!=", "nil", "{", "sel", ":=", "fields", ".", "SelectorFromSet", "(", "filter", ".", "LabelSelector", ")", "\n", "if", "!", "sel", ".", "Matches", "(", "fields", ".", "Set", "(", "c", ".", "Labels", ")", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// filterContainer returns whether passed container matches filtering criteria
[ "filterContainer", "returns", "whether", "passed", "container", "matches", "filtering", "criteria" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_list.go#L14-L29
train
cri-o/cri-o
server/container_list.go
filterContainerList
func (s *Server) filterContainerList(filter *pb.ContainerFilter, origCtrList []*oci.Container) []*oci.Container { // Filter using container id and pod id first. if filter.Id != "" { id, err := s.CtrIDIndex().Get(filter.Id) if err != nil { // If we don't find a container ID with a filter, it should not // be considered an error. Log a warning and return an empty struct logrus.Warnf("unable to find container ID %s", filter.Id) return []*oci.Container{} } c := s.ContainerServer.GetContainer(id) if c != nil { switch { case filter.PodSandboxId == "": return []*oci.Container{c} case c.Sandbox() == filter.PodSandboxId: return []*oci.Container{c} default: return []*oci.Container{} } } } else if filter.PodSandboxId != "" { pod := s.ContainerServer.GetSandbox(filter.PodSandboxId) if pod == nil { return []*oci.Container{} } return pod.Containers().List() } logrus.Debug("no filters were applied, returning full container list") return origCtrList }
go
func (s *Server) filterContainerList(filter *pb.ContainerFilter, origCtrList []*oci.Container) []*oci.Container { // Filter using container id and pod id first. if filter.Id != "" { id, err := s.CtrIDIndex().Get(filter.Id) if err != nil { // If we don't find a container ID with a filter, it should not // be considered an error. Log a warning and return an empty struct logrus.Warnf("unable to find container ID %s", filter.Id) return []*oci.Container{} } c := s.ContainerServer.GetContainer(id) if c != nil { switch { case filter.PodSandboxId == "": return []*oci.Container{c} case c.Sandbox() == filter.PodSandboxId: return []*oci.Container{c} default: return []*oci.Container{} } } } else if filter.PodSandboxId != "" { pod := s.ContainerServer.GetSandbox(filter.PodSandboxId) if pod == nil { return []*oci.Container{} } return pod.Containers().List() } logrus.Debug("no filters were applied, returning full container list") return origCtrList }
[ "func", "(", "s", "*", "Server", ")", "filterContainerList", "(", "filter", "*", "pb", ".", "ContainerFilter", ",", "origCtrList", "[", "]", "*", "oci", ".", "Container", ")", "[", "]", "*", "oci", ".", "Container", "{", "if", "filter", ".", "Id", "!=", "\"\"", "{", "id", ",", "err", ":=", "s", ".", "CtrIDIndex", "(", ")", ".", "Get", "(", "filter", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"unable to find container ID %s\"", ",", "filter", ".", "Id", ")", "\n", "return", "[", "]", "*", "oci", ".", "Container", "{", "}", "\n", "}", "\n", "c", ":=", "s", ".", "ContainerServer", ".", "GetContainer", "(", "id", ")", "\n", "if", "c", "!=", "nil", "{", "switch", "{", "case", "filter", ".", "PodSandboxId", "==", "\"\"", ":", "return", "[", "]", "*", "oci", ".", "Container", "{", "c", "}", "\n", "case", "c", ".", "Sandbox", "(", ")", "==", "filter", ".", "PodSandboxId", ":", "return", "[", "]", "*", "oci", ".", "Container", "{", "c", "}", "\n", "default", ":", "return", "[", "]", "*", "oci", ".", "Container", "{", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "filter", ".", "PodSandboxId", "!=", "\"\"", "{", "pod", ":=", "s", ".", "ContainerServer", ".", "GetSandbox", "(", "filter", ".", "PodSandboxId", ")", "\n", "if", "pod", "==", "nil", "{", "return", "[", "]", "*", "oci", ".", "Container", "{", "}", "\n", "}", "\n", "return", "pod", ".", "Containers", "(", ")", ".", "List", "(", ")", "\n", "}", "\n", "logrus", ".", "Debug", "(", "\"no filters were applied, returning full container list\"", ")", "\n", "return", "origCtrList", "\n", "}" ]
// filterContainerList applies a protobuf-defined filter to retrieve only intended containers. Not matching // the filter is not considered an error but will return an empty response.
[ "filterContainerList", "applies", "a", "protobuf", "-", "defined", "filter", "to", "retrieve", "only", "intended", "containers", ".", "Not", "matching", "the", "filter", "is", "not", "considered", "an", "error", "but", "will", "return", "an", "empty", "response", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_list.go#L33-L63
train
cri-o/cri-o
oci/runtime_vm.go
newRuntimeVM
func newRuntimeVM(path string) RuntimeImpl { logrus.Debug("oci.newRuntimeVM() start") defer logrus.Debug("oci.newRuntimeVM() end") // FIXME: We need to register those types for now, but this should be // defined as a specific package that would be shared both by CRI-O and // containerd. This would allow shim implementation to import a single // package to do the proper registration. const prefix = "types.containerd.io" // register TypeUrls for commonly marshaled external types major := strconv.Itoa(rspec.VersionMajor) typeurl.Register(&rspec.Spec{}, prefix, "opencontainers/runtime-spec", major, "Spec") typeurl.Register(&rspec.Process{}, prefix, "opencontainers/runtime-spec", major, "Process") typeurl.Register(&rspec.LinuxResources{}, prefix, "opencontainers/runtime-spec", major, "LinuxResources") typeurl.Register(&rspec.WindowsResources{}, prefix, "opencontainers/runtime-spec", major, "WindowsResources") return &runtimeVM{ path: path, ctx: context.Background(), ctrs: make(map[string]containerInfo), } }
go
func newRuntimeVM(path string) RuntimeImpl { logrus.Debug("oci.newRuntimeVM() start") defer logrus.Debug("oci.newRuntimeVM() end") // FIXME: We need to register those types for now, but this should be // defined as a specific package that would be shared both by CRI-O and // containerd. This would allow shim implementation to import a single // package to do the proper registration. const prefix = "types.containerd.io" // register TypeUrls for commonly marshaled external types major := strconv.Itoa(rspec.VersionMajor) typeurl.Register(&rspec.Spec{}, prefix, "opencontainers/runtime-spec", major, "Spec") typeurl.Register(&rspec.Process{}, prefix, "opencontainers/runtime-spec", major, "Process") typeurl.Register(&rspec.LinuxResources{}, prefix, "opencontainers/runtime-spec", major, "LinuxResources") typeurl.Register(&rspec.WindowsResources{}, prefix, "opencontainers/runtime-spec", major, "WindowsResources") return &runtimeVM{ path: path, ctx: context.Background(), ctrs: make(map[string]containerInfo), } }
[ "func", "newRuntimeVM", "(", "path", "string", ")", "RuntimeImpl", "{", "logrus", ".", "Debug", "(", "\"oci.newRuntimeVM() start\"", ")", "\n", "defer", "logrus", ".", "Debug", "(", "\"oci.newRuntimeVM() end\"", ")", "\n", "const", "prefix", "=", "\"types.containerd.io\"", "\n", "major", ":=", "strconv", ".", "Itoa", "(", "rspec", ".", "VersionMajor", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "Spec", "{", "}", ",", "prefix", ",", "\"opencontainers/runtime-spec\"", ",", "major", ",", "\"Spec\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "Process", "{", "}", ",", "prefix", ",", "\"opencontainers/runtime-spec\"", ",", "major", ",", "\"Process\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "LinuxResources", "{", "}", ",", "prefix", ",", "\"opencontainers/runtime-spec\"", ",", "major", ",", "\"LinuxResources\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "WindowsResources", "{", "}", ",", "prefix", ",", "\"opencontainers/runtime-spec\"", ",", "major", ",", "\"WindowsResources\"", ")", "\n", "return", "&", "runtimeVM", "{", "path", ":", "path", ",", "ctx", ":", "context", ".", "Background", "(", ")", ",", "ctrs", ":", "make", "(", "map", "[", "string", "]", "containerInfo", ")", ",", "}", "\n", "}" ]
// newRuntimeVM creates a new runtimeVM instance
[ "newRuntimeVM", "creates", "a", "new", "runtimeVM", "instance" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/runtime_vm.go#L59-L80
train
cri-o/cri-o
oci/runtime_vm.go
UnpauseContainer
func (r *runtimeVM) UnpauseContainer(c *Container) error { logrus.Debug("runtimeVM.UnpauseContainer() start") defer logrus.Debug("runtimeVM.UnpauseContainer() end") // Lock the container c.opLock.Lock() defer c.opLock.Unlock() if _, err := r.task.Resume(r.ctx, &task.ResumeRequest{ ID: c.ID(), }); err != nil { return errdefs.FromGRPC(err) } return nil }
go
func (r *runtimeVM) UnpauseContainer(c *Container) error { logrus.Debug("runtimeVM.UnpauseContainer() start") defer logrus.Debug("runtimeVM.UnpauseContainer() end") // Lock the container c.opLock.Lock() defer c.opLock.Unlock() if _, err := r.task.Resume(r.ctx, &task.ResumeRequest{ ID: c.ID(), }); err != nil { return errdefs.FromGRPC(err) } return nil }
[ "func", "(", "r", "*", "runtimeVM", ")", "UnpauseContainer", "(", "c", "*", "Container", ")", "error", "{", "logrus", ".", "Debug", "(", "\"runtimeVM.UnpauseContainer() start\"", ")", "\n", "defer", "logrus", ".", "Debug", "(", "\"runtimeVM.UnpauseContainer() end\"", ")", "\n", "c", ".", "opLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "opLock", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "err", ":=", "r", ".", "task", ".", "Resume", "(", "r", ".", "ctx", ",", "&", "task", ".", "ResumeRequest", "{", "ID", ":", "c", ".", "ID", "(", ")", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errdefs", ".", "FromGRPC", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnpauseContainer unpauses a container.
[ "UnpauseContainer", "unpauses", "a", "container", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/runtime_vm.go#L590-L605
train
cri-o/cri-o
utils/utils.go
ExecCmd
func ExecCmd(name string, args ...string) (string, error) { cmd := exec.Command(name, args...) var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found { cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v)) } err := cmd.Run() if err != nil { return "", fmt.Errorf("`%v %v` failed: %v %v (%v)", name, strings.Join(args, " "), stderr.String(), stdout.String(), err) } return stdout.String(), nil }
go
func ExecCmd(name string, args ...string) (string, error) { cmd := exec.Command(name, args...) var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found { cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v)) } err := cmd.Run() if err != nil { return "", fmt.Errorf("`%v %v` failed: %v %v (%v)", name, strings.Join(args, " "), stderr.String(), stdout.String(), err) } return stdout.String(), nil }
[ "func", "ExecCmd", "(", "name", "string", ",", "args", "...", "string", ")", "(", "string", ",", "error", ")", "{", "cmd", ":=", "exec", ".", "Command", "(", "name", ",", "args", "...", ")", "\n", "var", "stdout", "bytes", ".", "Buffer", "\n", "var", "stderr", "bytes", ".", "Buffer", "\n", "cmd", ".", "Stdout", "=", "&", "stdout", "\n", "cmd", ".", "Stderr", "=", "&", "stderr", "\n", "if", "v", ",", "found", ":=", "os", ".", "LookupEnv", "(", "\"XDG_RUNTIME_DIR\"", ")", ";", "found", "{", "cmd", ".", "Env", "=", "append", "(", "cmd", ".", "Env", ",", "fmt", ".", "Sprintf", "(", "\"XDG_RUNTIME_DIR=%s\"", ",", "v", ")", ")", "\n", "}", "\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"`%v %v` failed: %v %v (%v)\"", ",", "name", ",", "strings", ".", "Join", "(", "args", ",", "\" \"", ")", ",", "stderr", ".", "String", "(", ")", ",", "stdout", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "stdout", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// ExecCmd executes a command with args and returns its output as a string along // with an error, if any
[ "ExecCmd", "executes", "a", "command", "with", "args", "and", "returns", "its", "output", "as", "a", "string", "along", "with", "an", "error", "if", "any" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L29-L45
train
cri-o/cri-o
utils/utils.go
ExecCmdWithStdStreams
func ExecCmdWithStdStreams(stdin io.Reader, stdout, stderr io.Writer, name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found { cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v)) } err := cmd.Run() if err != nil { return fmt.Errorf("`%v %v` failed: %v", name, strings.Join(args, " "), err) } return nil }
go
func ExecCmdWithStdStreams(stdin io.Reader, stdout, stderr io.Writer, name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found { cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v)) } err := cmd.Run() if err != nil { return fmt.Errorf("`%v %v` failed: %v", name, strings.Join(args, " "), err) } return nil }
[ "func", "ExecCmdWithStdStreams", "(", "stdin", "io", ".", "Reader", ",", "stdout", ",", "stderr", "io", ".", "Writer", ",", "name", "string", ",", "args", "...", "string", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "name", ",", "args", "...", ")", "\n", "cmd", ".", "Stdin", "=", "stdin", "\n", "cmd", ".", "Stdout", "=", "stdout", "\n", "cmd", ".", "Stderr", "=", "stderr", "\n", "if", "v", ",", "found", ":=", "os", ".", "LookupEnv", "(", "\"XDG_RUNTIME_DIR\"", ")", ";", "found", "{", "cmd", ".", "Env", "=", "append", "(", "cmd", ".", "Env", ",", "fmt", ".", "Sprintf", "(", "\"XDG_RUNTIME_DIR=%s\"", ",", "v", ")", ")", "\n", "}", "\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"`%v %v` failed: %v\"", ",", "name", ",", "strings", ".", "Join", "(", "args", ",", "\" \"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ExecCmdWithStdStreams execute a command with the specified standard streams.
[ "ExecCmdWithStdStreams", "execute", "a", "command", "with", "the", "specified", "standard", "streams", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L48-L63
train
cri-o/cri-o
utils/utils.go
RunUnderSystemdScope
func RunUnderSystemdScope(pid int, slice string, unitName string) error { var properties []systemdDbus.Property conn, err := systemdDbus.New() if err != nil { return err } properties = append(properties, systemdDbus.PropSlice(slice)) properties = append(properties, newProp("PIDs", []uint32{uint32(pid)})) properties = append(properties, newProp("Delegate", true)) properties = append(properties, newProp("DefaultDependencies", false)) ch := make(chan string) _, err = conn.StartTransientUnit(unitName, "replace", properties, ch) if err != nil { return err } defer conn.Close() // Block until job is started <-ch return nil }
go
func RunUnderSystemdScope(pid int, slice string, unitName string) error { var properties []systemdDbus.Property conn, err := systemdDbus.New() if err != nil { return err } properties = append(properties, systemdDbus.PropSlice(slice)) properties = append(properties, newProp("PIDs", []uint32{uint32(pid)})) properties = append(properties, newProp("Delegate", true)) properties = append(properties, newProp("DefaultDependencies", false)) ch := make(chan string) _, err = conn.StartTransientUnit(unitName, "replace", properties, ch) if err != nil { return err } defer conn.Close() // Block until job is started <-ch return nil }
[ "func", "RunUnderSystemdScope", "(", "pid", "int", ",", "slice", "string", ",", "unitName", "string", ")", "error", "{", "var", "properties", "[", "]", "systemdDbus", ".", "Property", "\n", "conn", ",", "err", ":=", "systemdDbus", ".", "New", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "properties", "=", "append", "(", "properties", ",", "systemdDbus", ".", "PropSlice", "(", "slice", ")", ")", "\n", "properties", "=", "append", "(", "properties", ",", "newProp", "(", "\"PIDs\"", ",", "[", "]", "uint32", "{", "uint32", "(", "pid", ")", "}", ")", ")", "\n", "properties", "=", "append", "(", "properties", ",", "newProp", "(", "\"Delegate\"", ",", "true", ")", ")", "\n", "properties", "=", "append", "(", "properties", ",", "newProp", "(", "\"DefaultDependencies\"", ",", "false", ")", ")", "\n", "ch", ":=", "make", "(", "chan", "string", ")", "\n", "_", ",", "err", "=", "conn", ".", "StartTransientUnit", "(", "unitName", ",", "\"replace\"", ",", "properties", ",", "ch", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "<-", "ch", "\n", "return", "nil", "\n", "}" ]
// RunUnderSystemdScope adds the specified pid to a systemd scope
[ "RunUnderSystemdScope", "adds", "the", "specified", "pid", "to", "a", "systemd", "scope" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L71-L92
train
cri-o/cri-o
utils/utils.go
CopyDetachable
func CopyDetachable(dst io.Writer, src io.Reader, keys []byte) (written int64, err error) { // Sanity check interfaces if dst == nil || src == nil { return 0, fmt.Errorf("src/dst reader/writer nil") } if len(keys) == 0 { // Default keys : ctrl-p ctrl-q keys = []byte{16, 17} } buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { preservBuf := []byte{} for i, key := range keys { preservBuf = append(preservBuf, buf[0:nr]...) if nr != 1 || buf[0] != key { break } if i == len(keys)-1 { // src.Close() return 0, DetachError{} } nr, er = src.Read(buf) } nw, ew := dst.Write(preservBuf) nr = len(preservBuf) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } } if er != nil { if er != io.EOF { err = er } break } } return written, err }
go
func CopyDetachable(dst io.Writer, src io.Reader, keys []byte) (written int64, err error) { // Sanity check interfaces if dst == nil || src == nil { return 0, fmt.Errorf("src/dst reader/writer nil") } if len(keys) == 0 { // Default keys : ctrl-p ctrl-q keys = []byte{16, 17} } buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { preservBuf := []byte{} for i, key := range keys { preservBuf = append(preservBuf, buf[0:nr]...) if nr != 1 || buf[0] != key { break } if i == len(keys)-1 { // src.Close() return 0, DetachError{} } nr, er = src.Read(buf) } nw, ew := dst.Write(preservBuf) nr = len(preservBuf) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } } if er != nil { if er != io.EOF { err = er } break } } return written, err }
[ "func", "CopyDetachable", "(", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ",", "keys", "[", "]", "byte", ")", "(", "written", "int64", ",", "err", "error", ")", "{", "if", "dst", "==", "nil", "||", "src", "==", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"src/dst reader/writer nil\"", ")", "\n", "}", "\n", "if", "len", "(", "keys", ")", "==", "0", "{", "keys", "=", "[", "]", "byte", "{", "16", ",", "17", "}", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "32", "*", "1024", ")", "\n", "for", "{", "nr", ",", "er", ":=", "src", ".", "Read", "(", "buf", ")", "\n", "if", "nr", ">", "0", "{", "preservBuf", ":=", "[", "]", "byte", "{", "}", "\n", "for", "i", ",", "key", ":=", "range", "keys", "{", "preservBuf", "=", "append", "(", "preservBuf", ",", "buf", "[", "0", ":", "nr", "]", "...", ")", "\n", "if", "nr", "!=", "1", "||", "buf", "[", "0", "]", "!=", "key", "{", "break", "\n", "}", "\n", "if", "i", "==", "len", "(", "keys", ")", "-", "1", "{", "return", "0", ",", "DetachError", "{", "}", "\n", "}", "\n", "nr", ",", "er", "=", "src", ".", "Read", "(", "buf", ")", "\n", "}", "\n", "nw", ",", "ew", ":=", "dst", ".", "Write", "(", "preservBuf", ")", "\n", "nr", "=", "len", "(", "preservBuf", ")", "\n", "if", "nw", ">", "0", "{", "written", "+=", "int64", "(", "nw", ")", "\n", "}", "\n", "if", "ew", "!=", "nil", "{", "err", "=", "ew", "\n", "break", "\n", "}", "\n", "if", "nr", "!=", "nw", "{", "err", "=", "io", ".", "ErrShortWrite", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "er", "!=", "nil", "{", "if", "er", "!=", "io", ".", "EOF", "{", "err", "=", "er", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "written", ",", "err", "\n", "}" ]
// CopyDetachable is similar to io.Copy but support a detach key sequence to break out.
[ "CopyDetachable", "is", "similar", "to", "io", ".", "Copy", "but", "support", "a", "detach", "key", "sequence", "to", "break", "out", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L109-L157
train
cri-o/cri-o
utils/utils.go
WriteGoroutineStacks
func WriteGoroutineStacks(w io.Writer) error { if w == nil { return fmt.Errorf("writer nil") } buf := make([]byte, 1<<20) for i := 0; ; i++ { n := runtime.Stack(buf, true) if n < len(buf) { buf = buf[:n] break } if len(buf) >= 32<<20 { break } buf = make([]byte, 2*len(buf)) } _, err := w.Write(buf) return err }
go
func WriteGoroutineStacks(w io.Writer) error { if w == nil { return fmt.Errorf("writer nil") } buf := make([]byte, 1<<20) for i := 0; ; i++ { n := runtime.Stack(buf, true) if n < len(buf) { buf = buf[:n] break } if len(buf) >= 32<<20 { break } buf = make([]byte, 2*len(buf)) } _, err := w.Write(buf) return err }
[ "func", "WriteGoroutineStacks", "(", "w", "io", ".", "Writer", ")", "error", "{", "if", "w", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"writer nil\"", ")", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "1", "<<", "20", ")", "\n", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "n", ":=", "runtime", ".", "Stack", "(", "buf", ",", "true", ")", "\n", "if", "n", "<", "len", "(", "buf", ")", "{", "buf", "=", "buf", "[", ":", "n", "]", "\n", "break", "\n", "}", "\n", "if", "len", "(", "buf", ")", ">=", "32", "<<", "20", "{", "break", "\n", "}", "\n", "buf", "=", "make", "(", "[", "]", "byte", ",", "2", "*", "len", "(", "buf", ")", ")", "\n", "}", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "buf", ")", "\n", "return", "err", "\n", "}" ]
// WriteGoroutineStacks writes out the goroutine stacks // of the caller. Up to 32 MB is allocated to print the // stack.
[ "WriteGoroutineStacks", "writes", "out", "the", "goroutine", "stacks", "of", "the", "caller", ".", "Up", "to", "32", "MB", "is", "allocated", "to", "print", "the", "stack", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L162-L180
train
cri-o/cri-o
utils/utils.go
WriteGoroutineStacksToFile
func WriteGoroutineStacksToFile(path string) error { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666) if err != nil { return err } defer f.Close() defer f.Sync() return WriteGoroutineStacks(f) }
go
func WriteGoroutineStacksToFile(path string) error { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666) if err != nil { return err } defer f.Close() defer f.Sync() return WriteGoroutineStacks(f) }
[ "func", "WriteGoroutineStacksToFile", "(", "path", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_WRONLY", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "defer", "f", ".", "Sync", "(", ")", "\n", "return", "WriteGoroutineStacks", "(", "f", ")", "\n", "}" ]
// WriteGoroutineStacksToFile write goroutine stacks // to the specified file.
[ "WriteGoroutineStacksToFile", "write", "goroutine", "stacks", "to", "the", "specified", "file", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L184-L193
train
cri-o/cri-o
utils/utils.go
GenerateID
func GenerateID() string { b := make([]byte, 32) rand.Read(b) return hex.EncodeToString(b) }
go
func GenerateID() string { b := make([]byte, 32) rand.Read(b) return hex.EncodeToString(b) }
[ "func", "GenerateID", "(", ")", "string", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "32", ")", "\n", "rand", ".", "Read", "(", "b", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "b", ")", "\n", "}" ]
// GenerateID generates a random unique id.
[ "GenerateID", "generates", "a", "random", "unique", "id", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L196-L200
train
cri-o/cri-o
utils/utils.go
openContainerFile
func openContainerFile(rootfs string, path string) (io.ReadCloser, error) { fp, err := symlink.FollowSymlinkInScope(filepath.Join(rootfs, path), rootfs) if err != nil { return nil, err } return os.Open(fp) }
go
func openContainerFile(rootfs string, path string) (io.ReadCloser, error) { fp, err := symlink.FollowSymlinkInScope(filepath.Join(rootfs, path), rootfs) if err != nil { return nil, err } return os.Open(fp) }
[ "func", "openContainerFile", "(", "rootfs", "string", ",", "path", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "fp", ",", "err", ":=", "symlink", ".", "FollowSymlinkInScope", "(", "filepath", ".", "Join", "(", "rootfs", ",", "path", ")", ",", "rootfs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "os", ".", "Open", "(", "fp", ")", "\n", "}" ]
// openContainerFile opens a file inside a container rootfs safely
[ "openContainerFile", "opens", "a", "file", "inside", "a", "container", "rootfs", "safely" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/utils.go#L203-L209
train
cri-o/cri-o
utils/ioutil/writer_group.go
Add
func (g *WriterGroup) Add(key string, w io.WriteCloser) { g.mu.Lock() defer g.mu.Unlock() if g.closed { w.Close() return } g.writers[key] = w }
go
func (g *WriterGroup) Add(key string, w io.WriteCloser) { g.mu.Lock() defer g.mu.Unlock() if g.closed { w.Close() return } g.writers[key] = w }
[ "func", "(", "g", "*", "WriterGroup", ")", "Add", "(", "key", "string", ",", "w", "io", ".", "WriteCloser", ")", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "g", ".", "closed", "{", "w", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "g", ".", "writers", "[", "key", "]", "=", "w", "\n", "}" ]
// Add adds a writer into the group. The writer will be closed // if the writer group is closed.
[ "Add", "adds", "a", "writer", "into", "the", "group", ".", "The", "writer", "will", "be", "closed", "if", "the", "writer", "group", "is", "closed", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/writer_group.go#L41-L49
train
cri-o/cri-o
utils/ioutil/writer_group.go
Get
func (g *WriterGroup) Get(key string) io.WriteCloser { g.mu.Lock() defer g.mu.Unlock() return g.writers[key] }
go
func (g *WriterGroup) Get(key string) io.WriteCloser { g.mu.Lock() defer g.mu.Unlock() return g.writers[key] }
[ "func", "(", "g", "*", "WriterGroup", ")", "Get", "(", "key", "string", ")", "io", ".", "WriteCloser", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "g", ".", "writers", "[", "key", "]", "\n", "}" ]
// Get gets a writer from the group, returns nil if the writer // doesn't exist.
[ "Get", "gets", "a", "writer", "from", "the", "group", "returns", "nil", "if", "the", "writer", "doesn", "t", "exist", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/writer_group.go#L53-L57
train
cri-o/cri-o
utils/ioutil/writer_group.go
Remove
func (g *WriterGroup) Remove(key string) { g.mu.Lock() defer g.mu.Unlock() w, ok := g.writers[key] if !ok { return } w.Close() delete(g.writers, key) }
go
func (g *WriterGroup) Remove(key string) { g.mu.Lock() defer g.mu.Unlock() w, ok := g.writers[key] if !ok { return } w.Close() delete(g.writers, key) }
[ "func", "(", "g", "*", "WriterGroup", ")", "Remove", "(", "key", "string", ")", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "w", ",", "ok", ":=", "g", ".", "writers", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "w", ".", "Close", "(", ")", "\n", "delete", "(", "g", ".", "writers", ",", "key", ")", "\n", "}" ]
// Remove removes a writer from the group.
[ "Remove", "removes", "a", "writer", "from", "the", "group", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/writer_group.go#L60-L69
train
cri-o/cri-o
utils/ioutil/writer_group.go
Write
func (g *WriterGroup) Write(p []byte) (int, error) { g.mu.Lock() defer g.mu.Unlock() for k, w := range g.writers { n, err := w.Write(p) if err == nil && len(p) == n { continue } // The writer is closed or in bad state, remove it. w.Close() delete(g.writers, k) } if len(g.writers) == 0 { return 0, errors.New("writer group is empty") } return len(p), nil }
go
func (g *WriterGroup) Write(p []byte) (int, error) { g.mu.Lock() defer g.mu.Unlock() for k, w := range g.writers { n, err := w.Write(p) if err == nil && len(p) == n { continue } // The writer is closed or in bad state, remove it. w.Close() delete(g.writers, k) } if len(g.writers) == 0 { return 0, errors.New("writer group is empty") } return len(p), nil }
[ "func", "(", "g", "*", "WriterGroup", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "k", ",", "w", ":=", "range", "g", ".", "writers", "{", "n", ",", "err", ":=", "w", ".", "Write", "(", "p", ")", "\n", "if", "err", "==", "nil", "&&", "len", "(", "p", ")", "==", "n", "{", "continue", "\n", "}", "\n", "w", ".", "Close", "(", ")", "\n", "delete", "(", "g", ".", "writers", ",", "k", ")", "\n", "}", "\n", "if", "len", "(", "g", ".", "writers", ")", "==", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"writer group is empty\"", ")", "\n", "}", "\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// Write writes data into each writer. If a writer returns error, // it will be closed and removed from the writer group. It returns // error if writer group is empty.
[ "Write", "writes", "data", "into", "each", "writer", ".", "If", "a", "writer", "returns", "error", "it", "will", "be", "closed", "and", "removed", "from", "the", "writer", "group", ".", "It", "returns", "error", "if", "writer", "group", "is", "empty", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/writer_group.go#L74-L90
train
cri-o/cri-o
utils/ioutil/writer_group.go
Close
func (g *WriterGroup) Close() { g.mu.Lock() defer g.mu.Unlock() for _, w := range g.writers { w.Close() } g.writers = nil g.closed = true }
go
func (g *WriterGroup) Close() { g.mu.Lock() defer g.mu.Unlock() for _, w := range g.writers { w.Close() } g.writers = nil g.closed = true }
[ "func", "(", "g", "*", "WriterGroup", ")", "Close", "(", ")", "{", "g", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "g", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "w", ":=", "range", "g", ".", "writers", "{", "w", ".", "Close", "(", ")", "\n", "}", "\n", "g", ".", "writers", "=", "nil", "\n", "g", ".", "closed", "=", "true", "\n", "}" ]
// Close closes the writer group. Write will return error after // closed.
[ "Close", "closes", "the", "writer", "group", ".", "Write", "will", "return", "error", "after", "closed", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/writer_group.go#L94-L102
train
cri-o/cri-o
oci/oci.go
New
func New(defaultRuntime string, runtimes map[string]RuntimeHandler, conmonPath string, conmonEnv []string, cgroupManager string, containerExitsDir string, containerAttachSocketDir string, logSizeMax int64, logToJournald bool, noPivot bool, ctrStopTimeout int64) (*Runtime, error) { defRuntime, ok := runtimes[defaultRuntime] if !ok { return nil, fmt.Errorf("no runtime configured for default_runtime=%q", defaultRuntime) } if defRuntime.RuntimePath == "" { return nil, fmt.Errorf("empty runtime path for default_runtime=%q", defaultRuntime) } return &Runtime{ defaultRuntime: defRuntime, runtimes: runtimes, conmonPath: conmonPath, conmonEnv: conmonEnv, cgroupManager: cgroupManager, containerExitsDir: containerExitsDir, containerAttachSocketDir: containerAttachSocketDir, logSizeMax: logSizeMax, logToJournald: logToJournald, noPivot: noPivot, ctrStopTimeout: ctrStopTimeout, runtimeImplList: make(map[string]RuntimeImpl), }, nil }
go
func New(defaultRuntime string, runtimes map[string]RuntimeHandler, conmonPath string, conmonEnv []string, cgroupManager string, containerExitsDir string, containerAttachSocketDir string, logSizeMax int64, logToJournald bool, noPivot bool, ctrStopTimeout int64) (*Runtime, error) { defRuntime, ok := runtimes[defaultRuntime] if !ok { return nil, fmt.Errorf("no runtime configured for default_runtime=%q", defaultRuntime) } if defRuntime.RuntimePath == "" { return nil, fmt.Errorf("empty runtime path for default_runtime=%q", defaultRuntime) } return &Runtime{ defaultRuntime: defRuntime, runtimes: runtimes, conmonPath: conmonPath, conmonEnv: conmonEnv, cgroupManager: cgroupManager, containerExitsDir: containerExitsDir, containerAttachSocketDir: containerAttachSocketDir, logSizeMax: logSizeMax, logToJournald: logToJournald, noPivot: noPivot, ctrStopTimeout: ctrStopTimeout, runtimeImplList: make(map[string]RuntimeImpl), }, nil }
[ "func", "New", "(", "defaultRuntime", "string", ",", "runtimes", "map", "[", "string", "]", "RuntimeHandler", ",", "conmonPath", "string", ",", "conmonEnv", "[", "]", "string", ",", "cgroupManager", "string", ",", "containerExitsDir", "string", ",", "containerAttachSocketDir", "string", ",", "logSizeMax", "int64", ",", "logToJournald", "bool", ",", "noPivot", "bool", ",", "ctrStopTimeout", "int64", ")", "(", "*", "Runtime", ",", "error", ")", "{", "defRuntime", ",", "ok", ":=", "runtimes", "[", "defaultRuntime", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no runtime configured for default_runtime=%q\"", ",", "defaultRuntime", ")", "\n", "}", "\n", "if", "defRuntime", ".", "RuntimePath", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"empty runtime path for default_runtime=%q\"", ",", "defaultRuntime", ")", "\n", "}", "\n", "return", "&", "Runtime", "{", "defaultRuntime", ":", "defRuntime", ",", "runtimes", ":", "runtimes", ",", "conmonPath", ":", "conmonPath", ",", "conmonEnv", ":", "conmonEnv", ",", "cgroupManager", ":", "cgroupManager", ",", "containerExitsDir", ":", "containerExitsDir", ",", "containerAttachSocketDir", ":", "containerAttachSocketDir", ",", "logSizeMax", ":", "logSizeMax", ",", "logToJournald", ":", "logToJournald", ",", "noPivot", ":", "noPivot", ",", "ctrStopTimeout", ":", "ctrStopTimeout", ",", "runtimeImplList", ":", "make", "(", "map", "[", "string", "]", "RuntimeImpl", ")", ",", "}", ",", "nil", "\n", "}" ]
// New creates a new Runtime with options provided
[ "New", "creates", "a", "new", "Runtime", "with", "options", "provided" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/oci.go#L100-L134
train
cri-o/cri-o
oci/oci.go
ValidateRuntimeHandler
func (r *Runtime) ValidateRuntimeHandler(handler string) (RuntimeHandler, error) { if handler == "" { return RuntimeHandler{}, fmt.Errorf("empty runtime handler") } runtimeHandler, ok := r.runtimes[handler] if !ok { return RuntimeHandler{}, fmt.Errorf("failed to find runtime handler %s from runtime list %v", handler, r.runtimes) } if runtimeHandler.RuntimePath == "" { return RuntimeHandler{}, fmt.Errorf("empty runtime path for runtime handler %s", handler) } return runtimeHandler, nil }
go
func (r *Runtime) ValidateRuntimeHandler(handler string) (RuntimeHandler, error) { if handler == "" { return RuntimeHandler{}, fmt.Errorf("empty runtime handler") } runtimeHandler, ok := r.runtimes[handler] if !ok { return RuntimeHandler{}, fmt.Errorf("failed to find runtime handler %s from runtime list %v", handler, r.runtimes) } if runtimeHandler.RuntimePath == "" { return RuntimeHandler{}, fmt.Errorf("empty runtime path for runtime handler %s", handler) } return runtimeHandler, nil }
[ "func", "(", "r", "*", "Runtime", ")", "ValidateRuntimeHandler", "(", "handler", "string", ")", "(", "RuntimeHandler", ",", "error", ")", "{", "if", "handler", "==", "\"\"", "{", "return", "RuntimeHandler", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"empty runtime handler\"", ")", "\n", "}", "\n", "runtimeHandler", ",", "ok", ":=", "r", ".", "runtimes", "[", "handler", "]", "\n", "if", "!", "ok", "{", "return", "RuntimeHandler", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"failed to find runtime handler %s from runtime list %v\"", ",", "handler", ",", "r", ".", "runtimes", ")", "\n", "}", "\n", "if", "runtimeHandler", ".", "RuntimePath", "==", "\"\"", "{", "return", "RuntimeHandler", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"empty runtime path for runtime handler %s\"", ",", "handler", ")", "\n", "}", "\n", "return", "runtimeHandler", ",", "nil", "\n", "}" ]
// ValidateRuntimeHandler returns an error if the runtime handler string // provided does not match any valid use case.
[ "ValidateRuntimeHandler", "returns", "an", "error", "if", "the", "runtime", "handler", "string", "provided", "does", "not", "match", "any", "valid", "use", "case", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/oci.go#L143-L158
train
cri-o/cri-o
oci/oci.go
RuntimeImpl
func (r *Runtime) RuntimeImpl(c *Container) (RuntimeImpl, error) { impl, ok := r.runtimeImplList[c.ID()] if !ok { return r.newRuntimeImpl(c) } return impl, nil }
go
func (r *Runtime) RuntimeImpl(c *Container) (RuntimeImpl, error) { impl, ok := r.runtimeImplList[c.ID()] if !ok { return r.newRuntimeImpl(c) } return impl, nil }
[ "func", "(", "r", "*", "Runtime", ")", "RuntimeImpl", "(", "c", "*", "Container", ")", "(", "RuntimeImpl", ",", "error", ")", "{", "impl", ",", "ok", ":=", "r", ".", "runtimeImplList", "[", "c", ".", "ID", "(", ")", "]", "\n", "if", "!", "ok", "{", "return", "r", ".", "newRuntimeImpl", "(", "c", ")", "\n", "}", "\n", "return", "impl", ",", "nil", "\n", "}" ]
// RuntimeImpl returns the runtime implementation for a given container
[ "RuntimeImpl", "returns", "the", "runtime", "implementation", "for", "a", "given", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/oci.go#L249-L256
train
cri-o/cri-o
oci/oci_linux.go
newPipe
func newPipe() (parent *os.File, child *os.File, err error) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0) if err != nil { return nil, nil, err } return os.NewFile(uintptr(fds[1]), "parent"), os.NewFile(uintptr(fds[0]), "child"), nil }
go
func newPipe() (parent *os.File, child *os.File, err error) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0) if err != nil { return nil, nil, err } return os.NewFile(uintptr(fds[1]), "parent"), os.NewFile(uintptr(fds[0]), "child"), nil }
[ "func", "newPipe", "(", ")", "(", "parent", "*", "os", ".", "File", ",", "child", "*", "os", ".", "File", ",", "err", "error", ")", "{", "fds", ",", "err", ":=", "unix", ".", "Socketpair", "(", "unix", ".", "AF_LOCAL", ",", "unix", ".", "SOCK_STREAM", "|", "unix", ".", "SOCK_CLOEXEC", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "os", ".", "NewFile", "(", "uintptr", "(", "fds", "[", "1", "]", ")", ",", "\"parent\"", ")", ",", "os", ".", "NewFile", "(", "uintptr", "(", "fds", "[", "0", "]", ")", ",", "\"child\"", ")", ",", "nil", "\n", "}" ]
// newPipe creates a unix socket pair for communication
[ "newPipe", "creates", "a", "unix", "socket", "pair", "for", "communication" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/oci_linux.go#L59-L65
train
cri-o/cri-o
oci/kill.go
findStringInSignalMap
func findStringInSignalMap(killSignal syscall.Signal) (string, error) { for k, v := range signal.SignalMap { if v == killSignal { return k, nil } } return "", errors.Errorf("unable to convert signal to string") }
go
func findStringInSignalMap(killSignal syscall.Signal) (string, error) { for k, v := range signal.SignalMap { if v == killSignal { return k, nil } } return "", errors.Errorf("unable to convert signal to string") }
[ "func", "findStringInSignalMap", "(", "killSignal", "syscall", ".", "Signal", ")", "(", "string", ",", "error", ")", "{", "for", "k", ",", "v", ":=", "range", "signal", ".", "SignalMap", "{", "if", "v", "==", "killSignal", "{", "return", "k", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"unable to convert signal to string\"", ")", "\n", "}" ]
// Reverse lookup signal string from its map
[ "Reverse", "lookup", "signal", "string", "from", "its", "map" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/kill.go#L11-L19
train
cri-o/cri-o
lib/container.go
GetStorageContainer
func (c *ContainerServer) GetStorageContainer(container string) (*cstorage.Container, error) { ociCtr, err := c.LookupContainer(container) if err != nil { return nil, err } return c.store.Container(ociCtr.ID()) }
go
func (c *ContainerServer) GetStorageContainer(container string) (*cstorage.Container, error) { ociCtr, err := c.LookupContainer(container) if err != nil { return nil, err } return c.store.Container(ociCtr.ID()) }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetStorageContainer", "(", "container", "string", ")", "(", "*", "cstorage", ".", "Container", ",", "error", ")", "{", "ociCtr", ",", "err", ":=", "c", ".", "LookupContainer", "(", "container", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "c", ".", "store", ".", "Container", "(", "ociCtr", ".", "ID", "(", ")", ")", "\n", "}" ]
// GetStorageContainer searches for a container with the given name or ID in the given store
[ "GetStorageContainer", "searches", "for", "a", "container", "with", "the", "given", "name", "or", "ID", "in", "the", "given", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L14-L20
train
cri-o/cri-o
lib/container.go
GetContainerTopLayerID
func (c *ContainerServer) GetContainerTopLayerID(containerID string) (string, error) { ctr, err := c.GetStorageContainer(containerID) if err != nil { return "", err } return ctr.LayerID, nil }
go
func (c *ContainerServer) GetContainerTopLayerID(containerID string) (string, error) { ctr, err := c.GetStorageContainer(containerID) if err != nil { return "", err } return ctr.LayerID, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetContainerTopLayerID", "(", "containerID", "string", ")", "(", "string", ",", "error", ")", "{", "ctr", ",", "err", ":=", "c", ".", "GetStorageContainer", "(", "containerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "ctr", ".", "LayerID", ",", "nil", "\n", "}" ]
// GetContainerTopLayerID gets the ID of the top layer of the given container
[ "GetContainerTopLayerID", "gets", "the", "ID", "of", "the", "top", "layer", "of", "the", "given", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L23-L29
train
cri-o/cri-o
lib/container.go
GetContainerRwSize
func (c *ContainerServer) GetContainerRwSize(containerID string) (int64, error) { container, err := c.store.Container(containerID) if err != nil { return 0, err } // Get the size of the top layer by calculating the size of the diff // between the layer and its parent. The top layer of a container is // the only RW layer, all others are immutable layer, err := c.store.Layer(container.LayerID) if err != nil { return 0, err } return c.store.DiffSize(layer.Parent, layer.ID) }
go
func (c *ContainerServer) GetContainerRwSize(containerID string) (int64, error) { container, err := c.store.Container(containerID) if err != nil { return 0, err } // Get the size of the top layer by calculating the size of the diff // between the layer and its parent. The top layer of a container is // the only RW layer, all others are immutable layer, err := c.store.Layer(container.LayerID) if err != nil { return 0, err } return c.store.DiffSize(layer.Parent, layer.ID) }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetContainerRwSize", "(", "containerID", "string", ")", "(", "int64", ",", "error", ")", "{", "container", ",", "err", ":=", "c", ".", "store", ".", "Container", "(", "containerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "layer", ",", "err", ":=", "c", ".", "store", ".", "Layer", "(", "container", ".", "LayerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "c", ".", "store", ".", "DiffSize", "(", "layer", ".", "Parent", ",", "layer", ".", "ID", ")", "\n", "}" ]
// GetContainerRwSize Gets the size of the mutable top layer of the container
[ "GetContainerRwSize", "Gets", "the", "size", "of", "the", "mutable", "top", "layer", "of", "the", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L32-L46
train
cri-o/cri-o
lib/container.go
GetContainerFromShortID
func (c *ContainerServer) GetContainerFromShortID(cid string) (*oci.Container, error) { if cid == "" { return nil, fmt.Errorf("container ID should not be empty") } containerID, err := c.ctrIDIndex.Get(cid) if err != nil { return nil, fmt.Errorf("container with ID starting with %s not found: %v", cid, err) } ctr := c.GetContainer(containerID) if ctr == nil { return nil, fmt.Errorf("specified container not found: %s", containerID) } return ctr, nil }
go
func (c *ContainerServer) GetContainerFromShortID(cid string) (*oci.Container, error) { if cid == "" { return nil, fmt.Errorf("container ID should not be empty") } containerID, err := c.ctrIDIndex.Get(cid) if err != nil { return nil, fmt.Errorf("container with ID starting with %s not found: %v", cid, err) } ctr := c.GetContainer(containerID) if ctr == nil { return nil, fmt.Errorf("specified container not found: %s", containerID) } return ctr, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetContainerFromShortID", "(", "cid", "string", ")", "(", "*", "oci", ".", "Container", ",", "error", ")", "{", "if", "cid", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"container ID should not be empty\"", ")", "\n", "}", "\n", "containerID", ",", "err", ":=", "c", ".", "ctrIDIndex", ".", "Get", "(", "cid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"container with ID starting with %s not found: %v\"", ",", "cid", ",", "err", ")", "\n", "}", "\n", "ctr", ":=", "c", ".", "GetContainer", "(", "containerID", ")", "\n", "if", "ctr", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"specified container not found: %s\"", ",", "containerID", ")", "\n", "}", "\n", "return", "ctr", ",", "nil", "\n", "}" ]
// GetContainerFromShortID gets an oci container matching the specified full or partial id
[ "GetContainerFromShortID", "gets", "an", "oci", "container", "matching", "the", "specified", "full", "or", "partial", "id" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L89-L104
train
cri-o/cri-o
lib/container.go
LookupContainer
func (c *ContainerServer) LookupContainer(idOrName string) (*oci.Container, error) { if idOrName == "" { return nil, fmt.Errorf("container ID or name should not be empty") } ctrID, err := c.ctrNameIndex.Get(idOrName) if err != nil { if err == registrar.ErrNameNotReserved { ctrID = idOrName } else { return nil, err } } return c.GetContainerFromShortID(ctrID) }
go
func (c *ContainerServer) LookupContainer(idOrName string) (*oci.Container, error) { if idOrName == "" { return nil, fmt.Errorf("container ID or name should not be empty") } ctrID, err := c.ctrNameIndex.Get(idOrName) if err != nil { if err == registrar.ErrNameNotReserved { ctrID = idOrName } else { return nil, err } } return c.GetContainerFromShortID(ctrID) }
[ "func", "(", "c", "*", "ContainerServer", ")", "LookupContainer", "(", "idOrName", "string", ")", "(", "*", "oci", ".", "Container", ",", "error", ")", "{", "if", "idOrName", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"container ID or name should not be empty\"", ")", "\n", "}", "\n", "ctrID", ",", "err", ":=", "c", ".", "ctrNameIndex", ".", "Get", "(", "idOrName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "registrar", ".", "ErrNameNotReserved", "{", "ctrID", "=", "idOrName", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "c", ".", "GetContainerFromShortID", "(", "ctrID", ")", "\n", "}" ]
// LookupContainer returns the container with the given name or full or partial id
[ "LookupContainer", "returns", "the", "container", "with", "the", "given", "name", "or", "full", "or", "partial", "id" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L124-L139
train
cri-o/cri-o
lib/container.go
LookupSandbox
func (c *ContainerServer) LookupSandbox(idOrName string) (*sandbox.Sandbox, error) { if idOrName == "" { return nil, fmt.Errorf("container ID or name should not be empty") } podID, err := c.podNameIndex.Get(idOrName) if err != nil { if err == registrar.ErrNameNotReserved { podID = idOrName } else { return nil, err } } return c.getSandboxFromRequest(podID) }
go
func (c *ContainerServer) LookupSandbox(idOrName string) (*sandbox.Sandbox, error) { if idOrName == "" { return nil, fmt.Errorf("container ID or name should not be empty") } podID, err := c.podNameIndex.Get(idOrName) if err != nil { if err == registrar.ErrNameNotReserved { podID = idOrName } else { return nil, err } } return c.getSandboxFromRequest(podID) }
[ "func", "(", "c", "*", "ContainerServer", ")", "LookupSandbox", "(", "idOrName", "string", ")", "(", "*", "sandbox", ".", "Sandbox", ",", "error", ")", "{", "if", "idOrName", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"container ID or name should not be empty\"", ")", "\n", "}", "\n", "podID", ",", "err", ":=", "c", ".", "podNameIndex", ".", "Get", "(", "idOrName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "registrar", ".", "ErrNameNotReserved", "{", "podID", "=", "idOrName", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "c", ".", "getSandboxFromRequest", "(", "podID", ")", "\n", "}" ]
// LookupSandbox returns the pod sandbox with the given name or full or partial id
[ "LookupSandbox", "returns", "the", "pod", "sandbox", "with", "the", "given", "name", "or", "full", "or", "partial", "id" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container.go#L142-L157
train
cri-o/cri-o
server/container_exec.go
Exec
func (ss StreamService) Exec(containerID string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { c, err := ss.runtimeServer.GetContainerFromShortID(containerID) if err != nil { return fmt.Errorf("could not find container %q: %v", containerID, err) } if err := ss.runtimeServer.Runtime().UpdateContainerStatus(c); err != nil { return err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return fmt.Errorf("container is not created or running") } return ss.runtimeServer.Runtime().ExecContainer(c, cmd, stdin, stdout, stderr, tty, resize) }
go
func (ss StreamService) Exec(containerID string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { c, err := ss.runtimeServer.GetContainerFromShortID(containerID) if err != nil { return fmt.Errorf("could not find container %q: %v", containerID, err) } if err := ss.runtimeServer.Runtime().UpdateContainerStatus(c); err != nil { return err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return fmt.Errorf("container is not created or running") } return ss.runtimeServer.Runtime().ExecContainer(c, cmd, stdin, stdout, stderr, tty, resize) }
[ "func", "(", "ss", "StreamService", ")", "Exec", "(", "containerID", "string", ",", "cmd", "[", "]", "string", ",", "stdin", "io", ".", "Reader", ",", "stdout", ",", "stderr", "io", ".", "WriteCloser", ",", "tty", "bool", ",", "resize", "<-", "chan", "remotecommand", ".", "TerminalSize", ")", "error", "{", "c", ",", "err", ":=", "ss", ".", "runtimeServer", ".", "GetContainerFromShortID", "(", "containerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not find container %q: %v\"", ",", "containerID", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "ss", ".", "runtimeServer", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cState", ":=", "c", ".", "State", "(", ")", "\n", "if", "!", "(", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "||", "cState", ".", "Status", "==", "oci", ".", "ContainerStateCreated", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"container is not created or running\"", ")", "\n", "}", "\n", "return", "ss", ".", "runtimeServer", ".", "Runtime", "(", ")", ".", "ExecContainer", "(", "c", ",", "cmd", ",", "stdin", ",", "stdout", ",", "stderr", ",", "tty", ",", "resize", ")", "\n", "}" ]
// Exec endpoint for streaming.Runtime
[ "Exec", "endpoint", "for", "streaming", ".", "Runtime" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_exec.go#L34-L50
train
fatih/structs
field.go
Tag
func (f *Field) Tag(key string) string { return f.field.Tag.Get(key) }
go
func (f *Field) Tag(key string) string { return f.field.Tag.Get(key) }
[ "func", "(", "f", "*", "Field", ")", "Tag", "(", "key", "string", ")", "string", "{", "return", "f", ".", "field", ".", "Tag", ".", "Get", "(", "key", ")", "\n", "}" ]
// Tag returns the value associated with key in the tag string. If there is no // such key in the tag, Tag returns the empty string.
[ "Tag", "returns", "the", "value", "associated", "with", "key", "in", "the", "tag", "string", ".", "If", "there", "is", "no", "such", "key", "in", "the", "tag", "Tag", "returns", "the", "empty", "string", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/field.go#L24-L26
train
fatih/structs
field.go
Field
func (f *Field) Field(name string) *Field { field, ok := f.FieldOk(name) if !ok { panic("field not found") } return field }
go
func (f *Field) Field(name string) *Field { field, ok := f.FieldOk(name) if !ok { panic("field not found") } return field }
[ "func", "(", "f", "*", "Field", ")", "Field", "(", "name", "string", ")", "*", "Field", "{", "field", ",", "ok", ":=", "f", ".", "FieldOk", "(", "name", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"field not found\"", ")", "\n", "}", "\n", "return", "field", "\n", "}" ]
// Field returns the field from a nested struct. It panics if the nested struct // is not exported or if the field was not found.
[ "Field", "returns", "the", "field", "from", "a", "nested", "struct", ".", "It", "panics", "if", "the", "nested", "struct", "is", "not", "exported", "or", "if", "the", "field", "was", "not", "found", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/field.go#L108-L115
train
fatih/structs
structs.go
FillMap
func (s *Struct) FillMap(out map[string]interface{}) { if out == nil { return } fields := s.structFields() for _, field := range fields { name := field.Name val := s.value.FieldByName(name) isSubStruct := false var finalVal interface{} tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) if tagName != "" { name = tagName } // if the value is a zero value and the field is marked as omitempty do // not include if tagOpts.Has("omitempty") { zero := reflect.Zero(val.Type()).Interface() current := val.Interface() if reflect.DeepEqual(current, zero) { continue } } if !tagOpts.Has("omitnested") { finalVal = s.nested(val) v := reflect.ValueOf(val.Interface()) if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Map, reflect.Struct: isSubStruct = true } } else { finalVal = val.Interface() } if tagOpts.Has("string") { s, ok := val.Interface().(fmt.Stringer) if ok { out[name] = s.String() } continue } if isSubStruct && (tagOpts.Has("flatten")) { for k := range finalVal.(map[string]interface{}) { out[k] = finalVal.(map[string]interface{})[k] } } else { out[name] = finalVal } } }
go
func (s *Struct) FillMap(out map[string]interface{}) { if out == nil { return } fields := s.structFields() for _, field := range fields { name := field.Name val := s.value.FieldByName(name) isSubStruct := false var finalVal interface{} tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) if tagName != "" { name = tagName } // if the value is a zero value and the field is marked as omitempty do // not include if tagOpts.Has("omitempty") { zero := reflect.Zero(val.Type()).Interface() current := val.Interface() if reflect.DeepEqual(current, zero) { continue } } if !tagOpts.Has("omitnested") { finalVal = s.nested(val) v := reflect.ValueOf(val.Interface()) if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Map, reflect.Struct: isSubStruct = true } } else { finalVal = val.Interface() } if tagOpts.Has("string") { s, ok := val.Interface().(fmt.Stringer) if ok { out[name] = s.String() } continue } if isSubStruct && (tagOpts.Has("flatten")) { for k := range finalVal.(map[string]interface{}) { out[k] = finalVal.(map[string]interface{})[k] } } else { out[name] = finalVal } } }
[ "func", "(", "s", "*", "Struct", ")", "FillMap", "(", "out", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "if", "out", "==", "nil", "{", "return", "\n", "}", "\n", "fields", ":=", "s", ".", "structFields", "(", ")", "\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "name", ":=", "field", ".", "Name", "\n", "val", ":=", "s", ".", "value", ".", "FieldByName", "(", "name", ")", "\n", "isSubStruct", ":=", "false", "\n", "var", "finalVal", "interface", "{", "}", "\n", "tagName", ",", "tagOpts", ":=", "parseTag", "(", "field", ".", "Tag", ".", "Get", "(", "s", ".", "TagName", ")", ")", "\n", "if", "tagName", "!=", "\"\"", "{", "name", "=", "tagName", "\n", "}", "\n", "if", "tagOpts", ".", "Has", "(", "\"omitempty\"", ")", "{", "zero", ":=", "reflect", ".", "Zero", "(", "val", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "current", ":=", "val", ".", "Interface", "(", ")", "\n", "if", "reflect", ".", "DeepEqual", "(", "current", ",", "zero", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "if", "!", "tagOpts", ".", "Has", "(", "\"omitnested\"", ")", "{", "finalVal", "=", "s", ".", "nested", "(", "val", ")", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "val", ".", "Interface", "(", ")", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ",", "reflect", ".", "Struct", ":", "isSubStruct", "=", "true", "\n", "}", "\n", "}", "else", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "}", "\n", "if", "tagOpts", ".", "Has", "(", "\"string\"", ")", "{", "s", ",", "ok", ":=", "val", ".", "Interface", "(", ")", ".", "(", "fmt", ".", "Stringer", ")", "\n", "if", "ok", "{", "out", "[", "name", "]", "=", "s", ".", "String", "(", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "if", "isSubStruct", "&&", "(", "tagOpts", ".", "Has", "(", "\"flatten\"", ")", ")", "{", "for", "k", ":=", "range", "finalVal", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "out", "[", "k", "]", "=", "finalVal", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "[", "k", "]", "\n", "}", "\n", "}", "else", "{", "out", "[", "name", "]", "=", "finalVal", "\n", "}", "\n", "}", "\n", "}" ]
// FillMap is the same as Map. Instead of returning the output, it fills the // given map.
[ "FillMap", "is", "the", "same", "as", "Map", ".", "Instead", "of", "returning", "the", "output", "it", "fills", "the", "given", "map", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L89-L150
train
fatih/structs
structs.go
Field
func (s *Struct) Field(name string) *Field { f, ok := s.FieldOk(name) if !ok { panic("field not found") } return f }
go
func (s *Struct) Field(name string) *Field { f, ok := s.FieldOk(name) if !ok { panic("field not found") } return f }
[ "func", "(", "s", "*", "Struct", ")", "Field", "(", "name", "string", ")", "*", "Field", "{", "f", ",", "ok", ":=", "s", ".", "FieldOk", "(", "name", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"field not found\"", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// Field returns a new Field struct that provides several high level functions // around a single struct field entity. It panics if the field is not found.
[ "Field", "returns", "a", "new", "Field", "struct", "that", "provides", "several", "high", "level", "functions", "around", "a", "single", "struct", "field", "entity", ".", "It", "panics", "if", "the", "field", "is", "not", "found", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L275-L282
train
fatih/structs
structs.go
FieldOk
func (s *Struct) FieldOk(name string) (*Field, bool) { t := s.value.Type() field, ok := t.FieldByName(name) if !ok { return nil, false } return &Field{ field: field, value: s.value.FieldByName(name), defaultTag: s.TagName, }, true }
go
func (s *Struct) FieldOk(name string) (*Field, bool) { t := s.value.Type() field, ok := t.FieldByName(name) if !ok { return nil, false } return &Field{ field: field, value: s.value.FieldByName(name), defaultTag: s.TagName, }, true }
[ "func", "(", "s", "*", "Struct", ")", "FieldOk", "(", "name", "string", ")", "(", "*", "Field", ",", "bool", ")", "{", "t", ":=", "s", ".", "value", ".", "Type", "(", ")", "\n", "field", ",", "ok", ":=", "t", ".", "FieldByName", "(", "name", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "false", "\n", "}", "\n", "return", "&", "Field", "{", "field", ":", "field", ",", "value", ":", "s", ".", "value", ".", "FieldByName", "(", "name", ")", ",", "defaultTag", ":", "s", ".", "TagName", ",", "}", ",", "true", "\n", "}" ]
// FieldOk returns a new Field struct that provides several high level functions // around a single struct field entity. The boolean returns true if the field // was found.
[ "FieldOk", "returns", "a", "new", "Field", "struct", "that", "provides", "several", "high", "level", "functions", "around", "a", "single", "struct", "field", "entity", ".", "The", "boolean", "returns", "true", "if", "the", "field", "was", "found", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L287-L300
train
fatih/structs
structs.go
structFields
func (s *Struct) structFields() []reflect.StructField { t := s.value.Type() var f []reflect.StructField for i := 0; i < t.NumField(); i++ { field := t.Field(i) // we can't access the value of unexported fields if field.PkgPath != "" { continue } // don't check if it's omitted if tag := field.Tag.Get(s.TagName); tag == "-" { continue } f = append(f, field) } return f }
go
func (s *Struct) structFields() []reflect.StructField { t := s.value.Type() var f []reflect.StructField for i := 0; i < t.NumField(); i++ { field := t.Field(i) // we can't access the value of unexported fields if field.PkgPath != "" { continue } // don't check if it's omitted if tag := field.Tag.Get(s.TagName); tag == "-" { continue } f = append(f, field) } return f }
[ "func", "(", "s", "*", "Struct", ")", "structFields", "(", ")", "[", "]", "reflect", ".", "StructField", "{", "t", ":=", "s", ".", "value", ".", "Type", "(", ")", "\n", "var", "f", "[", "]", "reflect", ".", "StructField", "\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "t", ".", "Field", "(", "i", ")", "\n", "if", "field", ".", "PkgPath", "!=", "\"\"", "{", "continue", "\n", "}", "\n", "if", "tag", ":=", "field", ".", "Tag", ".", "Get", "(", "s", ".", "TagName", ")", ";", "tag", "==", "\"-\"", "{", "continue", "\n", "}", "\n", "f", "=", "append", "(", "f", ",", "field", ")", "\n", "}", "\n", "return", "f", "\n", "}" ]
// structFields returns the exported struct fields for a given s struct. This // is a convenient helper method to avoid duplicate code in some of the // functions.
[ "structFields", "returns", "the", "exported", "struct", "fields", "for", "a", "given", "s", "struct", ".", "This", "is", "a", "convenient", "helper", "method", "to", "avoid", "duplicate", "code", "in", "some", "of", "the", "functions", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L405-L426
train
fatih/structs
structs.go
IsStruct
func IsStruct(s interface{}) bool { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = v.Elem() } // uninitialized zero value of a struct if v.Kind() == reflect.Invalid { return false } return v.Kind() == reflect.Struct }
go
func IsStruct(s interface{}) bool { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = v.Elem() } // uninitialized zero value of a struct if v.Kind() == reflect.Invalid { return false } return v.Kind() == reflect.Struct }
[ "func", "IsStruct", "(", "s", "interface", "{", "}", ")", "bool", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "s", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Invalid", "{", "return", "false", "\n", "}", "\n", "return", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "\n", "}" ]
// IsStruct returns true if the given variable is a struct or a pointer to // struct.
[ "IsStruct", "returns", "true", "if", "the", "given", "variable", "is", "a", "struct", "or", "a", "pointer", "to", "struct", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L487-L499
train
fatih/structs
structs.go
nested
func (s *Struct) nested(val reflect.Value) interface{} { var finalVal interface{} v := reflect.ValueOf(val.Interface()) if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: n := New(val.Interface()) n.TagName = s.TagName m := n.Map() // do not add the converted value if there are no exported fields, ie: // time.Time if len(m) == 0 { finalVal = val.Interface() } else { finalVal = m } case reflect.Map: // get the element type of the map mapElem := val.Type() switch val.Type().Kind() { case reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice, reflect.Chan: mapElem = val.Type().Elem() if mapElem.Kind() == reflect.Ptr { mapElem = mapElem.Elem() } } // only iterate over struct types, ie: map[string]StructType, // map[string][]StructType, if mapElem.Kind() == reflect.Struct || (mapElem.Kind() == reflect.Slice && mapElem.Elem().Kind() == reflect.Struct) { m := make(map[string]interface{}, val.Len()) for _, k := range val.MapKeys() { m[k.String()] = s.nested(val.MapIndex(k)) } finalVal = m break } // TODO(arslan): should this be optional? finalVal = val.Interface() case reflect.Slice, reflect.Array: if val.Type().Kind() == reflect.Interface { finalVal = val.Interface() break } // TODO(arslan): should this be optional? // do not iterate of non struct types, just pass the value. Ie: []int, // []string, co... We only iterate further if it's a struct. // i.e []foo or []*foo if val.Type().Elem().Kind() != reflect.Struct && !(val.Type().Elem().Kind() == reflect.Ptr && val.Type().Elem().Elem().Kind() == reflect.Struct) { finalVal = val.Interface() break } slices := make([]interface{}, val.Len()) for x := 0; x < val.Len(); x++ { slices[x] = s.nested(val.Index(x)) } finalVal = slices default: finalVal = val.Interface() } return finalVal }
go
func (s *Struct) nested(val reflect.Value) interface{} { var finalVal interface{} v := reflect.ValueOf(val.Interface()) if v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: n := New(val.Interface()) n.TagName = s.TagName m := n.Map() // do not add the converted value if there are no exported fields, ie: // time.Time if len(m) == 0 { finalVal = val.Interface() } else { finalVal = m } case reflect.Map: // get the element type of the map mapElem := val.Type() switch val.Type().Kind() { case reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice, reflect.Chan: mapElem = val.Type().Elem() if mapElem.Kind() == reflect.Ptr { mapElem = mapElem.Elem() } } // only iterate over struct types, ie: map[string]StructType, // map[string][]StructType, if mapElem.Kind() == reflect.Struct || (mapElem.Kind() == reflect.Slice && mapElem.Elem().Kind() == reflect.Struct) { m := make(map[string]interface{}, val.Len()) for _, k := range val.MapKeys() { m[k.String()] = s.nested(val.MapIndex(k)) } finalVal = m break } // TODO(arslan): should this be optional? finalVal = val.Interface() case reflect.Slice, reflect.Array: if val.Type().Kind() == reflect.Interface { finalVal = val.Interface() break } // TODO(arslan): should this be optional? // do not iterate of non struct types, just pass the value. Ie: []int, // []string, co... We only iterate further if it's a struct. // i.e []foo or []*foo if val.Type().Elem().Kind() != reflect.Struct && !(val.Type().Elem().Kind() == reflect.Ptr && val.Type().Elem().Elem().Kind() == reflect.Struct) { finalVal = val.Interface() break } slices := make([]interface{}, val.Len()) for x := 0; x < val.Len(); x++ { slices[x] = s.nested(val.Index(x)) } finalVal = slices default: finalVal = val.Interface() } return finalVal }
[ "func", "(", "s", "*", "Struct", ")", "nested", "(", "val", "reflect", ".", "Value", ")", "interface", "{", "}", "{", "var", "finalVal", "interface", "{", "}", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "val", ".", "Interface", "(", ")", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "n", ":=", "New", "(", "val", ".", "Interface", "(", ")", ")", "\n", "n", ".", "TagName", "=", "s", ".", "TagName", "\n", "m", ":=", "n", ".", "Map", "(", ")", "\n", "if", "len", "(", "m", ")", "==", "0", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "}", "else", "{", "finalVal", "=", "m", "\n", "}", "\n", "case", "reflect", ".", "Map", ":", "mapElem", ":=", "val", ".", "Type", "(", ")", "\n", "switch", "val", ".", "Type", "(", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Ptr", ",", "reflect", ".", "Array", ",", "reflect", ".", "Map", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Chan", ":", "mapElem", "=", "val", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n", "if", "mapElem", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "mapElem", "=", "mapElem", ".", "Elem", "(", ")", "\n", "}", "\n", "}", "\n", "if", "mapElem", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "||", "(", "mapElem", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "&&", "mapElem", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "val", ".", "Len", "(", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "val", ".", "MapKeys", "(", ")", "{", "m", "[", "k", ".", "String", "(", ")", "]", "=", "s", ".", "nested", "(", "val", ".", "MapIndex", "(", "k", ")", ")", "\n", "}", "\n", "finalVal", "=", "m", "\n", "break", "\n", "}", "\n", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "case", "reflect", ".", "Slice", ",", "reflect", ".", "Array", ":", "if", "val", ".", "Type", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "break", "\n", "}", "\n", "if", "val", ".", "Type", "(", ")", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "&&", "!", "(", "val", ".", "Type", "(", ")", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "&&", "val", ".", "Type", "(", ")", ".", "Elem", "(", ")", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", ")", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "break", "\n", "}", "\n", "slices", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "val", ".", "Len", "(", ")", ")", "\n", "for", "x", ":=", "0", ";", "x", "<", "val", ".", "Len", "(", ")", ";", "x", "++", "{", "slices", "[", "x", "]", "=", "s", ".", "nested", "(", "val", ".", "Index", "(", "x", ")", ")", "\n", "}", "\n", "finalVal", "=", "slices", "\n", "default", ":", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "}", "\n", "return", "finalVal", "\n", "}" ]
// nested retrieves recursively all types for the given value and returns the // nested value.
[ "nested", "retrieves", "recursively", "all", "types", "for", "the", "given", "value", "and", "returns", "the", "nested", "value", "." ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/structs.go#L509-L584
train
fatih/structs
tags.go
Has
func (t tagOptions) Has(opt string) bool { for _, tagOpt := range t { if tagOpt == opt { return true } } return false }
go
func (t tagOptions) Has(opt string) bool { for _, tagOpt := range t { if tagOpt == opt { return true } } return false }
[ "func", "(", "t", "tagOptions", ")", "Has", "(", "opt", "string", ")", "bool", "{", "for", "_", ",", "tagOpt", ":=", "range", "t", "{", "if", "tagOpt", "==", "opt", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Has returns true if the given option is available in tagOptions
[ "Has", "returns", "true", "if", "the", "given", "option", "is", "available", "in", "tagOptions" ]
878a968ab22548362a09bdb3322f98b00f470d46
https://github.com/fatih/structs/blob/878a968ab22548362a09bdb3322f98b00f470d46/tags.go#L9-L17
train
micro/go-plugins
registry/eureka/options.go
OAuth2ClientCredentials
func OAuth2ClientCredentials(clientID, clientSecret, tokenURL string) registry.Option { return func(o *registry.Options) { c := clientcredentials.Config{ ClientID: clientID, ClientSecret: clientSecret, TokenURL: tokenURL, } o.Context = context.WithValue(o.Context, contextHttpClient{}, newOAuthClient(c)) } }
go
func OAuth2ClientCredentials(clientID, clientSecret, tokenURL string) registry.Option { return func(o *registry.Options) { c := clientcredentials.Config{ ClientID: clientID, ClientSecret: clientSecret, TokenURL: tokenURL, } o.Context = context.WithValue(o.Context, contextHttpClient{}, newOAuthClient(c)) } }
[ "func", "OAuth2ClientCredentials", "(", "clientID", ",", "clientSecret", ",", "tokenURL", "string", ")", "registry", ".", "Option", "{", "return", "func", "(", "o", "*", "registry", ".", "Options", ")", "{", "c", ":=", "clientcredentials", ".", "Config", "{", "ClientID", ":", "clientID", ",", "ClientSecret", ":", "clientSecret", ",", "TokenURL", ":", "tokenURL", ",", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "contextHttpClient", "{", "}", ",", "newOAuthClient", "(", "c", ")", ")", "\n", "}", "\n", "}" ]
// Enable OAuth 2.0 Client Credentials Grant Flow
[ "Enable", "OAuth", "2", ".", "0", "Client", "Credentials", "Grant", "Flow" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/eureka/options.go#L19-L29
train
micro/go-plugins
wrapper/trace/awsxray/util.go
getHTTP
func getHTTP(url, method string, err error) *awsxray.HTTP { return &awsxray.HTTP{ Request: &awsxray.Request{ Method: method, URL: url, }, Response: &awsxray.Response{ Status: getStatus(err), }, } }
go
func getHTTP(url, method string, err error) *awsxray.HTTP { return &awsxray.HTTP{ Request: &awsxray.Request{ Method: method, URL: url, }, Response: &awsxray.Response{ Status: getStatus(err), }, } }
[ "func", "getHTTP", "(", "url", ",", "method", "string", ",", "err", "error", ")", "*", "awsxray", ".", "HTTP", "{", "return", "&", "awsxray", ".", "HTTP", "{", "Request", ":", "&", "awsxray", ".", "Request", "{", "Method", ":", "method", ",", "URL", ":", "url", ",", "}", ",", "Response", ":", "&", "awsxray", ".", "Response", "{", "Status", ":", "getStatus", "(", "err", ")", ",", "}", ",", "}", "\n", "}" ]
// getHTTP returns a http struct
[ "getHTTP", "returns", "a", "http", "struct" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/util.go#L16-L26
train
micro/go-plugins
wrapper/trace/awsxray/util.go
getSegment
func getSegment(name string, ctx context.Context) *awsxray.Segment { md, _ := metadata.FromContext(ctx) parentId := getParentId(md) traceId := getTraceId(md) // try get existing segment for parent Id if s, ok := awsxray.FromContext(ctx); ok { // only set existing segment as parent if its not a subsegment itself if len(parentId) == 0 && len(s.Type) == 0 { parentId = s.Id } if len(traceId) == 0 { traceId = s.TraceId } } // create segment s := &awsxray.Segment{ Id: fmt.Sprintf("%x", getRandom(8)), Name: name, TraceId: traceId, StartTime: float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9, } // we have a parent so subsegment if len(parentId) > 0 { s.ParentId = parentId s.Type = "subsegment" } return s }
go
func getSegment(name string, ctx context.Context) *awsxray.Segment { md, _ := metadata.FromContext(ctx) parentId := getParentId(md) traceId := getTraceId(md) // try get existing segment for parent Id if s, ok := awsxray.FromContext(ctx); ok { // only set existing segment as parent if its not a subsegment itself if len(parentId) == 0 && len(s.Type) == 0 { parentId = s.Id } if len(traceId) == 0 { traceId = s.TraceId } } // create segment s := &awsxray.Segment{ Id: fmt.Sprintf("%x", getRandom(8)), Name: name, TraceId: traceId, StartTime: float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9, } // we have a parent so subsegment if len(parentId) > 0 { s.ParentId = parentId s.Type = "subsegment" } return s }
[ "func", "getSegment", "(", "name", "string", ",", "ctx", "context", ".", "Context", ")", "*", "awsxray", ".", "Segment", "{", "md", ",", "_", ":=", "metadata", ".", "FromContext", "(", "ctx", ")", "\n", "parentId", ":=", "getParentId", "(", "md", ")", "\n", "traceId", ":=", "getTraceId", "(", "md", ")", "\n", "if", "s", ",", "ok", ":=", "awsxray", ".", "FromContext", "(", "ctx", ")", ";", "ok", "{", "if", "len", "(", "parentId", ")", "==", "0", "&&", "len", "(", "s", ".", "Type", ")", "==", "0", "{", "parentId", "=", "s", ".", "Id", "\n", "}", "\n", "if", "len", "(", "traceId", ")", "==", "0", "{", "traceId", "=", "s", ".", "TraceId", "\n", "}", "\n", "}", "\n", "s", ":=", "&", "awsxray", ".", "Segment", "{", "Id", ":", "fmt", ".", "Sprintf", "(", "\"%x\"", ",", "getRandom", "(", "8", ")", ")", ",", "Name", ":", "name", ",", "TraceId", ":", "traceId", ",", "StartTime", ":", "float64", "(", "time", ".", "Now", "(", ")", ".", "Truncate", "(", "time", ".", "Millisecond", ")", ".", "UnixNano", "(", ")", ")", "/", "1e9", ",", "}", "\n", "if", "len", "(", "parentId", ")", ">", "0", "{", "s", ".", "ParentId", "=", "parentId", "\n", "s", ".", "Type", "=", "\"subsegment\"", "\n", "}", "\n", "return", "s", "\n", "}" ]
// getSegment creates a new segment based on whether we're part of an existing flow
[ "getSegment", "creates", "a", "new", "segment", "based", "on", "whether", "we", "re", "part", "of", "an", "existing", "flow" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/util.go#L41-L72
train
micro/go-plugins
wrapper/trace/awsxray/util.go
getStatus
func getStatus(err error) int { // no error if err == nil { return 200 } // try get errors.Error if e, ok := err.(*errors.Error); ok { return int(e.Code) } // try parse marshalled error if e := errors.Parse(err.Error()); e.Code > 0 { return int(e.Code) } // could not parse, 500 return 500 }
go
func getStatus(err error) int { // no error if err == nil { return 200 } // try get errors.Error if e, ok := err.(*errors.Error); ok { return int(e.Code) } // try parse marshalled error if e := errors.Parse(err.Error()); e.Code > 0 { return int(e.Code) } // could not parse, 500 return 500 }
[ "func", "getStatus", "(", "err", "error", ")", "int", "{", "if", "err", "==", "nil", "{", "return", "200", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "errors", ".", "Error", ")", ";", "ok", "{", "return", "int", "(", "e", ".", "Code", ")", "\n", "}", "\n", "if", "e", ":=", "errors", ".", "Parse", "(", "err", ".", "Error", "(", ")", ")", ";", "e", ".", "Code", ">", "0", "{", "return", "int", "(", "e", ".", "Code", ")", "\n", "}", "\n", "return", "500", "\n", "}" ]
// getStatus returns a status code from the error
[ "getStatus", "returns", "a", "status", "code", "from", "the", "error" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/util.go#L75-L93
train
micro/go-plugins
wrapper/trace/awsxray/util.go
setCallStatus
func setCallStatus(s *awsxray.Segment, url, method string, err error) { s.HTTP = getHTTP(url, method, err) status := getStatus(err) switch { case status >= 500: s.Fault = true case status >= 400: s.Error = true case err != nil: s.Fault = true } }
go
func setCallStatus(s *awsxray.Segment, url, method string, err error) { s.HTTP = getHTTP(url, method, err) status := getStatus(err) switch { case status >= 500: s.Fault = true case status >= 400: s.Error = true case err != nil: s.Fault = true } }
[ "func", "setCallStatus", "(", "s", "*", "awsxray", ".", "Segment", ",", "url", ",", "method", "string", ",", "err", "error", ")", "{", "s", ".", "HTTP", "=", "getHTTP", "(", "url", ",", "method", ",", "err", ")", "\n", "status", ":=", "getStatus", "(", "err", ")", "\n", "switch", "{", "case", "status", ">=", "500", ":", "s", ".", "Fault", "=", "true", "\n", "case", "status", ">=", "400", ":", "s", ".", "Error", "=", "true", "\n", "case", "err", "!=", "nil", ":", "s", ".", "Fault", "=", "true", "\n", "}", "\n", "}" ]
// setCallStatus sets the http section and related status
[ "setCallStatus", "sets", "the", "http", "section", "and", "related", "status" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/util.go#L140-L152
train
micro/go-plugins
wrapper/breaker/hystrix/hystrix.go
NewClientWrapper
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &clientWrapper{c} } }
go
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &clientWrapper{c} } }
[ "func", "NewClientWrapper", "(", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "clientWrapper", "{", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper returns a hystrix client Wrapper.
[ "NewClientWrapper", "returns", "a", "hystrix", "client", "Wrapper", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/breaker/hystrix/hystrix.go#L21-L25
train
micro/go-plugins
codec/msgpackrpc/rpc.go
decodeBody
func decodeBody(r *msgp.Reader, v interface{}) error { b, ok := v.(msgp.Decodable) if !ok { return ErrNotDecodable } return msgp.Decode(r, b) }
go
func decodeBody(r *msgp.Reader, v interface{}) error { b, ok := v.(msgp.Decodable) if !ok { return ErrNotDecodable } return msgp.Decode(r, b) }
[ "func", "decodeBody", "(", "r", "*", "msgp", ".", "Reader", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "ok", ":=", "v", ".", "(", "msgp", ".", "Decodable", ")", "\n", "if", "!", "ok", "{", "return", "ErrNotDecodable", "\n", "}", "\n", "return", "msgp", ".", "Decode", "(", "r", ",", "b", ")", "\n", "}" ]
// decodeBody decodes the body of the message.
[ "decodeBody", "decodes", "the", "body", "of", "the", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/rpc.go#L31-L38
train
micro/go-plugins
codec/msgpackrpc/rpc.go
EncodeMsg
func (r *Request) EncodeMsg(w *msgp.Writer) error { var bm msgp.Encodable if r.Body != nil { var ok bool bm, ok = r.Body.(msgp.Encodable) if !ok { return ErrNotEncodable } } var err error if err = w.WriteArrayHeader(RequestPackSize); err != nil { return err } if err = w.WriteInt(RequestType); err != nil { return err } if err = w.WriteString(r.ID); err != nil { return err } if err = w.WriteString(r.Method); err != nil { return err } // No body to encode. Write a zero-length params array. if bm == nil { return w.WriteArrayHeader(0) } // 1-item array containing the body. if err = w.WriteArrayHeader(1); err != nil { return err } return msgp.Encode(w, bm) }
go
func (r *Request) EncodeMsg(w *msgp.Writer) error { var bm msgp.Encodable if r.Body != nil { var ok bool bm, ok = r.Body.(msgp.Encodable) if !ok { return ErrNotEncodable } } var err error if err = w.WriteArrayHeader(RequestPackSize); err != nil { return err } if err = w.WriteInt(RequestType); err != nil { return err } if err = w.WriteString(r.ID); err != nil { return err } if err = w.WriteString(r.Method); err != nil { return err } // No body to encode. Write a zero-length params array. if bm == nil { return w.WriteArrayHeader(0) } // 1-item array containing the body. if err = w.WriteArrayHeader(1); err != nil { return err } return msgp.Encode(w, bm) }
[ "func", "(", "r", "*", "Request", ")", "EncodeMsg", "(", "w", "*", "msgp", ".", "Writer", ")", "error", "{", "var", "bm", "msgp", ".", "Encodable", "\n", "if", "r", ".", "Body", "!=", "nil", "{", "var", "ok", "bool", "\n", "bm", ",", "ok", "=", "r", ".", "Body", ".", "(", "msgp", ".", "Encodable", ")", "\n", "if", "!", "ok", "{", "return", "ErrNotEncodable", "\n", "}", "\n", "}", "\n", "var", "err", "error", "\n", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "RequestPackSize", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "w", ".", "WriteInt", "(", "RequestType", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "w", ".", "WriteString", "(", "r", ".", "ID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "w", ".", "WriteString", "(", "r", ".", "Method", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "bm", "==", "nil", "{", "return", "w", ".", "WriteArrayHeader", "(", "0", ")", "\n", "}", "\n", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "msgp", ".", "Encode", "(", "w", ",", "bm", ")", "\n", "}" ]
// EncodeMsg encodes the request to writer. The body is expected to // be an encodable type.
[ "EncodeMsg", "encodes", "the", "request", "to", "writer", ".", "The", "body", "is", "expected", "to", "be", "an", "encodable", "type", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/rpc.go#L52-L92
train