diff options
50 files changed, 854 insertions, 628 deletions
diff --git a/.golangci.yml b/.golangci.yml index b04683b7b..5480b02bb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -28,6 +28,7 @@ linters: - misspell - prealloc - unparam + - nakedret linters-settings: errcheck: check-blank: false diff --git a/cmd/podman/common/createparse.go b/cmd/podman/common/createparse.go index aca6f752e..fe6e322c2 100644 --- a/cmd/podman/common/createparse.go +++ b/cmd/podman/common/createparse.go @@ -1,7 +1,6 @@ package common import ( - "github.com/containers/libpod/cmd/podman/parse" "github.com/containers/libpod/pkg/util" "github.com/pkg/errors" ) @@ -17,27 +16,7 @@ func (c *ContainerCLIOpts) validate() error { if _, err := util.ValidatePullType(c.Pull); err != nil { return err } - // Verify the additional hosts are in correct format - for _, host := range c.Net.AddHosts { - if _, err := parse.ValidateExtraHost(host); err != nil { - return err - } - } - if dnsSearches := c.Net.DNSSearch; len(dnsSearches) > 0 { - // Validate domains are good - for _, dom := range dnsSearches { - if dom == "." { - if len(dnsSearches) > 1 { - return errors.Errorf("cannot pass additional search domains when also specifying '.'") - } - continue - } - if _, err := parse.ValidateDomain(dom); err != nil { - return err - } - } - } var imageVolType = map[string]string{ "bind": "", "tmpfs": "", diff --git a/cmd/podman/common/netflags.go b/cmd/podman/common/netflags.go index 06c1b4521..1a47733e7 100644 --- a/cmd/podman/common/netflags.go +++ b/cmd/podman/common/netflags.go @@ -3,7 +3,9 @@ package common import ( "net" + "github.com/containers/libpod/cmd/podman/parse" "github.com/containers/libpod/pkg/domain/entities" + "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -58,20 +60,60 @@ func NetFlagsToNetOptions(cmd *cobra.Command) (*entities.NetOptions, error) { if err != nil { return nil, err } - servers, err := cmd.Flags().GetStringSlice("dns") - if err != nil { - return nil, err + // Verify the additional hosts are in correct format + for _, host := range opts.AddHosts { + if _, err := parse.ValidateExtraHost(host); err != nil { + return nil, err + } } - for _, d := range servers { - if d == "none" { - opts.DNSHost = true - break + + if cmd.Flags().Changed("dns") { + servers, err := cmd.Flags().GetStringSlice("dns") + if err != nil { + return nil, err + } + for _, d := range servers { + if d == "none" { + opts.UseImageResolvConf = true + if len(servers) > 1 { + return nil, errors.Errorf("%s is not allowed to be specified with other DNS ip addresses", d) + } + break + } + dns := net.ParseIP(d) + if dns == nil { + return nil, errors.Errorf("%s is not an ip address", d) + } + opts.DNSServers = append(opts.DNSServers, dns) } - opts.DNSServers = append(opts.DNSServers, net.ParseIP(d)) } - opts.DNSSearch, err = cmd.Flags().GetStringSlice("dns-search") - if err != nil { - return nil, err + + if cmd.Flags().Changed("dns-opt") { + options, err := cmd.Flags().GetStringSlice("dns-opt") + if err != nil { + return nil, err + } + opts.DNSOptions = options + } + + if cmd.Flags().Changed("dns-search") { + dnsSearches, err := cmd.Flags().GetStringSlice("dns-search") + if err != nil { + return nil, err + } + // Validate domains are good + for _, dom := range dnsSearches { + if dom == "." { + if len(dnsSearches) > 1 { + return nil, errors.Errorf("cannot pass additional search domains when also specifying '.'") + } + continue + } + if _, err := parse.ValidateDomain(dom); err != nil { + return nil, err + } + } + opts.DNSSearch = dnsSearches } m, err := cmd.Flags().GetString("mac-address") @@ -85,6 +127,7 @@ func NetFlagsToNetOptions(cmd *cobra.Command) (*entities.NetOptions, error) { } opts.StaticMAC = &mac } + inputPorts, err := cmd.Flags().GetStringSlice("publish") if err != nil { return nil, err @@ -95,6 +138,31 @@ func NetFlagsToNetOptions(cmd *cobra.Command) (*entities.NetOptions, error) { return nil, err } } + + ip, err := cmd.Flags().GetString("ip") + if err != nil { + return nil, err + } + if ip != "" { + staticIP := net.ParseIP(ip) + if staticIP == nil { + return nil, errors.Errorf("%s is not an ip address", ip) + } + opts.StaticIP = &staticIP + } + opts.NoHosts, err = cmd.Flags().GetBool("no-hosts") + + if cmd.Flags().Changed("network") { + network, err := cmd.Flags().GetString("network") + if err != nil { + return nil, err + } + + return nil, errors.Errorf("network %s is not yet supported", network) + // TODO How do I convert a string network to a Specgen.Namespace? + // opts.Network = specgen.Namespace{NSMode: network} + } + return &opts, err } diff --git a/cmd/podman/common/specgen.go b/cmd/podman/common/specgen.go index b8526993c..1eb8fc0bd 100644 --- a/cmd/podman/common/specgen.go +++ b/cmd/podman/common/specgen.go @@ -292,9 +292,12 @@ func FillOutSpecGen(s *specgen.SpecGenerator, c *ContainerCLIOpts, args []string } s.ShmSize = &shmSize s.HostAdd = c.Net.AddHosts - s.DNSServer = c.Net.DNSServers + s.UseImageResolvConf = c.Net.UseImageResolvConf + s.DNSServers = c.Net.DNSServers s.DNSSearch = c.Net.DNSSearch - s.DNSOption = c.Net.DNSOptions + s.DNSOptions = c.Net.DNSOptions + s.StaticIP = c.Net.StaticIP + s.StaticMAC = c.Net.StaticMAC // deferred, must be added on libpod side //var ImageVolumes map[string]struct{} @@ -424,6 +427,7 @@ func FillOutSpecGen(s *specgen.SpecGenerator, c *ContainerCLIOpts, args []string } } + s.SeccompPolicy = c.SeccompPolicy // TODO any idea why this was done // storage.go from spec/ // grab it diff --git a/cmd/podman/containers/run.go b/cmd/podman/containers/run.go index 9d222e44d..16a54e578 100644 --- a/cmd/podman/containers/run.go +++ b/cmd/podman/containers/run.go @@ -122,7 +122,7 @@ func run(cmd *cobra.Command, args []string) error { return nil } if runRmi { - _, err := registry.ImageEngine().Delete(registry.GetContext(), []string{args[0]}, entities.ImageDeleteOptions{}) + _, err := registry.ImageEngine().Remove(registry.GetContext(), []string{args[0]}, entities.ImageRemoveOptions{}) if err != nil { logrus.Errorf("%s", errors.Wrapf(err, "failed removing image")) } diff --git a/cmd/podman/images/inspect.go b/cmd/podman/images/inspect.go index 4482ceee5..11bef02ba 100644 --- a/cmd/podman/images/inspect.go +++ b/cmd/podman/images/inspect.go @@ -20,11 +20,13 @@ import ( var ( // Command: podman image _inspect_ inspectCmd = &cobra.Command{ - Use: "inspect [flags] IMAGE", - Short: "Display the configuration of an image", - Long: `Displays the low-level information on an image identified by name or ID.`, - RunE: inspect, - Example: `podman image inspect alpine`, + Use: "inspect [flags] IMAGE", + Short: "Display the configuration of an image", + Long: `Displays the low-level information on an image identified by name or ID.`, + RunE: inspect, + Example: `podman inspect alpine + podman inspect --format "imageId: {{.Id}} size: {{.Size}}" alpine + podman inspect --format "image: {{.ImageName}} driver: {{.Driver}}" myctr`, } inspectOpts *entities.InspectOptions ) @@ -39,14 +41,14 @@ func init() { } func inspect(cmd *cobra.Command, args []string) error { - latestContainer := inspectOpts.Latest - - if len(args) == 0 && !latestContainer { - return errors.Errorf("container or image name must be specified: podman inspect [options [...]] name") + if inspectOpts.Size { + return fmt.Errorf("--size can only be used for containers") } - - if len(args) > 0 && latestContainer { - return errors.Errorf("you cannot provide additional arguments with --latest") + if inspectOpts.Latest { + return fmt.Errorf("--latest can only be used for containers") + } + if len(args) == 0 { + return errors.Errorf("image name must be specified: podman image inspect [options [...]] name") } results, err := registry.ImageEngine().Inspect(context.Background(), args, *inspectOpts) diff --git a/cmd/podman/images/rm.go b/cmd/podman/images/rm.go index 135fda387..da6a90d2b 100644 --- a/cmd/podman/images/rm.go +++ b/cmd/podman/images/rm.go @@ -2,7 +2,6 @@ package images import ( "fmt" - "os" "github.com/containers/libpod/cmd/podman/registry" "github.com/containers/libpod/pkg/domain/entities" @@ -23,7 +22,7 @@ var ( podman image rm c4dfb1609ee2 93fd78260bd1 c0ed59d05ff7`, } - imageOpts = entities.ImageDeleteOptions{} + imageOpts = entities.ImageRemoveOptions{} ) func init() { @@ -40,32 +39,25 @@ func imageRemoveFlagSet(flags *pflag.FlagSet) { flags.BoolVarP(&imageOpts.All, "all", "a", false, "Remove all images") flags.BoolVarP(&imageOpts.Force, "force", "f", false, "Force Removal of the image") } -func rm(cmd *cobra.Command, args []string) error { +func rm(cmd *cobra.Command, args []string) error { if len(args) < 1 && !imageOpts.All { return errors.Errorf("image name or ID must be specified") } if len(args) > 0 && imageOpts.All { return errors.Errorf("when using the --all switch, you may not pass any images names or IDs") } - report, err := registry.ImageEngine().Delete(registry.GetContext(), args, imageOpts) - if err != nil { - switch { - case report != nil && report.ImageNotFound != nil: - fmt.Fprintln(os.Stderr, err.Error()) - registry.SetExitCode(2) - case report != nil && report.ImageInUse != nil: - fmt.Fprintln(os.Stderr, err.Error()) - default: - return err + + report, err := registry.ImageEngine().Remove(registry.GetContext(), args, imageOpts) + if report != nil { + for _, u := range report.Untagged { + fmt.Println("Untagged: " + u) } + for _, d := range report.Deleted { + fmt.Println("Deleted: " + d) + } + registry.SetExitCode(report.ExitCode) } - for _, u := range report.Untagged { - fmt.Println("Untagged: " + u) - } - for _, d := range report.Deleted { - fmt.Println("Deleted: " + d) - } - return nil + return err } diff --git a/cmd/podman/images/tree.go b/cmd/podman/images/tree.go new file mode 100644 index 000000000..5e82e9dea --- /dev/null +++ b/cmd/podman/images/tree.go @@ -0,0 +1,40 @@ +package images + +import ( + "fmt" + + "github.com/containers/libpod/cmd/podman/registry" + "github.com/containers/libpod/pkg/domain/entities" + "github.com/spf13/cobra" +) + +var ( + treeDescription = "Prints layer hierarchy of an image in a tree format" + treeCmd = &cobra.Command{ + Use: "tree [flags] IMAGE", + Args: cobra.ExactArgs(1), + Short: treeDescription, + Long: treeDescription, + RunE: tree, + Example: "podman image tree alpine:latest", + } + treeOpts entities.ImageTreeOptions +) + +func init() { + registry.Commands = append(registry.Commands, registry.CliCommand{ + Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, + Command: treeCmd, + Parent: imageCmd, + }) + treeCmd.Flags().BoolVar(&treeOpts.WhatRequires, "whatrequires", false, "Show all child images and layers of the specified image") +} + +func tree(_ *cobra.Command, args []string) error { + results, err := registry.ImageEngine().Tree(registry.Context(), args[0], treeOpts) + if err != nil { + return err + } + fmt.Println(results.Tree) + return nil +} diff --git a/cmd/podman/inspect.go b/cmd/podman/inspect.go index e67bc326b..93bf58bdd 100644 --- a/cmd/podman/inspect.go +++ b/cmd/podman/inspect.go @@ -1,10 +1,8 @@ package main import ( - "context" "fmt" - "github.com/containers/image/v5/docker/reference" "github.com/containers/libpod/cmd/podman/common" "github.com/containers/libpod/cmd/podman/containers" "github.com/containers/libpod/cmd/podman/images" @@ -21,11 +19,12 @@ var ( // Command: podman _inspect_ Object_ID inspectCmd = &cobra.Command{ Use: "inspect [flags] {CONTAINER_ID | IMAGE_ID}", - Args: cobra.ExactArgs(1), Short: "Display the configuration of object denoted by ID", Long: "Displays the low-level information on an object identified by name or ID", TraverseChildren: true, RunE: inspect, + Example: `podman inspect alpine + podman inspect --format "imageId: {{.Id}} size: {{.Size}}" alpine`, } ) @@ -35,21 +34,25 @@ func init() { Command: inspectCmd, }) inspectOpts = common.AddInspectFlagSet(inspectCmd) + flags := inspectCmd.Flags() + flags.StringVarP(&inspectOpts.Type, "type", "t", "", "Return JSON for specified type, (image or container) (default \"all\")") + if !registry.IsRemote() { + flags.BoolVarP(&inspectOpts.Latest, "latest", "l", false, "Act on the latest container podman is aware of (containers only)") + } } func inspect(cmd *cobra.Command, args []string) error { - // First check if the input is even valid for an image - if _, err := reference.Parse(args[0]); err == nil { - if found, err := registry.ImageEngine().Exists(context.Background(), args[0]); err != nil { - return err - } else if found.Value { - return images.Inspect(cmd, args, inspectOpts) + switch inspectOpts.Type { + case "image": + return images.Inspect(cmd, args, inspectOpts) + case "container": + return containers.Inspect(cmd, args, inspectOpts) + case "": + if err := images.Inspect(cmd, args, inspectOpts); err == nil { + return nil } - } - if found, err := registry.ContainerEngine().ContainerExists(context.Background(), args[0]); err != nil { - return err - } else if found.Value { return containers.Inspect(cmd, args, inspectOpts) + default: + return fmt.Errorf("invalid type %q is must be 'container' or 'image'", inspectOpts.Type) } - return fmt.Errorf("%s not found on system", args[0]) } diff --git a/cmd/podman/system/service.go b/cmd/podman/system/service.go index 6522a45f8..f4b91dd78 100644 --- a/cmd/podman/system/service.go +++ b/cmd/podman/system/service.go @@ -2,8 +2,10 @@ package system import ( "fmt" + "net/url" "os" "path/filepath" + "syscall" "time" "github.com/containers/libpod/cmd/podman/registry" @@ -59,6 +61,23 @@ func service(cmd *cobra.Command, args []string) error { } logrus.Infof("using API endpoint: '%s'", apiURI) + // Clean up any old existing unix domain socket + if len(apiURI) > 0 { + uri, err := url.Parse(apiURI) + if err != nil { + return err + } + + // socket activation uses a unix:// socket in the shipped unit files but apiURI is coded as "" at this layer. + if "unix" == uri.Scheme && !registry.IsRemote() { + if err := syscall.Unlink(uri.Path); err != nil && !os.IsNotExist(err) { + return err + } + mask := syscall.Umask(0177) + defer syscall.Umask(mask) + } + } + opts := entities.ServiceOptions{ URI: apiURI, Timeout: time.Duration(srvArgs.Timeout) * time.Second, @@ -71,7 +90,8 @@ func service(cmd *cobra.Command, args []string) error { logrus.Warn("This function is EXPERIMENTAL") fmt.Fprintf(os.Stderr, "This function is EXPERIMENTAL.\n") - return registry.ContainerEngine().RestService(registry.GetContext(), opts) + + return restService(opts, cmd.Flags(), registry.PodmanConfig()) } func resolveApiURI(_url []string) (string, error) { diff --git a/cmd/podman/system/service_abi.go b/cmd/podman/system/service_abi.go new file mode 100644 index 000000000..3da6ccfc7 --- /dev/null +++ b/cmd/podman/system/service_abi.go @@ -0,0 +1,57 @@ +// +build ABISupport + +package system + +import ( + "context" + "net" + "strings" + + api "github.com/containers/libpod/pkg/api/server" + "github.com/containers/libpod/pkg/domain/entities" + "github.com/containers/libpod/pkg/domain/infra" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/spf13/pflag" +) + +func restService(opts entities.ServiceOptions, flags *pflag.FlagSet, cfg *entities.PodmanConfig) error { + var ( + listener *net.Listener + err error + ) + + if opts.URI != "" { + fields := strings.Split(opts.URI, ":") + if len(fields) == 1 { + return errors.Errorf("%s is an invalid socket destination", opts.URI) + } + address := strings.Join(fields[1:], ":") + l, err := net.Listen(fields[0], address) + if err != nil { + return errors.Wrapf(err, "unable to create socket %s", opts.URI) + } + listener = &l + } + + rt, err := infra.GetRuntime(context.Background(), flags, cfg) + if err != nil { + return err + } + + server, err := api.NewServerWithSettings(rt, opts.Timeout, listener) + if err != nil { + return err + } + defer func() { + if err := server.Shutdown(); err != nil { + logrus.Warnf("Error when stopping API service: %s", err) + } + }() + + err = server.Serve() + if listener != nil { + _ = (*listener).Close() + } + return err +} diff --git a/cmd/podman/system/service_unsupported.go b/cmd/podman/system/service_unsupported.go new file mode 100644 index 000000000..95f8189f6 --- /dev/null +++ b/cmd/podman/system/service_unsupported.go @@ -0,0 +1,14 @@ +// +build !ABISupport + +package system + +import ( + "errors" + + "github.com/containers/libpod/pkg/domain/entities" + "github.com/spf13/pflag" +) + +func restService(opts entities.ServiceOptions, flags *pflag.FlagSet, cfg *entities.PodmanConfig) error { + return errors.New("not supported") +} diff --git a/hack/golangci-lint.sh b/hack/golangci-lint.sh index 385b21f39..f4e60d8f5 100755 --- a/hack/golangci-lint.sh +++ b/hack/golangci-lint.sh @@ -3,13 +3,22 @@ # Need to run linter twice to cover all the build tags code paths declare -A BUILD_TAGS +# TODO: add systemd tag BUILD_TAGS[default]="apparmor,seccomp,selinux" BUILD_TAGS[abi]="${BUILD_TAGS[default]},ABISupport,varlink,!remoteclient" -BUILD_TAGS[tunnel]="${BUILD_TAGS[default]},!ABISupport,!varlink,remoteclient" +BUILD_TAGS[tunnel]="${BUILD_TAGS[default]},!ABISupport,varlink,remoteclient" + +declare -A SKIP_DIRS +SKIP_DIRS[abi]="" +# TODO: add "ABISupport" build tag to pkg/api +SKIP_DIRS[tunnel]="pkg/api" [[ $1 == run ]] && shift for i in tunnel abi; do - echo Build Tags: ${BUILD_TAGS[$i]} - golangci-lint run --build-tags=${BUILD_TAGS[$i]} "$@" + echo "" + echo Running golangci-lint for "$i" + echo Build Tags "$i": ${BUILD_TAGS[$i]} + echo Skipped directories "$i": ${SKIP_DIRS[$i]} + golangci-lint run --build-tags=${BUILD_TAGS[$i]} --skip-dirs=${SKIP_DIRS[$i]} "$@" done diff --git a/libpod/image/image.go b/libpod/image/image.go index 7198a42a3..bbf803056 100644 --- a/libpod/image/image.go +++ b/libpod/image/image.go @@ -867,22 +867,77 @@ func (i *Image) Intermediate(ctx context.Context) (bool, error) { return false, nil } +// User returns the image's user +func (i *Image) User(ctx context.Context) (string, error) { + imgInspect, err := i.inspect(ctx, false) + if err != nil { + return "", err + } + return imgInspect.Config.User, nil +} + +// StopSignal returns the image's StopSignal +func (i *Image) StopSignal(ctx context.Context) (string, error) { + imgInspect, err := i.inspect(ctx, false) + if err != nil { + return "", err + } + return imgInspect.Config.StopSignal, nil +} + +// WorkingDir returns the image's WorkingDir +func (i *Image) WorkingDir(ctx context.Context) (string, error) { + imgInspect, err := i.inspect(ctx, false) + if err != nil { + return "", err + } + return imgInspect.Config.WorkingDir, nil +} + +// Cmd returns the image's cmd +func (i *Image) Cmd(ctx context.Context) ([]string, error) { + imgInspect, err := i.inspect(ctx, false) + if err != nil { + return nil, err + } + return imgInspect.Config.Cmd, nil +} + +// Entrypoint returns the image's entrypoint +func (i *Image) Entrypoint(ctx context.Context) ([]string, error) { + imgInspect, err := i.inspect(ctx, false) + if err != nil { + return nil, err + } + return imgInspect.Config.Entrypoint, nil +} + +// Env returns the image's env +func (i *Image) Env(ctx context.Context) ([]string, error) { + imgInspect, err := i.imageInspectInfo(ctx) + if err != nil { + return nil, err + } + return imgInspect.Env, nil +} + // Labels returns the image's labels func (i *Image) Labels(ctx context.Context) (map[string]string, error) { imgInspect, err := i.imageInspectInfo(ctx) if err != nil { - return nil, nil + return nil, err } return imgInspect.Labels, nil } // GetLabel Returns a case-insensitive match of a given label func (i *Image) GetLabel(ctx context.Context, label string) (string, error) { - imageLabels, err := i.Labels(ctx) + labels, err := i.Labels(ctx) if err != nil { return "", err } - for k, v := range imageLabels { + + for k, v := range labels { if strings.ToLower(k) == strings.ToLower(label) { return v, nil } diff --git a/pkg/api/handlers/compat/events.go b/pkg/api/handlers/compat/events.go index 8ef32716d..7ebfb0d1e 100644 --- a/pkg/api/handlers/compat/events.go +++ b/pkg/api/handlers/compat/events.go @@ -6,8 +6,8 @@ import ( "github.com/containers/libpod/libpod" "github.com/containers/libpod/libpod/events" - "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/domain/entities" "github.com/gorilla/schema" jsoniter "github.com/json-iterator/go" "github.com/pkg/errors" @@ -70,7 +70,7 @@ func GetEvents(w http.ResponseWriter, r *http.Request) { coder.SetEscapeHTML(true) for event := range eventChannel { - e := handlers.EventToApiEvent(event) + e := entities.ConvertToEntitiesEvent(*event) if err := coder.Encode(e); err != nil { logrus.Errorf("unable to write json: %q", err) } diff --git a/pkg/api/handlers/libpod/images.go b/pkg/api/handlers/libpod/images.go index 284b33637..46401e4f2 100644 --- a/pkg/api/handlers/libpod/images.go +++ b/pkg/api/handlers/libpod/images.go @@ -22,6 +22,7 @@ import ( "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/api/handlers/utils" "github.com/containers/libpod/pkg/domain/entities" + "github.com/containers/libpod/pkg/domain/infra/abi" "github.com/containers/libpod/pkg/util" utils2 "github.com/containers/libpod/utils" "github.com/gorilla/schema" @@ -698,3 +699,30 @@ func SearchImages(w http.ResponseWriter, r *http.Request) { utils.WriteResponse(w, http.StatusOK, reports) } + +// ImagesRemove is the endpoint for image removal. +func ImagesRemove(w http.ResponseWriter, r *http.Request) { + runtime := r.Context().Value("runtime").(*libpod.Runtime) + decoder := r.Context().Value("decoder").(*schema.Decoder) + query := struct { + All bool `schema:"all"` + Force bool `schema:"force"` + Images []string `schema:"images"` + }{ + All: false, + Force: false, + } + + if err := decoder.Decode(&query, r.URL.Query()); err != nil { + utils.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest, + errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String())) + return + } + + opts := entities.ImageRemoveOptions{All: query.All, Force: query.Force} + + imageEngine := abi.ImageEngine{Libpod: runtime} + rmReport, rmError := imageEngine.Remove(r.Context(), query.Images, opts) + report := handlers.LibpodImagesRemoveReport{ImageRemoveReport: *rmReport, Error: rmError.Error()} + utils.WriteResponse(w, http.StatusOK, report) +} diff --git a/pkg/api/handlers/swagger/swagger.go b/pkg/api/handlers/swagger/swagger.go index ba97a4755..87891d4a8 100644 --- a/pkg/api/handlers/swagger/swagger.go +++ b/pkg/api/handlers/swagger/swagger.go @@ -49,6 +49,13 @@ type swagLibpodImagesPullResponse struct { Body handlers.LibpodImagesPullReport } +// Remove response +// swagger:response DocsLibpodImagesRemoveResponse +type swagLibpodImagesRemoveResponse struct { + // in:body + Body handlers.LibpodImagesRemoveReport +} + // Delete response // swagger:response DocsImageDeleteResponse type swagImageDeleteResponse struct { diff --git a/pkg/api/handlers/types.go b/pkg/api/handlers/types.go index 4c081cf85..58a12ea6a 100644 --- a/pkg/api/handlers/types.go +++ b/pkg/api/handlers/types.go @@ -4,16 +4,13 @@ import ( "context" "encoding/json" "fmt" - "strconv" "time" "github.com/containers/image/v5/manifest" - "github.com/containers/libpod/libpod/events" libpodImage "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/domain/entities" docker "github.com/docker/docker/api/types" dockerContainer "github.com/docker/docker/api/types/container" - dockerEvents "github.com/docker/docker/api/types/events" dockerNetwork "github.com/docker/docker/api/types/network" "github.com/docker/go-connections/nat" "github.com/pkg/errors" @@ -39,6 +36,14 @@ type LibpodImagesPullReport struct { ID string `json:"id"` } +// LibpodImagesRemoveReport is the return type for image removal via the rest +// api. +type LibpodImagesRemoveReport struct { + entities.ImageRemoveReport + // Image removal requires is to return data and an error. + Error string +} + type ContainersPruneReport struct { docker.ContainersPruneReport } @@ -143,10 +148,6 @@ type PodCreateConfig struct { Share string `json:"share"` } -type Event struct { - dockerEvents.Message -} - type HistoryResponse struct { ID string `json:"Id"` Created int64 `json:"Created"` @@ -173,49 +174,6 @@ type ExecCreateResponse struct { docker.IDResponse } -func (e *Event) ToLibpodEvent() *events.Event { - exitCode, err := strconv.Atoi(e.Actor.Attributes["containerExitCode"]) - if err != nil { - return nil - } - status, err := events.StringToStatus(e.Action) - if err != nil { - return nil - } - t, err := events.StringToType(e.Type) - if err != nil { - return nil - } - lp := events.Event{ - ContainerExitCode: exitCode, - ID: e.Actor.ID, - Image: e.Actor.Attributes["image"], - Name: e.Actor.Attributes["name"], - Status: status, - Time: time.Unix(e.Time, e.TimeNano), - Type: t, - } - return &lp -} - -func EventToApiEvent(e *events.Event) *Event { - return &Event{dockerEvents.Message{ - Type: e.Type.String(), - Action: e.Status.String(), - Actor: dockerEvents.Actor{ - ID: e.ID, - Attributes: map[string]string{ - "image": e.Image, - "name": e.Name, - "containerExitCode": strconv.Itoa(e.ContainerExitCode), - }, - }, - Scope: "local", - Time: e.Time.Unix(), - TimeNano: e.Time.UnixNano(), - }} -} - func ImageToImageSummary(l *libpodImage.Image) (*entities.ImageSummary, error) { containers, err := l.Containers() if err != nil { @@ -311,7 +269,7 @@ func ImageDataToImageInspect(ctx context.Context, l *libpodImage.Image) (*ImageI // NetworkDisabled: false, // MacAddress: "", // OnBuild: nil, - // Labels: nil, + Labels: info.Labels, // StopSignal: "", // StopTimeout: nil, // Shell: nil, diff --git a/pkg/api/server/register_images.go b/pkg/api/server/register_images.go index 6cc6f0cfa..f59dca6f5 100644 --- a/pkg/api/server/register_images.go +++ b/pkg/api/server/register_images.go @@ -822,6 +822,38 @@ func (s *APIServer) registerImagesHandlers(r *mux.Router) error { // 500: // $ref: '#/responses/InternalError' r.Handle(VersionedPath("/libpod/images/import"), s.APIHandler(libpod.ImagesImport)).Methods(http.MethodPost) + // swagger:operation GET /libpod/images/remove libpod libpodImagesRemove + // --- + // tags: + // - images + // summary: Remove one or more images from the storage. + // description: Remove one or more images from the storage. + // parameters: + // - in: query + // name: images + // description: Images IDs or names to remove. + // type: array + // items: + // type: string + // - in: query + // name: all + // description: Remove all images. + // type: boolean + // default: true + // - in: query + // name: force + // description: Force image removal (including containers using the images). + // type: boolean + // produces: + // - application/json + // responses: + // 200: + // $ref: "#/responses/DocsLibpodImagesRemoveResponse" + // 400: + // $ref: "#/responses/BadParamError" + // 500: + // $ref: '#/responses/InternalError' + r.Handle(VersionedPath("/libpod/images/remove"), s.APIHandler(libpod.ImagesRemove)).Methods(http.MethodGet) // swagger:operation POST /libpod/images/pull libpod libpodImagesPull // --- // tags: diff --git a/pkg/api/types/types.go b/pkg/api/types/types.go new file mode 100644 index 000000000..1b91364e3 --- /dev/null +++ b/pkg/api/types/types.go @@ -0,0 +1,9 @@ +package types + +const ( + // DefaultAPIVersion is the version of the API the server defaults to. + DefaultAPIVersion = "1.40" // See https://docs.docker.com/engine/api/v1.40/ + + // DefaultAPIVersion is the minimal required version of the API. + MinimalAPIVersion = "1.24" +) diff --git a/pkg/bindings/connection.go b/pkg/bindings/connection.go index 29b6f04ec..da3755fc8 100644 --- a/pkg/bindings/connection.go +++ b/pkg/bindings/connection.go @@ -15,7 +15,7 @@ import ( "strings" "time" - "github.com/containers/libpod/pkg/api/handlers" + "github.com/containers/libpod/pkg/api/types" jsoniter "github.com/json-iterator/go" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -27,7 +27,7 @@ var ( basePath = &url.URL{ Scheme: "http", Host: "d", - Path: "/v" + handlers.MinimalApiVersion + "/libpod", + Path: "/v" + types.MinimalAPIVersion + "/libpod", } ) diff --git a/pkg/bindings/images/images.go b/pkg/bindings/images/images.go index 3550c3968..06f01c7a0 100644 --- a/pkg/bindings/images/images.go +++ b/pkg/bindings/images/images.go @@ -74,7 +74,7 @@ func GetImage(ctx context.Context, nameOrID string, size *bool) (*entities.Image return &inspectedData, response.Process(&inspectedData) } -func ImageTree(ctx context.Context, nameOrId string) error { +func Tree(ctx context.Context, nameOrId string) error { return bindings.ErrNotImplemented } @@ -109,23 +109,34 @@ func Load(ctx context.Context, r io.Reader, name *string) (*entities.ImageLoadRe return &report, response.Process(&report) } -// Remove deletes an image from local storage. The optional force parameter will forcibly remove -// the image by removing all all containers, including those that are Running, first. -func Remove(ctx context.Context, nameOrID string, force *bool) ([]map[string]string, error) { - var deletes []map[string]string +// Remove deletes an image from local storage. The optional force parameter +// will forcibly remove the image by removing all all containers, including +// those that are Running, first. +func Remove(ctx context.Context, images []string, opts entities.ImageRemoveOptions) (*entities.ImageRemoveReport, error) { + var report handlers.LibpodImagesRemoveReport conn, err := bindings.GetClient(ctx) if err != nil { return nil, err } params := url.Values{} - if force != nil { - params.Set("force", strconv.FormatBool(*force)) + params.Set("all", strconv.FormatBool(opts.All)) + params.Set("force", strconv.FormatBool(opts.Force)) + for _, i := range images { + params.Add("images", i) } - response, err := conn.DoRequest(nil, http.MethodDelete, "/images/%s", params, nameOrID) + + response, err := conn.DoRequest(nil, http.MethodGet, "/images/remove", params) if err != nil { return nil, err } - return deletes, response.Process(&deletes) + if err := response.Process(&report); err != nil { + return nil, err + } + var rmError error + if report.Error != "" { + rmError = errors.New(report.Error) + } + return &report.ImageRemoveReport, rmError } // Export saves an image from local storage as a tarball or image archive. The optional format diff --git a/pkg/bindings/system/system.go b/pkg/bindings/system/system.go index fce8bbb8e..e2f264139 100644 --- a/pkg/bindings/system/system.go +++ b/pkg/bindings/system/system.go @@ -7,8 +7,8 @@ import ( "net/http" "net/url" - "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/bindings" + "github.com/containers/libpod/pkg/domain/entities" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -16,7 +16,7 @@ import ( // Events allows you to monitor libdpod related events like container creation and // removal. The events are then passed to the eventChan provided. The optional cancelChan // can be used to cancel the read of events and close down the HTTP connection. -func Events(ctx context.Context, eventChan chan (handlers.Event), cancelChan chan bool, since, until *string, filters map[string][]string) error { +func Events(ctx context.Context, eventChan chan (entities.Event), cancelChan chan bool, since, until *string, filters map[string][]string) error { conn, err := bindings.GetClient(ctx) if err != nil { return err @@ -48,7 +48,7 @@ func Events(ctx context.Context, eventChan chan (handlers.Event), cancelChan cha } dec := json.NewDecoder(response.Body) for { - e := handlers.Event{} + e := entities.Event{} if err := dec.Decode(&e); err != nil { if err == io.EOF { break diff --git a/pkg/domain/entities/engine_container.go b/pkg/domain/entities/engine_container.go index b730f8743..506d1c317 100644 --- a/pkg/domain/entities/engine_container.go +++ b/pkg/domain/entities/engine_container.go @@ -54,7 +54,6 @@ type ContainerEngine interface { PodStop(ctx context.Context, namesOrIds []string, options PodStopOptions) ([]*PodStopReport, error) PodTop(ctx context.Context, options PodTopOptions) (*StringSliceReport, error) PodUnpause(ctx context.Context, namesOrIds []string, options PodunpauseOptions) ([]*PodUnpauseReport, error) - RestService(ctx context.Context, opts ServiceOptions) error SetupRootless(ctx context.Context, cmd *cobra.Command) error VarlinkService(ctx context.Context, opts ServiceOptions) error VolumeCreate(ctx context.Context, opts VolumeCreateOptions) (*IdOrNameResponse, error) diff --git a/pkg/domain/entities/engine_image.go b/pkg/domain/entities/engine_image.go index 052e7bee5..84680ab1b 100644 --- a/pkg/domain/entities/engine_image.go +++ b/pkg/domain/entities/engine_image.go @@ -9,7 +9,6 @@ import ( type ImageEngine interface { Build(ctx context.Context, containerFiles []string, opts BuildOptions) (*BuildReport, error) Config(ctx context.Context) (*config.Config, error) - Delete(ctx context.Context, nameOrId []string, opts ImageDeleteOptions) (*ImageDeleteReport, error) Diff(ctx context.Context, nameOrId string, options DiffOptions) (*DiffReport, error) Exists(ctx context.Context, nameOrId string) (*BoolReport, error) History(ctx context.Context, nameOrId string, opts ImageHistoryOptions) (*ImageHistoryReport, error) @@ -20,8 +19,10 @@ type ImageEngine interface { Prune(ctx context.Context, opts ImagePruneOptions) (*ImagePruneReport, error) Pull(ctx context.Context, rawImage string, opts ImagePullOptions) (*ImagePullReport, error) Push(ctx context.Context, source string, destination string, opts ImagePushOptions) error + Remove(ctx context.Context, images []string, opts ImageRemoveOptions) (*ImageRemoveReport, error) Save(ctx context.Context, nameOrId string, tags []string, options ImageSaveOptions) error Search(ctx context.Context, term string, opts ImageSearchOptions) ([]ImageSearchReport, error) Tag(ctx context.Context, nameOrId string, tags []string, options ImageTagOptions) error + Tree(ctx context.Context, nameOrId string, options ImageTreeOptions) (*ImageTreeReport, error) Untag(ctx context.Context, nameOrId string, tags []string, options ImageUntagOptions) error } diff --git a/pkg/domain/entities/events.go b/pkg/domain/entities/events.go new file mode 100644 index 000000000..8861be158 --- /dev/null +++ b/pkg/domain/entities/events.go @@ -0,0 +1,61 @@ +package entities + +import ( + "strconv" + "time" + + libpodEvents "github.com/containers/libpod/libpod/events" + dockerEvents "github.com/docker/docker/api/types/events" +) + +// Event combines various event-related data such as time, event type, status +// and more. +type Event struct { + // TODO: it would be nice to have full control over the types at some + // point and fork such Docker types. + dockerEvents.Message +} + +// ConvertToLibpodEvent converts an entities event to a libpod one. +func ConvertToLibpodEvent(e Event) *libpodEvents.Event { + exitCode, err := strconv.Atoi(e.Actor.Attributes["containerExitCode"]) + if err != nil { + return nil + } + status, err := libpodEvents.StringToStatus(e.Action) + if err != nil { + return nil + } + t, err := libpodEvents.StringToType(e.Type) + if err != nil { + return nil + } + return &libpodEvents.Event{ + ContainerExitCode: exitCode, + ID: e.Actor.ID, + Image: e.Actor.Attributes["image"], + Name: e.Actor.Attributes["name"], + Status: status, + Time: time.Unix(e.Time, e.TimeNano), + Type: t, + } +} + +// ConvertToEntitiesEvent converts a libpod event to an entities one. +func ConvertToEntitiesEvent(e libpodEvents.Event) *Event { + return &Event{dockerEvents.Message{ + Type: e.Type.String(), + Action: e.Status.String(), + Actor: dockerEvents.Actor{ + ID: e.ID, + Attributes: map[string]string{ + "image": e.Image, + "name": e.Name, + "containerExitCode": strconv.Itoa(e.ContainerExitCode), + }, + }, + Scope: "local", + Time: e.Time.Unix(), + TimeNano: e.Time.UnixNano(), + }} +} diff --git a/pkg/domain/entities/images.go b/pkg/domain/entities/images.go index 3a6d159e4..773cd90b4 100644 --- a/pkg/domain/entities/images.go +++ b/pkg/domain/entities/images.go @@ -82,19 +82,24 @@ func (i *ImageSummary) IsDangling() bool { return i.Dangling } -type ImageDeleteOptions struct { - All bool +// ImageRemoveOptions can be used to alter image removal. +type ImageRemoveOptions struct { + // All will remove all images. + All bool + // Foce will force image removal including containers using the images. Force bool } -// ImageDeleteResponse is the response for removing one or more image(s) from storage -// and containers what was untagged vs actually removed -type ImageDeleteReport struct { - Untagged []string `json:",omitempty"` - Deleted []string `json:",omitempty"` - Errors []error - ImageNotFound error - ImageInUse error +// ImageRemoveResponse is the response for removing one or more image(s) from storage +// and containers what was untagged vs actually removed. +type ImageRemoveReport struct { + // Deleted images. + Deleted []string `json:",omitempty"` + // Untagged images. Can be longer than Deleted. + Untagged []string `json:",omitempty"` + // ExitCode describes the exit codes as described in the `podman rmi` + // man page. + ExitCode int } type ImageHistoryOptions struct{} @@ -273,3 +278,13 @@ type ImageSaveOptions struct { Output string Quiet bool } + +// ImageTreeOptions provides options for ImageEngine.Tree() +type ImageTreeOptions struct { + WhatRequires bool // Show all child images and layers of the specified image +} + +// ImageTreeReport provides results from ImageEngine.Tree() +type ImageTreeReport struct { + Tree string // TODO: Refactor move presentation work out of server +} diff --git a/pkg/domain/entities/pods.go b/pkg/domain/entities/pods.go index 04673ef18..aa1445a6a 100644 --- a/pkg/domain/entities/pods.go +++ b/pkg/domain/entities/pods.go @@ -134,7 +134,7 @@ func (p PodCreateOptions) ToPodSpecGen(s *specgen.PodSpecGenerator) { s.StaticMAC = p.Net.StaticMAC s.PortMappings = p.Net.PublishPorts s.CNINetworks = p.Net.CNINetworks - if p.Net.DNSHost { + if p.Net.UseImageResolvConf { s.NoManageResolvConf = true } s.DNSServer = p.Net.DNSServers diff --git a/pkg/domain/entities/types.go b/pkg/domain/entities/types.go index b89aa869a..d742cc53d 100644 --- a/pkg/domain/entities/types.go +++ b/pkg/domain/entities/types.go @@ -32,17 +32,17 @@ type VolumeDeleteReport struct{ Report } // NetOptions reflect the shared network options between // pods and containers type NetOptions struct { - AddHosts []string - CNINetworks []string - DNSHost bool - DNSOptions []string - DNSSearch []string - DNSServers []net.IP - Network specgen.Namespace - NoHosts bool - PublishPorts []ocicni.PortMapping - StaticIP *net.IP - StaticMAC *net.HardwareAddr + AddHosts []string + CNINetworks []string + UseImageResolvConf bool + DNSOptions []string + DNSSearch []string + DNSServers []net.IP + Network specgen.Namespace + NoHosts bool + PublishPorts []ocicni.PortMapping + StaticIP *net.IP + StaticMAC *net.HardwareAddr } // All CLI inspect commands and inspect sub-commands use the same options @@ -50,6 +50,7 @@ type InspectOptions struct { Format string `json:",omitempty"` Latest bool `json:",omitempty"` Size bool `json:",omitempty"` + Type string `json:",omitempty"` } // All API and CLI diff commands and diff sub-commands use the same options diff --git a/pkg/domain/infra/abi/containers.go b/pkg/domain/infra/abi/containers.go index 50003dbe2..e71ceb536 100644 --- a/pkg/domain/infra/abi/containers.go +++ b/pkg/domain/infra/abi/containers.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/events.go b/pkg/domain/infra/abi/events.go index 9540a5b96..20773cdce 100644 --- a/pkg/domain/infra/abi/events.go +++ b/pkg/domain/infra/abi/events.go @@ -1,5 +1,3 @@ -//+build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/healthcheck.go b/pkg/domain/infra/abi/healthcheck.go index 699483243..351bf4f7e 100644 --- a/pkg/domain/infra/abi/healthcheck.go +++ b/pkg/domain/infra/abi/healthcheck.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/images.go b/pkg/domain/infra/abi/images.go index 0f710ad28..32f7d75e5 100644 --- a/pkg/domain/infra/abi/images.go +++ b/pkg/domain/infra/abi/images.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( @@ -23,6 +21,7 @@ import ( domainUtils "github.com/containers/libpod/pkg/domain/utils" "github.com/containers/libpod/pkg/util" "github.com/containers/storage" + "github.com/hashicorp/go-multierror" imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -36,76 +35,6 @@ func (ir *ImageEngine) Exists(_ context.Context, nameOrId string) (*entities.Boo return &entities.BoolReport{Value: err == nil}, nil } -func (ir *ImageEngine) Delete(ctx context.Context, nameOrId []string, opts entities.ImageDeleteOptions) (*entities.ImageDeleteReport, error) { - report := entities.ImageDeleteReport{} - - if opts.All { - var previousTargets []*libpodImage.Image - repeatRun: - targets, err := ir.Libpod.ImageRuntime().GetRWImages() - if err != nil { - return &report, errors.Wrapf(err, "unable to query local images") - } - if len(targets) == 0 { - return &report, nil - } - if len(targets) > 0 && len(targets) == len(previousTargets) { - return &report, errors.New("unable to delete all images; re-run the rmi command again.") - } - previousTargets = targets - - for _, img := range targets { - isParent, err := img.IsParent(ctx) - if err != nil { - return &report, err - } - if isParent { - continue - } - err = ir.deleteImage(ctx, img, opts, report) - report.Errors = append(report.Errors, err) - } - if len(previousTargets) != 1 { - goto repeatRun - } - return &report, nil - } - - for _, id := range nameOrId { - image, err := ir.Libpod.ImageRuntime().NewFromLocal(id) - if err != nil { - return nil, err - } - - err = ir.deleteImage(ctx, image, opts, report) - if err != nil { - return &report, err - } - } - return &report, nil -} - -func (ir *ImageEngine) deleteImage(ctx context.Context, img *libpodImage.Image, opts entities.ImageDeleteOptions, report entities.ImageDeleteReport) error { - results, err := ir.Libpod.RemoveImage(ctx, img, opts.Force) - switch errors.Cause(err) { - case nil: - break - case storage.ErrImageUsedByContainer: - report.ImageInUse = errors.New( - fmt.Sprintf("A container associated with containers/storage, i.e. via Buildah, CRI-O, etc., may be associated with this image: %-12.12s\n", img.ID())) - return nil - case libpodImage.ErrNoSuchImage: - report.ImageNotFound = err - return nil - default: - return err - } - - report.Deleted = append(report.Deleted, results.Deleted) - report.Untagged = append(report.Untagged, results.Untagged...) - return nil -} - func (ir *ImageEngine) Prune(ctx context.Context, opts entities.ImagePruneOptions) (*entities.ImagePruneReport, error) { results, err := ir.Libpod.ImageRuntime().PruneImages(ctx, opts.All, opts.Filter) if err != nil { @@ -476,3 +405,147 @@ func (ir *ImageEngine) Build(ctx context.Context, containerFiles []string, opts } return &entities.BuildReport{ID: id}, nil } + +func (ir *ImageEngine) Tree(ctx context.Context, nameOrId string, opts entities.ImageTreeOptions) (*entities.ImageTreeReport, error) { + img, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) + if err != nil { + return nil, err + } + results, err := img.GenerateTree(opts.WhatRequires) + if err != nil { + return nil, err + } + return &entities.ImageTreeReport{Tree: results}, nil +} + +// Remove removes one or more images from local storage. +func (ir *ImageEngine) Remove(ctx context.Context, images []string, opts entities.ImageRemoveOptions) (report *entities.ImageRemoveReport, finalError error) { + var ( + // noSuchImageErrors indicates that at least one image was not found. + noSuchImageErrors bool + // inUseErrors indicates that at least one image is being used by a + // container. + inUseErrors bool + // otherErrors indicates that at least one error other than the two + // above occured. + otherErrors bool + // deleteError is a multierror to conveniently collect errors during + // removal. We really want to delete as many images as possible and not + // error out immediately. + deleteError *multierror.Error + ) + + report = &entities.ImageRemoveReport{} + + // Set the removalCode and the error after all work is done. + defer func() { + switch { + // 2 + case inUseErrors: + // One of the specified images has child images or is + // being used by a container. + report.ExitCode = 2 + // 1 + case noSuchImageErrors && !(otherErrors || inUseErrors): + // One of the specified images did not exist, and no other + // failures. + report.ExitCode = 1 + // 0 + default: + // Nothing to do. + } + if deleteError != nil { + // go-multierror has a trailing new line which we need to remove to normalize the string. + finalError = deleteError.ErrorOrNil() + finalError = errors.New(strings.TrimSpace(finalError.Error())) + } + }() + + // deleteImage is an anonymous function to conveniently delete an image + // withouth having to pass all local data around. + deleteImage := func(img *image.Image) error { + results, err := ir.Libpod.RemoveImage(ctx, img, opts.Force) + switch errors.Cause(err) { + case nil: + break + case storage.ErrImageUsedByContainer: + inUseErrors = true // Important for exit codes in Podman. + return errors.New( + fmt.Sprintf("A container associated with containers/storage, i.e. via Buildah, CRI-O, etc., may be associated with this image: %-12.12s\n", img.ID())) + default: + otherErrors = true // Important for exit codes in Podman. + return err + } + + report.Deleted = append(report.Deleted, results.Deleted) + report.Untagged = append(report.Untagged, results.Untagged...) + return nil + } + + // Delete all images from the local storage. + if opts.All { + previousImages := 0 + // Remove all images one-by-one. + for { + storageImages, err := ir.Libpod.ImageRuntime().GetRWImages() + if err != nil { + deleteError = multierror.Append(deleteError, + errors.Wrapf(err, "unable to query local images")) + otherErrors = true // Important for exit codes in Podman. + return + } + // No images (left) to remove, so we're done. + if len(storageImages) == 0 { + return + } + // Prevent infinity loops by making a delete-progress check. + if previousImages == len(storageImages) { + otherErrors = true // Important for exit codes in Podman. + deleteError = multierror.Append(deleteError, + errors.New("unable to delete all images, check errors and re-run image removal if needed")) + break + } + previousImages = len(storageImages) + // Delete all "leaves" (i.e., images without child images). + for _, img := range storageImages { + isParent, err := img.IsParent(ctx) + if err != nil { + otherErrors = true // Important for exit codes in Podman. + deleteError = multierror.Append(deleteError, err) + } + // Skip parent images. + if isParent { + continue + } + if err := deleteImage(img); err != nil { + deleteError = multierror.Append(deleteError, err) + } + } + } + + return + } + + // Delete only the specified images. + for _, id := range images { + img, err := ir.Libpod.ImageRuntime().NewFromLocal(id) + switch errors.Cause(err) { + case nil: + break + case image.ErrNoSuchImage: + noSuchImageErrors = true // Important for exit codes in Podman. + fallthrough + default: + deleteError = multierror.Append(deleteError, err) + continue + } + + err = deleteImage(img) + if err != nil { + otherErrors = true // Important for exit codes in Podman. + deleteError = multierror.Append(deleteError, err) + } + } + + return +} diff --git a/pkg/domain/infra/abi/images_list.go b/pkg/domain/infra/abi/images_list.go index 68b961cb6..9add915ea 100644 --- a/pkg/domain/infra/abi/images_list.go +++ b/pkg/domain/infra/abi/images_list.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/pods.go b/pkg/domain/infra/abi/pods.go index 6b6e13e24..c4ae9efbf 100644 --- a/pkg/domain/infra/abi/pods.go +++ b/pkg/domain/infra/abi/pods.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/runtime.go b/pkg/domain/infra/abi/runtime.go index b53fb6d3a..7394cadfc 100644 --- a/pkg/domain/infra/abi/runtime.go +++ b/pkg/domain/infra/abi/runtime.go @@ -1,5 +1,3 @@ -// +build ABISupport - package abi import ( diff --git a/pkg/domain/infra/abi/system.go b/pkg/domain/infra/abi/system.go index 078f5404d..e5c109ee6 100644 --- a/pkg/domain/infra/abi/system.go +++ b/pkg/domain/infra/abi/system.go @@ -1,20 +1,15 @@ -// +build ABISupport - package abi import ( "context" "fmt" "io/ioutil" - "net" "os" "strconv" - "strings" "syscall" "github.com/containers/common/pkg/config" "github.com/containers/libpod/libpod/define" - api "github.com/containers/libpod/pkg/api/server" "github.com/containers/libpod/pkg/cgroups" "github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/rootless" @@ -33,42 +28,6 @@ func (ic *ContainerEngine) Info(ctx context.Context) (*define.Info, error) { return ic.Libpod.Info() } -func (ic *ContainerEngine) RestService(_ context.Context, opts entities.ServiceOptions) error { - var ( - listener *net.Listener - err error - ) - - if opts.URI != "" { - fields := strings.Split(opts.URI, ":") - if len(fields) == 1 { - return errors.Errorf("%s is an invalid socket destination", opts.URI) - } - address := strings.Join(fields[1:], ":") - l, err := net.Listen(fields[0], address) - if err != nil { - return errors.Wrapf(err, "unable to create socket %s", opts.URI) - } - listener = &l - } - - server, err := api.NewServerWithSettings(ic.Libpod, opts.Timeout, listener) - if err != nil { - return err - } - defer func() { - if err := server.Shutdown(); err != nil { - logrus.Warnf("Error when stopping API service: %s", err) - } - }() - - err = server.Serve() - if listener != nil { - _ = (*listener).Close() - } - return err -} - func (ic *ContainerEngine) VarlinkService(_ context.Context, opts entities.ServiceOptions) error { var varlinkInterfaces = []*iopodman.VarlinkInterface{ iopodmanAPI.New(opts.Command, ic.Libpod), diff --git a/pkg/domain/infra/abi/terminal/sigproxy_linux.go b/pkg/domain/infra/abi/terminal/sigproxy_linux.go index d7f5853d8..b422e549e 100644 --- a/pkg/domain/infra/abi/terminal/sigproxy_linux.go +++ b/pkg/domain/infra/abi/terminal/sigproxy_linux.go @@ -1,5 +1,3 @@ -// +build ABISupport - package terminal import ( diff --git a/pkg/domain/infra/abi/terminal/terminal.go b/pkg/domain/infra/abi/terminal/terminal.go index f187bdd6b..0fc3af511 100644 --- a/pkg/domain/infra/abi/terminal/terminal.go +++ b/pkg/domain/infra/abi/terminal/terminal.go @@ -1,5 +1,3 @@ -// +build ABISupport - package terminal import ( diff --git a/pkg/domain/infra/abi/terminal/terminal_linux.go b/pkg/domain/infra/abi/terminal/terminal_linux.go index 664205df1..15701342f 100644 --- a/pkg/domain/infra/abi/terminal/terminal_linux.go +++ b/pkg/domain/infra/abi/terminal/terminal_linux.go @@ -1,5 +1,3 @@ -// +build ABISupport - package terminal import ( diff --git a/pkg/domain/infra/tunnel/events.go b/pkg/domain/infra/tunnel/events.go index 46d88341a..93da3aeb4 100644 --- a/pkg/domain/infra/tunnel/events.go +++ b/pkg/domain/infra/tunnel/events.go @@ -4,7 +4,6 @@ import ( "context" "strings" - "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/bindings/system" "github.com/containers/libpod/pkg/domain/entities" "github.com/pkg/errors" @@ -21,10 +20,10 @@ func (ic *ContainerEngine) Events(ctx context.Context, opts entities.EventsOptio filters[split[0]] = append(filters[split[0]], strings.Join(split[1:], "=")) } } - binChan := make(chan handlers.Event) + binChan := make(chan entities.Event) go func() { for e := range binChan { - opts.EventChan <- e.ToLibpodEvent() + opts.EventChan <- entities.ConvertToLibpodEvent(e) } }() return system.Events(ic.ClientCxt, binChan, nil, &opts.Since, &opts.Until, filters) diff --git a/pkg/domain/infra/tunnel/images.go b/pkg/domain/infra/tunnel/images.go index 6ea2bd9f2..822842936 100644 --- a/pkg/domain/infra/tunnel/images.go +++ b/pkg/domain/infra/tunnel/images.go @@ -19,25 +19,8 @@ func (ir *ImageEngine) Exists(_ context.Context, nameOrId string) (*entities.Boo return &entities.BoolReport{Value: found}, err } -func (ir *ImageEngine) Delete(ctx context.Context, nameOrId []string, opts entities.ImageDeleteOptions) (*entities.ImageDeleteReport, error) { - report := entities.ImageDeleteReport{} - - for _, id := range nameOrId { - results, err := images.Remove(ir.ClientCxt, id, &opts.Force) - if err != nil { - return nil, err - } - for _, e := range results { - if a, ok := e["Deleted"]; ok { - report.Deleted = append(report.Deleted, a) - } - - if a, ok := e["Untagged"]; ok { - report.Untagged = append(report.Untagged, a) - } - } - } - return &report, nil +func (ir *ImageEngine) Remove(ctx context.Context, imagesArg []string, opts entities.ImageRemoveOptions) (*entities.ImageRemoveReport, error) { + return images.Remove(ir.ClientCxt, imagesArg, opts) } func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions) ([]*entities.ImageSummary, error) { @@ -263,3 +246,7 @@ func (ir *ImageEngine) Config(_ context.Context) (*config.Config, error) { func (ir *ImageEngine) Build(ctx context.Context, containerFiles []string, opts entities.BuildOptions) (*entities.BuildReport, error) { return nil, errors.New("not implemented yet") } + +func (ir *ImageEngine) Tree(ctx context.Context, nameOrId string, opts entities.ImageTreeOptions) (*entities.ImageTreeReport, error) { + return nil, errors.New("not implemented yet") +} diff --git a/pkg/domain/infra/tunnel/system.go b/pkg/domain/infra/tunnel/system.go index f373525c5..97bf885e7 100644 --- a/pkg/domain/infra/tunnel/system.go +++ b/pkg/domain/infra/tunnel/system.go @@ -14,10 +14,6 @@ func (ic *ContainerEngine) Info(ctx context.Context) (*define.Info, error) { return system.Info(ic.ClientCxt) } -func (ic *ContainerEngine) RestService(_ context.Context, _ entities.ServiceOptions) error { - panic(errors.New("rest service is not supported when tunneling")) -} - func (ic *ContainerEngine) VarlinkService(_ context.Context, _ entities.ServiceOptions) error { panic(errors.New("varlink service is not supported when tunneling")) } diff --git a/pkg/rootless/rootless_linux.c b/pkg/rootless/rootless_linux.c index da52a7217..72d461cdc 100644 --- a/pkg/rootless/rootless_linux.c +++ b/pkg/rootless/rootless_linux.c @@ -535,8 +535,36 @@ create_pause_process (const char *pause_pid_file_path, char **argv) } } +static void +join_namespace_or_die (int pid_to_join, const char *ns_file) +{ + char ns_path[PATH_MAX]; + int ret; + int fd; + + ret = snprintf (ns_path, PATH_MAX, "/proc/%d/ns/%s", pid_to_join, ns_file); + if (ret == PATH_MAX) + { + fprintf (stderr, "internal error: namespace path too long\n"); + _exit (EXIT_FAILURE); + } + + fd = open (ns_path, O_CLOEXEC | O_RDONLY); + if (fd < 0) + { + fprintf (stderr, "cannot open: %s\n", ns_path); + _exit (EXIT_FAILURE); + } + if (setns (fd, 0) < 0) + { + fprintf (stderr, "cannot set namespace to %s: %s\n", ns_path, strerror (errno)); + _exit (EXIT_FAILURE); + } + close (fd); +} + int -reexec_userns_join (int userns, int mountns, char *pause_pid_file_path) +reexec_userns_join (int pid_to_join, char *pause_pid_file_path) { char uid[16]; char gid[16]; @@ -606,19 +634,8 @@ reexec_userns_join (int userns, int mountns, char *pause_pid_file_path) _exit (EXIT_FAILURE); } - if (setns (userns, 0) < 0) - { - fprintf (stderr, "cannot setns: %s\n", strerror (errno)); - _exit (EXIT_FAILURE); - } - close (userns); - - if (mountns >= 0 && setns (mountns, 0) < 0) - { - fprintf (stderr, "cannot setns: %s\n", strerror (errno)); - _exit (EXIT_FAILURE); - } - close (mountns); + join_namespace_or_die (pid_to_join, "user"); + join_namespace_or_die (pid_to_join, "mnt"); if (syscall_setresgid (0, 0, 0) < 0) { diff --git a/pkg/rootless/rootless_linux.go b/pkg/rootless/rootless_linux.go index 5ddfab7ad..3de136f12 100644 --- a/pkg/rootless/rootless_linux.go +++ b/pkg/rootless/rootless_linux.go @@ -31,7 +31,7 @@ extern uid_t rootless_uid(); extern uid_t rootless_gid(); extern int reexec_in_user_namespace(int ready, char *pause_pid_file_path, char *file_to_read, int fd); extern int reexec_in_user_namespace_wait(int pid, int options); -extern int reexec_userns_join(int userns, int mountns, char *pause_pid_file_path); +extern int reexec_userns_join(int pid, char *pause_pid_file_path); */ import "C" @@ -124,91 +124,6 @@ func tryMappingTool(tool string, pid int, hostID int, mappings []idtools.IDMap) return nil } -func readUserNs(path string) (string, error) { - b := make([]byte, 256) - _, err := unix.Readlink(path, b) - if err != nil { - return "", err - } - return string(b), nil -} - -func readUserNsFd(fd uintptr) (string, error) { - return readUserNs(fmt.Sprintf("/proc/self/fd/%d", fd)) -} - -func getParentUserNs(fd uintptr) (uintptr, error) { - const nsGetParent = 0xb702 - ret, _, errno := unix.Syscall(unix.SYS_IOCTL, fd, uintptr(nsGetParent), 0) - if errno != 0 { - return 0, errno - } - return (uintptr)(unsafe.Pointer(ret)), nil -} - -// getUserNSFirstChild returns an open FD for the first direct child user namespace that created the process -// Each container creates a new user namespace where the runtime runs. The current process in the container -// might have created new user namespaces that are child of the initial namespace we created. -// This function finds the initial namespace created for the container that is a child of the current namespace. -// -// current ns -// / \ -// TARGET -> a [other containers] -// / -// b -// / -// NS READ USING THE PID -> c -func getUserNSFirstChild(fd uintptr) (*os.File, error) { - currentNS, err := readUserNs("/proc/self/ns/user") - if err != nil { - return nil, err - } - - ns, err := readUserNsFd(fd) - if err != nil { - return nil, errors.Wrapf(err, "cannot read user namespace") - } - if ns == currentNS { - return nil, errors.New("process running in the same user namespace") - } - - for { - nextFd, err := getParentUserNs(fd) - if err != nil { - if err == unix.ENOTTY { - return os.NewFile(fd, "userns child"), nil - } - return nil, errors.Wrapf(err, "cannot get parent user namespace") - } - - ns, err = readUserNsFd(nextFd) - if err != nil { - return nil, errors.Wrapf(err, "cannot read user namespace") - } - - if ns == currentNS { - if err := unix.Close(int(nextFd)); err != nil { - return nil, err - } - - // Drop O_CLOEXEC for the fd. - _, _, errno := unix.Syscall(unix.SYS_FCNTL, fd, unix.F_SETFD, 0) - if errno != 0 { - if err := unix.Close(int(fd)); err != nil { - logrus.Errorf("failed to close file descriptor %d", fd) - } - return nil, errno - } - - return os.NewFile(fd, "userns child"), nil - } - if err := unix.Close(int(fd)); err != nil { - return nil, err - } - fd = nextFd - } -} - // joinUserAndMountNS re-exec podman in a new userNS and join the user and mount // namespace of the specified PID without looking up its parent. Useful to join directly // the conmon process. @@ -220,31 +135,7 @@ func joinUserAndMountNS(pid uint, pausePid string) (bool, int, error) { cPausePid := C.CString(pausePid) defer C.free(unsafe.Pointer(cPausePid)) - userNS, err := os.Open(fmt.Sprintf("/proc/%d/ns/user", pid)) - if err != nil { - return false, -1, err - } - defer func() { - if err := userNS.Close(); err != nil { - logrus.Errorf("unable to close namespace: %q", err) - } - }() - - mountNS, err := os.Open(fmt.Sprintf("/proc/%d/ns/mnt", pid)) - if err != nil { - return false, -1, err - } - defer func() { - if err := mountNS.Close(); err != nil { - logrus.Errorf("unable to close namespace: %q", err) - } - }() - - fd, err := getUserNSFirstChild(userNS.Fd()) - if err != nil { - return false, -1, err - } - pidC := C.reexec_userns_join(C.int(fd.Fd()), C.int(mountNS.Fd()), cPausePid) + pidC := C.reexec_userns_join(C.int(pid), cPausePid) if int(pidC) < 0 { return false, -1, errors.Errorf("cannot re-exec process") } diff --git a/pkg/specgen/container_validate.go b/pkg/specgen/container_validate.go index 9152e7ee7..c24869784 100644 --- a/pkg/specgen/container_validate.go +++ b/pkg/specgen/container_validate.go @@ -91,13 +91,13 @@ func (s *SpecGenerator) Validate() error { } // useimageresolveconf conflicts with dnsserver, dnssearch, dnsoption if s.UseImageResolvConf { - if len(s.DNSServer) > 0 { + if len(s.DNSServers) > 0 { return exclusiveOptions("UseImageResolvConf", "DNSServer") } if len(s.DNSSearch) > 0 { return exclusiveOptions("UseImageResolvConf", "DNSSearch") } - if len(s.DNSOption) > 0 { + if len(s.DNSOptions) > 0 { return exclusiveOptions("UseImageResolvConf", "DNSOption") } } diff --git a/pkg/specgen/generate/container.go b/pkg/specgen/generate/container.go index 7233acb8a..31465d8bf 100644 --- a/pkg/specgen/generate/container.go +++ b/pkg/specgen/generate/container.go @@ -20,17 +20,27 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat } // Image stop signal - if s.StopSignal == nil && newImage.Config != nil { - sig, err := signal.ParseSignalNameOrNumber(newImage.Config.StopSignal) + if s.StopSignal == nil { + stopSignal, err := newImage.StopSignal(ctx) + if err != nil { + return err + } + sig, err := signal.ParseSignalNameOrNumber(stopSignal) if err != nil { return err } s.StopSignal = &sig } + // Image envs from the image if they don't exist // already - if newImage.Config != nil && len(newImage.Config.Env) > 0 { - envs, err := envLib.ParseSlice(newImage.Config.Env) + env, err := newImage.Env(ctx) + if err != nil { + return err + } + + if len(env) > 0 { + envs, err := envLib.ParseSlice(env) if err != nil { return err } @@ -41,12 +51,15 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat } } + labels, err := newImage.Labels(ctx) + if err != nil { + return err + } + // labels from the image that dont exist already - if config := newImage.Config; config != nil { - for k, v := range config.Labels { - if _, exists := s.Labels[k]; !exists { - s.Labels[k] = v - } + for k, v := range labels { + if _, exists := s.Labels[k]; !exists { + s.Labels[k] = v } } @@ -75,20 +88,30 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat } // entrypoint - if config := newImage.Config; config != nil { - if len(s.Entrypoint) < 1 && len(config.Entrypoint) > 0 { - s.Entrypoint = config.Entrypoint - } - if len(s.Command) < 1 && len(config.Cmd) > 0 { - s.Command = config.Cmd - } - if len(s.Command) < 1 && len(s.Entrypoint) < 1 { - return errors.Errorf("No command provided or as CMD or ENTRYPOINT in this image") - } - // workdir - if len(s.WorkDir) < 1 && len(config.WorkingDir) > 1 { - s.WorkDir = config.WorkingDir - } + entrypoint, err := newImage.Entrypoint(ctx) + if err != nil { + return err + } + if len(s.Entrypoint) < 1 && len(entrypoint) > 0 { + s.Entrypoint = entrypoint + } + command, err := newImage.Cmd(ctx) + if err != nil { + return err + } + if len(s.Command) < 1 && len(command) > 0 { + s.Command = command + } + if len(s.Command) < 1 && len(s.Entrypoint) < 1 { + return errors.Errorf("No command provided or as CMD or ENTRYPOINT in this image") + } + // workdir + workingDir, err := newImage.WorkingDir(ctx) + if err != nil { + return err + } + if len(s.WorkDir) < 1 && len(workingDir) > 1 { + s.WorkDir = workingDir } if len(s.SeccompProfilePath) < 1 { @@ -99,15 +122,17 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat s.SeccompProfilePath = p } - if user := s.User; len(user) == 0 { - switch { + if len(s.User) == 0 { + s.User, err = newImage.User(ctx) + if err != nil { + return err + } + // TODO This should be enabled when namespaces actually work //case usernsMode.IsKeepID(): // user = fmt.Sprintf("%d:%d", rootless.GetRootlessUID(), rootless.GetRootlessGID()) - case newImage.Config == nil || (newImage.Config != nil && len(newImage.Config.User) == 0): + if len(s.User) == 0 { s.User = "0" - default: - s.User = newImage.Config.User } } if err := finishThrottleDevices(s); err != nil { @@ -116,7 +141,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat // Unless already set via the CLI, check if we need to disable process // labels or set the defaults. if len(s.SelinuxOpts) == 0 { - if err := SetLabelOpts(s, r, s.PidNS, s.IpcNS); err != nil { + if err := setLabelOpts(s, r, s.PidNS, s.IpcNS); err != nil { return err } } diff --git a/pkg/specgen/generate/namespaces.go b/pkg/specgen/generate/namespaces.go index cdd7d86da..16a1c048f 100644 --- a/pkg/specgen/generate/namespaces.go +++ b/pkg/specgen/generate/namespaces.go @@ -3,9 +3,7 @@ package generate import ( "os" - "github.com/containers/common/pkg/capabilities" "github.com/containers/libpod/libpod" - "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/specgen" "github.com/cri-o/ocicni/pkg/ocicni" spec "github.com/opencontainers/runtime-spec/specs-go" @@ -147,20 +145,19 @@ func GenerateNamespaceContainerOpts(s *specgen.SpecGenerator, rt *libpod.Runtime if len(s.DNSSearch) > 0 { options = append(options, libpod.WithDNSSearch(s.DNSSearch)) } - if len(s.DNSServer) > 0 { - // TODO I'm not sure how we are going to handle this given the input - if len(s.DNSServer) == 1 { //&& strings.ToLower(s.DNSServer[0].) == "none" { - options = append(options, libpod.WithUseImageResolvConf()) - } else { - var dnsServers []string - for _, d := range s.DNSServer { - dnsServers = append(dnsServers, d.String()) - } - options = append(options, libpod.WithDNS(dnsServers)) + + if s.UseImageResolvConf { + options = append(options, libpod.WithUseImageResolvConf()) + } else { + var dnsServers []string + for _, d := range s.DNSServers { + dnsServers = append(dnsServers, d.String()) } + options = append(options, libpod.WithDNS(dnsServers)) } - if len(s.DNSOption) > 0 { - options = append(options, libpod.WithDNSOption(s.DNSOption)) + + if len(s.DNSOptions) > 0 { + options = append(options, libpod.WithDNSOption(s.DNSOptions)) } if s.StaticIP != nil { options = append(options, libpod.WithStaticIP(*s.StaticIP)) @@ -324,66 +321,6 @@ func userConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator) err return nil } -func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, newImage *image.Image) error { - // HANDLE CAPABILITIES - // NOTE: Must happen before SECCOMP - if s.Privileged { - g.SetupPrivileged(true) - } - - useNotRoot := func(user string) bool { - if user == "" || user == "root" || user == "0" { - return false - } - return true - } - configSpec := g.Config - var err error - var caplist []string - bounding := configSpec.Process.Capabilities.Bounding - if useNotRoot(s.User) { - configSpec.Process.Capabilities.Bounding = caplist - } - caplist, err = capabilities.MergeCapabilities(configSpec.Process.Capabilities.Bounding, s.CapAdd, s.CapDrop) - if err != nil { - return err - } - - configSpec.Process.Capabilities.Bounding = caplist - configSpec.Process.Capabilities.Permitted = caplist - configSpec.Process.Capabilities.Inheritable = caplist - configSpec.Process.Capabilities.Effective = caplist - configSpec.Process.Capabilities.Ambient = caplist - if useNotRoot(s.User) { - caplist, err = capabilities.MergeCapabilities(bounding, s.CapAdd, s.CapDrop) - if err != nil { - return err - } - } - configSpec.Process.Capabilities.Bounding = caplist - - // HANDLE SECCOMP - if s.SeccompProfilePath != "unconfined" { - seccompConfig, err := getSeccompConfig(s, configSpec, newImage) - if err != nil { - return err - } - configSpec.Linux.Seccomp = seccompConfig - } - - // Clear default Seccomp profile from Generator for privileged containers - if s.SeccompProfilePath == "unconfined" || s.Privileged { - configSpec.Linux.Seccomp = nil - } - - g.SetRootReadonly(s.ReadOnlyFilesystem) - for sysctlKey, sysctlVal := range s.Sysctl { - g.AddLinuxSysctl(sysctlKey, sysctlVal) - } - - return nil -} - // GetNamespaceOptions transforms a slice of kernel namespaces // into a slice of pod create options. Currently, not all // kernel namespaces are supported, and they will be returned in an error diff --git a/pkg/specgen/generate/security.go b/pkg/specgen/generate/security.go index ef4b3b47a..e2da9e976 100644 --- a/pkg/specgen/generate/security.go +++ b/pkg/specgen/generate/security.go @@ -1,15 +1,22 @@ package generate import ( + "strings" + + "github.com/containers/common/pkg/capabilities" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/specgen" + "github.com/containers/libpod/pkg/util" + "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) -// SetLabelOpts sets the label options of the SecurityConfig according to the +// setLabelOpts sets the label options of the SecurityConfig according to the // input. -func SetLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig specgen.Namespace, ipcConfig specgen.Namespace) error { +func setLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig specgen.Namespace, ipcConfig specgen.Namespace) error { if !runtime.EnableLabeling() || s.Privileged { s.SelinuxOpts = label.DisableSecOpt() return nil @@ -48,12 +55,10 @@ func SetLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig s return nil } -// ConfigureGenerator configures the generator according to the input. -/* -func (c *SecurityConfig) ConfigureGenerator(g *generate.Generator, user *UserConfig) error { +func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, newImage *image.Image) error { // HANDLE CAPABILITIES // NOTE: Must happen before SECCOMP - if c.Privileged { + if s.Privileged { g.SetupPrivileged(true) } @@ -63,56 +68,66 @@ func (c *SecurityConfig) ConfigureGenerator(g *generate.Generator, user *UserCon } return true } - configSpec := g.Config var err error - var defaultCaplist []string + var caplist []string bounding := configSpec.Process.Capabilities.Bounding - if useNotRoot(user.User) { - configSpec.Process.Capabilities.Bounding = defaultCaplist + if useNotRoot(s.User) { + configSpec.Process.Capabilities.Bounding = caplist } - defaultCaplist, err = capabilities.MergeCapabilities(configSpec.Process.Capabilities.Bounding, c.CapAdd, c.CapDrop) + caplist, err = capabilities.MergeCapabilities(configSpec.Process.Capabilities.Bounding, s.CapAdd, s.CapDrop) if err != nil { return err } + privCapsRequired := []string{} + + // If the container image specifies an label with a + // capabilities.ContainerImageLabel then split the comma separated list + // of capabilities and record them. This list indicates the only + // capabilities, required to run the container. + var capsRequiredRequested []string + for key, val := range s.Labels { + if util.StringInSlice(key, capabilities.ContainerImageLabels) { + capsRequiredRequested = strings.Split(val, ",") + } + } + if !s.Privileged && len(capsRequiredRequested) > 0 { - privCapRequired := []string{} - - if !c.Privileged && len(c.CapRequired) > 0 { - // Pass CapRequired in CapAdd field to normalize capabilities names - capRequired, err := capabilities.MergeCapabilities(nil, c.CapRequired, nil) + // Pass capRequiredRequested in CapAdd field to normalize capabilities names + capsRequired, err := capabilities.MergeCapabilities(nil, capsRequiredRequested, nil) if err != nil { - logrus.Errorf("capabilities requested by user or image are not valid: %q", strings.Join(c.CapRequired, ",")) + logrus.Errorf("capabilities requested by user or image are not valid: %q", strings.Join(capsRequired, ",")) } else { - // Verify all capRequiered are in the defaultCapList - for _, cap := range capRequired { - if !util.StringInSlice(cap, defaultCaplist) { - privCapRequired = append(privCapRequired, cap) + // Verify all capRequiered are in the capList + for _, cap := range capsRequired { + if !util.StringInSlice(cap, caplist) { + privCapsRequired = append(privCapsRequired, cap) } } } - if len(privCapRequired) == 0 { - defaultCaplist = capRequired + if len(privCapsRequired) == 0 { + caplist = capsRequired } else { - logrus.Errorf("capabilities requested by user or image are not allowed by default: %q", strings.Join(privCapRequired, ",")) + logrus.Errorf("capabilities requested by user or image are not allowed by default: %q", strings.Join(privCapsRequired, ",")) } } - configSpec.Process.Capabilities.Bounding = defaultCaplist - configSpec.Process.Capabilities.Permitted = defaultCaplist - configSpec.Process.Capabilities.Inheritable = defaultCaplist - configSpec.Process.Capabilities.Effective = defaultCaplist - configSpec.Process.Capabilities.Ambient = defaultCaplist - if useNotRoot(user.User) { - defaultCaplist, err = capabilities.MergeCapabilities(bounding, c.CapAdd, c.CapDrop) + + configSpec.Process.Capabilities.Bounding = caplist + configSpec.Process.Capabilities.Permitted = caplist + configSpec.Process.Capabilities.Inheritable = caplist + configSpec.Process.Capabilities.Effective = caplist + configSpec.Process.Capabilities.Ambient = caplist + if useNotRoot(s.User) { + caplist, err = capabilities.MergeCapabilities(bounding, s.CapAdd, s.CapDrop) if err != nil { return err } } - configSpec.Process.Capabilities.Bounding = defaultCaplist + configSpec.Process.Capabilities.Bounding = caplist // HANDLE SECCOMP - if c.SeccompProfilePath != "unconfined" { - seccompConfig, err := getSeccompConfig(c, configSpec) + if s.SeccompProfilePath != "unconfined" { + seccompConfig, err := getSeccompConfig(s, configSpec, newImage) if err != nil { return err } @@ -120,35 +135,14 @@ func (c *SecurityConfig) ConfigureGenerator(g *generate.Generator, user *UserCon } // Clear default Seccomp profile from Generator for privileged containers - if c.SeccompProfilePath == "unconfined" || c.Privileged { + if s.SeccompProfilePath == "unconfined" || s.Privileged { configSpec.Linux.Seccomp = nil } - for _, opt := range c.SecurityOpts { - // Split on both : and = - splitOpt := strings.Split(opt, "=") - if len(splitOpt) == 1 { - splitOpt = strings.Split(opt, ":") - } - if len(splitOpt) < 2 { - continue - } - switch splitOpt[0] { - case "label": - configSpec.Annotations[libpod.InspectAnnotationLabel] = splitOpt[1] - case "seccomp": - configSpec.Annotations[libpod.InspectAnnotationSeccomp] = splitOpt[1] - case "apparmor": - configSpec.Annotations[libpod.InspectAnnotationApparmor] = splitOpt[1] - } - } - - g.SetRootReadonly(c.ReadOnlyRootfs) - for sysctlKey, sysctlVal := range c.Sysctl { + g.SetRootReadonly(s.ReadOnlyFilesystem) + for sysctlKey, sysctlVal := range s.Sysctl { g.AddLinuxSysctl(sysctlKey, sysctlVal) } return nil } - -*/ diff --git a/pkg/specgen/specgen.go b/pkg/specgen/specgen.go index 1a05733f9..0b568dd5c 100644 --- a/pkg/specgen/specgen.go +++ b/pkg/specgen/specgen.go @@ -319,24 +319,24 @@ type ContainerNetworkConfig struct { // by Podman, but instead sourced from the image. // Conflicts with DNSServer, DNSSearch, DNSOption. UseImageResolvConf bool `json:"use_image_resolve_conf,omitempty"` - // DNSServer is a set of DNS servers that will be used in the + // DNSServers is a set of DNS servers that will be used in the // container's resolv.conf, replacing the host's DNS Servers which are // used by default. // Conflicts with UseImageResolvConf. // Optional. - DNSServer []net.IP `json:"dns_server,omitempty"` + DNSServers []net.IP `json:"dns_server,omitempty"` // DNSSearch is a set of DNS search domains that will be used in the // container's resolv.conf, replacing the host's DNS search domains // which are used by default. // Conflicts with UseImageResolvConf. // Optional. DNSSearch []string `json:"dns_search,omitempty"` - // DNSOption is a set of DNS options that will be used in the + // DNSOptions is a set of DNS options that will be used in the // container's resolv.conf, replacing the host's DNS options which are // used by default. // Conflicts with UseImageResolvConf. // Optional. - DNSOption []string `json:"dns_option,omitempty"` + DNSOptions []string `json:"dns_option,omitempty"` // UseImageHosts indicates that /etc/hosts should not be managed by // Podman, and instead sourced from the image. // Conflicts with HostAdd. |