Compare commits

...

121 Commits
v0.8 ... v0.15

Author SHA1 Message Date
Daniel J Walsh
d1330a5c46 Bump to v0.15
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #503
Approved by: rhatdan
2018-02-27 12:54:29 +00:00
Daniel J Walsh
b75bf0a5b3 Currently buildah run is not handling command options correctly
This patch will allow commands like

buildah run $ctr ls -lZ /

To work correctly.

Need to update vendor of urfave cli.

Also changed all commands to no longer accept global options after the COMMAND.
Single boolean options can now be passed together.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #493
Approved by: rhatdan
2018-02-27 12:08:45 +00:00
TomSweeneyRedHat
cb42905a7f Add selinux test from #486
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #501
Approved by: rhatdan
2018-02-27 00:47:42 +00:00
Daniel J Walsh
ee11d75f3e Bump to v0.14
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #499
Approved by: rhatdan
2018-02-27 00:28:50 +00:00
Daniel J Walsh
9bf5a5e52a Breaking change on CommonBuildOpts
Just have to refuse to use previous created containers when doing a run.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #500
Approved by: rhatdan
2018-02-27 00:05:12 +00:00
Daniel J Walsh
873ecd8791 If commonOpts do not exist, we should return rather then segfault
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #498
Approved by: TomSweeneyRedHat
2018-02-26 22:49:44 +00:00
Shyukri Shyukriev
99066e0104 Add openSUSE in install section
Signed-off-by: Shyukri Shyukriev <shshyukriev@suse.com>

Closes: #492
Approved by: rhatdan
2018-02-26 00:20:33 +00:00
TomSweeneyRedHat
68a6c0a4c0 Display full error string instead of just status
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #485
Approved by: rhatdan
2018-02-24 09:12:53 +00:00
Daniel J Walsh
963c1d95c0 Merge pull request #494 from umohnani8/secrets
Fix secrets patch for buildah bud
2018-02-23 13:49:47 -05:00
umohnani8
4bbe6e7cc0 Implement --volume and --shm-size for bud and from
Add the remaining --volume and --shm-size flags to buildah bud and from
--volume supports the following options: rw, ro, z, Z, private, slave, shared

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #491
Approved by: rhatdan
2018-02-23 17:53:00 +00:00
umohnani8
fb14850b50 Fix secrets patch for buildah bud
buildah bud was failing to get the secrets data
The issue was buildah bud was not being given the /usr/share/containers/mounts.conf file path
so it had no secrets to mount
Also reworked the way the secrets data was being copied from the host to the container

Signed-off-by: umohnani8 <umohnani@redhat.com>
2018-02-23 12:38:39 -05:00
umohnani8
669ffddd99 Vendor in latest containers/image
Fixes the naming issue of blobs and config for the dir transport
by removing the .tar extension

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #489
Approved by: rhatdan
2018-02-22 18:57:31 +00:00
TomSweeneyRedHat
ac093aecd1 Add libseccomp-devel to packages to install
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #490
Approved by: rhatdan
2018-02-22 18:01:09 +00:00
Daniel J Walsh
ef0ca9cd2d Bump to v0.13
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #488
Approved by: TomSweeneyRedHat
2018-02-22 14:25:16 +00:00
Daniel J Walsh
5ca91c0eb7 Vendor in latest containers/storage
This fixes a large SELinux bug.  Currently if you do the following
commands

ctr=$(buildah from scratch)
mnt=$(buildah mount $ctr)
dnf install --installroot=$mnt httpd
buildah run $ctr touch /test

The last command fails.  The reason for this is the SELinux labels are getting applied
to the mount point, since it was not being mounted as an overlay file system.

Containers/storage was updated to always mount an overlay even if the lower layer is empty
This then causes the mount point to use a context mount, and changes dnf to not apply
labels.  This change then allows buildah run to create confined containers to run code.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #486
Approved by: TomSweeneyRedHat
2018-02-22 13:55:26 +00:00
baude
e623e5c004 Initial ginkgo framework
This is an initial attempt at bringing in the ginkgo test framework into
buildah.  The inspect bats file was also imported.

Signed-off-by: baude <bbaude@redhat.com>

Closes: #472
Approved by: rhatdan
2018-02-22 13:06:08 +00:00
Giuseppe Scrivano
9d163a50d1 run: do not open /etc/hosts if not needed
Avoid opening the file in write mode if we are not going to write
anything.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>

Closes: #487
Approved by: rhatdan
2018-02-22 13:04:38 +00:00
umohnani8
93a3c89943 Add the following flags to buildah bud and from
--add-host
	--cgroup-parent
	--cpu-period
	--cpu-quota
	--cpu-shares
	--cpuset-cpus
	--cpuset-mems
	--memory
	--memory-swap
	--security-opt
	--ulimit

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #477
Approved by: rhatdan
2018-02-19 17:00:29 +00:00
umohnani8
b23f145416 Vendor in packages
vendor in profiles from github.com/docker/docker/profiles to support seccomp.
vendor in latest runtime-tools to support bind mounting.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #477
Approved by: rhatdan
2018-02-19 17:00:29 +00:00
TomSweeneyRedHat
43d1102d02 Touchup doc in rpm spec
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #483
Approved by: rhatdan
2018-02-19 14:52:38 +00:00
TomSweeneyRedHat
95f16ab260 Remove you/your from manpages
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #484
Approved by: rhatdan
2018-02-19 14:30:16 +00:00
Michael Gugino
09e7ddf544 Fix README link to tutorials
Current link is broken.

This commit corrects the link to point at the
correct file.

Signed-off-by: Michael Gugino <mgugino@redhat.com>

Closes: #480
Approved by: nalind
2018-02-15 15:15:15 +00:00
TomSweeneyRedHat
ee383ec9cf Add redis test to baseline
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #476
Approved by: nalind
2018-02-14 14:18:08 +00:00
TomSweeneyRedHat
d59af12866 Fix versioning to 0.12
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #478
Approved by: rhatdan
2018-02-14 10:06:43 +00:00
Daniel J Walsh
e073df11aa Merge pull request #473 from rhatdan/master
Bump version to 0.12
2018-02-12 12:08:24 -05:00
Daniel J Walsh
8badcc2d02 Bump version to 0.12
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
2018-02-12 11:48:48 -05:00
Daniel J Walsh
a586779353 We are copying a directory not a single file
When populating a container from a container image with a
volume directory, we need to copy the content of the source
directory into the target.  The code was mistakenly looking
for a file not a directory.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #471
Approved by: nalind
2018-02-12 15:57:23 +00:00
umohnani8
4eb654f10c Removing docs and completions for run options
Figured that these options need to be in from and bud instead.
Removed the options from the documentation of run and bud for now.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #470
Approved by: rhatdan
2018-02-12 15:22:09 +00:00
Boaz Shuster
f29314579d Return multi errors in buildah-rm
Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #458
Approved by: rhatdan
2018-02-12 12:02:37 +00:00
TomSweeneyRedHat
9e20c3d948 Don't drop error on mix case imagename
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #468
Approved by: rhatdan
2018-02-11 11:41:44 +00:00
TomSweeneyRedHat
46c1a54b15 Revert to using latest go-md2man
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #463
Approved by: rhatdan
2018-02-10 12:24:54 +00:00
Benjamin Kircher
67b565da7b Docs: note that buildah needs to run as root
You have to be root to run buildah. This commit adds a notice to the
buildah(1) man-page and improves the front-page README.md a bit so that
this is more obvious to the user.

Fixes issue #420.

Signed-off-by: Benjamin Kircher <benjamin.kircher@gmail.com>

Closes: #462
Approved by: rhatdan
2018-02-10 12:07:07 +00:00
baude
dd4a6aea97 COPR enablement
For COPR builds, we will use a a slightly modified spec and the
makesrpm method over SCM builds so we can have dynamic package
names.

Signed-off-by: baude <bbaude@redhat.com>

Closes: #460
Approved by: rhatdan
2018-02-10 11:49:46 +00:00
William Henry
9116598a2e Added handing for simpler error message for Unknown Dockerfile instructions.
Signed-off-by: William Henry <whenry@redhat.com>

Closes: #457
Approved by: rhatdan
2018-02-10 11:32:38 +00:00
TomSweeneyRedHat
df2a10d43f Add limitation to buildah rmi man page
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #464
Approved by: rhatdan
2018-02-10 11:15:34 +00:00
TomSweeneyRedHat
e9915937ac Rename tutorials.md to README.md in tutorial dir
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #459
Approved by: rhatdan
2018-02-10 11:14:52 +00:00
Daniel J Walsh
5a9c591abf Merge pull request #455 from umohnani8/certs
Make /etc/containers/certs.d the default certs directory
2018-02-07 08:44:32 -05:00
Daniel J Walsh
531ef9159d Merge pull request #446 from umohnani8/flags_docs
Add documentation and completions for the following flags
2018-02-06 17:21:41 -05:00
umohnani8
811cf927d7 Change default certs directory to /etc/containers/certs.dir
Made changes to the man pages to reflect this.

Signed-off-by: umohnani8 <umohnani@redhat.com>
2018-02-06 17:04:34 -05:00
umohnani8
032b56ee8d Vendor in latest containers/image
Adds support for default certs directory to be /etc/containers/certs.d

Signed-off-by: umohnani8 <umohnani@redhat.com>
2018-02-06 17:04:34 -05:00
Daniel J Walsh
6af847dd2a Vendor in latest containers/storage
A patch got merged into containers/storage that makes sure SELinux labels
are appliced when committing to storage.  This prevents a failure condition
which arrises from leaked mount points between the time a container is mounted
and it is committed.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #453
Approved by: TomSweeneyRedHat
2018-02-06 20:26:45 +00:00
Nalin Dahyabhai
6b207f7b0c Fix unintended reversal of the ignoreUnrecognizedInstructions flag
We were interpreting the ignoreUnrecognizedInstructions incorrectly, so
fix that, and call out the unrecognized instruction keyword in the error
message (or debug message, if we're ignoring it).

Should fix #451.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #452
Approved by: rhatdan
2018-02-06 18:58:25 +00:00
umohnani8
c14697ebe4 Add documentation and completions for the following flags
--add-host
	--cgroup-parent
	--cpu-period
	--cpu-quota
	--cpu-shares
	--cpuset-mems
	--memory
	--memory-swap
	--security-opt
	--ulimit

These flags are going to be used by buildah run and bud.
The implementation will follow in another PR.

Signed-off-by: umohnani8 <umohnani@redhat.com>
2018-02-06 12:45:17 -05:00
Nalin Dahyabhai
c35493248e build-using-dockerfile: set the 'author' field for MAINTAINER
When we encounter the MAINTAINER keyword in a Dockerfile, imagebuilder
updates the Author field in the imagebuilder.Builder structure.  Pick up
that value when we go to commit the image.

Should fix #448.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #450
Approved by: rhatdan
2018-02-06 01:18:55 +00:00
umohnani8
d03a894969 Fix md2man issues
Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #447
Approved by: rhatdan
2018-02-05 21:52:41 +00:00
Boaz Shuster
fbb8b702bc Return exit code 1 when buildah-rmi fails
Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #412
Approved by: rhatdan
2018-02-05 13:50:30 +00:00
Boaz Shuster
815cedfc71 Trim the image reference to just its name before calling getImageName
When setting a container name the getImageName function goes through
all the names of the resolved image and finds the name that contains
the given name by the user.

However, if the user is specifying "docker.io/tagged-image"
the Docker transport returns "docker.io/library/tagged-image" which
makes getImageName returns the original image name because it does
not find a match.

To resolve this issue before calling getImageName the image given
by the user will be trimmed to be just the name.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #422
Approved by: rhatdan
2018-02-04 11:26:43 +00:00
TomSweeneyRedHat
1c97f6ac2c Bump Fedora 26 to 27 in rpm test
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #444
Approved by: rhatdan
2018-02-04 11:25:25 +00:00
umohnani8
bc9d574c10 Add new line after executing template for buildah inspect
No new line was returned when using the --format flag for buildah
inspect.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #442
Approved by: rhatdan
2018-02-02 21:11:52 +00:00
TomSweeneyRedHat
c84db980ae Touch up rmi -f usage statement
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #441
Approved by: rhatdan
2018-02-02 20:15:08 +00:00
umohnani8
85a37b39e8 Add --format and --filter to buildah containers
buildah containers now supports oretty-printing using a Go template
with the --format flag. And output can be filtered based on id, name, or
ancestor.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #437
Approved by: rhatdan
2018-02-02 19:32:06 +00:00
Arthur Mello
49095a83f8 Add --prune,-p option to rmi command
Allows rmi to remove all dangling images (images without a tag and without a child image)
Add new test case

Signed-off-by: Arthur Mello <amello@redhat.com>

Closes: #418
Approved by: rhatdan
2018-02-01 10:50:33 +00:00
TomSweeneyRedHat
6c05a352df Add authfile param to commit
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #433
Approved by: rhatdan
2018-02-01 05:48:09 +00:00
umohnani8
1849466827 Fix --runtime-flag for buildah run and bud
The --runtime-flag flag for buildah run and bud would fail
whenever the global flags of the runtime were passed to it.
Changed it to accept the format [global-flag]=[value] where
global-flag would be converted to --[global-flag] in the code.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #431
Approved by: rhatdan
2018-01-30 18:21:46 +00:00
umohnani8
4f38267342 format should override quiet for images
quiet was overriding format, but we want format to override quiet
if both the flags are set for buildah images.

Changed it so that it errors out if both quiet and format are set.

Signed-off-by: umohnani8 <umohnani@redhat.com>

Closes: #426
Approved by: rhatdan
2018-01-30 17:06:51 +00:00
TomSweeneyRedHat
9790b89771 Allow all auth params to work with bud
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #419
Approved by: rhatdan
2018-01-30 15:41:52 +00:00
Fabio Bertinatto
61f5319504 Don't overwrite directory permissions on --chown
Signed-off-by: Fabio Bertinatto <fbertina@redhat.com>

Closes: #389
Approved by: rhatdan
2018-01-30 05:09:06 +00:00
Boaz Shuster
947714fbd2 Unescape HTML characters output into the terminal
By default, the JSON encoder from the Go standard library
escapes the HTML characters which causes the maintainer output
looks strange:

"maintainer": "NGINX Docker Maintainers \u003cdocker-maint@nginx.com\u003e"
Instead of:
"maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"

This patch fixes this issue in "buildah-inspect" only as this is
the only place that such characters are displayed.

Note: if the output of "buildah-inspect" is piped or redirected
then the HTML characters are not escaped.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #421
Approved by: rhatdan
2018-01-30 04:51:17 +00:00
Boaz Shuster
c615c3e23d Fix typo then->than
Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #423
Approved by: rhatdan
2018-01-29 05:50:24 +00:00
Daniel J Walsh
d0e1ad1a1a Merge pull request #415 from TomSweeneyRedHat/dev/tsweeney/pwdprompt
Prompt for un/pwd if not supplied with --creds
2018-01-27 09:34:51 +01:00
Boaz Shuster
b68f88c53d Fix: setting the container name to the image
In commit 47ac96155f the image name that is used
for setting the container name is taken from the resolved image
unless it is empty.

The image has the "Names" field and right now the first name is
taken. However, when the image is a tagged image, the container name
will end up using the original name instead of the given one.

For example:

$ buildah tag busybox busybox1
$ buildah from busybox1

Will set the name of the container as "busybox-working-container"
while it was expected to be "busybox1-working-container".

This patch fixes this particular issue.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #399
Approved by: rhatdan
2018-01-26 08:07:58 +00:00
TomSweeneyRedHat
7dc787a9c7 Prompt for un/pwd if not supplied with --creds
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>
2018-01-25 15:03:59 -05:00
TomSweeneyRedHat
2dbb2a13ed Make bud be really quiet
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #408
Approved by: rhatdan
2018-01-24 15:11:30 +00:00
Boaz Shuster
ad49b24d0b Return a better error message when failed to resolve an image
During the creation of a new builder object there are errors
that are only logged into "logrus.Debugf".

If in the end of the process "ref" or "img" are nil and "options.FromImage"
is set then it means that there was an issue.
By default, it was assumed that the image name is wrong. Yet,
this assumption isn't always correct. For example, it might fail due to
authorization or connection errors.

In this patch, I am attempting to fix this problem by checking the
last error stored in the "err" variable and returning the cause
of the failure.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #406
Approved by: rhatdan
2018-01-24 14:03:28 +00:00
Boaz Shuster
ba128004ca Fix "make validate" warnings
Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #405
Approved by: rhatdan
2018-01-22 14:46:54 +00:00
TomSweeneyRedHat
5179733c63 Update auth tests and fix bud man page
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #404
Approved by: rhatdan
2018-01-22 13:34:50 +00:00
TomSweeneyRedHat
40c3a57d5a Try to fix buildah-containers.md CI test issue
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #395
Approved by: rhatdan
2018-01-19 20:20:13 +00:00
Daniel J Walsh
de9e71dda7 Drop support for 1.7
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #400
Approved by: rhatdan
2018-01-18 23:00:15 +00:00
TomSweeneyRedHat
1052f3ba40 Create Buildah issue template
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #397
Approved by: rhatdan
2018-01-18 11:56:31 +00:00
Daniel J Walsh
6bad262ff1 Bump to version 0.11
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #394
Approved by: @ripcurld0
2018-01-17 13:42:19 +00:00
TomSweeneyRedHat
092591620b Show ctrid when doing rm -all
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #392
Approved by: rhatdan
2018-01-16 18:38:28 +00:00
Boaz Shuster
4d6c90e902 vendor containers/image to 386d6c33c9d622ed84baf14f4b1ff1be86800ccd
Signed-off-by: Boaz Shuster <bshuster@redhat.com>

Closes: #393
Approved by: rhatdan
2018-01-16 16:44:34 +00:00
TomSweeneyRedHat
17d9a73329 Touchup rm and container man pages
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #391
Approved by: rhatdan
2018-01-16 15:48:29 +00:00
Boaz Shuster
fe2de4f491 Handle commit error gracefully
This change gives a better error message when the commit fails
because of bad authentication.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #385
Approved by: rhatdan
2018-01-15 15:48:20 +00:00
TomSweeneyRedHat
adfb256a0f Remove new errors and use established ones in rmi
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #388
Approved by: rhatdan
2018-01-10 17:01:41 +00:00
Huamin Chen
029bdbcbd0 fix buildah push description
Signed-off-by: Huamin Chen <hchen@redhat.com>

Closes: #387
Approved by: rhatdan
2018-01-09 18:45:53 +00:00
TomSweeneyRedHat
fd995e6166 Add --all functionality to rmi
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #384
Approved by: rhatdan
2018-01-08 21:07:25 +00:00
Nalin Dahyabhai
ae7d2f3547 Ignore sequential duplicate layers when reading v2s1
When a v2s1 image is stored to disk, some of the layer blobs listed in
its manifest may be discarded as.  Account for this.

Start treating a failure to decode v1compat information as a fatal error
instead of trying to fake it.

Tweak how we build the created-by field in history when generating one
from v2s1 information to better match what we see in v2s2 images.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #383
Approved by: rhatdan
2018-01-08 21:06:35 +00:00
Nalin Dahyabhai
86fa0803e8 Sanity check the history/diffid list sizes
When building an image's config blob, add a sanity check that the number
of diffIDs that we're including matches the number of entries in the
history which don't claim to be empty layers.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #383
Approved by: rhatdan
2018-01-08 21:06:35 +00:00
Nalin Dahyabhai
81dfe0a964 When we say we skip a secrets config file, do so
When we warn about not processing a secrets configuration file, actually
skip anything we might have salvaged from it to make our behavior match
the warning.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #380
Approved by: rhatdan
2018-01-05 16:09:53 +00:00
Nalin Dahyabhai
9bff989832 Use NewImageSource() instead of NewImage()
Use NewImageSource() instead of NewImage() when checking if an image is
actually there, since it makes the image library do less work while
answering the same question for us.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #381
Approved by: rhatdan
2018-01-05 15:54:34 +00:00
TomSweeneyRedHat
b8740e386e Add --all to remove containers
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #382
Approved by: rhatdan
2018-01-05 15:53:19 +00:00
Daniel J Walsh
9f5e1b3a77 Make lint was complaining about some vetshowed err
We often use err as a variable inside of subblocks, and
we don't want golint to complain about it.

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #379
Approved by: nalind
2018-01-03 21:10:28 +00:00
Daniel J Walsh
01f8c7afee Remove chrootuser handling and use libpod/pkg
I have made a subpackage of libpod to handle chrootuser,
using the user code from buildah.

This patch removes user handling from buildah and uses
projectatomic/libpod/pkg/chrootuser

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #377
Approved by: nalind
2018-01-03 15:36:10 +00:00
TomSweeneyRedHat
67e5341846 Add kernel version requirement to install.md and touchups
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #372
Approved by: rhatdan
2018-01-03 13:00:36 +00:00
Daniel J Walsh
123493895f Merge pull request #370 from rhatdan/master
Bump to version 0.10
2017-12-26 07:18:41 -05:00
Daniel J Walsh
129fb109d5 Bump to version 0.10
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
2017-12-24 06:59:23 -05:00
Boaz Shuster
979c945674 Display Config and Manifest as strings
Builder has the Config and the Manifest fields which are []byte.
The type is []byte because it's eaiser to serialize them that way.
However, when these fields are displayed in the following way:

buildah inspect -f '{{.Config}} {{.Manifest}}' IMAGE

they might be shown as a byte slice.

This patch suggests to use a struct that wraps Builder's exposed
fields such as Config, Manifest and Container as strings and
thus make them readable when inspecting specific field.

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>

Closes: #368
Approved by: rhatdan
2017-12-19 22:16:37 +00:00
TomSweeneyRedHat
c77a8d39f1 Create Registry in Docker for Travis CI
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #290
Approved by: rhatdan
2017-12-18 21:26:57 +00:00
TomSweeneyRedHat
f4151372e5 Create Tutorials menu and add link to README.md
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #367
Approved by: rhatdan
2017-12-15 21:28:32 +00:00
Nalin Dahyabhai
0705787a07 Bump containers/image
Bump containers/image to 4fdf9c9b8a1e014705581ff77df6446e67a8318d.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #366
Approved by: nalind
2017-12-15 17:54:40 +00:00
Nalin Dahyabhai
a5129ec3eb Add a test that 'rmi' works with truncated image IDs
Add a test to ensure that 'buildah rmi' works if passed a truncated
version of an image's ID.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #361
Approved by: rhatdan
2017-12-15 12:13:47 +00:00
Nalin Dahyabhai
47ac96155f Use configured registries to resolve image names
When locating an image for pulling, inspection, or pushing, if we're
given an image name that doesn't include a domain/registry, try building
a set of candidate names using the configured registries as domains, and
then pull/inspect/push using the first of those names that works.

If a name that we're given corresponds to a prefix of the ID of a local
image, skip completion and use the ID directly instead.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #360
Approved by: rhatdan
2017-12-14 22:21:16 +00:00
Nalin Dahyabhai
8b2b56d9b8 Update to work with newer image library
Update shallowCopy() to work with the newer version of image.
Remove things from Push() that we don't need to do any more.
Preserve digests in image names, make sure we update creation times, and
add a test to ensure that we can pull, commit, and push using such names
as sources.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #187
Approved by: rhatdan
2017-12-14 20:57:13 +00:00
Nalin Dahyabhai
544e63de42 Bump containers/image and containers/storage
Update containers/image and containers/storage to current master
(17449738f2bb4c6375c20dcdcfe2a6cccf03f312 and
0d32dfce498e06c132c60dac945081bf44c22464, respectively).

Also updates github.com/docker/docker, golang.org/x/sys, and
golang.org/x/text.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #187
Approved by: rhatdan
2017-12-14 20:57:13 +00:00
Máirín Duffy
43a025ebf9 updating logo reference in README
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Removing old 'underwear hat' logo, replacing with updated logo artwork

Closes: #359
Approved by: rhatdan
2017-12-13 17:02:17 +00:00
Antoine Beaupré
6116d6a9bc install golang metapackage from backports
`golang-1.8` *is* available in stretch, but /usr/bin/go does *not*
point to it by default, *unless* the `golang` meta-package is
installed from backports.

Signed-off-by: Antoine Beaupré <anarcat@debian.org>

Closes: #354
Approved by: rhatdan
2017-12-13 12:38:52 +00:00
Antoine Beaupré
e5aa6c9fc5 add install.runc target
We need this for platforms like Ubuntu and Debian that do not ship a
standard (post 1.0rc4) version of runc.

I'm assuming here this is why we're building `runc` on our own here -
but it doesn't make sense to just do that while leaving only a symlink
in $PWD. We want to actually install the thing as well. So we add an
`install.runc` target, similar to `install.libseccomp.sudo` to make
sure we install `runc` in the right location.

An alternative to this would be to change the documentation to do the
`install` command by hand, but this is more error-prone. As runc
trickles down to the Debian distros, we can then just remove the `make
install.runc` call and, eventually, the target itself.

Closes: #355

Signed-off-by: Antoine Beaupré <anarcat@debian.org>

Closes: #354
Approved by: rhatdan
2017-12-13 12:38:52 +00:00
Antoine Beaupré
95ca6c1e1f run make install as sudo
Explicitly using `sudo` in the `make install` line makes it clear that
the rest of the commands can (and probably should) be ran as non-root.

Signed-off-by: Antoine Beaupré <anarcat@debian.org>

Closes: #354
Approved by: rhatdan
2017-12-13 12:38:52 +00:00
Antoine Beaupré
7244ef44fb add Debian stable install instructions
Note that the instructions may seem unusual to people used to
`apt-key`, but they conform to the [emerging standard](https://wiki.debian.org/DebianRepository/UseThirdParty) for
third-party repositories in Debian.

We use ostree from backports because it matches the version in the
Ubuntu Flatpak PPA. We also explicitly require golang 1.8, which gives
us a 1.8.1 runtime in stretch. We otherwise use the Project Atomic,
but that's only because of Skopeo and similar tools.

Signed-off-by: Antoine Beaupré <anarcat@debian.org>

Closes: #354
Approved by: rhatdan
2017-12-13 12:38:52 +00:00
Antoine Beaupré
9df6f62a4c add headings for different OSes
Signed-off-by: Antoine Beaupré <anarcat@debian.org>

Closes: #354
Approved by: rhatdan
2017-12-13 12:38:52 +00:00
Daniel J Walsh
bf01a80b2b Merge pull request #349 from TomSweeneyRedHat/dev/tsweeney/baseline2
Touchup baseline and rpm tests
2017-12-11 12:00:57 -06:00
Daniel J Walsh
ccd3b3fedb Merge pull request #351 from ripcurld0/small_nitpick
Small nitpick at matches(Since,Before)Image in cmd/buildah/images
2017-12-08 20:49:49 -06:00
Nalin Dahyabhai
4b4e25868c Merge pull request #350 from ipbabble/tutorial2
Add a new tutorial for using Buildah with registries
2017-12-07 17:12:36 -05:00
William Henry
4d943752fe Fixed some more Tom nits.
Signed-off-by: William Henry <whenry@redhat.com>
2017-12-07 10:57:14 -07:00
William Henry
9128a40ada Fixed some Tom nits.
Signed-off-by: William Henry <whenry@redhat.com>
2017-12-07 09:18:13 -07:00
William Henry
8910199181 Add a new tutorial for using Buildah with registries
Signed-off-by: William Henry <whenry@redhat.com>
2017-12-07 08:40:03 -07:00
Fabio Bertinatto
1fc5a49958 Add --chown option to add/copy commands
Signed-off-by: Fabio Bertinatto <fbertina@redhat.com>

Closes: #336
Approved by: rhatdan
2017-12-07 13:45:12 +00:00
Boaz Shuster
98f1533731 Small nitpick at matches(Since,Before)Image in cmd/buildah/images
Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>
2017-12-07 14:09:45 +02:00
TomSweeneyRedHat
aae843123f Touchup baseline and rpm tests
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>
2017-12-06 11:14:09 -05:00
Nalin Dahyabhai
77804bf256 Merge pull request #348 from vbatts/readme
README: better first glance idea
2017-12-05 13:40:28 -05:00
Vincent Batts
7aaa21d70a README: better first glance idea
Fixes #347

Make the project's first-glance easier to digest.

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2017-12-05 09:09:44 -05:00
TomSweeneyRedHat
ee9b8cde5a Create rpm and baseline test script
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #346
Approved by: rhatdan
2017-12-04 17:01:00 +00:00
TomSweeneyRedHat
04ea079130 Bump version to 0.9
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #345
Approved by: rhatdan
2017-12-02 11:51:00 +00:00
Nalin Dahyabhai
2dd03d6741 tests/rpm.bats: use Fedora 27
Update tests/rpm.bats to use Fedora 27.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #342
Approved by: rhatdan
2017-12-01 13:22:58 +00:00
TomSweeneyRedHat
1680a5f0a0 Fix iterator and a few typos in baseline test
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #335
Approved by: rhatdan
2017-12-01 00:02:53 +00:00
TomSweeneyRedHat
5dd1a5f3c9 Touchup test scripts for some minor nits
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #335
Approved by: rhatdan
2017-12-01 00:02:53 +00:00
TomSweeneyRedHat
15792b227a Allow push to use the image id
Signed-off-by: TomSweeneyRedHat <tsweeney@redhat.com>

Closes: #341
Approved by: nalind
2017-11-30 23:47:13 +00:00
Daniel J Walsh
38d3cddb0c Make sure builtin volumes have the correct label
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>

Closes: #339
Approved by: nalind
2017-11-28 21:44:17 +00:00
Nalin Dahyabhai
a99d5f0798 Bump the GIT_VALIDATION_EPOCH to a newer version
Bump the GIT_VALIDATION_EPOCH in tests/validate/git-validation.sh to a
later commit.

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #340
Approved by: rhatdan
2017-11-28 19:39:37 +00:00
Nalin Dahyabhai
53c3e6434d Bump RPM version to 0.8
Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>

Closes: #340
Approved by: rhatdan
2017-11-28 19:39:37 +00:00
286 changed files with 19009 additions and 23595 deletions

28
.copr/Makefile Normal file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/make -f
spec := contrib/rpm/buildah_copr.spec
outdir := $(CURDIR)
tmpdir := build
gitdir := $(PWD)/.git
rev := $(shell sed 's/\(.......\).*/\1/' $(gitdir)/$$(sed -n '/^ref:/{s/.* //;p}' $(gitdir)/HEAD))
date := $(shell date +%Y%m%d.%H%M)
version := $(shell sed -n '/Version:/{s/.* //;p}' $(spec))
release := $(date).git.$(rev)
srpm: $(outdir)/buildah-$(version)-$(release).src.rpm
$(tmpdir)/buildah.spec: $(spec)
@mkdir -p $(tmpdir)
sed '/^Release:/s/\(: *\).*/\1$(release)%{?dist}/' $< >$@
$(tmpdir)/$(version).tar.gz: $(gitdir)/..
@mkdir -p $(tmpdir)
tar c --exclude-vcs --exclude-vcs-ignores -C $< --transform 's|^\.|buildah-$(version)|' . | gzip -9 >$@
$(outdir)/buildah-$(version)-$(release).src.rpm: $(tmpdir)/buildah.spec $(tmpdir)/$(version).tar.gz
@mkdir -p $(outdir)
rpmbuild -D'_srcrpmdir $(outdir)' -D'_sourcedir $(tmpdir)' -bs $(tmpdir)/buildah.spec
.PHONY: srpm

65
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,65 @@
<!--
If you are reporting a new issue, make sure that we do not have any duplicates
already open. You can ensure this by searching the issue list for this
repository. If there is a duplicate, please close your issue and add a comment
to the existing issue instead.
If you suspect your issue is a bug, please edit your issue description to
include the BUG REPORT INFORMATION shown below. If you fail to provide this
information within 7 days, we cannot debug your issue and will close it. We
will, however, reopen it if you later provide the information.
---------------------------------------------------
BUG REPORT INFORMATION
---------------------------------------------------
Use the commands below to provide key information from your environment:
You do NOT have to include this information if this is a FEATURE REQUEST
-->
**Description**
<!--
Briefly describe the problem you are having in a few paragraphs.
-->
**Steps to reproduce the issue:**
1.
2.
3.
**Describe the results you received:**
**Describe the results you expected:**
**Output of `rpm -q buildah` or `apt list buildah`:**
```
(paste your output here)
```
**Output of `buildah version`:**
```
(paste your output here)
```
**Output of `cat /etc/*release`:**
```
(paste your output here)
```
**Output of `uname -a`:**
```
(paste your output here)
```
**Output of `cat /etc/containers/storage.conf`:**
```
(paste your output here)
```

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
docs/buildah*.1
/buildah
/imgtype
/build/

View File

@@ -23,9 +23,15 @@ dnf install -y \
libselinux-devel \
libselinux-utils \
make \
openssl \
ostree-devel \
skopeo-containers \
which
# Install gomega
go get github.com/onsi/gomega/...
# PAPR adds a merge commit, for testing, which fails the
# short-commit-subject validation test, so tell git-validate.sh to only check
# up to, but not including, the merge commit.

View File

@@ -9,6 +9,40 @@ host:
required: true
tests:
# Let's create a self signed certificate and get it in the right places
- hostname
- ip a
- ping -c 3 localhost
- cat /etc/hostname
- mkdir -p /home/travis/auth
- openssl req -newkey rsa:4096 -nodes -sha256 -keyout /home/travis/auth/domain.key -x509 -days 2 -out /home/travis/auth/domain.crt -subj "/C=US/ST=Foo/L=Bar/O=Red Hat, Inc./CN=localhost"
- cp /home/travis/auth/domain.crt /home/travis/auth/domain.cert
- sudo mkdir -p /etc/docker/certs.d/docker.io/
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/docker.io/ca.crt
- sudo mkdir -p /etc/docker/certs.d/localhost:5000/
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/localhost:5000/ca.crt
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/localhost:5000/domain.crt
# Create the credentials file, then start up the Docker registry
- docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > /home/travis/auth/htpasswd
- docker run -d -p 5000:5000 --name registry -v /home/travis/auth:/home/travis/auth:Z -e "REGISTRY_AUTH=htpasswd" -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" -e REGISTRY_AUTH_HTPASSWD_PATH=/home/travis/auth/htpasswd -e REGISTRY_HTTP_TLS_CERTIFICATE=/home/travis/auth/domain.crt -e REGISTRY_HTTP_TLS_KEY=/home/travis/auth/domain.key registry:2
# Test Docker setup
- docker ps --all
- docker images
- ls -alF /home/travis/auth
- docker pull alpine
- docker login localhost:5000 --username testuser --password testpassword
- docker tag alpine localhost:5000/my-alpine
- docker push localhost:5000/my-alpine
- docker ps --all
- docker images
- docker rmi docker.io/alpine
- docker rmi localhost:5000/my-alpine
- docker pull localhost:5000/my-alpine
- docker ps --all
- docker images
- docker rmi localhost:5000/my-alpine
# mount yum repos to inherit injected mirrors from PAPR
- docker run --net=host --privileged -v /etc/yum.repos.d:/etc/yum.repos.d.host:ro
-v $PWD:/code registry.fedoraproject.org/fedora:26 sh -c

View File

@@ -2,7 +2,6 @@ language: go
dist: trusty
sudo: required
go:
- 1.7
- 1.8
- 1.9.x
- tip
@@ -20,10 +19,46 @@ services:
- docker
before_install:
- sudo add-apt-repository -y ppa:duggan/bats
- sudo apt-get -qq update
- sudo apt-get update
- sudo apt-get -qq install bats btrfs-tools git libapparmor-dev libdevmapper-dev libglib2.0-dev libgpgme11-dev libselinux1-dev
- sudo apt-get -qq remove libseccomp2
- sudo apt-get -qq update
- sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce
- mkdir /home/travis/auth
install:
# Let's create a self signed certificate and get it in the right places
- hostname
- ip a
- ping -c 3 localhost
- cat /etc/hostname
- openssl req -newkey rsa:4096 -nodes -sha256 -keyout /home/travis/auth/domain.key -x509 -days 2 -out /home/travis/auth/domain.crt -subj "/C=US/ST=Foo/L=Bar/O=Red Hat, Inc./CN=localhost"
- cp /home/travis/auth/domain.crt /home/travis/auth/domain.cert
- sudo mkdir -p /etc/docker/certs.d/docker.io/
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/docker.io/ca.crt
- sudo mkdir -p /etc/docker/certs.d/localhost:5000/
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/localhost:5000/ca.crt
- sudo cp /home/travis/auth/domain.crt /etc/docker/certs.d/localhost:5000/domain.crt
# Create the credentials file, then start up the Docker registry
- docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > /home/travis/auth/htpasswd
- docker run -d -p 5000:5000 --name registry -v /home/travis/auth:/home/travis/auth:Z -e "REGISTRY_AUTH=htpasswd" -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" -e REGISTRY_AUTH_HTPASSWD_PATH=/home/travis/auth/htpasswd -e REGISTRY_HTTP_TLS_CERTIFICATE=/home/travis/auth/domain.crt -e REGISTRY_HTTP_TLS_KEY=/home/travis/auth/domain.key registry:2
script:
# Let's do some docker stuff just for verification purposes
- docker ps --all
- docker images
- ls -alF /home/travis/auth
- docker pull alpine
- docker login localhost:5000 --username testuser --password testpassword
- docker tag alpine localhost:5000/my-alpine
- docker push localhost:5000/my-alpine
- docker ps --all
- docker images
- docker rmi docker.io/alpine
- docker rmi localhost:5000/my-alpine
- docker pull localhost:5000/my-alpine
- docker ps --all
- docker images
- docker rmi localhost:5000/my-alpine
# Setting up Docker Registry is complete, let's do Buildah testing!
- make install.tools install.libseccomp.sudo all runc validate TAGS="apparmor seccomp containers_image_ostree_stub"
- go test -c -tags "apparmor seccomp `./btrfs_tag.sh` `./libdm_tag.sh` `./ostree_tag.sh` `./selinux_tag.sh`" ./cmd/buildah
- tmp=`mktemp -d`; mkdir $tmp/root $tmp/runroot; sudo PATH="$PATH" ./buildah.test -test.v -root $tmp/root -runroot $tmp/runroot -storage-driver vfs -signature-policy `pwd`/tests/policy.json

View File

@@ -24,7 +24,7 @@ imgtype: *.go docker/*.go util/*.go tests/imgtype.go
.PHONY: clean
clean:
$(RM) buildah imgtype
$(RM) buildah imgtype build
$(MAKE) -C docs clean
.PHONY: docs
@@ -53,6 +53,7 @@ validate:
install.tools:
$(GO) get -u $(BUILDFLAGS) github.com/cpuguy83/go-md2man
$(GO) get -u $(BUILDFLAGS) github.com/vbatts/git-validation
$(GO) get -u $(BUILDFLAGS) github.com/onsi/ginkgo/ginkgo
$(GO) get -u $(BUILDFLAGS) gopkg.in/alecthomas/gometalinter.v1
gometalinter.v1 -i
@@ -78,8 +79,13 @@ install:
install.completions:
install -m 644 -D contrib/completions/bash/buildah $(DESTDIR)/${BASHINSTALLDIR}/buildah
.PHONY: install.runc
install.runc:
install -m 755 ../../opencontainers/runc/runc $(DESTDIR)/$(BINDIR)/
.PHONY: test-integration
test-integration:
ginkgo -v tests/e2e/.
cd tests; ./test_runner.sh
.PHONY: test-unit

130
README.md
View File

@@ -1,4 +1,4 @@
![buildah logo](https://cdn.rawgit.com/projectatomic/buildah/master/logos/buildah.svg)
![buildah logo](https://cdn.rawgit.com/projectatomic/buildah/master/logos/buildah-logo_large.png)
# [Buildah](https://www.youtube.com/embed/YVk5NgSiUw8) - a tool which facilitates building OCI container images
================================================================
@@ -19,108 +19,38 @@ The Buildah package provides a command line tool which can be used to
**[Changelog](CHANGELOG.md)**
**Installation notes**
**[Installation notes](install.md)**
Prior to installing Buildah, install the following packages on your linux distro:
* make
* golang (Requires version 1.8.1 or higher.)
* bats
* btrfs-progs-devel
* bzip2
* device-mapper-devel
* git
* go-md2man
* gpgme-devel
* glib2-devel
* libassuan-devel
* ostree-devel
* runc (Requires version 1.0 RC4 or higher.)
* skopeo-containers
**[Tutorials](docs/tutorials/README.md)**
In Fedora, you can use this command:
## Example
From [`./examples/lighttpd.sh`](examples/lighttpd.sh):
```bash
$ cat > lighttpd.sh <<EOF
#!/bin/bash -x
ctr1=`buildah from ${1:-fedora}`
## Get all updates and install our minimal httpd server
buildah run $ctr1 -- dnf update -y
buildah run $ctr1 -- dnf install -y lighttpd
## Include some buildtime annotations
buildah config --annotation "com.example.build.host=$(uname -n)" $ctr1
## Run our server and expose the port
buildah config $ctr1 --cmd "/usr/sbin/lighttpd -D -f /etc/lighttpd/lighttpd.conf"
buildah config $ctr1 --port 80
## Commit this container to an image name
buildah commit $ctr1 ${2:-$USER/lighttpd}
EOF
$ chmod +x lighttpd.sh
$ sudo ./lighttpd.sh
```
dnf -y install \
make \
golang \
bats \
btrfs-progs-devel \
device-mapper-devel \
glib2-devel \
gpgme-devel \
libassuan-devel \
ostree-devel \
git \
bzip2 \
go-md2man \
runc \
skopeo-containers
```
Then to install Buildah on Fedora follow the steps in this example:
```
mkdir ~/buildah
cd ~/buildah
export GOPATH=`pwd`
git clone https://github.com/projectatomic/buildah ./src/github.com/projectatomic/buildah
cd ./src/github.com/projectatomic/buildah
make
make install
buildah --help
```
In RHEL 7, ensure that you are subscribed to `rhel-7-server-rpms`,
`rhel-7-server-extras-rpms`, and `rhel-7-server-optional-rpms`, then
run this command:
```
yum -y install \
make \
golang \
bats \
btrfs-progs-devel \
device-mapper-devel \
glib2-devel \
gpgme-devel \
libassuan-devel \
ostree-devel \
git \
bzip2 \
go-md2man \
runc \
skopeo-containers
```
The build steps for Buildah on RHEL are the same as Fedora, above.
In Ubuntu zesty and xenial, you can use this command:
```
apt-get -y install software-properties-common
add-apt-repository -y ppa:alexlarsson/flatpak
add-apt-repository -y ppa:gophers/archive
apt-add-repository -y ppa:projectatomic/ppa
apt-get -y -qq update
apt-get -y install bats btrfs-tools git libapparmor-dev libdevmapper-dev libglib2.0-dev libgpgme11-dev libostree-dev libseccomp-dev libselinux1-dev skopeo-containers go-md2man
apt-get -y install golang-1.8
```
Then to install Buildah on Ubuntu follow the steps in this example:
```
mkdir ~/buildah
cd ~/buildah
export GOPATH=`pwd`
git clone https://github.com/projectatomic/buildah ./src/github.com/projectatomic/buildah
cd ./src/github.com/projectatomic/buildah
PATH=/usr/lib/go-1.8/bin:$PATH make runc all TAGS="apparmor seccomp"
make install
buildah --help
```
Buildah uses `runc` to run commands when `buildah run` is used, or when `buildah build-using-dockerfile`
encounters a `RUN` instruction, so you'll also need to build and install a compatible version of
[runc](https://github.com/opencontainers/runc) for Buildah to call for those cases.
## Commands
| Command | Description |
@@ -135,7 +65,7 @@ encounters a `RUN` instruction, so you'll also need to build and install a compa
| [buildah-images(1)](/docs/buildah-images.md) | List images in local storage. |
| [buildah-inspect(1)](/docs/buildah-inspect.md) | Inspects the configuration of a container or image. |
| [buildah-mount(1)](/docs/buildah-mount.md) | Mount the working container's root filesystem. |
| [buildah-push(1)](/docs/buildah-push.md) | Copies an image from local storage. |
| [buildah-push(1)](/docs/buildah-push.md) | Push an image from local storage to elsewhere. |
| [buildah-rm(1)](/docs/buildah-rm.md) | Removes one or more working containers. |
| [buildah-rmi(1)](/docs/buildah-rmi.md) | Removes one or more images. |
| [buildah-run(1)](/docs/buildah-run.md) | Run a command inside of the container. |

101
add.go
View File

@@ -12,10 +12,17 @@ import (
"time"
"github.com/containers/storage/pkg/archive"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/projectatomic/libpod/pkg/chrootuser"
"github.com/sirupsen/logrus"
)
//AddAndCopyOptions holds options for add and copy commands.
type AddAndCopyOptions struct {
Chown string
}
// addURL copies the contents of the source URL to the destination. This is
// its own function so that deferred closes happen after we're done pulling
// down each item of potentially many.
@@ -58,7 +65,7 @@ func addURL(destination, srcurl string) error {
// Add copies the contents of the specified sources into the container's root
// filesystem, optionally extracting contents of local files that look like
// non-empty archives.
func (b *Builder) Add(destination string, extract bool, source ...string) error {
func (b *Builder) Add(destination string, extract bool, options AddAndCopyOptions, source ...string) error {
mountPoint, err := b.Mount(b.MountLabel)
if err != nil {
return err
@@ -68,12 +75,17 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
logrus.Errorf("error unmounting container: %v", err2)
}
}()
// Find out which user (and group) the destination should belong to.
user, err := b.user(mountPoint, options.Chown)
if err != nil {
return err
}
dest := mountPoint
if destination != "" && filepath.IsAbs(destination) {
dest = filepath.Join(dest, destination)
} else {
if err = os.MkdirAll(filepath.Join(dest, b.WorkDir()), 0755); err != nil {
return errors.Wrapf(err, "error ensuring directory %q exists)", filepath.Join(dest, b.WorkDir()))
if err = ensureDir(filepath.Join(dest, b.WorkDir()), user, 0755); err != nil {
return err
}
dest = filepath.Join(dest, b.WorkDir(), destination)
}
@@ -81,8 +93,8 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
// with a '/', create it so that we can be sure that it's a directory,
// and any files we're copying will be placed in the directory.
if len(destination) > 0 && destination[len(destination)-1] == os.PathSeparator {
if err = os.MkdirAll(dest, 0755); err != nil {
return errors.Wrapf(err, "error ensuring directory %q exists", dest)
if err = ensureDir(dest, user, 0755); err != nil {
return err
}
}
// Make sure the destination's parent directory is usable.
@@ -118,6 +130,9 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
if err := addURL(d, src); err != nil {
return err
}
if err := setOwner("", d, user); err != nil {
return err
}
continue
}
@@ -138,13 +153,15 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
// the source directory into the target directory. Try
// to create it first, so that if there's a problem,
// we'll discover why that won't work.
d := dest
if err := os.MkdirAll(d, 0755); err != nil {
return errors.Wrapf(err, "error ensuring directory %q exists", d)
if err = ensureDir(dest, user, 0755); err != nil {
return err
}
logrus.Debugf("copying %q to %q", gsrc+string(os.PathSeparator)+"*", d+string(os.PathSeparator)+"*")
if err := copyWithTar(gsrc, d); err != nil {
return errors.Wrapf(err, "error copying %q to %q", gsrc, d)
logrus.Debugf("copying %q to %q", gsrc+string(os.PathSeparator)+"*", dest+string(os.PathSeparator)+"*")
if err := copyWithTar(gsrc, dest); err != nil {
return errors.Wrapf(err, "error copying %q to %q", gsrc, dest)
}
if err := setOwner(gsrc, dest, user); err != nil {
return err
}
continue
}
@@ -161,6 +178,9 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
if err := copyFileWithTar(gsrc, d); err != nil {
return errors.Wrapf(err, "error copying %q to %q", gsrc, d)
}
if err := setOwner(gsrc, d, user); err != nil {
return err
}
continue
}
// We're extracting an archive into the destination directory.
@@ -172,3 +192,62 @@ func (b *Builder) Add(destination string, extract bool, source ...string) error
}
return nil
}
// user returns the user (and group) information which the destination should belong to.
func (b *Builder) user(mountPoint string, userspec string) (specs.User, error) {
if userspec == "" {
userspec = b.User()
}
uid, gid, err := chrootuser.GetUser(mountPoint, userspec)
u := specs.User{
UID: uid,
GID: gid,
Username: userspec,
}
return u, err
}
// setOwner sets the uid and gid owners of a given path.
func setOwner(src, dest string, user specs.User) error {
fid, err := os.Stat(dest)
if err != nil {
return errors.Wrapf(err, "error reading %q", dest)
}
if !fid.IsDir() || src == "" {
if err := os.Lchown(dest, int(user.UID), int(user.GID)); err != nil {
return errors.Wrapf(err, "error setting ownership of %q", dest)
}
return nil
}
err = filepath.Walk(src, func(p string, info os.FileInfo, we error) error {
relPath, err2 := filepath.Rel(src, p)
if err2 != nil {
return errors.Wrapf(err2, "error getting relative path of %q to set ownership on destination", p)
}
if relPath != "." {
absPath := filepath.Join(dest, relPath)
if err2 := os.Lchown(absPath, int(user.UID), int(user.GID)); err != nil {
return errors.Wrapf(err2, "error setting ownership of %q", absPath)
}
}
return nil
})
if err != nil {
return errors.Wrapf(err, "error walking dir %q to set ownership", src)
}
return nil
}
// ensureDir creates a directory if it doesn't exist, setting ownership and permissions as passed by user and perm.
func ensureDir(path string, user specs.User, perm os.FileMode) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := os.MkdirAll(path, perm); err != nil {
return errors.Wrapf(err, "error ensuring directory %q exists", path)
}
if err := os.Chown(path, int(user.UID), int(user.GID)); err != nil {
return errors.Wrapf(err, "error setting ownership of %q", path)
}
}
return nil
}

View File

@@ -19,8 +19,9 @@ const (
// Package is the name of this package, used in help output and to
// identify working containers.
Package = "buildah"
// Version for the Package
Version = "0.8"
// Version for the Package. Bump version in contrib/rpm/buildah.spec
// too.
Version = "0.15"
// 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
@@ -93,6 +94,79 @@ type Builder struct {
Docker docker.V2Image `json:"docker,omitempty"`
// DefaultMountsFilePath is the file path holding the mounts to be mounted in "host-path:container-path" format
DefaultMountsFilePath string `json:"defaultMountsFilePath,omitempty"`
CommonBuildOpts *CommonBuildOptions
}
// BuilderInfo are used as objects to display container information
type BuilderInfo struct {
Type string
FromImage string
FromImageID string
Config string
Manifest string
Container string
ContainerID string
MountPoint string
ProcessLabel string
MountLabel string
ImageAnnotations map[string]string
ImageCreatedBy string
OCIv1 v1.Image
Docker docker.V2Image
DefaultMountsFilePath string
}
// GetBuildInfo gets a pointer to a Builder object and returns a BuilderInfo object from it.
// This is used in the inspect command to display Manifest and Config as string and not []byte.
func GetBuildInfo(b *Builder) BuilderInfo {
return BuilderInfo{
Type: b.Type,
FromImage: b.FromImage,
FromImageID: b.FromImageID,
Config: string(b.Config),
Manifest: string(b.Manifest),
Container: b.Container,
ContainerID: b.ContainerID,
MountPoint: b.MountPoint,
ProcessLabel: b.ProcessLabel,
ImageAnnotations: b.ImageAnnotations,
ImageCreatedBy: b.ImageCreatedBy,
OCIv1: b.OCIv1,
Docker: b.Docker,
DefaultMountsFilePath: b.DefaultMountsFilePath,
}
}
// CommonBuildOptions are reseources that can be defined by flags for both buildah from and bud
type CommonBuildOptions struct {
// AddHost is the list of hostnames to add to the resolv.conf
AddHost []string
//CgroupParent it 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
//Memory limit
Memory int64
//MemorySwap limit value equal to memory plus swap.
MemorySwap int64
//SecruityOpts modify the way container security is running
LabelOpts []string
SeccompProfilePath string
ApparmorProfile string
//ShmSize is the shared memory size
ShmSize string
//Ulimit options
Ulimit []string
//Volumes to bind mount into the container
Volumes []string
}
// BuilderOptions are used to initialize a new Builder.
@@ -134,6 +208,7 @@ type BuilderOptions struct {
SystemContext *types.SystemContext
// DefaultMountsFilePath is the file path holding the mounts to be mounted in "host-path:container-path" format
DefaultMountsFilePath string
CommonBuildOpts *CommonBuildOptions
}
// ImportOptions are used to initialize a Builder from an existing container
@@ -159,6 +234,10 @@ type ImportFromImageOptions struct {
// specified, indicating that the shared, system-wide default policy
// should be used.
SignaturePolicyPath string
// github.com/containers/image/types SystemContext to hold information
// about which registries we should check for completing image names
// that don't include a domain portion.
SystemContext *types.SystemContext
}
// NewBuilder creates a new build container.

View File

@@ -2,27 +2,38 @@ package main
import (
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/urfave/cli"
)
var (
addAndCopyFlags = []cli.Flag{
cli.StringFlag{
Name: "chown",
Usage: "Set the user and group ownership of the destination content",
},
}
addDescription = "Adds the contents of a file, URL, or directory to a container's working\n directory. If a local file appears to be an archive, its contents are\n extracted and added instead of the archive file itself."
copyDescription = "Copies the contents of a file, URL, or directory into a container's working\n directory"
addCommand = cli.Command{
Name: "add",
Usage: "Add content to the container",
Description: addDescription,
Action: addCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [[FILE | DIRECTORY | URL] ...] [DESTINATION]",
Name: "add",
Usage: "Add content to the container",
Description: addDescription,
Flags: addAndCopyFlags,
Action: addCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [[FILE | DIRECTORY | URL] ...] [DESTINATION]",
SkipArgReorder: true,
}
copyCommand = cli.Command{
Name: "copy",
Usage: "Copy content into the container",
Description: copyDescription,
Action: copyCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [[FILE | DIRECTORY | URL] ...] [DESTINATION]",
Name: "copy",
Usage: "Copy content into the container",
Description: copyDescription,
Flags: addAndCopyFlags,
Action: copyCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [[FILE | DIRECTORY | URL] ...] [DESTINATION]",
SkipArgReorder: true,
}
)
@@ -34,7 +45,11 @@ func addAndCopyCmd(c *cli.Context, extractLocalArchives bool) error {
name := args[0]
args = args.Tail()
// If list is greater then one, the last item is the destination
if err := validateFlags(c, addAndCopyFlags); err != nil {
return err
}
// If list is greater than one, the last item is the destination
dest := ""
size := len(args)
if size > 1 {
@@ -52,8 +67,11 @@ func addAndCopyCmd(c *cli.Context, extractLocalArchives bool) error {
return errors.Wrapf(err, "error reading build container %q", name)
}
err = builder.Add(dest, extractLocalArchives, args...)
if err != nil {
options := buildah.AddAndCopyOptions{
Chown: c.String("chown"),
}
if err := builder.Add(dest, extractLocalArchives, options, args...); err != nil {
return errors.Wrapf(err, "error adding content to container %q", builder.Container)
}

View File

@@ -21,6 +21,16 @@ var (
Name: "build-arg",
Usage: "`argument=value` to supply to the builder",
},
cli.StringFlag{
Name: "cert-dir",
Value: "",
Usage: "use certificates at the specified path to access the registry",
},
cli.StringFlag{
Name: "creds",
Value: "",
Usage: "use `[username[:password]]` for accessing the registry",
},
cli.StringSliceFlag{
Name: "file, f",
Usage: "`pathname or URL` of a Dockerfile",
@@ -66,13 +76,14 @@ var (
budDescription = "Builds an OCI image using instructions in one or more Dockerfiles."
budCommand = cli.Command{
Name: "build-using-dockerfile",
Aliases: []string{"bud"},
Usage: "Build an image using instructions in a Dockerfile",
Description: budDescription,
Flags: budFlags,
Action: budCmd,
ArgsUsage: "CONTEXT-DIRECTORY | URL",
Name: "build-using-dockerfile",
Aliases: []string{"bud"},
Usage: "Build an image using instructions in a Dockerfile",
Description: budDescription,
Flags: append(budFlags, fromAndBudFlags...),
Action: budCmd,
ArgsUsage: "CONTEXT-DIRECTORY | URL",
SkipArgReorder: true,
}
)
@@ -181,21 +192,38 @@ func budCmd(c *cli.Context) error {
return err
}
options := imagebuildah.BuildOptions{
ContextDirectory: contextDir,
PullPolicy: pullPolicy,
Compression: imagebuildah.Gzip,
Quiet: c.Bool("quiet"),
SignaturePolicyPath: c.String("signature-policy"),
SkipTLSVerify: !c.Bool("tls-verify"),
Args: args,
Output: output,
AdditionalTags: tags,
Runtime: c.String("runtime"),
RuntimeArgs: c.StringSlice("runtime-flag"),
OutputFormat: format,
AuthFilePath: c.String("authfile"),
systemContext, err := systemContextFromOptions(c)
if err != nil {
return errors.Wrapf(err, "error building system context")
}
runtimeFlags := []string{}
for _, arg := range c.StringSlice("runtime-flag") {
runtimeFlags = append(runtimeFlags, "--"+arg)
}
commonOpts, err := parseCommonBuildOptions(c)
if err != nil {
return err
}
options := imagebuildah.BuildOptions{
ContextDirectory: contextDir,
PullPolicy: pullPolicy,
Compression: imagebuildah.Gzip,
Quiet: c.Bool("quiet"),
SignaturePolicyPath: c.String("signature-policy"),
Args: args,
Output: output,
AdditionalTags: tags,
Runtime: c.String("runtime"),
RuntimeArgs: runtimeFlags,
OutputFormat: format,
SystemContext: systemContext,
CommonBuildOpts: commonOpts,
DefaultMountsFilePath: c.GlobalString("default-mounts-file"),
}
if !c.Bool("quiet") {
options.ReportWriter = os.Stderr
}

View File

@@ -10,11 +10,16 @@ import (
"github.com/containers/storage/pkg/archive"
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/projectatomic/buildah/util"
"github.com/urfave/cli"
)
var (
commitFlags = []cli.Flag{
cli.StringFlag{
Name: "authfile",
Usage: "path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json",
},
cli.StringFlag{
Name: "cert-dir",
Value: "",
@@ -23,7 +28,7 @@ var (
cli.StringFlag{
Name: "creds",
Value: "",
Usage: "use `username[:password]` for accessing the registry",
Usage: "use `[username[:password]]` for accessing the registry",
},
cli.BoolFlag{
Name: "disable-compression, D",
@@ -58,12 +63,13 @@ var (
}
commitDescription = "Writes a new image using the container's read-write layer and, if it is based\n on an image, the layers of that image"
commitCommand = cli.Command{
Name: "commit",
Usage: "Create an image from a working container",
Description: commitDescription,
Flags: commitFlags,
Action: commitCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID IMAGE",
Name: "commit",
Usage: "Create an image from a working container",
Description: commitDescription,
Flags: commitFlags,
Action: commitCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID IMAGE",
SkipArgReorder: true,
}
)
@@ -143,7 +149,10 @@ func commitCmd(c *cli.Context) error {
}
err = builder.Commit(dest, options)
if err != nil {
return errors.Wrapf(err, "error committing container %q to %q", builder.Container, image)
return util.GetFailureCause(
err,
errors.Wrapf(err, "error committing container %q to %q", builder.Container, image),
)
}
if c.Bool("rm") {

View File

@@ -1,20 +1,30 @@
package main
import (
"fmt"
"net"
"os"
"reflect"
"regexp"
"strings"
"syscall"
"time"
is "github.com/containers/image/storage"
"github.com/containers/image/types"
"github.com/containers/storage"
units "github.com/docker/go-units"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
)
const (
// SeccompDefaultPath defines the default seccomp path
SeccompDefaultPath = "/usr/share/containers/seccomp.json"
// SeccompOverridePath if this exists it overrides the default seccomp path
SeccompOverridePath = "/etc/crio/seccomp.json"
)
var needToShutdownStore = false
@@ -65,9 +75,10 @@ func openBuilders(store storage.Store) (builders []*buildah.Builder, err error)
return buildah.OpenAllBuilders(store)
}
func openImage(store storage.Store, name string) (builder *buildah.Builder, err error) {
func openImage(sc *types.SystemContext, store storage.Store, name string) (builder *buildah.Builder, err error) {
options := buildah.ImportFromImageOptions{
Image: name,
Image: name,
SystemContext: sc,
}
builder, err = buildah.ImportBuilderFromImage(store, options)
if err != nil {
@@ -82,7 +93,7 @@ func openImage(store storage.Store, name string) (builder *buildah.Builder, err
func getDateAndDigestAndSize(image storage.Image, store storage.Store) (time.Time, string, int64, error) {
created := time.Time{}
is.Transport.SetStore(store)
storeRef, err := is.Transport.ParseStoreReference(store, "@"+image.ID)
storeRef, err := is.Transport.ParseStoreReference(store, image.ID)
if err != nil {
return created, "", -1, err
}
@@ -136,28 +147,44 @@ func systemContextFromOptions(c *cli.Context) (*types.SystemContext, error) {
if c.IsSet("authfile") {
ctx.AuthFilePath = c.String("authfile")
}
if c.GlobalIsSet("registries-conf") {
ctx.SystemRegistriesConfPath = c.GlobalString("registries-conf")
}
if c.GlobalIsSet("registries-conf-dir") {
ctx.RegistriesDirPath = c.GlobalString("registries-conf-dir")
}
return ctx, nil
}
func parseCreds(creds string) (string, string, error) {
func parseCreds(creds string) (string, string) {
if creds == "" {
return "", "", errors.Wrapf(syscall.EINVAL, "credentials can't be empty")
return "", ""
}
up := strings.SplitN(creds, ":", 2)
if len(up) == 1 {
return up[0], "", nil
return up[0], ""
}
if up[0] == "" {
return "", "", errors.Wrapf(syscall.EINVAL, "username can't be empty")
return "", up[1]
}
return up[0], up[1], nil
return up[0], up[1]
}
func getDockerAuth(creds string) (*types.DockerAuthConfig, error) {
username, password, err := parseCreds(creds)
if err != nil {
return nil, err
username, password := parseCreds(creds)
if username == "" {
fmt.Print("Username: ")
fmt.Scanln(&username)
}
if password == "" {
fmt.Print("Password: ")
termPassword, err := terminal.ReadPassword(0)
if err != nil {
return nil, errors.Wrapf(err, "could not read password from terminal")
}
password = string(termPassword)
}
return &types.DockerAuthConfig{
Username: username,
Password: password,
@@ -199,3 +226,243 @@ func validateFlags(c *cli.Context, flags []cli.Flag) error {
}
return nil
}
var fromAndBudFlags = []cli.Flag{
cli.StringSliceFlag{
Name: "add-host",
Usage: "add a custom host-to-IP mapping (host:ip) (default [])",
},
cli.StringFlag{
Name: "cgroup-parent",
Usage: "optional parent cgroup for the container",
},
cli.Uint64Flag{
Name: "cpu-period",
Usage: "limit the CPU CFS (Completely Fair Scheduler) period",
},
cli.Int64Flag{
Name: "cpu-quota",
Usage: "limit the CPU CFS (Completely Fair Scheduler) quota",
},
cli.Uint64Flag{
Name: "cpu-shares",
Usage: "CPU shares (relative weight)",
},
cli.StringFlag{
Name: "cpuset-cpus",
Usage: "CPUs in which to allow execution (0-3, 0,1)",
},
cli.StringFlag{
Name: "cpuset-mems",
Usage: "memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.",
},
cli.StringFlag{
Name: "memory, m",
Usage: "memory limit (format: <number>[<unit>], where unit = b, k, m or g)",
},
cli.StringFlag{
Name: "memory-swap",
Usage: "swap limit equal to memory plus swap: '-1' to enable unlimited swap",
},
cli.StringSliceFlag{
Name: "security-opt",
Usage: "security Options (default [])",
},
cli.StringFlag{
Name: "shm-size",
Usage: "size of `/dev/shm`. The format is `<number><unit>`.",
Value: "65536k",
},
cli.StringSliceFlag{
Name: "ulimit",
Usage: "ulimit options (default [])",
},
cli.StringSliceFlag{
Name: "volume, v",
Usage: "bind mount a volume into the container (default [])",
},
}
func parseCommonBuildOptions(c *cli.Context) (*buildah.CommonBuildOptions, error) {
var (
memoryLimit int64
memorySwap int64
err error
)
if c.String("memory") != "" {
memoryLimit, err = units.RAMInBytes(c.String("memory"))
if err != nil {
return nil, errors.Wrapf(err, "invalid value for memory")
}
}
if c.String("memory-swap") != "" {
memorySwap, err = units.RAMInBytes(c.String("memory-swap"))
if err != nil {
return nil, errors.Wrapf(err, "invalid value for memory-swap")
}
}
if len(c.StringSlice("add-host")) > 0 {
for _, host := range c.StringSlice("add-host") {
if err := validateExtraHost(host); err != nil {
return nil, errors.Wrapf(err, "invalid value for add-host")
}
}
}
if _, err := units.FromHumanSize(c.String("shm-size")); err != nil {
return nil, errors.Wrapf(err, "invalid --shm-size")
}
if err := parseVolumes(c.StringSlice("volume")); err != nil {
return nil, err
}
commonOpts := &buildah.CommonBuildOptions{
AddHost: c.StringSlice("add-host"),
CgroupParent: c.String("cgroup-parent"),
CPUPeriod: c.Uint64("cpu-period"),
CPUQuota: c.Int64("cpu-quota"),
CPUSetCPUs: c.String("cpuset-cpus"),
CPUSetMems: c.String("cpuset-mems"),
CPUShares: c.Uint64("cpu-shares"),
Memory: memoryLimit,
MemorySwap: memorySwap,
ShmSize: c.String("shm-size"),
Ulimit: c.StringSlice("ulimit"),
Volumes: c.StringSlice("volume"),
}
if err := parseSecurityOpts(c.StringSlice("security-opt"), commonOpts); err != nil {
return nil, err
}
return commonOpts, nil
}
func parseSecurityOpts(securityOpts []string, commonOpts *buildah.CommonBuildOptions) error {
for _, opt := range securityOpts {
if opt == "no-new-privileges" {
return errors.Errorf("no-new-privileges is not supported")
}
con := strings.SplitN(opt, "=", 2)
if len(con) != 2 {
return errors.Errorf("Invalid --security-opt 1: %q", opt)
}
switch con[0] {
case "label":
commonOpts.LabelOpts = append(commonOpts.LabelOpts, con[1])
case "apparmor":
commonOpts.ApparmorProfile = con[1]
case "seccomp":
commonOpts.SeccompProfilePath = con[1]
default:
return errors.Errorf("Invalid --security-opt 2: %q", opt)
}
}
if commonOpts.SeccompProfilePath == "" {
if _, err := os.Stat(SeccompOverridePath); err == nil {
commonOpts.SeccompProfilePath = SeccompOverridePath
} else {
if !os.IsNotExist(err) {
return errors.Wrapf(err, "can't check if %q exists", SeccompOverridePath)
}
if _, err := os.Stat(SeccompDefaultPath); err != nil {
if !os.IsNotExist(err) {
return errors.Wrapf(err, "can't check if %q exists", SeccompDefaultPath)
}
} else {
commonOpts.SeccompProfilePath = SeccompDefaultPath
}
}
}
return nil
}
func parseVolumes(volumes []string) error {
if len(volumes) == 0 {
return nil
}
for _, volume := range volumes {
arr := strings.SplitN(volume, ":", 3)
if len(arr) < 2 {
return errors.Errorf("incorrect volume format %q, should be host-dir:ctr-dir[:option]", volume)
}
if err := validateVolumeHostDir(arr[0]); err != nil {
return err
}
if err := validateVolumeCtrDir(arr[1]); err != nil {
return err
}
if len(arr) > 2 {
if err := validateVolumeOpts(arr[2]); err != nil {
return err
}
}
}
return nil
}
func validateVolumeHostDir(hostDir string) error {
if _, err := os.Stat(hostDir); err != nil {
return errors.Wrapf(err, "error checking path %q", hostDir)
}
return nil
}
func validateVolumeCtrDir(ctrDir string) error {
if ctrDir[0] != '/' {
return errors.Errorf("invalid container directory path %q", ctrDir)
}
return nil
}
func validateVolumeOpts(option string) error {
var foundRootPropagation, foundRWRO, foundLabelChange int
options := strings.Split(option, ",")
for _, opt := range options {
switch opt {
case "rw", "ro":
if foundRWRO > 1 {
return errors.Errorf("invalid options %q, can only specify 1 'rw' or 'ro' option", option)
}
foundRWRO++
case "z", "Z":
if foundLabelChange > 1 {
return errors.Errorf("invalid options %q, can only specify 1 'z' or 'Z' option", option)
}
foundLabelChange++
case "private", "rprivate", "shared", "rshared", "slave", "rslave":
if foundRootPropagation > 1 {
return errors.Errorf("invalid options %q, can only specify 1 '[r]shared', '[r]private' or '[r]slave' option", option)
}
foundRootPropagation++
default:
return errors.Errorf("invalid option type %q", option)
}
}
return nil
}
// validateExtraHost validates that the specified string is a valid extrahost and returns it.
// ExtraHost is in the form of name:ip where the ip has to be a valid ip (ipv4 or ipv6).
// for add-host flag
func validateExtraHost(val string) error {
// allow for IPv6 addresses in extra hosts by only splitting on first ":"
arr := strings.SplitN(val, ":", 2)
if len(arr) != 2 || len(arr[0]) == 0 {
return fmt.Errorf("bad format for add-host: %q", val)
}
if _, err := validateIPAddress(arr[1]); err != nil {
return fmt.Errorf("invalid IP address in add-host: %q", arr[1])
}
return nil
}
// validateIPAddress validates an Ip address.
// for dns, ip, and ip6 flags also
func validateIPAddress(val string) (string, error) {
var ip = net.ParseIP(strings.TrimSpace(val))
if ip != nil {
return ip.String(), nil
}
return "", fmt.Errorf("%s is not an ip address", val)
}

View File

@@ -105,9 +105,13 @@ func pullTestImage(t *testing.T, imageName string) (string, error) {
if err != nil {
t.Fatal(err)
}
commonOpts := &buildah.CommonBuildOptions{
LabelOpts: nil,
}
options := buildah.BuilderOptions{
FromImage: imageName,
SignaturePolicyPath: signaturePolicyPath,
CommonBuildOpts: commonOpts,
}
b, err := buildah.NewBuilder(store, options)

View File

@@ -74,12 +74,13 @@ var (
}
configDescription = "Modifies the configuration values which will be saved to the image"
configCommand = cli.Command{
Name: "config",
Usage: "Update image configuration settings",
Description: configDescription,
Flags: configFlags,
Action: configCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
Name: "config",
Usage: "Update image configuration settings",
Description: configDescription,
Flags: configFlags,
Action: configCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
SkipArgReorder: true,
}
)

View File

@@ -3,7 +3,11 @@ package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"text/template"
"github.com/containers/storage"
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/urfave/cli"
@@ -17,12 +21,43 @@ type jsonContainer struct {
ContainerName string `json:"containername"`
}
type containerOutputParams struct {
ContainerID string
Builder string
ImageID string
ImageName string
ContainerName string
}
type containerOptions struct {
all bool
format string
json bool
noHeading bool
noTruncate bool
quiet bool
}
type containerFilterParams struct {
id string
name string
ancestor string
}
var (
containersFlags = []cli.Flag{
cli.BoolFlag{
Name: "all, a",
Usage: "also list non-buildah containers",
},
cli.StringFlag{
Name: "filter, f",
Usage: "filter output based on conditions provided",
},
cli.StringFlag{
Name: "format",
Usage: "pretty-print containers using a Go template",
},
cli.BoolFlag{
Name: "json",
Usage: "output in JSON format",
@@ -42,12 +77,13 @@ var (
}
containersDescription = "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"
containersCommand = cli.Command{
Name: "containers",
Usage: "List working containers and their base images",
Description: containersDescription,
Flags: containersFlags,
Action: containersCmd,
ArgsUsage: " ",
Name: "containers",
Usage: "List working containers and their base images",
Description: containersDescription,
Flags: containersFlags,
Action: containersCmd,
ArgsUsage: " ",
SkipArgReorder: true,
}
)
@@ -60,38 +96,35 @@ func containersCmd(c *cli.Context) error {
return err
}
quiet := c.Bool("quiet")
truncate := !c.Bool("notruncate")
JSONContainers := []jsonContainer{}
jsonOut := c.Bool("json")
if c.IsSet("quiet") && c.IsSet("format") {
return errors.Errorf("quiet and format are mutually exclusive")
}
list := func(n int, containerID, imageID, image, container string, isBuilder bool) {
if jsonOut {
JSONContainers = append(JSONContainers, jsonContainer{ID: containerID, Builder: isBuilder, ImageID: imageID, ImageName: image, ContainerName: container})
return
}
opts := containerOptions{
all: c.Bool("all"),
format: c.String("format"),
json: c.Bool("json"),
noHeading: c.Bool("noheading"),
noTruncate: c.Bool("notruncate"),
quiet: c.Bool("quiet"),
}
if n == 0 && !c.Bool("noheading") && !quiet {
if truncate {
fmt.Printf("%-12s %-8s %-12s %-32s %s\n", "CONTAINER ID", "BUILDER", "IMAGE ID", "IMAGE NAME", "CONTAINER NAME")
} else {
fmt.Printf("%-64s %-8s %-64s %-32s %s\n", "CONTAINER ID", "BUILDER", "IMAGE ID", "IMAGE NAME", "CONTAINER NAME")
}
}
if quiet {
fmt.Printf("%s\n", containerID)
} else {
isBuilderValue := ""
if isBuilder {
isBuilderValue = " *"
}
if truncate {
fmt.Printf("%-12.12s %-8s %-12.12s %-32s %s\n", containerID, isBuilderValue, imageID, image, container)
} else {
fmt.Printf("%-64s %-8s %-64s %-32s %s\n", containerID, isBuilderValue, imageID, image, container)
}
var params *containerFilterParams
if c.IsSet("filter") {
params, err = parseCtrFilter(c.String("filter"))
if err != nil {
return errors.Wrapf(err, "error parsing filter")
}
}
if !opts.noHeading && !opts.quiet && opts.format == "" && !opts.json {
containerOutputHeader(!opts.noTruncate)
}
return outputContainers(store, opts, params)
}
func outputContainers(store storage.Store, opts containerOptions, params *containerFilterParams) error {
seenImages := make(map[string]string)
imageNameForID := func(id string) string {
if id == "" {
@@ -112,12 +145,36 @@ func containersCmd(c *cli.Context) error {
if err != nil {
return errors.Wrapf(err, "error reading build containers")
}
if !c.Bool("all") {
for i, builder := range builders {
var (
containerOutput []containerOutputParams
JSONContainers []jsonContainer
)
if !opts.all {
// only output containers created by buildah
for _, builder := range builders {
image := imageNameForID(builder.FromImageID)
list(i, builder.ContainerID, builder.FromImageID, image, builder.Container, true)
if !matchesCtrFilter(builder.ContainerID, builder.Container, builder.FromImageID, image, params) {
continue
}
if opts.json {
JSONContainers = append(JSONContainers, jsonContainer{ID: builder.ContainerID,
Builder: true,
ImageID: builder.FromImageID,
ImageName: image,
ContainerName: builder.Container})
continue
}
output := containerOutputParams{
ContainerID: builder.ContainerID,
Builder: " *",
ImageID: builder.FromImageID,
ImageName: image,
ContainerName: builder.Container,
}
containerOutput = append(containerOutput, output)
}
} else {
// output all containers currently in storage
builderMap := make(map[string]struct{})
for _, builder := range builders {
builderMap[builder.ContainerID] = struct{}{}
@@ -126,22 +183,136 @@ func containersCmd(c *cli.Context) error {
if err2 != nil {
return errors.Wrapf(err2, "error reading list of all containers")
}
for i, container := range containers {
for _, container := range containers {
name := ""
if len(container.Names) > 0 {
name = container.Names[0]
}
_, ours := builderMap[container.ID]
list(i, container.ID, container.ImageID, imageNameForID(container.ImageID), name, ours)
builder := ""
if ours {
builder = " *"
}
if !matchesCtrFilter(container.ID, name, container.ImageID, imageNameForID(container.ImageID), params) {
continue
}
if opts.json {
JSONContainers = append(JSONContainers, jsonContainer{ID: container.ID,
Builder: ours,
ImageID: container.ImageID,
ImageName: imageNameForID(container.ImageID),
ContainerName: name})
}
output := containerOutputParams{
ContainerID: container.ID,
Builder: builder,
ImageID: container.ImageID,
ImageName: imageNameForID(container.ImageID),
ContainerName: name,
}
containerOutput = append(containerOutput, output)
}
}
if jsonOut {
if opts.json {
data, err := json.MarshalIndent(JSONContainers, "", " ")
if err != nil {
return err
}
fmt.Printf("%s\n", data)
return nil
}
for _, ctr := range containerOutput {
if opts.quiet {
fmt.Printf("%-64s\n", ctr.ContainerID)
continue
}
if opts.format != "" {
if err := containerOutputUsingTemplate(opts.format, ctr); err != nil {
return err
}
continue
}
containerOutputUsingFormatString(!opts.noTruncate, ctr)
}
return nil
}
func containerOutputUsingTemplate(format string, params containerOutputParams) error {
tmpl, err := template.New("container").Parse(format)
if err != nil {
return errors.Wrapf(err, "Template parsing error")
}
err = tmpl.Execute(os.Stdout, params)
if err != nil {
return err
}
fmt.Println()
return nil
}
func containerOutputUsingFormatString(truncate bool, params containerOutputParams) {
if truncate {
fmt.Printf("%-12.12s %-8s %-12.12s %-32s %s\n", params.ContainerID, params.Builder, params.ImageID, params.ImageName, params.ContainerName)
} else {
fmt.Printf("%-64s %-8s %-64s %-32s %s\n", params.ContainerID, params.Builder, params.ImageID, params.ImageName, params.ContainerName)
}
}
func containerOutputHeader(truncate bool) {
if truncate {
fmt.Printf("%-12s %-8s %-12s %-32s %s\n", "CONTAINER ID", "BUILDER", "IMAGE ID", "IMAGE NAME", "CONTAINER NAME")
} else {
fmt.Printf("%-64s %-8s %-64s %-32s %s\n", "CONTAINER ID", "BUILDER", "IMAGE ID", "IMAGE NAME", "CONTAINER NAME")
}
}
func parseCtrFilter(filter string) (*containerFilterParams, error) {
params := new(containerFilterParams)
filters := strings.Split(filter, ",")
for _, param := range filters {
pair := strings.SplitN(param, "=", 2)
if len(pair) != 2 {
return nil, errors.Errorf("incorrect filter value %q, should be of form filter=value", param)
}
switch strings.TrimSpace(pair[0]) {
case "id":
params.id = pair[1]
case "name":
params.name = pair[1]
case "ancestor":
params.ancestor = pair[1]
default:
return nil, errors.Errorf("invalid filter %q", pair[0])
}
}
return params, nil
}
func matchesCtrName(ctrName, argName string) bool {
return strings.Contains(ctrName, argName)
}
func matchesAncestor(imgName, imgID, argName string) bool {
if matchesID(imgID, argName) {
return true
}
return matchesReference(imgName, argName)
}
func matchesCtrFilter(ctrID, ctrName, imgID, imgName string, params *containerFilterParams) bool {
if params == nil {
return true
}
if params.id != "" && !matchesID(ctrID, params.id) {
return false
}
if params.name != "" && !matchesCtrName(ctrName, params.name) {
return false
}
if params.ancestor != "" && !matchesAncestor(imgName, imgID, params.ancestor) {
return false
}
return true
}

View File

@@ -23,7 +23,7 @@ var (
cli.StringFlag{
Name: "creds",
Value: "",
Usage: "use `username[:password]` for accessing the registry",
Usage: "use `[username[:password]]` for accessing the registry",
},
cli.StringFlag{
Name: "name",
@@ -53,17 +53,17 @@ var (
fromDescription = "Creates a new working container, either from scratch or using a specified\n image as a starting point"
fromCommand = cli.Command{
Name: "from",
Usage: "Create a working container based on an image",
Description: fromDescription,
Flags: fromFlags,
Action: fromCmd,
ArgsUsage: "IMAGE",
Name: "from",
Usage: "Create a working container based on an image",
Description: fromDescription,
Flags: append(fromFlags, fromAndBudFlags...),
Action: fromCmd,
ArgsUsage: "IMAGE",
SkipArgReorder: true,
}
)
func fromCmd(c *cli.Context) error {
args := c.Args()
if len(args) == 0 {
return errors.Errorf("an image name (or \"scratch\") must be specified")
@@ -95,6 +95,11 @@ func fromCmd(c *cli.Context) error {
return err
}
commonOpts, err := parseCommonBuildOptions(c)
if err != nil {
return err
}
options := buildah.BuilderOptions{
FromImage: args[0],
Container: c.String("name"),
@@ -102,7 +107,9 @@ func fromCmd(c *cli.Context) error {
SignaturePolicyPath: signaturePolicy,
SystemContext: systemContext,
DefaultMountsFilePath: c.GlobalString("default-mounts-file"),
CommonBuildOpts: commonOpts,
}
if !c.Bool("quiet") {
options.ReportWriter = os.Stderr
}

View File

@@ -14,6 +14,7 @@ import (
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
)
type jsonImage struct {
@@ -51,7 +52,7 @@ var (
},
cli.StringFlag{
Name: "format",
Usage: "pretty-print images using a Go template. will override --quiet",
Usage: "pretty-print images using a Go template",
},
cli.BoolFlag{
Name: "json",
@@ -73,12 +74,13 @@ var (
imagesDescription = "Lists locally stored images."
imagesCommand = cli.Command{
Name: "images",
Usage: "List images in local storage",
Description: imagesDescription,
Flags: imagesFlags,
Action: imagesCmd,
ArgsUsage: " ",
Name: "images",
Usage: "List images in local storage",
Description: imagesDescription,
Flags: imagesFlags,
Action: imagesCmd,
ArgsUsage: " ",
SkipArgReorder: true,
}
)
@@ -96,6 +98,10 @@ func imagesCmd(c *cli.Context) error {
return errors.Wrapf(err, "error reading images")
}
if c.IsSet("quiet") && c.IsSet("format") {
return errors.Errorf("quiet and format are mutually exclusive")
}
quiet := c.Bool("quiet")
truncate := !c.Bool("no-trunc")
digests := c.Bool("digests")
@@ -125,8 +131,6 @@ func imagesCmd(c *cli.Context) error {
if err != nil {
return errors.Wrapf(err, "error parsing filter")
}
} else {
params = nil
}
if len(images) > 0 && !c.Bool("noheading") && !quiet && !hasTemplate {
@@ -178,7 +182,7 @@ func setFilterDate(store storage.Store, images []storage.Image, imgName string)
for _, name := range image.Names {
if matchesReference(name, imgName) {
// Set the date to this image
ref, err := is.Transport.ParseStoreReference(store, "@"+image.ID)
ref, err := is.Transport.ParseStoreReference(store, image.ID)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing reference to image %q: %v", image.ID, err)
}
@@ -290,7 +294,7 @@ func matchesDangling(name string, dangling string) bool {
}
func matchesLabel(image storage.Image, store storage.Store, label string) bool {
storeRef, err := is.Transport.ParseStoreReference(store, "@"+image.ID)
storeRef, err := is.Transport.ParseStoreReference(store, image.ID)
if err != nil {
return false
}
@@ -322,19 +326,13 @@ func matchesLabel(image storage.Image, store storage.Store, label string) bool {
// Returns true if the image was created since the filter image. Returns
// false otherwise
func matchesBeforeImage(image storage.Image, name string, params *filterParams) bool {
if image.Created.IsZero() || image.Created.Before(params.beforeDate) {
return true
}
return false
return image.Created.IsZero() || image.Created.Before(params.beforeDate)
}
// Returns true if the image was created since the filter image. Returns
// false otherwise
func matchesSinceImage(image storage.Image, name string, params *filterParams) bool {
if image.Created.IsZero() || image.Created.After(params.sinceDate) {
return true
}
return false
return image.Created.IsZero() || image.Created.After(params.sinceDate)
}
func matchesID(imageID, argID string) bool {
@@ -376,7 +374,9 @@ func outputUsingTemplate(format string, params imageOutputParams) error {
if err != nil {
return err
}
fmt.Println()
if terminal.IsTerminal(int(os.Stdout.Fd())) {
fmt.Println()
}
return nil
}

View File

@@ -253,7 +253,7 @@ func TestOutputImagesFormatString(t *testing.T) {
output, err := captureOutputWithError(func() error {
return outputImages(images[:1], "{{.ID}}", store, nil, "", true, true, false, false)
})
expectedOutput := fmt.Sprintf("%s", images[0].ID)
expectedOutput := images[0].ID
if err != nil {
t.Error("format string output produces error")
} else if strings.TrimSpace(output) != strings.TrimSpace(expectedOutput) {

View File

@@ -9,6 +9,7 @@ import (
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
)
const (
@@ -33,12 +34,13 @@ var (
}
inspectDescription = "Inspects a build container's or built image's configuration."
inspectCommand = cli.Command{
Name: "inspect",
Usage: "Inspects the configuration of a container or image",
Description: inspectDescription,
Flags: inspectFlags,
Action: inspectCmd,
ArgsUsage: "CONTAINER-OR-IMAGE",
Name: "inspect",
Usage: "Inspects the configuration of a container or image",
Description: inspectDescription,
Flags: inspectFlags,
Action: inspectCmd,
ArgsUsage: "CONTAINER-OR-IMAGE",
SkipArgReorder: true,
}
)
@@ -56,6 +58,11 @@ func inspectCmd(c *cli.Context) error {
return err
}
systemContext, err := systemContextFromOptions(c)
if err != nil {
return errors.Wrapf(err, "error building system context")
}
format := defaultFormat
if c.String("format") != "" {
format = c.String("format")
@@ -76,13 +83,13 @@ func inspectCmd(c *cli.Context) error {
if c.IsSet("type") {
return errors.Wrapf(err, "error reading build container %q", name)
}
builder, err = openImage(store, name)
builder, err = openImage(systemContext, store, name)
if err != nil {
return errors.Wrapf(err, "error reading build object %q", name)
}
}
case inspectTypeImage:
builder, err = openImage(store, name)
builder, err = openImage(systemContext, store, name)
if err != nil {
return errors.Wrapf(err, "error reading image %q", name)
}
@@ -91,13 +98,19 @@ func inspectCmd(c *cli.Context) error {
}
if c.IsSet("format") {
return t.Execute(os.Stdout, builder)
if err := t.Execute(os.Stdout, buildah.GetBuildInfo(builder)); err != nil {
return err
}
if terminal.IsTerminal(int(os.Stdout.Fd())) {
fmt.Println()
}
return nil
}
b, err := json.MarshalIndent(builder, "", " ")
if err != nil {
return errors.Wrapf(err, "error encoding build container as json")
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if terminal.IsTerminal(int(os.Stdout.Fd())) {
enc.SetEscapeHTML(false)
}
_, err = fmt.Println(string(b))
return err
return enc.Encode(builder)
}

View File

@@ -33,6 +33,14 @@ func main() {
Name: "debug",
Usage: "print debugging information",
},
cli.StringFlag{
Name: "registries-conf",
Usage: "path to registries.conf file (not usually used)",
},
cli.StringFlag{
Name: "registries-conf-dir",
Usage: "path to registries.conf.d directory (not usually used)",
},
cli.StringFlag{
Name: "root",
Usage: "storage root dir",

View File

@@ -16,12 +16,13 @@ var (
},
}
mountCommand = cli.Command{
Name: "mount",
Usage: "Mount a working container's root filesystem",
Description: mountDescription,
Action: mountCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
Flags: mountFlags,
Name: "mount",
Usage: "Mount a working container's root filesystem",
Description: mountDescription,
Action: mountCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
Flags: mountFlags,
SkipArgReorder: true,
}
)

View File

@@ -12,6 +12,7 @@ import (
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
"github.com/projectatomic/buildah/util"
"github.com/urfave/cli"
)
@@ -29,7 +30,7 @@ var (
cli.StringFlag{
Name: "creds",
Value: "",
Usage: "use `username[:password]` for accessing the registry",
Usage: "use `[username[:password]]` for accessing the registry",
},
cli.BoolFlag{
Name: "disable-compression, D",
@@ -64,12 +65,13 @@ var (
`, strings.Join(transports.ListNames(), ", "))
pushCommand = cli.Command{
Name: "push",
Usage: "Push an image to a specified destination",
Description: pushDescription,
Flags: pushFlags,
Action: pushCmd,
ArgsUsage: "IMAGE DESTINATION",
Name: "push",
Usage: "Push an image to a specified destination",
Description: pushDescription,
Flags: pushFlags,
Action: pushCmd,
ArgsUsage: "IMAGE DESTINATION",
SkipArgReorder: true,
}
)
@@ -141,7 +143,10 @@ func pushCmd(c *cli.Context) error {
err = buildah.Push(src, dest, options)
if err != nil {
return errors.Wrapf(err, "error pushing image %q to %q", src, destSpec)
return util.GetFailureCause(
err,
errors.Wrapf(err, "error pushing image %q to %q", src, destSpec),
)
}
return nil

View File

@@ -2,6 +2,7 @@ package main
import (
"fmt"
"io"
"os"
"github.com/pkg/errors"
@@ -10,19 +11,36 @@ import (
var (
rmDescription = "Removes one or more working containers, unmounting them if necessary"
rmCommand = cli.Command{
Name: "rm",
Aliases: []string{"delete"},
Usage: "Remove one or more working containers",
Description: rmDescription,
Action: rmCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [...]",
rmFlags = []cli.Flag{
cli.BoolFlag{
Name: "all, a",
Usage: "remove all containers",
},
}
rmCommand = cli.Command{
Name: "rm",
Aliases: []string{"delete"},
Usage: "Remove one or more working containers",
Description: rmDescription,
Action: rmCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID [...]",
Flags: rmFlags,
SkipArgReorder: true,
}
)
// writeError writes `lastError` into `w` if not nil and return the next error `err`
func writeError(w io.Writer, err error, lastError error) error {
if lastError != nil {
fmt.Fprintln(w, lastError)
}
return err
}
func rmCmd(c *cli.Context) error {
delContainerErrStr := "error removing container"
args := c.Args()
if len(args) == 0 {
if len(args) == 0 && !c.Bool("all") {
return errors.Errorf("container ID must be specified")
}
store, err := getStore(c)
@@ -30,28 +48,36 @@ func rmCmd(c *cli.Context) error {
return err
}
var e error
for _, name := range args {
builder, err := openBuilder(store, name)
if e == nil {
e = err
}
var lastError error
if c.Bool("all") {
builders, err := openBuilders(store)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading build container %q: %v\n", name, err)
continue
return errors.Wrapf(err, "error reading build containers")
}
id := builder.ContainerID
err = builder.Delete()
if e == nil {
e = err
for _, builder := range builders {
id := builder.ContainerID
if err = builder.Delete(); err != nil {
lastError = writeError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, builder.Container), lastError)
continue
}
fmt.Printf("%s\n", id)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error removing container %q: %v\n", builder.Container, err)
continue
} else {
for _, name := range args {
builder, err := openBuilder(store, name)
if err != nil {
lastError = writeError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
continue
}
id := builder.ContainerID
if err = builder.Delete(); err != nil {
lastError = writeError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
continue
}
fmt.Printf("%s\n", id)
}
fmt.Printf("%s\n", id)
}
return e
return lastError
}

View File

@@ -2,6 +2,7 @@ package main
import (
"fmt"
"os"
is "github.com/containers/image/storage"
"github.com/containers/image/transports"
@@ -16,28 +17,46 @@ import (
var (
rmiDescription = "removes one or more locally stored images."
rmiFlags = []cli.Flag{
cli.BoolFlag{
Name: "all, a",
Usage: "remove all images",
},
cli.BoolFlag{
Name: "prune, p",
Usage: "prune dangling images",
},
cli.BoolFlag{
Name: "force, f",
Usage: "force removal of the image",
Usage: "force removal of the image and any containers using the image",
},
}
rmiCommand = cli.Command{
Name: "rmi",
Usage: "removes one or more images from local storage",
Description: rmiDescription,
Action: rmiCmd,
ArgsUsage: "IMAGE-NAME-OR-ID [...]",
Flags: rmiFlags,
Name: "rmi",
Usage: "removes one or more images from local storage",
Description: rmiDescription,
Action: rmiCmd,
ArgsUsage: "IMAGE-NAME-OR-ID [...]",
Flags: rmiFlags,
SkipArgReorder: true,
}
)
func rmiCmd(c *cli.Context) error {
force := c.Bool("force")
removeAll := c.Bool("all")
pruneDangling := c.Bool("prune")
args := c.Args()
if len(args) == 0 {
if len(args) == 0 && !removeAll && !pruneDangling {
return errors.Errorf("image name or ID must be specified")
}
if len(args) > 0 && removeAll {
return errors.Errorf("when using the --all switch, you may not pass any images names or IDs")
}
if removeAll && pruneDangling {
return errors.Errorf("when using the --all switch, you may not use --prune switch")
}
if err := validateFlags(c, rmiFlags); err != nil {
return err
}
@@ -47,26 +66,62 @@ func rmiCmd(c *cli.Context) error {
return err
}
for _, id := range args {
image, err := getImage(id, store)
imagesToDelete := args[:]
var lastError error
if removeAll {
imagesToDelete, err = findAllImages(store)
if err != nil {
return errors.Wrapf(err, "could not get image %q", id)
return err
}
}
if pruneDangling {
imagesToDelete, err = findDanglingImages(store)
if err != nil {
return err
}
}
for _, id := range imagesToDelete {
image, err := getImage(id, store)
if err != nil || image == nil {
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
if err == nil {
err = storage.ErrNotAnImage
}
lastError = errors.Wrapf(err, "could not get image %q", id)
continue
}
if image != nil {
ctrIDs, err := runningContainers(image, store)
if err != nil {
return errors.Wrapf(err, "error getting running containers for image %q", id)
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "error getting running containers for image %q", id)
continue
}
if len(ctrIDs) > 0 && len(image.Names) <= 1 {
if force {
err = removeContainers(ctrIDs, store)
if err != nil {
return errors.Wrapf(err, "error removing containers %v for image %q", ctrIDs, id)
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "error removing containers %v for image %q", ctrIDs, id)
continue
}
} else {
for _, ctrID := range ctrIDs {
return fmt.Errorf("Could not remove image %q (must force) - container %q is using its reference image", id, ctrID)
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(storage.ErrImageUsedByContainer, "Could not remove image %q (must force) - container %q is using its reference image", id, ctrID)
}
continue
}
}
// If the user supplied an ID, we cannot delete the image if it is referred to by multiple tags
@@ -79,7 +134,11 @@ func rmiCmd(c *cli.Context) error {
} else {
name, err2 := untagImage(id, image, store)
if err2 != nil {
return errors.Wrapf(err, "error removing tag %q from image %q", id, image.ID)
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err2, "error removing tag %q from image %q", id, image.ID)
continue
}
fmt.Printf("untagged: %s\n", name)
}
@@ -89,13 +148,17 @@ func rmiCmd(c *cli.Context) error {
}
id, err := removeImage(image, store)
if err != nil {
return errors.Wrapf(err, "error removing image %q", image.ID)
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "error removing image %q", image.ID)
continue
}
fmt.Printf("%s\n", id)
}
}
return nil
return lastError
}
func getImage(id string, store storage.Store) (*storage.Image, error) {
@@ -178,7 +241,7 @@ func removeContainers(ctrIDs []string, store storage.Store) error {
func properImageRef(id string) (types.ImageReference, error) {
var err error
if ref, err := alltransports.ParseImageName(id); err == nil {
if img, err2 := ref.NewImage(nil); err2 == nil {
if img, err2 := ref.NewImageSource(nil); err2 == nil {
img.Close()
return ref, nil
}
@@ -192,7 +255,7 @@ func properImageRef(id string) (types.ImageReference, error) {
func storageImageRef(store storage.Store, id string) (types.ImageReference, error) {
var err error
if ref, err := is.Transport.ParseStoreReference(store, id); err == nil {
if img, err2 := ref.NewImage(nil); err2 == nil {
if img, err2 := ref.NewImageSource(nil); err2 == nil {
img.Close()
return ref, nil
}
@@ -210,12 +273,44 @@ func storageImageID(store storage.Store, id string) (types.ImageReference, error
if img, err := store.Image(id); err == nil && img != nil {
imageID = img.ID
}
if ref, err := is.Transport.ParseStoreReference(store, "@"+imageID); err == nil {
if img, err2 := ref.NewImage(nil); err2 == nil {
if ref, err := is.Transport.ParseStoreReference(store, imageID); err == nil {
if img, err2 := ref.NewImageSource(nil); err2 == nil {
img.Close()
return ref, nil
}
return nil, errors.Wrapf(err, "error confirming presence of storage image reference %q", transports.ImageName(ref))
}
return nil, errors.Wrapf(err, "error parsing %q as a storage image reference: %v", "@"+id)
return nil, errors.Wrapf(err, "error parsing %q as a storage image reference: %v", id)
}
// Returns a list of all existing images
func findAllImages(store storage.Store) ([]string, error) {
imagesToDelete := []string{}
images, err := store.Images()
if err != nil {
return nil, errors.Wrapf(err, "error reading images")
}
for _, image := range images {
imagesToDelete = append(imagesToDelete, image.ID)
}
return imagesToDelete, nil
}
// Returns a list of all dangling images
func findDanglingImages(store storage.Store) ([]string, error) {
imagesToDelete := []string{}
images, err := store.Images()
if err != nil {
return nil, errors.Wrapf(err, "error reading images")
}
for _, image := range images {
if len(image.Names) == 0 {
imagesToDelete = append(imagesToDelete, image.ID)
}
}
return imagesToDelete, nil
}

View File

@@ -17,7 +17,7 @@ var (
runFlags = []cli.Flag{
cli.StringFlag{
Name: "hostname",
Usage: "Set the hostname inside of the container",
Usage: "set the hostname inside of the container",
},
cli.StringFlag{
Name: "runtime",
@@ -28,6 +28,10 @@ var (
Name: "runtime-flag",
Usage: "add global flags for the container runtime",
},
cli.StringSliceFlag{
Name: "security-opt",
Usage: "security Options (default [])",
},
cli.BoolFlag{
Name: "tty",
Usage: "allocate a pseudo-TTY in the container",
@@ -39,12 +43,13 @@ var (
}
runDescription = "Runs a specified command using the container's root filesystem as a root\n filesystem, using configuration settings inherited from the container's\n image or as specified using previous calls to the config command"
runCommand = cli.Command{
Name: "run",
Usage: "Run a command inside of the container",
Description: runDescription,
Flags: runFlags,
Action: runCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID COMMAND [ARGS [...]]",
Name: "run",
Usage: "Run a command inside of the container",
Description: runDescription,
Flags: runFlags,
Action: runCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID COMMAND [ARGS [...]]",
SkipArgReorder: true,
}
)
@@ -73,10 +78,15 @@ func runCmd(c *cli.Context) error {
return errors.Wrapf(err, "error reading build container %q", name)
}
runtimeFlags := []string{}
for _, arg := range c.StringSlice("runtime-flag") {
runtimeFlags = append(runtimeFlags, "--"+arg)
}
options := buildah.RunOptions{
Hostname: c.String("hostname"),
Runtime: c.String("runtime"),
Args: c.StringSlice("runtime-flag"),
Args: runtimeFlags,
}
if c.IsSet("tty") {

View File

@@ -9,11 +9,12 @@ import (
var (
tagDescription = "Adds one or more additional names to locally-stored image"
tagCommand = cli.Command{
Name: "tag",
Usage: "Add an additional name to a local image",
Description: tagDescription,
Action: tagCmd,
ArgsUsage: "IMAGE-NAME [IMAGE-NAME ...]",
Name: "tag",
Usage: "Add an additional name to a local image",
Description: tagDescription,
Action: tagCmd,
ArgsUsage: "IMAGE-NAME [IMAGE-NAME ...]",
SkipArgReorder: true,
}
)

View File

@@ -7,12 +7,13 @@ import (
var (
umountCommand = cli.Command{
Name: "umount",
Aliases: []string{"unmount"},
Usage: "Unmount a working container's root filesystem",
Description: "Unmounts a working container's root filesystem",
Action: umountCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
Name: "umount",
Aliases: []string{"unmount"},
Usage: "Unmount a working container's root filesystem",
Description: "Unmounts a working container's root filesystem",
Action: umountCmd,
ArgsUsage: "CONTAINER-NAME-OR-ID",
SkipArgReorder: true,
}
)

View File

@@ -42,7 +42,8 @@ func versionCmd(c *cli.Context) error {
//cli command to print out the version info of buildah
var versionCommand = cli.Command{
Name: "version",
Usage: "Display the Buildah Version Information",
Action: versionCmd,
Name: "version",
Usage: "Display the Buildah Version Information",
Action: versionCmd,
SkipArgReorder: true,
}

162
commit.go
View File

@@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"io"
"syscall"
"time"
cp "github.com/containers/image/copy"
@@ -19,17 +20,6 @@ import (
"github.com/sirupsen/logrus"
)
var (
// gzippedEmptyLayer is a gzip-compressed version of an empty tar file (just 1024 zero bytes). This
// comes from github.com/docker/distribution/manifest/schema1/config_builder.go by way of
// github.com/containers/image/image/docker_schema2.go; there is a non-zero embedded timestamp; we could
// zero that, but that would just waste storage space in registries, so lets use the same values.
gzippedEmptyLayer = []byte{
31, 139, 8, 0, 0, 9, 110, 136, 0, 255, 98, 24, 5, 163, 96, 20, 140, 88,
0, 8, 0, 0, 255, 255, 46, 175, 181, 239, 0, 4, 0, 0,
}
)
// CommitOptions can be used to alter how an image is committed.
type CommitOptions struct {
// PreferredManifestType is the preferred type of image manifest. The
@@ -90,7 +80,7 @@ type PushOptions struct {
// almost any other destination has higher expectations.
// We assume that "dest" is a reference to a local image (specifically, a containers/image/storage.storageReference),
// and will fail if it isn't.
func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReference, systemContext *types.SystemContext) error {
func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReference, systemContext *types.SystemContext, compression archive.Compression) error {
var names []string
// Read the target image name.
if dest.DockerReference() != nil {
@@ -106,10 +96,34 @@ func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReferenc
if err != nil {
return errors.Wrapf(err, "error opening image %q for writing", transports.ImageName(dest))
}
// Write an empty filesystem layer, because the image layer requires at least one.
_, err = destImage.PutBlob(bytes.NewReader(gzippedEmptyLayer), types.BlobInfo{Size: int64(len(gzippedEmptyLayer))})
// Look up the container's read-write layer.
container, err := b.store.Container(b.ContainerID)
if err != nil {
return errors.Wrapf(err, "error writing dummy layer for image %q", transports.ImageName(dest))
return errors.Wrapf(err, "error reading information about working container %q", b.ContainerID)
}
// Extract the read-write layer's contents, using whatever compression the container image used to
// calculate the blob sum in the manifest.
switch compression {
case archive.Gzip:
logrus.Debugf("extracting layer %q with gzip", container.LayerID)
case archive.Bzip2:
// Until the image specs define a media type for bzip2-compressed layers, even if we know
// how to decompress them, we can't try to compress layers with bzip2.
return errors.Wrapf(syscall.ENOTSUP, "media type for bzip2-compressed layers is not defined")
default:
logrus.Debugf("extracting layer %q with unknown compressor(?)", container.LayerID)
}
diffOptions := &storage.DiffOptions{
Compression: &compression,
}
layerDiff, err := b.store.Diff("", container.LayerID, diffOptions)
if err != nil {
return errors.Wrapf(err, "error reading layer %q from source image %q", container.LayerID, transports.ImageName(src))
}
defer layerDiff.Close()
// Write a copy of the layer as a blob, for the new image to reference.
if _, err = destImage.PutBlob(layerDiff, types.BlobInfo{Digest: "", Size: -1}); err != nil {
return errors.Wrapf(err, "error creating new read-only layer from container %q", b.ContainerID)
}
// Read the newly-generated configuration blob.
config, err := srcImage.ConfigBlob()
@@ -125,11 +139,10 @@ func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReferenc
Digest: digest.Canonical.FromBytes(config),
Size: int64(len(config)),
}
_, err = destImage.PutBlob(bytes.NewReader(config), configBlobInfo)
if err != nil && len(config) > 0 {
if _, err = destImage.PutBlob(bytes.NewReader(config), configBlobInfo); err != nil {
return errors.Wrapf(err, "error writing image configuration for temporary copy of %q", transports.ImageName(dest))
}
// Read the newly-generated, mostly fake, manifest.
// Read the newly-generated manifest, which already contains a layer entry for the read-write layer.
manifest, _, err := srcImage.Manifest()
if err != nil {
return errors.Wrapf(err, "error reading new manifest for image %q", transports.ImageName(dest))
@@ -148,79 +161,9 @@ func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReferenc
if err != nil {
return errors.Wrapf(err, "error closing new image %q", transports.ImageName(dest))
}
// Locate the new image in the lower-level API. Extract its items.
destImg, err := is.Transport.GetStoreImage(b.store, dest)
image, err := is.Transport.GetStoreImage(b.store, dest)
if err != nil {
return errors.Wrapf(err, "error locating new image %q", transports.ImageName(dest))
}
items, err := b.store.ListImageBigData(destImg.ID)
if err != nil {
return errors.Wrapf(err, "error reading list of named data for image %q", destImg.ID)
}
bigdata := make(map[string][]byte)
for _, itemName := range items {
var data []byte
data, err = b.store.ImageBigData(destImg.ID, itemName)
if err != nil {
return errors.Wrapf(err, "error reading named data %q for image %q", itemName, destImg.ID)
}
bigdata[itemName] = data
}
// Delete the image so that we can recreate it.
_, err = b.store.DeleteImage(destImg.ID, true)
if err != nil {
return errors.Wrapf(err, "error deleting image %q for rewriting", destImg.ID)
}
// Look up the container's read-write layer.
container, err := b.store.Container(b.ContainerID)
if err != nil {
return errors.Wrapf(err, "error reading information about working container %q", b.ContainerID)
}
parentLayer := ""
// Look up the container's source image's layer, if there is a source image.
if container.ImageID != "" {
img, err2 := b.store.Image(container.ImageID)
if err2 != nil {
return errors.Wrapf(err2, "error reading information about working container %q's source image", b.ContainerID)
}
parentLayer = img.TopLayer
}
// Extract the read-write layer's contents.
layerDiff, err := b.store.Diff(parentLayer, container.LayerID, nil)
if err != nil {
return errors.Wrapf(err, "error reading layer %q from source image %q", container.LayerID, transports.ImageName(src))
}
defer layerDiff.Close()
// Write a copy of the layer for the new image to reference.
layer, _, err := b.store.PutLayer("", parentLayer, []string{}, "", false, layerDiff)
if err != nil {
return errors.Wrapf(err, "error creating new read-only layer from container %q", b.ContainerID)
}
// Create a low-level image record that uses the new layer, discarding the old metadata.
image, err := b.store.CreateImage(destImg.ID, []string{}, layer.ID, "{}", nil)
if err != nil {
err2 := b.store.DeleteLayer(layer.ID)
if err2 != nil {
logrus.Debugf("error removing layer %q: %v", layer, err2)
}
return errors.Wrapf(err, "error creating new low-level image %q", transports.ImageName(dest))
}
logrus.Debugf("(re-)created image ID %q using layer %q", image.ID, layer.ID)
defer func() {
if err != nil {
_, err2 := b.store.DeleteImage(image.ID, true)
if err2 != nil {
logrus.Debugf("error removing image %q: %v", image.ID, err2)
}
}
}()
// Store the configuration and manifest, which are big data items, along with whatever else is there.
for itemName, data := range bigdata {
err = b.store.SetImageBigData(image.ID, itemName, data)
if err != nil {
return errors.Wrapf(err, "error saving data item %q", itemName)
}
logrus.Debugf("saved data item %q to %q", itemName, image.ID)
return errors.Wrapf(err, "error locating just-written image %q", transports.ImageName(dest))
}
// Add the target name(s) to the new image.
if len(names) > 0 {
@@ -237,7 +180,7 @@ func (b *Builder) shallowCopy(dest types.ImageReference, src types.ImageReferenc
// configuration, to a new image in the specified location, and if we know how,
// add any additional tags that were specified.
func (b *Builder) Commit(dest types.ImageReference, options CommitOptions) error {
policy, err := signature.DefaultPolicy(getSystemContext(options.SignaturePolicyPath))
policy, err := signature.DefaultPolicy(getSystemContext(options.SystemContext, options.SignaturePolicyPath))
if err != nil {
return errors.Wrapf(err, "error obtaining default signature policy")
}
@@ -247,13 +190,13 @@ func (b *Builder) Commit(dest types.ImageReference, options CommitOptions) error
}
defer func() {
if err2 := policyContext.Destroy(); err2 != nil {
logrus.Debugf("error destroying signature polcy context: %v", err2)
logrus.Debugf("error destroying signature policy context: %v", err2)
}
}()
// Check if we're keeping everything in local storage. If so, we can take certain shortcuts.
_, destIsStorage := dest.Transport().(is.StoreTransport)
exporting := !destIsStorage
src, err := b.makeContainerImageRef(options.PreferredManifestType, exporting, options.Compression, options.HistoryTimestamp)
src, err := b.makeImageRef(options.PreferredManifestType, exporting, options.Compression, options.HistoryTimestamp)
if err != nil {
return errors.Wrapf(err, "error computing layer digests and building metadata")
}
@@ -265,7 +208,7 @@ func (b *Builder) Commit(dest types.ImageReference, options CommitOptions) error
}
} else {
// Copy only the most recent layer, the configuration, and the manifest.
err = b.shallowCopy(dest, src, getSystemContext(options.SignaturePolicyPath))
err = b.shallowCopy(dest, src, getSystemContext(options.SystemContext, options.SignaturePolicyPath), options.Compression)
if err != nil {
return errors.Wrapf(err, "error copying layer and metadata")
}
@@ -291,7 +234,7 @@ func (b *Builder) Commit(dest types.ImageReference, options CommitOptions) error
// Push copies the contents of the image to a new location.
func Push(image string, dest types.ImageReference, options PushOptions) error {
systemContext := getSystemContext(options.SignaturePolicyPath)
systemContext := getSystemContext(options.SystemContext, options.SignaturePolicyPath)
policy, err := signature.DefaultPolicy(systemContext)
if err != nil {
return errors.Wrapf(err, "error obtaining default signature policy")
@@ -300,36 +243,11 @@ func Push(image string, dest types.ImageReference, options PushOptions) error {
if err != nil {
return errors.Wrapf(err, "error creating new signature policy context")
}
defer func() {
if err2 := policyContext.Destroy(); err2 != nil {
logrus.Debugf("error destroying signature polcy context: %v", err2)
}
}()
importOptions := ImportFromImageOptions{
Image: image,
SignaturePolicyPath: options.SignaturePolicyPath,
}
builder, err := importBuilderFromImage(options.Store, importOptions)
if err != nil {
return errors.Wrap(err, "error importing builder information from image")
}
// Look up the image name and its layer.
ref, err := is.Transport.ParseStoreReference(options.Store, image)
// Look up the image.
src, err := is.Transport.ParseStoreReference(options.Store, image)
if err != nil {
return errors.Wrapf(err, "error parsing reference to image %q", image)
}
img, err := is.Transport.GetStoreImage(options.Store, ref)
if err != nil {
return errors.Wrapf(err, "error locating image %q", image)
}
// Give the image we're producing the same ancestors as its source image.
builder.FromImage = builder.Docker.ContainerConfig.Image
builder.FromImageID = string(builder.Docker.Parent)
// Prep the layers and manifest for export.
src, err := builder.makeImageImageRef(options.Compression, img.Names, img.TopLayer, nil)
if err != nil {
return errors.Wrapf(err, "error recomputing layer digests and building metadata")
}
// Copy everything.
err = cp.Image(policyContext, dest, src, getCopyOptions(options.ReportWriter, nil, options.SystemContext, options.ManifestType))
if err != nil {

View File

@@ -16,8 +16,11 @@ func getCopyOptions(reportWriter io.Writer, sourceSystemContext *types.SystemCon
}
}
func getSystemContext(signaturePolicyPath string) *types.SystemContext {
func getSystemContext(defaults *types.SystemContext, signaturePolicyPath string) *types.SystemContext {
sc := &types.SystemContext{}
if defaults != nil {
*sc = *defaults
}
if signaturePolicyPath != "" {
sc.SignaturePolicyPath = signaturePolicyPath
}

View File

@@ -2,7 +2,6 @@ package buildah
import (
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strings"
@@ -139,23 +138,30 @@ func makeDockerV2S1Image(manifest docker.V2S1Manifest) (docker.V2Image, error) {
}
// Build a filesystem history.
history := []docker.V2S2History{}
lastID := ""
for i := range manifest.History {
h := docker.V2S2History{
Created: time.Now().UTC(),
Author: "",
CreatedBy: "",
Comment: "",
EmptyLayer: false,
}
// Decode the compatibility field.
dcompat := docker.V1Compatibility{}
if err2 := json.Unmarshal([]byte(manifest.History[i].V1Compatibility), &dcompat); err2 == nil {
h.Created = dcompat.Created.UTC()
h.Author = dcompat.Author
h.Comment = dcompat.Comment
if len(dcompat.ContainerConfig.Cmd) > 0 {
h.CreatedBy = fmt.Sprintf("%v", dcompat.ContainerConfig.Cmd)
}
h.EmptyLayer = dcompat.ThrowAway
if err = json.Unmarshal([]byte(manifest.History[i].V1Compatibility), &dcompat); err != nil {
return docker.V2Image{}, errors.Errorf("error parsing image compatibility data (%q) from history", manifest.History[i].V1Compatibility)
}
// Skip this history item if it shares the ID of the last one
// that we saw, since the image library will do the same.
if i > 0 && dcompat.ID == lastID {
continue
}
lastID = dcompat.ID
// Construct a new history item using the recovered information.
createdBy := ""
if len(dcompat.ContainerConfig.Cmd) > 0 {
createdBy = strings.Join(dcompat.ContainerConfig.Cmd, " ")
}
h := docker.V2S2History{
Created: dcompat.Created.UTC(),
Author: dcompat.Author,
CreatedBy: createdBy,
Comment: dcompat.Comment,
EmptyLayer: dcompat.ThrowAway,
}
// Prepend this layer to the list, because a v2s1 format manifest's list is in reverse order
// compared to v2s2, which lists earlier layers before later ones.

View File

@@ -210,6 +210,10 @@ return 1
_buildah_rmi() {
local boolean_options="
--all
-a
--force
-f
--help
-h
"
@@ -226,6 +230,8 @@ return 1
_buildah_rm() {
local boolean_options="
--all
-a
--help
-h
"
@@ -296,6 +302,7 @@ return 1
"
local options_with_args="
--authfile
--cert-dir
--creds
--signature-policy
@@ -345,16 +352,31 @@ return 1
"
local options_with_args="
--add-host
--authfile
--signature-policy
--build-arg
--cert-dir
--cgroup-parent
--cpu-period
--cpu-quota
--cpu-shares
--cpuset-cpus
--cpuset-mems
--creds
-f
--file
--format
--label
-m
--memory
--memory-swap
--runtime
--runtime-flag
--tag
--security-opt
--signature-policy
-t
--file
-f
--build-arg
--format
--tag
--ulimit
"
local all_options="$options_with_args $boolean_options"
@@ -390,6 +412,7 @@ return 1
--hostname
--runtime
--runtime-flag
--security-opt
--volume
-v
"
@@ -554,6 +577,9 @@ return 1
"
local options_with_args="
--filter
-f
--format
"
local all_options="$options_with_args $boolean_options"
@@ -631,11 +657,23 @@ return 1
"
local options_with_args="
--add-host
--authfile
--cert-dir
--cgroup-parent
--cpu-period
--cpu-quota
--cpu-shares
--cpuset-cpus
--cpuset-mems
--creds
-m
--memory
--memory-swap
--name
--signature-policy
--security-opt
--ulimit
"

View File

@@ -25,7 +25,8 @@
%global shortcommit %(c=%{commit}; echo ${c:0:7})
Name: buildah
Version: 0.7
# Bump version in buildah.go too
Version: 0.15
Release: 1.git%{shortcommit}%{?dist}
Summary: A command line tool used to creating OCI Images
License: ASL 2.0
@@ -41,8 +42,10 @@ BuildRequires: gpgme-devel
BuildRequires: device-mapper-devel
BuildRequires: btrfs-progs-devel
BuildRequires: libassuan-devel
BuildRequires: libseccomp-devel
BuildRequires: glib2-devel
BuildRequires: ostree-devel
BuildRequires: make
Requires: runc >= 1.0.0-6
Requires: container-selinux
Requires: skopeo-containers
@@ -88,6 +91,79 @@ make DESTDIR=%{buildroot} PREFIX=%{_prefix} install install.completions
%{_datadir}/bash-completion/completions/*
%changelog
* Tue Feb 27 2018 Dan Walsh <dwalsh@redhat.com> 0.15-1
- Fix handling of buildah run command options
* Mon Feb 26 2018 Dan Walsh <dwalsh@redhat.com> 0.14-1
- If commonOpts do not exist, we should return rather then segfault
- Display full error string instead of just status
- Implement --volume and --shm-size for bud and from
- Fix secrets patch for buildah bud
- Fixes the naming issue of blobs and config for the dir transport by removing the .tar extension
* Thu Feb 22 2018 Dan Walsh <dwalsh@redhat.com> 0.13-1
- Vendor in latest containers/storage
- This fixes a large SELinux bug.
- run: do not open /etc/hosts if not needed
- Add the following flags to buildah bud and from
--add-host
--cgroup-parent
--cpu-period
--cpu-quota
--cpu-shares
--cpuset-cpus
--cpuset-mems
--memory
--memory-swap
--security-opt
--ulimit
* Mon Feb 12 2018 Dan Walsh <dwalsh@redhat.com> 0.12-1
- Added handing for simpler error message for Unknown Dockerfile instructions.
- Change default certs directory to /etc/containers/certs.d
- Vendor in latest containers/image
- Vendor in latest containers/storage
- build-using-dockerfile: set the 'author' field for MAINTAINER
- Return exit code 1 when buildah-rmi fails
- Trim the image reference to just its name before calling getImageName
- Touch up rmi -f usage statement
- Add --format and --filter to buildah containers
- Add --prune,-p option to rmi command
- Add authfile param to commit
- Fix --runtime-flag for buildah run and bud
- format should override quiet for images
- Allow all auth params to work with bud
- Do not overwrite directory permissions on --chown
- Unescape HTML characters output into the terminal
- Fix: setting the container name to the image
- Prompt for un/pwd if not supplied with --creds
- Make bud be really quiet
- Return a better error message when failed to resolve an image
- Update auth tests and fix bud man page
* Tue Jan 16 2018 Dan Walsh <dwalsh@redhat.com> 0.11-1
- Add --all to remove containers
- Add --all functionality to rmi
- Show ctrid when doing rm -all
- Ignore sequential duplicate layers when reading v2s1
- Lots of minor bug fixes
- Vendor in latest containers/image and containers/storage
* Sat Dec 23 2017 Dan Walsh <dwalsh@redhat.com> 0.10-1
- Display Config and Manifest as strings
- Bump containers/image
- Use configured registries to resolve image names
- Update to work with newer image library
- Add --chown option to add/copy commands
* Sat Dec 2 2017 Dan Walsh <dwalsh@redhat.com> 0.9-1
- Allow push to use the image id
- Make sure builtin volumes have the correct label
* Thu Nov 16 2017 Dan Walsh <dwalsh@redhat.com> 0.8-1
- Buildah bud was failing on SELinux machines, this fixes this
- Block access to certain kernel file systems inside of the container
* Thu Nov 16 2017 Dan Walsh <dwalsh@redhat.com> 0.7-1
- Ignore errors when trying to read containers buildah.json for loading SELinux reservations
- Use credentials from kpod login for buildah
@@ -98,6 +174,10 @@ make DESTDIR=%{buildroot} PREFIX=%{_prefix} install install.completions
- Bump github.com/vbatts/tar-split
- Set option.terminal appropriately in run
* Wed Nov 08 2017 Dan Walsh <dwalsh@redhat.com> 0.5-2
- Bump github.com/vbatts/tar-split
- Fixes CVE That could allow a container image to cause a DOS
* Tue Nov 07 2017 Dan Walsh <dwalsh@redhat.com> 0.5-1
- Add secrets patch to buildah
- Add proper SELinux labeling to buildah run
@@ -128,10 +208,19 @@ make DESTDIR=%{buildroot} PREFIX=%{_prefix} install install.completions
- Turn on --enable-gc when running gometalinter
- rmi: handle truncated image IDs
* Thu Jul 20 2017 Dan Walsh <dwalsh@redhat.com> 0.3.0-1
* Tue Aug 15 2017 Josh Boyer <jwboyer@redhat.com> - 0.3-5.gitb9b2a8a
- Build for s390x as well
* Wed Aug 02 2017 Fedora Release Engineering <releng@fedoraproject.org> - 0.3-4.gitb9b2a8a
- Rebuilt for https://fedoraproject.org/wiki/Fedora_27_Binutils_Mass_Rebuild
* Wed Jul 26 2017 Fedora Release Engineering <releng@fedoraproject.org> - 0.3-3.gitb9b2a8a
- Rebuilt for https://fedoraproject.org/wiki/Fedora_27_Mass_Rebuild
* Thu Jul 20 2017 Dan Walsh <dwalsh@redhat.com> 0.3-2.gitb9b2a8a7e
- Bump for inclusion of OCI 1.0 Runtime and Image Spec
* Tue Jul 18 2017 Dan Walsh <dwalsh@redhat.com> 0.2.0-1
* Tue Jul 18 2017 Dan Walsh <dwalsh@redhat.com> 0.2.0-1.gitac2aad6
- buildah run: Add support for -- ending options parsing
- buildah Add/Copy support for glob syntax
- buildah commit: Add flag to remove containers on commit
@@ -148,7 +237,11 @@ make DESTDIR=%{buildroot} PREFIX=%{_prefix} install install.completions
- buildah version: add command
- buildah run: Handle run without an explicit command correctly
- Ensure volume points get created, and with perms
- buildah containers: Add a -a/--all option
- buildah containers: Add a -a/--all option
* Wed Jun 14 2017 Dan Walsh <dwalsh@redhat.com> 0.1.0-2.git597d2ab9
- Release Candidate 1
- All features have now been implemented.
* Fri Apr 14 2017 Dan Walsh <dwalsh@redhat.com> 0.0.1-1.git7a0a5333
- First package for Fedora

View File

@@ -13,10 +13,18 @@ appears to be an archive, its contents are extracted and added instead of the
archive file itself. If a local directory is specified as a source, its
*contents* are copied to the destination.
## OPTIONS
**--chown** *owner*:*group*
Sets the user and group ownership of the destination content.
## EXAMPLE
buildah add containerID '/myapp/app.conf' '/myapp/app.conf'
buildah add --chown myuser:mygroup containerID '/myapp/app.conf' '/myapp/app.conf'
buildah add containerID '/home/myuser/myproject.go'
buildah add containerID '/home/myuser/myfiles.tar' '/tmp'

View File

@@ -14,9 +14,15 @@ to a temporary location.
## OPTIONS
**--add-host**=[]
Add a custom host-to-IP mapping (host:ip)
Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** option can be set multiple times.
**--authfile** *path*
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `kpod login`.
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `podman login`.
If the authorization state is not found there, $HOME/.docker/config.json is checked, which is set using `docker login`.
**--build-arg** *arg=value*
@@ -26,6 +32,84 @@ instructions read from the Dockerfiles in the same way that environment
variables are, but which will not be added to environment variable list in the
resulting image's configuration.
**--cert-dir** *path*
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry.
Default certificates directory is _/etc/containers/certs.d_.
**--cgroup-parent**=""
Path to cgroups under which the cgroup for the container 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.
**--cpu-period**=*0*
Limit the CPU CFS (Completely Fair Scheduler) period
Limit the container's CPU usage. This flag tell the kernel to restrict the container's CPU usage to the period you specify.
**--cpu-quota**=*0*
Limit the CPU CFS (Completely Fair Scheduler) quota
Limit the container's CPU usage. By default, containers run with the full
CPU resource. This flag tell the kernel to restrict the container's CPU usage
to the quota you specify.
**--cpu-shares**=*0*
CPU shares (relative weight)
By default, all containers get the same proportion of CPU cycles. This proportion
can be modified by changing the container's CPU share weighting relative
to the weighting of all other running containers.
To modify the proportion from the default of 1024, use the **--cpu-shares**
flag to set the weighting to 2 or higher.
The proportion will only apply when CPU-intensive processes are running.
When tasks in one container are idle, other containers can use the
left-over CPU time. The actual amount of CPU time will vary depending on
the number of containers running on the system.
For example, consider three containers, one has a cpu-share of 1024 and
two others have a cpu-share setting of 512. When processes in all three
containers attempt to use 100% of CPU, the first container would receive
50% of the total CPU time. If you add a fourth container with a cpu-share
of 1024, the first container only gets 33% of the CPU. The remaining containers
receive 16.5%, 16.5% and 33% of the CPU.
On a multi-core system, the shares of CPU time are distributed over all CPU
cores. Even if a container is limited to less than 100% of CPU time, it can
use 100% of each individual CPU core.
For example, consider a system with more than three cores. If you start one
container **{C0}** with **-c=512** running one process, and another container
**{C1}** with **-c=1024** running two processes, this can result in the following
division of CPU shares:
PID container CPU CPU share
100 {C0} 0 100% of CPU0
101 {C1} 1 100% of CPU1
102 {C1} 2 100% of CPU2
**--cpuset-cpus**=""
CPUs in which to allow execution (0-3, 0,1)
**--cpuset-mems**=""
Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1`
then processes in your container will only use memory from the first
two memory nodes.
**--creds** *creds*
The [username[:password]] to use to authenticate with the registry if required.
If one or both values are not supplied, a command line prompt will appear and the
value can be entered. The password is entered without echo.
**-f, --file** *Dockerfile*
Specifies a Dockerfile which contains instructions for building the image,
@@ -43,6 +127,27 @@ Control the format for the built image's manifest and configuration data.
Recognized formats include *oci* (OCI image-spec v1.0, the default) and
*docker* (version 2, using schema format 2 for the manifest).
**-m**, **--memory**=""
Memory limit (format: <number>[<unit>], where unit = b, k, m or g)
Allows you to constrain the memory available to a container. If the host
supports swap memory, then the **-m** memory setting can be larger than physical
RAM. If a limit of 0 is specified (not using **-m**), the container's memory is
not limited. The actual limit may be rounded up to a multiple of the operating
system's page size (the value would be very large, that's millions of trillions).
**--memory-swap**="LIMIT"
A limit value equal to memory plus swap. Must be used with the **-m**
(**--memory**) flag. The swap `LIMIT` should always be larger than **-m**
(**--memory**) value. By default, the swap `LIMIT` will be set to double
the value of --memory.
The format of `LIMIT` is `<number>[<unit>]`. Unit can be `b` (bytes),
`k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you don't specify a
unit, `b` is used. Set LIMIT to `-1` to enable unlimited swap.
**--pull**
Pull the image if it is not present. If this flag is disabled (with
@@ -53,7 +158,7 @@ Defaults to *true*.
Pull the image even if a version of the image is already present.
**--quiet**
**-q, --quiet**
Suppress output messages which indicate which instruction is being processed,
and of progress when pulling images from a registry, and when writing the
@@ -66,7 +171,34 @@ commands specified by the **RUN** instruction.
**--runtime-flag** *flag*
Adds global flags for the container rutime.
Adds global flags for the container rutime. To list the supported flags, please
consult the manpages of the selected container runtime (`runc` is the default
runtime, the manpage to consult is `runc(8)`).
Note: Do not pass the leading `--` to the flag. To pass the runc flag `--log-format json`
to buildah bud, the option given would be `--runtime-flag log-format=json`.
**--security-opt**=[]
Security Options
"label=user:USER" : Set the label user for the container
"label=role:ROLE" : Set the label role for the container
"label=type:TYPE" : Set the label type for the container
"label=level:LEVEL" : Set the label level for the container
"label=disable" : Turn off label confinement for the container
"no-new-privileges" : Not supported
"seccomp=unconfined" : Turn off seccomp confinement for the container
"seccomp=profile.json : White listed syscalls seccomp Json file to be used as a seccomp filter
"apparmor=unconfined" : Turn off apparmor confinement for the container
"apparmor=your-profile" : Set the apparmor confinement profile for the container
**--shm-size**=""
Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`.
Unit is optional and can be `b` (bytes), `k` (kilobytes), `m`(megabytes), or `g` (gigabytes).
If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`.
**--signature-policy** *signaturepolicy*
@@ -81,7 +213,76 @@ process completes successfully.
**--tls-verify** *bool-value*
Require HTTPS and verify certificates when talking to container registries (defaults to true)
Require HTTPS and verify certificates when talking to container registries (defaults to true).
**--ulimit**=[]
Ulimit options
**-v**|**--volume**[=*[HOST-DIR:CONTAINER-DIR[:OPTIONS]]*]
Create a bind mount. If you specify, ` -v /HOST-DIR:/CONTAINER-DIR`, podman
bind mounts `/HOST-DIR` in the host to `/CONTAINER-DIR` in the podman
container. The `OPTIONS` are a comma delimited list and can be:
* [rw|ro]
* [z|Z]
* [`[r]shared`|`[r]slave`|`[r]private`]
The `CONTAINER-DIR` must be an absolute path such as `/src/docs`. The `HOST-DIR`
must be an absolute path as well. podman bind-mounts the `HOST-DIR` to the
path you specify. For example, if you supply the `/foo` value, podman creates a bind-mount.
You can specify multiple **-v** options to mount one or more mounts to a
container.
You can 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.
Labeling systems like SELinux require that proper labels are placed on volume
content mounted into a container. 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 container context, you can 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 containers
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 container can use a private volume.
By default bind mounted volumes are `private`. That means any mounts done
inside container will not be visible on the host and vice versa. This behavior can
be changed by specifying a volume mount propagation property.
When the mount propagation policy is set to `shared`, any mounts completed inside
the container on that volume will be visible to both the host and container. When
the mount propagation policy is set to `slave`, one way mount propagation is enabled
and any mounts completed on the host for that volume will be visible only inside of the container.
To control the mount propagation property of volume use the `:[r]shared`,
`:[r]slave` or `:[r]private` propagation flag. The propagation property can
be specified only for bind mounted volumes and not for internal volumes or
named volumes. For mount propagation to work on the source mount point (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 has to be either shared or slave.
Use `df <source-dir>` to determine the source mount and then use
`findmnt -o TARGET,PROPAGATION <source-mount-dir>` to determine propagation
properties of source mount, if `findmnt` utility is not available, the source mount point
can be determined by looking at the mount entry in `/proc/self/mountinfo`. Look
at `optional fields` and see if any propagaion properties are specified.
`shared:X` means the mount is `shared`, `master:X` means the mount is `slave` and if
nothing is there that means the mount is `private`.
To change propagation properties of a mount point use the `mount` command. For
example, to bind mount the source directory `/foo` do
`mount --bind /foo /foo` and `mount --make-private --make-shared /foo`. This
will convert /foo into a `shared` mount point. The propagation properties of the source
mount can be changed directly. For instance if `/` is the source mount for
`/foo`, then use `mount --make-shared /` to convert `/` into a `shared` mount.
## EXAMPLE
@@ -97,5 +298,17 @@ buildah bud --tls-verify=true -t imageName -f Dockerfile.simple
buildah bud --tls-verify=false -t imageName .
buildah bud --runtime-flag log-format=json .
buildah bud --runtime-flag debug .
buildah bud --authfile /tmp/auths/myauths.json --cert-dir ~/auth --tls-verify=true --creds=username:password -t imageName -f Dockerfile.simple
buildah bud --memory 40m --cpu-period 10000 --cpu-quota 50000 --ulimit nofile=1024:1028 -t imageName .
buildah bud --security-opt label=level:s0:c100,c200 --cgroup-parent /path/to/cgroup/parent -t imageName .
buildah bud --volume /home/test:/myvol:ro,Z -t imageName .
## SEE ALSO
buildah(1), kpod-login(1), docker-login(1)
buildah(1), podman-login(1), docker-login(1)

View File

@@ -13,13 +13,21 @@ specified, an ID is assigned, but no name is assigned to the image.
## OPTIONS
**--authfile** *path*
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `podman login`.
If the authorization state is not found there, $HOME/.docker/config.json is checked, which is set using `docker login`.
**--cert-dir** *path*
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry.
Default certificates directory is _/etc/containers/certs.d_.
**--creds** *creds*
The username[:password] to use to authenticate with the registry if required.
The [username[:password]] to use to authenticate with the registry if required.
If one or both values are not supplied, a command line prompt will appear and the
value can be entered. The password is entered without echo.
**--disable-compression, -D**
@@ -71,5 +79,8 @@ This example commits the container to the image on the local registry while turn
This example commits the container to the image on the local registry using credentials and certificates for authentication.
`buildah commit --cert-dir ~/auth --tls-verify=true --creds=username:password containerID docker://localhost:5000/imageId`
This example commits the container to the image on the local registry using credentials from the /tmp/auths/myauths.json file and certificates for authentication.
`buildah commit --authfile /tmp/auths/myauths.json --cert-dir ~/auth --tls-verify=true --creds=username:password containerID docker://localhost:5000/imageId`
## SEE ALSO
buildah(1)

View File

@@ -15,7 +15,34 @@ IDs, and the names and IDs of the images from which they were initialized.
**--all, -a**
List information about all containers, including those which were not created
by and are not being used by Buildah.
by and are not being used by Buildah. Containers created by Buildah are
denoted with an '*' in the 'BUILDER' column.
**--filter, -f**
Filter output based on conditions provided.
Valid filters are listed below:
| **Filter** | **Description** |
| --------------- | ------------------------------------------------------------------- |
| id | [ID] Container's ID |
| name | [Name] Container's name |
| ancestor | [ImageName] Image or descendant used to create container |
**--format**
Pretty-print containers using a Go template.
Valid placeholders for the Go template are listed below:
| **Placeholder** | **Description** |
| --------------- | -----------------------------------------|
| .ContainerID | Container ID |
| .Builder | Whether container was created by buildah |
| .ImageID | Image ID |
| .ImageName | Image name |
| .ContainerName | Container name |
**--json**
@@ -36,12 +63,55 @@ Displays only the container IDs.
## EXAMPLE
buildah containers
```
CONTAINER ID BUILDER IMAGE ID IMAGE NAME CONTAINER NAME
29bdb522fc62 * 3fd9065eaf02 docker.io/library/alpine:latest alpine-working-container
c6b04237ac8e * f9b6f7f7b9d3 docker.io/library/busybox:latest busybox-working-container
```
buildah containers --quiet
```
29bdb522fc62d43fca0c1a0f11cfc6dfcfed169cf6cf25f928ebca1a612ff5b0
c6b04237ac8e9d435ec9cf0e7eda91e302f2db9ef908418522c2d666352281eb
```
buildah containers -q --noheading --notruncate
```
29bdb522fc62d43fca0c1a0f11cfc6dfcfed169cf6cf25f928ebca1a612ff5b0
c6b04237ac8e9d435ec9cf0e7eda91e302f2db9ef908418522c2d666352281eb
```
buildah containers --json
```
[
{
"id": "29bdb522fc62d43fca0c1a0f11cfc6dfcfed169cf6cf25f928ebca1a612ff5b0",
"builder": true,
"imageid": "3fd9065eaf02feaf94d68376da52541925650b81698c53c6824d92ff63f98353",
"imagename": "docker.io/library/alpine:latest",
"containername": "alpine-working-container"
},
{
"id": "c6b04237ac8e9d435ec9cf0e7eda91e302f2db9ef908418522c2d666352281eb",
"builder": true,
"imageid": "f9b6f7f7b9d34113f66e16a9da3e921a580937aec98da344b852ca540aaa2242",
"imagename": "docker.io/library/busybox:latest",
"containername": "busybox-working-container"
}
]
```
buildah containers --format "{{.ContainerID}} {{.ContainerName}}"
```
3fbeaa87e583ee7a3e6787b2d3af961ef21946a0c01a08938e4f52d53cce4c04 myalpine-working-container
fbfd3505376ee639c3ed50f9d32b78445cd59198a1dfcacf2e7958cda2516d5c ubuntu-working-container
```
buildah containers --filter ancestor=ubuntu
```
CONTAINER ID BUILDER IMAGE ID IMAGE NAME CONTAINER NAME
fbfd3505376e * 0ff04b2e7b63 docker.io/library/ubuntu:latest ubuntu-working-container
```
## SEE ALSO
buildah(1)

View File

@@ -11,10 +11,18 @@ Copies the contents of a file, URL, or a directory to a container's working
directory or a specified location in the container. If a local directory is
specified as a source, its *contents* are copied to the destination.
## OPTIONS
**--chown** *owner*:*group*
Sets the user and group ownership of the destination content.
## EXAMPLE
buildah copy containerID '/myapp/app.conf' '/myapp/app.conf'
buildah copy --chown myuser:mygroup containerID '/myapp/app.conf' '/myapp/app.conf'
buildah copy containerID '/home/myuser/myproject.go'
buildah copy containerID '/home/myuser/myfiles.tar' '/tmp'

View File

@@ -17,7 +17,7 @@ Multiple transports are supported:
An existing local directory _path_ retrieving the manifest, layer tarballs and signatures as individual files. This is a non-standardized format, primarily useful for debugging or noninvasive container inspection.
**docker://**_docker-reference_ (Default)
An image in a registry implementing the "Docker Registry HTTP API V2". By default, uses the authorization state in `$XDG_RUNTIME_DIR/containers/auth.json`, which is set using `(kpod login)`. If the authorization state is not found there, `$HOME/.docker/config.json` is checked, which is set using `(docker login)`.
An image in a registry implementing the "Docker Registry HTTP API V2". By default, uses the authorization state in `$XDG_RUNTIME_DIR/containers/auth.json`, which is set using `(podman login)`. If the authorization state is not found there, `$HOME/.docker/config.json` is checked, which is set using `(docker login)`.
**docker-archive:**_path_
An image is retrieved as a `docker load` formatted file.
@@ -36,18 +36,115 @@ The container ID of the container that was created. On error, -1 is returned an
## OPTIONS
**--add-host**=[]
Add a custom host-to-IP mapping (host:ip)
Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** option can be set multiple times.
**--authfile** *path*
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `kpod login`.
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `podman login`.
If the authorization state is not found there, $HOME/.docker/config.json is checked, which is set using `docker login`.
**--cert-dir** *path*
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry.
Default certificates directory is _/etc/containers/certs.d_.
**--cgroup-parent**=""
Path to cgroups under which the cgroup for the container 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.
**--cpu-period**=*0*
Limit the CPU CFS (Completely Fair Scheduler) period
Limit the container's CPU usage. This flag tell the kernel to restrict the container's CPU usage to the period you specify.
**--cpu-quota**=*0*
Limit the CPU CFS (Completely Fair Scheduler) quota
Limit the container's CPU usage. By default, containers run with the full
CPU resource. This flag tell the kernel to restrict the container's CPU usage
to the quota you specify.
**--cpu-shares**=*0*
CPU shares (relative weight)
By default, all containers get the same proportion of CPU cycles. This proportion
can be modified by changing the container's CPU share weighting relative
to the weighting of all other running containers.
To modify the proportion from the default of 1024, use the **--cpu-shares**
flag to set the weighting to 2 or higher.
The proportion will only apply when CPU-intensive processes are running.
When tasks in one container are idle, other containers can use the
left-over CPU time. The actual amount of CPU time will vary depending on
the number of containers running on the system.
For example, consider three containers, one has a cpu-share of 1024 and
two others have a cpu-share setting of 512. When processes in all three
containers attempt to use 100% of CPU, the first container would receive
50% of the total CPU time. If you add a fourth container with a cpu-share
of 1024, the first container only gets 33% of the CPU. The remaining containers
receive 16.5%, 16.5% and 33% of the CPU.
On a multi-core system, the shares of CPU time are distributed over all CPU
cores. Even if a container is limited to less than 100% of CPU time, it can
use 100% of each individual CPU core.
For example, consider a system with more than three cores. If you start one
container **{C0}** with **-c=512** running one process, and another container
**{C1}** with **-c=1024** running two processes, this can result in the following
division of CPU shares:
PID container CPU CPU share
100 {C0} 0 100% of CPU0
101 {C1} 1 100% of CPU1
102 {C1} 2 100% of CPU2
**--cpuset-cpus**=""
CPUs in which to allow execution (0-3, 0,1)
**--cpuset-mems**=""
Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1`
then processes in your container will only use memory from the first
two memory nodes.
**--creds** *creds*
The username[:password] to use to authenticate with the registry if required.
The [username[:password]] to use to authenticate with the registry if required.
If one or both values are not supplied, a command line prompt will appear and the
value can be entered. The password is entered without echo.
**-m**, **--memory**=""
Memory limit (format: <number>[<unit>], where unit = b, k, m or g)
Allows you to constrain the memory available to a container. If the host
supports swap memory, then the **-m** memory setting can be larger than physical
RAM. If a limit of 0 is specified (not using **-m**), the container's memory is
not limited. The actual limit may be rounded up to a multiple of the operating
system's page size (the value would be very large, that's millions of trillions).
**--memory-swap**="LIMIT"
A limit value equal to memory plus swap. Must be used with the **-m**
(**--memory**) flag. The swap `LIMIT` should always be larger than **-m**
(**--memory**) value. By default, the swap `LIMIT` will be set to double
the value of --memory.
The format of `LIMIT` is `<number>[<unit>]`. Unit can be `b` (bytes),
`k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you don't specify a
unit, `b` is used. Set LIMIT to `-1` to enable unlimited swap.
**--name** *name*
@@ -67,6 +164,29 @@ Pull the image even if a version of the image is already present.
If an image needs to be pulled from the registry, suppress progress output.
**--security-opt**=[]
Security Options
"label=user:USER" : Set the label user for the container
"label=role:ROLE" : Set the label role for the container
"label=type:TYPE" : Set the label type for the container
"label=level:LEVEL" : Set the label level for the container
"label=disable" : Turn off label confinement for the container
"no-new-privileges" : Not supported
"seccomp=unconfined" : Turn off seccomp confinement for the container
"seccomp=profile.json : White listed syscalls seccomp Json file to be used as a seccomp filter
"apparmor=unconfined" : Turn off apparmor confinement for the container
"apparmor=your-profile" : Set the apparmor confinement profile for the container
**--shm-size**=""
Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`.
Unit is optional and can be `b` (bytes), `k` (kilobytes), `m`(megabytes), or `g` (gigabytes).
If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`.
**--signature-policy** *signaturepolicy*
Pathname of a signature policy file to use. It is not recommended that this
@@ -77,6 +197,75 @@ option be used, as the default behavior of using the system-wide default policy
Require HTTPS and verify certificates when talking to container registries (defaults to true)
**--ulimit**=[]
Ulimit options
**-v**|**--volume**[=*[HOST-DIR:CONTAINER-DIR[:OPTIONS]]*]
Create a bind mount. If you specify, ` -v /HOST-DIR:/CONTAINER-DIR`, podman
bind mounts `/HOST-DIR` in the host to `/CONTAINER-DIR` in the podman
container. The `OPTIONS` are a comma delimited list and can be:
* [rw|ro]
* [z|Z]
* [`[r]shared`|`[r]slave`|`[r]private`]
The `CONTAINER-DIR` must be an absolute path such as `/src/docs`. The `HOST-DIR`
must be an absolute path as well. podman bind-mounts the `HOST-DIR` to the
path you specify. For example, if you supply the `/foo` value, podman creates a bind-mount.
You can specify multiple **-v** options to mount one or more mounts to a
container.
You can 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.
Labeling systems like SELinux require that proper labels are placed on volume
content mounted into a container. 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 container context, you can 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 containers
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 container can use a private volume.
By default bind mounted volumes are `private`. That means any mounts done
inside container will not be visible on the host and vice versa. This behavior can
be changed by specifying a volume mount propagation property.
When the mount propagation policy is set to `shared`, any mounts completed inside
the container on that volume will be visible to both the host and container. When
the mount propagation policy is set to `slave`, one way mount propagation is enabled
and any mounts completed on the host for that volume will be visible only inside of the container.
To control the mount propagation property of volume use the `:[r]shared`,
`:[r]slave` or `:[r]private` propagation flag. The propagation property can
be specified only for bind mounted volumes and not for internal volumes or
named volumes. For mount propagation to work on the source mount point (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 has to be either shared or slave.
Use `df <source-dir>` to determine the source mount and then use
`findmnt -o TARGET,PROPAGATION <source-mount-dir>` to determine propagation
properties of source mount, if `findmnt` utility is not available, the source mount point
can be determined by looking at the mount entry in `/proc/self/mountinfo`. Look
at `optional fields` and see if any propagaion properties are specified.
`shared:X` means the mount is `shared`, `master:X` means the mount is `slave` and if
nothing is there that means the mount is `private`.
To change propagation properties of a mount point use the `mount` command. For
example, to bind mount the source directory `/foo` do
`mount --bind /foo /foo` and `mount --make-private --make-shared /foo`. This
will convert /foo into a `shared` mount point. The propagation properties of the source
mount can be changed directly. For instance if `/` is the source mount for
`/foo`, then use `mount --make-shared /` to convert `/` into a `shared` mount.
## EXAMPLE
buildah from imagename --pull
@@ -93,5 +282,11 @@ buildah from myregistry/myrepository/imagename:imagetag --creds=myusername:mypas
buildah from myregistry/myrepository/imagename:imagetag --authfile=/tmp/auths/myauths.json
buildah from --memory 40m --cpu-shares 2 --cpuset-cpus 0,2 --security-opt label=level:s0:c100,c200 myregistry/myrepository/imagename:imagetag
buildah from --ulimit nofile=1024:1028 --cgroup-parent /path/to/cgroup/parent myregistry/myrepository/imagename:imagetag
buildah from --volume /home/test:/myvol:ro,Z myregistry/myrepository/imagename:imagetag
## SEE ALSO
buildah(1), kpod-login(1), docker-login(1)
buildah(1), podman-login(1), docker-login(1)

View File

@@ -22,7 +22,7 @@ keywords are 'dangling', 'label', 'before' and 'since'.
**--format="TEMPLATE"**
Pretty-print images using a Go template. Will override --quiet
Pretty-print images using a Go template.
**--json**

View File

@@ -12,7 +12,7 @@ buildah mount - Mount a working container's root filesystem.
Mounts the specified container's root file system in a location which can be
accessed from the host, and returns its location.
If you execute the command without any arguments, the tool will list all of the
If the mount command is invoked without any arguments, the tool will list all of the
currently mounted containers.
## RETURN VALUE

View File

@@ -24,7 +24,7 @@ Image stored in local container/storage
An existing local directory _path_ storing the manifest, layer tarballs and signatures as individual files. This is a non-standardized format, primarily useful for debugging or noninvasive container inspection.
**docker://**_docker-reference_
An image in a registry implementing the "Docker Registry HTTP API V2". By default, uses the authorization state in `$XDG_RUNTIME_DIR/containers/auth.json`, which is set using `(kpod login)`. If the authorization state is not found there, `$HOME/.docker/config.json` is checked, which is set using `(docker login)`.
An image in a registry implementing the "Docker Registry HTTP API V2". By default, uses the authorization state in `$XDG_RUNTIME_DIR/containers/auth.json`, which is set using `(podman login)`. If the authorization state is not found there, `$HOME/.docker/config.json` is checked, which is set using `(docker login)`.
**docker-archive:**_path_[**:**_docker-reference_]
An image is stored in the `docker save` formatted file. _docker-reference_ is only used when creating such a file, and it must not contain a digest.
@@ -42,16 +42,19 @@ Image stored in local container/storage
**--authfile** *path*
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `kpod login`.
Path of the authentication file. Default is ${XDG_RUNTIME\_DIR}/containers/auth.json, which is set using `podman login`.
If the authorization state is not found there, $HOME/.docker/config.json is checked, which is set using `docker login`.
**--cert-dir** *path*
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry
Use certificates at *path* (*.crt, *.cert, *.key) to connect to the registry.
Default certificates directory is _/etc/containers/certs.d_.
**--creds** *creds*
The username[:password] to use to authenticate with the registry if required.
The [username[:password]] to use to authenticate with the registry if required.
If one or both values are not supplied, a command line prompt will appear and the
value can be entered. The password is entered without echo.
**--disable-compression, -D**
@@ -104,4 +107,4 @@ This example extracts the imageID image and puts it into the registry on the loc
`# buildah push --cert-dir ~/auth --tls-verify=true --creds=username:password imageID docker://localhost:5000/my-imageID`
## SEE ALSO
buildah(1), kpod-login(1), docker-login(1)
buildah(1), podman-login(1), docker-login(1)

View File

@@ -9,11 +9,19 @@ buildah rm - Removes one or more working containers.
## DESCRIPTION
Removes one or more working containers, unmounting them if necessary.
## OPTIONS
**--all, -a**
All Buildah containers will be removed. Buildah containers are denoted with an '*' in the 'BUILDER' column listed by the command 'buildah containers'.
## EXAMPLE
buildah rm containerID
buildah rm containerID1 containerID2 containerID3
buildah rm --all
## SEE ALSO
buildah(1)

View File

@@ -9,16 +9,35 @@ buildah rmi - Removes one or more images.
## DESCRIPTION
Removes one or more locally stored images.
## LIMITATIONS
If the image was pushed to a directory path using the 'dir:' transport
the rmi command can not remove the image. Instead standard file system
commands should be used.
## OPTIONS
**--all, -a**
All local images will be removed from the system that do not have containers using the image as a reference image.
**--prune, -p**
All local images will be removed from the system that do not have a tag and do not have a child image pointing to them.
**--force, -f**
Executing this command will stop all containers that are using the image and remove them from the system
This option will cause Buildah to remove all containers that are using the image before removing the image from the system.
## EXAMPLE
buildah rmi imageID
buildah rmi --all
buildah rmi --all --force
buildah rmi --prune
buildah rmi --force imageID
buildah rmi imageID1 imageID2 imageID3

View File

@@ -10,11 +10,10 @@ buildah run - Run a command inside of the container.
Launches a container and runs the specified command in that container using the
container's root filesystem as a root filesystem, using configuration settings
inherited from the container's image or as specified using previous calls to
the *buildah config* command. If you execute *buildah run* and expect an
interactive shell, you need to specify the --tty flag.
the *buildah config* command. To execute *buildah run* within an
interactive shell, specify the --tty option.
## OPTIONS
**--hostname**
Set the hostname inside of the running container.
@@ -25,8 +24,10 @@ The *path* to an alternate OCI-compatible runtime.
**--runtime-flag** *flag*
Adds global flags for the container runtime. To list the supported flags, please
consult manpages of your selected container runtime (`runc` is the default
runtime, the manpage to consult is `runc(8)`)
consult the manpages of the selected container runtime (`runc` is the default
runtime, the manpage to consult is `runc(8)`).
Note: Do not pass the leading `--` to the flag. To pass the runc flag `--log-format json`
to buildah run, the option given would be `--runtime-flag log-format=json`.
**--tty**
@@ -40,8 +41,8 @@ with the stdin and stdout stream of the container. Setting the `--tty` option t
Bind mount a location from the host into the container for its lifetime.
NOTE: End parsing of options with the `--` option, so that you can pass other
options to the command inside of the container
NOTE: End parsing of options with the `--` option, so that other
options can be passed to the command inside of the container.
## EXAMPLE
@@ -49,7 +50,9 @@ buildah run containerID -- ps -auxw
buildah run containerID --hostname myhost -- ps -auxw
buildah run containerID --runtime-flag --no-new-keyring -- ps -auxw
buildah run --runtime-flag log-format=json containerID /bin/bash
buildah run --runtime-flag debug containerID /bin/bash
buildah run --tty containerID /bin/bash

View File

@@ -16,6 +16,8 @@ The Buildah package provides a command line tool which can be used to:
* Use the updated contents of a container's root filesystem as a filesystem layer to create a new image.
* Delete a working container or an image.
This tool needs to be run as the root user.
## OPTIONS
**--debug**
@@ -24,12 +26,28 @@ Print debugging information
**--default-mounts-file**
path to default mounts file (default path: "/usr/share/containers/mounts.conf")
Path to default mounts file (default path: "/usr/share/containers/mounts.conf")
**--help, -h**
Show help
**--registries-conf** *path*
Pathname of the configuration file which specifies which registries should be
consulted when completing image names which do not include a registry or domain
portion. It is not recommended that this option be used, as the default
behavior of using the system-wide configuration
(*/etc/containers/registries.conf*) is most often preferred.
**--registries-conf-dir** *path*
Pathname of the directory which contains configuration snippets which specify
registries which should be consulted when completing image names which do not
include a registry or domain portion. It is not recommended that this option
be used, as the default behavior of using the system-wide configuration
(*/etc/containers/registries.d*) is most often preferred.
**--root** **value**
Storage root dir (default: "/var/lib/containers/storage")

View File

@@ -1,3 +1,5 @@
![buildah logo](https://cdn.rawgit.com/projectatomic/buildah/master/logos/buildah-logo_large.png)
# Buildah Tutorial 1
## Building OCI container images

View File

@@ -0,0 +1,134 @@
![buildah logo](https://cdn.rawgit.com/projectatomic/buildah/master/logos/buildah-logo_large.png)
# Buildah Tutorial 2
## Using Buildah with container registries
The purpose of this tutorial is to demonstrate how Buildah can be used to move OCI compliant images in and out of private or public registries.
In the [first tutorial](https://github.com/projectatomic/buildah/blob/master/docs/tutorials/01-intro.md) we built an image from scratch that we called `fedora-bashecho` and we pushed it to a local Docker repository using the `docker-daemon` protocol. We are going to use the same image to push to a private Docker registry.
First we must pull down a registry. As a shortcut we will save the container name that is returned from the `buildah from` command, into a bash variable called `registry`. This is just like we did in Tutorial 1:
# registry=$(buildah from registry)
It is worth pointing out that the `from` command can also use other protocols beyond the default (and implicity assumed) order that first looks in local containers-storage (containers-storage:) and then looks in the Docker hub (docker:). For example, if you already had a registry container image in a local Docker registry then you could use the following:
# registry=$(buildah from docker-daemon:registry:latest)
Then we need to start the registry. You should start the registry in a separate shell and leave it running there:
# buildah run $registry
If you would like to see more details as to what is going on inside the registry, especially if you are having problems with the registry, you can run the registry container in debug mode as follows:
# buildah --debug run $registry
You can use `--debug` on any Buildah command.
The registry is running and is waiting for requests to process. Notice that this registry is a Docker registry that we pulled from Docker hub and we are running it for this example using `buildah run`. There is no Docker daemon running at this time.
Let's push our image to the private registry. By default, Buildah is set up to expect secure connections to a registry. Therefore we will need to turn the TLS verification off using the `--tls-verify` flag. We also need to tell Buildah that the registry is on this local host ( i.e. localhost) and listening on port 5000. Similar to what you'd expect to do on multi-tenant Docker hub, we will explicitly specify that the registry is to store the image under the `ipbabble` repository - so as not to clash with other users' similarly named images.
# buildah push --tls-verify=false fedora-bashecho docker://localhost:5000/ipbabble/fedora-bashecho:latest
[Skopeo](https://github.com/projectatomic/skopeo) is a ProjectAtomic tool that was created to inspect images in registries without having to pull the image from the registry. It has grown to have many other uses. We will verify that the image has been stored by using Skopeo to inspect the image in the registry:
# skopeo inspect --tls-verify=false docker://localhost:5000/ipbabble/fedora-bashecho:latest
{
"Name": "localhost:5000/ipbabble/fedora-bashecho",
"Digest": "sha256:6806f9385f97bc09f54b5c0ef583e58c3bc906c8c0b3e693d8782d0a0acf2137",
"RepoTags": [
"latest"
],
"Created": "2017-12-05T21:38:12.311901938Z",
"DockerVersion": "",
"Labels": {
"name": "fedora-bashecho"
},
"Architecture": "amd64",
"Os": "linux",
"Layers": [
"sha256:0cb7556c714767b8da6e0299cbeab765abaddede84769475c023785ae66d10ca"
]
}
We can verify that it is still portable with Docker by starting Docker again, as we did in the first tutorial. Then we can pull down the image and starting the container using Docker:
# systemctl start docker
# docker pull localhost:5000/ipbabble/fedora-bashecho
Using default tag: latest
Trying to pull repository localhost:5000/ipbabble/fedora-bashecho ...
sha256:6806f9385f97bc09f54b5c0ef583e58c3bc906c8c0b3e693d8782d0a0acf2137: Pulling from localhost:5000/ipbabble/fedora-bashecho
0cb7556c7147: Pull complete
Digest: sha256:6806f9385f97bc09f54b5c0ef583e58c3bc906c8c0b3e693d8782d0a0acf2137
Status: Downloaded newer image for localhost:5000/ipbabble/fedora-bashecho:latest
# docker run localhost:5000/ipbabble/fedora-bashecho
This is a new container named ipbabble [ 0 ]
This is a new container named ipbabble [ 1 ]
This is a new container named ipbabble [ 2 ]
This is a new container named ipbabble [ 3 ]
This is a new container named ipbabble [ 4 ]
This is a new container named ipbabble [ 5 ]
This is a new container named ipbabble [ 6 ]
This is a new container named ipbabble [ 7 ]
This is a new container named ipbabble [ 8 ]
This is a new container named ipbabble [ 9 ]
# systemctl stop docker
Pushing to Docker hub is just as easy. Of course you must have an account with credentials. In this example I'm using a Docker hub API key, which has the form "username:password" (example password has been edited for privacy), that I created with my Docker hub account. I use the `--creds` flag to use my API key. I also specify my local image name `fedora-bashecho` as my image source and I use the `docker` protocol with no host or port so that it will look at the default Docker hub registry:
# buildah push --creds ipbabble:5bbb9990-6eeb-1234-af1a-aaa80066887c fedora-bashecho docker://ipbabble/fedora-bashecho:latest
And let's inspect that with Skopeo:
# skopeo inspect --creds ipbabble:5bbb9990-6eeb-1234-af1a-aaa80066887c docker://ipbabble/fedora-bashecho:latest
{
"Name": "docker.io/ipbabble/fedora-bashecho",
"Digest": "sha256:6806f9385f97bc09f54b5c0ef583e58c3bc906c8c0b3e693d8782d0a0acf2137",
"RepoTags": [
"latest"
],
"Created": "2017-12-05T21:38:12.311901938Z",
"DockerVersion": "",
"Labels": {
"name": "fedora-bashecho"
},
"Architecture": "amd64",
"Os": "linux",
"Layers": [
"sha256:0cb7556c714767b8da6e0299cbeab765abaddede84769475c023785ae66d10ca"
]
}
We can use Buildah to pull down the image using the `buildah from` command. But before we do let's clean up our local containers-storage so that we don't have an existing fedora-bashecho - otherwise Buildah will know it already exists and not bother pulling it down.
# buildah images
IMAGE ID IMAGE NAME CREATED AT SIZE
d4cd7d73ee42 docker.io/library/registry:latest Dec 1, 2017 22:15 31.74 MB
e31b0f0b0a63 docker.io/library/fedora-bashecho:latest Dec 5, 2017 21:38 772 B
# buildah rmi fedora-bashecho
untagged: docker.io/library/fedora-bashecho:latest
e31b0f0b0a63e94c5a558d438d7490fab930a282a4736364360ab9b92cb25f3a
# buildah images
IMAGE ID IMAGE NAME CREATED AT SIZE
d4cd7d73ee42 docker.io/library/registry:latest Dec 1, 2017 22:15 31.74 MB
Okay, so we don't have a fedora-bashecho anymore. Let's pull the image from Docker hub:
# buildah from ipbabble/fedora-bashecho
If you don't want to bother doing the remove image step (`rmi`) you can use the flag `--pull-always` to force the image to be pulled again and overwrite any corresponding local image.
Now check that image is in the local containers-storage:
# buildah images
IMAGE ID IMAGE NAME CREATED AT SIZE
d4cd7d73ee42 docker.io/library/registry:latest Dec 1, 2017 22:15 31.74 MB
864871ac1c45 docker.io/ipbabble/fedora-bashecho:latest Dec 5, 2017 21:38 315.4 MB
Success!
If you have any suggestions or issues please post them at the [ProjectAtomic Buildah Issues page](https://github.com/projectatomic/buildah/issues).
For more information on Buildah and how you might contribute please visit the [Buildah home page on Github](https://github.com/projectatomic/buildah).

16
docs/tutorials/README.md Normal file
View File

@@ -0,0 +1,16 @@
![buildah logo](https://cdn.rawgit.com/projectatomic/buildah/master/logos/buildah-logo_large.png)
# Buildah Tutorials
## Links to a number of useful tutorials for the Buildah project.
**[Introduction Tutorial](https://github.com/projectatomic/buildah/tree/master/docs/tutorials/01-intro.md)**
Learn how to build container images compliant with the [Open Container Initiative](https://www.opencontainers.org/) (OCI) [image specification](https://github.com/opencontainers/image-spec) using Buildah.
**[Buildah and Registries Tutorial](https://github.com/projectatomic/buildah/tree/master/docs/tutorials/02-registries-repositories.md)**
Learn how Buildah can be used to move OCI compliant images in and out of private or public registries.

198
image.go
View File

@@ -12,7 +12,6 @@ import (
"github.com/containers/image/docker/reference"
"github.com/containers/image/image"
"github.com/containers/image/manifest"
is "github.com/containers/image/storage"
"github.com/containers/image/types"
"github.com/containers/storage"
@@ -43,7 +42,6 @@ type containerImageRef struct {
name reference.Named
names []string
layerID string
addHistory bool
oconfig []byte
dconfig []byte
created time.Time
@@ -59,7 +57,6 @@ type containerImageSource struct {
store storage.Store
layerID string
names []string
addHistory bool
compression archive.Compression
config []byte
configDigest digest.Digest
@@ -68,12 +65,32 @@ type containerImageSource struct {
exporting bool
}
func (i *containerImageRef) NewImage(sc *types.SystemContext) (types.Image, error) {
func (i *containerImageRef) NewImage(sc *types.SystemContext) (types.ImageCloser, error) {
src, err := i.NewImageSource(sc)
if err != nil {
return nil, err
}
return image.FromSource(src)
return image.FromSource(sc, src)
}
func expectedOCIDiffIDs(image v1.Image) int {
expected := 0
for _, history := range image.History {
if !history.EmptyLayer {
expected = expected + 1
}
}
return expected
}
func expectedDockerDiffIDs(image docker.V2Image) int {
expected := 0
for _, history := range image.History {
if !history.EmptyLayer {
expected = expected + 1
}
}
return expected
}
func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.ImageSource, err error) {
@@ -128,11 +145,14 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
if err != nil {
return nil, err
}
created := i.created
oimage.Created = &created
dimage := docker.V2Image{}
err = json.Unmarshal(i.dconfig, &dimage)
if err != nil {
return nil, err
}
dimage.Created = created
// Start building manifests.
omanifest := v1.Manifest{
@@ -164,9 +184,39 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
// Extract each layer and compute its digests, both compressed (if requested) and uncompressed.
for _, layerID := range layers {
// The default layer media type assumes no compression.
omediaType := v1.MediaTypeImageLayer
dmediaType := docker.V2S2MediaTypeUncompressedLayer
// Figure out which media type we want to call this. Assume no compression.
// If we're not re-exporting the data, reuse the blobsum and diff IDs.
if !i.exporting && layerID != i.layerID {
layer, err2 := i.store.Layer(layerID)
if err2 != nil {
return nil, errors.Wrapf(err, "unable to locate layer %q", layerID)
}
if layer.UncompressedDigest == "" {
return nil, errors.Errorf("unable to look up size of layer %q", layerID)
}
layerBlobSum := layer.UncompressedDigest
layerBlobSize := layer.UncompressedSize
// Note this layer in the manifest, using the uncompressed blobsum.
olayerDescriptor := v1.Descriptor{
MediaType: omediaType,
Digest: layerBlobSum,
Size: layerBlobSize,
}
omanifest.Layers = append(omanifest.Layers, olayerDescriptor)
dlayerDescriptor := docker.V2S2Descriptor{
MediaType: dmediaType,
Digest: layerBlobSum,
Size: layerBlobSize,
}
dmanifest.Layers = append(dmanifest.Layers, dlayerDescriptor)
// Note this layer in the list of diffIDs, again using the uncompressed blobsum.
oimage.RootFS.DiffIDs = append(oimage.RootFS.DiffIDs, layerBlobSum)
dimage.RootFS.DiffIDs = append(dimage.RootFS.DiffIDs, layerBlobSum)
continue
}
// Figure out if we need to change the media type, in case we're using compression.
if i.compression != archive.Uncompressed {
switch i.compression {
case archive.Gzip:
@@ -177,50 +227,26 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
// Until the image specs define a media type for bzip2-compressed layers, even if we know
// how to decompress them, we can't try to compress layers with bzip2.
return nil, errors.New("media type for bzip2-compressed layers is not defined")
case archive.Xz:
// Until the image specs define a media type for xz-compressed layers, even if we know
// how to decompress them, we can't try to compress layers with xz.
return nil, errors.New("media type for xz-compressed layers is not defined")
default:
logrus.Debugf("compressing layer %q with unknown compressor(?)", layerID)
}
}
// If we're not re-exporting the data, just fake up layer and diff IDs for the manifest.
if !i.exporting {
fakeLayerDigest := digest.NewDigestFromHex(digest.Canonical.String(), layerID)
// Add a note in the manifest about the layer. The blobs should be identified by their
// possibly-compressed blob digests, but just use the layer IDs here.
olayerDescriptor := v1.Descriptor{
MediaType: omediaType,
Digest: fakeLayerDigest,
Size: -1,
}
omanifest.Layers = append(omanifest.Layers, olayerDescriptor)
dlayerDescriptor := docker.V2S2Descriptor{
MediaType: dmediaType,
Digest: fakeLayerDigest,
Size: -1,
}
dmanifest.Layers = append(dmanifest.Layers, dlayerDescriptor)
// Add a note about the diffID, which should be uncompressed digest of the blob, but
// just use the layer ID here.
oimage.RootFS.DiffIDs = append(oimage.RootFS.DiffIDs, fakeLayerDigest)
dimage.RootFS.DiffIDs = append(dimage.RootFS.DiffIDs, fakeLayerDigest)
continue
}
// Start reading the layer.
rc, err := i.store.Diff("", layerID, nil)
noCompression := archive.Uncompressed
diffOptions := &storage.DiffOptions{
Compression: &noCompression,
}
rc, err := i.store.Diff("", layerID, diffOptions)
if err != nil {
return nil, errors.Wrapf(err, "error extracting layer %q", layerID)
}
defer rc.Close()
// Set up to decompress the layer, in case it's coming out compressed. Due to implementation
// differences, the result may not match the digest the blob had when it was originally imported,
// so we have to recompute all of this anyway if we want to be sure the digests we use will be
// correct.
uncompressed, err := archive.DecompressStream(rc)
if err != nil {
return nil, errors.Wrapf(err, "error decompressing layer %q", layerID)
}
defer uncompressed.Close()
srcHasher := digest.Canonical.Digester()
reader := io.TeeReader(uncompressed, srcHasher.Hash())
reader := io.TeeReader(rc, srcHasher.Hash())
// Set up to write the possibly-recompressed blob.
layerFile, err := os.OpenFile(filepath.Join(path, "layer"), os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
@@ -229,7 +255,7 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
destHasher := digest.Canonical.Digester()
counter := ioutils.NewWriteCounter(layerFile)
multiWriter := io.MultiWriter(counter, destHasher.Hash())
// Compress the layer, if we're compressing it.
// Compress the layer, if we're recompressing it.
writer, err := archive.CompressStream(multiWriter, i.compression)
if err != nil {
return nil, errors.Wrapf(err, "error compressing layer %q", layerID)
@@ -267,27 +293,36 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
Size: size,
}
dmanifest.Layers = append(dmanifest.Layers, dlayerDescriptor)
// Add a note about the diffID, which is always an uncompressed value.
// Add a note about the diffID, which is always the layer's uncompressed digest.
oimage.RootFS.DiffIDs = append(oimage.RootFS.DiffIDs, srcHasher.Digest())
dimage.RootFS.DiffIDs = append(dimage.RootFS.DiffIDs, srcHasher.Digest())
}
if i.addHistory {
// Build history notes in the image configurations.
onews := v1.History{
Created: &i.created,
CreatedBy: i.createdBy,
Author: oimage.Author,
EmptyLayer: false,
}
oimage.History = append(oimage.History, onews)
dnews := docker.V2S2History{
Created: i.created,
CreatedBy: i.createdBy,
Author: dimage.Author,
EmptyLayer: false,
}
dimage.History = append(dimage.History, dnews)
// Build history notes in the image configurations.
onews := v1.History{
Created: &i.created,
CreatedBy: i.createdBy,
Author: oimage.Author,
EmptyLayer: false,
}
oimage.History = append(oimage.History, onews)
dnews := docker.V2S2History{
Created: i.created,
CreatedBy: i.createdBy,
Author: dimage.Author,
EmptyLayer: false,
}
dimage.History = append(dimage.History, dnews)
// Sanity check that we didn't just create a mismatch between non-empty layers in the
// history and the number of diffIDs.
expectedDiffIDs := expectedOCIDiffIDs(oimage)
if len(oimage.RootFS.DiffIDs) != expectedDiffIDs {
return nil, errors.Errorf("internal error: history lists %d non-empty layers, but we have %d layers on disk", expectedDiffIDs, len(oimage.RootFS.DiffIDs))
}
expectedDiffIDs = expectedDockerDiffIDs(dimage)
if len(dimage.RootFS.DiffIDs) != expectedDiffIDs {
return nil, errors.Errorf("internal error: history lists %d non-empty layers, but we have %d layers on disk", expectedDiffIDs, len(dimage.RootFS.DiffIDs))
}
// Encode the image configuration blob.
@@ -347,7 +382,6 @@ func (i *containerImageRef) NewImageSource(sc *types.SystemContext) (src types.I
store: i.store,
layerID: i.layerID,
names: i.names,
addHistory: i.addHistory,
compression: i.compression,
config: config,
configDigest: digest.Canonical.FromBytes(config),
@@ -402,16 +436,22 @@ func (i *containerImageSource) Reference() types.ImageReference {
return i.ref
}
func (i *containerImageSource) GetSignatures(ctx context.Context) ([][]byte, error) {
func (i *containerImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) {
if instanceDigest != nil && *instanceDigest != digest.FromBytes(i.manifest) {
return nil, errors.Errorf("TODO")
}
return nil, nil
}
func (i *containerImageSource) GetTargetManifest(digest digest.Digest) ([]byte, string, error) {
return []byte{}, "", errors.Errorf("TODO")
func (i *containerImageSource) GetManifest(instanceDigest *digest.Digest) ([]byte, string, error) {
if instanceDigest != nil && *instanceDigest != digest.FromBytes(i.manifest) {
return nil, "", errors.Errorf("TODO")
}
return i.manifest, i.manifestType, nil
}
func (i *containerImageSource) GetManifest() ([]byte, string, error) {
return i.manifest, i.manifestType, nil
func (i *containerImageSource) LayerInfosForCopy() ([]types.BlobInfo, error) {
return nil, nil
}
func (i *containerImageSource) GetBlob(blob types.BlobInfo) (reader io.ReadCloser, size int64, err error) {
@@ -445,10 +485,14 @@ func (i *containerImageSource) GetBlob(blob types.BlobInfo) (reader io.ReadClose
return ioutils.NewReadCloserWrapper(layerFile, closer), size, nil
}
func (b *Builder) makeImageRef(manifestType string, exporting, addHistory bool, compress archive.Compression, names []string, layerID string, historyTimestamp *time.Time) (types.ImageReference, error) {
func (b *Builder) makeImageRef(manifestType string, exporting bool, compress archive.Compression, historyTimestamp *time.Time) (types.ImageReference, error) {
var name reference.Named
if len(names) > 0 {
if parsed, err := reference.ParseNamed(names[0]); err == nil {
container, err := b.store.Container(b.ContainerID)
if err != nil {
return nil, errors.Wrapf(err, "error locating container %q", b.ContainerID)
}
if len(container.Names) > 0 {
if parsed, err2 := reference.ParseNamed(container.Names[0]); err2 == nil {
name = parsed
}
}
@@ -471,9 +515,8 @@ func (b *Builder) makeImageRef(manifestType string, exporting, addHistory bool,
store: b.store,
compression: compress,
name: name,
names: names,
layerID: layerID,
addHistory: addHistory,
names: container.Names,
layerID: container.LayerID,
oconfig: oconfig,
dconfig: dconfig,
created: created,
@@ -484,18 +527,3 @@ func (b *Builder) makeImageRef(manifestType string, exporting, addHistory bool,
}
return ref, nil
}
func (b *Builder) makeContainerImageRef(manifestType string, exporting bool, compress archive.Compression, historyTimestamp *time.Time) (types.ImageReference, error) {
if manifestType == "" {
manifestType = OCIv1ImageManifest
}
container, err := b.store.Container(b.ContainerID)
if err != nil {
return nil, errors.Wrapf(err, "error locating container %q", b.ContainerID)
}
return b.makeImageRef(manifestType, exporting, true, compress, container.Names, container.LayerID, historyTimestamp)
}
func (b *Builder) makeImageImageRef(compress archive.Compression, names []string, layerID string, historyTimestamp *time.Time) (types.ImageReference, error) {
return b.makeImageRef(manifest.GuessMIMEType(b.Manifest), true, false, compress, names, layerID, historyTimestamp)
}

View File

@@ -95,8 +95,6 @@ type BuildOptions struct {
// specified, indicating that the shared, system-wide default policy
// should be used.
SignaturePolicyPath string
// SkipTLSVerify denotes whether TLS verification should not be used.
SkipTLSVerify bool
// ReportWriter is an io.Writer which will be used to report the
// progress of the (possible) pulling of the source image and the
// writing of the new image.
@@ -105,7 +103,11 @@ type BuildOptions struct {
// configuration data.
// Accepted values are OCIv1ImageFormat and Dockerv2ImageFormat.
OutputFormat string
AuthFilePath string
// SystemContext holds parameters used for authentication.
SystemContext *types.SystemContext
CommonBuildOpts *buildah.CommonBuildOptions
// DefaultMountsFilePath is the file path holding the mounts to be mounted in "host-path:container-path" format
DefaultMountsFilePath string
}
// Executor is a buildah-based implementation of the imagebuilder.Executor
@@ -137,18 +139,8 @@ type Executor struct {
volumeCache map[string]string
volumeCacheInfo map[string]os.FileInfo
reportWriter io.Writer
}
func makeSystemContext(signaturePolicyPath, authFilePath string, skipTLSVerify bool) *types.SystemContext {
sc := &types.SystemContext{}
if signaturePolicyPath != "" {
sc.SignaturePolicyPath = signaturePolicyPath
}
if authFilePath != "" {
sc.AuthFilePath = authFilePath
}
sc.DockerInsecureSkipTLSVerify = skipTLSVerify
return sc
commonBuildOptions *buildah.CommonBuildOptions
defaultMountsFilePath string
}
// Preserve informs the executor that from this point on, it needs to ensure
@@ -341,7 +333,7 @@ func (b *Executor) Copy(excludes []string, copies ...imagebuilder.Copy) error {
sources = append(sources, filepath.Join(b.contextDir, src))
}
}
if err := b.builder.Add(copy.Dest, copy.Download, sources...); err != nil {
if err := b.builder.Add(copy.Dest, copy.Download, buildah.AddAndCopyOptions{}, sources...); err != nil {
return err
}
}
@@ -380,6 +372,7 @@ func (b *Executor) Run(run imagebuilder.Run, config docker.Config) error {
Entrypoint: config.Entrypoint,
Cmd: config.Cmd,
NetworkDisabled: config.NetworkDisabled,
Quiet: b.quiet,
}
args := run.Args
@@ -401,12 +394,23 @@ func (b *Executor) Run(run imagebuilder.Run, config docker.Config) error {
// UnrecognizedInstruction is called when we encounter an instruction that the
// imagebuilder parser didn't understand.
func (b *Executor) UnrecognizedInstruction(step *imagebuilder.Step) error {
if !b.ignoreUnrecognizedInstructions {
logrus.Debugf("+(UNIMPLEMENTED?) %#v", step)
err_str := fmt.Sprintf("Build error: Unknown instruction: %q ", step.Command)
err := fmt.Sprintf(err_str+"%#v", step)
if b.ignoreUnrecognizedInstructions {
logrus.Debugf(err)
return nil
}
logrus.Errorf("+(UNIMPLEMENTED?) %#v", step)
return errors.Errorf("Unrecognized instruction: %#v", step)
switch logrus.GetLevel() {
case logrus.ErrorLevel:
logrus.Errorf(err_str)
case logrus.DebugLevel:
logrus.Debugf(err)
default:
logrus.Errorf("+(UNHANDLED LOGLEVEL) %#v", step)
}
return errors.Errorf(err)
}
// NewExecutor creates a new instance of the imagebuilder.Executor interface.
@@ -418,22 +422,24 @@ func NewExecutor(store storage.Store, options BuildOptions) (*Executor, error) {
registry: options.Registry,
transport: options.Transport,
ignoreUnrecognizedInstructions: options.IgnoreUnrecognizedInstructions,
quiet: options.Quiet,
runtime: options.Runtime,
runtimeArgs: options.RuntimeArgs,
transientMounts: options.TransientMounts,
compression: options.Compression,
output: options.Output,
outputFormat: options.OutputFormat,
additionalTags: options.AdditionalTags,
signaturePolicyPath: options.SignaturePolicyPath,
systemContext: makeSystemContext(options.SignaturePolicyPath, options.AuthFilePath, options.SkipTLSVerify),
volumeCache: make(map[string]string),
volumeCacheInfo: make(map[string]os.FileInfo),
log: options.Log,
out: options.Out,
err: options.Err,
reportWriter: options.ReportWriter,
quiet: options.Quiet,
runtime: options.Runtime,
runtimeArgs: options.RuntimeArgs,
transientMounts: options.TransientMounts,
compression: options.Compression,
output: options.Output,
outputFormat: options.OutputFormat,
additionalTags: options.AdditionalTags,
signaturePolicyPath: options.SignaturePolicyPath,
systemContext: options.SystemContext,
volumeCache: make(map[string]string),
volumeCacheInfo: make(map[string]os.FileInfo),
log: options.Log,
out: options.Out,
err: options.Err,
reportWriter: options.ReportWriter,
commonBuildOptions: options.CommonBuildOpts,
defaultMountsFilePath: options.DefaultMountsFilePath,
}
if exec.err == nil {
exec.err = os.Stderr
@@ -469,12 +475,15 @@ func (b *Executor) Prepare(ib *imagebuilder.Builder, node *parser.Node, from str
b.log("FROM %s", from)
}
builderOptions := buildah.BuilderOptions{
FromImage: from,
PullPolicy: b.pullPolicy,
Registry: b.registry,
Transport: b.transport,
SignaturePolicyPath: b.signaturePolicyPath,
ReportWriter: b.reportWriter,
FromImage: from,
PullPolicy: b.pullPolicy,
Registry: b.registry,
Transport: b.transport,
SignaturePolicyPath: b.signaturePolicyPath,
ReportWriter: b.reportWriter,
SystemContext: b.systemContext,
CommonBuildOpts: b.commonBuildOptions,
DefaultMountsFilePath: b.defaultMountsFilePath,
}
builder, err := buildah.NewBuilder(b.store, builderOptions)
if err != nil {
@@ -578,6 +587,8 @@ func (b *Executor) Commit(ib *imagebuilder.Builder) (err error) {
if err2 == nil {
imageRef = imageRef2
err = nil
} else {
err = err2
}
}
} else {
@@ -586,6 +597,9 @@ func (b *Executor) Commit(ib *imagebuilder.Builder) (err error) {
if err != nil {
return errors.Wrapf(err, "error parsing reference for image to be written")
}
if ib.Author != "" {
b.builder.SetMaintainer(ib.Author)
}
config := ib.Config()
b.builder.SetHostname(config.Hostname)
b.builder.SetDomainname(config.Domainname)

View File

@@ -16,9 +16,9 @@ func importBuilderDataFromImage(store storage.Store, systemContext *types.System
imageName := ""
if imageID != "" {
ref, err := is.Transport.ParseStoreReference(store, "@"+imageID)
ref, err := is.Transport.ParseStoreReference(store, imageID)
if err != nil {
return nil, errors.Wrapf(err, "no such image %q", "@"+imageID)
return nil, errors.Wrapf(err, "no such image %q", imageID)
}
src, err2 := ref.NewImage(systemContext)
if err2 != nil {
@@ -68,7 +68,7 @@ func importBuilder(store storage.Store, options ImportOptions) (*Builder, error)
return nil, err
}
systemContext := getSystemContext(options.SignaturePolicyPath)
systemContext := getSystemContext(&types.SystemContext{}, options.SignaturePolicyPath)
builder, err := importBuilderDataFromImage(store, systemContext, c.ImageID, options.Container, c.ID)
if err != nil {
@@ -95,21 +95,27 @@ func importBuilder(store storage.Store, options ImportOptions) (*Builder, error)
}
func importBuilderFromImage(store storage.Store, options ImportFromImageOptions) (*Builder, error) {
var img *storage.Image
var err error
if options.Image == "" {
return nil, errors.Errorf("image name must be specified")
}
img, err := util.FindImage(store, options.Image)
if err != nil {
return nil, errors.Wrapf(err, "error locating image %q for importing settings", options.Image)
systemContext := getSystemContext(options.SystemContext, options.SignaturePolicyPath)
for _, image := range util.ResolveName(options.Image, "", systemContext, store) {
img, err = util.FindImage(store, image)
if err != nil {
continue
}
builder, err2 := importBuilderDataFromImage(store, systemContext, img.ID, "", "")
if err2 != nil {
return nil, errors.Wrapf(err2, "error importing build settings from image %q", options.Image)
}
return builder, nil
}
systemContext := getSystemContext(options.SignaturePolicyPath)
builder, err := importBuilderDataFromImage(store, systemContext, img.ID, "", "")
if err != nil {
return nil, errors.Wrapf(err, "error importing build settings from image %q", options.Image)
}
return builder, nil
return nil, errors.Wrapf(err, "error locating image %q for importing settings", options.Image)
}

167
install.md Normal file
View File

@@ -0,0 +1,167 @@
# Installation Instructions
## System Requirements
### Kernel Version Requirements
To run Buildah on Red Hat Enterprise Linux or CentOS, version 7.4 or higher is required.
On other Linux distributions Buildah requires a kernel version of 4.0 or
higher in order to support the OverlayFS filesystem. The kernel version can be checked
with the 'uname -a' command.
### runc Requirement
Buildah uses `runc` to run commands when `buildah run` is used, or when `buildah build-using-dockerfile`
encounters a `RUN` instruction, so you'll also need to build and install a compatible version of
[runc](https://github.com/opencontainers/runc) for Buildah to call for those cases. If Buildah is installed
via a package manager such as yum, dnf or apt-get, runc will be installed as part of that process.
## Package Installation
Buildah is available on several software repositories and can be installed via a package manager such
as yum, dnf or apt-get on a number of Linux distributions.
## Installation from GitHub
Prior to installing Buildah, install the following packages on your Linux distro:
* make
* golang (Requires version 1.8.1 or higher.)
* bats
* btrfs-progs-devel
* bzip2
* device-mapper-devel
* git
* go-md2man
* gpgme-devel
* glib2-devel
* libassuan-devel
* libseccomp-devel
* ostree-devel
* runc (Requires version 1.0 RC4 or higher.)
* skopeo-containers
### Fedora
In Fedora, you can use this command:
```
dnf -y install \
make \
golang \
bats \
btrfs-progs-devel \
device-mapper-devel \
glib2-devel \
gpgme-devel \
libassuan-devel \
libseccomp-devel \
ostree-devel \
git \
bzip2 \
go-md2man \
runc \
skopeo-containers
```
Then to install Buildah on Fedora follow the steps in this example:
```
mkdir ~/buildah
cd ~/buildah
export GOPATH=`pwd`
git clone https://github.com/projectatomic/buildah ./src/github.com/projectatomic/buildah
cd ./src/github.com/projectatomic/buildah
make
sudo make install
buildah --help
```
### RHEL, CentOS
In RHEL and CentOS 7, ensure that you are subscribed to `rhel-7-server-rpms`,
`rhel-7-server-extras-rpms`, and `rhel-7-server-optional-rpms`, then
run this command:
```
yum -y install \
make \
golang \
bats \
btrfs-progs-devel \
device-mapper-devel \
glib2-devel \
gpgme-devel \
libassuan-devel \
libseccomp-devel \
ostree-devel \
git \
bzip2 \
go-md2man \
runc \
skopeo-containers
```
The build steps for Buildah on RHEL or CentOS are the same as Fedora, above.
### openSUSE
Currently openSUSE Leap 15 offers `go1.8` , while openSUSE Tumbleweed has `go1.9`.
`zypper in go1.X` should do the work, then run this command:
```
zypper in make \
git \
golang \
runc \
bzip2 \
libgpgme-devel \
libseccomp-devel \
device-mapper-devel \
libbtrfs-devel \
go-md2man
```
The build steps for Buildah on SUSE / openSUSE are the same as Fedora, above.
### Ubuntu
In Ubuntu zesty and xenial, you can use these commands:
```
apt-get -y install software-properties-common
add-apt-repository -y ppa:alexlarsson/flatpak
add-apt-repository -y ppa:gophers/archive
apt-add-repository -y ppa:projectatomic/ppa
apt-get -y -qq update
apt-get -y install bats btrfs-tools git libapparmor-dev libdevmapper-dev libglib2.0-dev libgpgme11-dev libostree-dev libseccomp-dev libselinux1-dev skopeo-containers go-md2man
apt-get -y install golang-1.8
```
Then to install Buildah on Ubuntu follow the steps in this example:
```
mkdir ~/buildah
cd ~/buildah
export GOPATH=`pwd`
git clone https://github.com/projectatomic/buildah ./src/github.com/projectatomic/buildah
cd ./src/github.com/projectatomic/buildah
PATH=/usr/lib/go-1.8/bin:$PATH make runc all TAGS="apparmor seccomp"
sudo make install install.runc
buildah --help
```
### Debian
To install the required dependencies, you can use those commands, tested under Debian GNU/Linux amd64 9.3 (stretch):
```
gpg --recv-keys 0x018BA5AD9DF57A4448F0E6CF8BECF1637AD8C79D
gpg --export 0x018BA5AD9DF57A4448F0E6CF8BECF1637AD8C79D >> /usr/share/keyrings/projectatomic-ppa.gpg
echo 'deb [signed-by=/usr/share/keyrings/projectatomic-ppa.gpg] http://ppa.launchpad.net/projectatomic/ppa/ubuntu zesty main' > /etc/apt/sources.list.d/projectatomic-ppa.list
apt update
apt -y install -t stretch-backports libostree-dev golang
apt -y install bats btrfs-tools git libapparmor-dev libdevmapper-dev libglib2.0-dev libgpgme11-dev libseccomp-dev libselinux1-dev skopeo-containers go-md2man
```
The build steps on Debian are otherwise the same as Ubuntu, above.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 88 KiB

216
new.go
View File

@@ -14,6 +14,7 @@ import (
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/openshift/imagebuilder"
"github.com/pkg/errors"
"github.com/projectatomic/buildah/util"
"github.com/sirupsen/logrus"
)
@@ -26,6 +27,10 @@ const (
// can't find one in the local Store, in order to generate a source
// reference for the image that we can then copy to the local Store.
DefaultTransport = "docker://"
// minimumTruncatedIDLength is the minimum length of an identifier that
// we'll accept as possibly being a truncated image ID.
minimumTruncatedIDLength = 3
)
func reserveSELinuxLabels(store storage.Store, id string) error {
@@ -58,91 +63,173 @@ func reserveSELinuxLabels(store storage.Store, id string) error {
return nil
}
func pullAndFindImage(store storage.Store, imageName string, options BuilderOptions, sc *types.SystemContext) (*storage.Image, types.ImageReference, error) {
ref, err := pullImage(store, imageName, options, sc)
if err != nil {
logrus.Debugf("error pulling image %q: %v", imageName, err)
return nil, nil, err
}
img, err := is.Transport.GetStoreImage(store, ref)
if err != nil {
logrus.Debugf("error reading pulled image %q: %v", imageName, err)
return nil, nil, err
}
return img, ref, nil
}
func getImageName(name string, img *storage.Image) string {
imageName := name
if len(img.Names) > 0 {
imageName = img.Names[0]
// When the image used by the container is a tagged image
// the container name might be set to the original image instead of
// the image given in the "form" command line.
// This loop is supposed to fix this.
for _, n := range img.Names {
if strings.Contains(n, name) {
imageName = n
break
}
}
}
return imageName
}
func imageNamePrefix(imageName string) string {
prefix := imageName
s := strings.Split(imageName, "/")
if len(s) > 0 {
prefix = s[len(s)-1]
}
s = strings.Split(prefix, ":")
if len(s) > 0 {
prefix = s[0]
}
s = strings.Split(prefix, "@")
if len(s) > 0 {
prefix = s[0]
}
return prefix
}
func imageManifestAndConfig(ref types.ImageReference, systemContext *types.SystemContext) (manifest, config []byte, err error) {
if ref != nil {
src, err := ref.NewImage(systemContext)
if err != nil {
return nil, nil, errors.Wrapf(err, "error instantiating image for %q", transports.ImageName(ref))
}
defer src.Close()
config, err := src.ConfigBlob()
if err != nil {
return nil, nil, errors.Wrapf(err, "error reading image configuration for %q", transports.ImageName(ref))
}
manifest, _, err := src.Manifest()
if err != nil {
return nil, nil, errors.Wrapf(err, "error reading image manifest for %q", transports.ImageName(ref))
}
return manifest, config, nil
}
return nil, nil, nil
}
func newBuilder(store storage.Store, options BuilderOptions) (*Builder, error) {
var ref types.ImageReference
var img *storage.Image
manifest := []byte{}
config := []byte{}
var err error
var manifest []byte
var config []byte
if options.FromImage == BaseImageFakeName {
options.FromImage = ""
}
image := options.FromImage
if options.Transport == "" {
options.Transport = DefaultTransport
}
systemContext := getSystemContext(options.SignaturePolicyPath)
systemContext := getSystemContext(options.SystemContext, options.SignaturePolicyPath)
for _, image := range util.ResolveName(options.FromImage, options.Registry, systemContext, store) {
if len(image) >= minimumTruncatedIDLength {
if img, err = store.Image(image); err == nil && img != nil && strings.HasPrefix(img.ID, image) {
if ref, err = is.Transport.ParseStoreReference(store, img.ID); err != nil {
return nil, errors.Wrapf(err, "error parsing reference to image %q", img.ID)
}
break
}
}
imageID := ""
if image != "" {
var err error
if options.PullPolicy == PullAlways {
pulledReference, err2 := pullImage(store, options, systemContext)
pulledImg, pulledReference, err2 := pullAndFindImage(store, image, options, systemContext)
if err2 != nil {
return nil, errors.Wrapf(err2, "error pulling image %q", image)
logrus.Debugf("error pulling and reading image %q: %v", image, err2)
err = err2
continue
}
ref = pulledReference
img = pulledImg
break
}
if ref == nil {
srcRef, err2 := alltransports.ParseImageName(image)
if err2 != nil {
srcRef2, err3 := alltransports.ParseImageName(options.Registry + image)
if err3 != nil {
srcRef3, err4 := alltransports.ParseImageName(options.Transport + options.Registry + image)
if err4 != nil {
return nil, errors.Wrapf(err4, "error parsing image name %q", options.Transport+options.Registry+image)
}
srcRef2 = srcRef3
}
srcRef = srcRef2
}
destImage, err2 := localImageNameForReference(store, srcRef)
if err2 != nil {
return nil, errors.Wrapf(err2, "error computing local image name for %q", transports.ImageName(srcRef))
srcRef, err2 := alltransports.ParseImageName(image)
if err2 != nil {
if options.Transport == "" {
logrus.Debugf("error parsing image name %q: %v", image, err2)
err = err2
continue
}
if destImage == "" {
return nil, errors.Errorf("error computing local image name for %q", transports.ImageName(srcRef))
srcRef2, err3 := alltransports.ParseImageName(options.Transport + image)
if err3 != nil {
logrus.Debugf("error parsing image name %q: %v", image, err2)
err = err3
continue
}
srcRef = srcRef2
}
ref, err = is.Transport.ParseStoreReference(store, destImage)
if err != nil {
return nil, errors.Wrapf(err, "error parsing reference to image %q", destImage)
}
destImage, err2 := localImageNameForReference(store, srcRef)
if err2 != nil {
return nil, errors.Wrapf(err2, "error computing local image name for %q", transports.ImageName(srcRef))
}
if destImage == "" {
return nil, errors.Errorf("error computing local image name for %q", transports.ImageName(srcRef))
}
image = destImage
ref, err = is.Transport.ParseStoreReference(store, destImage)
if err != nil {
return nil, errors.Wrapf(err, "error parsing reference to image %q", destImage)
}
img, err = is.Transport.GetStoreImage(store, ref)
if err != nil {
if errors.Cause(err) == storage.ErrImageUnknown && options.PullPolicy != PullIfMissing {
return nil, errors.Wrapf(err, "no such image %q", transports.ImageName(ref))
logrus.Debugf("no such image %q: %v", transports.ImageName(ref), err)
continue
}
ref2, err2 := pullImage(store, options, systemContext)
pulledImg, pulledReference, err2 := pullAndFindImage(store, image, options, systemContext)
if err2 != nil {
return nil, errors.Wrapf(err2, "error pulling image %q", image)
logrus.Debugf("error pulling and reading image %q: %v", image, err2)
err = err2
continue
}
ref = ref2
img, err = is.Transport.GetStoreImage(store, ref)
}
if err != nil {
return nil, errors.Wrapf(err, "no such image %q", transports.ImageName(ref))
ref = pulledReference
img = pulledImg
}
break
}
if options.FromImage != "" && (ref == nil || img == nil) {
// If options.FromImage is set but we ended up
// with nil in ref or in img then there was an error that
// we should return.
return nil, util.GetFailureCause(err, errors.Wrapf(storage.ErrImageUnknown, "no such image %q in registry", options.FromImage))
}
image := options.FromImage
imageID := ""
if img != nil {
image = getImageName(imageNamePrefix(image), img)
imageID = img.ID
src, err := ref.NewImage(systemContext)
if err != nil {
return nil, errors.Wrapf(err, "error instantiating image for %q", transports.ImageName(ref))
}
defer src.Close()
config, err = src.ConfigBlob()
if err != nil {
return nil, errors.Wrapf(err, "error reading image configuration for %q", transports.ImageName(ref))
}
manifest, _, err = src.Manifest()
if err != nil {
return nil, errors.Wrapf(err, "error reading image manifest for %q", transports.ImageName(ref))
}
}
if manifest, config, err = imageManifestAndConfig(ref, systemContext); err != nil {
return nil, errors.Wrapf(err, "error reading data from image %q", transports.ImageName(ref))
}
name := "working-container"
@@ -151,20 +238,7 @@ func newBuilder(store storage.Store, options BuilderOptions) (*Builder, error) {
} else {
var err2 error
if image != "" {
prefix := image
s := strings.Split(prefix, "/")
if len(s) > 0 {
prefix = s[len(s)-1]
}
s = strings.Split(prefix, ":")
if len(s) > 0 {
prefix = s[0]
}
s = strings.Split(prefix, "@")
if len(s) > 0 {
prefix = s[0]
}
name = prefix + "-" + name
name = imageNamePrefix(image) + "-" + name
}
suffix := 1
tmpName := name
@@ -177,6 +251,7 @@ func newBuilder(store storage.Store, options BuilderOptions) (*Builder, error) {
}
name = tmpName
}
coptions := storage.ContainerOptions{}
container, err := store.CreateContainer("", []string{name}, imageID, "", "", &coptions)
if err != nil {
@@ -191,10 +266,10 @@ func newBuilder(store storage.Store, options BuilderOptions) (*Builder, error) {
}
}()
if err := reserveSELinuxLabels(store, container.ID); err != nil {
if err = reserveSELinuxLabels(store, container.ID); err != nil {
return nil, err
}
processLabel, mountLabel, err := label.InitLabels(nil)
processLabel, mountLabel, err := label.InitLabels(options.CommonBuildOpts.LabelOpts)
if err != nil {
return nil, err
}
@@ -213,6 +288,7 @@ func newBuilder(store storage.Store, options BuilderOptions) (*Builder, error) {
ProcessLabel: processLabel,
MountLabel: mountLabel,
DefaultMountsFilePath: options.DefaultMountsFilePath,
CommonBuildOpts: options.CommonBuildOpts,
}
if options.Mount {

28
new_test.go Normal file
View File

@@ -0,0 +1,28 @@
package buildah
import (
"testing"
"github.com/containers/storage"
)
func TestGetImageName(t *testing.T) {
tt := []struct {
caseName string
name string
names []string
expected string
}{
{"tagged image", "busybox1", []string{"docker.io/library/busybox:latest", "docker.io/library/busybox1:latest"}, "docker.io/library/busybox1:latest"},
{"image name not in the resolved image names", "image1", []string{"docker.io/library/busybox:latest", "docker.io/library/busybox1:latest"}, "docker.io/library/busybox:latest"},
{"resolved image with empty name list", "image1", []string{}, "image1"},
}
for _, tc := range tt {
img := &storage.Image{Names: tc.names}
res := getImageName(tc.name, img)
if res != tc.expected {
t.Errorf("test case '%s' failed: expected %#v but got %#v", tc.caseName, tc.expected, res)
}
}
}

41
pull.go
View File

@@ -53,27 +53,17 @@ func localImageNameForReference(store storage.Store, srcRef types.ImageReference
return name, nil
}
func pullImage(store storage.Store, options BuilderOptions, sc *types.SystemContext) (types.ImageReference, error) {
name := options.FromImage
spec := name
if options.Registry != "" {
spec = options.Registry + spec
}
spec2 := spec
if options.Transport != "" {
spec2 = options.Transport + spec
}
srcRef, err := alltransports.ParseImageName(name)
func pullImage(store storage.Store, imageName string, options BuilderOptions, sc *types.SystemContext) (types.ImageReference, error) {
spec := imageName
srcRef, err := alltransports.ParseImageName(spec)
if err != nil {
if options.Transport == "" {
return nil, errors.Wrapf(err, "error parsing image name %q", spec)
}
spec = options.Transport + spec
srcRef2, err2 := alltransports.ParseImageName(spec)
if err2 != nil {
srcRef3, err3 := alltransports.ParseImageName(spec2)
if err3 != nil {
return nil, errors.Wrapf(err3, "error parsing image name %q", spec2)
}
srcRef2 = srcRef3
return nil, errors.Wrapf(err2, "error parsing image name %q", spec)
}
srcRef = srcRef2
}
@@ -91,6 +81,12 @@ func pullImage(store storage.Store, options BuilderOptions, sc *types.SystemCont
return nil, errors.Wrapf(err, "error parsing image name %q", destName)
}
img, err := srcRef.NewImageSource(sc)
if err != nil {
return nil, errors.Wrapf(err, "error initializing %q as an image source", spec)
}
img.Close()
policy, err := signature.DefaultPolicy(sc)
if err != nil {
return nil, errors.Wrapf(err, "error obtaining default signature policy")
@@ -103,12 +99,15 @@ func pullImage(store storage.Store, options BuilderOptions, sc *types.SystemCont
defer func() {
if err2 := policyContext.Destroy(); err2 != nil {
logrus.Debugf("error destroying signature polcy context: %v", err2)
logrus.Debugf("error destroying signature policy context: %v", err2)
}
}()
logrus.Debugf("copying %q to %q", spec, name)
logrus.Debugf("copying %q to %q", spec, destName)
err = cp.Image(policyContext, destRef, srcRef, getCopyOptions(options.ReportWriter, options.SystemContext, nil, ""))
return destRef, err
if err == nil {
return destRef, nil
}
return nil, err
}

197
run.go
View File

@@ -1,7 +1,9 @@
package buildah
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
@@ -9,9 +11,12 @@ import (
"strings"
"github.com/containers/storage/pkg/ioutils"
"github.com/docker/docker/profiles/seccomp"
units "github.com/docker/go-units"
digest "github.com/opencontainers/go-digest"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
@@ -64,9 +69,85 @@ type RunOptions struct {
// decision can be overridden by specifying either WithTerminal or
// WithoutTerminal.
Terminal int
// Quiet tells the run to turn off output to stdout.
Quiet bool
}
func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts []specs.Mount, bindFiles, volumes []string) error {
func addRlimits(ulimit []string, g *generate.Generator) error {
var (
ul *units.Ulimit
err error
)
for _, u := range ulimit {
if ul, err = units.ParseUlimit(u); err != nil {
return errors.Wrapf(err, "ulimit option %q requires name=SOFT:HARD, failed to be parsed", u)
}
g.AddProcessRlimits("RLIMIT_"+strings.ToUpper(ul.Name), uint64(ul.Hard), uint64(ul.Soft))
}
return nil
}
func addHostsToFile(hosts []string) error {
if len(hosts) == 0 {
return nil
}
file, err := os.OpenFile("/etc/hosts", os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, host := range hosts {
fmt.Fprintln(w, host)
}
return w.Flush()
}
func addCommonOptsToSpec(commonOpts *CommonBuildOptions, g *generate.Generator) error {
// RESOURCES - CPU
if commonOpts.CPUPeriod != 0 {
g.SetLinuxResourcesCPUPeriod(commonOpts.CPUPeriod)
}
if commonOpts.CPUQuota != 0 {
g.SetLinuxResourcesCPUQuota(commonOpts.CPUQuota)
}
if commonOpts.CPUShares != 0 {
g.SetLinuxResourcesCPUShares(commonOpts.CPUShares)
}
if commonOpts.CPUSetCPUs != "" {
g.SetLinuxResourcesCPUCpus(commonOpts.CPUSetCPUs)
}
if commonOpts.CPUSetMems != "" {
g.SetLinuxResourcesCPUMems(commonOpts.CPUSetMems)
}
// RESOURCES - MEMORY
if commonOpts.Memory != 0 {
g.SetLinuxResourcesMemoryLimit(commonOpts.Memory)
}
if commonOpts.MemorySwap != 0 {
g.SetLinuxResourcesMemorySwap(commonOpts.MemorySwap)
}
if commonOpts.CgroupParent != "" {
g.SetLinuxCgroupsPath(commonOpts.CgroupParent)
}
if err := addRlimits(commonOpts.Ulimit, g); err != nil {
return err
}
if err := addHostsToFile(commonOpts.AddHost); err != nil {
return err
}
logrus.Debugln("Resources:", commonOpts)
return nil
}
func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts []specs.Mount, bindFiles, builtinVolumes, volumeMounts []string, shmSize string) error {
// The passed-in mounts matter the most to us.
mounts := make([]specs.Mount, len(optionMounts))
copy(mounts, optionMounts)
@@ -81,6 +162,9 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts
}
// Add mounts from the generated list, unless they conflict.
for _, specMount := range spec.Mounts {
if specMount.Destination == "/dev/shm" {
specMount.Options = []string{"nosuid", "noexec", "nodev", "mode=1777", "size=" + shmSize}
}
if haveMount(specMount.Destination) {
// Already have something to mount there, so skip this one.
continue
@@ -112,6 +196,7 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts
secretMounts, err := secretMounts(file, b.MountLabel, cdir)
if err != nil {
logrus.Warn("error mounting secrets, skipping...")
continue
}
for _, mount := range secretMounts {
if haveMount(mount.Destination) {
@@ -122,7 +207,7 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts
}
// Add temporary copies of the contents of volume locations at the
// volume locations, unless we already have something there.
for _, volume := range volumes {
for _, volume := range builtinVolumes {
if haveMount(volume) {
// Already mounting something there, no need to bother.
continue
@@ -134,8 +219,11 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts
if err = os.MkdirAll(volumePath, 0755); err != nil {
return errors.Wrapf(err, "error creating directory %q for volume %q in container %q", volumePath, volume, b.ContainerID)
}
if err = label.Relabel(volumePath, b.MountLabel, false); err != nil {
return errors.Wrapf(err, "error relabeling directory %q for volume %q in container %q", volumePath, volume, b.ContainerID)
}
srcPath := filepath.Join(mountPoint, volume)
if err = copyFileWithTar(srcPath, volumePath); err != nil && !os.IsNotExist(err) {
if err = copyWithTar(srcPath, volumePath); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error populating directory %q for volume %q in container %q using contents of %q", volumePath, volume, b.ContainerID, srcPath)
}
@@ -148,6 +236,57 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, optionMounts
Options: []string{"bind"},
})
}
// Bind mount volumes given by the user at execution
var options []string
for _, i := range volumeMounts {
spliti := strings.Split(i, ":")
if len(spliti) > 2 {
options = strings.Split(spliti[2], ",")
}
if haveMount(spliti[1]) {
continue
}
options = append(options, "rbind")
var foundrw, foundro, foundz, foundZ bool
var rootProp string
for _, opt := range options {
switch opt {
case "rw":
foundrw = true
case "ro":
foundro = true
case "z":
foundz = true
case "Z":
foundZ = true
case "private", "rprivate", "slave", "rslave", "shared", "rshared":
rootProp = opt
}
}
if !foundrw && !foundro {
options = append(options, "rw")
}
if foundz {
if err := label.Relabel(spliti[0], spec.Linux.MountLabel, true); err != nil {
return errors.Wrapf(err, "relabel failed %q", spliti[0])
}
}
if foundZ {
if err := label.Relabel(spliti[0], spec.Linux.MountLabel, false); err != nil {
return errors.Wrapf(err, "relabel failed %q", spliti[0])
}
}
if rootProp == "" {
options = append(options, "private")
}
mounts = append(mounts, specs.Mount{
Destination: spliti[1],
Type: "bind",
Source: spliti[0],
Options: options,
})
}
// Set the list in the spec.
spec.Mounts = mounts
return nil
@@ -174,6 +313,15 @@ func (b *Builder) Run(command []string, options RunOptions) error {
g.AddProcessEnv(env[0], env[1])
}
}
if b.CommonBuildOpts == nil {
return errors.Errorf("Invalid format on container you must recreate the container")
}
if err := addCommonOptsToSpec(b.CommonBuildOpts, &g); err != nil {
return err
}
if len(command) > 0 {
g.SetProcessArgs(command)
} else {
@@ -244,11 +392,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
return errors.Wrapf(err, "error removing network namespace for run")
}
}
if options.User != "" {
user, err = getUser(mountPoint, options.User)
} else {
user, err = getUser(mountPoint, b.User())
}
user, err = b.user(mountPoint, options.User)
if err != nil {
return err
}
@@ -262,8 +406,40 @@ func (b *Builder) Run(command []string, options RunOptions) error {
return errors.Wrapf(err, "error ensuring working directory %q exists", spec.Process.Cwd)
}
//Security Opts
g.SetProcessApparmorProfile(b.CommonBuildOpts.ApparmorProfile)
// HANDLE SECCOMP
if b.CommonBuildOpts.SeccompProfilePath != "unconfined" {
if b.CommonBuildOpts.SeccompProfilePath != "" {
seccompProfile, err := ioutil.ReadFile(b.CommonBuildOpts.SeccompProfilePath)
if err != nil {
return errors.Wrapf(err, "opening seccomp profile (%s) failed", b.CommonBuildOpts.SeccompProfilePath)
}
seccompConfig, err := seccomp.LoadProfile(string(seccompProfile), spec)
if err != nil {
return errors.Wrapf(err, "loading seccomp profile (%s) failed", b.CommonBuildOpts.SeccompProfilePath)
}
spec.Linux.Seccomp = seccompConfig
} else {
seccompConfig, err := seccomp.GetDefaultProfile(spec)
if err != nil {
return errors.Wrapf(err, "loading seccomp profile (%s) failed", b.CommonBuildOpts.SeccompProfilePath)
}
spec.Linux.Seccomp = seccompConfig
}
}
cgroupMnt := specs.Mount{
Destination: "/sys/fs/cgroup",
Type: "cgroup",
Source: "cgroup",
Options: []string{"nosuid", "noexec", "nodev", "relatime", "ro"},
}
g.AddMount(cgroupMnt)
bindFiles := []string{"/etc/hosts", "/etc/resolv.conf"}
err = b.setupMounts(mountPoint, spec, options.Mounts, bindFiles, b.Volumes())
err = b.setupMounts(mountPoint, spec, options.Mounts, bindFiles, b.Volumes(), b.CommonBuildOpts.Volumes, b.CommonBuildOpts.ShmSize)
if err != nil {
return errors.Wrapf(err, "error resolving mountpoints for container")
}
@@ -285,6 +461,9 @@ func (b *Builder) Run(command []string, options RunOptions) error {
cmd.Dir = mountPoint
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
if options.Quiet {
cmd.Stdout = nil
}
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {

View File

@@ -3,7 +3,6 @@ package buildah
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
@@ -23,12 +22,6 @@ var (
OverrideMountsFile = "/etc/containers/mounts.conf"
)
// SecretData info
type SecretData struct {
Name string
Data []byte
}
func getMounts(filePath string) []string {
file, err := os.Open(filePath)
if err != nil {
@@ -48,67 +41,6 @@ func getMounts(filePath string) []string {
return mounts
}
// SaveTo saves secret data to given directory
func (s SecretData) SaveTo(dir string) error {
path := filepath.Join(dir, s.Name)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil && !os.IsExist(err) {
return err
}
return ioutil.WriteFile(path, s.Data, 0700)
}
func readAll(root, prefix string) ([]SecretData, error) {
path := filepath.Join(root, prefix)
data := []SecretData{}
files, err := ioutil.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
return data, nil
}
return nil, err
}
for _, f := range files {
fileData, err := readFile(root, filepath.Join(prefix, f.Name()))
if err != nil {
// If the file did not exist, might be a dangling symlink
// Ignore the error
if os.IsNotExist(err) {
continue
}
return nil, err
}
data = append(data, fileData...)
}
return data, nil
}
func readFile(root, name string) ([]SecretData, error) {
path := filepath.Join(root, name)
s, err := os.Stat(path)
if err != nil {
return nil, err
}
if s.IsDir() {
dirData, err2 := readAll(root, name)
if err2 != nil {
return nil, err2
}
return dirData, nil
}
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return []SecretData{{Name: name, Data: bytes}}, nil
}
// getHostAndCtrDir separates the host:container paths
func getMountsMap(path string) (string, string, error) {
arr := strings.SplitN(path, ":", 2)
@@ -118,15 +50,6 @@ func getMountsMap(path string) (string, string, error) {
return "", "", errors.Errorf("unable to get host and container dir")
}
func getHostSecretData(hostDir string) ([]SecretData, error) {
var allSecrets []SecretData
hostSecrets, err := readAll(hostDir, "")
if err != nil {
return nil, errors.Wrapf(err, "failed to read secrets from %q", hostDir)
}
return append(allSecrets, hostSecrets...), nil
}
// secretMount copies the contents of host directory to container directory
// and returns a list of mounts
func secretMounts(filePath, mountLabel, containerWorkingDir string) ([]rspec.Mount, error) {
@@ -157,16 +80,10 @@ func secretMounts(filePath, mountLabel, containerWorkingDir string) ([]rspec.Mou
return nil, err
}
data, err := getHostSecretData(hostDir)
if err != nil {
return nil, errors.Wrapf(err, "getting host secret data failed")
}
for _, s := range data {
err = s.SaveTo(ctrDirOnHost)
if err != nil {
return nil, err
}
if err = copyWithTar(hostDir, ctrDirOnHost); err != nil && !os.IsNotExist(err) {
return nil, errors.Wrapf(err, "error getting host secret data")
}
err = label.Relabel(ctrDirOnHost, mountLabel, false)
if err != nil {
return nil, errors.Wrap(err, "error applying correct labels")

48
tests/authenticate.bats Normal file
View File

@@ -0,0 +1,48 @@
#!/usr/bin/env bats
load helpers
@test "from-authenticate-cert-and-creds" {
buildah from --pull --name "alpine" --signature-policy ${TESTSDIR}/policy.json alpine
run buildah push --signature-policy ${TESTSDIR}/policy.json --tls-verify=false --creds testuser:testpassword alpine localhost:5000/my-alpine
echo "$output"
[ "$status" -eq 0 ]
# This should fail
run buildah push --signature-policy ${TESTSDIR}/policy.json --tls-verify=true localhost:5000/my-alpine
[ "$status" -ne 0 ]
# This should fail
run buildah from --signature-policy ${TESTSDIR}/policy.json --tls-verify=false --creds baduser:badpassword localhost:5000/my-alpine
[ "$status" -ne 0 ]
# This should work
run buildah from --name "my-alpine" --signature-policy ${TESTSDIR}/policy.json --tls-verify=false --creds testuser:testpassword localhost:5000/my-alpine
[ "$status" -eq 0 ]
# Create Dockerfile for bud tests
FILE=./Dockerfile
/bin/cat <<EOM >$FILE
FROM localhost:5000/my-alpine
EOM
chmod +x $FILE
# Remove containers and images before bud tests
buildah rm --all
buildah rmi -f --all
# bud test bad password should fail
run buildah bud -f ./Dockerfile --signature-policy ${TESTSDIR}/policy.json --tls-verify=false --creds=testuser:badpassword
[ "$status" -ne 0 ]
# bud test this should work
run buildah bud -f ./Dockerfile --signature-policy ${TESTSDIR}/policy.json --tls-verify=false --creds=testuser:testpassword
echo $status
[ "$status" -eq 0 ]
# Clean up
rm -f ./Dockerfile
buildah rm -a
buildah rmi -f --all
}

View File

@@ -7,7 +7,7 @@ load helpers
buildah rm $cid
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json scratch)
buildah rm $cid
cid=$(buildah from alpine --pull --signature-policy ${TESTSDIR}/policy.json --name i-love-naming-things)
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json --name i-love-naming-things alpine)
buildah rm i-love-naming-things
}

View File

@@ -139,7 +139,7 @@ load helpers
@test "bud-http-context-dir-with-Dockerfile-post" {
starthttpd ${TESTSDIR}/bud/http-context-subdir
target=scratch-image
buildah bud http://0.0.0.0:${HTTP_SERVER_PORT}/context.tar --signature-policy ${TESTSDIR}/policy.json -t ${target} -f context/Dockerfile
buildah bud --signature-policy ${TESTSDIR}/policy.json -t ${target} -f context/Dockerfile http://0.0.0.0:${HTTP_SERVER_PORT}/context.tar
stophttpd
cid=$(buildah from ${target})
buildah rm ${cid}
@@ -236,3 +236,29 @@ load helpers
[ "$status" -eq 0 ]
[ "$output" = "" ]
}
@test "bud-maintainer" {
target=alpine-image
buildah bud --signature-policy ${TESTSDIR}/policy.json -t ${target} ${TESTSDIR}/bud/maintainer
run buildah --debug=false inspect --type=image --format '{{.Docker.Author}}' ${target}
[ "$status" -eq 0 ]
[ "$output" = kilroy ]
run buildah --debug=false inspect --type=image --format '{{.OCIv1.Author}}' ${target}
[ "$status" -eq 0 ]
[ "$output" = kilroy ]
buildah rmi $(buildah --debug=false images -q)
run buildah --debug=false images -q
[ "$status" -eq 0 ]
[ "$output" = "" ]
}
@test "bud-unrecognized-instruction" {
target=alpine-image
run buildah bud --signature-policy ${TESTSDIR}/policy.json -t ${target} ${TESTSDIR}/bud/unrecognized
[ "$status" -ne 0 ]
[[ "$output" =~ BOGUS ]]
buildah rmi $(buildah --debug=false images -q)
run buildah --debug=false images -q
[ "$status" -eq 0 ]
[ "$output" = "" ]
}

View File

@@ -0,0 +1,2 @@
FROM alpine
MAINTAINER kilroy

View File

@@ -0,0 +1,2 @@
FROM alpine
BOGUS nope-nope-nope

124
tests/byid.bats Normal file
View File

@@ -0,0 +1,124 @@
#!/usr/bin/env bats
load helpers
@test "from-by-id" {
image=busybox
# Pull down the image, if we have to.
cid=$(buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json $image)
[ $? -eq 0 ]
[ $(wc -l <<< "$cid") -eq 1 ]
buildah rm $cid
# Get the image's ID.
run buildah --debug=false images -q $image
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
iid="$output"
# Use the image's ID to create a container.
run buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json ${iid}
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
cid="$output"
buildah rm $cid
# Use a truncated form of the image's ID to create a container.
run buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json ${iid:0:6}
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
cid="$output"
buildah rm $cid
buildah rmi $iid
}
@test "inspect-by-id" {
image=busybox
# Pull down the image, if we have to.
cid=$(buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json $image)
[ $? -eq 0 ]
[ $(wc -l <<< "$cid") -eq 1 ]
buildah rm $cid
# Get the image's ID.
run buildah --debug=false images -q $image
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
iid="$output"
# Use the image's ID to inspect it.
run buildah --debug=false inspect --type=image ${iid}
echo "$output"
[ $status -eq 0 ]
# Use a truncated copy of the image's ID to inspect it.
run buildah --debug=false inspect --type=image ${iid:0:6}
echo "$output"
[ $status -eq 0 ]
buildah rmi $iid
}
@test "push-by-id" {
for image in busybox kubernetes/pause ; do
echo pulling/pushing image $image
TARGET=${TESTDIR}/subdir-$(basename $image)
mkdir -p $TARGET $TARGET-truncated
# Pull down the image, if we have to.
cid=$(buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json $image)
[ $? -eq 0 ]
[ $(wc -l <<< "$cid") -eq 1 ]
buildah rm $cid
# Get the image's ID.
run buildah --debug=false images -q $IMAGE
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
iid="$output"
# Use the image's ID to push it.
run buildah push --signature-policy ${TESTSDIR}/policy.json $iid dir:$TARGET
echo "$output"
[ $status -eq 0 ]
# Use a truncated form of the image's ID to push it.
run buildah push --signature-policy ${TESTSDIR}/policy.json ${iid:0:6} dir:$TARGET-truncated
echo "$output"
[ $status -eq 0 ]
# Use the image's complete ID to remove it.
buildah rmi $iid
done
}
@test "rmi-by-id" {
image=busybox
# Pull down the image, if we have to.
cid=$(buildah --debug=false from --pull --signature-policy ${TESTSDIR}/policy.json $image)
[ $? -eq 0 ]
[ $(wc -l <<< "$cid") -eq 1 ]
buildah rm $cid
# Get the image's ID.
run buildah --debug=false images -q $image
echo "$output"
[ $status -eq 0 ]
[ $(wc -l <<< "$output") -eq 1 ]
iid="$output"
# Use a truncated copy of the image's ID to remove it.
run buildah --debug=false rmi ${iid:0:6}
echo "$output"
[ $status -eq 0 ]
}

View File

@@ -111,3 +111,29 @@ load helpers
[ "$status" -ne 0 ]
buildah rm $cid
}
@test "copy --chown" {
mkdir -p ${TESTDIR}/subdir
mkdir -p ${TESTDIR}/other-subdir
createrandom ${TESTDIR}/subdir/randomfile
createrandom ${TESTDIR}/subdir/other-randomfile
createrandom ${TESTDIR}/randomfile
createrandom ${TESTDIR}/other-subdir/randomfile
createrandom ${TESTDIR}/other-subdir/other-randomfile
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json alpine)
root=$(buildah mount $cid)
buildah config --workingdir / $cid
buildah copy --chown 1:1 $cid ${TESTDIR}/randomfile
buildah copy --chown root:1 $cid ${TESTDIR}/randomfile /randomfile2
buildah copy --chown nobody $cid ${TESTDIR}/randomfile /randomfile3
buildah copy --chown nobody:root $cid ${TESTDIR}/subdir /subdir
test $(stat -c "%u:%g" $root/randomfile) = "1:1"
test $(stat -c "%U:%g" $root/randomfile2) = "root:1"
test $(stat -c "%U" $root/randomfile3) = "nobody"
(cd $root/subdir/; for i in *; do test $(stat -c "%U:%G" $i) = "nobody:root"; done)
buildah copy --chown root:root $cid ${TESTDIR}/other-subdir /subdir
(cd $root/subdir/; for i in *randomfile; do test $(stat -c "%U:%G" $i) = "root:root"; done)
test $(stat -c "%U:%G" $root/subdir) = "nobody:root"
buildah rm $cid
}

44
tests/digest.bats Normal file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env bats
load helpers
fromreftest() {
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json $1)
pushdir=${TESTDIR}/fromreftest
mkdir -p ${pushdir}/{1,2,3}
buildah push --signature-policy ${TESTSDIR}/policy.json $1 dir:${pushdir}/1
buildah commit --signature-policy ${TESTSDIR}/policy.json $cid new-image
buildah push --signature-policy ${TESTSDIR}/policy.json new-image dir:${pushdir}/2
buildah rmi new-image
buildah commit --signature-policy ${TESTSDIR}/policy.json $cid dir:${pushdir}/3
buildah rm $cid
rm -fr ${pushdir}
}
@test "from-by-digest-s1" {
fromreftest kubernetes/pause@sha256:f8cd50c5a287dd8c5f226cf69c60c737d34ed43726c14b8a746d9de2d23eda2b
}
@test "from-by-digest-s1-a-discarded-layer" {
fromreftest docker/whalesay@sha256:178598e51a26abbc958b8a2e48825c90bc22e641de3d31e18aaf55f3258ba93b
}
@test "from-by-tag-s1" {
fromreftest kubernetes/pause:go
}
@test "from-by-repo-only-s1" {
fromreftest kubernetes/pause
}
@test "from-by-digest-s2" {
fromreftest alpine@sha256:e9cec9aec697d8b9d450edd32860ecd363f2f3174c8338beb5f809422d182c63
}
@test "from-by-tag-s2" {
fromreftest alpine:2.6
}
@test "from-by-repo-only-s2" {
fromreftest alpine
}

View File

@@ -0,0 +1,333 @@
package integration
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"encoding/json"
"github.com/containers/image/copy"
"github.com/containers/image/signature"
"github.com/containers/image/storage"
"github.com/containers/image/transports/alltransports"
"github.com/containers/image/types"
sstorage "github.com/containers/storage"
"github.com/containers/storage/pkg/reexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"github.com/pkg/errors"
"github.com/projectatomic/buildah"
)
var (
INTEGRATION_ROOT string
STORAGE_OPTIONS = "--storage-driver vfs"
ARTIFACT_DIR = "/tmp/.artifacts"
CACHE_IMAGES = []string{"alpine", "busybox", FEDORA_MINIMAL}
RESTORE_IMAGES = []string{"alpine", "busybox"}
ALPINE = "docker.io/library/alpine:latest"
BB_GLIBC = "docker.io/library/busybox:glibc"
FEDORA_MINIMAL = "registry.fedoraproject.org/fedora-minimal:latest"
defaultWaitTimeout = 90
)
// BuildAhSession wraps the gexec.session so we can extend it
type BuildAhSession struct {
*gexec.Session
}
// BuildAhTest struct for command line options
type BuildAhTest struct {
BuildAhBinary string
RunRoot string
StorageOptions string
ArtifactPath string
TempDir string
SignaturePath string
Root string
RegistriesConf string
}
// TestBuildAh ginkgo master function
func TestBuildAh(t *testing.T) {
if reexec.Init() {
os.Exit(1)
}
RegisterFailHandler(Fail)
RunSpecs(t, "Buildah Suite")
}
var _ = BeforeSuite(func() {
//Cache images
cwd, _ := os.Getwd()
INTEGRATION_ROOT = filepath.Join(cwd, "../../")
buildah := BuildahCreate("/tmp")
buildah.ArtifactPath = ARTIFACT_DIR
if _, err := os.Stat(ARTIFACT_DIR); os.IsNotExist(err) {
if err = os.Mkdir(ARTIFACT_DIR, 0777); err != nil {
fmt.Printf("%q\n", err)
os.Exit(1)
}
}
for _, image := range CACHE_IMAGES {
fmt.Printf("Caching %s...\n", image)
if err := buildah.CreateArtifact(image); err != nil {
fmt.Printf("%q\n", err)
os.Exit(1)
}
}
})
// CreateTempDirin
func CreateTempDirInTempDir() (string, error) {
return ioutil.TempDir("", "buildah_test")
}
// BuildahCreate a BuildAhTest instance for the tests
func BuildahCreate(tempDir string) BuildAhTest {
cwd, _ := os.Getwd()
buildAhBinary := filepath.Join(cwd, "../../buildah")
if os.Getenv("BUILDAH_BINARY") != "" {
buildAhBinary = os.Getenv("BUILDAH_BINARY")
}
storageOptions := STORAGE_OPTIONS
if os.Getenv("STORAGE_OPTIONS") != "" {
storageOptions = os.Getenv("STORAGE_OPTIONS")
}
return BuildAhTest{
BuildAhBinary: buildAhBinary,
RunRoot: filepath.Join(tempDir, "runroot"),
Root: filepath.Join(tempDir, "root"),
StorageOptions: storageOptions,
ArtifactPath: ARTIFACT_DIR,
TempDir: tempDir,
SignaturePath: "../../tests/policy.json",
RegistriesConf: "../../registries.conf",
}
}
//MakeOptions assembles all the buildah main options
func (p *BuildAhTest) MakeOptions() []string {
return strings.Split(fmt.Sprintf("--root %s --runroot %s --registries-conf %s",
p.Root, p.RunRoot, p.RegistriesConf), " ")
}
// BuildAh is the exec call to buildah on the filesystem
func (p *BuildAhTest) BuildAh(args []string) *BuildAhSession {
buildAhOptions := p.MakeOptions()
buildAhOptions = append(buildAhOptions, strings.Split(p.StorageOptions, " ")...)
buildAhOptions = append(buildAhOptions, args...)
fmt.Printf("Running: %s %s\n", p.BuildAhBinary, strings.Join(buildAhOptions, " "))
command := exec.Command(p.BuildAhBinary, buildAhOptions...)
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
if err != nil {
Fail(fmt.Sprintf("unable to run buildah command: %s", strings.Join(buildAhOptions, " ")))
}
return &BuildAhSession{session}
}
// Cleanup cleans up the temporary store
func (p *BuildAhTest) Cleanup() {
// Nuke tempdir
if err := os.RemoveAll(p.TempDir); err != nil {
fmt.Printf("%q\n", err)
}
}
// GrepString takes session output and behaves like grep. it returns a bool
// if successful and an array of strings on positive matches
func (s *BuildAhSession) GrepString(term string) (bool, []string) {
var (
greps []string
matches bool
)
for _, line := range strings.Split(s.OutputToString(), "\n") {
if strings.Contains(line, term) {
matches = true
greps = append(greps, line)
}
}
return matches, greps
}
// OutputToString formats session output to string
func (s *BuildAhSession) OutputToString() string {
fields := strings.Fields(fmt.Sprintf("%s", s.Out.Contents()))
return strings.Join(fields, " ")
}
// OutputToStringArray returns the output as a []string
// where each array item is a line split by newline
func (s *BuildAhSession) OutputToStringArray() []string {
output := fmt.Sprintf("%s", s.Out.Contents())
return strings.Split(output, "\n")
}
// IsJSONOutputValid attempts to unmarshall the session buffer
// and if successful, returns true, else false
func (s *BuildAhSession) IsJSONOutputValid() bool {
var i interface{}
if err := json.Unmarshal(s.Out.Contents(), &i); err != nil {
fmt.Println(err)
return false
}
return true
}
func (s *BuildAhSession) WaitWithDefaultTimeout() {
s.Wait(defaultWaitTimeout)
}
// SystemExec is used to exec a system command to check its exit code or output
func (p *BuildAhTest) SystemExec(command string, args []string) *BuildAhSession {
c := exec.Command(command, args...)
session, err := gexec.Start(c, GinkgoWriter, GinkgoWriter)
if err != nil {
Fail(fmt.Sprintf("unable to run command: %s %s", command, strings.Join(args, " ")))
}
return &BuildAhSession{session}
}
// CreateArtifact creates a cached image in the artifact dir
func (p *BuildAhTest) CreateArtifact(image string) error {
imageName := fmt.Sprintf("docker://%s", image)
systemContext := types.SystemContext{
SignaturePolicyPath: p.SignaturePath,
}
policy, err := signature.DefaultPolicy(&systemContext)
if err != nil {
return errors.Errorf("error loading signature policy: %v", err)
}
policyContext, err := signature.NewPolicyContext(policy)
if err != nil {
return errors.Errorf("error loading signature policy: %v", err)
}
defer func() {
_ = policyContext.Destroy()
}()
options := &copy.Options{}
importRef, err := alltransports.ParseImageName(imageName)
if err != nil {
return errors.Errorf("error parsing image name %v: %v", image, err)
}
imageDir := strings.Replace(image, "/", "_", -1)
exportTo := filepath.Join("dir:", p.ArtifactPath, imageDir)
exportRef, err := alltransports.ParseImageName(exportTo)
if err != nil {
return errors.Errorf("error parsing image name %v: %v", exportTo, err)
}
return copy.Image(policyContext, exportRef, importRef, options)
}
// RestoreArtifact puts the cached image into our test store
func (p *BuildAhTest) RestoreArtifact(image string) error {
storeOptions := sstorage.DefaultStoreOptions
storeOptions.GraphDriverName = "vfs"
//storeOptions.GraphDriverOptions = storageOptions
storeOptions.GraphRoot = p.Root
storeOptions.RunRoot = p.RunRoot
store, err := sstorage.GetStore(storeOptions)
options := &copy.Options{}
if err != nil {
return errors.Errorf("error opening storage: %v", err)
}
defer func() {
_, _ = store.Shutdown(false)
}()
storage.Transport.SetStore(store)
ref, err := storage.Transport.ParseStoreReference(store, image)
if err != nil {
return errors.Errorf("error parsing image name: %v", err)
}
imageDir := strings.Replace(image, "/", "_", -1)
importFrom := fmt.Sprintf("dir:%s", filepath.Join(p.ArtifactPath, imageDir))
importRef, err := alltransports.ParseImageName(importFrom)
if err != nil {
return errors.Errorf("error parsing image name %v: %v", image, err)
}
systemContext := types.SystemContext{
SignaturePolicyPath: p.SignaturePath,
}
policy, err := signature.DefaultPolicy(&systemContext)
if err != nil {
return errors.Errorf("error loading signature policy: %v", err)
}
policyContext, err := signature.NewPolicyContext(policy)
if err != nil {
return errors.Errorf("error loading signature policy: %v", err)
}
defer func() {
_ = policyContext.Destroy()
}()
err = copy.Image(policyContext, ref, importRef, options)
if err != nil {
return errors.Errorf("error importing %s: %v", importFrom, err)
}
return nil
}
// RestoreAllArtifacts unpacks all cached images
func (p *BuildAhTest) RestoreAllArtifacts() error {
for _, image := range RESTORE_IMAGES {
if err := p.RestoreArtifact(image); err != nil {
return err
}
}
return nil
}
// StringInSlice determines if a string is in a string slice, returns bool
func StringInSlice(s string, sl []string) bool {
for _, i := range sl {
if i == s {
return true
}
}
return false
}
//LineInOutputStartsWith returns true if a line in a
// session output starts with the supplied string
func (s *BuildAhSession) LineInOuputStartsWith(term string) bool {
for _, i := range s.OutputToStringArray() {
if strings.HasPrefix(i, term) {
return true
}
}
return false
}
//LineInOutputContains returns true if a line in a
// session output starts with the supplied string
func (s *BuildAhSession) LineInOuputContains(term string) bool {
for _, i := range s.OutputToStringArray() {
if strings.Contains(i, term) {
return true
}
}
return false
}
// InspectContainerToJSON takes the session output of an inspect
// container and returns json
func (s *BuildAhSession) InspectImageJSON() buildah.BuilderInfo {
var i buildah.BuilderInfo
err := json.Unmarshal(s.Out.Contents(), &i)
Expect(err).To(BeNil())
return i
}

92
tests/e2e/inspect_test.go Normal file
View File

@@ -0,0 +1,92 @@
package integration
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Podman load", func() {
var (
tempdir string
err error
buildahtest BuildAhTest
)
BeforeEach(func() {
tempdir, err = CreateTempDirInTempDir()
if err != nil {
os.Exit(1)
}
buildahtest = BuildahCreate(tempdir)
})
AfterEach(func() {
buildahtest.Cleanup()
})
It("buildah inspect json", func() {
b := buildahtest.BuildAh([]string{"from", "--pull=false", "scratch"})
b.WaitWithDefaultTimeout()
Expect(b.ExitCode()).To(Equal(0))
cid := b.OutputToString()
result := buildahtest.BuildAh([]string{"inspect", cid})
result.WaitWithDefaultTimeout()
Expect(result.ExitCode()).To(Equal(0))
Expect(result.IsJSONOutputValid()).To(BeTrue())
})
It("buildah inspect format", func() {
b := buildahtest.BuildAh([]string{"from", "--pull=false", "scratch"})
b.WaitWithDefaultTimeout()
Expect(b.ExitCode()).To(Equal(0))
cid := b.OutputToString()
result := buildahtest.BuildAh([]string{"inspect", "--format", "\"{{.}}\"", cid})
result.WaitWithDefaultTimeout()
Expect(result.ExitCode()).To(Equal(0))
})
It("buildah inspect image", func() {
b := buildahtest.BuildAh([]string{"from", "--pull=false", "scratch"})
b.WaitWithDefaultTimeout()
Expect(b.ExitCode()).To(Equal(0))
cid := b.OutputToString()
commit := buildahtest.BuildAh([]string{"commit", cid, "scratchy-image"})
commit.WaitWithDefaultTimeout()
Expect(commit.ExitCode()).To(Equal(0))
result := buildahtest.BuildAh([]string{"inspect", "--type", "image", "scratchy-image"})
result.WaitWithDefaultTimeout()
Expect(result.ExitCode()).To(Equal(0))
Expect(result.IsJSONOutputValid()).To(BeTrue())
result = buildahtest.BuildAh([]string{"inspect", "--type", "image", "scratchy-image:latest"})
result.WaitWithDefaultTimeout()
Expect(result.ExitCode()).To(Equal(0))
Expect(result.IsJSONOutputValid()).To(BeTrue())
})
It("buildah HTML escaped", func() {
b := buildahtest.BuildAh([]string{"from", "--pull=false", "scratch"})
b.WaitWithDefaultTimeout()
Expect(b.ExitCode()).To(Equal(0))
cid := b.OutputToString()
config := buildahtest.BuildAh([]string{"config", "--label", "maintainer=\"Darth Vader <dvader@darkside.io>\"", cid})
config.WaitWithDefaultTimeout()
Expect(config.ExitCode()).To(Equal(0))
commit := buildahtest.BuildAh([]string{"commit", cid, "darkside-image"})
commit.WaitWithDefaultTimeout()
Expect(commit.ExitCode()).To(Equal(0))
result := buildahtest.BuildAh([]string{"inspect", "--type", "image", "darkside-image"})
result.WaitWithDefaultTimeout()
Expect(result.ExitCode()).To(Equal(0))
data := result.InspectImageJSON()
Expect(data.Docker.Config.Labels["maintainer"]).To(Equal("\"Darth Vader <dvader@darkside.io>\""))
})
})

View File

@@ -12,12 +12,10 @@ load helpers
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json dir:${elsewhere})
buildah rm $cid
buildah rmi ${elsewhere}
[ "$cid" = elsewhere-img-working-container ]
cid=$(buildah from --pull-always --signature-policy ${TESTSDIR}/policy.json dir:${elsewhere})
buildah rm $cid
buildah rmi ${elsewhere}
[ "$cid" = `basename ${elsewhere}`-working-container ]
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json scratch)
@@ -26,12 +24,10 @@ load helpers
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json dir:${elsewhere})
buildah rm $cid
buildah rmi ${elsewhere}
[ "$cid" = elsewhere-img-working-container ]
cid=$(buildah from --pull-always --signature-policy ${TESTSDIR}/policy.json dir:${elsewhere})
buildah rm $cid
buildah rmi ${elsewhere}
[ "$cid" = `basename ${elsewhere}`-working-container ]
}
@@ -73,7 +69,6 @@ load helpers
}
@test "from-authenticate-cert-and-creds" {
mkdir -p ${TESTDIR}/auth
# Create creds and store in ${TESTDIR}/auth/htpasswd
# docker run --entrypoint htpasswd registry:2 -Bbn testuser testpassword > ${TESTDIR}/auth/htpasswd
@@ -112,3 +107,105 @@ load helpers
# buildah rm $ctrid
# buildah rmi -f $(buildah --debug=false images -q)
}
@test "from-tagged-image" {
# Github #396: Make sure the container name starts with the correct image even when it's tagged.
cid=$(buildah from --pull=false --signature-policy ${TESTSDIR}/policy.json scratch)
buildah commit --signature-policy ${TESTSDIR}/policy.json "$cid" scratch2
buildah rm $cid
buildah tag scratch2 scratch3
cid=$(buildah from --signature-policy ${TESTSDIR}/policy.json scratch3)
[ "$cid" == scratch3-working-container ]
buildah rm ${cid}
buildah rmi scratch2 scratch3
# Github https://github.com/projectatomic/buildah/issues/396#issuecomment-360949396
cid=$(buildah from --pull=true --signature-policy ${TESTSDIR}/policy.json alpine)
buildah rm $cid
buildah tag alpine alpine2
cid=$(buildah from --signature-policy ${TESTSDIR}/policy.json docker.io/alpine2)
[ "$cid" == alpine2-working-container ]
buildah rm ${cid}
buildah rmi alpine alpine2
}
@test "from cpu-period test" {
cid=$(buildah from --cpu-period=5000 --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/cpu/cpu.cfs_period_us
echo $output
[ "$status" -eq 0 ]
[[ "$output" =~ "5000" ]]
buildah rm $cid
}
@test "from cpu-quota test" {
cid=$(buildah from --cpu-quota=5000 --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us
echo "$output"
[ "$status" -eq 0 ]
[[ "$output" =~ 5000 ]]
buildah rm $cid
}
@test "from cpu-shares test" {
cid=$(buildah from --cpu-shares=2 --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/cpu/cpu.shares
echo "$output"
[ "$status" -eq 0 ]
[[ "$output" =~ 2 ]]
buildah rm $cid
}
@test "from cpuset-cpus test" {
cid=$(buildah from --cpuset-cpus=0 --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/cpuset/cpuset.cpus
echo "$output"
[ "$status" -eq 0 ]
[[ "$output" =~ 0 ]]
buildah rm $cid
}
@test "from cpuset-mems test" {
cid=$(buildah from --cpuset-mems=0 --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/cpuset/cpuset.mems
echo "$output"
[ "$status" -eq 0 ]
[[ "$output" =~ 0 ]]
buildah rm $cid
}
@test "from memory test" {
cid=$(buildah from --memory=40m --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid cat /sys/fs/cgroup/memory/memory.limit_in_bytes
echo $output
[ "$status" -eq 0 ]
[[ "$output" =~ 41943040 ]]
buildah rm $cid
}
@test "from volume test" {
cid=$(buildah from --volume=${TESTDIR}:/myvol --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid -- cat /proc/mounts
echo $output
[ "$status" -eq 0 ]
[[ "$output" =~ /myvol ]]
buildah rm $cid
}
@test "from volume ro test" {
cid=$(buildah from --volume=${TESTDIR}:/myvol:ro --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid -- cat /proc/mounts
echo $output
[ "$status" -eq 0 ]
[[ "$output" =~ /myvol ]]
buildah rm $cid
}
@test "from shm-size test" {
cid=$(buildah from --shm-size=80m --pull --signature-policy ${TESTSDIR}/policy.json alpine)
run buildah run $cid -- df -h
echo $output
[ "$status" -eq 0 ]
[[ "$output" =~ 80 ]]
buildah rm $cid
}

View File

@@ -42,7 +42,7 @@ function createrandom() {
}
function buildah() {
${BUILDAH_BINARY} --debug --root ${TESTDIR}/root --runroot ${TESTDIR}/runroot --storage-driver ${STORAGE_DRIVER} "$@"
${BUILDAH_BINARY} --debug --registries-conf ${TESTSDIR}/registries.conf --root ${TESTDIR}/root --runroot ${TESTDIR}/runroot --storage-driver ${STORAGE_DRIVER} "$@"
}
function imgtype() {

View File

@@ -8,6 +8,7 @@ import (
"strings"
is "github.com/containers/image/storage"
"github.com/containers/image/transports/alltransports"
"github.com/containers/image/types"
"github.com/containers/storage"
"github.com/opencontainers/image-spec/specs-go/v1"
@@ -33,7 +34,9 @@ func main() {
policy := flag.String("signature-policy", "", "signature policy file")
mtype := flag.String("expected-manifest-type", buildah.OCIv1ImageManifest, "expected manifest type")
showm := flag.Bool("show-manifest", false, "output the manifest JSON")
rebuildm := flag.Bool("rebuild-manifest", false, "rebuild the manifest JSON")
showc := flag.Bool("show-config", false, "output the configuration JSON")
rebuildc := flag.Bool("rebuild-config", false, "rebuild the configuration JSON")
flag.Parse()
logrus.SetLevel(logrus.ErrorLevel)
if debug != nil && *debug {
@@ -79,6 +82,7 @@ func main() {
logrus.Errorf("error opening storage: %v", err)
return
}
is.Transport.SetStore(store)
errors := false
defer func() {
@@ -88,6 +92,7 @@ func main() {
}
}()
for _, image := range args {
var ref types.ImageReference
oImage := v1.Image{}
dImage := docker.V2Image{}
oManifest := v1.Manifest{}
@@ -97,9 +102,13 @@ func main() {
ref, err := is.Transport.ParseStoreReference(store, image)
if err != nil {
logrus.Errorf("error parsing reference %q: %v", image, err)
errors = true
continue
ref2, err2 := alltransports.ParseImageName(image)
if err2 != nil {
logrus.Errorf("error parsing reference %q: %v", image, err)
errors = true
continue
}
ref = ref2
}
img, err := ref.NewImage(systemContext)
@@ -161,6 +170,66 @@ func main() {
errors = true
continue
}
switch manifestType {
case buildah.OCIv1ImageManifest:
if rebuildm != nil && *rebuildm {
err = json.Unmarshal(manifest, &oManifest)
if err != nil {
logrus.Errorf("error parsing manifest from %q: %v", image, err)
errors = true
continue
}
manifest, err = json.Marshal(oManifest)
if err != nil {
logrus.Errorf("error rebuilding manifest from %q: %v", image, err)
errors = true
continue
}
}
if rebuildc != nil && *rebuildc {
err = json.Unmarshal(config, &oImage)
if err != nil {
logrus.Errorf("error parsing config from %q: %v", image, err)
errors = true
continue
}
config, err = json.Marshal(oImage)
if err != nil {
logrus.Errorf("error rebuilding config from %q: %v", image, err)
errors = true
continue
}
}
case buildah.Dockerv2ImageManifest:
if rebuildm != nil && *rebuildm {
err = json.Unmarshal(manifest, &dManifest)
if err != nil {
logrus.Errorf("error parsing manifest from %q: %v", image, err)
errors = true
continue
}
manifest, err = json.Marshal(dManifest)
if err != nil {
logrus.Errorf("error rebuilding manifest from %q: %v", image, err)
errors = true
continue
}
}
if rebuildc != nil && *rebuildc {
err = json.Unmarshal(config, &dImage)
if err != nil {
logrus.Errorf("error parsing config from %q: %v", image, err)
errors = true
continue
}
config, err = json.Marshal(dImage)
if err != nil {
logrus.Errorf("error rebuilding config from %q: %v", image, err)
errors = true
continue
}
}
}
if expectedConfigType != "" && configType != expectedConfigType {
logrus.Errorf("expected config type %q in %q, got %q", expectedConfigType, image, configType)
errors = true

View File

@@ -1,28 +0,0 @@
#!/usr/bin/env bats
load helpers
@test "inspect-json" {
cid=$(buildah from --pull=false --signature-policy ${TESTSDIR}/policy.json scratch)
run buildah --debug=false inspect "$cid"
[ "$status" -eq 0 ]
[ "$output" != "" ]
}
@test "inspect-format" {
cid=$(buildah from --pull=false --signature-policy ${TESTSDIR}/policy.json scratch)
run buildah --debug=false inspect --format '{{.}}' "$cid"
[ "$status" -eq 0 ]
[ "$output" != "" ]
}
@test "inspect-image" {
cid=$(buildah from --pull=false --signature-policy ${TESTSDIR}/policy.json scratch)
buildah commit --signature-policy ${TESTSDIR}/policy.json $cid scratchy-image
run buildah --debug=false inspect --type image scratchy-image
[ "$status" -eq 0 ]
[ "$output" != "" ]
run buildah --debug=false inspect --type image scratchy-image:latest
[ "$status" -eq 0 ]
[ "$output" != "" ]
}

View File

@@ -8,11 +8,15 @@ load helpers
cid=$(buildah from --pull=false --signature-policy ${TESTSDIR}/policy.json ${source})
for format in "" docker oci ; do
mkdir -p ${TESTDIR}/committed${format:+.${format}}
buildah commit ${format:+--format ${format}} --reference-time ${TESTDIR}/reference-time-file --signature-policy ${TESTSDIR}/policy.json "$cid" scratch-image${format:+-${format}}
buildah commit ${format:+--format ${format}} --reference-time ${TESTDIR}/reference-time-file --signature-policy ${TESTSDIR}/policy.json "$cid" dir:${TESTDIR}/committed${format:+.${format}}
# Force no compression to generate what we push.
buildah commit -D ${format:+--format ${format}} --reference-time ${TESTDIR}/reference-time-file --signature-policy ${TESTSDIR}/policy.json "$cid" scratch-image${format:+-${format}}
buildah commit -D ${format:+--format ${format}} --reference-time ${TESTDIR}/reference-time-file --signature-policy ${TESTSDIR}/policy.json "$cid" dir:${TESTDIR}/committed${format:+.${format}}
mkdir -p ${TESTDIR}/pushed${format:+.${format}}
buildah push --signature-policy ${TESTSDIR}/policy.json scratch-image${format:+-${format}} dir:${TESTDIR}/pushed${format:+.${format}}
diff -u ${TESTDIR}/committed${format:+.${format}}/manifest.json ${TESTDIR}/pushed${format:+.${format}}/manifest.json
# Reencode the manifest to lose variations due to different encoders or definitions of structures.
imgtype -expected-manifest-type "*" -rebuild-manifest -show-manifest dir:${TESTDIR}/committed${format:+.${format}} > ${TESTDIR}/manifest.committed${format:+.${format}}
imgtype -expected-manifest-type "*" -rebuild-manifest -show-manifest dir:${TESTDIR}/pushed${format:+.${format}} > ${TESTDIR}/manifest.pushed${format:+.${format}}
diff -u ${TESTDIR}/manifest.committed${format:+.${format}} ${TESTDIR}/manifest.pushed${format:+.${format}}
[ "$output" = "" ]
done
buildah rm "$cid"
@@ -38,3 +42,14 @@ load helpers
buildah rmi alpine
rm -rf my-dir
}
@test "push with imageid" {
cid=$(buildah from --pull --signature-policy ${TESTSDIR}/policy.json alpine)
imageid=$(buildah images -q)
run buildah push --signature-policy ${TESTSDIR}/policy.json $imageid dir:my-dir
echo "$output"
[ "$status" -eq 0 ]
buildah rm "$cid"
buildah rmi alpine
rm -rf my-dir
}

Some files were not shown because too many files have changed in this diff Show More