repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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\n", "cStatus", ":=", "ctr", ".", "State", "(", ")", "\n", "switch", "cStatus", ".", "Status", "{", "case", "oci", ".", "ContainerStatePaused", ":", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ctrID", ")", "\n", "case", "oci", ".", "ContainerStateCreated", ",", "oci", ".", "ContainerStateRunning", ":", "if", "force", "{", "_", ",", "err", "=", "c", ".", "ContainerStop", "(", "ctx", ",", "container", ",", "10", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "ctrID", ")", "\n", "}", "\n", "}", "else", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ctrID", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "runtime", ".", "DeleteContainer", "(", "ctr", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "ctrID", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "filepath", ".", "Join", "(", "c", ".", "Config", "(", ")", ".", "RuntimeConfig", ".", "ContainerExitsDir", ",", "ctrID", ")", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "ctrID", ")", "\n", "}", "\n", "c", ".", "RemoveContainer", "(", "ctr", ")", "\n\n", "if", "err", ":=", "c", ".", "storageRuntimeServer", ".", "DeleteContainer", "(", "ctrID", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "ctrID", ")", "\n", "}", "\n\n", "c", ".", "ReleaseContainerName", "(", "ctr", ".", "Name", "(", ")", ")", "\n\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", "(", "\"", "\"", ",", "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", "{", "// call to check that v is a pointer", "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", ":", "// avoid reserializing the type if we have an 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\n", "url", ",", "err", ":=", "TypeURL", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\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", ")", "{", "// # 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", "\n", "kubeArgs", ":=", "containerKubeConfig", ".", "Args", "\n\n", "// 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", "\n", "}", "\n", "if", "kubeCommands", "==", "nil", "{", "kubeCommands", "=", "imageOCIConfig", ".", "Config", ".", "Entrypoint", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "kubeCommands", ")", "==", "0", "&&", "len", "(", "kubeArgs", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// create entrypoint and args", "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\n", "processArgs", ":=", "append", "(", "[", "]", "string", "{", "entrypoint", "}", ",", "args", "...", ")", "\n\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "processArgs", ")", "\n\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", "(", "\"", "\"", ")", "\n", "}", "\n", "imageUser", ":=", "\"", "\"", "\n", "if", "imageConfig", "!=", "nil", "{", "imageUser", "=", "imageConfig", ".", "Config", ".", "User", "\n", "}", "\n", "containerUser", ":=", "generateUserString", "(", "sc", ".", "GetRunAsUsername", "(", ")", ",", "imageUser", ",", "sc", ".", "GetRunAsUser", "(", ")", ",", ")", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "containerUser", ")", "\n\n", "// Add uid, gid and groups from user", "uid", ",", "gid", ",", "addGroups", ",", "err", ":=", "utils", ".", "GetUserInfo", "(", "rootfs", ",", "containerUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// verify uid exists in containers /etc/passwd, else generate a passwd with the user entry", "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\n", "mnt", ":=", "rspec", ".", "Mount", "{", "Type", ":", "\"", "\"", ",", "Source", ":", "passwdPath", ",", "Destination", ":", "\"", "\"", ",", "Options", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "}", "\n", "specgen", ".", "AddMount", "(", "mnt", ")", "\n", "}", "\n\n", "specgen", ".", "SetProcessUID", "(", "uid", ")", "\n", "specgen", ".", "SetProcessGID", "(", "gid", ")", "\n", "if", "sc", ".", "GetRunAsGroup", "(", ")", "!=", "nil", "{", "specgen", ".", "SetProcessGID", "(", "uint32", "(", "sc", ".", "GetRunAsGroup", "(", ")", ".", "GetValue", "(", ")", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "group", ":=", "range", "addGroups", "{", "specgen", ".", "AddProcessAdditionalGid", "(", "group", ")", "\n", "}", "\n\n", "// Add groups from CRI", "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", "// We use the user from the image config if nothing is provided", "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\n", "if", "profile", "==", "apparmorRuntimeDefault", "{", "// If the value is runtime/default, then return default profile.", "return", "s", ".", "appArmorProfile", "\n", "}", "\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\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\n", "// Update state.json", "if", "err", "=", "c", ".", "updateStateName", "(", "ctr", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update config.json", "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\n", "// Update containers.json", "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", "\"", "\"", ":", "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\n", "case", "\"", "\"", ":", "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\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", "{", "// Walk does not follow symbolic links", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "dirSize", "+=", "uint64", "(", "info", ".", "Size", "(", ")", ")", "\n", "inodeCount", "++", "\n\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\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", ",", "\"", "\"", ",", "container", ")", "\n", "}", "\n", "c", ".", "runtime", ".", "UpdateContainerStatus", "(", "ctr", ")", "\n", "cStatus", ":=", "ctr", ".", "State", "(", ")", "\n\n", "// If the container is not running, error and move on.", "if", "cStatus", ".", "Status", "!=", "oci", ".", "ContainerStateRunning", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "container", ")", "\n", "}", "\n\n", "if", "err", "=", "c", ".", "runtime", ".", "SignalContainer", "(", "ctr", ",", "killSignal", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "_", ",", "randErr", ":=", "rand", ".", "Reader", ".", "Read", "(", "b", ")", "\n", "if", "randErr", "!=", "nil", "{", "return", "randErr", "\n", "}", "\n\n", "nsName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "b", ")", "\n", "symlinkPath", ":=", "filepath", ".", "Join", "(", "NsRunDir", ",", "nsName", ")", "\n\n", "if", "err", ":=", "os", ".", "Symlink", "(", "n", ".", "Path", "(", ")", ",", "symlinkPath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fd", ",", "err", ":=", "os", ".", "Open", "(", "symlinkPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "removeErr", ":=", "os", ".", "RemoveAll", "(", "symlinkPath", ")", ";", "removeErr", "!=", "nil", "{", "return", "removeErr", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "n", ".", "symlink", "=", "fd", "\n\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\n", "if", "n", ".", "closed", "{", "// netNsRemove() can be called multiple", "// times without returning an error.", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "n", ".", "symlinkRemove", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "n", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "n", ".", "closed", "=", "true", "\n\n", "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", "(", ")", ",", "\"", "\"", ")", "\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\n", "if", "n", ".", "Path", "(", ")", "!=", "\"", "\"", "{", "if", "err", ":=", "os", ".", "RemoveAll", "(", "n", ".", "Path", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\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", ",", "\"", "\"", ")", "\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", "(", ")", ")", ",", "}", ",", "// TODO(runcom): OOMScoreAdj is missing", "}", "\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\n", "mux", ".", "Get", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Write", "(", "js", ")", "\n", "}", ")", ")", "\n\n", "mux", ".", "Get", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "containerID", ":=", "bone", ".", "GetValue", "(", "req", ",", "\"", "\"", ")", "\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", "(", "\"", "\"", ",", "containerID", ")", ",", "http", ".", "StatusNotFound", ")", "\n", "case", "errCtrStateNil", ":", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "containerID", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "case", "errSandboxNotFound", ":", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Write", "(", "js", ")", "\n", "}", ")", ")", "\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", "(", "\"", "\"", ")", "\n", "s", ".", "stopAllPodSandboxes", "(", "ctx", ")", "\n", "err", "=", "os", ".", "Remove", "(", "shutdownFile", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "shutdownFile", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "watcher", ".", "Close", "(", ")", "\n\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "event", ":=", "<-", "watcher", ".", "Events", ":", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "event", ")", "\n", "if", "event", ".", "Op", "&", "fsnotify", ".", "Create", "==", "fsnotify", ".", "Create", "{", "containerID", ":=", "filepath", ".", "Base", "(", "event", ".", "Name", ")", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "containerID", ")", "\n", "c", ":=", "s", ".", "GetContainer", "(", "containerID", ")", "\n", "if", "c", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "containerID", ")", "\n", "err", ":=", "s", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "containerID", ")", "\n", "continue", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "containerID", ")", "\n", "err", ":=", "s", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"", "\"", ",", "c", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "else", "{", "s", ".", "ContainerStateToDisk", "(", "c", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "case", "err", ":=", "<-", "watcher", ".", "Errors", ":", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "case", "<-", "s", ".", "monitorsChan", ":", "logrus", ".", "Debug", "(", "\"", "\"", ")", "\n", "close", "(", "done", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", ":=", "watcher", ".", "Add", "(", "s", ".", "config", ".", "ContainerExitsDir", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Errorf", "(", "\"", "\"", ",", "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", "{", "// Filter using container id and pod id first.", "if", "filter", ".", "Id", "!=", "\"", "\"", "{", "id", ",", "err", ":=", "s", ".", "CtrIDIndex", "(", ")", ".", "Get", "(", "filter", ".", "Id", ")", "\n", "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", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\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", "(", "\"", "\"", ")", "\n", "defer", "logrus", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "// 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", "=", "\"", "\"", "\n", "// register TypeUrls for commonly marshaled external types", "major", ":=", "strconv", ".", "Itoa", "(", "rspec", ".", "VersionMajor", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "Spec", "{", "}", ",", "prefix", ",", "\"", "\"", ",", "major", ",", "\"", "\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "Process", "{", "}", ",", "prefix", ",", "\"", "\"", ",", "major", ",", "\"", "\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "LinuxResources", "{", "}", ",", "prefix", ",", "\"", "\"", ",", "major", ",", "\"", "\"", ")", "\n", "typeurl", ".", "Register", "(", "&", "rspec", ".", "WindowsResources", "{", "}", ",", "prefix", ",", "\"", "\"", ",", "major", ",", "\"", "\"", ")", "\n\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", "(", "\"", "\"", ")", "\n", "defer", "logrus", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "// Lock the container", "c", ".", "opLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "opLock", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "err", ":=", "r", ".", "task", ".", "Resume", "(", "r", ".", "ctx", ",", "&", "task", ".", "ResumeRequest", "{", "ID", ":", "c", ".", "ID", "(", ")", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errdefs", ".", "FromGRPC", "(", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ")", ";", "found", "{", "cmd", ".", "Env", "=", "append", "(", "cmd", ".", "Env", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ")", ")", "\n", "}", "\n\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ",", "stderr", ".", "String", "(", ")", ",", "stdout", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ")", ";", "found", "{", "cmd", ".", "Env", "=", "append", "(", "cmd", ".", "Env", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ")", ")", "\n", "}", "\n\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "[", "]", "uint32", "{", "uint32", "(", "pid", ")", "}", ")", ")", "\n", "properties", "=", "append", "(", "properties", ",", "newProp", "(", "\"", "\"", ",", "true", ")", ")", "\n", "properties", "=", "append", "(", "properties", ",", "newProp", "(", "\"", "\"", ",", "false", ")", ")", "\n", "ch", ":=", "make", "(", "chan", "string", ")", "\n", "_", ",", "err", "=", "conn", ".", "StartTransientUnit", "(", "unitName", ",", "\"", "\"", ",", "properties", ",", "ch", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "// Block until job is started", "<-", "ch", "\n\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", ")", "{", "// Sanity check interfaces", "if", "dst", "==", "nil", "||", "src", "==", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "keys", ")", "==", "0", "{", "// Default keys : ctrl-p ctrl-q", "keys", "=", "[", "]", "byte", "{", "16", ",", "17", "}", "\n", "}", "\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", "{", "// src.Close()", "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", "(", "\"", "\"", ")", "\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\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", "// The writer is closed or in bad state, remove it.", "w", ".", "Close", "(", ")", "\n", "delete", "(", "g", ".", "writers", ",", "k", ")", "\n", "}", "\n", "if", "len", "(", "g", ".", "writers", ")", "==", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\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", "(", "\"", "\"", ",", "defaultRuntime", ")", "\n", "}", "\n", "if", "defRuntime", ".", "RuntimePath", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "defaultRuntime", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "runtimeHandler", ",", "ok", ":=", "r", ".", "runtimes", "[", "handler", "]", "\n", "if", "!", "ok", "{", "return", "RuntimeHandler", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handler", ",", "r", ".", "runtimes", ")", "\n", "}", "\n", "if", "runtimeHandler", ".", "RuntimePath", "==", "\"", "\"", "{", "return", "RuntimeHandler", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handler", ")", "\n", "}", "\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\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", "]", ")", ",", "\"", "\"", ")", ",", "os", ".", "NewFile", "(", "uintptr", "(", "fds", "[", "0", "]", ")", ",", "\"", "\"", ")", ",", "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", "(", "\"", "\"", ")", "\n\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\n", "// 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", ")", "\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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "containerID", ",", "err", ":=", "c", ".", "ctrIDIndex", ".", "Get", "(", "cid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cid", ",", "err", ")", "\n", "}", "\n\n", "ctr", ":=", "c", ".", "GetContainer", "(", "containerID", ")", "\n", "if", "ctr", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "}", "\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\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", "(", "\"", "\"", ")", "\n", "}", "\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\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", "(", "\"", "\"", ",", "containerID", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "ss", ".", "runtimeServer", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cState", ":=", "c", ".", "State", "(", ")", "\n", "if", "!", "(", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "||", "cState", ".", "Status", "==", "oci", ".", "ContainerStateCreated", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\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\n", "fields", ":=", "s", ".", "structFields", "(", ")", "\n\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "name", ":=", "field", ".", "Name", "\n", "val", ":=", "s", ".", "value", ".", "FieldByName", "(", "name", ")", "\n", "isSubStruct", ":=", "false", "\n", "var", "finalVal", "interface", "{", "}", "\n\n", "tagName", ",", "tagOpts", ":=", "parseTag", "(", "field", ".", "Tag", ".", "Get", "(", "s", ".", "TagName", ")", ")", "\n", "if", "tagName", "!=", "\"", "\"", "{", "name", "=", "tagName", "\n", "}", "\n\n", "// if the value is a zero value and the field is marked as omitempty do", "// not include", "if", "tagOpts", ".", "Has", "(", "\"", "\"", ")", "{", "zero", ":=", "reflect", ".", "Zero", "(", "val", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "current", ":=", "val", ".", "Interface", "(", ")", "\n\n", "if", "reflect", ".", "DeepEqual", "(", "current", ",", "zero", ")", "{", "continue", "\n", "}", "\n", "}", "\n\n", "if", "!", "tagOpts", ".", "Has", "(", "\"", "\"", ")", "{", "finalVal", "=", "s", ".", "nested", "(", "val", ")", "\n\n", "v", ":=", "reflect", ".", "ValueOf", "(", "val", ".", "Interface", "(", ")", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n\n", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ",", "reflect", ".", "Struct", ":", "isSubStruct", "=", "true", "\n", "}", "\n", "}", "else", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "}", "\n\n", "if", "tagOpts", ".", "Has", "(", "\"", "\"", ")", "{", "s", ",", "ok", ":=", "val", ".", "Interface", "(", ")", ".", "(", "fmt", ".", "Stringer", ")", "\n", "if", "ok", "{", "out", "[", "name", "]", "=", "s", ".", "String", "(", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "if", "isSubStruct", "&&", "(", "tagOpts", ".", "Has", "(", "\"", "\"", ")", ")", "{", "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", "(", "\"", "\"", ")", "\n", "}", "\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\n", "field", ",", "ok", ":=", "t", ".", "FieldByName", "(", "name", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "false", "\n", "}", "\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\n", "var", "f", "[", "]", "reflect", ".", "StructField", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumField", "(", ")", ";", "i", "++", "{", "field", ":=", "t", ".", "Field", "(", "i", ")", "\n", "// we can't access the value of unexported fields", "if", "field", ".", "PkgPath", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// don't check if it's omitted", "if", "tag", ":=", "field", ".", "Tag", ".", "Get", "(", "s", ".", "TagName", ")", ";", "tag", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "f", "=", "append", "(", "f", ",", "field", ")", "\n", "}", "\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\n", "// uninitialized zero value of a struct", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Invalid", "{", "return", "false", "\n", "}", "\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\n", "v", ":=", "reflect", ".", "ValueOf", "(", "val", ".", "Interface", "(", ")", ")", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n\n", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "n", ":=", "New", "(", "val", ".", "Interface", "(", ")", ")", "\n", "n", ".", "TagName", "=", "s", ".", "TagName", "\n", "m", ":=", "n", ".", "Map", "(", ")", "\n\n", "// do not add the converted value if there are no exported fields, ie:", "// time.Time", "if", "len", "(", "m", ")", "==", "0", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "}", "else", "{", "finalVal", "=", "m", "\n", "}", "\n", "case", "reflect", ".", "Map", ":", "// get the element type of the 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\n", "// 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", "(", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "val", ".", "MapKeys", "(", ")", "{", "m", "[", "k", ".", "String", "(", ")", "]", "=", "s", ".", "nested", "(", "val", ".", "MapIndex", "(", "k", ")", ")", "\n", "}", "\n", "finalVal", "=", "m", "\n", "break", "\n", "}", "\n\n", "// TODO(arslan): should this be optional?", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "case", "reflect", ".", "Slice", ",", "reflect", ".", "Array", ":", "if", "val", ".", "Type", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "finalVal", "=", "val", ".", "Interface", "(", ")", "\n", "break", "\n", "}", "\n\n", "// 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", "(", ")", "\n", "break", "\n", "}", "\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\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\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\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\n", "// 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", "\n", "}", "\n", "if", "len", "(", "traceId", ")", "==", "0", "{", "traceId", "=", "s", ".", "TraceId", "\n", "}", "\n", "}", "\n\n", "// create segment", "s", ":=", "&", "awsxray", ".", "Segment", "{", "Id", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "getRandom", "(", "8", ")", ")", ",", "Name", ":", "name", ",", "TraceId", ":", "traceId", ",", "StartTime", ":", "float64", "(", "time", ".", "Now", "(", ")", ".", "Truncate", "(", "time", ".", "Millisecond", ")", ".", "UnixNano", "(", ")", ")", "/", "1e9", ",", "}", "\n\n", "// we have a parent so subsegment", "if", "len", "(", "parentId", ")", ">", "0", "{", "s", ".", "ParentId", "=", "parentId", "\n", "s", ".", "Type", "=", "\"", "\"", "\n", "}", "\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", "{", "// no error", "if", "err", "==", "nil", "{", "return", "200", "\n", "}", "\n\n", "// try get errors.Error", "if", "e", ",", "ok", ":=", "err", ".", "(", "*", "errors", ".", "Error", ")", ";", "ok", "{", "return", "int", "(", "e", ".", "Code", ")", "\n", "}", "\n\n", "// try parse marshalled error", "if", "e", ":=", "errors", ".", "Parse", "(", "err", ".", "Error", "(", ")", ")", ";", "e", ".", "Code", ">", "0", "{", "return", "int", "(", "e", ".", "Code", ")", "\n", "}", "\n\n", "// could not parse, 500", "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\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\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\n", "if", "r", ".", "Body", "!=", "nil", "{", "var", "ok", "bool", "\n", "bm", ",", "ok", "=", "r", ".", "Body", ".", "(", "msgp", ".", "Encodable", ")", "\n", "if", "!", "ok", "{", "return", "ErrNotEncodable", "\n", "}", "\n", "}", "\n\n", "var", "err", "error", "\n\n", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "RequestPackSize", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "w", ".", "WriteInt", "(", "RequestType", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "w", ".", "WriteString", "(", "r", ".", "ID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "w", ".", "WriteString", "(", "r", ".", "Method", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// No body to encode. Write a zero-length params array.", "if", "bm", "==", "nil", "{", "return", "w", ".", "WriteArrayHeader", "(", "0", ")", "\n", "}", "\n\n", "// 1-item array containing the body.", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\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
micro/go-plugins
codec/msgpackrpc/rpc.go
EncodeMsg
func (n *Notification) EncodeMsg(w *msgp.Writer) error { var bm msgp.Encodable if n.Body != nil { var ok bool bm, ok = n.Body.(msgp.Encodable) if !ok { return ErrNotEncodable } } var err error if err = w.WriteArrayHeader(NotificationPackSize); err != nil { return err } if err = w.WriteInt(NotificationType); err != nil { return err } if err = w.WriteString(n.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 (n *Notification) EncodeMsg(w *msgp.Writer) error { var bm msgp.Encodable if n.Body != nil { var ok bool bm, ok = n.Body.(msgp.Encodable) if !ok { return ErrNotEncodable } } var err error if err = w.WriteArrayHeader(NotificationPackSize); err != nil { return err } if err = w.WriteInt(NotificationType); err != nil { return err } if err = w.WriteString(n.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", "(", "n", "*", "Notification", ")", "EncodeMsg", "(", "w", "*", "msgp", ".", "Writer", ")", "error", "{", "var", "bm", "msgp", ".", "Encodable", "\n\n", "if", "n", ".", "Body", "!=", "nil", "{", "var", "ok", "bool", "\n", "bm", ",", "ok", "=", "n", ".", "Body", ".", "(", "msgp", ".", "Encodable", ")", "\n", "if", "!", "ok", "{", "return", "ErrNotEncodable", "\n", "}", "\n", "}", "\n\n", "var", "err", "error", "\n\n", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "NotificationPackSize", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "w", ".", "WriteInt", "(", "NotificationType", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", "=", "w", ".", "WriteString", "(", "n", ".", "Method", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// No body to encode. Write a zero-length params array.", "if", "bm", "==", "nil", "{", "return", "w", ".", "WriteArrayHeader", "(", "0", ")", "\n", "}", "\n\n", "// 1-item array containing the body.", "if", "err", "=", "w", ".", "WriteArrayHeader", "(", "1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "msgp", ".", "Encode", "(", "w", ",", "bm", ")", "\n", "}" ]
// EncodeMsg encodes the notification to writer. The body is expected to // be an encodable type.
[ "EncodeMsg", "encodes", "the", "notification", "to", "writer", ".", "The", "body", "is", "expected", "to", "be", "an", "encodable", "type", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/rpc.go#L292-L328
train
micro/go-plugins
registry/kubernetes/client/mock/utils.go
Stop
func (w *mockWatcher) Stop() { select { case <-w.stop: return default: close(w.stop) close(w.results) } }
go
func (w *mockWatcher) Stop() { select { case <-w.stop: return default: close(w.stop) close(w.results) } }
[ "func", "(", "w", "*", "mockWatcher", ")", "Stop", "(", ")", "{", "select", "{", "case", "<-", "w", ".", "stop", ":", "return", "\n", "default", ":", "close", "(", "w", ".", "stop", ")", "\n", "close", "(", "w", ".", "results", ")", "\n", "}", "\n", "}" ]
// Stop closes any channels
[ "Stop", "closes", "any", "channels" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/mock/utils.go#L19-L27
train
micro/go-plugins
broker/redis/redis.go
recv
func (s *subscriber) recv() { // Close the connection once the subscriber stops receiving. defer s.conn.Close() for { switch x := s.conn.Receive().(type) { case redis.Message: var m broker.Message // Handle error? Only a log would be necessary since this type // of issue cannot be fixed. if err := s.codec.Unmarshal(x.Data, &m); err != nil { break } p := publication{ topic: x.Channel, message: &m, } // Handle error? Retry? if err := s.handle(&p); err != nil { break } // Added for posterity, however Ack is a no-op. if s.opts.AutoAck { if err := p.Ack(); err != nil { break } } case redis.Subscription: if x.Count == 0 { return } case error: return } } }
go
func (s *subscriber) recv() { // Close the connection once the subscriber stops receiving. defer s.conn.Close() for { switch x := s.conn.Receive().(type) { case redis.Message: var m broker.Message // Handle error? Only a log would be necessary since this type // of issue cannot be fixed. if err := s.codec.Unmarshal(x.Data, &m); err != nil { break } p := publication{ topic: x.Channel, message: &m, } // Handle error? Retry? if err := s.handle(&p); err != nil { break } // Added for posterity, however Ack is a no-op. if s.opts.AutoAck { if err := p.Ack(); err != nil { break } } case redis.Subscription: if x.Count == 0 { return } case error: return } } }
[ "func", "(", "s", "*", "subscriber", ")", "recv", "(", ")", "{", "// Close the connection once the subscriber stops receiving.", "defer", "s", ".", "conn", ".", "Close", "(", ")", "\n\n", "for", "{", "switch", "x", ":=", "s", ".", "conn", ".", "Receive", "(", ")", ".", "(", "type", ")", "{", "case", "redis", ".", "Message", ":", "var", "m", "broker", ".", "Message", "\n\n", "// Handle error? Only a log would be necessary since this type", "// of issue cannot be fixed.", "if", "err", ":=", "s", ".", "codec", ".", "Unmarshal", "(", "x", ".", "Data", ",", "&", "m", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n\n", "p", ":=", "publication", "{", "topic", ":", "x", ".", "Channel", ",", "message", ":", "&", "m", ",", "}", "\n\n", "// Handle error? Retry?", "if", "err", ":=", "s", ".", "handle", "(", "&", "p", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n\n", "// Added for posterity, however Ack is a no-op.", "if", "s", ".", "opts", ".", "AutoAck", "{", "if", "err", ":=", "p", ".", "Ack", "(", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n\n", "case", "redis", ".", "Subscription", ":", "if", "x", ".", "Count", "==", "0", "{", "return", "\n", "}", "\n\n", "case", "error", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// recv loops to receive new messages from Redis and handle them // as publications.
[ "recv", "loops", "to", "receive", "new", "messages", "from", "Redis", "and", "handle", "them", "as", "publications", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/redis/redis.go#L54-L95
train
micro/go-plugins
broker/redis/redis.go
Init
func (b *redisBroker) Init(opts ...broker.Option) error { if b.pool != nil { return errors.New("redis: cannot init while connected") } for _, o := range opts { o(&b.opts) } return nil }
go
func (b *redisBroker) Init(opts ...broker.Option) error { if b.pool != nil { return errors.New("redis: cannot init while connected") } for _, o := range opts { o(&b.opts) } return nil }
[ "func", "(", "b", "*", "redisBroker", ")", "Init", "(", "opts", "...", "broker", ".", "Option", ")", "error", "{", "if", "b", ".", "pool", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "b", ".", "opts", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Init sets or overrides broker options.
[ "Init", "sets", "or", "overrides", "broker", "options", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/redis/redis.go#L137-L147
train
micro/go-plugins
broker/redis/redis.go
Disconnect
func (b *redisBroker) Disconnect() error { err := b.pool.Close() b.pool = nil b.addr = "" return err }
go
func (b *redisBroker) Disconnect() error { err := b.pool.Close() b.pool = nil b.addr = "" return err }
[ "func", "(", "b", "*", "redisBroker", ")", "Disconnect", "(", ")", "error", "{", "err", ":=", "b", ".", "pool", ".", "Close", "(", ")", "\n", "b", ".", "pool", "=", "nil", "\n", "b", ".", "addr", "=", "\"", "\"", "\n", "return", "err", "\n", "}" ]
// Disconnect closes the connection pool.
[ "Disconnect", "closes", "the", "connection", "pool", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/redis/redis.go#L192-L197
train
micro/go-plugins
broker/redis/redis.go
Publish
func (b *redisBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { v, err := b.opts.Codec.Marshal(msg) if err != nil { return err } conn := b.pool.Get() _, err = redis.Int(conn.Do("PUBLISH", topic, v)) conn.Close() return err }
go
func (b *redisBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { v, err := b.opts.Codec.Marshal(msg) if err != nil { return err } conn := b.pool.Get() _, err = redis.Int(conn.Do("PUBLISH", topic, v)) conn.Close() return err }
[ "func", "(", "b", "*", "redisBroker", ")", "Publish", "(", "topic", "string", ",", "msg", "*", "broker", ".", "Message", ",", "opts", "...", "broker", ".", "PublishOption", ")", "error", "{", "v", ",", "err", ":=", "b", ".", "opts", ".", "Codec", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "conn", ":=", "b", ".", "pool", ".", "Get", "(", ")", "\n", "_", ",", "err", "=", "redis", ".", "Int", "(", "conn", ".", "Do", "(", "\"", "\"", ",", "topic", ",", "v", ")", ")", "\n", "conn", ".", "Close", "(", ")", "\n\n", "return", "err", "\n", "}" ]
// Publish publishes a message.
[ "Publish", "publishes", "a", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/redis/redis.go#L200-L211
train
micro/go-plugins
broker/redis/redis.go
Subscribe
func (b *redisBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { var options broker.SubscribeOptions for _, o := range opts { o(&options) } s := subscriber{ codec: b.opts.Codec, conn: &redis.PubSubConn{Conn: b.pool.Get()}, topic: topic, handle: handler, opts: options, } // Run the receiver routine. go s.recv() if err := s.conn.Subscribe(s.topic); err != nil { return nil, err } return &s, nil }
go
func (b *redisBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { var options broker.SubscribeOptions for _, o := range opts { o(&options) } s := subscriber{ codec: b.opts.Codec, conn: &redis.PubSubConn{Conn: b.pool.Get()}, topic: topic, handle: handler, opts: options, } // Run the receiver routine. go s.recv() if err := s.conn.Subscribe(s.topic); err != nil { return nil, err } return &s, nil }
[ "func", "(", "b", "*", "redisBroker", ")", "Subscribe", "(", "topic", "string", ",", "handler", "broker", ".", "Handler", ",", "opts", "...", "broker", ".", "SubscribeOption", ")", "(", "broker", ".", "Subscriber", ",", "error", ")", "{", "var", "options", "broker", ".", "SubscribeOptions", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "s", ":=", "subscriber", "{", "codec", ":", "b", ".", "opts", ".", "Codec", ",", "conn", ":", "&", "redis", ".", "PubSubConn", "{", "Conn", ":", "b", ".", "pool", ".", "Get", "(", ")", "}", ",", "topic", ":", "topic", ",", "handle", ":", "handler", ",", "opts", ":", "options", ",", "}", "\n\n", "// Run the receiver routine.", "go", "s", ".", "recv", "(", ")", "\n\n", "if", "err", ":=", "s", ".", "conn", ".", "Subscribe", "(", "s", ".", "topic", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "s", ",", "nil", "\n", "}" ]
// Subscribe returns a subscriber for the topic and handler.
[ "Subscribe", "returns", "a", "subscriber", "for", "the", "topic", "and", "handler", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/redis/redis.go#L214-L236
train
micro/go-plugins
broker/stomp/context.go
setSubscribeOption
func setSubscribeOption(k, v interface{}) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
go
func setSubscribeOption(k, v interface{}) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
[ "func", "setSubscribeOption", "(", "k", ",", "v", "interface", "{", "}", ")", "broker", ".", "SubscribeOption", "{", "return", "func", "(", "o", "*", "broker", ".", "SubscribeOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "k", ",", "v", ")", "\n", "}", "\n", "}" ]
// setSubscribeOption returns a function to setup a context with given value
[ "setSubscribeOption", "returns", "a", "function", "to", "setup", "a", "context", "with", "given", "value" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/context.go#L25-L32
train
micro/go-plugins
broker/stomp/context.go
setBrokerOption
func setBrokerOption(k, v interface{}) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
go
func setBrokerOption(k, v interface{}) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
[ "func", "setBrokerOption", "(", "k", ",", "v", "interface", "{", "}", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "k", ",", "v", ")", "\n", "}", "\n", "}" ]
// setBrokerOption returns a function to setup a context with given value
[ "setBrokerOption", "returns", "a", "function", "to", "setup", "a", "context", "with", "given", "value" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/context.go#L35-L42
train
micro/go-plugins
broker/stomp/context.go
setPublishOption
func setPublishOption(k, v interface{}) broker.PublishOption { return func(o *broker.PublishOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
go
func setPublishOption(k, v interface{}) broker.PublishOption { return func(o *broker.PublishOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, k, v) } }
[ "func", "setPublishOption", "(", "k", ",", "v", "interface", "{", "}", ")", "broker", ".", "PublishOption", "{", "return", "func", "(", "o", "*", "broker", ".", "PublishOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "k", ",", "v", ")", "\n", "}", "\n", "}" ]
// setPublishOption returns a function to setup a context with given value
[ "setPublishOption", "returns", "a", "function", "to", "setup", "a", "context", "with", "given", "value" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/context.go#L45-L52
train
micro/go-plugins
server/grpc/util.go
convertCode
func convertCode(err error) codes.Code { switch err { case nil: return codes.OK case io.EOF: return codes.OutOfRange case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: return codes.FailedPrecondition case os.ErrInvalid: return codes.InvalidArgument case context.Canceled: return codes.Canceled case context.DeadlineExceeded: return codes.DeadlineExceeded } switch { case os.IsExist(err): return codes.AlreadyExists case os.IsNotExist(err): return codes.NotFound case os.IsPermission(err): return codes.PermissionDenied } return codes.Unknown }
go
func convertCode(err error) codes.Code { switch err { case nil: return codes.OK case io.EOF: return codes.OutOfRange case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: return codes.FailedPrecondition case os.ErrInvalid: return codes.InvalidArgument case context.Canceled: return codes.Canceled case context.DeadlineExceeded: return codes.DeadlineExceeded } switch { case os.IsExist(err): return codes.AlreadyExists case os.IsNotExist(err): return codes.NotFound case os.IsPermission(err): return codes.PermissionDenied } return codes.Unknown }
[ "func", "convertCode", "(", "err", "error", ")", "codes", ".", "Code", "{", "switch", "err", "{", "case", "nil", ":", "return", "codes", ".", "OK", "\n", "case", "io", ".", "EOF", ":", "return", "codes", ".", "OutOfRange", "\n", "case", "io", ".", "ErrClosedPipe", ",", "io", ".", "ErrNoProgress", ",", "io", ".", "ErrShortBuffer", ",", "io", ".", "ErrShortWrite", ",", "io", ".", "ErrUnexpectedEOF", ":", "return", "codes", ".", "FailedPrecondition", "\n", "case", "os", ".", "ErrInvalid", ":", "return", "codes", ".", "InvalidArgument", "\n", "case", "context", ".", "Canceled", ":", "return", "codes", ".", "Canceled", "\n", "case", "context", ".", "DeadlineExceeded", ":", "return", "codes", ".", "DeadlineExceeded", "\n", "}", "\n", "switch", "{", "case", "os", ".", "IsExist", "(", "err", ")", ":", "return", "codes", ".", "AlreadyExists", "\n", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "return", "codes", ".", "NotFound", "\n", "case", "os", ".", "IsPermission", "(", "err", ")", ":", "return", "codes", ".", "PermissionDenied", "\n", "}", "\n", "return", "codes", ".", "Unknown", "\n", "}" ]
// convertCode converts a standard Go error into its canonical code. Note that // this is only used to translate the error returned by the server applications.
[ "convertCode", "converts", "a", "standard", "Go", "error", "into", "its", "canonical", "code", ".", "Note", "that", "this", "is", "only", "used", "to", "translate", "the", "error", "returned", "by", "the", "server", "applications", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/server/grpc/util.go#L24-L48
train
micro/go-plugins
wrapper/endpoint/endpoint.go
NewClientWrapper
func NewClientWrapper(cw client.Wrapper, eps ...string) client.Wrapper { // create map of endpoints endpoints := make(map[string]bool) for _, ep := range eps { endpoints[ep] = true } return func(c client.Client) client.Client { return &clientWrapper{endpoints, cw, c} } }
go
func NewClientWrapper(cw client.Wrapper, eps ...string) client.Wrapper { // create map of endpoints endpoints := make(map[string]bool) for _, ep := range eps { endpoints[ep] = true } return func(c client.Client) client.Client { return &clientWrapper{endpoints, cw, c} } }
[ "func", "NewClientWrapper", "(", "cw", "client", ".", "Wrapper", ",", "eps", "...", "string", ")", "client", ".", "Wrapper", "{", "// create map of endpoints", "endpoints", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "ep", ":=", "range", "eps", "{", "endpoints", "[", "ep", "]", "=", "true", "\n", "}", "\n\n", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "clientWrapper", "{", "endpoints", ",", "cw", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper wraps another client wrapper but only executes when the endpoints specified are executed.
[ "NewClientWrapper", "wraps", "another", "client", "wrapper", "but", "only", "executes", "when", "the", "endpoints", "specified", "are", "executed", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/endpoint/endpoint.go#L29-L39
train
micro/go-plugins
wrapper/endpoint/endpoint.go
NewHandlerWrapper
func NewHandlerWrapper(hw server.HandlerWrapper, eps ...string) server.HandlerWrapper { // create map of endpoints endpoints := make(map[string]bool) for _, ep := range eps { endpoints[ep] = true } return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { // execute the handler wrapper? if !endpoints[req.Endpoint()] { // no return h(ctx, req, rsp) } // yes return hw(h)(ctx, req, rsp) } } }
go
func NewHandlerWrapper(hw server.HandlerWrapper, eps ...string) server.HandlerWrapper { // create map of endpoints endpoints := make(map[string]bool) for _, ep := range eps { endpoints[ep] = true } return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { // execute the handler wrapper? if !endpoints[req.Endpoint()] { // no return h(ctx, req, rsp) } // yes return hw(h)(ctx, req, rsp) } } }
[ "func", "NewHandlerWrapper", "(", "hw", "server", ".", "HandlerWrapper", ",", "eps", "...", "string", ")", "server", ".", "HandlerWrapper", "{", "// create map of endpoints", "endpoints", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "ep", ":=", "range", "eps", "{", "endpoints", "[", "ep", "]", "=", "true", "\n", "}", "\n\n", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "// execute the handler wrapper?", "if", "!", "endpoints", "[", "req", ".", "Endpoint", "(", ")", "]", "{", "// no", "return", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n\n", "// yes", "return", "hw", "(", "h", ")", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper wraps another handler wrapper but only executes when the endpoints specified are executed.
[ "NewHandlerWrapper", "wraps", "another", "handler", "wrapper", "but", "only", "executes", "when", "the", "endpoints", "specified", "are", "executed", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/endpoint/endpoint.go#L42-L61
train
micro/go-plugins
micro/cors/cors.go
NewPlugin
func NewPlugin() plugin.Plugin { return &allowedCors{ allowedHeaders: []string{}, allowedOrigins: []string{}, allowedMethods: []string{}, } }
go
func NewPlugin() plugin.Plugin { return &allowedCors{ allowedHeaders: []string{}, allowedOrigins: []string{}, allowedMethods: []string{}, } }
[ "func", "NewPlugin", "(", ")", "plugin", ".", "Plugin", "{", "return", "&", "allowedCors", "{", "allowedHeaders", ":", "[", "]", "string", "{", "}", ",", "allowedOrigins", ":", "[", "]", "string", "{", "}", ",", "allowedMethods", ":", "[", "]", "string", "{", "}", ",", "}", "\n", "}" ]
// NewPlugin Creates the CORS Plugin
[ "NewPlugin", "Creates", "the", "CORS", "Plugin" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/cors/cors.go#L83-L89
train
micro/go-plugins
wrapper/service/service.go
NewClientWrapper
func NewClientWrapper(service micro.Service) client.Wrapper { return func(c client.Client) client.Client { return &clientWrapper{service, c} } }
go
func NewClientWrapper(service micro.Service) client.Wrapper { return func(c client.Client) client.Client { return &clientWrapper{service, c} } }
[ "func", "NewClientWrapper", "(", "service", "micro", ".", "Service", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "clientWrapper", "{", "service", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper wraps a service within a client so it can be accessed by subsequent client wrappers.
[ "NewClientWrapper", "wraps", "a", "service", "within", "a", "client", "so", "it", "can", "be", "accessed", "by", "subsequent", "client", "wrappers", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/service/service.go#L23-L27
train
micro/go-plugins
wrapper/service/service.go
NewHandlerWrapper
func NewHandlerWrapper(service micro.Service) server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { ctx = micro.NewContext(ctx, service) return h(ctx, req, rsp) } } }
go
func NewHandlerWrapper(service micro.Service) server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { ctx = micro.NewContext(ctx, service) return h(ctx, req, rsp) } } }
[ "func", "NewHandlerWrapper", "(", "service", "micro", ".", "Service", ")", "server", ".", "HandlerWrapper", "{", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "ctx", "=", "micro", ".", "NewContext", "(", "ctx", ",", "service", ")", "\n", "return", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper wraps a service within the handler so it can be accessed by the handler itself.
[ "NewHandlerWrapper", "wraps", "a", "service", "within", "the", "handler", "so", "it", "can", "be", "accessed", "by", "the", "handler", "itself", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/service/service.go#L30-L37
train
micro/go-plugins
wrapper/select/shard/shard.go
NewClientWrapper
func NewClientWrapper(key string) client.Wrapper { return func(c client.Client) client.Client { return &shard{ key: key, Client: c, } } }
go
func NewClientWrapper(key string) client.Wrapper { return func(c client.Client) client.Client { return &shard{ key: key, Client: c, } } }
[ "func", "NewClientWrapper", "(", "key", "string", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "shard", "{", "key", ":", "key", ",", "Client", ":", "c", ",", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper is a wrapper which shards based on a header key value
[ "NewClientWrapper", "is", "a", "wrapper", "which", "shards", "based", "on", "a", "header", "key", "value" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/select/shard/shard.go#L62-L69
train
micro/go-plugins
broker/googlepubsub/options.go
ClientOption
func ClientOption(c ...option.ClientOption) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, clientOptionKey{}, c) } }
go
func ClientOption(c ...option.ClientOption) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, clientOptionKey{}, c) } }
[ "func", "ClientOption", "(", "c", "...", "option", ".", "ClientOption", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "clientOptionKey", "{", "}", ",", "c", ")", "\n", "}", "\n", "}" ]
// ClientOption is a broker Option which allows google pubsub client options to be // set for the client
[ "ClientOption", "is", "a", "broker", "Option", "which", "allows", "google", "pubsub", "client", "options", "to", "be", "set", "for", "the", "client" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/options.go#L25-L32
train
micro/go-plugins
broker/googlepubsub/options.go
ProjectID
func ProjectID(id string) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, projectIDKey{}, id) } }
go
func ProjectID(id string) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, projectIDKey{}, id) } }
[ "func", "ProjectID", "(", "id", "string", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "projectIDKey", "{", "}", ",", "id", ")", "\n", "}", "\n", "}" ]
// ProjectID provides an option which sets the google project id
[ "ProjectID", "provides", "an", "option", "which", "sets", "the", "google", "project", "id" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/options.go#L35-L42
train
micro/go-plugins
broker/googlepubsub/options.go
CreateSubscription
func CreateSubscription(b bool) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, createSubscription{}, b) } }
go
func CreateSubscription(b bool) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, createSubscription{}, b) } }
[ "func", "CreateSubscription", "(", "b", "bool", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "createSubscription", "{", "}", ",", "b", ")", "\n", "}", "\n", "}" ]
// CreateSubscription prevents the creation of the subscription if it not exists
[ "CreateSubscription", "prevents", "the", "creation", "of", "the", "subscription", "if", "it", "not", "exists" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/options.go#L45-L53
train
micro/go-plugins
broker/googlepubsub/options.go
DeleteSubscription
func DeleteSubscription(b bool) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, deleteSubscription{}, b) } }
go
func DeleteSubscription(b bool) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, deleteSubscription{}, b) } }
[ "func", "DeleteSubscription", "(", "b", "bool", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "deleteSubscription", "{", "}", ",", "b", ")", "\n", "}", "\n", "}" ]
// DeleteSubscription prevents the deletion of the subscription if it not exists
[ "DeleteSubscription", "prevents", "the", "deletion", "of", "the", "subscription", "if", "it", "not", "exists" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/options.go#L56-L64
train
micro/go-plugins
broker/googlepubsub/options.go
MaxExtension
func MaxExtension(d time.Duration) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxExtensionKey{}, d) } }
go
func MaxExtension(d time.Duration) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxExtensionKey{}, d) } }
[ "func", "MaxExtension", "(", "d", "time", ".", "Duration", ")", "broker", ".", "SubscribeOption", "{", "return", "func", "(", "o", "*", "broker", ".", "SubscribeOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "maxExtensionKey", "{", "}", ",", "d", ")", "\n", "}", "\n", "}" ]
// MaxExtension is the maximum period for which the Subscription should // automatically extend the ack deadline for each message.
[ "MaxExtension", "is", "the", "maximum", "period", "for", "which", "the", "Subscription", "should", "automatically", "extend", "the", "ack", "deadline", "for", "each", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/options.go#L80-L88
train