Eliminate the use of containers/building import in pkg subdirs

We want to shrink the size of the import when importing pkg from
buildah. This should help us shrink the size of the golang bindings
in podman.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
This commit is contained in:
Daniel J Walsh 2021-02-06 17:49:40 -05:00
parent 6421c84180
commit 4704e6cb3f
No known key found for this signature in database
GPG Key ID: A2DF901DABE2C028
33 changed files with 450 additions and 344 deletions

3
add.go
View File

@ -16,6 +16,7 @@ import (
"time"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/chrootuser"
"github.com/containers/storage/pkg/fileutils"
"github.com/containers/storage/pkg/idtools"
@ -51,7 +52,7 @@ type AddAndCopyOptions struct {
// ID mapping options to use when contents to be copied are part of
// another container, and need ownerships to be mapped from the host to
// that container's values before copying them into the container.
IDMappingOptions *IDMappingOptions
IDMappingOptions *define.IDMappingOptions
// DryRun indicates that the content should be digested, but not actually
// copied into the container.
DryRun bool

View File

@ -25,10 +25,10 @@ import (
const (
// Package is the name of this package, used in help output and to
// identify working containers.
Package = "buildah"
Package = define.Package
// Version for the Package. Bump version in contrib/rpm/buildah.spec
// too.
Version = "1.20.0-dev"
Version = define.Version
// The value we use to identify what type of information, currently a
// serialized Builder structure, we are using as per-container state.
// This should only be changed when we make incompatible changes to
@ -66,35 +66,22 @@ const (
// NetworkConfigurationPolicy takes the value NetworkDefault, NetworkDisabled,
// or NetworkEnabled.
type NetworkConfigurationPolicy int
type NetworkConfigurationPolicy = define.NetworkConfigurationPolicy
const (
// NetworkDefault is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that the default behavior should be used.
NetworkDefault NetworkConfigurationPolicy = iota
NetworkDefault = define.NetworkDefault
// NetworkDisabled is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that network interfaces should NOT be configured for
// newly-created network namespaces.
NetworkDisabled
NetworkDisabled = define.NetworkDisabled
// NetworkEnabled is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that network interfaces should be configured for
// newly-created network namespaces.
NetworkEnabled
NetworkEnabled = define.NetworkEnabled
)
// String formats a NetworkConfigurationPolicy as a string.
func (p NetworkConfigurationPolicy) String() string {
switch p {
case NetworkDefault:
return "NetworkDefault"
case NetworkDisabled:
return "NetworkDisabled"
case NetworkEnabled:
return "NetworkEnabled"
}
return fmt.Sprintf("unknown NetworkConfigurationPolicy %d", p)
}
// Builder objects are used to represent containers which are being used to
// build images. They also carry potential updates which will be applied to
// the image's configuration when the container's contents are used to build an
@ -149,15 +136,15 @@ type Builder struct {
DefaultMountsFilePath string `json:"defaultMountsFilePath,omitempty"`
// Isolation controls how we handle "RUN" statements and the Run() method.
Isolation Isolation
Isolation define.Isolation
// NamespaceOptions controls how we set up the namespaces for processes that we run in the container.
NamespaceOptions NamespaceOptions
NamespaceOptions define.NamespaceOptions
// ConfigureNetwork controls whether or not network interfaces and
// routing are configured for a new network namespace (i.e., when not
// joining another's namespace and not just using the host's
// namespace), effectively deciding whether or not the process has a
// usable network.
ConfigureNetwork NetworkConfigurationPolicy
ConfigureNetwork define.NetworkConfigurationPolicy
// CNIPluginPath is the location of CNI plugin helpers, if they should be
// run from a location other than the default location.
CNIPluginPath string
@ -165,7 +152,7 @@ type Builder struct {
// the default configuration directory shouldn't be used.
CNIConfigDir string
// ID mapping options to use when running processes in the container with non-host user namespaces.
IDMappingOptions IDMappingOptions
IDMappingOptions define.IDMappingOptions
// Capabilities is a list of capabilities to use when running commands in the container.
Capabilities []string
// PrependedEmptyLayers are history entries that we'll add to a
@ -177,7 +164,7 @@ type Builder struct {
// committed image after the history item for the layer that we're
// committing.
AppendedEmptyLayers []v1.History
CommonBuildOpts *CommonBuildOptions
CommonBuildOpts *define.CommonBuildOptions
// TopLayer is the top layer of the image
TopLayer string
// Format for the build Image
@ -187,7 +174,7 @@ type Builder struct {
// ContentDigester counts the digest of all Add()ed content
ContentDigester CompositeDigester
// Devices are the additional devices to add to the containers
Devices ContainerDevices
Devices define.ContainerDevices
}
// BuilderInfo are used as objects to display container information
@ -209,14 +196,14 @@ type BuilderInfo struct {
Docker docker.V2Image
DefaultMountsFilePath string
Isolation string
NamespaceOptions NamespaceOptions
NamespaceOptions define.NamespaceOptions
Capabilities []string
ConfigureNetwork string
CNIPluginPath string
CNIConfigDir string
IDMappingOptions IDMappingOptions
IDMappingOptions define.IDMappingOptions
History []v1.History
Devices ContainerDevices
Devices define.ContainerDevices
}
// GetBuildInfo gets a pointer to a Builder object and returns a BuilderInfo object from it.
@ -256,66 +243,7 @@ func GetBuildInfo(b *Builder) BuilderInfo {
}
// CommonBuildOptions are resources that can be defined by flags for both buildah from and build-using-dockerfile
type CommonBuildOptions struct {
// AddHost is the list of hostnames to add to the build container's /etc/hosts.
AddHost []string
// CgroupParent is the path to cgroups under which the cgroup for the container will be created.
CgroupParent string
// CPUPeriod limits the CPU CFS (Completely Fair Scheduler) period
CPUPeriod uint64
// CPUQuota limits the CPU CFS (Completely Fair Scheduler) quota
CPUQuota int64
// CPUShares (relative weight
CPUShares uint64
// CPUSetCPUs in which to allow execution (0-3, 0,1)
CPUSetCPUs string
// CPUSetMems memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
CPUSetMems string
// HTTPProxy determines whether *_proxy env vars from the build host are passed into the container.
HTTPProxy bool
// Memory is the upper limit (in bytes) on how much memory running containers can use.
Memory int64
// DNSSearch is the list of DNS search domains to add to the build container's /etc/resolv.conf
DNSSearch []string
// DNSServers is the list of DNS servers to add to the build container's /etc/resolv.conf
DNSServers []string
// DNSOptions is the list of DNS
DNSOptions []string
// MemorySwap limits the amount of memory and swap together.
MemorySwap int64
// LabelOpts is the a slice of fields of an SELinux context, given in "field:pair" format, or "disable".
// Recognized field names are "role", "type", and "level".
LabelOpts []string
// OmitTimestamp forces epoch 0 as created timestamp to allow for
// deterministic, content-addressable builds.
OmitTimestamp bool
// SeccompProfilePath is the pathname of a seccomp profile.
SeccompProfilePath string
// ApparmorProfile is the name of an apparmor profile.
ApparmorProfile string
// ShmSize is the "size" value to use when mounting an shmfs on the container's /dev/shm directory.
ShmSize string
// Ulimit specifies resource limit options, in the form type:softlimit[:hardlimit].
// These types are recognized:
// "core": maximum core dump size (ulimit -c)
// "cpu": maximum CPU time (ulimit -t)
// "data": maximum size of a process's data segment (ulimit -d)
// "fsize": maximum size of new files (ulimit -f)
// "locks": maximum number of file locks (ulimit -x)
// "memlock": maximum amount of locked memory (ulimit -l)
// "msgqueue": maximum amount of data in message queues (ulimit -q)
// "nice": niceness adjustment (nice -n, ulimit -e)
// "nofile": maximum number of open files (ulimit -n)
// "nproc": maximum number of processes (ulimit -u)
// "rss": maximum size of a process's (ulimit -m)
// "rtprio": maximum real-time scheduling priority (ulimit -r)
// "rttime": maximum amount of real-time execution between blocking syscalls
// "sigpending": maximum number of pending signals (ulimit -i)
// "stack": maximum stack size (ulimit -s)
Ulimit []string
// Volumes to bind mount into the container
Volumes []string
}
type CommonBuildOptions = define.CommonBuildOptions
// BuilderOptions are used to initialize a new Builder.
type BuilderOptions struct {
@ -331,7 +259,7 @@ type BuilderOptions struct {
// PullPolicy decides whether or not we should pull the image that
// we're using as a base image. It should be PullIfMissing,
// PullAlways, or PullNever.
PullPolicy PullPolicy
PullPolicy define.PullPolicy
// Registry is a value which is prepended to the image's name, if it
// needs to be pulled and the image name alone can not be resolved to a
// reference to a source image. No separator is implicitly added.
@ -360,16 +288,16 @@ type BuilderOptions struct {
DefaultMountsFilePath string
// Isolation controls how we handle "RUN" statements and the Run()
// method.
Isolation Isolation
Isolation define.Isolation
// NamespaceOptions controls how we set up namespaces for processes that
// we might need to run using the container's root filesystem.
NamespaceOptions NamespaceOptions
NamespaceOptions define.NamespaceOptions
// ConfigureNetwork controls whether or not network interfaces and
// routing are configured for a new network namespace (i.e., when not
// joining another's namespace and not just using the host's
// namespace), effectively deciding whether or not the process has a
// usable network.
ConfigureNetwork NetworkConfigurationPolicy
ConfigureNetwork define.NetworkConfigurationPolicy
// CNIPluginPath is the location of CNI plugin helpers, if they should be
// run from a location other than the default location.
CNIPluginPath string
@ -377,15 +305,15 @@ type BuilderOptions struct {
// the default configuration directory shouldn't be used.
CNIConfigDir string
// ID mapping options to use if we're setting up our own user namespace.
IDMappingOptions *IDMappingOptions
IDMappingOptions *define.IDMappingOptions
// Capabilities is a list of capabilities to use when
// running commands in the container.
Capabilities []string
CommonBuildOpts *CommonBuildOptions
CommonBuildOpts *define.CommonBuildOptions
// Format for the container image
Format string
// Devices are the additional devices to add to the containers
Devices ContainerDevices
Devices define.ContainerDevices
//DefaultEnv for containers
DefaultEnv []string
// MaxPullRetries is the maximum number of attempts we'll make to pull
@ -460,7 +388,7 @@ func OpenBuilder(store storage.Store, container string) (*Builder, error) {
return nil, errors.Wrapf(err, "error parsing %q, read from %q", string(buildstate), filepath.Join(cdir, stateFile))
}
if b.Type != containerType {
return nil, errors.Errorf("container %q is not a %s container (is a %q container)", container, Package, b.Type)
return nil, errors.Errorf("container %q is not a %s container (is a %q container)", container, define.Package, b.Type)
}
b.store = store
b.fixupConfig()
@ -504,7 +432,7 @@ func OpenBuilderByPath(store storage.Store, path string) (*Builder, error) {
if err != nil {
logrus.Debugf("error parsing %q, read from %q: %v", string(buildstate), filepath.Join(cdir, stateFile), err)
} else if b.Type != containerType {
logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, Package, b.Type)
logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, define.Package, b.Type)
}
}
return nil, storage.ErrContainerUnknown
@ -541,7 +469,7 @@ func OpenAllBuilders(store storage.Store) (builders []*Builder, err error) {
if err != nil {
logrus.Debugf("error parsing %q, read from %q: %v", string(buildstate), filepath.Join(cdir, stateFile), err)
} else if b.Type != containerType {
logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, Package, b.Type)
logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, define.Package, b.Type)
}
}
return builders, nil

View File

@ -6,6 +6,7 @@ import (
"time"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/imagebuildah"
buildahcli "github.com/containers/buildah/pkg/cli"
"github.com/containers/buildah/pkg/parse"
@ -168,7 +169,7 @@ func commitCmd(c *cobra.Command, args []string, iopts commitInputOptions) error
}
// Add builder identity information.
builder.SetLabel(buildah.BuilderIdentityAnnotation, buildah.Version)
builder.SetLabel(buildah.BuilderIdentityAnnotation, define.Version)
encConfig, encLayers, err := getEncryptConfig(iopts.encryptionKeys, iopts.encryptLayers)
if err != nil {

View File

@ -7,6 +7,7 @@ import (
"testing"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
is "github.com/containers/image/v5/storage"
"github.com/containers/image/v5/types"
"github.com/containers/storage"
@ -112,7 +113,7 @@ func pullTestImage(t *testing.T) string {
if err != nil {
t.Fatal(err)
}
commonOpts := &buildah.CommonBuildOptions{
commonOpts := &define.CommonBuildOptions{
LabelOpts: nil,
}
options := buildah.BuilderOptions{

View File

@ -9,6 +9,7 @@ import (
"text/template"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/formats"
"github.com/containers/buildah/util"
"github.com/containers/storage"
@ -67,7 +68,7 @@ type containersResults struct {
func init() {
var (
containersDescription = "\n Lists containers which appear to be " + buildah.Package + " working containers, their\n names and IDs, and the names and IDs of the images from which they were\n initialized."
containersDescription = "\n Lists containers which appear to be " + define.Package + " working containers, their\n names and IDs, and the names and IDs of the images from which they were\n initialized."
opts containersResults
)
containersCommand := &cobra.Command{

View File

@ -8,6 +8,7 @@ import (
"strings"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
buildahcli "github.com/containers/buildah/pkg/cli"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/common/pkg/auth"
@ -210,15 +211,15 @@ func fromCmd(c *cobra.Command, args []string, iopts fromReply) error {
return errors.Errorf("can only set one of 'pull' or 'pull-always' or 'pull-never'")
}
pullPolicy := buildah.PullIfMissing
pullPolicy := define.PullIfMissing
if iopts.pull {
pullPolicy = buildah.PullIfNewer
pullPolicy = define.PullIfNewer
}
if iopts.pullAlways {
pullPolicy = buildah.PullAlways
pullPolicy = define.PullAlways
}
if iopts.pullNever {
pullPolicy = buildah.PullNever
pullPolicy = define.PullNever
}
signaturePolicy := iopts.signaturePolicy
@ -252,7 +253,7 @@ func fromCmd(c *cobra.Command, args []string, iopts fromReply) error {
if err != nil {
return err
}
devices := buildah.ContainerDevices{}
devices := define.ContainerDevices{}
for _, device := range append(defaultContainerConfig.Containers.Devices, iopts.Devices...) {
dev, err := parse.DeviceFromPath(device)
if err != nil {

View File

@ -9,6 +9,7 @@ import (
"text/template"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
@ -96,7 +97,7 @@ func debugInfo() map[string]interface{} {
info := map[string]interface{}{}
info["compiler"] = runtime.Compiler
info["go version"] = runtime.Version()
info["buildah version"] = buildah.Version
info["buildah version"] = define.Version
info["git commit"] = GitCommit
return info
}

View File

@ -10,6 +10,7 @@ import (
"syscall"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/cli"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/common/pkg/config"
@ -79,7 +80,7 @@ func init() {
cobra.OnInitialize(initConfig)
//rootCmd.TraverseChildren = true
rootCmd.Version = fmt.Sprintf("%s (image-spec %s, runtime-spec %s)", buildah.Version, ispecs.Version, rspecs.Version)
rootCmd.Version = fmt.Sprintf("%s (image-spec %s, runtime-spec %s)", define.Version, ispecs.Version, rspecs.Version)
rootCmd.PersistentFlags().BoolVar(&globalFlagResults.Debug, "debug", false, "print debugging information")
// TODO Need to allow for environment variable
rootCmd.PersistentFlags().StringVar(&globalFlagResults.RegistriesConf, "registries-conf", "", "path to registries.conf file (not usually used)")

View File

@ -7,7 +7,7 @@ import (
"time"
cniversion "github.com/containernetworking/cni/pkg/version"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
iversion "github.com/containers/image/v5/version"
ispecs "github.com/opencontainers/image-spec/specs-go"
rspecs "github.com/opencontainers/runtime-spec/specs-go"
@ -33,7 +33,7 @@ func versionCmd(c *cobra.Command, args []string) error {
}
}
fmt.Println("Version: ", buildah.Version)
fmt.Println("Version: ", define.Version)
fmt.Println("Go Version: ", runtime.Version())
fmt.Println("Image Spec: ", ispecs.Version)
fmt.Println("Runtime Spec: ", rspecs.Version)

View File

@ -7,6 +7,7 @@ import (
"path/filepath"
"time"
"github.com/containers/buildah/define"
"github.com/containers/common/pkg/retry"
cp "github.com/containers/image/v5/copy"
"github.com/containers/image/v5/docker"
@ -19,9 +20,9 @@ import (
const (
// OCI used to define the "oci" image format
OCI = "oci"
OCI = define.OCI
// DOCKER used to define the "docker" image format
DOCKER = "docker"
DOCKER = define.DOCKER
)
func getCopyOptions(store storage.Store, reportWriter io.Writer, sourceSystemContext *types.SystemContext, destinationSystemContext *types.SystemContext, manifestType string, removeSignatures bool, addSigner string, ociEncryptLayers *[]int, ociEncryptConfig *encconfig.EncryptConfig, ociDecryptConfig *encconfig.DecryptConfig) *cp.Options {

63
define/build.go Normal file
View File

@ -0,0 +1,63 @@
package define
// CommonBuildOptions are resources that can be defined by flags for both buildah from and build-using-dockerfile
type CommonBuildOptions struct {
// AddHost is the list of hostnames to add to the build container's /etc/hosts.
AddHost []string
// CgroupParent is the path to cgroups under which the cgroup for the container will be created.
CgroupParent string
// CPUPeriod limits the CPU CFS (Completely Fair Scheduler) period
CPUPeriod uint64
// CPUQuota limits the CPU CFS (Completely Fair Scheduler) quota
CPUQuota int64
// CPUShares (relative weight
CPUShares uint64
// CPUSetCPUs in which to allow execution (0-3, 0,1)
CPUSetCPUs string
// CPUSetMems memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
CPUSetMems string
// HTTPProxy determines whether *_proxy env vars from the build host are passed into the container.
HTTPProxy bool
// Memory is the upper limit (in bytes) on how much memory running containers can use.
Memory int64
// DNSSearch is the list of DNS search domains to add to the build container's /etc/resolv.conf
DNSSearch []string
// DNSServers is the list of DNS servers to add to the build container's /etc/resolv.conf
DNSServers []string
// DNSOptions is the list of DNS
DNSOptions []string
// MemorySwap limits the amount of memory and swap together.
MemorySwap int64
// LabelOpts is the a slice of fields of an SELinux context, given in "field:pair" format, or "disable".
// Recognized field names are "role", "type", and "level".
LabelOpts []string
// OmitTimestamp forces epoch 0 as created timestamp to allow for
// deterministic, content-addressable builds.
OmitTimestamp bool
// SeccompProfilePath is the pathname of a seccomp profile.
SeccompProfilePath string
// ApparmorProfile is the name of an apparmor profile.
ApparmorProfile string
// ShmSize is the "size" value to use when mounting an shmfs on the container's /dev/shm directory.
ShmSize string
// Ulimit specifies resource limit options, in the form type:softlimit[:hardlimit].
// These types are recognized:
// "core": maximum core dump size (ulimit -c)
// "cpu": maximum CPU time (ulimit -t)
// "data": maximum size of a process's data segment (ulimit -d)
// "fsize": maximum size of new files (ulimit -f)
// "locks": maximum number of file locks (ulimit -x)
// "memlock": maximum amount of locked memory (ulimit -l)
// "msgqueue": maximum amount of data in message queues (ulimit -q)
// "nice": niceness adjustment (nice -n, ulimit -e)
// "nofile": maximum number of open files (ulimit -n)
// "nproc": maximum number of processes (ulimit -u)
// "rss": maximum size of a process's (ulimit -m)
// "rtprio": maximum real-time scheduling priority (ulimit -r)
// "rttime": maximum amount of real-time execution between blocking syscalls
// "sigpending": maximum number of pending signals (ulimit -i)
// "stack": maximum stack size (ulimit -s)
Ulimit []string
// Volumes to bind mount into the container
Volumes []string
}

34
define/isolation.go Normal file
View File

@ -0,0 +1,34 @@
package define
import (
"fmt"
)
type Isolation int
const (
// IsolationDefault is whatever we think will work best.
IsolationDefault Isolation = iota
// IsolationOCI is a proper OCI runtime.
IsolationOCI
// IsolationChroot is a more chroot-like environment: less isolation,
// but with fewer requirements.
IsolationChroot
// IsolationOCIRootless is a proper OCI runtime in rootless mode.
IsolationOCIRootless
)
// String converts a Isolation into a string.
func (i Isolation) String() string {
switch i {
case IsolationDefault:
return "IsolationDefault"
case IsolationOCI:
return "IsolationOCI"
case IsolationChroot:
return "IsolationChroot"
case IsolationOCIRootless:
return "IsolationOCIRootless"
}
return fmt.Sprintf("unrecognized isolation type %d", i)
}

87
define/namespace.go Normal file
View File

@ -0,0 +1,87 @@
package define
import (
"fmt"
)
// NamespaceOption controls how we set up a namespace when launching processes.
type NamespaceOption struct {
// Name specifies the type of namespace, typically matching one of the
// ...Namespace constants defined in
// github.com/opencontainers/runtime-spec/specs-go.
Name string
// Host is used to force our processes to use the host's namespace of
// this type.
Host bool
// Path is the path of the namespace to attach our process to, if Host
// is not set. If Host is not set and Path is also empty, a new
// namespace will be created for the process that we're starting.
// If Name is specs.NetworkNamespace, if Path doesn't look like an
// absolute path, it is treated as a comma-separated list of CNI
// configuration names which will be selected from among all of the CNI
// network configurations which we find.
Path string
}
// NamespaceOptions provides some helper methods for a slice of NamespaceOption
// structs.
type NamespaceOptions []NamespaceOption
// Find the configuration for the namespace of the given type. If there are
// duplicates, find the _last_ one of the type, since we assume it was appended
// more recently.
func (n *NamespaceOptions) Find(namespace string) *NamespaceOption {
for i := range *n {
j := len(*n) - 1 - i
if (*n)[j].Name == namespace {
return &((*n)[j])
}
}
return nil
}
// AddOrReplace either adds or replaces the configuration for a given namespace.
func (n *NamespaceOptions) AddOrReplace(options ...NamespaceOption) {
nextOption:
for _, option := range options {
for i := range *n {
j := len(*n) - 1 - i
if (*n)[j].Name == option.Name {
(*n)[j] = option
continue nextOption
}
}
*n = append(*n, option)
}
}
// NetworkConfigurationPolicy takes the value NetworkDefault, NetworkDisabled,
// or NetworkEnabled.
type NetworkConfigurationPolicy int
const (
// NetworkDefault is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that the default behavior should be used.
NetworkDefault NetworkConfigurationPolicy = iota
// NetworkDisabled is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that network interfaces should NOT be configured for
// newly-created network namespaces.
NetworkDisabled
// NetworkEnabled is one of the values that BuilderOptions.ConfigureNetwork
// can take, signalling that network interfaces should be configured for
// newly-created network namespaces.
NetworkEnabled
)
// String formats a NetworkConfigurationPolicy as a string.
func (p NetworkConfigurationPolicy) String() string {
switch p {
case NetworkDefault:
return "NetworkDefault"
case NetworkDisabled:
return "NetworkDisabled"
case NetworkEnabled:
return "NetworkEnabled"
}
return fmt.Sprintf("unknown NetworkConfigurationPolicy %d", p)
}

55
define/pull.go Normal file
View File

@ -0,0 +1,55 @@
package define
import (
"fmt"
)
// PullPolicy takes the value PullIfMissing, PullAlways, PullIfNewer, or PullNever.
type PullPolicy int
const (
// PullIfMissing is one of the values that BuilderOptions.PullPolicy
// can take, signalling that the source image should be pulled from a
// registry if a local copy of it is not already present.
PullIfMissing PullPolicy = iota
// PullAlways is one of the values that BuilderOptions.PullPolicy can
// take, signalling that a fresh, possibly updated, copy of the image
// should be pulled from a registry before the build proceeds.
PullAlways
// PullIfNewer is one of the values that BuilderOptions.PullPolicy
// can take, signalling that the source image should only be pulled
// from a registry if a local copy is not already present or if a
// newer version the image is present on the repository.
PullIfNewer
// PullNever is one of the values that BuilderOptions.PullPolicy can
// take, signalling that the source image should not be pulled from a
// registry.
PullNever
// OCI used to define the "oci" image format
OCI = "oci"
// DOCKER used to define the "docker" image format
DOCKER = "docker"
)
// String converts a PullPolicy into a string.
func (p PullPolicy) String() string {
switch p {
case PullIfMissing:
return "PullIfMissing"
case PullAlways:
return "PullAlways"
case PullIfNewer:
return "PullIfNewer"
case PullNever:
return "PullNever"
}
return fmt.Sprintf("unrecognized policy %d", p)
}
var PolicyMap = map[string]PullPolicy{
"missing": PullIfMissing,
"always": PullAlways,
"never": PullNever,
"ifnewer": PullIfNewer,
}

View File

@ -1,50 +1,23 @@
package define
import (
"fmt"
"github.com/opencontainers/runtime-spec/specs-go"
)
// PullPolicy takes the value PullIfMissing, PullAlways, PullIfNewer, or PullNever.
type PullPolicy int
const (
// PullIfMissing is one of the values that BuilderOptions.PullPolicy
// can take, signalling that the source image should be pulled from a
// registry if a local copy of it is not already present.
PullIfMissing PullPolicy = iota
// PullAlways is one of the values that BuilderOptions.PullPolicy can
// take, signalling that a fresh, possibly updated, copy of the image
// should be pulled from a registry before the build proceeds.
PullAlways
// PullIfNewer is one of the values that BuilderOptions.PullPolicy
// can take, signalling that the source image should only be pulled
// from a registry if a local copy is not already present or if a
// newer version the image is present on the repository.
PullIfNewer
// PullNever is one of the values that BuilderOptions.PullPolicy can
// take, signalling that the source image should not be pulled from a
// registry if a local copy of it is not already present.
PullNever
// Package is the name of this package, used in help output and to
// identify working containers.
Package = "buildah"
// Version for the Package. Bump version in contrib/rpm/buildah.spec
// too.
Version = "1.20.0-dev"
)
// String converts a PullPolicy into a string.
func (p PullPolicy) String() string {
switch p {
case PullIfMissing:
return "PullIfMissing"
case PullAlways:
return "PullAlways"
case PullIfNewer:
return "PullIfNewer"
case PullNever:
return "PullNever"
}
return fmt.Sprintf("unrecognized policy %d", p)
}
var PolicyMap = map[string]PullPolicy{
"missing": PullIfMissing,
"always": PullAlways,
"never": PullNever,
"ifnewer": PullIfNewer,
// IDMappingOptions controls how we set up UID/GID mapping when we set up a
// user namespace.
type IDMappingOptions struct {
HostUIDMapping bool
HostGIDMapping bool
UIDMap []specs.LinuxIDMapping
GIDMap []specs.LinuxIDMapping
}

9
define/types_unix.go Normal file
View File

@ -0,0 +1,9 @@
// +build darwin linux
package define
import (
"github.com/opencontainers/runc/libcontainer/devices"
)
type ContainerDevices = []devices.Device

View File

@ -0,0 +1,6 @@
// +build !linux,!darwin
package define
// ContainerDevices is currently not implemented.
type ContainerDevices = []struct{}

View File

@ -56,9 +56,9 @@ Define the builder options:
```go
builderOpts := buildah.BuilderOptions{
FromImage: "node:12-alpine", // Starting image
Isolation: buildah.IsolationChroot, // Isolation environment
CommonBuildOpts: &buildah.CommonBuildOptions{},
ConfigureNetwork: buildah.NetworkDefault,
Isolation: define.IsolationChroot, // Isolation environment
CommonBuildOpts: &define.CommonBuildOptions{},
ConfigureNetwork: define.NetworkDefault,
SystemContext: &types.SystemContext {},
}
```
@ -90,7 +90,7 @@ imageRef, err := is.Transport.ParseStoreReference(buildStore, "docker.io/myusern
Now you can run commit the build:
```go
imageId, _, _, err := builder.Commit(context.TODO(), imageRef, buildah.CommitOptions{})
imageId, _, _, err := builder.Commit(context.TODO(), imageRef, define.CommitOptions{})
```
## Rootless mode
@ -115,6 +115,7 @@ import (
"context"
"fmt"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/storage/pkg/unshare"
is "github.com/containers/image/v5/storage"
"github.com/containers/image/v5/types"
@ -141,9 +142,9 @@ func main() {
opts := buildah.BuilderOptions{
FromImage: "node:12-alpine",
Isolation: buildah.IsolationChroot,
CommonBuildOpts: &buildah.CommonBuildOptions{},
ConfigureNetwork: buildah.NetworkDefault,
Isolation: define.IsolationChroot,
CommonBuildOpts: &define.CommonBuildOptions{},
ConfigureNetwork: define.NetworkDefault,
SystemContext: &types.SystemContext {},
}
@ -167,7 +168,7 @@ func main() {
panic(err)
}
imageId, _, _, err := builder.Commit(context.TODO(), imageRef, buildah.CommitOptions{})
imageId, _, _, err := builder.Commit(context.TODO(), imageRef, define.CommitOptions{})
fmt.Printf("Image built! %s\n", imageId)
}

View File

@ -14,6 +14,7 @@ import (
"time"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
"github.com/containers/buildah/docker"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/image"
@ -60,7 +61,7 @@ type containerImageRef struct {
exporting bool
squash bool
emptyLayer bool
idMappingOptions *IDMappingOptions
idMappingOptions *define.IDMappingOptions
parent string
blobDirectory string
preEmptyLayers []v1.History
@ -279,7 +280,7 @@ func (i *containerImageRef) NewImageSource(ctx context.Context, sc *types.System
logrus.Debugf("layer list: %q", layers)
// Make a temporary directory to hold blobs.
path, err := ioutil.TempDir(os.TempDir(), Package)
path, err := ioutil.TempDir(os.TempDir(), define.Package)
if err != nil {
return nil, errors.Wrapf(err, "error creating temporary directory to hold layer blobs")
}

View File

@ -13,7 +13,7 @@ import (
"strings"
"time"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/common/pkg/config"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/types"
@ -28,10 +28,10 @@ import (
)
const (
PullIfMissing = buildah.PullIfMissing
PullAlways = buildah.PullAlways
PullIfNewer = buildah.PullIfNewer
PullNever = buildah.PullNever
PullIfMissing = define.PullIfMissing
PullAlways = define.PullAlways
PullIfNewer = define.PullIfNewer
PullNever = define.PullNever
Gzip = archive.Gzip
Bzip2 = archive.Bzip2
@ -50,7 +50,7 @@ type BuildOptions struct {
ContextDirectory string
// PullPolicy controls whether or not we pull images. It should be one
// of PullIfMissing, PullAlways, PullIfNewer, or PullNever.
PullPolicy buildah.PullPolicy
PullPolicy define.PullPolicy
// Registry is a value which is prepended to the image's name, if it
// needs to be pulled and the image name alone can not be resolved to a
// reference to a source image. No separator is implicitly added.
@ -63,7 +63,7 @@ type BuildOptions struct {
// Quiet tells us whether or not to announce steps as we go through them.
Quiet bool
// Isolation controls how Run() runs things.
Isolation buildah.Isolation
Isolation define.Isolation
// Runtime is the name of the command to run for RUN instructions when
// Isolation is either IsolationDefault or IsolationOCI. It should
// accept the same arguments and flags that runc does.
@ -111,13 +111,13 @@ type BuildOptions struct {
SystemContext *types.SystemContext
// NamespaceOptions controls how we set up namespaces processes that we
// might need when handling RUN instructions.
NamespaceOptions []buildah.NamespaceOption
NamespaceOptions []define.NamespaceOption
// ConfigureNetwork controls whether or not network interfaces and
// routing are configured for a new network namespace (i.e., when not
// joining another's namespace and not just using the host's
// namespace), effectively deciding whether or not the process has a
// usable network.
ConfigureNetwork buildah.NetworkConfigurationPolicy
ConfigureNetwork define.NetworkConfigurationPolicy
// CNIPluginPath is the location of CNI plugin helpers, if they should be
// run from a location other than the default location.
CNIPluginPath string
@ -126,7 +126,7 @@ type BuildOptions struct {
CNIConfigDir string
// ID mapping options to use if we're setting up our own user namespace
// when handling RUN instructions.
IDMappingOptions *buildah.IDMappingOptions
IDMappingOptions *define.IDMappingOptions
// AddCapabilities is a list of capabilities to add to the default set when
// handling RUN instructions.
AddCapabilities []string
@ -135,7 +135,7 @@ type BuildOptions struct {
// will be dropped.
DropCapabilities []string
// CommonBuildOpts is *required*.
CommonBuildOpts *buildah.CommonBuildOptions
CommonBuildOpts *define.CommonBuildOptions
// DefaultMountsFilePath is the file path holding the mounts to be mounted in "host-path:container-path" format
DefaultMountsFilePath string
// IIDFile tells the builder to write the image ID to the specified file

View File

@ -13,6 +13,7 @@ import (
"time"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/buildah/util"
"github.com/containers/common/pkg/config"
@ -56,7 +57,7 @@ type Executor struct {
stages map[string]*StageExecutor
store storage.Store
contextDir string
pullPolicy buildah.PullPolicy
pullPolicy define.PullPolicy
registry string
ignoreUnrecognizedInstructions bool
quiet bool
@ -74,13 +75,13 @@ type Executor struct {
signaturePolicyPath string
systemContext *types.SystemContext
reportWriter io.Writer
isolation buildah.Isolation
namespaceOptions []buildah.NamespaceOption
configureNetwork buildah.NetworkConfigurationPolicy
isolation define.Isolation
namespaceOptions []define.NamespaceOption
configureNetwork define.NetworkConfigurationPolicy
cniPluginPath string
cniConfigDir string
idmappingOptions *buildah.IDMappingOptions
commonBuildOptions *buildah.CommonBuildOptions
idmappingOptions *define.IDMappingOptions
commonBuildOptions *define.CommonBuildOptions
defaultMountsFilePath string
iidfile string
squash bool
@ -98,7 +99,7 @@ type Executor struct {
excludes []string
unusedArgs map[string]struct{}
capabilities []string
devices buildah.ContainerDevices
devices define.ContainerDevices
signBy string
architecture string
timestamp *time.Time
@ -144,7 +145,7 @@ func NewExecutor(store storage.Store, options BuildOptions, mainNode *parser.Nod
return nil, err
}
devices := buildah.ContainerDevices{}
devices := define.ContainerDevices{}
for _, device := range append(defaultContainerConfig.Containers.Devices, options.Devices...) {
dev, err := parse.DeviceFromPath(device)
if err != nil {

View File

@ -13,6 +13,7 @@ import (
"github.com/containers/buildah"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
buildahdocker "github.com/containers/buildah/docker"
"github.com/containers/buildah/pkg/rusage"
"github.com/containers/buildah/util"
@ -275,7 +276,7 @@ func (s *StageExecutor) Copy(excludes []string, copies ...imagebuilder.Copy) err
// The From field says to read the content from another
// container. Update the ID mappings and
// all-content-comes-from-below-this-directory value.
var idMappingOptions *buildah.IDMappingOptions
var idMappingOptions *define.IDMappingOptions
var copyExcludes []string
stripSetuid := false
stripSetgid := false
@ -1234,7 +1235,7 @@ func (s *StageExecutor) commit(ctx context.Context, createdBy string, emptyLayer
s.builder.SetHealthcheck(nil)
}
s.builder.ClearLabels()
s.builder.SetLabel(buildah.BuilderIdentityAnnotation, buildah.Version)
s.builder.SetLabel(buildah.BuilderIdentityAnnotation, define.Version)
for k, v := range config.Labels {
s.builder.SetLabel(k, v)
}

View File

@ -3,6 +3,7 @@ package buildah
import (
"context"
"github.com/containers/buildah/define"
"github.com/containers/buildah/docker"
"github.com/containers/buildah/util"
"github.com/containers/image/v5/image"
@ -93,7 +94,7 @@ func importBuilderDataFromImage(ctx context.Context, store storage.Store, system
ImageAnnotations: map[string]string{},
ImageCreatedBy: "",
NamespaceOptions: defaultNamespaceOptions,
IDMappingOptions: IDMappingOptions{
IDMappingOptions: define.IDMappingOptions{
HostUIDMapping: len(uidmap) == 0,
HostGIDMapping: len(uidmap) == 0,
UIDMap: uidmap,

15
new.go
View File

@ -6,6 +6,7 @@ import (
"math/rand"
"strings"
"github.com/containers/buildah/define"
"github.com/containers/buildah/util"
"github.com/containers/image/v5/docker"
"github.com/containers/image/v5/image"
@ -86,7 +87,7 @@ func imageNamePrefix(imageName string) string {
return prefix
}
func newContainerIDMappingOptions(idmapOptions *IDMappingOptions) storage.IDMappingOptions {
func newContainerIDMappingOptions(idmapOptions *define.IDMappingOptions) storage.IDMappingOptions {
var options storage.IDMappingOptions
if idmapOptions != nil {
options.HostUIDMapping = idmapOptions.HostUIDMapping
@ -157,11 +158,11 @@ func resolveImage(ctx context.Context, systemContext *types.SystemContext, store
return localImageRef, localImageRef.Transport().Name(), localImage, nil
}
if options.PullPolicy == PullNever || options.PullPolicy == PullIfMissing {
if options.PullPolicy == define.PullNever || options.PullPolicy == define.PullIfMissing {
if localImage != nil {
return localImageRef, localImageRef.Transport().Name(), localImage, nil
}
if options.PullPolicy == PullNever {
if options.PullPolicy == define.PullNever {
return nil, "", nil, errors.Errorf("pull policy is %q but %q could not be found locally", "never", options.FromImage)
}
}
@ -183,7 +184,7 @@ func resolveImage(ctx context.Context, systemContext *types.SystemContext, store
// localImage`).
if desc := resolved.Description(); len(desc) > 0 {
logrus.Debug(desc)
if !(options.PullPolicy == PullIfNewer && localImage != nil) {
if !(options.PullPolicy == define.PullIfNewer && localImage != nil) {
if options.ReportWriter != nil {
if _, err := options.ReportWriter.Write([]byte(desc + "\n")); err != nil {
return nil, "", nil, err
@ -206,7 +207,7 @@ func resolveImage(ctx context.Context, systemContext *types.SystemContext, store
// If there's a local image, the `pullCandidate` is considered
// to be newer if its time stamp differs from the local one.
// Otherwise, we don't pull and skip it.
if options.PullPolicy == PullIfNewer && localImage != nil {
if options.PullPolicy == define.PullIfNewer && localImage != nil {
remoteImage, err := ref.NewImage(ctx, systemContext)
if err != nil {
logrus.Debugf("unable to remote-inspect image %q: %v", pullCandidate.Value.String(), err)
@ -249,7 +250,7 @@ func resolveImage(ctx context.Context, systemContext *types.SystemContext, store
// If we were looking for a newer image but could not find one, return
// the local image if present.
if options.PullPolicy == PullIfNewer && localImage != nil {
if options.PullPolicy == define.PullIfNewer && localImage != nil {
return localImageRef, localImageRef.Transport().Name(), localImage, nil
}
@ -407,7 +408,7 @@ func newBuilder(ctx context.Context, store storage.Store, options BuilderOptions
ConfigureNetwork: options.ConfigureNetwork,
CNIPluginPath: options.CNIPluginPath,
CNIConfigDir: options.CNIConfigDir,
IDMappingOptions: IDMappingOptions{
IDMappingOptions: define.IDMappingOptions{
HostUIDMapping: len(uidmap) == 0,
HostGIDMapping: len(uidmap) == 0,
UIDMap: uidmap,

View File

@ -10,7 +10,7 @@ import (
"runtime"
"strings"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/completion"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/buildah/util"
@ -361,7 +361,7 @@ func DefaultFormat() string {
if format != "" {
return format
}
return buildah.OCI
return define.OCI
}
// DefaultIsolation returns the default image format
@ -373,7 +373,7 @@ func DefaultIsolation() string {
if unshare.IsRootless() {
return "rootless"
}
return buildah.OCI
return define.OCI
}
// DefaultHistory returns the default add-history setting

View File

@ -14,7 +14,7 @@ import (
"strings"
"unicode"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/image/v5/types"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/unshare"
@ -45,7 +45,7 @@ var (
)
// CommonBuildOptions parses the build options from the bud cli
func CommonBuildOptions(c *cobra.Command) (*buildah.CommonBuildOptions, error) {
func CommonBuildOptions(c *cobra.Command) (*define.CommonBuildOptions, error) {
var (
memoryLimit int64
memorySwap int64
@ -125,7 +125,7 @@ func CommonBuildOptions(c *cobra.Command) (*buildah.CommonBuildOptions, error) {
ulimit, _ = c.Flags().GetStringSlice("ulimit")
}
commonOpts := &buildah.CommonBuildOptions{
commonOpts := &define.CommonBuildOptions{
AddHost: addHost,
CPUPeriod: cpuPeriod,
CPUQuota: cpuQuota,
@ -150,7 +150,7 @@ func CommonBuildOptions(c *cobra.Command) (*buildah.CommonBuildOptions, error) {
return commonOpts, nil
}
func parseSecurityOpts(securityOpts []string, commonOpts *buildah.CommonBuildOptions) error {
func parseSecurityOpts(securityOpts []string, commonOpts *define.CommonBuildOptions) error {
for _, opt := range securityOpts {
if opt == "no-new-privileges" {
return errors.Errorf("no-new-privileges is not supported")
@ -611,7 +611,7 @@ func SystemContextFromOptions(c *cobra.Command) (*types.SystemContext, error) {
if err == nil && c.Flag("registries-conf-dir").Changed {
ctx.RegistriesDirPath = regConfDir
}
ctx.DockerRegistryUserAgent = fmt.Sprintf("Buildah/%s", buildah.Version)
ctx.DockerRegistryUserAgent = fmt.Sprintf("Buildah/%s", define.Version)
if c.Flag("os") != nil && c.Flag("os").Changed {
if os, err := c.Flags().GetString("os"); err == nil {
ctx.OSChoice = os
@ -740,7 +740,7 @@ func getDockerAuth(creds string) (*types.DockerAuthConfig, error) {
}
// IDMappingOptions parses the build options related to user namespaces and ID mapping.
func IDMappingOptions(c *cobra.Command, isolation buildah.Isolation) (usernsOptions buildah.NamespaceOptions, idmapOptions *buildah.IDMappingOptions, err error) {
func IDMappingOptions(c *cobra.Command, isolation define.Isolation) (usernsOptions define.NamespaceOptions, idmapOptions *define.IDMappingOptions, err error) {
user := c.Flag("userns-uid-map-user").Value.String()
group := c.Flag("userns-gid-map-group").Value.String()
// If only the user or group was specified, use the same value for the
@ -815,7 +815,7 @@ func IDMappingOptions(c *cobra.Command, isolation buildah.Isolation) (usernsOpti
// By default, having mappings configured means we use a user
// namespace. Otherwise, we don't.
usernsOption := buildah.NamespaceOption{
usernsOption := define.NamespaceOption{
Name: string(specs.UserNamespace),
Host: len(uidmap) == 0 && len(gidmap) == 0,
}
@ -837,11 +837,11 @@ func IDMappingOptions(c *cobra.Command, isolation buildah.Isolation) (usernsOpti
usernsOption.Path = how
}
}
usernsOptions = buildah.NamespaceOptions{usernsOption}
usernsOptions = define.NamespaceOptions{usernsOption}
usernetwork := c.Flags().Lookup("network")
if usernetwork != nil && !usernetwork.Changed {
usernsOptions = append(usernsOptions, buildah.NamespaceOption{
usernsOptions = append(usernsOptions, define.NamespaceOption{
Name: string(specs.NetworkNamespace),
Host: usernsOption.Host,
})
@ -851,7 +851,7 @@ func IDMappingOptions(c *cobra.Command, isolation buildah.Isolation) (usernsOpti
if (len(uidmap) != 0 || len(gidmap) != 0) && usernsOption.Host {
return nil, nil, errors.Errorf("can not specify ID mappings while using host's user namespace")
}
return usernsOptions, &buildah.IDMappingOptions{
return usernsOptions, &define.IDMappingOptions{
HostUIDMapping: usernsOption.Host,
HostGIDMapping: usernsOption.Host,
UIDMap: uidmap,
@ -886,9 +886,9 @@ func parseIDMap(spec []string) (m [][3]uint32, err error) {
}
// NamespaceOptions parses the build options for all namespaces except for user namespace.
func NamespaceOptions(c *cobra.Command) (namespaceOptions buildah.NamespaceOptions, networkPolicy buildah.NetworkConfigurationPolicy, err error) {
options := make(buildah.NamespaceOptions, 0, 7)
policy := buildah.NetworkDefault
func NamespaceOptions(c *cobra.Command) (namespaceOptions define.NamespaceOptions, networkPolicy define.NetworkConfigurationPolicy, err error) {
options := make(define.NamespaceOptions, 0, 7)
policy := define.NetworkDefault
for _, what := range []string{string(specs.IPCNamespace), "network", string(specs.PIDNamespace), string(specs.UTSNamespace)} {
if c.Flags().Lookup(what) != nil && c.Flag(what).Changed {
how := c.Flag(what).Value.String()
@ -899,33 +899,33 @@ func NamespaceOptions(c *cobra.Command) (namespaceOptions buildah.NamespaceOptio
switch how {
case "", "container", "private":
logrus.Debugf("setting %q namespace to %q", what, "")
options.AddOrReplace(buildah.NamespaceOption{
options.AddOrReplace(define.NamespaceOption{
Name: what,
})
case "host":
logrus.Debugf("setting %q namespace to host", what)
options.AddOrReplace(buildah.NamespaceOption{
options.AddOrReplace(define.NamespaceOption{
Name: what,
Host: true,
})
default:
if what == string(specs.NetworkNamespace) {
if how == "none" {
options.AddOrReplace(buildah.NamespaceOption{
options.AddOrReplace(define.NamespaceOption{
Name: what,
})
policy = buildah.NetworkDisabled
policy = define.NetworkDisabled
logrus.Debugf("setting network to disabled")
break
}
}
how = strings.TrimPrefix(how, "ns:")
if _, err := os.Stat(how); err != nil {
return nil, buildah.NetworkDefault, errors.Wrapf(err, "error checking for %s namespace", what)
return nil, define.NetworkDefault, errors.Wrapf(err, "error checking for %s namespace", what)
}
policy = buildah.NetworkEnabled
policy = define.NetworkEnabled
logrus.Debugf("setting %q namespace to %q", what, how)
options.AddOrReplace(buildah.NamespaceOption{
options.AddOrReplace(define.NamespaceOption{
Name: what,
Path: how,
})
@ -935,36 +935,36 @@ func NamespaceOptions(c *cobra.Command) (namespaceOptions buildah.NamespaceOptio
return options, policy, nil
}
func defaultIsolation() (buildah.Isolation, error) {
func defaultIsolation() (define.Isolation, error) {
isolation, isSet := os.LookupEnv("BUILDAH_ISOLATION")
if isSet {
switch strings.ToLower(isolation) {
case "oci":
return buildah.IsolationOCI, nil
return define.IsolationOCI, nil
case "rootless":
return buildah.IsolationOCIRootless, nil
return define.IsolationOCIRootless, nil
case "chroot":
return buildah.IsolationChroot, nil
return define.IsolationChroot, nil
default:
return 0, errors.Errorf("unrecognized $BUILDAH_ISOLATION value %q", isolation)
}
}
if unshare.IsRootless() {
return buildah.IsolationOCIRootless, nil
return define.IsolationOCIRootless, nil
}
return buildah.IsolationDefault, nil
return define.IsolationDefault, nil
}
// IsolationOption parses the --isolation flag.
func IsolationOption(isolation string) (buildah.Isolation, error) {
func IsolationOption(isolation string) (define.Isolation, error) {
if isolation != "" {
switch strings.ToLower(isolation) {
case "oci":
return buildah.IsolationOCI, nil
return define.IsolationOCI, nil
case "rootless":
return buildah.IsolationOCIRootless, nil
return define.IsolationOCIRootless, nil
case "chroot":
return buildah.IsolationChroot, nil
return define.IsolationChroot, nil
default:
return 0, errors.Errorf("unrecognized isolation type %q", isolation)
}

View File

@ -6,13 +6,14 @@ import (
"os"
"path/filepath"
"github.com/containers/buildah/define"
"github.com/containers/storage/pkg/unshare"
"github.com/opencontainers/runc/libcontainer/devices"
"github.com/pkg/errors"
)
func DeviceFromPath(device string) ([]devices.Device, error) {
var devs []devices.Device
func DeviceFromPath(device string) (define.ContainerDevices, error) {
var devs define.ContainerDevices
src, dst, permissions, err := Device(device)
if err != nil {
return nil, err

View File

@ -3,7 +3,7 @@
package parse
import (
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/pkg/errors"
)
@ -11,6 +11,6 @@ func getDefaultProcessLimits() []string {
return []string{}
}
func DeviceFromPath(device string) (buildah.ContainerDevices, error) {
return buildah.ContainerDevices{}, errors.Errorf("devices not supported")
func DeviceFromPath(device string) (define.ContainerDevices, error) {
return nil, errors.Errorf("devices not supported")
}

View File

@ -6,6 +6,7 @@ import (
"strings"
"time"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/blobcache"
"github.com/containers/image/v5/directory"
"github.com/containers/image/v5/docker"
@ -61,7 +62,7 @@ type PullOptions struct {
// encrypted if non-nil. If nil, it does not attempt to decrypt an image.
OciDecryptConfig *encconfig.DecryptConfig
// PullPolicy takes the value PullIfMissing, PullAlways, PullIfNewer, or PullNever.
PullPolicy PullPolicy
PullPolicy define.PullPolicy
}
func localImageNameForReference(ctx context.Context, store storage.Store, srcRef types.ImageReference) (string, error) {

91
run.go
View File

@ -4,12 +4,13 @@ import (
"fmt"
"io"
"github.com/containers/buildah/define"
"github.com/opencontainers/runtime-spec/specs-go"
)
const (
// runUsingRuntimeCommand is a command we use as a key for reexec
runUsingRuntimeCommand = Package + "-oci-runtime"
runUsingRuntimeCommand = define.Package + "-oci-runtime"
)
// TerminalPolicy takes the value DefaultTerminal, WithoutTerminal, or WithTerminal.
@ -41,74 +42,38 @@ func (t TerminalPolicy) String() string {
}
// NamespaceOption controls how we set up a namespace when launching processes.
type NamespaceOption struct {
// Name specifies the type of namespace, typically matching one of the
// ...Namespace constants defined in
// github.com/opencontainers/runtime-spec/specs-go.
Name string
// Host is used to force our processes to use the host's namespace of
// this type.
Host bool
// Path is the path of the namespace to attach our process to, if Host
// is not set. If Host is not set and Path is also empty, a new
// namespace will be created for the process that we're starting.
// If Name is specs.NetworkNamespace, if Path doesn't look like an
// absolute path, it is treated as a comma-separated list of CNI
// configuration names which will be selected from among all of the CNI
// network configurations which we find.
Path string
}
type NamespaceOption = define.NamespaceOption
// NamespaceOptions provides some helper methods for a slice of NamespaceOption
// structs.
type NamespaceOptions []NamespaceOption
type NamespaceOptions = define.NamespaceOptions
// IDMappingOptions controls how we set up UID/GID mapping when we set up a
// user namespace.
type IDMappingOptions struct {
HostUIDMapping bool
HostGIDMapping bool
UIDMap []specs.LinuxIDMapping
GIDMap []specs.LinuxIDMapping
}
type IDMappingOptions = define.IDMappingOptions
// Isolation provides a way to specify whether we're supposed to use a proper
// OCI runtime, or some other method for running commands.
type Isolation int
type Isolation = define.Isolation
const (
// IsolationDefault is whatever we think will work best.
IsolationDefault Isolation = iota
IsolationDefault = define.IsolationDefault
// IsolationOCI is a proper OCI runtime.
IsolationOCI
IsolationOCI = define.IsolationOCI
// IsolationChroot is a more chroot-like environment: less isolation,
// but with fewer requirements.
IsolationChroot
IsolationChroot = define.IsolationChroot
// IsolationOCIRootless is a proper OCI runtime in rootless mode.
IsolationOCIRootless
IsolationOCIRootless = define.IsolationOCIRootless
)
// String converts a Isolation into a string.
func (i Isolation) String() string {
switch i {
case IsolationDefault:
return "IsolationDefault"
case IsolationOCI:
return "IsolationOCI"
case IsolationChroot:
return "IsolationChroot"
case IsolationOCIRootless:
return "IsolationOCIRootless"
}
return fmt.Sprintf("unrecognized isolation type %d", i)
}
// RunOptions can be used to alter how a command is run in the container.
type RunOptions struct {
// Hostname is the hostname we set for the running container.
Hostname string
// Isolation is either IsolationDefault, IsolationOCI, IsolationChroot, or IsolationOCIRootless.
Isolation Isolation
Isolation define.Isolation
// Runtime is the name of the runtime to run. It should accept the
// same arguments that runc does, and produce similar output.
Runtime string
@ -131,13 +96,13 @@ type RunOptions struct {
// Entrypoint is an override for the configured entry point.
Entrypoint []string
// NamespaceOptions controls how we set up the namespaces for the process.
NamespaceOptions NamespaceOptions
NamespaceOptions define.NamespaceOptions
// ConfigureNetwork controls whether or not network interfaces and
// routing are configured for a new network namespace (i.e., when not
// joining another's namespace and not just using the host's
// namespace), effectively deciding whether or not the process has a
// usable network.
ConfigureNetwork NetworkConfigurationPolicy
ConfigureNetwork define.NetworkConfigurationPolicy
// CNIPluginPath is the location of CNI plugin helpers, if they should be
// run from a location other than the default location.
CNIPluginPath string
@ -168,33 +133,5 @@ type RunOptions struct {
// lists, it will be dropped.
DropCapabilities []string
// Devices are the additional devices to add to the containers
Devices ContainerDevices
}
// Find the configuration for the namespace of the given type. If there are
// duplicates, find the _last_ one of the type, since we assume it was appended
// more recently.
func (n *NamespaceOptions) Find(namespace string) *NamespaceOption {
for i := range *n {
j := len(*n) - 1 - i
if (*n)[j].Name == namespace {
return &((*n)[j])
}
}
return nil
}
// AddOrReplace either adds or replaces the configuration for a given namespace.
func (n *NamespaceOptions) AddOrReplace(options ...NamespaceOption) {
nextOption:
for _, option := range options {
for i := range *n {
j := len(*n) - 1 - i
if (*n)[j].Name == option.Name {
(*n)[j] = option
continue nextOption
}
}
*n = append(*n, option)
}
Devices define.ContainerDevices
}

View File

@ -24,6 +24,7 @@ import (
"github.com/containers/buildah/bind"
"github.com/containers/buildah/chroot"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/overlay"
"github.com/containers/buildah/util"
"github.com/containers/common/pkg/capabilities"
@ -39,7 +40,6 @@ import (
"github.com/docker/libnetwork/resolvconf"
"github.com/docker/libnetwork/types"
"github.com/opencontainers/go-digest"
"github.com/opencontainers/runc/libcontainer/devices"
"github.com/opencontainers/runtime-spec/specs-go"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
@ -51,7 +51,7 @@ import (
)
// ContainerDevices is an alias for a slice of github.com/opencontainers/runc/libcontainer/configs.Device structures.
type ContainerDevices = []devices.Device
type ContainerDevices define.ContainerDevices
func setChildProcess() error {
if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, uintptr(1), 0, 0, 0); err != nil {
@ -63,7 +63,7 @@ func setChildProcess() error {
// Run runs the specified command in the container's root filesystem.
func (b *Builder) Run(command []string, options RunOptions) error {
p, err := ioutil.TempDir("", Package)
p, err := ioutil.TempDir("", define.Package)
if err != nil {
return err
}
@ -87,10 +87,10 @@ func (b *Builder) Run(command []string, options RunOptions) error {
g := &gp
isolation := options.Isolation
if isolation == IsolationDefault {
if isolation == define.IsolationDefault {
isolation = b.Isolation
if isolation == IsolationDefault {
isolation = IsolationOCI
if isolation == define.IsolationDefault {
isolation = define.IsolationOCI
}
}
if err := checkAndOverrideIsolationOptions(isolation, &options); err != nil {
@ -200,7 +200,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
return err
}
// Only bind /etc/hosts if there's a network
if options.ConfigureNetwork != NetworkDisabled {
if options.ConfigureNetwork != define.NetworkDisabled {
bindFiles["/etc/hosts"] = hostFile
}
}
@ -211,7 +211,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
return err
}
// Only bind /etc/resolv.conf if there's a network
if options.ConfigureNetwork != NetworkDisabled {
if options.ConfigureNetwork != define.NetworkDisabled {
bindFiles["/etc/resolv.conf"] = resolvFile
}
}
@ -234,7 +234,7 @@ id=%q
image=%q
imageid=%q
rootless=%d
`, Version, b.Container, b.ContainerID, b.FromImage, b.FromImageID, rootless)
`, define.Version, b.Container, b.ContainerID, b.FromImage, b.FromImageID, rootless)
if err = ioutils.AtomicWriteFile(containerenvPath, []byte(containerenv), 0755); err != nil {
return err
@ -266,14 +266,14 @@ rootless=%d
}
switch isolation {
case IsolationOCI:
case define.IsolationOCI:
var moreCreateArgs []string
if options.NoPivot {
moreCreateArgs = []string{"--no-pivot"}
} else {
moreCreateArgs = nil
}
err = b.runUsingRuntimeSubproc(isolation, options, configureNetwork, configureNetworks, moreCreateArgs, spec, mountPoint, path, Package+"-"+filepath.Base(path))
err = b.runUsingRuntimeSubproc(isolation, options, configureNetwork, configureNetworks, moreCreateArgs, spec, mountPoint, path, define.Package+"-"+filepath.Base(path))
case IsolationChroot:
err = chroot.RunUsingChroot(spec, path, homeDir, options.Stdin, options.Stdout, options.Stderr)
case IsolationOCIRootless:
@ -284,14 +284,14 @@ rootless=%d
if err := setupRootlessSpecChanges(spec, path, b.CommonBuildOpts.ShmSize); err != nil {
return err
}
err = b.runUsingRuntimeSubproc(isolation, options, configureNetwork, configureNetworks, moreCreateArgs, spec, mountPoint, path, Package+"-"+filepath.Base(path))
err = b.runUsingRuntimeSubproc(isolation, options, configureNetwork, configureNetworks, moreCreateArgs, spec, mountPoint, path, define.Package+"-"+filepath.Base(path))
default:
err = errors.Errorf("don't know how to run this command")
}
return err
}
func addCommonOptsToSpec(commonOpts *CommonBuildOptions, g *generate.Generator) error {
func addCommonOptsToSpec(commonOpts *define.CommonBuildOptions, g *generate.Generator) error {
// Resources - CPU
if commonOpts.CPUPeriod != 0 {
g.SetLinuxResourcesCPUPeriod(commonOpts.CPUPeriod)
@ -393,7 +393,7 @@ func runSetupBuiltinVolumes(mountLabel, mountPoint, containerDir string, builtin
return mounts, nil
}
func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, bundlePath string, optionMounts []specs.Mount, bindFiles map[string]string, builtinVolumes, volumeMounts []string, shmSize string, namespaceOptions NamespaceOptions) error {
func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, bundlePath string, optionMounts []specs.Mount, bindFiles map[string]string, builtinVolumes, volumeMounts []string, shmSize string, namespaceOptions define.NamespaceOptions) error {
// Start building a new list of mounts.
var mounts []specs.Mount
haveMount := func(destination string) bool {
@ -535,7 +535,7 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, bundlePath st
}
// addNetworkConfig copies files from host and sets them up to bind mount into container
func (b *Builder) addNetworkConfig(rdir, hostPath string, chownOpts *idtools.IDPair, dnsServers, dnsSearch, dnsOptions []string, namespaceOptions NamespaceOptions) (string, error) {
func (b *Builder) addNetworkConfig(rdir, hostPath string, chownOpts *idtools.IDPair, dnsServers, dnsSearch, dnsOptions []string, namespaceOptions define.NamespaceOptions) (string, error) {
stat, err := os.Stat(hostPath)
if err != nil {
return "", err
@ -678,7 +678,7 @@ func setupTerminal(g *generate.Generator, terminalPolicy TerminalPolicy, termina
}
}
func runUsingRuntime(isolation Isolation, options RunOptions, configureNetwork bool, configureNetworks, moreCreateArgs []string, spec *specs.Spec, bundlePath, containerName string) (wstatus unix.WaitStatus, err error) {
func runUsingRuntime(isolation define.Isolation, options RunOptions, configureNetwork bool, configureNetworks, moreCreateArgs []string, spec *specs.Spec, bundlePath, containerName string) (wstatus unix.WaitStatus, err error) {
// Lock the caller to a single OS-level thread.
runtime.LockOSThread()
@ -1040,7 +1040,7 @@ func setupRootlessNetwork(pid int) (teardown func(), err error) {
}, nil
}
func runConfigureNetwork(isolation Isolation, options RunOptions, configureNetworks []string, pid int, containerName string, command []string) (teardown func(), err error) {
func runConfigureNetwork(isolation define.Isolation, options RunOptions, configureNetworks []string, pid int, containerName string, command []string) (teardown func(), err error) {
var netconf, undo []*libcni.NetworkConfigList
if isolation == IsolationOCIRootless {
@ -1504,7 +1504,7 @@ func runUsingRuntimeMain() {
os.Exit(1)
}
func setupNamespaces(g *generate.Generator, namespaceOptions NamespaceOptions, idmapOptions IDMappingOptions, policy NetworkConfigurationPolicy) (configureNetwork bool, configureNetworks []string, configureUTS bool, err error) {
func setupNamespaces(g *generate.Generator, namespaceOptions define.NamespaceOptions, idmapOptions define.IDMappingOptions, policy define.NetworkConfigurationPolicy) (configureNetwork bool, configureNetworks []string, configureUTS bool, err error) {
// Set namespace options in the container configuration.
configureUserns := false
specifiedNetwork := false
@ -1523,7 +1523,7 @@ func setupNamespaces(g *generate.Generator, namespaceOptions NamespaceOptions, i
configureNetworks = strings.Split(namespaceOption.Path, ",")
namespaceOption.Path = ""
}
configureNetwork = (policy != NetworkDisabled)
configureNetwork = (policy != define.NetworkDisabled)
}
case string(specs.UTSNamespace):
configureUTS = false
@ -1572,7 +1572,7 @@ func setupNamespaces(g *generate.Generator, namespaceOptions NamespaceOptions, i
if err := g.AddOrReplaceLinuxNamespace(string(specs.NetworkNamespace), ""); err != nil {
return false, nil, false, errors.Wrapf(err, "error adding new %q namespace for run", string(specs.NetworkNamespace))
}
configureNetwork = (policy != NetworkDisabled)
configureNetwork = (policy != define.NetworkDisabled)
}
} else {
if err := g.RemoveLinuxNamespace(string(specs.UserNamespace)); err != nil {
@ -2084,7 +2084,7 @@ func setupRootlessSpecChanges(spec *specs.Spec, bundleDir string, shmSize string
return nil
}
func (b *Builder) runUsingRuntimeSubproc(isolation Isolation, options RunOptions, configureNetwork bool, configureNetworks, moreCreateArgs []string, spec *specs.Spec, rootPath, bundlePath, containerName string) (err error) {
func (b *Builder) runUsingRuntimeSubproc(isolation define.Isolation, options RunOptions, configureNetwork bool, configureNetworks, moreCreateArgs []string, spec *specs.Spec, rootPath, bundlePath, containerName string) (err error) {
var confwg sync.WaitGroup
config, conferr := json.Marshal(runUsingRuntimeSubprocOptions{
Options: options,
@ -2144,13 +2144,13 @@ func (b *Builder) runUsingRuntimeSubproc(isolation Isolation, options RunOptions
return err
}
func checkAndOverrideIsolationOptions(isolation Isolation, options *RunOptions) error {
func checkAndOverrideIsolationOptions(isolation define.Isolation, options *RunOptions) error {
switch isolation {
case IsolationOCIRootless:
if ns := options.NamespaceOptions.Find(string(specs.IPCNamespace)); ns == nil || ns.Host {
logrus.Debugf("Forcing use of an IPC namespace.")
}
options.NamespaceOptions.AddOrReplace(NamespaceOption{Name: string(specs.IPCNamespace)})
options.NamespaceOptions.AddOrReplace(define.NamespaceOption{Name: string(specs.IPCNamespace)})
_, err := exec.LookPath("slirp4netns")
hostNetworking := err != nil
networkNamespacePath := ""
@ -2162,7 +2162,7 @@ func checkAndOverrideIsolationOptions(isolation Isolation, options *RunOptions)
networkNamespacePath = ""
}
}
options.NamespaceOptions.AddOrReplace(NamespaceOption{
options.NamespaceOptions.AddOrReplace(define.NamespaceOption{
Name: string(specs.NetworkNamespace),
Host: hostNetworking,
Path: networkNamespacePath,
@ -2170,11 +2170,11 @@ func checkAndOverrideIsolationOptions(isolation Isolation, options *RunOptions)
if ns := options.NamespaceOptions.Find(string(specs.PIDNamespace)); ns == nil || ns.Host {
logrus.Debugf("Forcing use of a PID namespace.")
}
options.NamespaceOptions.AddOrReplace(NamespaceOption{Name: string(specs.PIDNamespace), Host: false})
options.NamespaceOptions.AddOrReplace(define.NamespaceOption{Name: string(specs.PIDNamespace), Host: false})
if ns := options.NamespaceOptions.Find(string(specs.UserNamespace)); ns == nil || ns.Host {
logrus.Debugf("Forcing use of a user namespace.")
}
options.NamespaceOptions.AddOrReplace(NamespaceOption{Name: string(specs.UserNamespace)})
options.NamespaceOptions.AddOrReplace(define.NamespaceOption{Name: string(specs.UserNamespace)})
case IsolationOCI:
pidns := options.NamespaceOptions.Find(string(specs.PIDNamespace))
userns := options.NamespaceOptions.Find(string(specs.UserNamespace))
@ -2187,8 +2187,8 @@ func checkAndOverrideIsolationOptions(isolation Isolation, options *RunOptions)
// DefaultNamespaceOptions returns the default namespace settings from the
// runtime-tools generator library.
func DefaultNamespaceOptions() (NamespaceOptions, error) {
options := NamespaceOptions{
func DefaultNamespaceOptions() (define.NamespaceOptions, error) {
options := define.NamespaceOptions{
{Name: string(specs.CgroupNamespace), Host: true},
{Name: string(specs.IPCNamespace), Host: true},
{Name: string(specs.MountNamespace), Host: true},
@ -2204,7 +2204,7 @@ func DefaultNamespaceOptions() (NamespaceOptions, error) {
spec := g.Config
if spec.Linux != nil {
for _, ns := range spec.Linux.Namespaces {
options.AddOrReplace(NamespaceOption{
options.AddOrReplace(define.NamespaceOption{
Name: string(ns.Type),
Path: ns.Path,
})
@ -2231,7 +2231,7 @@ type runUsingRuntimeSubprocOptions struct {
ConfigureNetworks []string
MoreCreateArgs []string
ContainerName string
Isolation Isolation
Isolation define.Isolation
}
func init() {

View File

@ -6,9 +6,6 @@ import (
"github.com/pkg/errors"
)
// ContainerDevices is currently not implemented.
type ContainerDevices = []struct{}
func setChildProcess() error {
return errors.New("function not supported on non-linux systems")
}

View File

@ -22,6 +22,7 @@ import (
"github.com/containers/buildah"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/define"
"github.com/containers/buildah/imagebuildah"
"github.com/containers/image/v5/docker/daemon"
"github.com/containers/image/v5/image"
@ -507,8 +508,8 @@ func buildUsingBuildah(ctx context.Context, t *testing.T, store storage.Store, t
output := &bytes.Buffer{}
options := imagebuildah.BuildOptions{
ContextDirectory: contextDir,
CommonBuildOpts: &buildah.CommonBuildOptions{},
NamespaceOptions: []buildah.NamespaceOption{{
CommonBuildOpts: &define.CommonBuildOptions{},
NamespaceOptions: []define.NamespaceOption{{
Name: string(rspec.NetworkNamespace),
Host: true,
}},