diff options
Diffstat (limited to 'libpod')
-rw-r--r-- | libpod/container_api.go | 24 | ||||
-rw-r--r-- | libpod/container_exec.go | 4 | ||||
-rw-r--r-- | libpod/container_internal.go | 40 | ||||
-rw-r--r-- | libpod/container_internal_linux.go | 14 | ||||
-rw-r--r-- | libpod/container_internal_unsupported.go | 5 | ||||
-rw-r--r-- | libpod/container_top_linux.go | 2 | ||||
-rw-r--r-- | libpod/define/config.go | 24 | ||||
-rw-r--r-- | libpod/define/info.go | 101 | ||||
-rw-r--r-- | libpod/filters/containers.go | 157 | ||||
-rw-r--r-- | libpod/filters/pods.go (renamed from libpod/podfilters/pods.go) | 2 | ||||
-rw-r--r-- | libpod/healthcheck.go | 2 | ||||
-rw-r--r-- | libpod/info.go | 243 | ||||
-rw-r--r-- | libpod/oci.go | 5 | ||||
-rw-r--r-- | libpod/oci_attach_linux.go | 8 | ||||
-rw-r--r-- | libpod/oci_attach_unsupported.go | 4 | ||||
-rw-r--r-- | libpod/oci_conmon_linux.go | 28 | ||||
-rw-r--r-- | libpod/oci_conmon_unsupported.go | 4 | ||||
-rw-r--r-- | libpod/oci_missing.go | 15 | ||||
-rw-r--r-- | libpod/runtime.go | 40 | ||||
-rw-r--r-- | libpod/storage.go | 5 |
20 files changed, 536 insertions, 191 deletions
diff --git a/libpod/container_api.go b/libpod/container_api.go index 967180437..55c79fa74 100644 --- a/libpod/container_api.go +++ b/libpod/container_api.go @@ -3,7 +3,6 @@ package libpod import ( "bufio" "context" - "io" "io/ioutil" "net" "os" @@ -96,7 +95,7 @@ func (c *Container) Start(ctx context.Context, recursive bool) (err error) { // The channel will be closed automatically after the result of attach has been // sent. // If recursive is set, StartAndAttach will also start all containers this container depends on. -func (c *Container) StartAndAttach(ctx context.Context, streams *AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, recursive bool) (attachResChan <-chan error, err error) { +func (c *Container) StartAndAttach(ctx context.Context, streams *define.AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, recursive bool) (attachResChan <-chan error, err error) { if !c.batched { c.lock.Lock() defer c.lock.Unlock() @@ -213,29 +212,10 @@ func (c *Container) Kill(signal uint) error { return c.save() } -// AttachStreams contains streams that will be attached to the container -type AttachStreams struct { - // OutputStream will be attached to container's STDOUT - OutputStream io.WriteCloser - // ErrorStream will be attached to container's STDERR - ErrorStream io.WriteCloser - // InputStream will be attached to container's STDIN - InputStream *bufio.Reader - // AttachOutput is whether to attach to STDOUT - // If false, stdout will not be attached - AttachOutput bool - // AttachError is whether to attach to STDERR - // If false, stdout will not be attached - AttachError bool - // AttachInput is whether to attach to STDIN - // If false, stdout will not be attached - AttachInput bool -} - // Attach attaches to a container. // This function returns when the attach finishes. It does not hold the lock for // the duration of its runtime, only using it at the beginning to verify state. -func (c *Container) Attach(streams *AttachStreams, keys string, resize <-chan remotecommand.TerminalSize) error { +func (c *Container) Attach(streams *define.AttachStreams, keys string, resize <-chan remotecommand.TerminalSize) error { if !c.batched { c.lock.Lock() if err := c.syncContainer(); err != nil { diff --git a/libpod/container_exec.go b/libpod/container_exec.go index 5469462f8..c1ce8b724 100644 --- a/libpod/container_exec.go +++ b/libpod/container_exec.go @@ -221,7 +221,7 @@ func (c *Container) ExecStart(sessionID string) error { // ExecStartAndAttach starts and attaches to an exec session in a container. // TODO: Should we include detach keys in the signature to allow override? // TODO: How do we handle AttachStdin/AttachStdout/AttachStderr? -func (c *Container) ExecStartAndAttach(sessionID string, streams *AttachStreams) error { +func (c *Container) ExecStartAndAttach(sessionID string, streams *define.AttachStreams) error { if !c.batched { c.lock.Lock() defer c.lock.Unlock() @@ -544,7 +544,7 @@ func (c *Container) ExecResize(sessionID string, newSize remotecommand.TerminalS // Exec emulates the old Libpod exec API, providing a single call to create, // run, and remove an exec session. Returns exit code and error. Exit code is // not guaranteed to be set sanely if error is not nil. -func (c *Container) Exec(config *ExecConfig, streams *AttachStreams, resize <-chan remotecommand.TerminalSize) (int, error) { +func (c *Container) Exec(config *ExecConfig, streams *define.AttachStreams, resize <-chan remotecommand.TerminalSize) (int, error) { sessionID, err := c.ExecCreate(config) if err != nil { return -1, err diff --git a/libpod/container_internal.go b/libpod/container_internal.go index 4e18819b8..c930017a4 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -339,6 +339,29 @@ func (c *Container) syncContainer() error { return nil } +func (c *Container) setupStorageMapping(dest, from *storage.IDMappingOptions) { + if c.config.Rootfs != "" { + return + } + *dest = *from + if dest.AutoUserNs { + overrides := c.getUserOverrides() + dest.AutoUserNsOpts.PasswdFile = overrides.ContainerEtcPasswdPath + dest.AutoUserNsOpts.GroupFile = overrides.ContainerEtcGroupPath + if c.config.User != "" { + initialSize := uint32(0) + parts := strings.Split(c.config.User, ":") + for _, p := range parts { + s, err := strconv.ParseUint(p, 10, 32) + if err == nil && uint32(s) > initialSize { + initialSize = uint32(s) + } + } + dest.AutoUserNsOpts.InitialSize = initialSize + 1 + } + } +} + // Create container root filesystem for use func (c *Container) setupStorage(ctx context.Context) error { span, _ := opentracing.StartSpanFromContext(ctx, "setupStorage") @@ -398,14 +421,20 @@ func (c *Container) setupStorage(ctx context.Context) error { options.MountOpts = newOptions } - if c.config.Rootfs == "" { - options.IDMappingOptions = c.config.IDMappings - } + c.setupStorageMapping(&options.IDMappingOptions, &c.config.IDMappings) + containerInfo, err := c.runtime.storageService.CreateContainerStorage(ctx, c.runtime.imageContext, c.config.RootfsImageName, c.config.RootfsImageID, c.config.Name, c.config.ID, options) if err != nil { return errors.Wrapf(err, "error creating container storage") } + c.config.IDMappings.UIDMap = containerInfo.UIDMap + c.config.IDMappings.GIDMap = containerInfo.GIDMap + c.config.ProcessLabel = containerInfo.ProcessLabel + c.config.MountLabel = containerInfo.MountLabel + c.config.StaticDir = containerInfo.Dir + c.state.RunDir = containerInfo.RunDir + if len(c.config.IDMappings.UIDMap) != 0 || len(c.config.IDMappings.GIDMap) != 0 { if err := os.Chown(containerInfo.RunDir, c.RootUID(), c.RootGID()); err != nil { return err @@ -416,11 +445,6 @@ func (c *Container) setupStorage(ctx context.Context) error { } } - c.config.ProcessLabel = containerInfo.ProcessLabel - c.config.MountLabel = containerInfo.MountLabel - c.config.StaticDir = containerInfo.Dir - c.state.RunDir = containerInfo.RunDir - // Set the default Entrypoint and Command if containerInfo.Config != nil { if c.config.Entrypoint == nil { diff --git a/libpod/container_internal_linux.go b/libpod/container_internal_linux.go index a3f97f2a6..c40ad45b9 100644 --- a/libpod/container_internal_linux.go +++ b/libpod/container_internal_linux.go @@ -396,6 +396,20 @@ func (c *Container) generateSpec(ctx context.Context) (*spec.Spec, error) { } } + if c.config.IDMappings.AutoUserNs { + if err := g.AddOrReplaceLinuxNamespace(string(spec.UserNamespace), ""); err != nil { + return nil, err + } + g.ClearLinuxUIDMappings() + for _, uidmap := range c.config.IDMappings.UIDMap { + g.AddLinuxUIDMapping(uint32(uidmap.HostID), uint32(uidmap.ContainerID), uint32(uidmap.Size)) + } + g.ClearLinuxGIDMappings() + for _, gidmap := range c.config.IDMappings.GIDMap { + g.AddLinuxGIDMapping(uint32(gidmap.HostID), uint32(gidmap.ContainerID), uint32(gidmap.Size)) + } + } + g.SetRootPath(c.state.Mountpoint) g.AddAnnotation(annotations.Created, c.config.CreatedTime.Format(time.RFC3339Nano)) g.AddAnnotation("org.opencontainers.image.stopSignal", fmt.Sprintf("%d", c.config.StopSignal)) diff --git a/libpod/container_internal_unsupported.go b/libpod/container_internal_unsupported.go index 395271b2a..2a611c2d9 100644 --- a/libpod/container_internal_unsupported.go +++ b/libpod/container_internal_unsupported.go @@ -6,6 +6,7 @@ import ( "context" "github.com/containers/libpod/libpod/define" + "github.com/containers/libpod/pkg/lookup" spec "github.com/opencontainers/runtime-spec/specs-go" ) @@ -44,3 +45,7 @@ func (c *Container) copyOwnerAndPerms(source, dest string) error { func (c *Container) getOCICgroupPath() (string, error) { return "", define.ErrNotImplemented } + +func (c *Container) getUserOverrides() *lookup.Overrides { + return nil +} diff --git a/libpod/container_top_linux.go b/libpod/container_top_linux.go index 2a35a2ae9..98a69966a 100644 --- a/libpod/container_top_linux.go +++ b/libpod/container_top_linux.go @@ -112,7 +112,7 @@ func (c *Container) execPS(args []string) ([]string, error) { defer wErrPipe.Close() defer rErrPipe.Close() - streams := new(AttachStreams) + streams := new(define.AttachStreams) streams.OutputStream = wPipe streams.ErrorStream = wErrPipe streams.AttachOutput = true diff --git a/libpod/define/config.go b/libpod/define/config.go index 7b967f17d..10e00062a 100644 --- a/libpod/define/config.go +++ b/libpod/define/config.go @@ -1,5 +1,10 @@ package define +import ( + "bufio" + "io" +) + var ( // DefaultInfraImage to use for infra container DefaultInfraImage = "k8s.gcr.io/pause:3.2" @@ -33,3 +38,22 @@ const ( V2s2ManifestDir = "docker-dir" V2s2Archive = "docker-archive" ) + +// AttachStreams contains streams that will be attached to the container +type AttachStreams struct { + // OutputStream will be attached to container's STDOUT + OutputStream io.WriteCloser + // ErrorStream will be attached to container's STDERR + ErrorStream io.WriteCloser + // InputStream will be attached to container's STDIN + InputStream *bufio.Reader + // AttachOutput is whether to attach to STDOUT + // If false, stdout will not be attached + AttachOutput bool + // AttachError is whether to attach to STDERR + // If false, stdout will not be attached + AttachError bool + // AttachInput is whether to attach to STDIN + // If false, stdout will not be attached + AttachInput bool +} diff --git a/libpod/define/info.go b/libpod/define/info.go new file mode 100644 index 000000000..e9809c367 --- /dev/null +++ b/libpod/define/info.go @@ -0,0 +1,101 @@ +package define + +import "github.com/containers/storage/pkg/idtools" + +// Info is the overall struct that describes the host system +// running libpod/podman +type Info struct { + Host *HostInfo `json:"host"` + Store *StoreInfo `json:"store"` + Registries map[string]interface{} `json:"registries"` +} + +//HostInfo describes the libpod host +type HostInfo struct { + Arch string `json:"arch"` + BuildahVersion string `json:"buildahVersion"` + CGroupsVersion string `json:"cgroupVersion"` + Conmon *ConmonInfo `json:"conmon"` + CPUs int `json:"cpus"` + Distribution DistributionInfo `json:"distribution"` + EventLogger string `json:"eventLogger"` + Hostname string `json:"hostname"` + IDMappings IDMappings `json:"idMappings,omitempty"` + Kernel string `json:"kernel"` + MemFree int64 `json:"memFree"` + MemTotal int64 `json:"memTotal"` + OCIRuntime *OCIRuntimeInfo `json:"ociRuntime"` + OS string `json:"os"` + Rootless bool `json:"rootless"` + RuntimeInfo map[string]interface{} `json:"runtimeInfo,omitempty"` + Slirp4NetNS SlirpInfo `json:"slirp4netns,omitempty"` + SwapFree int64 `json:"swapFree"` + SwapTotal int64 `json:"swapTotal"` + Uptime string `json:"uptime"` +} + +// SlirpInfo describes the slirp exectuable that +// is being being used. +type SlirpInfo struct { + Executable string `json:"executable"` + Package string `json:"package"` + Version string `json:"version"` +} + +// IDMappings describe the GID and UID mappings +type IDMappings struct { + GIDMap []idtools.IDMap `json:"gidmap"` + UIDMap []idtools.IDMap `json:"uidmap"` +} + +// DistributionInfo describes the host distribution +// for libpod +type DistributionInfo struct { + Distribution string `json:"distribution"` + Version string `json:"version"` +} + +// ConmonInfo describes the conmon executable being used +type ConmonInfo struct { + Package string `json:"package"` + Path string `json:"path"` + Version string `json:"version"` +} + +// OCIRuntimeInfo describes the runtime (crun or runc) being +// used with podman +type OCIRuntimeInfo struct { + Name string `json:"name"` + Package string `json:"package"` + Path string `json:"path"` + Version string `json:"version"` +} + +// StoreInfo describes the container storage and its +// attributes +type StoreInfo struct { + ConfigFile string `json:"configFile"` + ContainerStore ContainerStore `json:"containerStore"` + GraphDriverName string `json:"graphDriverName"` + GraphOptions map[string]interface{} `json:"graphOptions"` + GraphRoot string `json:"graphRoot"` + GraphStatus map[string]string `json:"graphStatus"` + ImageStore ImageStore `json:"imageStore"` + RunRoot string `json:"runRoot"` + VolumePath string `json:"volumePath"` +} + +// ImageStore describes the image store. Right now only the number +// of images present +type ImageStore struct { + Number int `json:"number"` +} + +// ContainerStore describes the quantity of containers in the +// store by status +type ContainerStore struct { + Number int `json:"number"` + Paused int `json:"paused"` + Running int `json:"running"` + Stopped int `json:"stopped"` +} diff --git a/libpod/filters/containers.go b/libpod/filters/containers.go new file mode 100644 index 000000000..c13372f91 --- /dev/null +++ b/libpod/filters/containers.go @@ -0,0 +1,157 @@ +package lpfilters + +import ( + "regexp" + "strconv" + "strings" + "time" + + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/define" + "github.com/containers/libpod/pkg/timetype" + "github.com/containers/libpod/pkg/util" + "github.com/pkg/errors" +) + +// GenerateContainerFilterFuncs return ContainerFilter functions based of filter. +func GenerateContainerFilterFuncs(filter, filterValue string, r *libpod.Runtime) (func(container *libpod.Container) bool, error) { + switch filter { + case "id": + return func(c *libpod.Container) bool { + return strings.Contains(c.ID(), filterValue) + }, nil + case "label": + var filterArray = strings.SplitN(filterValue, "=", 2) + var filterKey = filterArray[0] + if len(filterArray) > 1 { + filterValue = filterArray[1] + } else { + filterValue = "" + } + return func(c *libpod.Container) bool { + for labelKey, labelValue := range c.Labels() { + if labelKey == filterKey && ("" == filterValue || labelValue == filterValue) { + return true + } + } + return false + }, nil + case "name": + return func(c *libpod.Container) bool { + match, err := regexp.MatchString(filterValue, c.Name()) + if err != nil { + return false + } + return match + }, nil + case "exited": + exitCode, err := strconv.ParseInt(filterValue, 10, 32) + if err != nil { + return nil, errors.Wrapf(err, "exited code out of range %q", filterValue) + } + return func(c *libpod.Container) bool { + ec, exited, err := c.ExitCode() + if ec == int32(exitCode) && err == nil && exited { + return true + } + return false + }, nil + case "status": + if !util.StringInSlice(filterValue, []string{"created", "running", "paused", "stopped", "exited", "unknown"}) { + return nil, errors.Errorf("%s is not a valid status", filterValue) + } + return func(c *libpod.Container) bool { + status, err := c.State() + if err != nil { + return false + } + if filterValue == "stopped" { + filterValue = "exited" + } + state := status.String() + if status == define.ContainerStateConfigured { + state = "created" + } else if status == define.ContainerStateStopped { + state = "exited" + } + return state == filterValue + }, nil + case "ancestor": + // This needs to refine to match docker + // - ancestor=(<image-name>[:tag]|<image-id>| ⟨image@digest⟩) - containers created from an image or a descendant. + return func(c *libpod.Container) bool { + containerConfig := c.Config() + if strings.Contains(containerConfig.RootfsImageID, filterValue) || strings.Contains(containerConfig.RootfsImageName, filterValue) { + return true + } + return false + }, nil + case "before": + ctr, err := r.LookupContainer(filterValue) + if err != nil { + return nil, errors.Errorf("unable to find container by name or id of %s", filterValue) + } + containerConfig := ctr.Config() + createTime := containerConfig.CreatedTime + return func(c *libpod.Container) bool { + cc := c.Config() + return createTime.After(cc.CreatedTime) + }, nil + case "since": + ctr, err := r.LookupContainer(filterValue) + if err != nil { + return nil, errors.Errorf("unable to find container by name or id of %s", filterValue) + } + containerConfig := ctr.Config() + createTime := containerConfig.CreatedTime + return func(c *libpod.Container) bool { + cc := c.Config() + return createTime.Before(cc.CreatedTime) + }, nil + case "volume": + //- volume=(<volume-name>|<mount-point-destination>) + return func(c *libpod.Container) bool { + containerConfig := c.Config() + var dest string + arr := strings.Split(filterValue, ":") + source := arr[0] + if len(arr) == 2 { + dest = arr[1] + } + for _, mount := range containerConfig.Spec.Mounts { + if dest != "" && (mount.Source == source && mount.Destination == dest) { + return true + } + if dest == "" && mount.Source == source { + return true + } + } + return false + }, nil + case "health": + return func(c *libpod.Container) bool { + hcStatus, err := c.HealthCheckStatus() + if err != nil { + return false + } + return hcStatus == filterValue + }, nil + case "until": + ts, err := timetype.GetTimestamp(filterValue, time.Now()) + if err != nil { + return nil, err + } + seconds, nanoseconds, err := timetype.ParseTimestamps(ts, 0) + if err != nil { + return nil, err + } + until := time.Unix(seconds, nanoseconds) + return func(c *libpod.Container) bool { + if !until.IsZero() && c.CreatedTime().After((until)) { + return true + } + return false + }, nil + } + return nil, errors.Errorf("%s is an invalid filter", filter) +} diff --git a/libpod/podfilters/pods.go b/libpod/filters/pods.go index 54fa85edc..9bf436eab 100644 --- a/libpod/podfilters/pods.go +++ b/libpod/filters/pods.go @@ -1,4 +1,4 @@ -package podfilters +package lpfilters import ( "strconv" diff --git a/libpod/healthcheck.go b/libpod/healthcheck.go index 08a613dfe..daddb6561 100644 --- a/libpod/healthcheck.go +++ b/libpod/healthcheck.go @@ -108,7 +108,7 @@ func (c *Container) runHealthCheck() (HealthCheckStatus, error) { hcw := hcWriteCloser{ captureBuffer, } - streams := new(AttachStreams) + streams := new(define.AttachStreams) streams.OutputStream = hcw streams.ErrorStream = hcw diff --git a/libpod/info.go b/libpod/info.go index 8d411f0d4..3cc767be6 100644 --- a/libpod/info.go +++ b/libpod/info.go @@ -13,7 +13,9 @@ import ( "time" "github.com/containers/buildah" + "github.com/containers/libpod/libpod/define" "github.com/containers/libpod/pkg/cgroups" + registries2 "github.com/containers/libpod/pkg/registries" "github.com/containers/libpod/pkg/rootless" "github.com/containers/storage" "github.com/containers/storage/pkg/system" @@ -21,14 +23,80 @@ import ( "github.com/sirupsen/logrus" ) +// Info returns the store and host information +func (r *Runtime) info() (*define.Info, error) { + info := define.Info{} + // get host information + hostInfo, err := r.hostInfo() + if err != nil { + return nil, errors.Wrapf(err, "error getting host info") + } + info.Host = hostInfo + + // get store information + storeInfo, err := r.storeInfo() + if err != nil { + return nil, errors.Wrapf(err, "error getting store info") + } + info.Store = storeInfo + registries := make(map[string]interface{}) + data, err := registries2.GetRegistriesData() + if err != nil { + return nil, errors.Wrapf(err, "error getting registries") + } + for _, reg := range data { + registries[reg.Prefix] = reg + } + regs, err := registries2.GetRegistries() + if err != nil { + return nil, errors.Wrapf(err, "error getting registries") + } + if len(regs) > 0 { + registries["search"] = regs + } + + info.Registries = registries + return &info, nil +} + // top-level "host" info -func (r *Runtime) hostInfo() (map[string]interface{}, error) { +func (r *Runtime) hostInfo() (*define.HostInfo, error) { // lets say OS, arch, number of cpus, amount of memory, maybe os distribution/version, hostname, kernel version, uptime - info := map[string]interface{}{} - info["os"] = runtime.GOOS - info["arch"] = runtime.GOARCH - info["cpus"] = runtime.NumCPU() - info["rootless"] = rootless.IsRootless() + mi, err := system.ReadMemInfo() + if err != nil { + return nil, errors.Wrapf(err, "error reading memory info") + } + + hostDistributionInfo := r.GetHostDistributionInfo() + + kv, err := readKernelVersion() + if err != nil { + return nil, errors.Wrapf(err, "error reading kernel version") + } + + host, err := os.Hostname() + if err != nil { + return nil, errors.Wrapf(err, "error getting hostname") + } + info := define.HostInfo{ + Arch: runtime.GOARCH, + BuildahVersion: buildah.Version, + CPUs: runtime.NumCPU(), + Distribution: hostDistributionInfo, + EventLogger: r.eventer.String(), + Hostname: host, + IDMappings: define.IDMappings{}, + Kernel: kv, + MemFree: mi.MemFree, + MemTotal: mi.MemTotal, + OS: runtime.GOOS, + Rootless: rootless.IsRootless(), + Slirp4NetNS: define.SlirpInfo{}, + SwapFree: mi.SwapFree, + SwapTotal: mi.SwapTotal, + } + + // CGroups version unified, err := cgroups.IsCgroup2UnifiedMode() if err != nil { return nil, errors.Wrapf(err, "error reading cgroups mode") @@ -37,17 +105,8 @@ func (r *Runtime) hostInfo() (map[string]interface{}, error) { if unified { cgroupVersion = "v2" } - info["CgroupVersion"] = cgroupVersion - mi, err := system.ReadMemInfo() - if err != nil { - return nil, errors.Wrapf(err, "error reading memory info") - } - // TODO this might be a place for github.com/dustin/go-humanize - info["MemTotal"] = mi.MemTotal - info["MemFree"] = mi.MemFree - info["SwapTotal"] = mi.SwapTotal - info["SwapFree"] = mi.SwapFree - hostDistributionInfo := r.GetHostDistributionInfo() + info.CGroupsVersion = cgroupVersion + if rootless.IsRootless() { if path, err := exec.LookPath("slirp4netns"); err == nil { logrus.Warnf("Failed to retrieve program version for %s: %v", path, err) @@ -55,11 +114,12 @@ func (r *Runtime) hostInfo() (map[string]interface{}, error) { if err != nil { logrus.Warnf("Failed to retrieve program version for %s: %v", path, err) } - program := map[string]interface{}{} - program["Executable"] = path - program["Version"] = version - program["Package"] = packageVersion(path) - info["slirp4netns"] = program + program := define.SlirpInfo{ + Executable: path, + Package: packageVersion(path), + Version: version, + } + info.Slirp4NetNS = program } uidmappings, err := rootless.ReadMappingsProc("/proc/self/uid_map") if err != nil { @@ -69,29 +129,19 @@ func (r *Runtime) hostInfo() (map[string]interface{}, error) { if err != nil { return nil, errors.Wrapf(err, "error reading gid mappings") } - idmappings := make(map[string]interface{}) - idmappings["uidmap"] = uidmappings - idmappings["gidmap"] = gidmappings - info["IDMappings"] = idmappings - } - info["Distribution"] = map[string]interface{}{ - "distribution": hostDistributionInfo["Distribution"], - "version": hostDistributionInfo["Version"], - } - info["BuildahVersion"] = buildah.Version - kv, err := readKernelVersion() - if err != nil { - return nil, errors.Wrapf(err, "error reading kernel version") + idmappings := define.IDMappings{ + GIDMap: gidmappings, + UIDMap: uidmappings, + } + info.IDMappings = idmappings } - info["kernel"] = kv - runtimeInfo, err := r.defaultOCIRuntime.RuntimeInfo() + conmonInfo, ociruntimeInfo, err := r.defaultOCIRuntime.RuntimeInfo() if err != nil { logrus.Errorf("Error getting info on OCI runtime %s: %v", r.defaultOCIRuntime.Name(), err) } else { - for k, v := range runtimeInfo { - info[k] = v - } + info.Conmon = conmonInfo + info.OCIRuntime = ociruntimeInfo } up, err := readUptime() @@ -105,6 +155,7 @@ func (r *Runtime) hostInfo() (map[string]interface{}, error) { return nil, errors.Wrapf(err, "error parsing system uptime") } + // TODO Isnt there a simple lib for this, something like humantime? hoursFound := false var timeBuffer bytes.Buffer var hoursBuffer bytes.Buffer @@ -121,32 +172,75 @@ func (r *Runtime) hostInfo() (map[string]interface{}, error) { } } - info["uptime"] = timeBuffer.String() + info.Uptime = timeBuffer.String() if hoursFound { hours, err := strconv.ParseFloat(hoursBuffer.String(), 64) if err == nil { days := hours / 24 - info["uptime"] = fmt.Sprintf("%s (Approximately %.2f days)", info["uptime"], days) + info.Uptime = fmt.Sprintf("%s (Approximately %.2f days)", info.Uptime, days) } } - host, err := os.Hostname() + return &info, nil +} + +func (r *Runtime) getContainerStoreInfo() (define.ContainerStore, error) { + var ( + paused, running, stopped int + ) + cs := define.ContainerStore{} + cons, err := r.GetAllContainers() if err != nil { - return nil, errors.Wrapf(err, "error getting hostname") + return cs, err } - info["hostname"] = host - info["eventlogger"] = r.eventer.String() - - return info, nil + for _, con := range cons { + state, err := con.State() + if err != nil { + return cs, err + } + switch state { + case define.ContainerStateRunning: + running += 1 + case define.ContainerStatePaused: + paused += 1 + default: + stopped += 1 + } + } + cs.Number = len(cons) + cs.Paused = paused + cs.Stopped = stopped + cs.Running = running + return cs, nil } // top-level "store" info -func (r *Runtime) storeInfo() (map[string]interface{}, error) { +func (r *Runtime) storeInfo() (*define.StoreInfo, error) { // lets say storage driver in use, number of images, number of containers - info := map[string]interface{}{} - info["GraphRoot"] = r.store.GraphRoot() - info["RunRoot"] = r.store.RunRoot() - info["GraphDriverName"] = r.store.GraphDriverName() + configFile, err := storage.DefaultConfigFile(rootless.IsRootless()) + if err != nil { + return nil, err + } + images, err := r.store.Images() + if err != nil { + return nil, errors.Wrapf(err, "error getting number of images") + } + conInfo, err := r.getContainerStoreInfo() + if err != nil { + return nil, err + } + imageInfo := define.ImageStore{Number: len(images)} + + info := define.StoreInfo{ + ImageStore: imageInfo, + ContainerStore: conInfo, + GraphRoot: r.store.GraphRoot(), + RunRoot: r.store.RunRoot(), + GraphDriverName: r.store.GraphDriverName(), + GraphOptions: nil, + VolumePath: r.config.Engine.VolumePath, + ConfigFile: configFile, + } graphOptions := map[string]interface{}{} for _, o := range r.store.GraphOptions() { split := strings.SplitN(o, "=", 2) @@ -164,14 +258,8 @@ func (r *Runtime) storeInfo() (map[string]interface{}, error) { graphOptions[split[0]] = split[1] } } - info["GraphOptions"] = graphOptions - info["VolumePath"] = r.config.Engine.VolumePath + info.GraphOptions = graphOptions - configFile, err := storage.DefaultConfigFile(rootless.IsRootless()) - if err != nil { - return nil, err - } - info["ConfigFile"] = configFile statusPairs, err := r.store.Status() if err != nil { return nil, err @@ -180,24 +268,8 @@ func (r *Runtime) storeInfo() (map[string]interface{}, error) { for _, pair := range statusPairs { status[pair[0]] = pair[1] } - info["GraphStatus"] = status - images, err := r.store.Images() - if err != nil { - return nil, errors.Wrapf(err, "error getting number of images") - } - info["ImageStore"] = map[string]interface{}{ - "number": len(images), - } - - containers, err := r.store.Containers() - if err != nil { - return nil, errors.Wrapf(err, "error getting number of containers") - } - info["ContainerStore"] = map[string]interface{}{ - "number": len(containers), - } - - return info, nil + info.GraphStatus = status + return &info, nil } func readKernelVersion() (string, error) { @@ -225,14 +297,13 @@ func readUptime() (string, error) { } // GetHostDistributionInfo returns a map containing the host's distribution and version -func (r *Runtime) GetHostDistributionInfo() map[string]string { - dist := make(map[string]string) - +func (r *Runtime) GetHostDistributionInfo() define.DistributionInfo { // Populate values in case we cannot find the values // or the file - dist["Distribution"] = "unknown" - dist["Version"] = "unknown" - + dist := define.DistributionInfo{ + Distribution: "unknown", + Version: "unknown", + } f, err := os.Open("/etc/os-release") if err != nil { return dist @@ -242,10 +313,10 @@ func (r *Runtime) GetHostDistributionInfo() map[string]string { l := bufio.NewScanner(f) for l.Scan() { if strings.HasPrefix(l.Text(), "ID=") { - dist["Distribution"] = strings.TrimPrefix(l.Text(), "ID=") + dist.Distribution = strings.TrimPrefix(l.Text(), "ID=") } if strings.HasPrefix(l.Text(), "VERSION_ID=") { - dist["Version"] = strings.Trim(strings.TrimPrefix(l.Text(), "VERSION_ID="), "\"") + dist.Version = strings.Trim(strings.TrimPrefix(l.Text(), "VERSION_ID="), "\"") } } return dist diff --git a/libpod/oci.go b/libpod/oci.go index ef46cf5c3..6adf42497 100644 --- a/libpod/oci.go +++ b/libpod/oci.go @@ -4,6 +4,7 @@ import ( "bufio" "net" + "github.com/containers/libpod/libpod/define" "k8s.io/client-go/tools/remotecommand" ) @@ -120,7 +121,7 @@ type OCIRuntime interface { ExitFilePath(ctr *Container) (string, error) // RuntimeInfo returns verbose information about the runtime. - RuntimeInfo() (map[string]interface{}, error) + RuntimeInfo() (*define.ConmonInfo, *define.OCIRuntimeInfo, error) } // ExecOptions are options passed into ExecContainer. They control the command @@ -141,7 +142,7 @@ type ExecOptions struct { // the container was run as will be used. User string // Streams are the streams that will be attached to the container. - Streams *AttachStreams + Streams *define.AttachStreams // PreserveFDs is a number of additional file descriptors (in addition // to 0, 1, 2) that will be passed to the executed process. The total FDs // passed will be 3 + PreserveFDs. diff --git a/libpod/oci_attach_linux.go b/libpod/oci_attach_linux.go index fb0a54bff..ff158c2d1 100644 --- a/libpod/oci_attach_linux.go +++ b/libpod/oci_attach_linux.go @@ -31,7 +31,7 @@ const ( // Attach to the given container // Does not check if state is appropriate // started is only required if startContainer is true -func (c *Container) attach(streams *AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, startContainer bool, started chan bool) error { +func (c *Container) attach(streams *define.AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, startContainer bool, started chan bool) error { if !streams.AttachOutput && !streams.AttachError && !streams.AttachInput { return errors.Wrapf(define.ErrInvalidArg, "must provide at least one stream to attach to") } @@ -94,7 +94,7 @@ func (c *Container) attach(streams *AttachStreams, keys string, resize <-chan re // 4. attachToExec sends on startFd, signalling it has attached to the socket and child is ready to go // 5. child receives on startFd, runs the runtime exec command // attachToExec is responsible for closing startFd and attachFd -func (c *Container) attachToExec(streams *AttachStreams, keys *string, sessionID string, startFd, attachFd *os.File) error { +func (c *Container) attachToExec(streams *define.AttachStreams, keys *string, sessionID string, startFd, attachFd *os.File) error { if !streams.AttachOutput && !streams.AttachError && !streams.AttachInput { return errors.Wrapf(define.ErrInvalidArg, "must provide at least one stream to attach to") } @@ -189,7 +189,7 @@ func buildSocketPath(socketPath string) string { return socketPath } -func setupStdioChannels(streams *AttachStreams, conn *net.UnixConn, detachKeys []byte) (chan error, chan error) { +func setupStdioChannels(streams *define.AttachStreams, conn *net.UnixConn, detachKeys []byte) (chan error, chan error) { receiveStdoutError := make(chan error) go func() { receiveStdoutError <- redirectResponseToOutputStreams(streams.OutputStream, streams.ErrorStream, streams.AttachOutput, streams.AttachError, conn) @@ -257,7 +257,7 @@ func redirectResponseToOutputStreams(outputStream, errorStream io.Writer, writeO return err } -func readStdio(streams *AttachStreams, receiveStdoutError, stdinDone chan error) error { +func readStdio(streams *define.AttachStreams, receiveStdoutError, stdinDone chan error) error { var err error select { case err = <-receiveStdoutError: diff --git a/libpod/oci_attach_unsupported.go b/libpod/oci_attach_unsupported.go index 987d2c973..3b0216e5d 100644 --- a/libpod/oci_attach_unsupported.go +++ b/libpod/oci_attach_unsupported.go @@ -9,10 +9,10 @@ import ( "k8s.io/client-go/tools/remotecommand" ) -func (c *Container) attach(streams *AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, startContainer bool, started chan bool) error { +func (c *Container) attach(streams *define.AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, startContainer bool, started chan bool) error { return define.ErrNotImplemented } -func (c *Container) attachToExec(streams *AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, sessionID string, startFd *os.File, attachFd *os.File) error { +func (c *Container) attachToExec(streams *define.AttachStreams, keys string, resize <-chan remotecommand.TerminalSize, sessionID string, startFd *os.File, attachFd *os.File) error { return define.ErrNotImplemented } diff --git a/libpod/oci_conmon_linux.go b/libpod/oci_conmon_linux.go index 2e96dbe57..c20e3f0b4 100644 --- a/libpod/oci_conmon_linux.go +++ b/libpod/oci_conmon_linux.go @@ -999,32 +999,30 @@ func (r *ConmonOCIRuntime) ExitFilePath(ctr *Container) (string, error) { } // RuntimeInfo provides information on the runtime. -func (r *ConmonOCIRuntime) RuntimeInfo() (map[string]interface{}, error) { +func (r *ConmonOCIRuntime) RuntimeInfo() (*define.ConmonInfo, *define.OCIRuntimeInfo, error) { runtimePackage := packageVersion(r.path) conmonPackage := packageVersion(r.conmonPath) runtimeVersion, err := r.getOCIRuntimeVersion() if err != nil { - return nil, errors.Wrapf(err, "error getting version of OCI runtime %s", r.name) + return nil, nil, errors.Wrapf(err, "error getting version of OCI runtime %s", r.name) } conmonVersion, err := r.getConmonVersion() if err != nil { - return nil, errors.Wrapf(err, "error getting conmon version") + return nil, nil, errors.Wrapf(err, "error getting conmon version") } - info := make(map[string]interface{}) - info["Conmon"] = map[string]interface{}{ - "path": r.conmonPath, - "package": conmonPackage, - "version": conmonVersion, + conmon := define.ConmonInfo{ + Package: conmonPackage, + Path: r.conmonPath, + Version: conmonVersion, } - info["OCIRuntime"] = map[string]interface{}{ - "name": r.name, - "path": r.path, - "package": runtimePackage, - "version": runtimeVersion, + ocirt := define.OCIRuntimeInfo{ + Name: r.name, + Path: r.path, + Package: runtimePackage, + Version: runtimeVersion, } - - return info, nil + return &conmon, &ocirt, nil } // makeAccessible changes the path permission and each parent directory to have --x--x--x diff --git a/libpod/oci_conmon_unsupported.go b/libpod/oci_conmon_unsupported.go index 395b6f6d9..1f9d89ff6 100644 --- a/libpod/oci_conmon_unsupported.go +++ b/libpod/oci_conmon_unsupported.go @@ -117,8 +117,8 @@ func (r *ConmonOCIRuntime) ExitFilePath(ctr *Container) (string, error) { } // RuntimeInfo is not supported on this OS. -func (r *ConmonOCIRuntime) RuntimeInfo() (map[string]interface{}, error) { - return nil, define.ErrNotImplemented +func (r *ConmonOCIRuntime) RuntimeInfo() (*define.ConmonInfo, *define.OCIRuntimeInfo, error) { + return nil, nil, define.ErrNotImplemented } // Package is not supported on this OS. diff --git a/libpod/oci_missing.go b/libpod/oci_missing.go index a5d589255..5284fb4b7 100644 --- a/libpod/oci_missing.go +++ b/libpod/oci_missing.go @@ -195,15 +195,14 @@ func (r *MissingRuntime) ExitFilePath(ctr *Container) (string, error) { } // RuntimeInfo returns information on the missing runtime -func (r *MissingRuntime) RuntimeInfo() (map[string]interface{}, error) { - info := make(map[string]interface{}) - info["OCIRuntime"] = map[string]interface{}{ - "name": r.name, - "path": "missing", - "package": "missing", - "version": "missing", +func (r *MissingRuntime) RuntimeInfo() (*define.ConmonInfo, *define.OCIRuntimeInfo, error) { + ocirt := define.OCIRuntimeInfo{ + Name: r.name, + Path: "missing", + Package: "missing", + Version: "missing", } - return info, nil + return nil, &ocirt, nil } // Return an error indicating the runtime is missing diff --git a/libpod/runtime.go b/libpod/runtime.go index 422b79359..a6032ad23 100644 --- a/libpod/runtime.go +++ b/libpod/runtime.go @@ -9,16 +9,14 @@ import ( "sync" "syscall" + "github.com/containers/common/pkg/config" is "github.com/containers/image/v5/storage" "github.com/containers/image/v5/types" - - "github.com/containers/common/pkg/config" "github.com/containers/libpod/libpod/define" "github.com/containers/libpod/libpod/events" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/libpod/lock" "github.com/containers/libpod/pkg/cgroups" - sysreg "github.com/containers/libpod/pkg/registries" "github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/util" "github.com/containers/storage" @@ -675,40 +673,8 @@ func (r *Runtime) refresh(alivePath string) error { } // Info returns the store and host information -func (r *Runtime) Info() ([]define.InfoData, error) { - info := []define.InfoData{} - // get host information - hostInfo, err := r.hostInfo() - if err != nil { - return nil, errors.Wrapf(err, "error getting host info") - } - info = append(info, define.InfoData{Type: "host", Data: hostInfo}) - - // get store information - storeInfo, err := r.storeInfo() - if err != nil { - return nil, errors.Wrapf(err, "error getting store info") - } - info = append(info, define.InfoData{Type: "store", Data: storeInfo}) - - registries := make(map[string]interface{}) - data, err := sysreg.GetRegistriesData() - if err != nil { - return nil, errors.Wrapf(err, "error getting registries") - } - for _, reg := range data { - registries[reg.Prefix] = reg - } - regs, err := sysreg.GetRegistries() - if err != nil { - return nil, errors.Wrapf(err, "error getting registries") - } - if len(regs) > 0 { - registries["search"] = regs - } - - info = append(info, define.InfoData{Type: "registries", Data: registries}) - return info, nil +func (r *Runtime) Info() (*define.Info, error) { + return r.info() } // generateName generates a unique name for a container or pod. diff --git a/libpod/storage.go b/libpod/storage.go index d675f4ffe..34e40f699 100644 --- a/libpod/storage.go +++ b/libpod/storage.go @@ -8,6 +8,7 @@ import ( "github.com/containers/image/v5/types" "github.com/containers/libpod/libpod/define" "github.com/containers/storage" + "github.com/containers/storage/pkg/idtools" v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/opentracing/opentracing-go" "github.com/pkg/errors" @@ -35,6 +36,8 @@ type ContainerInfo struct { Config *v1.Image ProcessLabel string MountLabel string + UIDMap []idtools.IDMap + GIDMap []idtools.IDMap } // RuntimeContainerMetadata is the structure that we encode as JSON and store @@ -166,6 +169,8 @@ func (r *storageService) CreateContainerStorage(ctx context.Context, systemConte logrus.Debugf("container %q has run directory %q", container.ID, containerRunDir) return ContainerInfo{ + UIDMap: options.UIDMap, + GIDMap: options.GIDMap, Dir: containerDir, RunDir: containerRunDir, Config: imageConfig, |