Merge pull request #14299 from cdoern/podClone

implement podman pod clone
This commit is contained in:
openshift-ci[bot] 2022-06-16 20:05:27 +00:00 committed by GitHub
commit 2af8851787
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 908 additions and 20 deletions

View File

@ -1607,8 +1607,14 @@ func AutocompleteClone(cmd *cobra.Command, args []string, toComplete string) ([]
}
switch len(args) {
case 0:
if cmd.Parent().Name() == "pod" { // needs to be " pod " to exclude 'podman'
return getPods(cmd, toComplete, completeDefault)
}
return getContainers(cmd, toComplete, completeDefault)
case 2:
if cmd.Parent().Name() == "pod" {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getImages(cmd, toComplete)
}
return nil, cobra.ShellCompDirectiveNoFileComp

View File

@ -98,7 +98,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
cgroupsFlagName := "cgroups"
createFlags.StringVar(
&cf.CgroupsMode,
cgroupsFlagName, cgroupConfig(),
cgroupsFlagName, cf.CgroupsMode,
`control container cgroup configuration ("enabled"|"disabled"|"no-conmon"|"split")`,
)
_ = cmd.RegisterFlagCompletionFunc(cgroupsFlagName, AutocompleteCgroupMode)
@ -150,7 +150,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
envFlagName := "env"
createFlags.StringArrayP(
envFlagName, "e", env(),
envFlagName, "e", Env(),
"Set environment variables in container",
)
_ = cmd.RegisterFlagCompletionFunc(envFlagName, completion.AutocompleteNone)
@ -256,7 +256,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
imageVolumeFlagName := "image-volume"
createFlags.String(
imageVolumeFlagName, containerConfig.Engine.ImageVolumeMode,
imageVolumeFlagName, cf.ImageVolume,
`Tells podman how to handle the builtin image volumes ("bind"|"tmpfs"|"ignore")`,
)
_ = cmd.RegisterFlagCompletionFunc(imageVolumeFlagName, AutocompleteImageVolume)
@ -298,7 +298,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
logDriverFlagName := "log-driver"
createFlags.StringVar(
&cf.LogDriver,
logDriverFlagName, LogDriver(),
logDriverFlagName, cf.LogDriver,
"Logging driver for the container",
)
_ = cmd.RegisterFlagCompletionFunc(logDriverFlagName, AutocompleteLogDriver)
@ -389,7 +389,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
pullFlagName := "pull"
createFlags.StringVar(
&cf.Pull,
pullFlagName, policy(),
pullFlagName, cf.Pull,
`Pull image before creating ("always"|"missing"|"never")`,
)
_ = cmd.RegisterFlagCompletionFunc(pullFlagName, AutocompletePullOption)
@ -406,7 +406,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
)
createFlags.BoolVar(
&cf.ReadOnlyTmpFS,
"read-only-tmpfs", true,
"read-only-tmpfs", cf.ReadOnlyTmpFS,
"When running containers in read-only mode mount a read-write tmpfs on /run, /tmp and /var/tmp",
)
requiresFlagName := "requires"
@ -439,7 +439,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
sdnotifyFlagName := "sdnotify"
createFlags.StringVar(
&cf.SdNotifyMode,
sdnotifyFlagName, define.SdNotifyModeContainer,
sdnotifyFlagName, cf.SdNotifyMode,
`control sd-notify behavior ("container"|"conmon"|"ignore")`,
)
_ = cmd.RegisterFlagCompletionFunc(sdnotifyFlagName, AutocompleteSDNotify)
@ -470,7 +470,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
stopTimeoutFlagName := "stop-timeout"
createFlags.UintVar(
&cf.StopTimeout,
stopTimeoutFlagName, containerConfig.Engine.StopTimeout,
stopTimeoutFlagName, cf.StopTimeout,
"Timeout (in seconds) that containers stopped by user command have to exit. If exceeded, the container will be forcibly stopped via SIGKILL.",
)
_ = cmd.RegisterFlagCompletionFunc(stopTimeoutFlagName, completion.AutocompleteNone)
@ -478,7 +478,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
systemdFlagName := "systemd"
createFlags.StringVar(
&cf.Systemd,
systemdFlagName, "true",
systemdFlagName, cf.Systemd,
`Run container in systemd mode ("true"|"false"|"always")`,
)
_ = cmd.RegisterFlagCompletionFunc(systemdFlagName, AutocompleteSystemdFlag)
@ -522,7 +522,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
timezoneFlagName := "tz"
createFlags.StringVar(
&cf.Timezone,
timezoneFlagName, containerConfig.TZ(),
timezoneFlagName, cf.Timezone,
"Set timezone in container",
)
_ = cmd.RegisterFlagCompletionFunc(timezoneFlagName, completion.AutocompleteNone) //TODO: add timezone completion
@ -530,7 +530,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
umaskFlagName := "umask"
createFlags.StringVar(
&cf.Umask,
umaskFlagName, containerConfig.Umask(),
umaskFlagName, cf.Umask,
"Set umask in container",
)
_ = cmd.RegisterFlagCompletionFunc(umaskFlagName, completion.AutocompleteNone)
@ -538,7 +538,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
ulimitFlagName := "ulimit"
createFlags.StringSliceVar(
&cf.Ulimit,
ulimitFlagName, ulimits(),
ulimitFlagName, cf.Ulimit,
"Ulimit options",
)
_ = cmd.RegisterFlagCompletionFunc(ulimitFlagName, completion.AutocompleteNone)
@ -577,7 +577,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
seccompPolicyFlagName := "seccomp-policy"
createFlags.StringVar(
&cf.SeccompPolicy,
seccompPolicyFlagName, "default",
seccompPolicyFlagName, cf.SeccompPolicy,
"Policy for selecting a seccomp profile (experimental)",
)
_ = cmd.RegisterFlagCompletionFunc(seccompPolicyFlagName, completion.AutocompleteDefault)
@ -769,7 +769,7 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
volumeFlagName := "volume"
createFlags.StringArrayVarP(
&cf.Volume,
volumeFlagName, "v", volumes(),
volumeFlagName, "v", cf.Volume,
volumeDesciption,
)
_ = cmd.RegisterFlagCompletionFunc(volumeFlagName, AutocompleteVolumeFlag)
@ -890,12 +890,13 @@ func DefineCreateFlags(cmd *cobra.Command, cf *entities.ContainerCreateOptions,
memorySwappinessFlagName := "memory-swappiness"
createFlags.Int64Var(
&cf.MemorySwappiness,
memorySwappinessFlagName, -1,
memorySwappinessFlagName, cf.MemorySwappiness,
"Tune container memory swappiness (0 to 100, or -1 for system default)",
)
_ = cmd.RegisterFlagCompletionFunc(memorySwappinessFlagName, completion.AutocompleteNone)
}
// anyone can use these
cpusFlagName := "cpus"
createFlags.Float64Var(
&cf.CPUS,

View File

@ -2,6 +2,8 @@ package common
import (
"github.com/containers/podman/v4/cmd/podman/registry"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/domain/entities"
)
func ulimits() []string {
@ -25,7 +27,7 @@ func devices() []string {
return nil
}
func env() []string {
func Env() []string {
if !registry.IsRemote() {
return containerConfig.Env()
}
@ -73,3 +75,21 @@ func LogDriver() string {
}
return ""
}
// DefineCreateDefault is used to initialize ctr create options before flag initialization
func DefineCreateDefaults(opts *entities.ContainerCreateOptions) {
opts.LogDriver = LogDriver()
opts.CgroupsMode = cgroupConfig()
opts.MemorySwappiness = -1
opts.ImageVolume = containerConfig.Engine.ImageVolumeMode
opts.Pull = policy()
opts.ReadOnlyTmpFS = true
opts.SdNotifyMode = define.SdNotifyModeContainer
opts.StopTimeout = containerConfig.Engine.StopTimeout
opts.Systemd = "true"
opts.Timezone = containerConfig.TZ()
opts.Umask = containerConfig.Umask()
opts.Ulimit = ulimits()
opts.SeccompPolicy = "default"
opts.Volume = volumes()
}

View File

@ -41,6 +41,7 @@ func cloneFlags(cmd *cobra.Command) {
forceFlagName := "force"
flags.BoolVarP(&ctrClone.Force, forceFlagName, "f", false, "force the existing container to be destroyed")
common.DefineCreateDefaults(&ctrClone.CreateOpts)
common.DefineCreateFlags(cmd, &ctrClone.CreateOpts, false, true)
}
func init() {

View File

@ -71,6 +71,7 @@ func createFlags(cmd *cobra.Command) {
)
flags.SetInterspersed(false)
common.DefineCreateDefaults(&cliVals)
common.DefineCreateFlags(cmd, &cliVals, false, false)
common.DefineNetFlags(cmd)

View File

@ -61,6 +61,7 @@ func runFlags(cmd *cobra.Command) {
flags := cmd.Flags()
flags.SetInterspersed(false)
common.DefineCreateDefaults(&cliVals)
common.DefineCreateFlags(cmd, &cliVals, false, false)
common.DefineNetFlags(cmd)

87
cmd/podman/pods/clone.go Normal file
View File

@ -0,0 +1,87 @@
package pods
import (
"context"
"fmt"
"github.com/containers/common/pkg/completion"
"github.com/containers/podman/v4/cmd/podman/common"
"github.com/containers/podman/v4/cmd/podman/registry"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
podCloneDescription = `Create an exact copy of a pod and the containers within it`
podCloneCommand = &cobra.Command{
Use: "clone [options] POD NAME",
Short: "Clone an existing pod",
Long: podCloneDescription,
RunE: clone,
Args: cobra.RangeArgs(1, 2),
ValidArgsFunction: common.AutocompleteClone,
Example: `podman pod clone pod_name new_name`,
}
)
var (
podClone entities.PodCloneOptions
)
func cloneFlags(cmd *cobra.Command) {
flags := cmd.Flags()
destroyFlagName := "destroy"
flags.BoolVar(&podClone.Destroy, destroyFlagName, false, "destroy the original pod")
startFlagName := "start"
flags.BoolVar(&podClone.Start, startFlagName, false, "start the new pod")
nameFlagName := "name"
flags.StringVarP(&podClone.CreateOpts.Name, nameFlagName, "n", "", "name the new pod")
_ = podCloneCommand.RegisterFlagCompletionFunc(nameFlagName, completion.AutocompleteNone)
common.DefineCreateDefaults(&podClone.InfraOptions)
common.DefineCreateFlags(cmd, &podClone.InfraOptions, true, false)
podClone.InfraOptions.MemorySwappiness = -1 // this is not implemented for pods yet, need to set -1 default manually
// need to fill an empty ctr create option for each container for sane defaults
// for now, these cannot be used. The flag names conflict too much
// this makes sense since this is a pod command not a container command
// TODO: add support for container specific arguments/flags
common.DefineCreateDefaults(&podClone.PerContainerOptions)
}
func init() {
registry.Commands = append(registry.Commands, registry.CliCommand{
Command: podCloneCommand,
Parent: podCmd,
})
cloneFlags(podCloneCommand)
}
func clone(cmd *cobra.Command, args []string) error {
switch len(args) {
case 0:
return errors.Wrapf(define.ErrInvalidArg, "must specify at least 1 argument")
case 2:
podClone.CreateOpts.Name = args[1]
}
podClone.ID = args[0]
podClone.PerContainerOptions.IsClone = true
rep, err := registry.ContainerEngine().PodClone(context.Background(), podClone)
if err != nil {
if rep != nil {
fmt.Printf("pod %s created but error after creation\n", rep.Id)
}
return err
}
fmt.Println(rep.Id)
return nil
}

View File

@ -64,6 +64,7 @@ func init() {
})
flags := createCommand.Flags()
flags.SetInterspersed(false)
common.DefineCreateDefaults(&infraOptions)
common.DefineCreateFlags(createCommand, &infraOptions, true, false)
common.DefineNetFlags(createCommand)

View File

@ -0,0 +1,418 @@
% podman-pod-clone(1)
## NAME
podman\-pod\-clone - Creates a copy of an existing pod
## SYNOPSIS
**podman pod clone** [*options*] *pod* *name*
## DESCRIPTION
**podman pod clone** creates a copy of a pod, recreating the identical config for the pod and for all of its containers. Users can modify the pods new name and select pod details within the infra container
## OPTIONS
#### **--cgroup-parent**=*path*
Path to cgroups under which the cgroup for the pod will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist.
#### **--cpus**
Set a number of CPUs for the pod that overrides the original pods CPU limits. If none are specified, the original pod's Nano CPUs are used.
#### **--cpuset-cpus**
CPUs in which to allow execution (0-3, 0,1). If none are specified, the original pod's CPUset is used.
#### **--destroy**
Remove the original pod that we are cloning once used to mimic the configuration.
#### **--device**=_host-device_[**:**_container-device_][**:**_permissions_]
Add a host device to the pod. Optional *permissions* parameter
can be used to specify device permissions. It is a combination of
**r** for read, **w** for write, and **m** for **mknod**(2).
Example: **--device=/dev/sdc:/dev/xvdc:rwm**.
Note: if _host_device_ is a symbolic link then it will be resolved first.
The pod will only store the major and minor numbers of the host device.
Note: the pod implements devices by storing the initial configuration passed by the user and recreating the device on each container added to the pod.
Podman may load kernel modules required for using the specified
device. The devices that Podman will load modules for when necessary are:
/dev/fuse.
#### **--device-read-bps**=*path*
Limit read rate (bytes per second) from a device (e.g. --device-read-bps=/dev/sda:1mb).
#### **--gidmap**=*pod_gid:host_gid:amount*
GID map for the user namespace. Using this flag will run all containers in the pod with user namespace enabled. It conflicts with the `--userns` and `--subgidname` flags.
#### **--help**, **-h**
Print usage statement.
#### **--hostname**=name
Set a hostname to the pod.
#### **--infra-command**=*command*
The command that will be run to start the infra container. Default: "/pause".
#### **--infra-conmon-pidfile**=*file*
Write the pid of the infra container's **conmon** process to a file. As **conmon** runs in a separate process than Podman, this is necessary when using systemd to manage Podman containers and pods.
#### **--infra-name**=*name*
The name that will be used for the pod's infra container.
#### **--label**=*label*, **-l**
Add metadata to a pod (e.g., --label com.example.key=value).
#### **--label-file**=*label*
Read in a line delimited file of labels.
#### **--name**, **-n**
Set a custom name for the cloned pod. The default if not specified is of the syntax: **<ORIGINAL_NAME>-clone**
#### **--pid**=*pid*
Set the PID mode for the pod. The default is to create a private PID namespace for the pod. Requires the PID namespace to be shared via --share.
host: use the hosts PID namespace for the pod
ns: join the specified PID namespace
private: create a new namespace for the pod (default)
#### **--security-opt**=*option*
Security Options
- `apparmor=unconfined` : Turn off apparmor confinement for the pod
- `apparmor=your-profile` : Set the apparmor confinement profile for the pod
- `label=user:USER` : Set the label user for the pod processes
- `label=role:ROLE` : Set the label role for the pod processes
- `label=type:TYPE` : Set the label process type for the pod processes
- `label=level:LEVEL` : Set the label level for the pod processes
- `label=filetype:TYPE` : Set the label file type for the pod files
- `label=disable` : Turn off label separation for the pod
Note: Labeling can be disabled for all pods/containers by setting label=false in the **containers.conf** (`/etc/containers/containers.conf` or `$HOME/.config/containers/containers.conf`) file.
- `mask=/path/1:/path/2` : The paths to mask separated by a colon. A masked path
cannot be accessed inside the containers within the pod.
- `no-new-privileges` : Disable container processes from gaining additional privileges.
- `seccomp=unconfined` : Turn off seccomp confinement for the pod
- `seccomp=profile.json` : Whitelisted syscalls seccomp Json file to be used as a seccomp filter
- `proc-opts=OPTIONS` : Comma-separated list of options to use for the /proc mount. More details for the
possible mount options are specified in the **proc(5)** man page.
- **unmask**=_ALL_ or _/path/1:/path/2_, or shell expanded paths (/proc/*): Paths to unmask separated by a colon. If set to **ALL**, it will unmask all the paths that are masked or made read only by default.
The default masked paths are **/proc/acpi, /proc/kcore, /proc/keys, /proc/latency_stats, /proc/sched_debug, /proc/scsi, /proc/timer_list, /proc/timer_stats, /sys/firmware, and /sys/fs/selinux.** The default paths that are read only are **/proc/asound, /proc/bus, /proc/fs, /proc/irq, /proc/sys, /proc/sysrq-trigger, /sys/fs/cgroup**.
Note: Labeling can be disabled for all containers by setting label=false in the **containers.conf** (`/etc/containers/containers.conf` or `$HOME/.config/containers/containers.conf`) file.
#### **--start**
When set to true, this flag starts the newly created pod after the
clone process has completed. All containers within the pod are started.
#### **--subgidname**=*name*
Name for GID map from the `/etc/subgid` file. Using this flag will run the container with user namespace enabled. This flag conflicts with `--userns` and `--gidmap`.
#### **--subuidname**=*name*
Name for UID map from the `/etc/subuid` file. Using this flag will run the container with user namespace enabled. This flag conflicts with `--userns` and `--uidmap`.
#### **--sysctl**=_name_=_value_
Configure namespace kernel parameters for all containers in the new pod.
For the IPC namespace, the following sysctls are allowed:
- kernel.msgmax
- kernel.msgmnb
- kernel.msgmni
- kernel.sem
- kernel.shmall
- kernel.shmmax
- kernel.shmmni
- kernel.shm_rmid_forced
- Sysctls beginning with fs.mqueue.\*
Note: if the ipc namespace is not shared within the pod, these sysctls are not allowed.
For the network namespace, only sysctls beginning with net.\* are allowed.
Note: if the network namespace is not shared within the pod, these sysctls are not allowed.
#### **--uidmap**=*container_uid*:*from_uid*:*amount*
Run all containers in the pod in a new user namespace using the supplied mapping. This
option conflicts with the **--userns** and **--subuidname** options. This
option provides a way to map host UIDs to container UIDs. It can be passed
several times to map different ranges.
#### **--userns**=*mode*
Set the user namespace mode for all the containers in a pod. It defaults to the **PODMAN_USERNS** environment variable. An empty value ("") means user namespaces are disabled.
Rootless user --userns=Key mappings:
Key | Host User | Container User
----------|---------------|---------------------
"" |$UID |0 (Default User account mapped to root user in container.)
keep-id |$UID |$UID (Map user account to same UID within container.)
auto |$UID | nil (Host User UID is not mapped into container.)
nomap |$UID | nil (Host User UID is not mapped into container.)
Valid _mode_ values are:
- *auto[:*_OPTIONS,..._*]*: automatically create a namespace. It is possible to specify these options to `auto`:
- *gidmapping=*_CONTAINER_GID:HOST_GID:SIZE_ to force a GID mapping to be present in the user namespace.
- *size=*_SIZE_: to specify an explicit size for the automatic user namespace. e.g. `--userns=auto:size=8192`. If `size` is not specified, `auto` will estimate a size for the user namespace.
- *uidmapping=*_CONTAINER_UID:HOST_UID:SIZE_ to force a UID mapping to be present in the user namespace.
- *host*: run in the user namespace of the caller. The processes running in the container will have the same privileges on the host as any other process launched by the calling user (default).
- *keep-id*: creates a user namespace where the current rootless user's UID:GID are mapped to the same values in the container. This option is ignored for containers created by the root user.
- *nomap*: creates a user namespace where the current rootless user's UID:GID are not mapped into the container. This option is ignored for containers created by the root user.
#### **--volume**, **-v**[=*[[SOURCE-VOLUME|HOST-DIR:]CONTAINER-DIR[:OPTIONS]]*]
Create a bind mount. If ` -v /HOST-DIR:/CONTAINER-DIR` is specified, Podman
bind mounts `/HOST-DIR` in the host to `/CONTAINER-DIR` in the Podman
container. Similarly, `-v SOURCE-VOLUME:/CONTAINER-DIR` will mount the volume
in the host to the container. If no such named volume exists, Podman will
create one. The `OPTIONS` are a comma-separated list and can be: <sup>[[1]](#Footnote1)</sup> (Note when using the remote client, including Mac and Windows (excluding WSL2) machines, the volumes will be mounted from the remote server, not necessarily the client machine.)
The _options_ is a comma-separated list and can be:
* **rw**|**ro**
* **z**|**Z**
* [**r**]**shared**|[**r**]**slave**|[**r**]**private**[**r**]**unbindable**
* [**r**]**bind**
* [**no**]**exec**
* [**no**]**dev**
* [**no**]**suid**
* [**O**]
* [**U**]
The `CONTAINER-DIR` must be an absolute path such as `/src/docs`. The volume
will be mounted into the container at this directory.
Volumes may specify a source as well, as either a directory on the host
or the name of a named volume. If no source is given, the volume will be created as an
anonymously named volume with a randomly generated name, and will be removed when
the pod is removed via the `--rm` flag or `podman rm --volumes` commands.
If a volume source is specified, it must be a path on the host or the name of a
named volume. Host paths are allowed to be absolute or relative; relative paths
are resolved relative to the directory Podman is run in. If the source does not
exist, Podman will return an error. Users must pre-create the source files or
directories.
Any source that does not begin with a `.` or `/` will be treated as the name of
a named volume. If a volume with that name does not exist, it will be created.
Volumes created with names are not anonymous, and they are not removed by the `--rm`
option and the `podman rm --volumes` command.
Specify multiple **-v** options to mount one or more volumes into a
pod.
`Write Protected Volume Mounts`
Add `:ro` or `:rw` suffix to a volume to mount it read-only or
read-write mode, respectively. By default, the volumes are mounted read-write.
See examples.
`Chowning Volume Mounts`
By default, Podman does not change the owner and group of source volume
directories mounted into containers. If a pod is created in a new user
namespace, the UID and GID in the container may correspond to another UID and
GID on the host.
The `:U` suffix tells Podman to use the correct host UID and GID based on the
UID and GID within the pod, to change recursively the owner and group of
the source volume.
**Warning** use with caution since this will modify the host filesystem.
`Labeling Volume Mounts`
Labeling systems like SELinux require that proper labels are placed on volume
content mounted into a pod. Without a label, the security system might
prevent the processes running inside the pod from using the content. By
default, Podman does not change the labels set by the OS.
To change a label in the pod context, add either of two suffixes
`:z` or `:Z` to the volume mount. These suffixes tell Podman to relabel file
objects on the shared volumes. The `z` option tells Podman that two pods
share the volume content. As a result, Podman labels the content with a shared
content label. Shared volume labels allow all containers to read/write content.
The `Z` option tells Podman to label the content with a private unshared label.
Only the current pod can use a private volume.
`Overlay Volume Mounts`
The `:O` flag tells Podman to mount the directory from the host as a
temporary storage using the `overlay file system`. The pod processes
can modify content within the mountpoint which is stored in the
container storage in a separate directory. In overlay terms, the source
directory will be the lower, and the container storage directory will be the
upper. Modifications to the mount point are destroyed when the pod
finishes executing, similar to a tmpfs mount point being unmounted.
Subsequent executions of the container will see the original source directory
content, any changes from previous pod executions no longer exist.
One use case of the overlay mount is sharing the package cache from the
host into the container to allow speeding up builds.
Note:
- The `O` flag conflicts with other options listed above.
Content mounted into the container is labeled with the private label.
On SELinux systems, labels in the source directory must be readable
by the infra container label. Usually containers can read/execute `container_share_t`
and can read/write `container_file_t`. If unable to change the labels on a
source volume, SELinux container separation must be disabled for the infra container/pod
to work.
- The source directory mounted into the pod with an overlay mount
should not be modified, it can cause unexpected failures. It is recommended
to not modify the directory until the container finishes running.
`Mounts propagation`
By default bind mounted volumes are `private`. That means any mounts done
inside pod will not be visible on host and vice versa. One can change
this behavior by specifying a volume mount propagation property. Making a
volume `shared` mounts done under that volume inside pod will be
visible on host and vice versa. Making a volume `slave` enables only one
way mount propagation and that is mounts done on host under that volume
will be visible inside container but not the other way around. <sup>[[1]](#Footnote1)</sup>
To control mount propagation property of a volume one can use the [**r**]**shared**,
[**r**]**slave**, [**r**]**private** or the [**r**]**unbindable** propagation flag.
Propagation property can be specified only for bind mounted volumes and not for
internal volumes or named volumes. For mount propagation to work the source mount
point (the mount point where source dir is mounted on) has to have the right propagation
properties. For shared volumes, the source mount point has to be shared. And for
slave volumes, the source mount point has to be either shared or slave.
<sup>[[1]](#Footnote1)</sup>
To recursively mount a volume and all of its submounts into a
pod, use the `rbind` option. By default the bind option is
used, and submounts of the source directory will not be mounted into the
pod.
Mounting the volume with the `nosuid` options means that SUID applications on
the volume will not be able to change their privilege. By default volumes
are mounted with `nosuid`.
Mounting the volume with the noexec option means that no executables on the
volume will be able to executed within the pod.
Mounting the volume with the nodev option means that no devices on the volume
will be able to be used by processes within the pod. By default volumes
are mounted with `nodev`.
If the `<source-dir>` is a mount point, then "dev", "suid", and "exec" options are
ignored by the kernel.
Use `df <source-dir>` to figure out the source mount and then use
`findmnt -o TARGET,PROPAGATION <source-mount-dir>` to figure out propagation
properties of source mount. If `findmnt` utility is not available, then one
can look at the mount entry for the source mount point in `/proc/self/mountinfo`. Look
at `optional fields` and see if any propagation properties are specified.
`shared:X` means mount is `shared`, `master:X` means mount is `slave` and if
nothing is there that means mount is `private`. <sup>[[1]](#Footnote1)</sup>
To change propagation properties of a mount point use `mount` command. For
example, if one wants to bind mount source directory `/foo` one can do
`mount --bind /foo /foo` and `mount --make-private --make-shared /foo`. This
will convert /foo into a `shared` mount point. Alternatively one can directly
change propagation properties of source mount. Say `/` is source mount for
`/foo`, then use `mount --make-shared /` to convert `/` into a `shared` mount.
Note: if the user only has access rights via a group, accessing the volume
from inside a rootless pod will fail.
#### **--volumes-from**[=*CONTAINER*[:*OPTIONS*]]
Mount volumes from the specified container(s). Used to share volumes between
containers and pods. The *options* is a comma-separated list with the following available elements:
* **rw**|**ro**
* **z**
Mounts already mounted volumes from a source container into another
pod. Must supply the source's container-id or container-name.
To share a volume, use the --volumes-from option when running
the target container. Volumes can be shared even if the source container
is not running.
By default, Podman mounts the volumes in the same mode (read-write or
read-only) as it is mounted in the source container.
This can be changed by adding a `ro` or `rw` _option_.
Labeling systems like SELinux require that proper labels are placed on volume
content mounted into a pod. Without a label, the security system might
prevent the processes running inside the container from using the content. By
default, Podman does not change the labels set by the OS.
To change a label in the pod context, add `z` to the volume mount.
This suffix tells Podman to relabel file objects on the shared volumes. The `z`
option tells Podman that two entities share the volume content. As a result,
Podman labels the content with a shared content label. Shared volume labels allow
all containers to read/write content.
If the location of the volume from the source container overlaps with
data residing on a target pod, then the volume hides
that data on the target.
## EXAMPLES
```
# podman pod clone pod-name
6b2c73ff8a1982828c9ae2092954bcd59836a131960f7e05221af9df5939c584
```
```
# podman pod clone --name=cloned-pod
d0cf1f782e2ed67e8c0050ff92df865a039186237a4df24d7acba5b1fa8cc6e7
6b2c73ff8a1982828c9ae2092954bcd59836a131960f7e05221af9df5939c584
```
```
# podman pod clone --destroy --cpus=5 d0cf1f782e2ed67e8c0050ff92df865a039186237a4df24d7acba5b1fa8cc6e7
6b2c73ff8a1982828c9ae2092954bcd59836a131960f7e05221af9df5939c584
```
```
# podman pod clone 2d4d4fca7219b4437e0d74fcdc272c4f031426a6eacd207372691207079551de new_name
5a9b7851013d326aa4ac4565726765901b3ecc01fcbc0f237bc7fd95588a24f9
```
## SEE ALSO
**[podman-pod-create(1)](podman-pod-create.1.md)**
## HISTORY
May 2022, Originally written by Charlie Doern <cdoern@redhat.com>

View File

@ -13,6 +13,7 @@ podman pod is a set of subcommands that manage pods, or groups of containers.
| Command | Man Page | Description |
| ------- | ------------------------------------------------- | --------------------------------------------------------------------------------- |
| clone | [podman-pod-clone(1)](podman-pod-clone.1.md) | Creates a copy of an existing pod. |
| create | [podman-pod-create(1)](podman-pod-create.1.md) | Create a new pod. |
| exists | [podman-pod-exists(1)](podman-pod-exists.1.md) | Check if a pod exists in local storage. |
| inspect | [podman-pod-inspect(1)](podman-pod-inspect.1.md) | Displays information describing a pod. |

View File

@ -450,3 +450,14 @@ func (p *Pod) initContainers() ([]*Container, error) {
}
return initCons, nil
}
func (p *Pod) Config() (*PodConfig, error) {
p.lock.Lock()
defer p.lock.Unlock()
conf := &PodConfig{}
err := JSONDeepCopy(p.config, conf)
return conf, err
}

View File

@ -71,6 +71,7 @@ type ContainerEngine interface {
PlayKube(ctx context.Context, body io.Reader, opts PlayKubeOptions) (*PlayKubeReport, error)
PlayKubeDown(ctx context.Context, body io.Reader, opts PlayKubeDownOptions) (*PlayKubeReport, error)
PodCreate(ctx context.Context, specg PodSpec) (*PodCreateReport, error)
PodClone(ctx context.Context, podClone PodCloneOptions) (*PodCloneReport, error)
PodExists(ctx context.Context, nameOrID string) (*BoolReport, error)
PodInspect(ctx context.Context, options PodInspectOptions) (*PodInspectReport, error)
PodKill(ctx context.Context, namesOrIds []string, options PodKillOptions) ([]*PodKillReport, error)

View File

@ -154,6 +154,16 @@ type PodLogsOptions struct {
Color bool
}
// PodCloneOptions contains options for cloning an existing pod
type PodCloneOptions struct {
ID string
Destroy bool
CreateOpts PodCreateOptions
InfraOptions ContainerCreateOptions
PerContainerOptions ContainerCreateOptions
Start bool
}
type ContainerCreateOptions struct {
Annotation []string
Attach []string
@ -290,6 +300,10 @@ type PodCreateReport struct {
Id string //nolint:revive,stylecheck
}
type PodCloneReport struct {
Id string //nolint
}
func (p *PodCreateOptions) CPULimits() *specs.LinuxCPU {
cpu := &specs.LinuxCPU{}
hasLimits := false

View File

@ -1593,6 +1593,11 @@ func (ic *ContainerEngine) ContainerClone(ctx context.Context, ctrCloneOpts enti
return nil, err
}
conf := c.Config()
if conf.Spec != nil && conf.Spec.Process != nil && conf.Spec.Process.Terminal { // if we do not pass term, running ctrs exit
spec.Terminal = true
}
// Print warnings
if len(out) > 0 {
for _, w := range out {
@ -1612,8 +1617,8 @@ func (ic *ContainerEngine) ContainerClone(ctx context.Context, ctrCloneOpts enti
switch {
case strings.Contains(n, "-clone"):
ind := strings.Index(n, "-clone") + 6
num, _ := strconv.Atoi(n[ind:])
if num == 0 { // clone1 is hard to get with this logic, just check for it here.
num, err := strconv.Atoi(n[ind:])
if num == 0 && err != nil { // clone1 is hard to get with this logic, just check for it here.
_, err = ic.Libpod.LookupContainer(n + "1")
if err != nil {
spec.Name = n + "1"

View File

@ -2,12 +2,15 @@ package abi
import (
"context"
"strconv"
"strings"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/domain/entities"
dfilters "github.com/containers/podman/v4/pkg/domain/filters"
"github.com/containers/podman/v4/pkg/signal"
"github.com/containers/podman/v4/pkg/specgen"
"github.com/containers/podman/v4/pkg/specgen/generate"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
@ -295,6 +298,88 @@ func (ic *ContainerEngine) PodCreate(ctx context.Context, specg entities.PodSpec
return &entities.PodCreateReport{Id: pod.ID()}, nil
}
func (ic *ContainerEngine) PodClone(ctx context.Context, podClone entities.PodCloneOptions) (*entities.PodCloneReport, error) {
spec := specgen.NewPodSpecGenerator()
p, err := generate.PodConfigToSpec(ic.Libpod, spec, &podClone.InfraOptions, podClone.ID)
if err != nil {
return nil, err
}
if len(podClone.CreateOpts.Name) > 0 {
spec.Name = podClone.CreateOpts.Name
} else {
n := p.Name()
_, err := ic.Libpod.LookupPod(n + "-clone")
if err == nil {
n += "-clone"
}
switch {
case strings.Contains(n, "-clone"): // meaning this name is taken!
ind := strings.Index(n, "-clone") + 6
num, err := strconv.Atoi(n[ind:])
if num == 0 && err != nil { // meaning invalid
_, err = ic.Libpod.LookupPod(n + "1")
if err != nil {
spec.Name = n + "1"
break
}
} else { // else we already have a number
n = n[0:ind]
}
err = nil
count := num
for err == nil { // until we cannot find a pod w/ this name, increment num and try again
count++
tempN := n + strconv.Itoa(count)
_, err = ic.Libpod.LookupPod(tempN)
}
n += strconv.Itoa(count)
spec.Name = n
default:
spec.Name = p.Name() + "-clone"
}
}
podSpec := entities.PodSpec{PodSpecGen: *spec}
pod, err := generate.MakePod(&podSpec, ic.Libpod)
if err != nil {
return nil, err
}
ctrs, err := p.AllContainers()
if err != nil {
return nil, err
}
for _, ctr := range ctrs {
if ctr.IsInfra() {
continue // already copied infra
}
podClone.PerContainerOptions.Pod = pod.ID()
_, err := ic.ContainerClone(ctx, entities.ContainerCloneOptions{ID: ctr.ID(), CreateOpts: podClone.PerContainerOptions})
if err != nil {
return nil, err
}
}
if podClone.Destroy {
var timeout *uint
err = ic.Libpod.RemovePod(ctx, p, true, true, timeout)
if err != nil {
return &entities.PodCloneReport{Id: pod.ID()}, err
}
}
if podClone.Start {
_, err := ic.PodStart(ctx, []string{pod.ID()}, entities.PodStartOptions{})
if err != nil {
return &entities.PodCloneReport{Id: pod.ID()}, err
}
}
return &entities.PodCloneReport{Id: pod.ID()}, nil
}
func (ic *ContainerEngine) PodTop(ctx context.Context, options entities.PodTopOptions) (*entities.StringSliceReport, error) {
var (
pod *libpod.Pod

View File

@ -195,6 +195,10 @@ func (ic *ContainerEngine) PodCreate(ctx context.Context, specg entities.PodSpec
return pods.CreatePodFromSpec(ic.ClientCtx, &specg)
}
func (ic *ContainerEngine) PodClone(ctx context.Context, podClone entities.PodCloneOptions) (*entities.PodCloneReport, error) {
return nil, nil
}
func (ic *ContainerEngine) PodTop(ctx context.Context, opts entities.PodTopOptions) (*entities.StringSliceReport, error) {
switch {
case opts.Latest:

View File

@ -450,7 +450,7 @@ func ConfigToSpec(rt *libpod.Runtime, specg *specgen.SpecGenerator, contaierID s
specg.IpcNS = specgen.Namespace{NSMode: specgen.Default} // default
}
case "uts":
specg.UtsNS = specgen.Namespace{NSMode: specgen.Default} // default
specg.UtsNS = specgen.Namespace{NSMode: specgen.Private} // default
case "user":
if conf.AddCurrentUserPasswdEntry {
specg.UserNS = specgen.Namespace{NSMode: specgen.KeepID}

View File

@ -2,12 +2,17 @@ package generate
import (
"context"
"fmt"
"net"
"os"
"strconv"
"strings"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/specgen"
"github.com/containers/podman/v4/pkg/specgenutil"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -210,3 +215,88 @@ func MapSpec(p *specgen.PodSpecGenerator) (*specgen.SpecGenerator, error) {
p.InfraContainerSpec.Image = p.InfraImage
return p.InfraContainerSpec, nil
}
func PodConfigToSpec(rt *libpod.Runtime, spec *specgen.PodSpecGenerator, infraOptions *entities.ContainerCreateOptions, id string) (p *libpod.Pod, err error) {
pod, err := rt.LookupPod(id)
if err != nil {
return nil, err
}
infraSpec := &specgen.SpecGenerator{}
if pod.HasInfraContainer() {
infraID, err := pod.InfraContainerID()
if err != nil {
return nil, err
}
_, _, err = ConfigToSpec(rt, infraSpec, infraID)
if err != nil {
return nil, err
}
infraSpec.Hostname = ""
infraSpec.CgroupParent = ""
infraSpec.Pod = "" // remove old pod...
infraOptions.IsClone = true
infraOptions.IsInfra = true
n := infraSpec.Name
_, err = rt.LookupContainer(n + "-clone")
if err == nil { // if we found a ctr with this name, set it so the below switch can tell
n += "-clone"
}
switch {
case strings.Contains(n, "-clone"):
ind := strings.Index(n, "-clone") + 6
num, err := strconv.Atoi(n[ind:])
if num == 0 && err != nil { // clone1 is hard to get with this logic, just check for it here.
_, err = rt.LookupContainer(n + "1")
if err != nil {
infraSpec.Name = n + "1"
break
}
} else {
n = n[0:ind]
}
err = nil
count := num
for err == nil {
count++
tempN := n + strconv.Itoa(count)
_, err = rt.LookupContainer(tempN)
}
n += strconv.Itoa(count)
infraSpec.Name = n
default:
infraSpec.Name = n + "-clone"
}
err = specgenutil.FillOutSpecGen(infraSpec, infraOptions, []string{})
if err != nil {
return nil, err
}
out, err := CompleteSpec(context.Background(), rt, infraSpec)
if err != nil {
return nil, err
}
// Print warnings
if len(out) > 0 {
for _, w := range out {
fmt.Println("Could not properly complete the spec as expected:")
fmt.Fprintf(os.Stderr, "%s\n", w)
}
}
spec.InfraContainerSpec = infraSpec
}
// need to reset hostname, name etc of both pod and infra
spec.Hostname = ""
if len(spec.InfraContainerSpec.Image) > 0 {
spec.InfraImage = spec.InfraContainerSpec.Image
}
return pod, nil
}

View File

@ -312,7 +312,7 @@ func FillOutSpecGen(s *specgen.SpecGenerator, c *entities.ContainerCreateOptions
s.PublishExposedPorts = c.PublishAll
}
if len(s.Pod) == 0 {
if len(s.Pod) == 0 || len(c.Pod) > 0 {
s.Pod = c.Pod
}

141
test/e2e/pod_clone_test.go Normal file
View File

@ -0,0 +1,141 @@
package integration
import (
"os"
. "github.com/containers/podman/v4/test/utils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
)
var _ = Describe("Podman pod clone", func() {
var (
tempdir string
err error
podmanTest *PodmanTestIntegration
)
BeforeEach(func() {
SkipIfRemote("podman pod clone is not supported in remote")
tempdir, err = CreateTempDirInTempDir()
if err != nil {
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup()
})
AfterEach(func() {
podmanTest.Cleanup()
f := CurrentGinkgoTestDescription()
processTestResult(f)
})
It("podman pod clone basic test", func() {
create := podmanTest.Podman([]string{"pod", "create", "--name", "1"})
create.WaitWithDefaultTimeout()
Expect(create).To(Exit(0))
run := podmanTest.Podman([]string{"run", "--pod", "1", "-dt", ALPINE})
run.WaitWithDefaultTimeout()
Expect(run).To(Exit(0))
clone := podmanTest.Podman([]string{"pod", "clone", create.OutputToString()})
clone.WaitWithDefaultTimeout()
Expect(clone).To(Exit(0))
podInspect := podmanTest.Podman([]string{"pod", "inspect", clone.OutputToString()})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).To(Exit(0))
data := podInspect.InspectPodToJSON()
Expect(data.Name).To(ContainSubstring("-clone"))
podStart := podmanTest.Podman([]string{"pod", "start", clone.OutputToString()})
podStart.WaitWithDefaultTimeout()
Expect(podStart).To(Exit(0))
podInspect = podmanTest.Podman([]string{"pod", "inspect", clone.OutputToString()})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).To(Exit(0))
data = podInspect.InspectPodToJSON()
Expect(data.Containers[1].State).To(ContainSubstring("running")) // make sure non infra ctr is running
})
It("podman pod clone renaming test", func() {
create := podmanTest.Podman([]string{"pod", "create", "--name", "1"})
create.WaitWithDefaultTimeout()
Expect(create).To(Exit(0))
clone := podmanTest.Podman([]string{"pod", "clone", "--name", "2", create.OutputToString()})
clone.WaitWithDefaultTimeout()
Expect(clone).To(Exit(0))
podInspect := podmanTest.Podman([]string{"pod", "inspect", clone.OutputToString()})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).To(Exit(0))
data := podInspect.InspectPodToJSON()
Expect(data.Name).To(ContainSubstring("2"))
podStart := podmanTest.Podman([]string{"pod", "start", clone.OutputToString()})
podStart.WaitWithDefaultTimeout()
Expect(podStart).To(Exit(0))
})
It("podman pod clone start test", func() {
create := podmanTest.Podman([]string{"pod", "create", "--name", "1"})
create.WaitWithDefaultTimeout()
Expect(create).To(Exit(0))
clone := podmanTest.Podman([]string{"pod", "clone", "--start", create.OutputToString()})
clone.WaitWithDefaultTimeout()
Expect(clone).To(Exit(0))
podInspect := podmanTest.Podman([]string{"pod", "inspect", clone.OutputToString()})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).To(Exit(0))
data := podInspect.InspectPodToJSON()
Expect(data.State).To(ContainSubstring("Running"))
})
It("podman pod clone destroy test", func() {
create := podmanTest.Podman([]string{"pod", "create", "--name", "1"})
create.WaitWithDefaultTimeout()
Expect(create).To(Exit(0))
clone := podmanTest.Podman([]string{"pod", "clone", "--destroy", create.OutputToString()})
clone.WaitWithDefaultTimeout()
Expect(clone).To(Exit(0))
podInspect := podmanTest.Podman([]string{"pod", "inspect", create.OutputToString()})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).ToNot(Exit(0))
})
It("podman pod clone infra option test", func() {
// proof of concept that all currently tested infra options work since
volName := "testVol"
volCreate := podmanTest.Podman([]string{"volume", "create", volName})
volCreate.WaitWithDefaultTimeout()
Expect(volCreate).Should(Exit(0))
podName := "testPod"
podCreate := podmanTest.Podman([]string{"pod", "create", "--name", podName})
podCreate.WaitWithDefaultTimeout()
Expect(podCreate).Should(Exit(0))
podClone := podmanTest.Podman([]string{"pod", "clone", "--volume", volName + ":/tmp1", podName})
podClone.WaitWithDefaultTimeout()
Expect(podClone).Should(Exit(0))
podInspect := podmanTest.Podman([]string{"pod", "inspect", "testPod-clone"})
podInspect.WaitWithDefaultTimeout()
Expect(podInspect).Should(Exit(0))
data := podInspect.InspectPodToJSON()
Expect(data.Mounts[0]).To(HaveField("Name", volName))
})
})