diff options
Diffstat (limited to 'pkg/domain/infra/abi')
-rw-r--r-- | pkg/domain/infra/abi/containers.go | 182 | ||||
-rw-r--r-- | pkg/domain/infra/abi/containers_runlabel.go | 12 | ||||
-rw-r--r-- | pkg/domain/infra/abi/cp.go | 6 | ||||
-rw-r--r-- | pkg/domain/infra/abi/generate.go | 161 | ||||
-rw-r--r-- | pkg/domain/infra/abi/healthcheck.go | 4 | ||||
-rw-r--r-- | pkg/domain/infra/abi/images.go | 41 | ||||
-rw-r--r-- | pkg/domain/infra/abi/images_list.go | 9 | ||||
-rw-r--r-- | pkg/domain/infra/abi/manifest.go | 4 | ||||
-rw-r--r-- | pkg/domain/infra/abi/network.go | 7 | ||||
-rw-r--r-- | pkg/domain/infra/abi/parse/parse.go | 2 | ||||
-rw-r--r-- | pkg/domain/infra/abi/play.go | 109 | ||||
-rw-r--r-- | pkg/domain/infra/abi/pods.go | 47 | ||||
-rw-r--r-- | pkg/domain/infra/abi/system.go | 26 | ||||
-rw-r--r-- | pkg/domain/infra/abi/trust.go | 8 | ||||
-rw-r--r-- | pkg/domain/infra/abi/volumes.go | 23 |
15 files changed, 266 insertions, 375 deletions
diff --git a/pkg/domain/infra/abi/containers.go b/pkg/domain/infra/abi/containers.go index eb45d4630..d2c8aefdc 100644 --- a/pkg/domain/infra/abi/containers.go +++ b/pkg/domain/infra/abi/containers.go @@ -75,8 +75,8 @@ func getContainersByContext(all, latest bool, names []string, runtime *libpod.Ru } // TODO: Should return *entities.ContainerExistsReport, error -func (ic *ContainerEngine) ContainerExists(ctx context.Context, nameOrId string) (*entities.BoolReport, error) { - _, err := ic.Libpod.LookupContainer(nameOrId) +func (ic *ContainerEngine) ContainerExists(ctx context.Context, nameOrID string) (*entities.BoolReport, error) { + _, err := ic.Libpod.LookupContainer(nameOrID) if err != nil && errors.Cause(err) != define.ErrNoSuchCtr { return nil, err } @@ -84,13 +84,11 @@ func (ic *ContainerEngine) ContainerExists(ctx context.Context, nameOrId string) } func (ic *ContainerEngine) ContainerWait(ctx context.Context, namesOrIds []string, options entities.WaitOptions) ([]entities.WaitReport, error) { - var ( - responses []entities.WaitReport - ) ctrs, err := getContainersByContext(false, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err } + responses := make([]entities.WaitReport, 0, len(ctrs)) for _, c := range ctrs { response := entities.WaitReport{Id: c.ID()} exitCode, err := c.WaitForConditionWithInterval(options.Interval, options.Condition) @@ -106,10 +104,9 @@ func (ic *ContainerEngine) ContainerWait(ctx context.Context, namesOrIds []strin func (ic *ContainerEngine) ContainerPause(ctx context.Context, namesOrIds []string, options entities.PauseUnPauseOptions) ([]*entities.PauseUnpauseReport, error) { var ( - ctrs []*libpod.Container - err error - report []*entities.PauseUnpauseReport + err error ) + ctrs := []*libpod.Container{} //nolint if options.All { ctrs, err = ic.Libpod.GetAllContainers() } else { @@ -118,6 +115,7 @@ func (ic *ContainerEngine) ContainerPause(ctx context.Context, namesOrIds []stri if err != nil { return nil, err } + report := make([]*entities.PauseUnpauseReport, 0, len(ctrs)) for _, c := range ctrs { err := c.Pause() report = append(report, &entities.PauseUnpauseReport{Id: c.ID(), Err: err}) @@ -127,10 +125,9 @@ func (ic *ContainerEngine) ContainerPause(ctx context.Context, namesOrIds []stri func (ic *ContainerEngine) ContainerUnpause(ctx context.Context, namesOrIds []string, options entities.PauseUnPauseOptions) ([]*entities.PauseUnpauseReport, error) { var ( - ctrs []*libpod.Container - err error - report []*entities.PauseUnpauseReport + err error ) + ctrs := []*libpod.Container{} //nolint if options.All { ctrs, err = ic.Libpod.GetAllContainers() } else { @@ -139,6 +136,7 @@ func (ic *ContainerEngine) ContainerUnpause(ctx context.Context, namesOrIds []st if err != nil { return nil, err } + report := make([]*entities.PauseUnpauseReport, 0, len(ctrs)) for _, c := range ctrs { err := c.Unpause() report = append(report, &entities.PauseUnpauseReport{Id: c.ID(), Err: err}) @@ -146,9 +144,6 @@ func (ic *ContainerEngine) ContainerUnpause(ctx context.Context, namesOrIds []st return report, nil } func (ic *ContainerEngine) ContainerStop(ctx context.Context, namesOrIds []string, options entities.StopOptions) ([]*entities.StopReport, error) { - var ( - reports []*entities.StopReport - ) names := namesOrIds for _, cidFile := range options.CIDFiles { content, err := ioutil.ReadFile(cidFile) @@ -162,32 +157,34 @@ func (ic *ContainerEngine) ContainerStop(ctx context.Context, namesOrIds []strin if err != nil && !(options.Ignore && errors.Cause(err) == define.ErrNoSuchCtr) { return nil, err } - for _, con := range ctrs { - report := entities.StopReport{Id: con.ID()} - err = con.StopWithTimeout(options.Timeout) + errMap, err := parallel.ContainerOp(ctx, ctrs, func(c *libpod.Container) error { + var err error + if options.Timeout != nil { + err = c.StopWithTimeout(*options.Timeout) + } else { + err = c.Stop() + } if err != nil { - // These first two are considered non-fatal under the right conditions - if errors.Cause(err) == define.ErrCtrStopped { - logrus.Debugf("Container %s is already stopped", con.ID()) - reports = append(reports, &report) - continue - - } else if options.All && errors.Cause(err) == define.ErrCtrStateInvalid { - logrus.Debugf("Container %s is not running, could not stop", con.ID()) - reports = append(reports, &report) - continue + switch { + case errors.Cause(err) == define.ErrCtrStopped: + logrus.Debugf("Container %s is already stopped", c.ID()) + case options.All && errors.Cause(err) == define.ErrCtrStateInvalid: + logrus.Debugf("Container %s is not running, could not stop", c.ID()) + default: + return err } - report.Err = err - reports = append(reports, &report) - continue - } else if err := con.Cleanup(ctx); err != nil { - // Only if no error, proceed to cleanup to ensure all - // mounts are removed before we exit. - report.Err = err - reports = append(reports, &report) - continue } - reports = append(reports, &report) + return c.Cleanup(ctx) + }) + if err != nil { + return nil, err + } + reports := make([]*entities.StopReport, 0, len(errMap)) + for ctr, err := range errMap { + report := new(entities.StopReport) + report.Id = ctr.ID() + report.Err = err + reports = append(reports, report) } return reports, nil } @@ -203,10 +200,10 @@ func (ic *ContainerEngine) ContainerPrune(ctx context.Context, options entities. filterFuncs = append(filterFuncs, generatedFunc) } } - return ic.pruneContainersHelper(ctx, filterFuncs) + return ic.pruneContainersHelper(filterFuncs) } -func (ic *ContainerEngine) pruneContainersHelper(ctx context.Context, filterFuncs []libpod.ContainerFilter) (*entities.ContainerPruneReport, error) { +func (ic *ContainerEngine) pruneContainersHelper(filterFuncs []libpod.ContainerFilter) (*entities.ContainerPruneReport, error) { prunedContainers, pruneErrors, err := ic.Libpod.PruneContainers(filterFuncs) if err != nil { return nil, err @@ -219,9 +216,6 @@ func (ic *ContainerEngine) pruneContainersHelper(ctx context.Context, filterFunc } func (ic *ContainerEngine) ContainerKill(ctx context.Context, namesOrIds []string, options entities.KillOptions) ([]*entities.KillReport, error) { - var ( - reports []*entities.KillReport - ) sig, err := signal.ParseSignalNameOrNumber(options.Signal) if err != nil { return nil, err @@ -230,6 +224,7 @@ func (ic *ContainerEngine) ContainerKill(ctx context.Context, namesOrIds []strin if err != nil { return nil, err } + reports := make([]*entities.KillReport, 0, len(ctrs)) for _, con := range ctrs { reports = append(reports, &entities.KillReport{ Id: con.ID(), @@ -240,9 +235,8 @@ func (ic *ContainerEngine) ContainerKill(ctx context.Context, namesOrIds []strin } func (ic *ContainerEngine) ContainerRestart(ctx context.Context, namesOrIds []string, options entities.RestartOptions) ([]*entities.RestartReport, error) { var ( - ctrs []*libpod.Container - err error - reports []*entities.RestartReport + ctrs []*libpod.Container + err error ) if options.Running { @@ -257,6 +251,7 @@ func (ic *ContainerEngine) ContainerRestart(ctx context.Context, namesOrIds []st } } + reports := make([]*entities.RestartReport, 0, len(ctrs)) for _, con := range ctrs { timeout := con.StopTimeout() if options.Timeout != nil { @@ -271,9 +266,7 @@ func (ic *ContainerEngine) ContainerRestart(ctx context.Context, namesOrIds []st } func (ic *ContainerEngine) ContainerRm(ctx context.Context, namesOrIds []string, options entities.RmOptions) ([]*entities.RmReport, error) { - var ( - reports []*entities.RmReport - ) + reports := []*entities.RmReport{} if options.Storage { for _, ctr := range namesOrIds { report := entities.RmReport{Id: ctr} @@ -322,7 +315,7 @@ func (ic *ContainerEngine) ContainerRm(ctx context.Context, namesOrIds []string, return reports, nil } - errMap, err := parallel.ParallelContainerOp(ctx, ctrs, func(c *libpod.Container) error { + errMap, err := parallel.ContainerOp(ctx, ctrs, func(c *libpod.Container) error { err := ic.Libpod.RemoveContainer(ctx, c, options.Force, options.Volumes) if err != nil { if options.Ignore && errors.Cause(err) == define.ErrNoSuchCtr { @@ -346,11 +339,11 @@ func (ic *ContainerEngine) ContainerRm(ctx context.Context, namesOrIds []string, } func (ic *ContainerEngine) ContainerInspect(ctx context.Context, namesOrIds []string, options entities.InspectOptions) ([]*entities.ContainerInspectReport, error) { - var reports []*entities.ContainerInspectReport ctrs, err := getContainersByContext(false, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err } + reports := make([]*entities.ContainerInspectReport, 0, len(ctrs)) for _, c := range ctrs { data, err := c.Inspect(options.Size) if err != nil { @@ -383,11 +376,11 @@ func (ic *ContainerEngine) ContainerTop(ctx context.Context, options entities.To return report, err } -func (ic *ContainerEngine) ContainerCommit(ctx context.Context, nameOrId string, options entities.CommitOptions) (*entities.CommitReport, error) { +func (ic *ContainerEngine) ContainerCommit(ctx context.Context, nameOrID string, options entities.CommitOptions) (*entities.CommitReport, error) { var ( mimeType string ) - ctr, err := ic.Libpod.LookupContainer(nameOrId) + ctr, err := ic.Libpod.LookupContainer(nameOrID) if err != nil { return nil, err } @@ -428,8 +421,8 @@ func (ic *ContainerEngine) ContainerCommit(ctx context.Context, nameOrId string, return &entities.CommitReport{Id: newImage.ID()}, nil } -func (ic *ContainerEngine) ContainerExport(ctx context.Context, nameOrId string, options entities.ContainerExportOptions) error { - ctr, err := ic.Libpod.LookupContainer(nameOrId) +func (ic *ContainerEngine) ContainerExport(ctx context.Context, nameOrID string, options entities.ContainerExportOptions) error { + ctr, err := ic.Libpod.LookupContainer(nameOrID) if err != nil { return err } @@ -438,9 +431,8 @@ func (ic *ContainerEngine) ContainerExport(ctx context.Context, nameOrId string, func (ic *ContainerEngine) ContainerCheckpoint(ctx context.Context, namesOrIds []string, options entities.CheckpointOptions) ([]*entities.CheckpointReport, error) { var ( - err error - cons []*libpod.Container - reports []*entities.CheckpointReport + err error + cons []*libpod.Container ) checkOpts := libpod.ContainerCheckpointOptions{ Keep: options.Keep, @@ -462,6 +454,7 @@ func (ic *ContainerEngine) ContainerCheckpoint(ctx context.Context, namesOrIds [ if err != nil { return nil, err } + reports := make([]*entities.CheckpointReport, 0, len(cons)) for _, con := range cons { err = con.Checkpoint(ctx, checkOpts) reports = append(reports, &entities.CheckpointReport{ @@ -474,10 +467,8 @@ func (ic *ContainerEngine) ContainerCheckpoint(ctx context.Context, namesOrIds [ func (ic *ContainerEngine) ContainerRestore(ctx context.Context, namesOrIds []string, options entities.RestoreOptions) ([]*entities.RestoreReport, error) { var ( - cons []*libpod.Container - err error - filterFuncs []libpod.ContainerFilter - reports []*entities.RestoreReport + cons []*libpod.Container + err error ) restoreOptions := libpod.ContainerCheckpointOptions{ @@ -490,10 +481,12 @@ func (ic *ContainerEngine) ContainerRestore(ctx context.Context, namesOrIds []st IgnoreStaticMAC: options.IgnoreStaticMAC, } - filterFuncs = append(filterFuncs, func(c *libpod.Container) bool { - state, _ := c.State() - return state == define.ContainerStateExited - }) + filterFuncs := []libpod.ContainerFilter{ + func(c *libpod.Container) bool { + state, _ := c.State() + return state == define.ContainerStateExited + }, + } switch { case options.Import != "": @@ -506,6 +499,7 @@ func (ic *ContainerEngine) ContainerRestore(ctx context.Context, namesOrIds []st if err != nil { return nil, err } + reports := make([]*entities.RestoreReport, 0, len(cons)) for _, con := range cons { err := con.Restore(ctx, restoreOptions) reports = append(reports, &entities.RestoreReport{ @@ -527,8 +521,8 @@ func (ic *ContainerEngine) ContainerCreate(ctx context.Context, s *specgen.SpecG return &entities.ContainerCreateReport{Id: ctr.ID()}, nil } -func (ic *ContainerEngine) ContainerAttach(ctx context.Context, nameOrId string, options entities.AttachOptions) error { - ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrId}, ic.Libpod) +func (ic *ContainerEngine) ContainerAttach(ctx context.Context, nameOrID string, options entities.AttachOptions) error { + ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrID}, ic.Libpod) if err != nil { return err } @@ -564,38 +558,38 @@ func makeExecConfig(options entities.ExecOptions) *libpod.ExecConfig { return execConfig } -func checkExecPreserveFDs(options entities.ExecOptions) (int, error) { - ec := define.ExecErrorCodeGeneric +func checkExecPreserveFDs(options entities.ExecOptions) error { if options.PreserveFDs > 0 { entries, err := ioutil.ReadDir("/proc/self/fd") if err != nil { - return ec, errors.Wrapf(err, "unable to read /proc/self/fd") + return errors.Wrapf(err, "unable to read /proc/self/fd") } m := make(map[int]bool) for _, e := range entries { i, err := strconv.Atoi(e.Name()) if err != nil { - return ec, errors.Wrapf(err, "cannot parse %s in /proc/self/fd", e.Name()) + return errors.Wrapf(err, "cannot parse %s in /proc/self/fd", e.Name()) } m[i] = true } for i := 3; i < 3+int(options.PreserveFDs); i++ { if _, found := m[i]; !found { - return ec, errors.New("invalid --preserve-fds=N specified. Not enough FDs available") + return errors.New("invalid --preserve-fds=N specified. Not enough FDs available") } } } - return ec, nil + return nil } -func (ic *ContainerEngine) ContainerExec(ctx context.Context, nameOrId string, options entities.ExecOptions, streams define.AttachStreams) (int, error) { - ec, err := checkExecPreserveFDs(options) +func (ic *ContainerEngine) ContainerExec(ctx context.Context, nameOrID string, options entities.ExecOptions, streams define.AttachStreams) (int, error) { + ec := define.ExecErrorCodeGeneric + err := checkExecPreserveFDs(options) if err != nil { return ec, err } - ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrId}, ic.Libpod) + ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrID}, ic.Libpod) if err != nil { return ec, err } @@ -607,12 +601,12 @@ func (ic *ContainerEngine) ContainerExec(ctx context.Context, nameOrId string, o return define.TranslateExecErrorToExitCode(ec, err), err } -func (ic *ContainerEngine) ContainerExecDetached(ctx context.Context, nameOrId string, options entities.ExecOptions) (string, error) { - _, err := checkExecPreserveFDs(options) +func (ic *ContainerEngine) ContainerExecDetached(ctx context.Context, nameOrID string, options entities.ExecOptions) (string, error) { + err := checkExecPreserveFDs(options) if err != nil { return "", err } - ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrId}, ic.Libpod) + ctrs, err := getContainersByContext(false, options.Latest, []string{nameOrID}, ic.Libpod) if err != nil { return "", err } @@ -647,7 +641,7 @@ func (ic *ContainerEngine) ContainerExecDetached(ctx context.Context, nameOrId s } func (ic *ContainerEngine) ContainerStart(ctx context.Context, namesOrIds []string, options entities.ContainerStartOptions) ([]*entities.ContainerStartReport, error) { - var reports []*entities.ContainerStartReport + reports := []*entities.ContainerStartReport{} var exitCode = define.ExecErrorCodeGeneric ctrs, rawInputs, err := getContainersAndInputByContext(false, options.Latest, namesOrIds, ic.Libpod) if err != nil { @@ -766,15 +760,15 @@ func (ic *ContainerEngine) ContainerList(ctx context.Context, options entities.C } // ContainerDiff provides changes to given container -func (ic *ContainerEngine) ContainerDiff(ctx context.Context, nameOrId string, opts entities.DiffOptions) (*entities.DiffReport, error) { +func (ic *ContainerEngine) ContainerDiff(ctx context.Context, nameOrID string, opts entities.DiffOptions) (*entities.DiffReport, error) { if opts.Latest { ctnr, err := ic.Libpod.GetLatestContainer() if err != nil { return nil, errors.Wrap(err, "unable to get latest container") } - nameOrId = ctnr.ID() + nameOrID = ctnr.ID() } - changes, err := ic.Libpod.GetDiff("", nameOrId) + changes, err := ic.Libpod.GetDiff("", nameOrID) return &entities.DiffReport{Changes: changes}, err } @@ -906,7 +900,7 @@ func (ic *ContainerEngine) ContainerLogs(ctx context.Context, containers []strin } func (ic *ContainerEngine) ContainerCleanup(ctx context.Context, namesOrIds []string, options entities.ContainerCleanupOptions) ([]*entities.ContainerCleanupReport, error) { - var reports []*entities.ContainerCleanupReport + reports := []*entities.ContainerCleanupReport{} ctrs, err := getContainersByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err @@ -957,11 +951,11 @@ func (ic *ContainerEngine) ContainerCleanup(ctx context.Context, namesOrIds []st } func (ic *ContainerEngine) ContainerInit(ctx context.Context, namesOrIds []string, options entities.ContainerInitOptions) ([]*entities.ContainerInitReport, error) { - var reports []*entities.ContainerInitReport ctrs, err := getContainersByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err } + reports := make([]*entities.ContainerInitReport, 0, len(ctrs)) for _, ctr := range ctrs { report := entities.ContainerInitReport{Id: ctr.ID()} err := ctr.Init(ctx) @@ -976,7 +970,7 @@ func (ic *ContainerEngine) ContainerInit(ctx context.Context, namesOrIds []strin return reports, nil } -func (ic *ContainerEngine) ContainerMount(ctx context.Context, nameOrIds []string, options entities.ContainerMountOptions) ([]*entities.ContainerMountReport, error) { +func (ic *ContainerEngine) ContainerMount(ctx context.Context, nameOrIDs []string, options entities.ContainerMountOptions) ([]*entities.ContainerMountReport, error) { if os.Geteuid() != 0 { if driver := ic.Libpod.StorageConfig().GraphDriverName; driver != "vfs" { // Do not allow to mount a graphdriver that is not vfs if we are creating the userns as part @@ -992,11 +986,11 @@ func (ic *ContainerEngine) ContainerMount(ctx context.Context, nameOrIds []strin os.Exit(ret) } } - var reports []*entities.ContainerMountReport - ctrs, err := getContainersByContext(options.All, options.Latest, nameOrIds, ic.Libpod) + ctrs, err := getContainersByContext(options.All, options.Latest, nameOrIDs, ic.Libpod) if err != nil { return nil, err } + reports := make([]*entities.ContainerMountReport, 0, len(ctrs)) for _, ctr := range ctrs { report := entities.ContainerMountReport{Id: ctr.ID()} report.Path, report.Err = ctr.Mount() @@ -1028,12 +1022,12 @@ func (ic *ContainerEngine) ContainerMount(ctx context.Context, nameOrIds []strin return reports, nil } -func (ic *ContainerEngine) ContainerUnmount(ctx context.Context, nameOrIds []string, options entities.ContainerUnmountOptions) ([]*entities.ContainerUnmountReport, error) { - var reports []*entities.ContainerUnmountReport - ctrs, err := getContainersByContext(options.All, options.Latest, nameOrIds, ic.Libpod) +func (ic *ContainerEngine) ContainerUnmount(ctx context.Context, nameOrIDs []string, options entities.ContainerUnmountOptions) ([]*entities.ContainerUnmountReport, error) { + ctrs, err := getContainersByContext(options.All, options.Latest, nameOrIDs, ic.Libpod) if err != nil { return nil, err } + reports := []*entities.ContainerUnmountReport{} for _, ctr := range ctrs { state, err := ctr.State() if err != nil { @@ -1063,12 +1057,12 @@ func (ic *ContainerEngine) Config(_ context.Context) (*config.Config, error) { return ic.Libpod.GetConfig() } -func (ic *ContainerEngine) ContainerPort(ctx context.Context, nameOrId string, options entities.ContainerPortOptions) ([]*entities.ContainerPortReport, error) { - var reports []*entities.ContainerPortReport - ctrs, err := getContainersByContext(options.All, options.Latest, []string{nameOrId}, ic.Libpod) +func (ic *ContainerEngine) ContainerPort(ctx context.Context, nameOrID string, options entities.ContainerPortOptions) ([]*entities.ContainerPortReport, error) { + ctrs, err := getContainersByContext(options.All, options.Latest, []string{nameOrID}, ic.Libpod) if err != nil { return nil, err } + reports := []*entities.ContainerPortReport{} for _, con := range ctrs { state, err := con.State() if err != nil { diff --git a/pkg/domain/infra/abi/containers_runlabel.go b/pkg/domain/infra/abi/containers_runlabel.go index 41f4444d5..37422aac5 100644 --- a/pkg/domain/infra/abi/containers_runlabel.go +++ b/pkg/domain/infra/abi/containers_runlabel.go @@ -116,7 +116,7 @@ func generateRunlabelCommand(runlabel string, img *image.Image, args []string, o err error name, imageName string globalOpts string - cmd, env []string + cmd []string ) // TODO: How do we get global opts as done in v1? @@ -149,7 +149,7 @@ func generateRunlabelCommand(runlabel string, img *image.Image, args []string, o return nil, nil, err } - env = generateRunEnvironment(name, imageName, options) + env := generateRunEnvironment(options) env = append(env, "PODMAN_RUNLABEL_NESTED=1") envmap, err := envLib.ParseSlice(env) if err != nil { @@ -185,9 +185,6 @@ func generateRunlabelCommand(runlabel string, img *image.Image, args []string, o // generateCommand takes a label (string) and converts it to an executable command func generateCommand(command, imageName, name, globalOpts string) ([]string, error) { - var ( - newCommand []string - ) if name == "" { name = imageName } @@ -201,8 +198,7 @@ func generateCommand(command, imageName, name, globalOpts string) ([]string, err if err != nil { return nil, err } - newCommand = append(newCommand, prog) - + newCommand := []string{prog} for _, arg := range cmd[1:] { var newArg string switch arg { @@ -234,7 +230,7 @@ func generateCommand(command, imageName, name, globalOpts string) ([]string, err // GenerateRunEnvironment merges the current environment variables with optional // environment variables provided by the user -func generateRunEnvironment(name, imageName string, options entities.ContainerRunlabelOptions) []string { +func generateRunEnvironment(options entities.ContainerRunlabelOptions) []string { newEnv := os.Environ() if options.Optional1 != "" { newEnv = append(newEnv, fmt.Sprintf("OPT1=%s", options.Optional1)) diff --git a/pkg/domain/infra/abi/cp.go b/pkg/domain/infra/abi/cp.go index 542813394..82b07e2e1 100644 --- a/pkg/domain/infra/abi/cp.go +++ b/pkg/domain/infra/abi/cp.go @@ -92,7 +92,7 @@ func (ic *ContainerEngine) ContainerCp(ctx context.Context, source, dest string, if isFromHostToCtr { if isVol, volDestName, volName := isVolumeDestName(destPath, ctr); isVol { //nolint(gocritic) - path, err := pathWithVolumeMount(ctr, ic.Libpod, volDestName, volName, destPath) + path, err := pathWithVolumeMount(ic.Libpod, volDestName, volName, destPath) if err != nil { return nil, errors.Wrapf(err, "error getting destination path from volume %s", volDestName) } @@ -126,7 +126,7 @@ func (ic *ContainerEngine) ContainerCp(ctx context.Context, source, dest string, } else { destOwner = idtools.IDPair{UID: os.Getuid(), GID: os.Getgid()} if isVol, volDestName, volName := isVolumeDestName(srcPath, ctr); isVol { //nolint(gocritic) - path, err := pathWithVolumeMount(ctr, ic.Libpod, volDestName, volName, srcPath) + path, err := pathWithVolumeMount(ic.Libpod, volDestName, volName, srcPath) if err != nil { return nil, errors.Wrapf(err, "error getting source path from volume %s", volDestName) } @@ -396,7 +396,7 @@ func isVolumeDestName(path string, ctr *libpod.Container) (bool, string, string) } // if SRCPATH or DESTPATH is from volume mount's destination -v or --mount type=volume, generates the path with volume mount point -func pathWithVolumeMount(ctr *libpod.Container, runtime *libpod.Runtime, volDestName, volName, path string) (string, error) { +func pathWithVolumeMount(runtime *libpod.Runtime, volDestName, volName, path string) (string, error) { destVolume, err := runtime.GetVolume(volName) if err != nil { return "", errors.Wrapf(err, "error getting volume destination %s", volName) diff --git a/pkg/domain/infra/abi/generate.go b/pkg/domain/infra/abi/generate.go index abb5e2911..8853303d5 100644 --- a/pkg/domain/infra/abi/generate.go +++ b/pkg/domain/infra/abi/generate.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "fmt" - "strings" "github.com/containers/libpod/libpod" "github.com/containers/libpod/libpod/define" @@ -16,165 +15,29 @@ import ( ) func (ic *ContainerEngine) GenerateSystemd(ctx context.Context, nameOrID string, options entities.GenerateSystemdOptions) (*entities.GenerateSystemdReport, error) { - opts := generate.Options{ - Files: options.Files, - New: options.New, - } - // First assume it's a container. - if info, found, err := ic.generateSystemdgenContainerInfo(nameOrID, nil, options); found && err != nil { - return nil, err - } else if found && err == nil { - output, err := generate.CreateContainerSystemdUnit(info, opts) - if err != nil { - return nil, err + ctr, ctrErr := ic.Libpod.LookupContainer(nameOrID) + if ctrErr == nil { + // Generate the unit for the container. + s, err := generate.ContainerUnit(ctr, options) + if err == nil { + return &entities.GenerateSystemdReport{Output: s}, nil } - return &entities.GenerateSystemdReport{Output: output}, nil - } - - // --new does not support pods. - if options.New { - return nil, errors.Errorf("error generating systemd unit files: cannot generate generic files for a pod") } - // We're either having a pod or garbage. + // If it's not a container, we either have a pod or garbage. pod, err := ic.Libpod.LookupPod(nameOrID) if err != nil { - return nil, err - } - - // Error out if the pod has no infra container, which we require to be the - // main service. - if !pod.HasInfraContainer() { - return nil, fmt.Errorf("error generating systemd unit files: Pod %q has no infra container", pod.Name()) + err = errors.Wrap(ctrErr, err.Error()) + return nil, errors.Wrapf(err, "%s does not refer to a container or pod", nameOrID) } - // Generate a systemdgen.ContainerInfo for the infra container. This - // ContainerInfo acts as the main service of the pod. - infraID, err := pod.InfraContainerID() - if err != nil { - return nil, nil - } - podInfo, _, err := ic.generateSystemdgenContainerInfo(infraID, pod, options) + // Generate the units for the pod and all its containers. + s, err := generate.PodUnits(pod, options) if err != nil { return nil, err } - - // Compute the container-dependency graph for the Pod. - containers, err := pod.AllContainers() - if err != nil { - return nil, err - } - if len(containers) == 0 { - return nil, fmt.Errorf("error generating systemd unit files: Pod %q has no containers", pod.Name()) - } - graph, err := libpod.BuildContainerGraph(containers) - if err != nil { - return nil, err - } - - // Traverse the dependency graph and create systemdgen.ContainerInfo's for - // each container. - containerInfos := []*generate.ContainerInfo{podInfo} - for ctr, dependencies := range graph.DependencyMap() { - // Skip the infra container as we already generated it. - if ctr.ID() == infraID { - continue - } - ctrInfo, _, err := ic.generateSystemdgenContainerInfo(ctr.ID(), nil, options) - if err != nil { - return nil, err - } - // Now add the container's dependencies and at the container as a - // required service of the infra container. - for _, dep := range dependencies { - if dep.ID() == infraID { - ctrInfo.BoundToServices = append(ctrInfo.BoundToServices, podInfo.ServiceName) - } else { - _, serviceName := generateServiceName(dep, nil, options) - ctrInfo.BoundToServices = append(ctrInfo.BoundToServices, serviceName) - } - } - podInfo.RequiredServices = append(podInfo.RequiredServices, ctrInfo.ServiceName) - containerInfos = append(containerInfos, ctrInfo) - } - - // Now generate the systemd service for all containers. - builder := strings.Builder{} - for i, info := range containerInfos { - if i > 0 { - builder.WriteByte('\n') - } - out, err := generate.CreateContainerSystemdUnit(info, opts) - if err != nil { - return nil, err - } - builder.WriteString(out) - } - - return &entities.GenerateSystemdReport{Output: builder.String()}, nil -} - -// generateSystemdgenContainerInfo is a helper to generate a -// systemdgen.ContainerInfo for `GenerateSystemd`. -func (ic *ContainerEngine) generateSystemdgenContainerInfo(nameOrID string, pod *libpod.Pod, options entities.GenerateSystemdOptions) (*generate.ContainerInfo, bool, error) { - ctr, err := ic.Libpod.LookupContainer(nameOrID) - if err != nil { - return nil, false, err - } - - timeout := ctr.StopTimeout() - if options.StopTimeout != nil { - timeout = *options.StopTimeout - } - - config := ctr.Config() - conmonPidFile := config.ConmonPidFile - if conmonPidFile == "" { - return nil, true, errors.Errorf("conmon PID file path is empty, try to recreate the container with --conmon-pidfile flag") - } - - createCommand := []string{} - if config.CreateCommand != nil { - createCommand = config.CreateCommand - } else if options.New { - return nil, true, errors.Errorf("cannot use --new on container %q: no create command found", nameOrID) - } - - name, serviceName := generateServiceName(ctr, pod, options) - info := &generate.ContainerInfo{ - ServiceName: serviceName, - ContainerName: name, - RestartPolicy: options.RestartPolicy, - PIDFile: conmonPidFile, - StopTimeout: timeout, - GenerateTimestamp: true, - CreateCommand: createCommand, - } - - return info, true, nil -} - -// generateServiceName generates the container name and the service name for systemd service. -func generateServiceName(ctr *libpod.Container, pod *libpod.Pod, options entities.GenerateSystemdOptions) (string, string) { - var kind, name, ctrName string - if pod == nil { - kind = options.ContainerPrefix //defaults to container - name = ctr.ID() - if options.Name { - name = ctr.Name() - } - ctrName = name - } else { - kind = options.PodPrefix //defaults to pod - name = pod.ID() - ctrName = ctr.ID() - if options.Name { - name = pod.Name() - ctrName = ctr.Name() - } - } - return ctrName, fmt.Sprintf("%s%s%s", kind, options.Separator, name) + return &entities.GenerateSystemdReport{Output: s}, nil } func (ic *ContainerEngine) GenerateKube(ctx context.Context, nameOrID string, options entities.GenerateKubeOptions) (*entities.GenerateKubeReport, error) { diff --git a/pkg/domain/infra/abi/healthcheck.go b/pkg/domain/infra/abi/healthcheck.go index 4e925ef56..dfa9a6fa5 100644 --- a/pkg/domain/infra/abi/healthcheck.go +++ b/pkg/domain/infra/abi/healthcheck.go @@ -7,8 +7,8 @@ import ( "github.com/containers/libpod/pkg/domain/entities" ) -func (ic *ContainerEngine) HealthCheckRun(ctx context.Context, nameOrId string, options entities.HealthCheckOptions) (*define.HealthCheckResults, error) { - status, err := ic.Libpod.HealthCheck(nameOrId) +func (ic *ContainerEngine) HealthCheckRun(ctx context.Context, nameOrID string, options entities.HealthCheckOptions) (*define.HealthCheckResults, error) { + status, err := ic.Libpod.HealthCheck(nameOrID) if err != nil { return nil, err } diff --git a/pkg/domain/infra/abi/images.go b/pkg/domain/infra/abi/images.go index d8af4d339..e630d9bc8 100644 --- a/pkg/domain/infra/abi/images.go +++ b/pkg/domain/infra/abi/images.go @@ -38,8 +38,8 @@ import ( // SignatureStoreDir defines default directory to store signatures const SignatureStoreDir = "/var/lib/containers/sigstore" -func (ir *ImageEngine) Exists(_ context.Context, nameOrId string) (*entities.BoolReport, error) { - _, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) +func (ir *ImageEngine) Exists(_ context.Context, nameOrID string) (*entities.BoolReport, error) { + _, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID) if err != nil && errors.Cause(err) != define.ErrNoSuchImage { return nil, err } @@ -65,8 +65,8 @@ func (ir *ImageEngine) pruneImagesHelper(ctx context.Context, all bool, filters return &report, nil } -func (ir *ImageEngine) History(ctx context.Context, nameOrId string, opts entities.ImageHistoryOptions) (*entities.ImageHistoryReport, error) { - image, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) +func (ir *ImageEngine) History(ctx context.Context, nameOrID string, opts entities.ImageHistoryOptions) (*entities.ImageHistoryReport, error) { + image, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID) if err != nil { return nil, err } @@ -167,7 +167,7 @@ func (ir *ImageEngine) Pull(ctx context.Context, rawImage string, options entiti return nil, errors.Wrapf(err, "error getting repository tags") } - var foundIDs []string + foundIDs := []string{} for _, tag := range tags { name := rawImage + ":" + tag newImage, err := ir.Libpod.ImageRuntime().New(ctx, name, options.SignaturePolicy, options.Authfile, writer, &dockerRegistryOptions, image.SigningOptions{}, nil, util.PullImageAlways) @@ -261,8 +261,8 @@ func (ir *ImageEngine) Push(ctx context.Context, source string, destination stri nil) } -// func (r *imageRuntime) Delete(ctx context.Context, nameOrId string, opts entities.ImageDeleteOptions) (*entities.ImageDeleteReport, error) { -// image, err := r.libpod.ImageEngine().NewFromLocal(nameOrId) +// func (r *imageRuntime) Delete(ctx context.Context, nameOrID string, opts entities.ImageDeleteOptions) (*entities.ImageDeleteReport, error) { +// image, err := r.libpod.ImageEngine().NewFromLocal(nameOrID) // if err != nil { // return nil, err // } @@ -292,8 +292,8 @@ func (ir *ImageEngine) Push(ctx context.Context, source string, destination stri // return &report, nil // } -func (ir *ImageEngine) Tag(ctx context.Context, nameOrId string, tags []string, options entities.ImageTagOptions) error { - newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) +func (ir *ImageEngine) Tag(ctx context.Context, nameOrID string, tags []string, options entities.ImageTagOptions) error { + newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID) if err != nil { return err } @@ -305,8 +305,8 @@ func (ir *ImageEngine) Tag(ctx context.Context, nameOrId string, tags []string, return nil } -func (ir *ImageEngine) Untag(ctx context.Context, nameOrId string, tags []string, options entities.ImageUntagOptions) error { - newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) +func (ir *ImageEngine) Untag(ctx context.Context, nameOrID string, tags []string, options entities.ImageUntagOptions) error { + newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID) if err != nil { return err } @@ -356,16 +356,16 @@ func (ir *ImageEngine) Import(ctx context.Context, opts entities.ImageImportOpti return &entities.ImageImportReport{Id: id}, nil } -func (ir *ImageEngine) Save(ctx context.Context, nameOrId string, tags []string, options entities.ImageSaveOptions) error { - newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrId) +func (ir *ImageEngine) Save(ctx context.Context, nameOrID string, tags []string, options entities.ImageSaveOptions) error { + newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID) if err != nil { return err } - return newImage.Save(ctx, nameOrId, options.Format, options.Output, tags, options.Quiet, options.Compress) + return newImage.Save(ctx, nameOrID, options.Format, options.Output, tags, options.Quiet, options.Compress) } -func (ir *ImageEngine) Diff(_ context.Context, nameOrId string, _ entities.DiffOptions) (*entities.DiffReport, error) { - changes, err := ir.Libpod.GetDiff("", nameOrId) +func (ir *ImageEngine) Diff(_ context.Context, nameOrID string, _ entities.DiffOptions) (*entities.DiffReport, error) { + changes, err := ir.Libpod.GetDiff("", nameOrID) if err != nil { return nil, err } @@ -420,8 +420,8 @@ 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) +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 } @@ -443,7 +443,7 @@ func removeErrorsToExitCode(rmErrors []error) int { // container. inUseErrors bool // otherErrors indicates that at least one error other than the two - // above occured. + // above occurred. otherErrors bool ) @@ -549,8 +549,7 @@ func (ir *ImageEngine) Remove(ctx context.Context, images []string, opts entitie rmErrors = append(rmErrors, err) } } - - return + return //nolint } // Shutdown Libpod engine diff --git a/pkg/domain/infra/abi/images_list.go b/pkg/domain/infra/abi/images_list.go index 3034e36ec..98c041c15 100644 --- a/pkg/domain/infra/abi/images_list.go +++ b/pkg/domain/infra/abi/images_list.go @@ -8,17 +8,12 @@ import ( ) func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions) ([]*entities.ImageSummary, error) { - var ( - images []*libpodImage.Image - err error - ) - - images, err = ir.Libpod.ImageRuntime().GetImagesWithFilters(opts.Filter) + images, err := ir.Libpod.ImageRuntime().GetImagesWithFilters(opts.Filter) if err != nil { return nil, err } - var summaries []*entities.ImageSummary + summaries := []*entities.ImageSummary{} for _, img := range images { var repoTags []string if opts.All { diff --git a/pkg/domain/infra/abi/manifest.go b/pkg/domain/infra/abi/manifest.go index a2b5fc0fc..a6f5bab6b 100644 --- a/pkg/domain/infra/abi/manifest.go +++ b/pkg/domain/infra/abi/manifest.go @@ -153,7 +153,7 @@ func (ir *ImageEngine) ManifestRemove(ctx context.Context, names []string) (stri } listImage, err := ir.Libpod.ImageRuntime().NewFromLocal(names[0]) if err != nil { - return "", errors.Wrapf(err, "error retriving local image from image name %s", names[0]) + return "", errors.Wrapf(err, "error retrieving local image from image name %s", names[0]) } updatedListID, err := listImage.RemoveManifest(instanceDigest) if err == nil { @@ -166,7 +166,7 @@ func (ir *ImageEngine) ManifestRemove(ctx context.Context, names []string) (stri func (ir *ImageEngine) ManifestPush(ctx context.Context, names []string, opts entities.ManifestPushOptions) error { listImage, err := ir.Libpod.ImageRuntime().NewFromLocal(names[0]) if err != nil { - return errors.Wrapf(err, "error retriving local image from image name %s", names[0]) + return errors.Wrapf(err, "error retrieving local image from image name %s", names[0]) } dest, err := alltransports.ParseImageName(names[1]) if err != nil { diff --git a/pkg/domain/infra/abi/network.go b/pkg/domain/infra/abi/network.go index 8e3515824..eba1af362 100644 --- a/pkg/domain/infra/abi/network.go +++ b/pkg/domain/infra/abi/network.go @@ -48,15 +48,12 @@ func (ic *ContainerEngine) NetworkList(ctx context.Context, options entities.Net } func (ic *ContainerEngine) NetworkInspect(ctx context.Context, namesOrIds []string, options entities.NetworkInspectOptions) ([]entities.NetworkInspectReport, error) { - var ( - rawCNINetworks []entities.NetworkInspectReport - ) - config, err := ic.Libpod.GetConfig() if err != nil { return nil, err } + rawCNINetworks := make([]entities.NetworkInspectReport, 0, len(namesOrIds)) for _, name := range namesOrIds { rawList, err := network.InspectNetwork(config, name) if err != nil { @@ -68,7 +65,7 @@ func (ic *ContainerEngine) NetworkInspect(ctx context.Context, namesOrIds []stri } func (ic *ContainerEngine) NetworkRm(ctx context.Context, namesOrIds []string, options entities.NetworkRmOptions) ([]*entities.NetworkRmReport, error) { - var reports []*entities.NetworkRmReport + reports := []*entities.NetworkRmReport{} config, err := ic.Libpod.GetConfig() if err != nil { diff --git a/pkg/domain/infra/abi/parse/parse.go b/pkg/domain/infra/abi/parse/parse.go index 6c0e1ee55..2320c6a32 100644 --- a/pkg/domain/infra/abi/parse/parse.go +++ b/pkg/domain/infra/abi/parse/parse.go @@ -12,7 +12,7 @@ import ( // Handle volume options from CLI. // Parse "o" option to find UID, GID. -func ParseVolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error) { +func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error) { libpodOptions := []libpod.VolumeCreateOption{} volumeOptions := make(map[string]string) diff --git a/pkg/domain/infra/abi/play.go b/pkg/domain/infra/abi/play.go index 6d0919d2b..7053cec9e 100644 --- a/pkg/domain/infra/abi/play.go +++ b/pkg/domain/infra/abi/play.go @@ -26,6 +26,7 @@ import ( "github.com/ghodss/yaml" "github.com/pkg/errors" "github.com/sirupsen/logrus" + v1apps "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" ) @@ -38,13 +39,7 @@ const ( func (ic *ContainerEngine) PlayKube(ctx context.Context, path string, options entities.PlayKubeOptions) (*entities.PlayKubeReport, error) { var ( - containers []*libpod.Container - pod *libpod.Pod - podOptions []libpod.PodCreateOption - podYAML v1.Pod - registryCreds *types.DockerAuthConfig - writer io.Writer - report entities.PlayKubeReport + kubeObject v1.ObjectReference ) content, err := ioutil.ReadFile(path) @@ -52,32 +47,91 @@ func (ic *ContainerEngine) PlayKube(ctx context.Context, path string, options en return nil, err } - if err := yaml.Unmarshal(content, &podYAML); err != nil { + if err := yaml.Unmarshal(content, &kubeObject); err != nil { return nil, errors.Wrapf(err, "unable to read %q as YAML", path) } // NOTE: pkg/bindings/play is also parsing the file. // A pkg/kube would be nice to refactor and abstract // parts of the K8s-related code. - if podYAML.Kind != "Pod" { - return nil, errors.Errorf("invalid YAML kind: %q. Pod is the only supported Kubernetes YAML kind", podYAML.Kind) + switch kubeObject.Kind { + case "Pod": + var podYAML v1.Pod + var podTemplateSpec v1.PodTemplateSpec + if err := yaml.Unmarshal(content, &podYAML); err != nil { + return nil, errors.Wrapf(err, "unable to read YAML %q as Kube Pod", path) + } + podTemplateSpec.ObjectMeta = podYAML.ObjectMeta + podTemplateSpec.Spec = podYAML.Spec + return ic.playKubePod(ctx, podTemplateSpec.ObjectMeta.Name, &podTemplateSpec, options) + case "Deployment": + var deploymentYAML v1apps.Deployment + if err := yaml.Unmarshal(content, &deploymentYAML); err != nil { + return nil, errors.Wrapf(err, "unable to read YAML %q as Kube Deployment", path) + } + return ic.playKubeDeployment(ctx, &deploymentYAML, options) + default: + return nil, errors.Errorf("invalid YAML kind: %q. [Pod|Deployment] are the only supported Kubernetes Kinds", kubeObject.Kind) + } + +} + +func (ic *ContainerEngine) playKubeDeployment(ctx context.Context, deploymentYAML *v1apps.Deployment, options entities.PlayKubeOptions) (*entities.PlayKubeReport, error) { + var ( + deploymentName string + podSpec v1.PodTemplateSpec + numReplicas int32 + i int32 + report entities.PlayKubeReport + ) + + deploymentName = deploymentYAML.ObjectMeta.Name + if deploymentName == "" { + return nil, errors.Errorf("Deployment does not have a name") + } + numReplicas = 1 + if deploymentYAML.Spec.Replicas != nil { + numReplicas = *deploymentYAML.Spec.Replicas + } + podSpec = deploymentYAML.Spec.Template + + // create "replicas" number of pods + for i = 0; i < numReplicas; i++ { + podName := fmt.Sprintf("%s-pod-%d", deploymentName, i) + podReport, err := ic.playKubePod(ctx, podName, &podSpec, options) + if err != nil { + return nil, errors.Wrapf(err, "Error encountered while bringing up pod %s", podName) + } + report.Pods = append(report.Pods, podReport.Pods...) } + return &report, nil +} + +func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podYAML *v1.PodTemplateSpec, options entities.PlayKubeOptions) (*entities.PlayKubeReport, error) { + var ( + pod *libpod.Pod + registryCreds *types.DockerAuthConfig + writer io.Writer + playKubePod entities.PlayKubePod + report entities.PlayKubeReport + ) // check for name collision between pod and container - podName := podYAML.ObjectMeta.Name if podName == "" { return nil, errors.Errorf("pod does not have a name") } for _, n := range podYAML.Spec.Containers { if n.Name == podName { - report.Logs = append(report.Logs, + playKubePod.Logs = append(playKubePod.Logs, fmt.Sprintf("a container exists with the same name (%q) as the pod in your YAML file; changing pod name to %s_pod\n", podName, podName)) podName = fmt.Sprintf("%s_pod", podName) } } - podOptions = append(podOptions, libpod.WithInfraContainer()) - podOptions = append(podOptions, libpod.WithPodName(podName)) + podOptions := []libpod.PodCreateOption{ + libpod.WithInfraContainer(), + libpod.WithPodName(podName), + } // TODO for now we just used the default kernel namespaces; we need to add/subtract this from yaml hostname := podYAML.Spec.Hostname @@ -217,6 +271,7 @@ func (ic *ContainerEngine) PlayKube(ctx context.Context, path string, options en return nil, err } + containers := make([]*libpod.Container, 0, len(podYAML.Spec.Containers)) for _, container := range podYAML.Spec.Containers { pullPolicy := util.PullImageMissing if len(container.ImagePullPolicy) > 0 { @@ -239,11 +294,11 @@ func (ic *ContainerEngine) PlayKube(ctx context.Context, path string, options en if err != nil { return nil, err } - conf, err := kubeContainerToCreateConfig(ctx, container, ic.Libpod, newImage, namespaces, volumes, pod.ID(), podInfraID, seccompPaths) + conf, err := kubeContainerToCreateConfig(ctx, container, newImage, namespaces, volumes, pod.ID(), podName, podInfraID, seccompPaths) if err != nil { return nil, err } - ctr, err := createconfig.CreateContainerFromCreateConfig(ic.Libpod, conf, ctx, pod) + ctr, err := createconfig.CreateContainerFromCreateConfig(ctx, ic.Libpod, conf, pod) if err != nil { return nil, err } @@ -259,11 +314,13 @@ func (ic *ContainerEngine) PlayKube(ctx context.Context, path string, options en } } - report.Pod = pod.ID() + playKubePod.ID = pod.ID() for _, ctr := range containers { - report.Containers = append(report.Containers, ctr.ID()) + playKubePod.Containers = append(playKubePod.Containers, ctr.ID()) } + report.Pods = append(report.Pods, playKubePod) + return &report, nil } @@ -351,7 +408,7 @@ func setupSecurityContext(securityConfig *createconfig.SecurityConfig, userConfi } // kubeContainerToCreateConfig takes a v1.Container and returns a createconfig describing a container -func kubeContainerToCreateConfig(ctx context.Context, containerYAML v1.Container, runtime *libpod.Runtime, newImage *image.Image, namespaces map[string]string, volumes map[string]string, podID, infraID string, seccompPaths *kubeSeccompPaths) (*createconfig.CreateConfig, error) { +func kubeContainerToCreateConfig(ctx context.Context, containerYAML v1.Container, newImage *image.Image, namespaces map[string]string, volumes map[string]string, podID, podName, infraID string, seccompPaths *kubeSeccompPaths) (*createconfig.CreateConfig, error) { var ( containerConfig createconfig.CreateConfig pidConfig createconfig.PidConfig @@ -368,7 +425,14 @@ func kubeContainerToCreateConfig(ctx context.Context, containerYAML v1.Container containerConfig.Image = containerYAML.Image containerConfig.ImageID = newImage.ID() - containerConfig.Name = containerYAML.Name + + // podName should be non-empty for Deployment objects to be able to create + // multiple pods having containers with unique names + if podName == "" { + return nil, errors.Errorf("kubeContainerToCreateConfig got empty podName") + } + containerConfig.Name = fmt.Sprintf("%s-%s", podName, containerYAML.Name) + containerConfig.Tty = containerYAML.TTY containerConfig.Pod = podID @@ -382,7 +446,10 @@ func kubeContainerToCreateConfig(ctx context.Context, containerYAML v1.Container setupSecurityContext(&securityConfig, &userConfig, containerYAML) - securityConfig.SeccompProfilePath = seccompPaths.findForContainer(containerConfig.Name) + // Since we prefix the container name with pod name to work-around the uniqueness requirement, + // the seccom profile should reference the actual container name from the YAML + // but apply to the containers with the prefixed name + securityConfig.SeccompProfilePath = seccompPaths.findForContainer(containerYAML.Name) containerConfig.Command = []string{} if imageData != nil && imageData.Config != nil { diff --git a/pkg/domain/infra/abi/pods.go b/pkg/domain/infra/abi/pods.go index 320880920..4a122f54d 100644 --- a/pkg/domain/infra/abi/pods.go +++ b/pkg/domain/infra/abi/pods.go @@ -45,8 +45,8 @@ func getPodsByContext(all, latest bool, pods []string, runtime *libpod.Runtime) return outpods, err } -func (ic *ContainerEngine) PodExists(ctx context.Context, nameOrId string) (*entities.BoolReport, error) { - _, err := ic.Libpod.LookupPod(nameOrId) +func (ic *ContainerEngine) PodExists(ctx context.Context, nameOrID string) (*entities.BoolReport, error) { + _, err := ic.Libpod.LookupPod(nameOrID) if err != nil && errors.Cause(err) != define.ErrNoSuchPod { return nil, err } @@ -54,9 +54,7 @@ func (ic *ContainerEngine) PodExists(ctx context.Context, nameOrId string) (*ent } func (ic *ContainerEngine) PodKill(ctx context.Context, namesOrIds []string, options entities.PodKillOptions) ([]*entities.PodKillReport, error) { - var ( - reports []*entities.PodKillReport - ) + reports := []*entities.PodKillReport{} sig, err := signal.ParseSignalNameOrNumber(options.Signal) if err != nil { return nil, err @@ -87,9 +85,7 @@ func (ic *ContainerEngine) PodKill(ctx context.Context, namesOrIds []string, opt } func (ic *ContainerEngine) PodPause(ctx context.Context, namesOrIds []string, options entities.PodPauseOptions) ([]*entities.PodPauseReport, error) { - var ( - reports []*entities.PodPauseReport - ) + reports := []*entities.PodPauseReport{} pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err @@ -114,9 +110,7 @@ func (ic *ContainerEngine) PodPause(ctx context.Context, namesOrIds []string, op } func (ic *ContainerEngine) PodUnpause(ctx context.Context, namesOrIds []string, options entities.PodunpauseOptions) ([]*entities.PodUnpauseReport, error) { - var ( - reports []*entities.PodUnpauseReport - ) + reports := []*entities.PodUnpauseReport{} pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err @@ -141,9 +135,7 @@ func (ic *ContainerEngine) PodUnpause(ctx context.Context, namesOrIds []string, } func (ic *ContainerEngine) PodStop(ctx context.Context, namesOrIds []string, options entities.PodStopOptions) ([]*entities.PodStopReport, error) { - var ( - reports []*entities.PodStopReport - ) + reports := []*entities.PodStopReport{} pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil && !(options.Ignore && errors.Cause(err) == define.ErrNoSuchPod) { return nil, err @@ -168,9 +160,7 @@ func (ic *ContainerEngine) PodStop(ctx context.Context, namesOrIds []string, opt } func (ic *ContainerEngine) PodRestart(ctx context.Context, namesOrIds []string, options entities.PodRestartOptions) ([]*entities.PodRestartReport, error) { - var ( - reports []*entities.PodRestartReport - ) + reports := []*entities.PodRestartReport{} pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err @@ -196,13 +186,12 @@ func (ic *ContainerEngine) PodRestart(ctx context.Context, namesOrIds []string, } func (ic *ContainerEngine) PodStart(ctx context.Context, namesOrIds []string, options entities.PodStartOptions) ([]*entities.PodStartReport, error) { - var ( - reports []*entities.PodStartReport - ) + reports := []*entities.PodStartReport{} pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil { return nil, err } + for _, p := range pods { report := entities.PodStartReport{Id: p.ID()} errs, err := p.Start(ctx) @@ -224,13 +213,11 @@ func (ic *ContainerEngine) PodStart(ctx context.Context, namesOrIds []string, op } func (ic *ContainerEngine) PodRm(ctx context.Context, namesOrIds []string, options entities.PodRmOptions) ([]*entities.PodRmReport, error) { - var ( - reports []*entities.PodRmReport - ) pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod) if err != nil && !(options.Ignore && errors.Cause(err) == define.ErrNoSuchPod) { return nil, err } + reports := make([]*entities.PodRmReport, 0, len(pods)) for _, p := range pods { report := entities.PodRmReport{Id: p.ID()} err := ic.Libpod.RemovePod(ctx, p, true, options.Force) @@ -247,13 +234,11 @@ func (ic *ContainerEngine) PodPrune(ctx context.Context, options entities.PodPru } func (ic *ContainerEngine) prunePodHelper(ctx context.Context) ([]*entities.PodPruneReport, error) { - var ( - reports []*entities.PodPruneReport - ) response, err := ic.Libpod.PrunePods(ctx) if err != nil { return nil, err } + reports := make([]*entities.PodPruneReport, 0, len(response)) for k, v := range response { reports = append(reports, &entities.PodPruneReport{ Err: v, @@ -298,9 +283,8 @@ func (ic *ContainerEngine) PodTop(ctx context.Context, options entities.PodTopOp func (ic *ContainerEngine) PodPs(ctx context.Context, options entities.PodPSOptions) ([]*entities.ListPodsReport, error) { var ( err error - filters []libpod.PodFilter - pds []*libpod.Pod - reports []*entities.ListPodsReport + filters = []libpod.PodFilter{} + pds = []*libpod.Pod{} ) for k, v := range options.Filters { @@ -326,6 +310,7 @@ func (ic *ContainerEngine) PodPs(ctx context.Context, options entities.PodPSOpti } } + reports := make([]*entities.ListPodsReport, 0, len(pds)) for _, p := range pds { var lpcs []*entities.ListPodContainer status, err := p.GetPodStatus() @@ -347,7 +332,7 @@ func (ic *ContainerEngine) PodPs(ctx context.Context, options entities.PodPSOpti Status: state.String(), }) } - infraId, err := p.InfraContainerID() + infraID, err := p.InfraContainerID() if err != nil { return nil, err } @@ -356,7 +341,7 @@ func (ic *ContainerEngine) PodPs(ctx context.Context, options entities.PodPSOpti Containers: lpcs, Created: p.CreatedTime(), Id: p.ID(), - InfraId: infraId, + InfraId: infraID, Name: p.Name(), Namespace: p.Namespace(), Status: status, diff --git a/pkg/domain/infra/abi/system.go b/pkg/domain/infra/abi/system.go index 9b538b301..90002326e 100644 --- a/pkg/domain/infra/abi/system.go +++ b/pkg/domain/infra/abi/system.go @@ -72,11 +72,9 @@ func (ic *ContainerEngine) SetupRootless(_ context.Context, cmd *cobra.Command) return err } unitName := fmt.Sprintf("podman-%d.scope", os.Getpid()) - if err := utils.RunUnderSystemdScope(os.Getpid(), "user.slice", unitName); err != nil { - if conf.Engine.CgroupManager == config.SystemdCgroupsManager { + if conf.Engine.CgroupManager == config.SystemdCgroupsManager { + if err := utils.RunUnderSystemdScope(os.Getpid(), "user.slice", unitName); err != nil { logrus.Warnf("Failed to add podman to systemd sandbox cgroup: %v", err) - } else { - logrus.Debugf("Failed to add podman to systemd sandbox cgroup: %v", err) } } } @@ -174,7 +172,7 @@ func checkInput() error { // nolint:deadcode,unused return nil } -// SystemPrune removes unsed data from the system. Pruning pods, containers, volumes and images. +// SystemPrune removes unused data from the system. Pruning pods, containers, volumes and images. func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.SystemPruneOptions) (*entities.SystemPruneReport, error) { var systemPruneReport = new(entities.SystemPruneReport) podPruneReport, err := ic.prunePodHelper(ctx) @@ -183,7 +181,7 @@ func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.Sys } systemPruneReport.PodPruneReport = podPruneReport - containerPruneReport, err := ic.pruneContainersHelper(ctx, nil) + containerPruneReport, err := ic.pruneContainersHelper(nil) if err != nil { return nil, err } @@ -214,10 +212,7 @@ func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.Sys func (ic *ContainerEngine) SystemDf(ctx context.Context, options entities.SystemDfOptions) (*entities.SystemDfReport, error) { var ( - dfImages []*entities.SystemDfImageReport - dfContainers []*entities.SystemDfContainerReport - dfVolumes []*entities.SystemDfVolumeReport - runningContainers []string + dfImages = []*entities.SystemDfImageReport{} ) // Get Images and iterate them @@ -284,6 +279,7 @@ func (ic *ContainerEngine) SystemDf(ctx context.Context, options entities.System if err != nil { return nil, err } + dfContainers := make([]*entities.SystemDfContainerReport, 0, len(cons)) for _, c := range cons { iid, _ := c.Image() conSize, err := c.RootFsSize() @@ -322,10 +318,12 @@ func (ic *ContainerEngine) SystemDf(ctx context.Context, options entities.System if err != nil { return nil, err } + runningContainers := make([]string, 0, len(running)) for _, c := range running { runningContainers = append(runningContainers, c.ID()) } + dfVolumes := make([]*entities.SystemDfVolumeReport, 0, len(vols)) for _, v := range vols { var consInUse int volSize, err := sizeOfPath(v.MountPoint()) @@ -338,7 +336,7 @@ func (ic *ContainerEngine) SystemDf(ctx context.Context, options entities.System } for _, viu := range inUse { if util.StringInSlice(viu, runningContainers) { - consInUse += 1 + consInUse++ } } report := entities.SystemDfVolumeReport{ @@ -376,12 +374,12 @@ func (se *SystemEngine) Renumber(ctx context.Context, flags *pflag.FlagSet, conf return nil } -func (s SystemEngine) Migrate(ctx context.Context, flags *pflag.FlagSet, config *entities.PodmanConfig, options entities.SystemMigrateOptions) error { +func (se SystemEngine) Migrate(ctx context.Context, flags *pflag.FlagSet, config *entities.PodmanConfig, options entities.SystemMigrateOptions) error { return nil } -func (s SystemEngine) Shutdown(ctx context.Context) { - if err := s.Libpod.Shutdown(false); err != nil { +func (se SystemEngine) Shutdown(ctx context.Context) { + if err := se.Libpod.Shutdown(false); err != nil { logrus.Error(err) } } diff --git a/pkg/domain/infra/abi/trust.go b/pkg/domain/infra/abi/trust.go index 5b89c91d9..03986ad0e 100644 --- a/pkg/domain/infra/abi/trust.go +++ b/pkg/domain/infra/abi/trust.go @@ -112,8 +112,8 @@ func (ir *ImageEngine) SetTrust(ctx context.Context, args []string, options enti return ioutil.WriteFile(policyPath, data, 0644) } -func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistriesDirPath string) ([]*trust.TrustPolicy, error) { - var output []*trust.TrustPolicy +func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistriesDirPath string) ([]*trust.Policy, error) { + var output []*trust.Policy registryConfigs, err := trust.LoadAndMergeConfig(systemRegistriesDirPath) if err != nil { @@ -121,7 +121,7 @@ func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistri } if len(policyContentStruct.Default) > 0 { - defaultPolicyStruct := trust.TrustPolicy{ + defaultPolicyStruct := trust.Policy{ Name: "* (default)", RepoName: "default", Type: trustTypeDescription(policyContentStruct.Default[0].Type), @@ -130,7 +130,7 @@ func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistri } for _, transval := range policyContentStruct.Transports { for repo, repoval := range transval { - tempTrustShowOutput := trust.TrustPolicy{ + tempTrustShowOutput := trust.Policy{ Name: repo, RepoName: repo, Type: repoval[0].Type, diff --git a/pkg/domain/infra/abi/volumes.go b/pkg/domain/infra/abi/volumes.go index 91b2440df..702e11003 100644 --- a/pkg/domain/infra/abi/volumes.go +++ b/pkg/domain/infra/abi/volumes.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" ) -func (ic *ContainerEngine) VolumeCreate(ctx context.Context, opts entities.VolumeCreateOptions) (*entities.IdOrNameResponse, error) { +func (ic *ContainerEngine) VolumeCreate(ctx context.Context, opts entities.VolumeCreateOptions) (*entities.IDOrNameResponse, error) { var ( volumeOptions []libpod.VolumeCreateOption ) @@ -24,7 +24,7 @@ func (ic *ContainerEngine) VolumeCreate(ctx context.Context, opts entities.Volum volumeOptions = append(volumeOptions, libpod.WithVolumeLabels(opts.Label)) } if len(opts.Options) > 0 { - parsedOptions, err := parse.ParseVolumeOptions(opts.Options) + parsedOptions, err := parse.VolumeOptions(opts.Options) if err != nil { return nil, err } @@ -34,15 +34,16 @@ func (ic *ContainerEngine) VolumeCreate(ctx context.Context, opts entities.Volum if err != nil { return nil, err } - return &entities.IdOrNameResponse{IdOrName: vol.Name()}, nil + return &entities.IDOrNameResponse{IDOrName: vol.Name()}, nil } func (ic *ContainerEngine) VolumeRm(ctx context.Context, namesOrIds []string, opts entities.VolumeRmOptions) ([]*entities.VolumeRmReport, error) { var ( err error - reports []*entities.VolumeRmReport vols []*libpod.Volume + reports = []*entities.VolumeRmReport{} ) + if opts.All { vols, err = ic.Libpod.Volumes() if err != nil { @@ -72,9 +73,8 @@ func (ic *ContainerEngine) VolumeRm(ctx context.Context, namesOrIds []string, op func (ic *ContainerEngine) VolumeInspect(ctx context.Context, namesOrIds []string, opts entities.VolumeInspectOptions) ([]*entities.VolumeInspectReport, error) { var ( - err error - reports []*entities.VolumeInspectReport - vols []*libpod.Volume + err error + vols []*libpod.Volume ) // Note: as with previous implementation, a single failure here @@ -93,6 +93,7 @@ func (ic *ContainerEngine) VolumeInspect(ctx context.Context, namesOrIds []strin vols = append(vols, vol) } } + reports := make([]*entities.VolumeInspectReport, 0, len(vols)) for _, v := range vols { config := entities.VolumeConfigResponse{ Name: v.Name(), @@ -115,13 +116,11 @@ func (ic *ContainerEngine) VolumePrune(ctx context.Context, opts entities.Volume } func (ic *ContainerEngine) pruneVolumesHelper(ctx context.Context) ([]*entities.VolumePruneReport, error) { - var ( - reports []*entities.VolumePruneReport - ) pruned, err := ic.Libpod.PruneVolumes(ctx) if err != nil { return nil, err } + reports := make([]*entities.VolumePruneReport, 0, len(pruned)) for k, v := range pruned { reports = append(reports, &entities.VolumePruneReport{ Err: v, @@ -132,9 +131,6 @@ func (ic *ContainerEngine) pruneVolumesHelper(ctx context.Context) ([]*entities. } func (ic *ContainerEngine) VolumeList(ctx context.Context, opts entities.VolumeListOptions) ([]*entities.VolumeListReport, error) { - var ( - reports []*entities.VolumeListReport - ) volumeFilters, err := filters.GenerateVolumeFilters(opts.Filter) if err != nil { return nil, err @@ -143,6 +139,7 @@ func (ic *ContainerEngine) VolumeList(ctx context.Context, opts entities.VolumeL if err != nil { return nil, err } + reports := make([]*entities.VolumeListReport, 0, len(vols)) for _, v := range vols { config := entities.VolumeConfigResponse{ Name: v.Name(), |