Compare commits

...

327 Commits

Author SHA1 Message Date
Fabiano Fidêncio
a8a623fb75 Merge pull request #2257 from fidencio/wip/runtime-option-fix
shim-v2: Be compatible with the old runtime options
2021-07-19 08:05:01 +02:00
Fabiano Fidêncio
fcc93b0074 shim-v2: Be compatible with the old runtime options
Seems that at least some versions of container, when using ConifgPath,
still rely on the runtime options and its APIs from the not in use
anymore github.com/containerd/cri-containerd/pkg/api/runtimeoptions/v1.

The fact backward compat breaks when moving from the old to the new
runtime options, which happened as part of f60641a6e6d, strongly feels
like a containerd bug.  Regardless, we can easily work this around on
our side without much hassle.

Just by importing old runtime options the unmarshalling doesn't break
anymore and we can easily check whether getting the options fails or not
and fallback to the old way if it does.

Fixes: #2258

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-18 00:07:57 +02:00
Fabiano Fidêncio
594ff3a5bd Merge pull request #2241 from fidencio/wip/use-the-correct-image-for-kata-deploy
kata-deploy: Use the correct image for kata-deploy
2021-07-15 00:59:45 +02:00
Fabiano Fidêncio
fdf9731992 kata-deploy: Use the correct image for kata-deploy
While doing the release we've faced the following issue:
```
  Dockerfile for action: '/home/runner/work/kata-containers/kata-containers/./packaging/kata-deploy/action/Dockerfile'.
  /usr/bin/docker build -t 8a33c1:c0625fe487ce5e4c8217747bef28861f -f "/home/runner/work/kata-containers/kata-containers/./packaging/kata-deploy/action/Dockerfile" "/home/runner/work/kata-containers/kata-containers/packaging/kata-deploy/action"
  Sending build context to Docker daemon  15.87kB
  Step 1/12 : FROM microsoft/azure-cli:latest
  pull access denied for microsoft/azure-cli, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
```

Carlos pointed out that the image has gone awry and that we could use
mcr.microsoft.com/azure-cli instead.

Fixes: #2240

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-15 00:03:11 +02:00
Fabiano Fidêncio
17262cfe93 Merge pull request #2236 from fidencio/2.2.0-alpha1-branch-bump
# Kata Containers 2.2.0-alpha1
2021-07-14 21:56:53 +02:00
Fabiano Fidêncio
c8aab29b38 release: Kata Containers 2.2.0-alpha1
- runtime: Register defer function at early stage
- Ensure the go vendored code is up-to-date and that we actually can call `cargo vendor` on every pull-request
- ci: add golang 1.16 to the CI
- Update outdated comments and do some minor reworks
- snap: Build initrd on ppc64le & s390x
- ci: static checks: use defined target_branch
- trace-forwarder: Add option rustflags, target, build-type for the make
- CI: Honour force-skip-ci label
- qemu: stop the virtiofsd specifically
- tracing: Consolidate tracing into a new katatrace package
- runtime: return error if clh's binary doesn't have a normal stat
- osbuilder: Fix the order of checking the distro config directory
- agent: Fix to parsing of /proc/self/mountinfo
- runtime: Fix lint issues
- snap: Miscellaneous s390x fixes
- runtime: Use CC=gcc on all RPM-based s390x
- s390x: Enable virtio-blk-ccw
- forwarder: Add dump only option
- shimv2: fix the issue of leaking the hypervisor processes
- runtime: Remove the version check for cloud hypervisor
- agent: fix wrong regular exp to fetch guest-cid
- runtime: refact virtcontainers/pkg/oci
- agent: enhance tests of execute_hook
- agent: Cleanup config
- Pass span context from runtime to agent to get a full trace #1968
- agent: update netlink libraries
- shimv2: update containerd vendor
- runtime: Format golang proto code
- agent: delete some lint attributes
- docs: Fix url in virtiofs documentation
- tools: agent-ctl: Fix build failure
- cargo: Use latest nix crate for all Rust code bases
- virtcontainers: Don't fail memory hotplug
- Add "watchable-mounts" concept to allow for  inotify support of specific types of mounts.
- tracing: Make runHooks() span creation return context
- kernel: Add Secure Execution guest
- packaging: Support Podman in QEMU build
- Update qat version
- docs: Set LIBC=gnu for s390x too
- shimv2: fix the issue of leaking wait goroutines
- runtime: report finish time in containers stats
- docs: Fix typos in Developer Guide
- docs: Update urls for Documentation Requirements document
- runtime: update default machine type to q35
- docs: fix brackets usage error for developer guide
- Remove the pc machine
- runtime: do not hot-remove PMEM devices
- docs: Update kata-deploy urls for installation document
- docs: Update url for installation guides
- agent: Add some mount options and sort the options alphabetically
- runtime: using detail propertites instead of function name in log field
- qemu: Add nvdimm read-only file support
- ci: snap: Fetch history to all branches and tags
- memory_offset must be larger than 32 bit
- containerd-shim-v2: Skip TestIoCopy unit test
- ppc64le: Adding test for appendProtectionDevice
- agent: Update rust version for tokio
- Upgrade mio to v0.7.13 to fix epoll_fd leak problem
- osbuilder: fix log message that is not error but seems like an error
- docs: Update url for breaking compatibility
- docs: Remove docker support with kata 2.x and sysctls
- docs: Update README for runtime documentation
- Support SEV
- test: Add a unit test for ioCopy()
- versions: Upgrade to cloud-hypervisor v16.0

e3860691 static-checks: Restrict static checks to go 1.15 and 1.16
f4fbf723 runtime: Update vendored code
a20074d4 static-checks: Check the vendored code
ac8f972e build: Add `make vendor`
f9643d83 agent-ctl: Add `make vendor`
5e69b498 trace-forwarder: Add `make vendor`
a104f132 agent: Add `make vendor`
579b3f34 runtime: Add `make vendor`
930ca55d runtime: Add `make handle_vendor`
39546a10 runtime: delete not used functions
d0bc148f runtime: Register defer function at early stage
350acb2d virtcontainers: refactoring code for error handling in sandbox
858f39ef virtcontainers: update wrong comments for code
e0a19f6a virtcontainers: update API documentation
8d6dd2ad snap: support golang 1.16.x
a48dc93f versions: update newest golang version
37996791 ci: add 1.16 to the list of golang versions to test
6999dcca trace-forwarder: Add option rustflags, target, build-type for the make
7db8a85a CI: Honour force-skip-ci label
007a6561 snap: Build initrd on ppc64le & s390x
9b8cc458 ci: static checks: use defined target_branch
9081bee2 runtime: return error if clh's binary has not a normal stat
b10e3e22 tracing: Consolidate tracing into a new katatrace package
88e70759 osbuilder: Fix the order of checking the distro config directory
1ab72518 agent: Fix to parsing of /proc/self/mountinfo
8f76626f qemu: stop the virtiofsd specifically
da3de3c2 shim-v2: Fix `gosimple` issue on utils_test.go
305fb054 virtcontainers: Fix `gosimple` issue on client.go
89cf168c virtcontainers: Ignore a staticcheck error on cpuset.go
2cc9006c snap: Miscellaneous s390x fixes
28b2c629 runtime: Use CC=gcc on SUSE s390x too
cfd690b6 virtcontainers: Use virtio-blk-ccw on s390x
8758ce26 agent: Enable virtio-blk-ccw
a33d6bae forwarder: Add dump only option
4c809a53 shimv2: fix the issue of leaking the hypervisor processes
d08603be runtime: Remove the version check for cloud hypervisor
2c943012 agent: fix wrong regular exp to fetch guest-cid
e6b1766f agent: Cleanup config
55c5c871 agent: enhance tests of execute_hook
bd595124 runtime: add spans and attributes for agent/mount
65d2fb5d agent: remove instrument attribute for some simple functions
cfb8139f agent: add more instruments for RPC calls
ae46e7bf runtime: pass span context to agent in ttRPC client
66dd8719 runtime: refact virtcontainers/pkg/oci
d671f789 agent: fix the issue of convert OCI spec to RPC spec
f607641a shimv2: fix the issue bring by updating containerd vendor
79e632bc version: update the cri-containerd to v1.5.2
32c9ae13 shimv2: update containerd vendor
aa264f91 agent: update netlink libraries
34bdddbe docs: Fix url in virtiofs documentation
3e8a07c4 tools: agent-ctl: Fix build failure
f6294226 cargo: Use latest nix crate for all Rust code bases
064dfb16 runtime: Add "watchable-mounts" concept for inotify support
3f0f1ceb docs: inotify: add initial documentation
6a93e5d5 agent: Initial watchable-bind implementation
57c0cee0 runtime: Cleanup mountSharedDirMounts, shareFile parameters
772c117d kernel: Add Secure Execution guest
f35ba94d packaging: Support Podman in QEMU build
8310a3d7 virtcontainers: Don't fail memory hotplug
ecd13ec4 docs: Update QAT docs with newer driver version
a822cdf6 osbuilder: Update QAT driver version
6a1a051c runtime: report finish time in containers stats
fe0085ca docs: Set LIBC=gnu for s390x too
08984b6e docs: Update urls for Documentation Requirements document
b3623a2c shimv2: fix the issue of leaking wait goroutines
2322f935 runtime: update default machine type to q35
11f9a914 docs: fix brackets usage error for developer guide
1316fa53 docs: Fix typos in Developer Guide
ac6b9c53 runtime: Hot-plug virtio-mem device on PCI bridge
789a5954 virtcontainers: Remove the pc machine
caf5760c runtime: Update golang proto code
bd20701f docs: Update kata-deploy urls for installation document
a9aa36ce docs: Update url for installation guides
ecdd137c runtime: do not hot-remove PMEM devices
000049b6 agent: delete some lint attributes
3f39df0d qemu: Add nvdimm read-only file support
23d31d5a ci: snap: Fetch history to all branches and tags
2022c64f runtime: using detail propertites instead of function name in log field
361bee91 runtime/virtcontrainers: fix alignment structures
6be8bf5c docs: update annotations documentation
7834f412 virtcontainers: change memory_offset to uint64
bd27f7ba agent: Sort PROPAGATION and OPTIONS alphabetically to scan easily
ad06eb90 containerd-shim-v2: Skip TestIoCopy unit test
ea9bb8e9 ppc64le: Adding test for appendProtectionDevice
799cb272 agent: Upgrade mio to v0.7.13 to fix epoll_fd leak problem
45fd58d1 osbuilder: fix log message that is not error but seems like an error
2fb176dd docs: Update url for breaking compatibility
601e2b65 docs: Remove docker support with kata 2.x and sysctls
be316945 virtcontainers: Fix TestQemuAmd64AppendProtectionDevice()
240aae96 docs: Update README for runtime documentation
8825bb29     agent: Update rust version for tokio
cabddcc7 tracing: Make runHooks() span creation return context
e544779c agent: Add some mount options
85c40001 versions: Upgrade to cloud-hypervisor v16.0
b26d5b1d virtcontainers: Support SEV
81c6e4ca runtime/vendor: add github.com/intel-go/cpuid
a918c46f test: Add a unit test for ioCopy()

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 17:52:21 +02:00
Fabiano Fidêncio
3a9ecbcca5 Merge pull request #2231 from liubin/fix/2230-register-defer-callback-at-early-stage
runtime: Register defer function at early stage
2021-07-14 17:50:48 +02:00
Fabiano Fidêncio
2f573bceaf Merge pull request #2223 from fidencio/wip/add-vendor-check-to-the-static-checks
Ensure the go vendored code is up-to-date and that we actually can call `cargo vendor` on every pull-request
2021-07-14 16:00:55 +02:00
Fabiano Fidêncio
e386069158 static-checks: Restrict static checks to go 1.15 and 1.16
Seems that we get different results when running it with go 1.13.
Instead of figuring out why it doesn't work as expected with an EOL
version of go, let's just not run the tests on go versions that are
already dead.

https://endoflife.date/go

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 14:00:00 +02:00
Fabiano Fidêncio
f4fbf723e1 runtime: Update vendored code
The go vendored code is not up-to-date and the newly added check for
that caught this up as part of
https://github.com/kata-containers/kata-containers/pull/2223/checks?check_run_id=3056830309

Let's take advantage of the `make vendor` target and update the vendored
code. :-)

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
a20074d45c static-checks: Check the vendored code
Let's ensure we always have the go vendored code up-to-date and that the
rust vendor does actually work.

Fixes: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
ac8f972e4b build: Add make vendor
Add a top-level `vendor` entry, which will help us when adding the
vendor check as part of the static checks.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
f9643d83fb agent-ctl: Add make vendor
This has a similar intent as the go code, but not totally equal.  For
the go code we want to ensure that the vendored code is up-to-date,
while here we want to ensure that `cargo vendor` actually works.

We happened to release a few tarballs where `cargo vendor` didn't work
and it causes some pain for downstream maintainers.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
5e69b498ed trace-forwarder: Add make vendor
This has a similar intent as the go code, but not totally equal.  For
the go code we want to ensure that the vendored code is up-to-date,
while here we want to ensure that `cargo vendor` actually works.

We happened to release a few tarballs where `cargo vendor` didn't work
and it causes some pain for downstream maintainers.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
a104f13230 agent: Add make vendor
This has a similar intent as the go code, but not totally equal.  For
the go code we want to ensure that the vendored code is up-to-date,
while here we want to ensure that `cargo vendor` actually works.

We happened to release a few tarballs where `cargo vendor` didn't work
and it causes some pain for downstream maintainers.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:41 +02:00
Fabiano Fidêncio
579b3f34c2 runtime: Add make vendor
Let's add this target so we can actually enforce, as part of the static
checks (which will be added in a follow-up commit), that our vendored go
code is up-to-date.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:40 +02:00
Fabiano Fidêncio
930ca55d02 runtime: Add make handle_vendor
This will help us to ensure that we always update the vendored code when
needed.   Right now we've been lacking behind and we tend to realise
something change during the next mandatory update, which is not exactly
optimal.

Related: #2159

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-14 13:59:40 +02:00
Fabiano Fidêncio
79977a25ec Merge pull request #2102 from devimc/2021-06-23/golang1.16
ci: add golang 1.16 to the CI
2021-07-14 13:59:07 +02:00
bin
39546a1070 runtime: delete not used functions
Delete some not used functions in sandbox.go

Fixes: #2230

Signed-off-by: bin <bin@hyper.sh>
2021-07-14 19:42:50 +08:00
Tim Zhang
38dcdc3d91 Merge pull request #2189 from liubin/2187
Update outdated comments and do some minor reworks
2021-07-14 17:39:52 +08:00
bin
d0bc148fe0 runtime: Register defer function at early stage
Register defer function at early stage ensure that
it can be called if the startSandbox fails.

Fixes: #2230

Signed-off-by: bin <bin@hyper.sh>
2021-07-14 17:20:53 +08:00
bin
350acb2d6e virtcontainers: refactoring code for error handling in sandbox
Use a defined error variable replade inplace error, and shortcut
for handling errors returned from function calls.

Fixes: #2187

Signed-off-by: bin <bin@hyper.sh>
2021-07-14 14:28:58 +08:00
bin
858f39ef75 virtcontainers: update wrong comments for code
Some comments/URL are old or wrong, update them
to the correct ones.

Fixes: #2187

Signed-off-by: bin <bin@hyper.sh>
2021-07-14 14:28:57 +08:00
bin
e0a19f6a16 virtcontainers: update API documentation
Some functions add context as its first parameter,
the documentation should update.

Fixes: #2187

Signed-off-by: bin <bin@hyper.sh>
2021-07-14 14:28:57 +08:00
Julio Montes
8d6dd2ad61 snap: support golang 1.16.x
Fix build process, set GO111MODULE environment variable to "auto"

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-07-13 12:22:33 -05:00
Julio Montes
a48dc93fd4 versions: update newest golang version
update newest golang version to 1.16.5

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-07-13 12:22:33 -05:00
Julio Montes
3799679109 ci: add 1.16 to the list of golang versions to test
Add 1.16 to the list of golang versions to test

fixes #2101

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-07-13 12:22:33 -05:00
Jakob Naucke
67dfb0b922 Merge pull request #2219 from Jakob-Naucke/snap-390-ppc-initrd
snap: Build initrd on ppc64le & s390x
2021-07-13 12:17:14 +02:00
Fabiano Fidêncio
bfa8fe3183 Merge pull request #2216 from snir911/static_checks_fix
ci: static checks: use defined target_branch
2021-07-13 10:17:15 +02:00
Fabiano Fidêncio
8c4dd3b421 Merge pull request #2199 from Tim-Zhang/tracing-enhance
trace-forwarder: Add option rustflags, target, build-type for the make
2021-07-13 10:16:21 +02:00
Fabiano Fidêncio
e27080b706 Merge pull request #2221 from jodh-intel/action-honour-force-skip-ci
CI: Honour force-skip-ci label
2021-07-13 08:25:02 +02:00
Tim Zhang
6999dccaa8 trace-forwarder: Add option rustflags, target, build-type for the make
Support rust-flags, target and build-type.

Fixes: #2215

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-07-13 11:35:46 +08:00
Eric Ernst
feeb1ef8b1 Merge pull request #2212 from lifupan/fix_virtiofsd
qemu: stop the virtiofsd specifically
2021-07-12 13:56:04 -07:00
Chelsea Mafrica
61b1a6732b Merge pull request #2179 from bporter816/bporter816/refactor-tracing
tracing: Consolidate tracing into a new katatrace package
2021-07-12 12:42:01 -04:00
James O. D. Hunt
7db8a85a1f CI: Honour force-skip-ci label
If a PR has the `force-skip-ci` label set, don't run the static tests.

Fixes: #2220.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2021-07-12 16:11:55 +01:00
Jakob Naucke
007a656173 snap: Build initrd on ppc64le & s390x
instead of image, does not require privileged containers since `losetup`
is not used and is thus more portable for various build environments.

Fixes: #2218
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-07-12 15:17:30 +02:00
Snir Sheriber
9b8cc4581d ci: static checks: use defined target_branch
Fixes: #2214
Signed-off-by: Snir Sheriber <ssheribe@redhat.com>
2021-07-12 15:38:37 +03:00
Tim Zhang
6c39c353e6 Merge pull request #2209 from liubin/fix/2208-log-error
runtime: return error if clh's binary doesn't have a normal stat
2021-07-12 15:49:29 +08:00
bin
9081bee2fd runtime: return error if clh's binary has not a normal stat
When checking clh's binary path if valid, return error even
though the error is not a IsNotExist error.

And add errors to log filed when errors occurred.

Fixes: #2208

Signed-off-by: bin <bin@hyper.sh>
2021-07-12 11:16:35 +08:00
Benjamin Porter
b10e3e22b5 tracing: Consolidate tracing into a new katatrace package
Removes custom trace functions defined across the repo and creates
a single trace function in a new katatrace package. Also moves
span tag management into this package and provides a function to
dynamically add a tag at runtime, such as a container id, etc.

Fixes #1162

Signed-off-by: Benjamin Porter <bporter816@gmail.com>
2021-07-11 14:19:51 -05:00
Fabiano Fidêncio
c8f32936d3 Merge pull request #2149 from ManaSugi/fix-order-check-dir
osbuilder: Fix the order of checking the distro config directory
2021-07-11 18:28:32 +02:00
Manabu Sugimoto
88e7075929 osbuilder: Fix the order of checking the distro config directory
Check if the distro config directory exists before using the directory

Fixes: #2148

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-07-11 15:24:25 +09:00
Fabiano Fidêncio
8c921e69ec Merge pull request #2183 from dgibson/mountinfo-misparse
agent: Fix to parsing of /proc/self/mountinfo
2021-07-10 13:07:12 +02:00
David Gibson
1ab72518b3 agent: Fix to parsing of /proc/self/mountinfo
get_mounts() parses /proc/self/mountinfo in order to get the mountpoints
for various cgroup filesystems.  One of the entries in mountinfo is the
"device" for each filesystem, but for virtual filesystems like /proc, /sys
and cgroups, the device entry is arbitrary.  Depending on the exact rootfs
setup, it can end up being "-".

This breaks get_mounts() because it uses " - " as a separator.  There
really is a " - " separator in mountinfo, but in this case the device entry
shows up as a second one.  Fix this, by changing a split to a splitn, which
will effectively only consider the first " - " in the line.

While we're there, make the warning message more useful, by having it
actually show which line it wasn't able to parse.

fixes #2182

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
2021-07-10 19:30:27 +10:00
fupan.lfp
8f76626fd6 qemu: stop the virtiofsd specifically
We'd better stop the virtiofsd specifically after stop qemu,
instead of depending on the qemu's termination to notify virtiofsd
to exit.

Fixes: #2211

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-07-10 17:26:19 +08:00
Fabiano Fidêncio
75356967c6 Merge pull request #2203 from fidencio/wip/fix-static-checks
runtime: Fix lint issues
2021-07-10 10:43:33 +02:00
Fabiano Fidêncio
da3de3c2eb shim-v2: Fix gosimple issue on utils_test.go
For some reason our static check started to get opinionated about code
that's been there for ages.

One of the suggestions is to improve:

```
INFO: Running golangci-lint on /home/fidencio/go/src/github.com/kata-containers/kata-containers/src/runtime/containerd-shim-v2
utils_test.go:76:36: S1039: unnecessary use of fmt.Sprintf (gosimple)
	testDir, err = ioutil.TempDir("", fmt.Sprintf("shimV2-"))
```

And that's what this PR is about.

Fixes: #2204

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-09 17:24:51 +02:00
Fabiano Fidêncio
305fb0547d virtcontainers: Fix gosimple issue on client.go
For some reason our static check started to get opinionated about code
that's been there for ages.

One of the suggestions is to improve:
```
INFO: Running golangci-lint on /home/fidencio/go/src/github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/agent/protocols/client
client.go:431:2: S1017: should replace this `if` statement with an unconditional `strings.TrimPrefix` (gosimple)
	if strings.HasPrefix(sock, "mock:") {
```

And that's what this PR is about.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-09 17:18:08 +02:00
Fabiano Fidêncio
89cf168c92 virtcontainers: Ignore a staticcheck error on cpuset.go
First of all, cpuset.go just comes from kubernetes and we shouldn't be
doing much with this file apart from updating it every now and then
(but that's material for another PR).

Right now, due to some change on the static checks we use as part of our
CI, we started getting issues as:
```
INFO: Running golangci-lint on /home/fidencio/go/src/github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/cpuset
cpuset.go:60:2: SA4005: ineffective assignment to field Builder.done (staticcheck)
	b.done = true
```

For those, let's just ignore the lint and move on.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-07-09 17:17:12 +02:00
Jakob Naucke
f793b28dfd Merge pull request #2193 from Jakob-Naucke/snap-s390x
snap: Miscellaneous s390x fixes
2021-07-09 11:08:25 +02:00
Jakob Naucke
9577e54e2a Merge pull request #2168 from Jakob-Naucke/fix-cc-suse-s390x
runtime: Use CC=gcc on all RPM-based s390x
2021-07-09 11:07:35 +02:00
Jakob Naucke
e8ec18a9d8 Merge pull request #2027 from Jakob-Naucke/virtio-blk-ccw
s390x: Enable virtio-blk-ccw
2021-07-08 18:22:44 +02:00
James O. D. Hunt
7a481c3f4f Merge pull request #2133 from jodh-intel/trace-forwarder-dump-only
forwarder: Add dump only option
2021-07-08 15:17:36 +01:00
Jakob Naucke
2cc9006c26 snap: Miscellaneous s390x fixes
- Ported from https://github.com/kata-containers/tests/pull/3612:
  Install protobuf-compiler for agent build on ppc64le & s390x
- Fixes in image target for ppc64le & s390x
  - Install image instead of initrd since it's preferred
  - Use Ubuntu as base since Alpine requires a musl agent (cannot be
    built on ppc64le & s390x because there is no such Rust target)
- Ported from
  https://github.com/kata-containers/kata-containers/pull/1265:
  Fix vmlinux install path
- Install libseccomp-dev on all architectures, not just x86_64

Fixes: #2192
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-07-08 15:02:47 +02:00
Jakob Naucke
28b2c629e3 runtime: Use CC=gcc on SUSE s390x too
This setting is required, as it is on Fedora-likes.

Fixes: #2167
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-07-08 15:01:32 +02:00
Jakob Naucke
cfd690b638 virtcontainers: Use virtio-blk-ccw on s390x
if virtio-blk-pci were to be used

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-07-08 14:59:47 +02:00
Jakob Naucke
8758ce26b7 agent: Enable virtio-blk-ccw
Forward-port of https://github.com/kata-containers/agent/pull/600.
Enable virtio-blk-ccw devices in agent (virtio-blk for s390x, already
enabled in runtime).

Fixes: #2026

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-07-08 14:59:47 +02:00
James O. D. Hunt
a33d6bae63 forwarder: Add dump only option
Added a `--dump-only` option which disables forwarding of trace spans.
This essentially makes the forwarder a NOP but can be useful for testing
purposes.

Fixes: #2132.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2021-07-08 13:12:17 +01:00
Fabiano Fidêncio
432296ae7a Merge pull request #2197 from lifupan/fix_leak_hypervisor
shimv2: fix the issue of leaking the hypervisor processes
2021-07-08 13:49:37 +02:00
Fabiano Fidêncio
cf4a63f1e5 Merge pull request #2137 from likebreath/0628/clh_remove_version_check
runtime: Remove the version check for cloud hypervisor
2021-07-08 10:14:18 +02:00
fupan.lfp
4c809a53d2 shimv2: fix the issue of leaking the hypervisor processes
Since we only send an shutdown qmp command to qemu when do
stopSandbox, and didn't wait until qemu process's exit, thus
we'd better to make sure it had exited when shimv2 terminated.
Thus here to do the last cleanup of the hypervisor.

Fixes: #2198

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-07-08 15:43:58 +08:00
Bo Chen
d08603bebb runtime: Remove the version check for cloud hypervisor
It looks like the version check for cloud hypervisor (clh) was added
initially when clh was actively evolving its API. We no longer need the
version check as clh API has been fairly stable for its recent releases.

Fixes: #1991

Signed-off-by: Bo Chen <chen.bo@intel.com>
2021-07-06 18:42:59 -07:00
Julio Montes
7d3cf04f29 Merge pull request #2125 from LiangZhou-CTY/patch-1
agent: fix wrong regular exp to fetch guest-cid
2021-07-06 07:01:43 -05:00
Tim Zhang
3f1aa8ff91 Merge pull request #2084 from liubin/fix/2082-refactor-vc-pkg-oci
runtime: refact virtcontainers/pkg/oci
2021-07-06 19:14:10 +08:00
Bin Liu
26985bbfff Merge pull request #2173 from Tim-Zhang/enhance-test-execute-hook
agent: enhance tests of execute_hook
2021-07-05 14:36:45 +08:00
Liang Zhou
2c9430123e agent: fix wrong regular exp to fetch guest-cid
Fix the incorrect regular expression to fetch the guest context ID.
In " [^,][^,]* ", [^,]* will match to the next ",",
which is after "socket",  so finally got incorrect result.
Use egrep -o "guest-cid=[0-9]*" instead.

Fixes: #2124

Signed-off-by: Liang Zhou <zhoul110@chinatelecom.cn>
2021-07-05 09:46:03 +08:00
Fabiano Fidêncio
015b3baf06 Merge pull request #2178 from mxpv/config
agent: Cleanup config
2021-07-03 09:51:16 +02:00
Fupan Li
2de9c5b41d Merge pull request #1969 from liubin/feature/1968-pass-span-context-to-agent
Pass span context from runtime to agent to get a full trace #1968
2021-07-03 09:31:02 +08:00
Maksym Pavlenko
e6b1766f6b agent: Cleanup config
This commit clean up config parsing and testing code to make it a bit more easy to maintain.
- Adds `with_context` from anyhow to include the underlying error. This helps to understand what exactly went wrong.
- Uses ensure and bail as a shorter alternative for `if` checks.
- TestData in test_parse_cmdline is now implements Default to reduce boilerplate code
- Remove `make_err` as it doesn’t make any sense.

Fixes: #2177

Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
2021-07-02 14:28:43 -07:00
Tim Zhang
55c5c871d2 agent: enhance tests of execute_hook
Use which to find the full path of exe before run execute_hook
to avoid error: 'No such file or directory'

Fixes: #2172

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-07-02 14:30:56 +08:00
bin
bd5951247c runtime: add spans and attributes for agent/mount
Add more spans and attributes for agent setup, add devices,
and mount volumes.

Fixes: #1968

Signed-off-by: bin <bin@hyper.sh>
2021-07-02 10:07:28 +08:00
bin
65d2fb5d11 agent: remove instrument attribute for some simple functions
For some simple functions that only process memory data(list/hashmap),
they don't need to be instrumented.

And sometime they may generate non-parent spans, if they are called from
daemon-style "threads".

Fixes: #1968

Signed-off-by: bin <bin@hyper.sh>
2021-07-02 10:07:28 +08:00
bin
cfb8139f36 agent: add more instruments for RPC calls
All RPC calls can get parent span context,
and create new sub-spans for the full trace.

Fixes: #1968

Signed-off-by: bin <bin@hyper.sh>
2021-07-02 10:07:28 +08:00
bin
ae46e7bf97 runtime: pass span context to agent in ttRPC client
Pass span context through ttRPC metadata, that
agent can get parent from the context to create
new sub-spans.

Fixes: #1968

Signed-off-by: bin <bin@hyper.sh>
2021-07-02 10:07:14 +08:00
Fabiano Fidêncio
3fe0af6a9b Merge pull request #2152 from liubin/fix/2111-update-netlink-libs
agent: update netlink libraries
2021-07-01 12:01:35 +02:00
Bin Liu
15d37d5823 Merge pull request #2040 from lifupan/upgrade_containerd
shimv2: update containerd vendor
2021-07-01 15:55:07 +08:00
bin
66dd8719e3 runtime: refact virtcontainers/pkg/oci
Use common functions wrapping logic of getting values
from annotations, parsing bool/uint32/uint64 and setting
to struct fields.

Fixes: #2082

Signed-off-by: bin <bin@hyper.sh>
2021-07-01 10:14:47 +08:00
Eric Ernst
d0ad388721 Merge pull request #2065 from ManaSugi/format-golang-proto
runtime: Format golang proto code
2021-06-30 11:08:57 -07:00
fupan.lfp
d671f78952 agent: fix the issue of convert OCI spec to RPC spec
Since the rpc spec used an interface to represen the ErrnoRet,
thus the transform function of OCItoGRPC should take care of
this case.

Depends-on: github.com/kata-containers/tests#3629

Fixes: #1441

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-06-30 22:56:59 +08:00
fupan.lfp
f607641a6e shimv2: fix the issue bring by updating containerd vendor
Fix the mismatch bring by the upgrading of vendor of  containerd,
cgroup and runtime spec.

Fixes: #1441

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-06-30 22:56:51 +08:00
fupan.lfp
79e632bc23 version: update the cri-containerd to v1.5.2
Upgrade the cri-containerd to v1.5.2 for CI.

Fixes: #1441

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-06-30 22:53:35 +08:00
fupan.lfp
32c9ae1388 shimv2: update containerd vendor
Since the latest containerd's shimv2 had changed the socket
from abstract unix socket to path unix socket, thus we'd
better to update the vendor to match with the latest containerd.

containerd from v1.3.9, v1.4.3 and v1.5.0 used the path unix socket
instead of abstract socket, thus kata wouldn's support the
containerd's version older than them.

Fixes: #1441

short logs:

15d9703d6 Remove ARM64 releases from release notes
    5d2e8e86d Revert "Release artifacts for Linux ARM64"
    7942ae68b Revert "Specify seccomp target arch for CC"
    3187b6dc8 tests: Adds consumed memory stats test
    969ec8949 Specify seccomp target arch for CC
    c19b7b64d RELEASES.md: recommend alternatives for deprecated
features
    8a62aa1c3 Deprecate built-in aufs snapshotter
    4e7915f80 CI: allow Go 1.13 for Docker/Moby compatibility
    8e589e873 Vagrantfile: update to Fedora 34
    5847340a7 tests: Refactors container image usage
    9f43eade6 Prepare v1.5.0-rc.3 release notes
    4c7b960cb prow needs some additional setup for docker buildx
    2e4c1d4b7 Use the multi-arch version of the test images
    4e00c4b65 integration tests needs lsof
    177273680 Add script to build test images
    1b5d59dfe Add multi-arch support for test images
    78e529727 add integration tests
    2b0e6cdd4 Separate jobs for build and test for openlab/arm64
    cdd075853 Release artifacts for Linux ARM64
    efcb18742 Add unit tests for PID NamespaceMode_TARGET validation
    b48f27df6 Support PID NamespaceMode_TARGET
    909660ea9 process: use the unbuffered channel as the done signal
    0f332dadd Update cgroups for regenerated protos
    391b123a5 adds quiet option for ref
    ab1654d0e Fix PushHandler cannot push image that contains duplicated
blobs
    00f8d32ef add not found debug out for check cmd; update usage
    55734b1c5 Prepare 1.5.0-rc.2 release notes
    3ef337ae3 Update containerd vendors to tags
    fbe1e140f Update Go to 1.16.3
    c1d1edbad gha: use sudo -E in some places to prevent dropping
env-vars
    7966a6652 Cleanup code
    5d79d3adb go.mod: update kubernetes to v1.20.6
    1c03c377e go.mod: github.com/containerd/fifo v1.0.0
    12a2a2108 go.mod: github.com/google/uuid v1.2.0
    3292ea586 pkg/seccomp: use sync.Once to speed up IsEnabled
    00b5c99b1 pkg/seccomp: simplify IsEnabled, update doc
    6dd29c25f go.mod: github.com/containerd/aufs
    330a2a809 go.mod: github.com/containerd/zfs
    34780d67a runtime/shim: check the namespace flag first
    c3dde8c4b freebsd: add zfs to the default plugins
    b431fe4fc freebsd: don't run shim delete in deleted dir
    1f4192daf freebsd: exclude v1 runtimes
    cb1580937 metadata: improve deleting a non-empty namespace's error
message
    5bf84034d Remove junit test result processor
    b83d04f91 Add variable names to runtime's interface definitions
    993b86399 Add shim start opts
    9e576b889 Optimize backoff
    5c02688b5 converter: use OpenWriter helper function
    fcf3b275f Add lock for ListPids
    fdb76f55d Fix backword-compatibility issue of non-versioned config
file
    d21fe4625 adds log for each failed host and status not found on host
    8a4cbabc6 Reimport windows layers when comitting snapshots
    2de38a926 fix(windows): create debug npipe failure
    41fc516a2 docs/rootless.md: recommend "easy way" over "hard way"
    864a3322b go.mod: github.com/containerd/go-cni v1.0.2
    ee34caccb go.mod: github.com/Microsoft/go-winio v0.4.17
    d478676d3 go.mod: github.com/containerd/imgcrypt v1.1.1
    1dd45d51c go.mod: github.com/containerd/typeurl v1.0.2
    abd4be07a fix the 404 url
    978ebbef6 Prepare 1.5.0-rc.1 release
    ce116d4c5 go.mod: github.com/containerd/imgcrypt
v1.1.1-0.20210412181126-0bed51b9522c
    0550c3233 containerd-stress: add snapshotter option for stress test
to use
    8a04bd052 address recent runtimes config confusion
    c4778fe1b go.mod: github.com/containernetworking/plugins v0.9.1
    5ce35ac39 devmapper: log pool status when mkfs fails
    75097b8ca hcsshim seems to have been updated
    9ad087947 Switch all our tests to version 2
    e96d2a5d9 Revert "remove two very old no longer used runtime
options"
    14f357b90 CI: update crun to 0.19
    294331060 go.mod: github.com/containerd/console v1.0.2
    bb6c0c2de Add more bolt utils
    0ad8c0a16 Decouple shim start from task creation
    c7504987e Implement windowsDiff.Compare via hcsshim/pkg/ociwclayer
    a64a76846 Replace inline applyWindowsLayer using hcsshim
    149fa366f Don't tease the logger with a %-less format string
    b399e2ef6 Don't lose Compare failure if aborting diff upload fails
    36bf3f0e8 go.mod: github.com/Microsoft/hcsshim v0.8.16
    8e1a8ecd8 Prepare v1.5.0-rc.0
    45df696bf Fix return event publishing error
    4bc8f692f optimize cri redirect logs
    9bc8d63c9 cri/server: use containerd/oci instead of
libcontainer/devices
    dd16b006e merge in the move to the new options type
    9144ce967 shows our runc.v2 default options in the containerd
default config
    3d20fa930 fix TestSetOOMScoreBoundaries
    4d4117415 Change CRI config runtime options type
    21ebeef74 integration: use busybox:1.32.0 since latest is
unavailable
    f9bcf4a8a add section link
    d4be6aa8f rm mirror defaults; doc registry deprecations
    7bb73da6b runtime/v2/shim: remove unused SetScore() and remove
sys.OOMScoreMaxKillable
    91e7d21ee sys: add AdjustOOMScore() utility
    44240116a sys: add boundary checks to SetOOMScore()
    ace1912bb sys: use assert for error checks in OOM tests
    6e7271522 sys: add missing pre-condition checks in tests
    badd60d3f sys: un-export runningPrivileged(), remove
runningUnprivileged()
    21a175860 go.mod github.com/klauspost/compress v1.11.13
    58c5fd09e re-enable cri test
    da998c81e move to gcr.io/k8s-staging-cri-tools test images
    8ba8533bd pkg/cri/opts.WithoutRunMount -> oci.WithoutRunMount
    92ea98eda cri-cni-release: add imgcrypt binaries (v1.1.0)
    4c1fa5719 remotes/docker: Only return "already exists" on push when
the upload was successful
    0186a329e remove two very old no longer used runtime options
    58a07754a Temporarily disable cri-tools critest
    7ae0a60fb Add OCI ref.name to unique key in remotes handler
    5ada2f74a Keep host order as defined in TOML file
    d9ff8ebef support multi-arch images for windows via ctr
    af1e2af72 ci: upload junit formatted test results
    6866b36ab Add workaround to keep docker hosts structs private
    c54d92c79 image: use generic decompressor for calculating DiffID
    1faca349e integration/client: rename package to "client"
    6fc9e4500 synchronize replace rules in integration/client go.mod
with main go.mod
    9e19a2984 Fix hosts test on Windows
    3f406d4af Cleanup vendor
    d56b49c13 Rewrite Docker hosts parser
    e1f51ba73 Use os.File#Seek() to get the size of a block device
    ddd4298a1 Migrate current TOML code to github.com/pelletier/go-toml
    499c2f7d4 Vendor github.com/pelletier/go-toml
    61c749036 integration/util: remove dependency on k8s.io/klog/v2
    d9765f7bf Extend default timeout for nested VM integration run
    5e94745f2 ctr: add --user for task exec
    f8c2f0475 remotes/ctr: allow to limit max concurrent uploads like
downloads
    4674ad7be Ignore some tests on darwin
    55450e773 Run unit tests on CI for MacOS
    311e326a1 Add CI job to cross compile all the things
    10a498c7c Update go-winio to fix compile error on armv7
    1a9c6f557 Revendor zfs to to fix integer overflow
    1fd3d12f9 `go mod tidy` the client integration test module
    da7d96ba3 Clean up WCOW layers after tests in the correct order
    9ad87b9ba adds critools-version
    72b7f4bab task: allow checkpoint on pause state
    e4b9b1038 Make CRI registry docs more clear
    ec4d7736d Increase timeout for linux integration tests
    eb7c7c71e Fix oom tests on non Linux
    708299ca4 Move RunningInUserNS() to its own package
    0886ceaea Fix reference ordering in CRI image store
    bf9db47e8 add caller info to the testHook
    305b42583 use happy-eyeballs for port-forwarding
    22ef69d77 Support HTTP debug in ctr
    01765d097 night ci fix: add packages for ubuntu 20.04
    8cdc1f13b go.mod: github.com/containerd/zfs
v0.0.0-20210322090317-0e92c2247fb7
    30e1e66e5 runtime/v2: Fix defer cleanup
    33776ada0 Use specific image for user namespaces tests
    7704fe72d Specifically mention "mkfs.ext4" on the error from the
command
    1410220d8 Fix error log when copy file
    fe787efa2 Fix error log when kill shim
    8d8c15ca5 contentproxy: ensure grpc stream is closed on commit
    6e343f25e Switch test image to a non rate-limited manifest list
    9fdc96c09 runtime/v2: add comment for checkCopyShimLogError
    24602e7a9 change default runtime for containerd-stress app
    8731888ec Re-enable CRIU tests by not using overlayfs snapshotter
    b520428b5 Fix CRIU
    4e76bcf06 gofmt -s -w all the things
    569023fd5 go.mod: github.com/containerd/nri
v0.0.0-20210316161719-dbaa18c31c14
    0e1f59e89 go.mod: github.com/containerd/zfs
v0.0.0-20210315114300-dde8f0fda960
    ffff68866 upgrade pause image to 3.5 for non-root
    88d3881e1 go.mod: github.com/containerd/fifo
v0.0.0-20210316144830-115abcc95a1d
    a22c43fa4 go.mod: github.com/containerd/aufs
v0.0.0-20210316121734-20793ff83c97
    f6f861736 go.mod: github.com/containerd/btrfs
v0.0.0-20210316141732-918d888fb676
    460b35236 go.mod: kubernetes v1.20.4
    5e484c961 runtime/v2/runc: fix the defer cleanup of the NewContainer
    e6086d9c0 Prepare release notes for v1.5.0-beta.4
    34b7a5f09 Update mailmap
    ba8f9845e move overlay-checks to an overlayutils package
    7776e5ef2 Support adding devices by dir
    d895118c7 runtime/v2/runc: fix leaking socket path
    a76cefd12 plugin status should be skip, not error
    766e7953a Change dgst to digest in debug
    4e8b2f309 rootfs: fix the error handling of the createInitLayer
    d3ad7f390 cmd/ctr: use e.g. in the command usage
    231bbdc37 cmd/ctr: fix export command
    ecb881e5e add imgcrypt stream processors to the default config
    ac2726e12 cmd/containerd: deduplicate config*.go
    9a7ca39cb defaults: add DefaultConfigDir
    8f863afd3 Use net.IP.IsLoopback() to match loopback addresses
    eabd9b98b runtime: ignore file-already-closed error if dead shim

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-06-30 22:53:24 +08:00
Fabiano Fidêncio
550029c473 Merge pull request #2060 from liubin/2059/delete-some-lint-attributes
agent: delete some lint attributes
2021-06-30 16:51:07 +02:00
Fabiano Fidêncio
7d05739f01 Merge pull request #2135 from GabyCT/topic/fixdocvirtiofs
docs: Fix url in virtiofs documentation
2021-06-30 16:47:01 +02:00
bin
aa264f915f agent: update netlink libraries
Update rtnetlink to use crate.io to make cargo vendor work.
Add vendor/ to .gitignore.

Fixes: #2111

Signed-off-by: bin <bin@hyper.sh>
2021-06-30 22:39:50 +08:00
Gabriela Cervantes
34bdddbeb5 docs: Fix url in virtiofs documentation
This PR updates the url for virtiofs documentation.

Fixes #2134

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-30 13:48:29 +00:00
Fabiano Fidêncio
d78e396a33 Merge pull request #2127 from sameo/topic/agent-ctl-build-fix
tools: agent-ctl: Fix build failure
2021-06-30 11:47:02 +02:00
Fabiano Fidêncio
7d37fbfdfb Merge pull request #2115 from sameo/topic/rust-nix
cargo: Use latest nix crate for all Rust code bases
2021-06-28 08:18:53 +02:00
Fabiano Fidêncio
a8bb8269fe Merge pull request #2047 from Jakob-Naucke/s390x-skip-hotplug
virtcontainers: Don't fail memory hotplug
2021-06-28 08:18:31 +02:00
Eric Ernst
69bf7e7519 Merge pull request #1964 from egernst/inotify
Add "watchable-mounts" concept to allow for  inotify support of specific types of mounts.
2021-06-25 12:59:04 -07:00
Samuel Ortiz
3e8a07c415 tools: agent-ctl: Fix build failure
Two nix packages with the same version are specified from the lock file.

Fixes #2126

Signed-off-by: Samuel Ortiz <samuel.e.ortiz@protonmail.com>
2021-06-25 12:11:38 +02:00
Samuel Ortiz
f6294226e8 cargo: Use latest nix crate for all Rust code bases
Our dependencies already bring several versions of nix, we should avoid
adding even more fragementation.

Fixes #2114

Signed-off-by: Samuel Ortiz <samuel.e.ortiz@protonmail.com>
2021-06-25 03:38:37 +02:00
Eric Ernst
064dfb164b runtime: Add "watchable-mounts" concept for inotify support
To workaround virtiofs' lack of inotify support, we'll special case
particular mounts which are typically watched, and pass on information
to the agent so it can ensure that the mount presented to the container
is indeed watchable (see applicable agent commit).

This commit will:
 - identify watchable mounts based on file count and mount source
 - create a watchable-bind storage object for these mounts to
   communicate intent to the agent
 - update the OCI spec to take the updated watchable mount source into account

Unit tests added and updated for the newly introduced
functionality/functions.

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-06-24 10:07:06 -07:00
Eric Ernst
3f0f1ceba0 docs: inotify: add initial documentation
We're introducing a workaround for enabling users to utilize inotify on
mounts that are backed by virtiofs. Let's add some documentation on how
this work.

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-06-24 10:07:06 -07:00
Maksym Pavlenko
6a93e5d593 agent: Initial watchable-bind implementation
Add support for watchable-bind storage driver. When watchable-bind storage
is present, the agent will create a watchable path in a tmpfs, and poll the
watchable-bind source to keep this new mount-point up to date.

This poll will allow the agent to present the mount-point to the
container, allowing for inotify usage by the container workload.

If a mount becomes too large, either in file count or in overall size,
we want to stop treating it as watchable, and instead just treat as a
bindmount. This'll help avoid DoS by growing tmpfs too large, as well
as limiting time spent scanning files. If a watchable-bind grows beyond
8 files (arbitrary sane number for certs/secrets) or 1MB (limit on ConfigMap size),
we treat it as a normal bind.

Fixes: #1879

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
Signed-off-by: Samuel Ortiz <samuel.e.ortiz@protonmail.com>

agent: watcher: SandboxStorages check loop cleanup
2021-06-24 10:07:06 -07:00
Eric Ernst
57c0cee0a5 runtime: Cleanup mountSharedDirMounts, shareFile parameters
There's no reason to pass the paths; they can be
determined when they are actually used.

Let's make the return values more comparable to the other mount handling
functions (we'll add storage object in future commit), and pass the mount maps as
function parameters.

...No functional changes here...

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-06-24 10:07:06 -07:00
Chelsea Mafrica
ac0bd57748 Merge pull request #2003 from cmaf/fix-span-runHooks
tracing: Make runHooks() span creation return context
2021-06-24 07:50:42 -07:00
Samuel Ortiz
9ab6e07330 Merge pull request #2107 from Jakob-Naucke/protvirt-kernel
kernel: Add Secure Execution guest
2021-06-24 15:29:15 +02:00
Jakob Naucke
3b356be87c Merge pull request #2068 from Jakob-Naucke/podman-qemu
packaging: Support Podman in QEMU build
2021-06-24 15:16:30 +02:00
Fabiano Fidêncio
bb4a256a30 Merge pull request #2104 from eadamsintel/update-qat-version
Update qat version
2021-06-24 11:41:14 +02:00
Jakob Naucke
772c117d4e kernel: Add Secure Execution guest
Add `CONFIG_PROTECTED_VIRTUALIZATION_GUEST=y` to s390's guest kernel
config, which enables running with a secure image (as generated by
s390-tools' `genprotimg`).

Fixes: #2106
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-24 11:34:28 +02:00
Jakob Naucke
f35ba94d30 packaging: Support Podman in QEMU build
Use Podman instead of Docker when $USE_PODMAN is set. This enables
running with Podman, e.g. to import images for CRI-O.

Fixes: #2067

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-24 11:08:47 +02:00
Jakob Naucke
8310a3d70a virtcontainers: Don't fail memory hotplug
Architectures that do not support memory hotplugging will fail when
memory limits are set because that amount is hotplugged. Issue a warning
instead. The long-term solution is virtio-mem.

Fixes: #1412
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-24 10:58:06 +02:00
Fabiano Fidêncio
5a22e0e3b1 Merge pull request #2093 from Jakob-Naucke/doc-s390x-gnu
docs: Set LIBC=gnu for s390x too
2021-06-24 08:08:48 +02:00
Eric Adams
ecd13ec43d docs: Update QAT docs with newer driver version
This updates the QAT docs to the latest driver version.

Fixes: #2103

Signed-off-by: Eric Adams <eric.adams@intel.com>
2021-06-23 23:51:20 +00:00
Eric Adams
a822cdf64d osbuilder: Update QAT driver version
This updates the QAT driver version to the latest version.

Fixes: #2103

Signed-off-by: Eric Adams <eric.adams@intel.com>
2021-06-23 23:49:19 +00:00
Fabiano Fidêncio
f5d9d89b73 Merge pull request #2089 from lifupan/fix_wait
shimv2: fix the issue of leaking wait goroutines
2021-06-23 23:06:11 +02:00
Fabiano Fidêncio
c47a597568 Merge pull request #2097 from littlejawa/issue_crio_ctr_6_main
runtime: report finish time in containers stats
2021-06-23 22:53:12 +02:00
GabyCT
a1d6c3c551 Merge pull request #2077 from davidhay1969/debug_doc_change
docs: Fix typos in Developer Guide
2021-06-23 14:11:48 -05:00
GabyCT
d7ce78cf6a Merge pull request #2095 from GabyCT/topic/fixDocuRe
docs: Update urls for Documentation Requirements document
2021-06-23 11:11:21 -05:00
Julien Ropé
6a1a051c65 runtime: report finish time in containers stats
Make sure we report the exit time for the container when we answer a "Status" request.

Fixes: #2096

Signed-off-by: Julien Ropé <jrope@redhat.com>
2021-06-23 17:36:47 +02:00
Jakob Naucke
fe0085ca55 docs: Set LIBC=gnu for s390x too
The Developer Guide instructs to install the agent from
`${ARCH}-unknown-linux-${LIBC}`, where `$LIBC` is set to `gnu` for
ppc64le (because Rust has no musl target there). The same is true for
s390x. Also set this for s390x.

Fixes: #2092

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-23 17:25:33 +02:00
Gabriela Cervantes
08984b6e31 docs: Update urls for Documentation Requirements document
This PR updates the proper urls for the Documentation Requirements document.

Fixes #2094

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-23 15:16:13 +00:00
Fabiano Fidêncio
951bb6a78f Merge pull request #2086 from liubin/fix/2085-change-machinetype-to-q35
runtime: update default machine type to q35
2021-06-23 14:26:40 +02:00
fupan.lfp
b3623a2c40 shimv2: fix the issue of leaking wait goroutines
After create an container/exec successfully, containerd
would wait it immediately, and if start it failed, there
is no chance to send value to exitCh, thus the wait goroutine
would blocked for ever and had no chance to exit.

Fixes: #2087

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-06-23 19:29:26 +08:00
Jakob Naucke
2a1b6d376a Merge pull request #2080 from focus-zhaos/initrd-doc
docs: fix brackets usage error for developer guide
2021-06-23 13:13:43 +02:00
bin
2322f935c1 runtime: update default machine type to q35
The machine type of pc is deleted, generated configuration
should update too.

Fixes: #2085

Signed-off-by: bin <bin@hyper.sh>
2021-06-23 17:08:44 +08:00
focus-zhaos
11f9a914b9 docs: fix brackets usage error for developer guide
Fixed 3 errors which misused the bracket to substitute parameter for initrd-img creation at the developer guide.

Fixes: #2079

Signed-off-by: focus-zhaos <zhaos@nbjl.nankai.edu.cn>
2021-06-23 17:01:57 +08:00
Dave Hay
1316fa5300 docs: Fix typos in Developer Guide
- Adding missing `$` symbols to 3 references to `sandbox_id` variable
- Adding missing `'` symbol to QEMU-related `socat` command

Fixes #2075

Signed-off-by: Dave Hay <david_hay@uk.ibm.com>
2021-06-23 08:46:43 +01:00
David Gibson
c0cc6d5978 Merge pull request #1954 from marcel-apf/remove-pc
Remove the pc machine
2021-06-23 12:00:05 +10:00
Julio Montes
b9e611e363 Merge pull request #2066 from devimc/2021-06-17/fixTeardownPmem
runtime: do not hot-remove PMEM devices
2021-06-22 09:06:59 -05:00
Marcel Apfelbaum
ac6b9c53d2 runtime: Hot-plug virtio-mem device on PCI bridge
Currently the virtio-mem device is hotplugged on the root bus.
This doesn't work for PCIe machines like q35.

Hotplug the virtio-mem device into the pci bridge instead.

Fixes #1953
Signed-off-by: Marcel Apfelbaum <marcel@redhat.com>
2021-06-22 12:34:48 +03:00
Marcel Apfelbaum
789a59549e virtcontainers: Remove the pc machine
Keeping around two different x86 machines has no added value
and require more tests and maintenance. Prefer the q35 machine
since it has more features and drop the pc machine.

Fixes #1953
Depends-on: github.com/kata-containers/tests#3586
Signed-off-by: Marcel Apfelbaum <marcel@redhat.com>
2021-06-22 11:54:07 +03:00
GabyCT
757ddf7b83 Merge pull request #2073 from GabyCT/topic/updateminikube
docs: Update kata-deploy urls for installation document
2021-06-21 14:13:28 -05:00
GabyCT
8bb9192e83 Merge pull request #2070 from GabyCT/topic/updateinstallurl
docs: Update url for installation guides
2021-06-21 11:37:33 -05:00
Manabu Sugimoto
caf5760c45 runtime: Update golang proto code
We should update golang proto files.
These changes are updated using libprotoc v3.6.1.

Fixes: #2064

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-06-19 18:53:56 +09:00
Gabriela Cervantes
bd20701f35 docs: Update kata-deploy urls for installation document
This PR updates the proper url for kata-deploy scripts at the
minikube installation.

Fixes #2072

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-18 18:48:56 +00:00
Gabriela Cervantes
a9aa36cebc docs: Update url for installation guides
This PR updates the correct url for kata installation guides in kata 2.x

Fixes #2069

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-18 16:48:07 +00:00
Julio Montes
ecdd137c6f runtime: do not hot-remove PMEM devices
PMEM devices cannot be hot-removed from a running VM.

fixes #2018

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-18 09:02:03 -05:00
bin
000049b69e agent: delete some lint attributes
Thes lint attributes can be deleted to keep clean code.

Fixes: #2059

Signed-off-by: bin <bin@hyper.sh>
2021-06-18 16:08:25 +08:00
snir911
1faaf5f35d Merge pull request #2000 from ManaSugi/update-mount-flags
agent: Add some mount options and sort the options alphabetically
2021-06-17 11:53:11 +03:00
Tim Zhang
90029032b4 Merge pull request #2049 from liubin/2048/fix-log-field
runtime: using detail propertites instead of function name in log field
2021-06-17 10:53:12 +08:00
Wainer Moschetta
9e6f1f7794 Merge pull request #2041 from wainersm/fix_qemu_5_2
qemu: Add nvdimm read-only file support
2021-06-16 20:48:17 -03:00
Wainer dos Santos Moschetta
3f39df0d18 qemu: Add nvdimm read-only file support
For QEMU 5.0.0 it is applied the patches/5.0.x/0002-memory-backend-file-nvdimm-support-read-only-files-a.patch
to fix an issue with the use of read-only files as backend memory of nvdimm devices. When Kata Containers bumped
to QEMU 5.2.0 that patch was left behind by mistake. In meanwhile a proper feature ("nvdimm: read-only file support")
was proposed and merged upstream (see https://mail.gnu.org/archive/html/qemu-devel/2021-01/msg00258.html).

This contain the backport of the commit 8360ebeb4f4a from QEMU master which should be applied on QEMU 5.2.0
so that feature is available to Kata Containers.

Fixes #2011

Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2021-06-16 17:03:05 -04:00
Fabiano Fidêncio
1bad9999fd Merge pull request #2051 from wainersm/hot_fix_snap_ci
ci: snap: Fetch history to all branches and tags
2021-06-16 22:41:02 +02:00
Wainer dos Santos Moschetta
23d31d5a7c ci: snap: Fetch history to all branches and tags
The snap/snapcraft.yaml set AGENT_VERSION to the current VERSION. The osbuilder script
will try to checkout the AGENT_VERSION tag. Let's ensure that all tags and branches
are fetched by the github's checkout action so the tag checkout does not fail.

Fixes #2052
Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2021-06-16 13:34:09 -04:00
bin
2022c64f94 runtime: using detail propertites instead of function name in log field
To print the correct value of kernel parameters, the log field
value should not be a function name. And for that qemuArchBase
doesn't contain debug flag, so the log contains debug/non-debug
parameters.

Fixes: #2048

Signed-off-by: bin <bin@hyper.sh>
2021-06-17 00:17:16 +08:00
Julio Montes
85bb5cffe1 Merge pull request #2017 from devimc/2021-06-11/fixPmemCSI
memory_offset must be larger than 32 bit
2021-06-16 09:10:48 -05:00
Julio Montes
361bee91f7 runtime/virtcontrainers: fix alignment structures
fix alignment of qemuArchBase and HypervisorConfig structures

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-16 07:16:49 -05:00
Julio Montes
6be8bf5c66 docs: update annotations documentation
update documentation to reflect value type of `memory_offset`

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-16 07:16:49 -05:00
Julio Montes
7834f4127f virtcontainers: change memory_offset to uint64
`memory_offset` is used to increase the maximum amount of memory
supported in a VM, this offset is equal to the NVDIMM/PMEM device that
is hot added, in real use case workloads such devices are bigger than
4G, which is the current limit (uint32).

fixes #2006

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-16 07:16:49 -05:00
Manabu Sugimoto
bd27f7bab5 agent: Sort PROPAGATION and OPTIONS alphabetically to scan easily
It's hard to visually scan over the list currently.
Therefore, we should sort the list alphabetically to scan easily.

Fixes: #1999

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-06-16 17:23:05 +09:00
snir911
fb318532b9 Merge pull request #2044 from devimc/2021-06-15/skipTestIoCopy
containerd-shim-v2: Skip TestIoCopy unit test
2021-06-16 09:59:35 +03:00
Chelsea Mafrica
6abe7caecb Merge pull request #2039 from Amulyam24/pef-tests
ppc64le: Adding test for appendProtectionDevice
2021-06-15 16:19:05 -07:00
Julio Montes
ad06eb90db containerd-shim-v2: Skip TestIoCopy unit test
TestIoCopy unit test is failing randonly, skip it until we have a fix

fixes #2043

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-15 13:17:05 -05:00
Amulya Meka
ea9bb8e9ad ppc64le: Adding test for appendProtectionDevice
Fixes: #2038

Signed-off-by: Amulya Meka <amulmek1@in.ibm.com>
2021-06-15 10:23:38 +00:00
James O. D. Hunt
685d631c4c Merge pull request #2004 from houfangdong/3849/fix-rust-version-for-tokio
agent: Update rust version for tokio
2021-06-15 11:06:37 +01:00
Fupan Li
1ab64e30aa Merge pull request #2034 from Tim-Zhang/fix-mio-epoll-fd-leak
Upgrade mio to v0.7.13 to fix epoll_fd leak problem
2021-06-15 15:33:10 +08:00
Tim Zhang
c881899903 Merge pull request #1990 from liubin/1989/fix-log-message
osbuilder: fix log message that is not error but seems like an error
2021-06-15 15:13:21 +08:00
Tim Zhang
799cb27234 agent: Upgrade mio to v0.7.13 to fix epoll_fd leak problem
Fixes: #2035
Fixes: tokio-rs/tokio/#3809

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-06-15 11:35:49 +08:00
bin
45fd58d11c osbuilder: fix log message that is not error but seems like an error
Only show checkout failed message if AGENT_VERSION is set
and the checkout is failed.

Fixes: #1989

Signed-off-by: bin <bin@hyper.sh>
2021-06-15 10:26:52 +08:00
GabyCT
2f322b8be0 Merge pull request #2032 from GabyCT/topic/fixkernelreadme
docs: Update url for breaking compatibility
2021-06-14 16:40:27 -05:00
Julio Montes
383041959d Merge pull request #2030 from GabyCT/topic/fixsys
docs: Remove docker support with kata 2.x and sysctls
2021-06-14 16:22:46 -05:00
Gabriela Cervantes
2fb176ddee docs: Update url for breaking compatibility
This PR updates the proper url for breaking compatibility for
kata 2.x

Fixes #2031

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-14 14:45:42 -05:00
Gabriela Cervantes
601e2b65c5 docs: Remove docker support with kata 2.x and sysctls
Currently in kata 2.x, we do not have docker support, this PR removes
the docker documentation with sysctls.

Fixes #2029

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-14 14:20:14 -05:00
Julio Montes
9d585935b5 Merge pull request #2020 from GabyCT/topic/fixreadruntime
docs: Update README for runtime documentation
2021-06-14 10:37:20 -05:00
Fabiano Fidêncio
5a71786986 Merge pull request #1674 from jimcadden/stable-2.0-SEV
Support SEV
2021-06-12 16:56:51 +02:00
Fabiano Fidêncio
be31694554 virtcontainers: Fix TestQemuAmd64AppendProtectionDevice()
Since SEV support has been added, an implementation mistake was also
added to TestQemuAmd64AppendProtectionDevice.

appendProtectionDevice() will, as it name says, append the protection
device to whatever was there previously.  So, when SEV was added, we
broke the comparison done for TDX as we didn't append the expected
output for TDX with what we already had for SEV.

This should be enough to get the tests passing.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-06-12 08:56:15 -04:00
Fabiano Fidêncio
723c0ac4d5 Merge pull request #1832 from littlejawa/issue_1713
test: Add a unit test for ioCopy()
2021-06-12 00:34:28 +02:00
Gabriela Cervantes
240aae96dd docs: Update README for runtime documentation
This PR removes old links that were used in kata 1.x but not
longer valid for kata 2.x

Fixes #2019

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-11 16:01:20 -05:00
GabyCT
66e4c77a54 Merge pull request #1993 from likebreath/0610/clh_v16.0
versions: Upgrade to cloud-hypervisor v16.0
2021-06-11 15:11:11 -05:00
Fabiano Fidêncio
e754ff37e4 Merge pull request #2015 from fidencio/2.2.0-alpha0-branch-bump
# Kata Containers 2.2.0-alpha0
2021-06-11 18:51:08 +02:00
Julio Montes
6e7b55baa9 Merge pull request #1995 from GabyCT/topic/removetravisreference
docs: Remove old travis reference
2021-06-11 09:23:47 -05:00
Fabiano Fidêncio
54832cd052 release: Kata Containers 2.2.0-alpha0
- Update CC=gcc setting for Fedora s390x
- osbuilder: Streamline s390x CMake & musl handling
- runtime: remove the call to storeSandbox at the end of createSandboxFromConfig
- virtcontainers: Add support for Secure Execution
- agent: Conform to the latest nix version (0.21.0)
- docs: Update the stable branch strategy to what was proposed in our ML
- runtime: add more traces for network
- tools/packaging: clone meson and dependencies before building QEMU
- runtime: remove covertool from cli test
- factory: Use lazy unmount
- docs: Fix Release Process document
- Add sandbox and container ID to trace spans
- agent: Fix fd leak caused by netlink
- metrics: Add virtiofsd exporter
- versions: Update kubernetes to 1.21.1
- tracing: Add basic VSOCK tracing
- agent: Upgrade tokio-vsock to fix fd leak of vsock socket
- runtime: fix some comments and logs
- runtime: Add support for PEF
- cleanup TODOs in runtime
- tracing: Make runtime span attributes more consistent
- virtiofsd: refactor qemu.go to use code in virtiofsd.go
- runtime: remove unused doc.go
- cgroup: fix the issue of set mem.limit and mem.swap
- agent: re-enable the standard SIGPIPE behavior
- virtiofsd: Fix file descriptors leak and return correct PID
- runtime: and cgroup and SandboxCgroupOnly check for check sub-command
- kernel: add ppc64le fragments
- docs: Use --ignore-preflight-errors=all flag
- agent: fix start container failed when dropping all capabilities
- agent: Remove unnecessary underscore(_) variables
- docs: Add instructions for getting QEMU source
- qemu: align before memory hotplug on arm64
- workflows: release kata 2.x snap through the stable channel
- Sandbox bindmount cleanup
- docs: Update add customer agent command
- agent: Stop relying in the unmaintained prctl crate
- how-to-use-virtio-mem-with-kata.md: Update doc to make it clear
- docs: Add document for memory hotplug on arm64
- github: Run require porting labels only at main
- kernel: add confidential guest build option
- rustjail: separated the propagation flags from mount flags
- runtime: improve sandbox cleanup logic
- docs: add note for connecting debug console for old versions
- image_build: align image size to 128M for arm64
- agent: avoid reaping the exit signal of execute_hook in the reaper
- agent: move the dependency tempfile to the dev-dependencies section
- docs: Document test repository changes when creating a stable branch
- docs: Remove horizontal ruler markers that disable spell checks
- docs/Developer-Guide: Add instructions to apply QEMU patches
- runtime: make dialing timeout configurable
- Get sandbox metrics cli
- Support TDx
- packaging/kata-cleanup: add k3s containerd volume
- osbuilder: Upgrade alpine version to 3.13.5
- Monitor cleanup
- Open CONFIG_VIRTIO_MEM in x86_64 Linux kernel
- agent: delete code which is no longer used
- cli: delete tracing code for kata-runtime binary
- docs: add per-Pod Kata configurations for `enable_pprof`
- Fix issue of virtio-mem
- Set fixed NOFILE limit value for kata-agent
- ci/install_yq.sh: install_yq: Check version before return
- runtime: use s.ctx instead ctx for checking cancellation
- runtime: fix some comments

a1247bc0 agent: Conform to the latest nix version (0.21.0)
3130e66d runtime: remove storeSandbox at the end of createSandboxFromConfig
7593ebf9 runtime: Use CC=gcc on Fedora s390x
a484d6db osbuilder: Streamline s390x CMake & musl handling
da2d9ab8 osbuilder: Remove CC=gcc for Fedora s390x
c0c05c73 virtcontainers: Add support for Secure Execution
78f21710 virtcontainers/s390x: Put consts into one block
784025bb runtime: add more traces for network
9ec9bbba tools/packaging: clone meson and dependencies before building QEMU
9158ec68 docs: Fix Release Process document
9e3349c1 agent: Fix fd leak caused by netlink
3d0e0b27 tracing: Add network model to span
8ca02072 tracing: Add sandbox and container ID to trace spans
a9a0eccf tracing: Add basic VSOCK tracing
2234b730 metrics: Add virtiofsd exporter
9bf781d7 agent: Upgrade tokio-vsock to fix fd leak of vsock socket
b68334a1 runtime: fix some comments and logs
1f5b229b runtime: remove FIXME in SandboxState about CgroupPath
fee0004a runtime: remove TODO about hot add memory in qemu.go
2e29ef9c runtime: remove TODO comment from StatusContainer
72cd8f5e virtiofsd: refactor qemu.go to use code in virtiofsd.go
0b22c48d runtime: remove unused doc.go
30f4834c cgroup: fix the issue of set mem.limit and mem.swap
0ae364c8 agent: re-enable the standard SIGPIPE behavior
05a46fed tracing: Make runtime span attributes more consistent
727bfc45 runtime: and cgroup and SandboxCgroupOnly check for check sub-command
b25ad1ab tracing: Make trace-forwarder async
45f02227 tracing: Add trace points
773deca2 virtiofsd: Fix file descriptors leak and return correct PID
37a426b4 runtime: Add support for PEF
fe670c5d docs: Use --ignore-preflight-errors=all flag
5b5047bd docs: Add instructions for getting QEMU source
3e4ebe10 agent: fix start container failed when dropping all capabilities
9a43d76d workflows: release kata 2.x snap through the stable channel
7f1030d3 sandbox-bindmount: persist mount information
089a7484 sandbox: Cleanup if failure to setup sandbox-bindmount occurs
f65acc20 docs: Update add customer agent command
20a382c1 agent: Remove unnecessary underscore(_) variables
4b88532c docs: Don't use Docker as an example of a container manager
4142e424 docs: Don't mention 1.x components as part of the stable branch strategy
a0af2bd7 docs: Use stable-2.x / 2.x.y as example in the branch strategy document
a5e1f66a docs: Maintain only one stable branch per major release
419773b8 docs: Emphasize behaviour changes may be a reason for a major bump
54a75008 docs: Refer to `main` branch in the stable branch strategy document
7dde0b5d kernel: add ppc64le fragments
84906181 kernel: skip fragments for ppc64le
9676b86b kernel: move CONFIG_RANDOMIZE_BASE
bd0cde40 factory: Use lazy unmount
f52468be agent/agent-ctl: Replace prctl crate by the capctl one
d289b1d6 agent-ctl: Perform a `cargo update`
bc36b7b4 qemu: align before memory hotplug on arm64
8aefc793 agent: Perform a `cargo update`
785be0bb how-to-use-virtio-mem-with-kata.md: Update doc to make it clear
f8a16c17 kernel: add confidential guest build option
a65f11ea docs: Add document for memory hotplug on arm64
1b607056 runtime: remove covertool from cli test
fc42dc07 github: Run require porting labels only at main
dbef2b29 versions: Update kubernetes to 1.21.1
35151f17 runtime: sandbox delete should succeed after verifying sandbox state
e5fe572f rustjail: separated the propagation flags from mount flags
ffbb4d9b docs: add note for connecting debug console for old versions
a5bb383c agent: avoid reaping the exit signal of execute_hook in the reaper
ce7a5ba2 agent: move the dependency tempfile to the dev-dependencies section
e24e9462 docs/Developer-Guide: Add instructions to apply QEMU patches
850cf8cd docs: Document test repository changes when creating a stable branch
8068a469 kata-runtime: add `metrics` command
37873061 kata-monitor: export get stats for sandbox
01b56d6c runtime: make dialing timeout configurable
e8038718 osbuilder: Upgrade alpine version to 3.13.5
3caed6f8 runtime: shim: dedup client, socket addr code
4bc006c8 runtime: Short the shim-monitor path
5fdf617e docs: Fix spell-check errors found after new text is discovered
42425456 docs: Remove horizontal ruler markers that disable spell checks
3883e4e2 kernel: configs: Open CONFIG_VIRTIO_MEM in x86_64 Linux kernel
4f61f4b4 virtcontainers: Support TDX
0affe886 virtcontainers: define confidential guest framework
539afba0 runtime: define config options to enable confidential computing
79831faf runtime: use s.ctx instead ctx for checking cancellation
f6d5fbf9 runtime: fix some comments
9381e5f3 packaging/kata-cleanup: add k3s containerd volume
7f7c3fc8 qemu.go: qemu: resizeMemory: Fix virtio-mem resize overflow issue
c9053ea3 qemu.go: qemu: setupVirtioMem: let sizeMB be multiple of 2Mib
a188577e agent: Set fixed NOFILE limit value for kata-agent
88cf3db6 runtime: implement CPUFlags function
2b0d5b25 image_build: align image size to 128M for arm64
d601ae34 agent: delete not used comments
6038da19 agent: delete rustjail/src/configs directory
84ee8aa8 agent: delete not used functions
d8896157 ci/install_yq.sh: install_yq: Check version before return
95e54e3f docs: add per-Pod Kata configurations for enable_pprof
13c23fec cli: delete tracing code for kata-runtime binary

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-06-11 16:10:01 +02:00
houfangdong
8825bb298f agent: Update rust version for tokio
This was fixed for tokio's version
    requirements for rust, see:
    https://github.com/tokio-rs/tokio#supported-rust-versions

    Fixes: #3849

Signed-off-by: houfangdong <houfangdong@loongson.cn>
2021-06-11 15:01:43 +08:00
Chelsea Mafrica
cabddcc735 tracing: Make runHooks() span creation return context
The call to Trace() in runHooks() does not return a context; fix this so
that the subsequent calls to runHook() produces a properly ordered trace
span.

Fixes #2001

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2021-06-10 23:50:51 -07:00
Manabu Sugimoto
e544779c61 agent: Add some mount options
Add the following mount options to catch up with the runtime spec
- silent
- loud
- (no)acl
- (no)iversion
- (no)lazytime

Fixes: #1999

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-06-11 15:08:46 +09:00
Fabiano Fidêncio
dc4307d3cc Merge pull request #1974 from Jakob-Naucke/fix-cc-fedora-s390x
Update CC=gcc setting for Fedora s390x
2021-06-11 00:31:51 +02:00
Fabiano Fidêncio
bd195d67d4 Merge pull request #1976 from Jakob-Naucke/streamline-s390x-osbuilder
osbuilder: Streamline s390x CMake & musl handling
2021-06-11 00:31:34 +02:00
Fabiano Fidêncio
24bbcf58d3 Merge pull request #1981 from LiangZhou-CTY/patch-1
runtime: remove the call to storeSandbox at the end of createSandboxFromConfig
2021-06-11 00:30:39 +02:00
Gabriela Cervantes
a668f310c3 docs: Remove old travis reference
This PR removes the travis reference as we currently for kata 2.0,
travis is not being supported.

Fixes #1994

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-10 17:17:17 -05:00
Fabiano Fidêncio
8239f6fc17 Merge pull request #1772 from Jakob-Naucke/sec-exec
virtcontainers: Add support for Secure Execution
2021-06-11 00:02:01 +02:00
Bo Chen
85c40001da versions: Upgrade to cloud-hypervisor v16.0
Highlights from the Cloud Hypervisor release v16.0: 1) Improved live
migration support; 2) Improved `vhost-user` support; 3) ARM64 ACPI and
UEFI support; 4) Bug fixes.

Details can be found: https://github.com/cloud-hypervisor/cloud-hypervisor/releases/tag/v16.0

Note: The client code of cloud-hypervisor's OpenAPI is automatically
generated by `openapi-generator` [1-2]. As the API changes do not
impact usages in Kata, no additional changes in kata's runtime are
needed to work with the current version of cloud-hypervisor.

[1] https://github.com/OpenAPITools/openapi-generator
[2] https://github.com/kata-containers/kata-containers/blob/main/src/runtime/virtcontainers/pkg/cloud-hypervisor/README.md

Fixes: #1992

Signed-off-by: Bo Chen <chen.bo@intel.com>
2021-06-10 10:16:39 -07:00
Fupan Li
9d84272dd1 Merge pull request #1988 from ManaSugi/conform-to-latest-nix
agent: Conform to the latest nix version (0.21.0)
2021-06-10 17:17:03 +08:00
Samuel Ortiz
15e3d1656b Merge pull request #1877 from fidencio/wip/update-stable-branch-strategy
docs: Update the stable branch strategy to what was proposed in our ML
2021-06-10 10:26:31 +02:00
Manabu Sugimoto
a1247bc0bb agent: Conform to the latest nix version (0.21.0)
We need to fix some agent's code to conform to the latest nix crate
to be able to use new features of the nix.

Fixes: #1987

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-06-10 16:58:51 +09:00
Liang Zhou
3130e66d33 runtime: remove storeSandbox at the end of createSandboxFromConfig
Remove storeSandbox() at the end of createSandboxFromConfig(),
because this callchain createSandboxFromConfig -> createContainers
has already calls storeSandbox().
This can improve the startup speed of the container,
even just for a little.

Fixes: #1980

Signed-off-by: Liang Zhou <zhoul110@chinatelecom.cn>
2021-06-10 11:56:40 +08:00
Tim Zhang
f26837a0f1 Merge pull request #1967 from liubin/fix/1956-add-more-traces-for-network
runtime: add more traces for network
2021-06-10 10:56:42 +08:00
Jakob Naucke
7593ebf947 runtime: Use CC=gcc on Fedora s390x
This was fixed for the Go agent back in
https://github.com/kata-containers/osbuilder/issues/217, but is also
required for the runtime.

Fixes: #1973

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-08 16:36:24 +02:00
Fabiano Fidêncio
16a835e4a0 Merge pull request #1966 from devimc/2021-06-04/fixSnapCerts
tools/packaging: clone meson and dependencies before building QEMU
2021-06-08 10:36:53 +02:00
Jakob Naucke
a484d6db87 osbuilder: Streamline s390x CMake & musl handling
- Merge codepath in lib.sh with ppc64le -- do not install CMake
- Like ppc64le, do not install musl rather than just not using it

Fixes: #1975

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-07 17:39:31 +02:00
Jakob Naucke
da2d9ab813 osbuilder: Remove CC=gcc for Fedora s390x
since that was required specifically for the Go agent

Fixes: #1973

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-07 17:32:05 +02:00
Fabiano Fidêncio
208ab60e1e Merge pull request #1863 from zhsj/drop-covertool
runtime: remove covertool from cli test
2021-06-07 16:21:51 +02:00
Fabiano Fidêncio
51ac042cad Merge pull request #939 from keloyang/detach
factory: Use lazy unmount
2021-06-07 13:26:16 +02:00
Jakob Naucke
c0c05c73e1 virtcontainers: Add support for Secure Execution
Secure Execution is a confidential computing technology on s390x (IBM Z
& LinuxONE). Enable the correspondent virtualization technology in QEMU
(where it is referred to as "Protected Virtualization").

- Introduce enableProtection and appendProtectionDevice functions for
  QEMU s390x.
- Introduce CheckCmdline to check for "prot_virt=1" being present on the
  kernel command line.
- Introduce CPUFacilities and avilableGuestProtection for hypervisor
  s390x to check for CPU support.

Fixes: #1771

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-07 10:50:33 +02:00
Jakob Naucke
78f21710e3 virtcontainers/s390x: Put consts into one block
Previously, all consts were in single lines in
virtcontainers/qemu_s390x.go. Put them into a const block.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2021-06-07 10:50:30 +02:00
bin
784025bb08 runtime: add more traces for network
Add traces for all the endpoinnt types
and the main interface functions.
Record errors for some traces.

Fixes: #1956

Signed-off-by: bin <bin@hyper.sh>
2021-06-07 11:38:40 +08:00
Julio Montes
a57118d03a Merge pull request #1961 from GabyCT/topic/fixreleasedoc
docs: Fix Release Process document
2021-06-04 14:59:11 -05:00
Julio Montes
9ec9bbbabc tools/packaging: clone meson and dependencies before building QEMU
In some distros (Ubuntu 18 and 20) it's not possible to clone meson
and QEMU dependencies from https://git.qemu.org due to problems with
its certificates, let's pull these dependencies from github before
building QEMU.

fixes #1965

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-06-04 14:52:39 -05:00
Chelsea Mafrica
60806ce3c8 Merge pull request #1957 from cmaf/tracing-attributes-sandboxID-1
Add sandbox and container ID to trace spans
2021-06-04 09:10:05 -07:00
Gabriela Cervantes
9158ec68cc docs: Fix Release Process document
This PR updates the correct url for github actions as well as it
corrects a misspelling.

Fixes #1960

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-06-03 12:51:25 -05:00
Tim Zhang
1255b83427 Merge pull request #1955 from Tim-Zhang/fix-fd-leak-of-netlink
agent: Fix fd leak caused by netlink
2021-06-03 20:15:15 +08:00
Tim Zhang
9e3349c18e agent: Fix fd leak caused by netlink
See also: little-dude/netlink#165

Fixes: #1952

Because the author of netlink has no time to maintain the crate
(https://github.com/little-dude/netlink/issues/161), so we
need to switch the dependency to github temporarily.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-06-03 17:23:37 +08:00
Chelsea Mafrica
3d0e0b2786 tracing: Add network model to span
Trace spans erroneously set the network model to default in all cases.
Add function to return network model string and use it to set attribute
in spans.

Fixes #1878

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2021-06-02 21:53:54 -07:00
Chelsea Mafrica
8ca0207281 tracing: Add sandbox and container ID to trace spans
Add sandbox, container, and hypervisor IDs to trace spans. Note that
some spans in sandbox.go are created with a trace() call from api.go.
These spans have additional attributes set after span creation to
overwrite the api attributes.

Fixes #1878

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2021-06-02 21:53:54 -07:00
Bin Liu
1673110ee9 Merge pull request #1930 from jcvenegas/kata-moinitor-export-virtiofsd
metrics: Add virtiofsd exporter
2021-06-03 10:38:55 +08:00
Fabiano Fidêncio
fd59030031 Merge pull request #1851 from fidencio/wip/bump-kubernetes-version-to-1.21.1
versions: Update kubernetes to 1.21.1
2021-06-02 23:41:57 +02:00
Chelsea Mafrica
33c12b6d08 Merge pull request #1929 from jodh-intel/add-agent-tracing
tracing: Add basic VSOCK tracing
2021-06-02 11:45:41 -07:00
Sandeep Gupta
b26d5b1d08 virtcontainers: Support SEV
fixes #1869

Signed-off-by: Jim Cadden <jcadden@ibm.com>
2021-06-02 14:32:50 -04:00
James O. D. Hunt
a9a0eccf33 tracing: Add basic VSOCK tracing
Implement an openTelemetry custom exporter that sends trace spans to a
VSOCK socket. A VSOCK-to-span converter (such as the Kata trace
forwarder) needs to be running on the host to allow systems like Jaeger
to capture the trace spans.

By default, tracing is not enabled (meaning a NOP tracer is used). To
activate tracing, set the `agent.kata.enable_tracing=true` in the
configuration file.

The type of tracing this change introduces is "static isolated"
tracing. See [1] for further details.

> **Note:**
>
> This change only provides the foundational changes for agent
> tracing work. The feature is _not_ yet complete since it does
> not yet show the correct trace hierarchy.

Fixes: #60.

[1] - https://github.com/kata-containers/agent/blob/master/TRACING.md

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2021-06-02 18:00:05 +01:00
Jim Cadden
81c6e4ca9f runtime/vendor: add github.com/intel-go/cpuid
Fixes: #1869

Signed-off-by: Jim Cadden <jcadden@ibm.com>
2021-06-02 12:59:04 -04:00
Carlos Venegas
2234b73090 metrics: Add virtiofsd exporter
Export proc stats for virtiofsd.

This commit only adds for hypervisors that have support for it.

- qemu
- cloud-hypervisor

Fixes: #1926

Signed-off-by: Carlos Venegas <jos.c.venegas.munoz@intel.com>
2021-06-02 16:06:00 +00:00
Julio Montes
1f0964bad8 Merge pull request #1951 from Tim-Zhang/fix-fd-leak-of-vsock
agent: Upgrade tokio-vsock to fix fd leak of vsock socket
2021-06-02 09:41:10 -05:00
Tim Zhang
9bf781d704 agent: Upgrade tokio-vsock to fix fd leak of vsock socket
Fixes: #1950

The further information: rust-vsock/vsock-rs#15

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-06-02 16:03:09 +08:00
Tim Zhang
476ec9bd86 Merge pull request #1948 from liubin/fix/1947-fix-comments
runtime: fix some comments and logs
2021-06-02 10:52:01 +08:00
Pradipta Banerjee
604e3a6fa1 Merge pull request #1882 from Amulyam24/pef
runtime: Add support for PEF
2021-06-01 12:56:53 +05:30
Peng Tao
41e04495f4 Merge pull request #1943 from bergwolf/cleanup2
cleanup TODOs in runtime
2021-06-01 14:16:46 +08:00
Chelsea Mafrica
bcde703b36 Merge pull request #1859 from cmaf/tracing-attributes-1
tracing: Make runtime span attributes more consistent
2021-05-31 21:57:58 -07:00
bin
b68334a1a8 runtime: fix some comments and logs
This commit fix some conments/logs.
And add some logs for debug.

Fixes: #1947

Signed-off-by: bin <bin@hyper.sh>
2021-06-01 09:04:18 +08:00
Bin Liu
d1ac0a1a2c Merge pull request #1938 from liubin/fix/1933-virtiofsd-refactor
virtiofsd: refactor qemu.go to use code in virtiofsd.go
2021-06-01 08:32:56 +08:00
Fabiano Fidêncio
d7b6e3e178 Merge pull request #1942 from bergwolf/cleanup
runtime: remove unused doc.go
2021-05-31 22:41:24 +02:00
Peng Tao
1f5b229bef runtime: remove FIXME in SandboxState about CgroupPath
It is in real life usage as we put non constrained sandbox processes
(like shim) in a separate cgroup path.

Fixes: #1944
Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2021-05-29 13:17:14 +08:00
Peng Tao
fee0004ad4 runtime: remove TODO about hot add memory in qemu.go
Already addressed by https://github.com/kata-containers/runtime/pull/786

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2021-05-29 11:15:50 +08:00
Peng Tao
2e29ef9cab runtime: remove TODO comment from StatusContainer
It is no longer valid as containerd already doesn't treat container pid
as host process pid.

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2021-05-29 11:10:32 +08:00
bin
72cd8f5ef6 virtiofsd: refactor qemu.go to use code in virtiofsd.go
CloudHypervisor is using virtiofsd.go to manage virtiofsd process,
but qemu has its code in qemu.go. This commit let qemu to re-use
code in virtiofsd.go to reduce code and improve maintenanceability.

Fixes: #1933

Signed-off-by: bin <bin@hyper.sh>
2021-05-29 11:00:05 +08:00
Peng Tao
0b22c48d2a runtime: remove unused doc.go
It doesn't even contain any actual code there.

Fixes: #1941
Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2021-05-29 10:25:29 +08:00
Peng Tao
c455d84571 Merge pull request #1918 from lifupan/main
cgroup: fix the issue of set mem.limit and mem.swap
2021-05-29 10:05:44 +08:00
Peng Tao
fd6d32ee42 Merge pull request #1939 from lifupan/fix_epipe
agent: re-enable the standard SIGPIPE behavior
2021-05-29 10:05:09 +08:00
Fabiano Fidêncio
bcf78a18ae Merge pull request #1932 from liubin/fix/1931-virtiofsd-fd-leak-and-return-right-pid
virtiofsd: Fix file descriptors leak and return correct PID
2021-05-28 12:29:56 +02:00
Fupan Li
a761e980e4 Merge pull request #1934 from liubin/fix/1927-check-SandboxCgroupOnly-and-cgroup-v2
runtime: and cgroup and SandboxCgroupOnly check for check sub-command
2021-05-28 16:43:44 +08:00
fupan.lfp
30f4834c5b cgroup: fix the issue of set mem.limit and mem.swap
When update memory limit, we should adapt the write sequence
for memory and swap memory, so it won't fail because
the new value and the old value don't fit kernel's
validation.

Fixes: #1917

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-05-28 15:44:14 +08:00
fupan.lfp
0ae364c8eb agent: re-enable the standard SIGPIPE behavior
The Rust standard library had suppressed the default SIGPIPE
behavior, see https://github.com/rust-lang/rust/pull/13158.
Since the parent's signal handler would be inherited by it's child
process, thus we should re-enable the standard SIGPIPE behavior as a
workaround.

Fixes: #1887

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-05-28 15:25:05 +08:00
Chelsea Mafrica
05a46fede0 tracing: Make runtime span attributes more consistent
Span attributes (tags) are not consistent in runtime tracing, so
designate and use core attributes such source, package, subsystem, and
type as span metadata for more understandable output.

Use WithAttributes() during span creation to reduce calls to
SetAttributes().

Modify Trace() in katautils to accept slice of attributes so multiple
functions using different attributes can use it.

Fixes #1852

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2021-05-27 10:07:11 -07:00
bin
727bfc4556 runtime: and cgroup and SandboxCgroupOnly check for check sub-command
In kata-runtime check sub-command, checks cgroups and SandboxCgroupOnly
to show message if the SandboxCgroupOnly is not set to true
and cgroup v2 is used.

Fixes: #1927

Signed-off-by: bin <bin@hyper.sh>
2021-05-27 21:19:12 +08:00
James O. D. Hunt
b25ad1ab2c tracing: Make trace-forwarder async
The tracing crates are now async, so update the trace forwarder to use
the new API.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2021-05-27 10:48:05 +01:00
James O. D. Hunt
45f02227b2 tracing: Add trace points
Use the tracing crate to create automatic trace spans for the _majority_
of top-level modules.

Note that not all functions in the top-level modules can be traced:

- Some functions cannot be traced due to the requirement that all
  function parameters implement the `Debug` trait. In some cases (such
  as `netlink.rs`), objects are being passed that are defined in
  different crates and which do not implement `Debug`.
- Some functions may never return (`signal.rs`).
- Some functions are inlined.
- Some functions are very simple getter/setter functions.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2021-05-27 10:42:58 +01:00
bin
773deca2f6 virtiofsd: Fix file descriptors leak and return correct PID
This commit will fix two problems:
- Virtiofsd process ID returned to the caller will always be 0,
   the pid var is never being assigned a value.
- Socket listen fd may leak in case of failure of starting virtiofsd process.
  This is a port of be9ca0d58b

Fixes: #1931

Signed-off-by: bin <bin@hyper.sh>
2021-05-27 16:51:41 +08:00
Amulyam24
37a426b4c6 runtime: Add support for PEF
Protected Execution Facility(PEF) is the confidential computing
technology on ppc64le. This PR adds the support for it in Kata.
Also re-vendor govmm for the latest changes.

Fixes: #1881

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2021-05-25 14:29:42 +00:00
Peng Tao
35f297ad50 Merge pull request #1899 from Amulyam24/fragments
kernel: add ppc64le fragments
2021-05-25 10:18:55 +08:00
Fabiano Fidêncio
9fb301f4df Merge pull request #1920 from ManaSugi/update-kubeadm-flag
docs: Use --ignore-preflight-errors=all flag
2021-05-24 21:12:12 +02:00
Fabiano Fidêncio
c3f6c88668 Merge pull request #1915 from quanweiZhou/fix_start_container_failed_when_drop_all_caps
agent: fix start container failed when dropping all capabilities
2021-05-24 14:13:52 +02:00
Tim Zhang
005e5ddedc Merge pull request #1905 from ManaSugi/del_underscore_var
agent: Remove unnecessary underscore(_) variables
2021-05-24 17:39:48 +08:00
Manabu Sugimoto
fe670c5de5 docs: Use --ignore-preflight-errors=all flag
The --skip-preflight-checks flag has been deprecated in the Kubernetes v1.9
and removed from Kubernetes v1.12.
We should use --ignore-preflight-errors=all flag instead of --skip-preflight-checks.

Fixes: #1919

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-05-24 18:06:41 +09:00
Fabiano Fidêncio
852aa9454f Merge pull request #1908 from stevenhorsman/add-doc-for-getting-qemu
docs: Add instructions for getting QEMU source
2021-05-24 10:31:03 +02:00
Fupan Li
c09d8fcfda Merge pull request #1888 from yuanzhe-liu0/qemu_align
qemu: align before memory hotplug on arm64
2021-05-24 16:13:01 +08:00
stevenhorsman
5b5047bd4a docs: Add instructions for getting QEMU source
Update the developer guide to add instructions of how to get the
correct version of the QEMU source and sets your_qemu_directory
variable, so that follow on steps are easier for a new joiner to the
community to understand

Fixes #1907

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2021-05-23 10:23:18 +01:00
quanweiZhou
3e4ebe10ac agent: fix start container failed when dropping all capabilities
When starting a container and dropping all capabilities,
the init child process has no permission to read the exec.fifo
file because the parent set the file mode 0o622. So change the exec.fifo file mode to 0o644.

fixes #1913

Signed-off-by: quanweiZhou <quanweiZhou@linux.alibaba.com>
2021-05-22 17:33:49 +08:00
Fabiano Fidêncio
c078628544 Merge pull request #1910 from devimc/2021-05-21/snap/updateChannels
workflows: release kata 2.x snap through the stable channel
2021-05-22 09:21:58 +02:00
Julio Montes
9a43d76d5e workflows: release kata 2.x snap through the stable channel
kata 1.x has been deprecated, now kata 2.x can be released through
the stable channel

fixes #1909

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-05-21 15:48:48 -05:00
Fabiano Fidêncio
7dc1d32017 Merge pull request #1897 from egernst/sandbox-bindmount-cleanup
Sandbox bindmount cleanup
2021-05-21 22:36:12 +02:00
GabyCT
6f3b1bb796 Merge pull request #1906 from stevenhorsman/fix-add-customer-agent-command
docs: Update add customer agent command
2021-05-21 15:04:04 -05:00
Eric Ernst
7f1030d303 sandbox-bindmount: persist mount information
Without this, if the shim dies, we will not have a reliable way to
identify what mounts should be cleaned up if `containerd-shim-kata-v2
cleanup` is called for the sandbox.

Before this, if you `ctr run` with a sandbox bindmount defined and SIGKILL the
containerd-shim-kata-v2, you'll notice the sandbox bindmount left on
host.

With this change, the shim is able to get the sandbox bindmount
information from disk and do the appropriate cleanup.

Fixes #1896

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-21 12:54:35 -07:00
Eric Ernst
089a7484e1 sandbox: Cleanup if failure to setup sandbox-bindmount occurs
If for any reason there's an error when trying to setup the sandbox
bindmounts, make sure we roll back any mounts already created when
setting up the sandbox.

Without this, we'd leave shared directory mount and potentially
sandbox-bindmounts on the host.

Fixes: #1895

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-21 12:54:35 -07:00
stevenhorsman
f65acc20dc docs: Update add customer agent command
Update the developer guide to correct the
command that adds a customer kata-agent to the rootfs image
putting it in /usr/bin/kata-agent rather than /bin/kata-agent

Fixes #1904

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2021-05-21 15:42:04 +01:00
Manabu Sugimoto
20a382c158 agent: Remove unnecessary underscore(_) variables
We should remove underscore(_) prefixed variables when ? operator is
used.

Fixes: #1903

Signed-off-by: Manabu Sugimoto <Manabu.Sugimoto@sony.com>
2021-05-21 17:45:34 +09:00
Fabiano Fidêncio
4b88532c2f docs: Don't use Docker as an example of a container manager
Let's update the doc to use Containerd and CRI-O as examples, which fits
better the 2.x world.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Fabiano Fidêncio
4142e42465 docs: Don't mention 1.x components as part of the stable branch strategy
Let's slightly rewrite the text to ensure users of 2.x that never had
contact with kata-containers 1.x would be able to understand the
sentences.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Fabiano Fidêncio
a0af2bd7dc docs: Use stable-2.x / 2.x.y as example in the branch strategy document
This may help to reduce some confusion as 1.x was a totally different
thing for the project.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Fabiano Fidêncio
a5e1f66a15 docs: Maintain only one stable branch per major release
This is a proposal that was sent to the ML and can be accessed via
http://lists.katacontainers.io/pipermail/kata-dev/2021-May/001894.html

Shortly, the proposal is to maintain only one stable branch per major
active release.

This will help the developers and the CI maintainers, to spend more time
on what's coming, rather on backporting and debugging issues with old
releases; while still providing one stable branch that downstream
companies can rely on.

Hopefully, with this we'll be able to lower the maintainance burden and
spend more time on getting things rock solid / move forward in a faster
pace with the project.

Fixes: #1876

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Fabiano Fidêncio
419773b8df docs: Emphasize behaviour changes may be a reason for a major bump
The current wording is good, but we could emphasize better that changes
on behaviour from a previous release by simply making the text bold
rather than italic.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Fabiano Fidêncio
54a750086d docs: Refer to main branch in the stable branch strategy document
As there's no active `master` branch as part of kata-containers 2.x,
let's avoid referring to it, and let's referr to the `main` branch
instead.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-21 09:52:39 +02:00
Amulyam24
7dde0b5d84 kernel: add ppc64le fragments
Adding support for ppc64le kernel fragments.

Fixes: #1898

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2021-05-21 07:06:45 +00:00
Amulyam24
8490618125 kernel: skip fragments for ppc64le
Adding !powerpc to the group of fragments not
supported on ppc64le.

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2021-05-21 06:09:05 +00:00
Amulyam24
9676b86b44 kernel: move CONFIG_RANDOMIZE_BASE
This config is not selected for ppc64le. It is
only supported on PPC32 for now. Moved it to
respective arch base.conf.

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2021-05-21 06:05:21 +00:00
Shukui Yang
bd0cde40e7 factory: Use lazy unmount
we can have the following case,
1. start kata container with factory feature, this need kata-runtime
   config to enable factory and use initrd as base image.
2. start a kata container.
3. cd /root; cd /run/vc/vm/template dir, this will make
   /run/vc/vm/template to be in used.
4. destroy vm template with kata-runtime factory destroy , and check
                the template mountpoint.
we can see  the template mountpoints will add everytime we repeat the above steps .

[root@centos1 template]# mount |grep template
[root@centos1 template]# docker run -ti --rm  --runtime untrusted-runtime --net none busybox echo

[root@centos1 template]# cd /root; cd /run/vc/vm/template/
[root@centos1 template]# /kata/bin/kata-runtime factory destroy
vm factory destroyed
[root@centos1 template]# mount |grep template
tmpfs on /run/vc/vm/template type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=2105344k)
[root@centos1 template]# docker run -ti --rm  --runtime untrusted-runtime --net none busybox echo

[root@centos1 template]# cd /root; cd /run/vc/vm/template/
[root@centos1 template]# /kata/bin/kata-runtime factory destroy
vm factory destroyed
[root@centos1 template]# mount |grep template
tmpfs on /run/vc/vm/template type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=2105344k)
tmpfs on /run/vc/vm/template type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=2105344k)

Fixes: #938

Signed-off-by: Shukui Yang <keloyangsk@gmail.com>
2021-05-20 16:18:28 +08:00
Fupan Li
0c463babf3 Merge pull request #1885 from fidencio/wip/stop-using-unmaintained-prctl-crate
agent: Stop relying in the unmaintained prctl crate
2021-05-20 10:50:04 +08:00
Fabiano Fidêncio
f52468bea7 agent/agent-ctl: Replace prctl crate by the capctl one
While evaluating the possibility of having kata-agent statically linked
to the GNU libc, we've ended up facing some issues with prctl.

When debugging the issues, we figured out that the crate hasn't been
maintained since 2015 and that the capctl one is a good 1:1 replacement
for what we need.

Fixes: #1844

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-19 20:16:26 +02:00
Fabiano Fidêncio
d289b1d621 agent-ctl: Perform a cargo update
While in the beginning of the development cycle, let's perform a `cargo
update`.

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-19 19:44:12 +02:00
Yuanzhe Liu
bc36b7b49f qemu: align before memory hotplug on arm64
When hotplug memory on arm64 in kata, kernel will shout:

[ 0.396551] Block size [0x40000000] unaligned hotplug range: start 0xc8000000, size 0x40000000
[ 0.396556] acpi PNP0C80:01: add_memory failed
[ 0.396834] acpi PNP0C80:01: acpi_memory_enable_device() error
[ 0.396948] acpi PNP0C80:01: Enumeration failure

It means that kernel will check if the memory range to be hotplugged
align with 1G before plug the memory. So we should twist the qemu to
make sure the memory range align with 1G to pass the kernel check.

Fixes: #1841

Signed-off-by: Yuanzhe Liu <yuanzheliu09@gmail.com>
2021-05-19 14:23:55 +00:00
Fabiano Fidêncio
8aefc79314 agent: Perform a cargo update
While in the beginning of the development cycle, let's perform a `cargo
update`.

Fixes: #1883

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-19 09:43:17 +02:00
Fupan Li
be936442eb Merge pull request #1846 from teawater/vm_doc
how-to-use-virtio-mem-with-kata.md: Update doc to make it clear
2021-05-18 14:07:49 +08:00
Hui Zhu
b97791add1 Merge pull request #1855 from jongwu/mem_doc
docs: Add document for memory hotplug on arm64
2021-05-18 09:32:55 +08:00
Hui Zhu
785be0bbde how-to-use-virtio-mem-with-kata.md: Update doc to make it clear
Update this howto because the virtio-mem support of kata, qemu and Linux
was updated.

Fixes: #1845

Signed-off-by: Hui Zhu <teawater@antfin.com>
2021-05-18 09:27:57 +08:00
Chelsea Mafrica
6b9e46ef54 Merge pull request #1858 from GabyCT/topic/fixprporting
github: Run require porting labels only at main
2021-05-17 11:43:04 -07:00
Chelsea Mafrica
2e52529895 Merge pull request #1822 from jimcadden/kernel-conf-guest
kernel: add confidential guest build option
2021-05-17 11:42:07 -07:00
Jim Cadden
f8a16c170a kernel: add confidential guest build option
Includes support for SEV guest kernels

Fixes #1870

Signed-off-by: Jim Cadden <jcadden@ibm.com>
2021-05-17 09:52:32 -04:00
Jianyong Wu
a65f11ea56 docs: Add document for memory hotplug on arm64
After some enablement work, memory hotplug can be used on arm64.
Here we offer a document to instruct user to enable it.

Fixes: #1854
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2021-05-17 16:21:37 +08:00
Shengjing Zhu
1b60705646 runtime: remove covertool from cli test
covertool has no active since 2018 and is not compatible with go1.16

  ../vendor/github.com/dlespiau/covertool/pkg/cover/cover.go:76:29: cannot use f (type dummyTestDeps) as type testing.testDeps in argument to testing.MainStart:
  dummyTestDeps does not implement testing.testDeps (missing SetPanicOnExit0 method)

Fixes: #1862

Signed-off-by: Shengjing Zhu <zhsj@debian.org>
2021-05-16 03:06:06 +08:00
Gabriela Cervantes
fc42dc07cf github: Run require porting labels only at main
This PR modifies that require porting labels only run at main.

Fixes #1857

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2021-05-14 16:21:44 -05:00
Peng Tao
f6c5f7c0ef Merge pull request #1844 from lifupan/main
rustjail: separated the propagation flags from mount flags
2021-05-14 10:25:35 +08:00
Eric Ernst
f8d1f9b86e Merge pull request #985 from bergwolf/sandbox-cgroups-only
runtime: improve sandbox cleanup logic
2021-05-13 16:31:26 -07:00
Fabiano Fidêncio
dbef2b2931 versions: Update kubernetes to 1.21.1
The reason for doing such is to (try to) avoid random crashes we've been
facing as part of our CI, such as the one reported as part of
https://github.com/kata-containers/tests/issues/3473

Fixes: #1850

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-14 00:08:55 +02:00
Peng Tao
35151f1786 runtime: sandbox delete should succeed after verifying sandbox state
Otherwise we might block delete and create orphan containers.

Fixes: #1039

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-13 14:05:49 -07:00
fupan.lfp
e5fe572f51 rustjail: separated the propagation flags from mount flags
Since the propagation flags couldn't be combinted with the
standard mount flags, and they should be used with the remount,
thus it's better to split them from the standard mount flags.

Fixes: #1699

Signed-off-by: fupan.lfp <fupan.lfp@antgroup.com>
2021-05-13 23:53:52 +08:00
snir911
c995a982bc Merge pull request #1843 from liubin/fix/1842-update-docs-for-connecting-debug-console
docs: add note for connecting debug console for old versions
2021-05-13 14:06:51 +03:00
bin
ffbb4d9b11 docs: add note for connecting debug console for old versions
Before 2.1-alpha1, user still need starting kata-monitor
to connect to debug console.

Fixes: #1842

Signed-off-by: bin <bin@hyper.sh>
2021-05-13 15:39:04 +08:00
GabyCT
bdc9a66bd9 Merge pull request #1770 from jongwu/image_align
image_build: align image size to 128M for arm64
2021-05-12 09:38:06 -05:00
Julien Ropé
a918c46fb6 test: Add a unit test for ioCopy()
Following the fix for #1713, adding a unit test for ioCopy() that
verifies that data is properly copied from source to destination
whatever the order in which the pipes are closed.

Fixes #1831

Signed-off-by: Julien Ropé <jrope@redhat.com>
2021-05-12 11:30:45 +02:00
Bin Liu
cc4748fa64 Merge pull request #1829 from Tim-Zhang/fix-reap
agent: avoid reaping the exit signal of execute_hook in the reaper
2021-05-12 17:24:25 +08:00
Bin Liu
15778a17e5 Merge pull request #1828 from Tim-Zhang/move-dep
agent: move the dependency tempfile to the dev-dependencies section
2021-05-12 17:21:50 +08:00
Tim Zhang
2909a0364d Merge pull request #1824 from c3d/issue/1823-release-process-version-bump
docs: Document test repository changes when creating a stable branch
2021-05-12 14:46:32 +08:00
Tim Zhang
a5bb383cf3 agent: avoid reaping the exit signal of execute_hook in the reaper
Fixes: #1826

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-05-12 14:40:20 +08:00
Tim Zhang
ce7a5ba22e agent: move the dependency tempfile to the dev-dependencies section
The tempfile is only used by tests.

Fixes: #1827

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-05-12 14:39:58 +08:00
Fabiano Fidêncio
979b73c35a Merge pull request #1794 from c3d/issue/1793-workaround-spell-checker-bug
docs: Remove horizontal ruler markers that disable spell checks
2021-05-11 23:27:37 +02:00
GabyCT
5d05f36117 Merge pull request #1825 from wainersm/docs_qemu_patches
docs/Developer-Guide: Add instructions to apply QEMU patches
2021-05-11 13:36:00 -05:00
Fabiano Fidêncio
ac61e60492 Merge pull request #1790 from snir911/configure_timeout
runtime: make dialing timeout configurable
2021-05-11 16:52:05 +02:00
Wainer dos Santos Moschetta
e24e94622c docs/Developer-Guide: Add instructions to apply QEMU patches
Occasionally patches are necessary to build QEMU with the kata containers
configuration. This changed the developer guide to make it clear it is
recommended to apply the patches; and tell how.

Fixes #1807
Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2021-05-11 10:39:53 -04:00
Christophe de Dinechin
850cf8cdb3 docs: Document test repository changes when creating a stable branch
When we create a new stable branch, it is good practice to ensure that the test
repository points to that stable branch, to make sure that it is not impacted by
later changes to the CI made on the stable branch.

Fixes: #1823

Signed-off-by: Christophe de Dinechin <christophe@dinechin.org>
2021-05-11 11:44:03 +02:00
Bin Liu
bffb099d99 Merge pull request #1816 from egernst/get-sandbox-metrics-cli
Get sandbox metrics cli
2021-05-11 13:10:30 +08:00
Samuel Ortiz
2c4e4ca1ac Merge pull request #1590 from devimc/2021-02-02/ConfidentialComputing
Support TDx
2021-05-10 22:19:40 +02:00
Fabiano Fidêncio
becd270ccf Merge pull request #1802 from nubificus/fix-k3s-cleanup
packaging/kata-cleanup: add k3s containerd volume
2021-05-10 21:15:43 +02:00
Eric Ernst
8068a4692f kata-runtime: add metrics command
For easier debug, let's add subcommand to kata-runtime for gathering
metrics associated with a given sandbox.

kata-runtime metrics --sandbox-id foobar

Fixes: #1815

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-10 10:45:10 -07:00
Fabiano Fidêncio
c4bd246efb Merge pull request #1818 from cmaf/update-alpine-version
osbuilder: Upgrade alpine version to 3.13.5
2021-05-10 17:55:35 +02:00
Eric Ernst
3787306107 kata-monitor: export get stats for sandbox
Gathering stats for a given sandbox is pretty useful; let's export a
function from katamonitor pkg to do this.

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-10 08:53:56 -07:00
Snir Sheriber
01b56d6cbf runtime: make dialing timeout configurable
allow to set dialing timeout in configuration.toml
default is 30s

Fixes: #1789
Signed-off-by: Snir Sheriber <ssheribe@redhat.com>
2021-05-10 16:39:37 +03:00
Eric Ernst
12a04cb0ba Merge pull request #1811 from egernst/monitor-cleanup
Monitor cleanup
2021-05-07 21:03:34 -07:00
Chelsea Mafrica
e8038718aa osbuilder: Upgrade alpine version to 3.13.5
We are using an older version of alpine, so upgrade to latest 3.13.5.

Fixes #1817

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2021-05-07 16:34:45 -07:00
Eric Ernst
3caed6f88d runtime: shim: dedup client, socket addr code
(1) Add an accessor function, SocketAddress, to the shim-v2 code for
determining the shim's abstract domain socket address, given the sandbox
ID.

(2) In kata monitor, create a function, BuildShimClient, for obtaining the appropriate
http.Client for communicating with the shim's monitoring endpoint.

(3) Update the kata CLI and kata-monitor code to make use of these.

(4) Migrate some kata monitor methods to be functions, in order to ease
future reuse.

(5) drop unused namespace from functions where it is no longer needed.

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2021-05-07 15:20:37 -07:00
Fabiano Fidêncio
4bc006c8a4 runtime: Short the shim-monitor path
Instead of having something like
"/containerd-shim/$namespace/$sandboxID/shim-monitor.sock", let's change
the approach to:
* create the file in a more neutral location "/run/vc", instead of
  "/containerd-shim";
* drop the namespace, as the sandboxID should be unique;
* remove ".sock" from the socket name.

This will result on a name that looks like:
"/run/vc/$sandboxID/shim-monitor"

Fixes: #497

Signed-off-by: Fabiano Fidêncio <fidencio@redhat.com>
2021-05-07 14:20:35 -07:00
Christophe de Dinechin
5fdf617e7f docs: Fix spell-check errors found after new text is discovered
The spell-checker scripts has some bugs that caused large chunks of texts to not
be spell checked at all (see #1793). The previous commit worked around this bug,
which exposed another bug:

The following source text:

    are discussions about using VM save and restore to
    give [`criu`](https://github.com/checkpoint-restore/criu)-like
    functionality, which might provide a solution

yields the surprising error below:

    WARNING: Word 'givelike': did you mean one of the following?: give like, give-like, wavelike

Apparently, an extra space is removed, which is another issue with the
spell-checking script. This case is somewhat contrived because of the URL link,
so for now, I decided for a creative rewriting, inserting the word "a" knowing
that "alike" is a valid word ;-)

Fixes: #1793

Signed-off-by: Christophe de Dinechin <dinechin@redhat.com>
2021-05-07 11:43:44 +02:00
Christophe de Dinechin
42425456e7 docs: Remove horizontal ruler markers that disable spell checks
There is a bug in the CI script checking spelling that causes it
to skip any text that follows a horizontal ruler.
(https://github.com/kata-containers/tests/issues/3448)

Solution: replace one horizontal ruler marker with another that
does not trip the spell-checking script.

Fixes: #1793

Signed-off-by: Christophe de Dinechin <dinechin@redhat.com>
2021-05-07 11:43:44 +02:00
Fabiano Fidêncio
0a3b7938c9 Merge pull request #1799 from teawater/open_vm
Open CONFIG_VIRTIO_MEM in x86_64 Linux kernel
2021-05-07 11:43:17 +02:00
Tim Zhang
1bfc426a2b Merge pull request #1784 from liubin/fix/1783-delete-un-used-fn
agent: delete code which is no longer used
2021-05-07 14:25:26 +08:00
Fabiano Fidêncio
2436839fa7 Merge pull request #1749 from liubin/fix/1748-delete-tracing-in-cli
cli: delete tracing code for kata-runtime binary
2021-05-07 08:17:16 +02:00
Tim Zhang
75648b0770 Merge pull request #1745 from liubin/fix/1744-add-doc-for-enable_pprof
docs: add per-Pod Kata configurations for `enable_pprof`
2021-05-07 13:45:34 +08:00
Fupan Li
70e1d44262 Merge pull request #1800 from teawater/fix_vm
Fix issue of virtio-mem
2021-05-07 13:08:12 +08:00
Fupan Li
487e165093 Merge pull request #1778 from snir911/patch_nofile
Set fixed NOFILE limit value for kata-agent
2021-05-07 13:06:10 +08:00
Tim Zhang
29716c35e6 Merge pull request #1777 from teawater/check_yq
ci/install_yq.sh: install_yq: Check version before return
2021-05-07 10:02:51 +08:00
Chelsea Mafrica
3e8137399c Merge pull request #1805 from liubin/fix/1804-select-sandbox-ctx
runtime: use s.ctx instead ctx for checking cancellation
2021-05-06 09:51:47 -07:00
Chelsea Mafrica
917665ab6d Merge pull request #1751 from liubin/fix/1750-fix-comments
runtime: fix some comments
2021-05-06 08:42:15 -07:00
Julio Montes
4f61f4b490 virtcontainers: Support TDX
Add support for Intel TDX confidential guests

fixes #1332

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-05-06 10:09:05 -05:00
Julio Montes
0affe8860d virtcontainers: define confidential guest framework
Define the structure and functions needed to support confidential
guests, this commit doesn't add support for any specific technology,
support for TDX, SEV, PEF and others will be added in following
commits.

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-05-06 10:09:05 -05:00
Julio Montes
539afba03d runtime: define config options to enable confidential computing
Define config options to enable or disable confidential computing and
its features, for example:
* Image service offloading
* Image decryption keys

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-05-06 10:09:05 -05:00
bin
79831fafaf runtime: use s.ctx instead ctx for checking cancellation
s.ctx should be used for checking cancellation, and the
local ctx is used for tracing.

Fixes: #1804

Signed-off-by: bin <bin@hyper.sh>
2021-05-06 17:22:53 +08:00
bin
f6d5fbf9ba runtime: fix some comments
This commint include two types of fixes for comments
in src/runtime/containerd-shim-v2/start.go.

- Update comment for calling of watchOOMEvents.
- Comments without heading spaces.

Fixes: #1750

Signed-off-by: bin <bin@hyper.sh>
2021-05-06 17:12:52 +08:00
Orestis Lagkas Nikolos
9381e5f31a packaging/kata-cleanup: add k3s containerd volume
kata-deploy cleanup expects to find containerd configuration
in /etc/containerd/config.toml. In case of k3s mount the k3s
containerd config as a volume.

Fixes #1801

Signed-off-by: Orestis Lagkas Nikolos <olagkasn@nubificus.co.uk>
2021-05-06 03:18:16 -05:00
Hui Zhu
7f7c3fc8ec qemu.go: qemu: resizeMemory: Fix virtio-mem resize overflow issue
This commit change sizeByte from uint32 to uint64 to fix overflow issue.

Fixes: #1796

Signed-off-by: Hui Zhu <teawater@antfin.com>
2021-05-06 14:13:50 +08:00
Hui Zhu
c9053ea3fb qemu.go: qemu: setupVirtioMem: let sizeMB be multiple of 2Mib
Got:
FATA[0000] run pod sandbox: rpc error: code = Unknown desc = failed to
create containerd task: Add 189759MB virtio-mem-pci fail QMP command
failed: backend memory size must be multiple of 0x200000: unknown

This commit let sizeMB be multiple of 2Mib to fix the issue.

Fixes: #1796

Signed-off-by: Hui Zhu <teawater@antfin.com>
2021-05-06 14:13:48 +08:00
Snir Sheriber
a188577ebf agent: Set fixed NOFILE limit value for kata-agent
Some applications may fail if NOFILE limit is set to unlimited.
Although in some environments this value is explicitly overridden,
lets set it to a more sane value in case it doesn't.

Fixes #1715
Signed-off-by: Snir Sheriber <ssheribe@redhat.com>
2021-05-04 15:06:11 +03:00
Julio Montes
88cf3db601 runtime: implement CPUFlags function
`CPUFlags` returns a map with all the CPU flags, these CPU flags
may help us to identiry whether a system support confidential computing
or not.

Signed-off-by: Julio Montes <julio.montes@intel.com>
2021-05-03 09:33:13 -05:00
Jianyong Wu
2b0d5b252e image_build: align image size to 128M for arm64
There is an inconformity between qemu and kernel of memory alignment
check in memory hotplug. Both of qemu and kernel will do the start
address alignment check in memory hotplug. But it's 2M in qemu
while 128M in kernel. It leads to an issue when memory hotplug.

Currently, the kata image is a nvdimm device, which will plug into the VM as
a dimm. If another dimm is pluged, it will reside on top of that nvdimm.
So, the start address of the second dimm may not pass the alginment
check in kernel if the nvdimm size doesn't align with 128M.

There are 3 ways to address this issue I think:
1. fix the alignment size in kernel according to qemu. I think people
in linux kernel community will not accept it.
2. do alignment check in qemu and force the start address of hotplug
in alignment with 128M, which means there maybe holes between memory blocks.
3. obey the rule in user end, which means fix it in kata.

I think the second one is the best, but I can't do that for some reason.
Thus, the last one is the choice here.

Fixes: #1769
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2021-05-03 10:44:30 +08:00
bin
d601ae3446 agent: delete not used comments
Delete comments meanless or make people confusion.

Fixes: #1783

Signed-off-by: bin <bin@hyper.sh>
2021-04-30 19:37:55 +08:00
bin
6038da1903 agent: delete rustjail/src/configs directory
This directory is not used anymore.

Fixes: #1783

Signed-off-by: bin <bin@hyper.sh>
2021-04-30 19:18:03 +08:00
bin
84ee8aa8b2 agent: delete not used functions
In file src/agent/rustjail/src/validator.rs,
these two functions are not used:
- get_namespace_path
- check_host_ns

Fixes: #1783

Signed-off-by: bin <bin@hyper.sh>
2021-04-30 19:17:41 +08:00
Hui Zhu
d8896157df ci/install_yq.sh: install_yq: Check version before return
Check the yq version before return.

Fixes: #1776

Signed-off-by: Hui Zhu <teawater@antfin.com>
2021-04-29 18:19:18 +08:00
bin
95e54e3f48 docs: add per-Pod Kata configurations for enable_pprof
Now enabling enable_pprof for individual pods is supported,
but not documented.

This commit will add per-Pod Kata configurations for `enable_pprof`
in file `docs/how-to/how-to-set-sandbox-config-kata.md`

Fixes: #1744

Signed-off-by: bin <bin@hyper.sh>
2021-04-26 22:20:49 +08:00
bin
13c23fec11 cli: delete tracing code for kata-runtime binary
There are no pod/container operations in kata-runtime binary,
tracing in this package is meaningless.

Fixes: #1748

Signed-off-by: bin <bin@hyper.sh>
2021-04-26 11:11:22 +08:00
1958 changed files with 180767 additions and 48795 deletions

View File

@@ -12,6 +12,9 @@ on:
- reopened
- labeled
- unlabeled
pull_request:
branches:
- main
jobs:
check-pr-porting-labels:

View File

@@ -9,6 +9,8 @@ jobs:
steps:
- name: Check out Git repository
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Install Snapcraft
uses: samuelmeuli/action-snapcraft@v1
@@ -33,5 +35,5 @@ jobs:
snap_file="kata-containers_${snap_version}_amd64.snap"
# Upload the snap if it exists
if [ -f ${snap_file} ]; then
snapcraft upload --release=candidate ${snap_file}
snapcraft upload --release=stable ${snap_file}
fi

View File

@@ -6,6 +6,8 @@ jobs:
steps:
- name: Check out
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Install Snapcraft
uses: samuelmeuli/action-snapcraft@v1

View File

@@ -1,10 +1,18 @@
on: ["pull_request"]
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
name: Static checks
jobs:
test:
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
go-version: [1.15.x, 1.16.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
env:
@@ -13,7 +21,7 @@ jobs:
TRAVIS_PULL_REQUEST_BRANCH: ${{ github.head_ref }}
TRAVIS_PULL_REQUEST_SHA : ${{ github.event.pull_request.head.sha }}
RUST_BACKTRACE: "1"
target_branch: ${TRAVIS_BRANCH}
target_branch: ${{ github.base_ref }}
steps:
- name: Install Go
uses: actions/setup-go@v2
@@ -51,6 +59,10 @@ jobs:
PATH=$PATH:"$HOME/.cargo/bin"
rustup target add x86_64-unknown-linux-musl
rustup component add rustfmt clippy
# Check whether the vendored code is up-to-date & working as the first thing
- name: Check vendored code
run: |
cd ${GOPATH}/src/github.com/${{ github.repository }} && make vendor
# Must build before static checks as we depend on some generated code in runtime and agent
- name: Build
run: |

View File

@@ -15,7 +15,7 @@ TOOLS =
TOOLS += agent-ctl
STANDARD_TARGETS = build check clean install test
STANDARD_TARGETS = build check clean install test vendor
include utils.mk

View File

@@ -1 +1 @@
2.1.0-rc0
2.2.0-alpha1

View File

@@ -18,7 +18,9 @@ function install_yq() {
GOPATH=${GOPATH:-${HOME}/go}
local yq_path="${GOPATH}/bin/yq"
local yq_pkg="github.com/mikefarah/yq"
[ -x "${GOPATH}/bin/yq" ] && return
local yq_version=3.4.1
[ -x "${GOPATH}/bin/yq" ] && [ "`${GOPATH}/bin/yq --version`"X == "yq version ${yq_version}"X ] && return
read -r -a sysInfo <<< "$(uname -sm)"
@@ -56,8 +58,6 @@ function install_yq() {
die "Please install curl"
fi
local yq_version=3.4.1
## NOTE: ${var,,} => gives lowercase value of var
local yq_url="https://${yq_pkg}/releases/download/${yq_version}/yq_${goos,,}_${goarch}"
curl -o "${yq_path}" -LSsf "${yq_url}"

View File

@@ -5,7 +5,7 @@
export tests_repo="${tests_repo:-github.com/kata-containers/tests}"
export tests_repo_dir="$GOPATH/src/$tests_repo"
export branch="${branch:-main}"
export branch="${target_branch:-main}"
# Clones the tests repository and checkout to the branch pointed out by
# the global $branch variable.

View File

@@ -37,6 +37,7 @@
- [Set up a debug console](#set-up-a-debug-console)
- [Simple debug console setup](#simple-debug-console-setup)
- [Enable agent debug console](#enable-agent-debug-console)
- [Start `kata-monitor` - ONLY NEEDED FOR 2.0.x](#start-kata-monitor---only-needed-for-20x)
- [Connect to debug console](#connect-to-debug-console)
- [Traditional debug console setup](#traditional-debug-console-setup)
- [Create a custom image containing a shell](#create-a-custom-image-containing-a-shell)
@@ -304,7 +305,7 @@ You MUST choose one of `alpine`, `centos`, `clearlinux`, `debian`, `euleros`, `f
> - You should only do this step if you are testing with the latest version of the agent.
```
$ sudo install -o root -g root -m 0550 -t ${ROOTFS_DIR}/bin ../../../src/agent/target/x86_64-unknown-linux-musl/release/kata-agent
$ sudo install -o root -g root -m 0550 -t ${ROOTFS_DIR}/usr/bin ../../../src/agent/target/x86_64-unknown-linux-musl/release/kata-agent
$ sudo install -o root -g root -m 0440 ../../../src/agent/kata-agent.service ${ROOTFS_DIR}/usr/lib/systemd/system/
$ sudo install -o root -g root -m 0440 ../../../src/agent/kata-containers.target ${ROOTFS_DIR}/usr/lib/systemd/system/
```
@@ -353,12 +354,13 @@ You MUST choose one of `alpine`, `centos`, `clearlinux`, `euleros`, and `fedora`
>
> - Check the [compatibility matrix](../tools/osbuilder/README.md#platform-distro-compatibility-matrix) before creating rootfs.
Optionally, add your custom agent binary to the rootfs with the following, `LIBC` default is `musl`, if `ARCH` is `ppc64le`, should set the `LIBC=gnu` and `ARCH=powerpc64le`:
Optionally, add your custom agent binary to the rootfs with the following commands. The default `$LIBC` used
is `musl`, but on ppc64le and s390x, `gnu` should be used. Also, Rust refers to ppc64le as `powerpc64le`:
```
$ export ARCH=$(shell uname -m)
$ [ ${ARCH} == "ppc64le" ] && export LIBC=gnu || export LIBC=musl
$ export ARCH=$(uname -m)
$ [ ${ARCH} == "ppc64le" ] || [ ${ARCH} == "s390x" ] && export LIBC=gnu || export LIBC=musl
$ [ ${ARCH} == "ppc64le" ] && export ARCH=powerpc64le
$ sudo install -o root -g root -m 0550 -T ../../../src/agent/target/$(ARCH)-unknown-linux-$(LIBC)/release/kata-agent ${ROOTFS_DIR}/sbin/init
$ sudo install -o root -g root -m 0550 -T ../../../src/agent/target/${ARCH}-unknown-linux-${LIBC}/release/kata-agent ${ROOTFS_DIR}/sbin/init
```
### Build an initrd image
@@ -393,14 +395,40 @@ You may choose to manually build your VMM/hypervisor.
Kata Containers makes use of upstream QEMU branch. The exact version
and repository utilized can be found by looking at the [versions file](../versions.yaml).
Kata often utilizes patches for not-yet-upstream fixes for components,
including QEMU. These can be found in the [packaging/QEMU directory](../tools/packaging/qemu/patches)
Find the correct version of QEMU from the versions file:
```
$ source ${GOPATH}/src/github.com/kata-containers/kata-containers/tools/packaging/scripts/lib.sh
$ qemu_version=$(get_from_kata_deps "assets.hypervisor.qemu.version")
$ echo ${qemu_version}
```
Get source from the matching branch of QEMU:
```
$ go get -d github.com/qemu/qemu
$ cd ${GOPATH}/src/github.com/qemu/qemu
$ git checkout ${qemu_version}
$ your_qemu_directory=${GOPATH}/src/github.com/qemu/qemu
```
There are scripts to manage the build and packaging of QEMU. For the examples below, set your
environment as:
```
$ go get -d github.com/kata-containers/kata-containers
$ packaging_dir="${GOPATH}/src/github.com/kata-containers/kata-containers/tools/packaging"
```
Kata often utilizes patches for not-yet-upstream and/or backported fixes for components,
including QEMU. These can be found in the [packaging/QEMU directory](../tools/packaging/qemu/patches),
and it's *recommended* that you apply them. For example, suppose that you are going to build QEMU
version 5.2.0, do:
```
$ cd $your_qemu_directory
$ $packaging_dir/scripts/apply_patches.sh $packaging_dir/qemu/patches/5.2.x/
```
To build utilizing the same options as Kata, you should make use of the `configure-hypervisor.sh` script. For example:
```
$ go get -d github.com/kata-containers/kata-containers/tools/packaging
$ cd $your_qemu_directory
$ ${GOPATH}/src/github.com/kata-containers/kata-containers/tools/packaging/scripts/configure-hypervisor.sh kata-qemu > kata.cfg
$ $packaging_dir/scripts/configure-hypervisor.sh kata-qemu > kata.cfg
$ eval ./configure "$(cat kata.cfg)"
$ make -j $(nproc)
$ sudo -E make install
@@ -475,6 +503,16 @@ debug_console_enabled = true
This will pass `agent.debug_console agent.debug_console_vport=1026` to agent as kernel parameters, and sandboxes created using this parameters will start a shell in guest if new connection is accept from VSOCK.
#### Start `kata-monitor` - ONLY NEEDED FOR 2.0.x
For Kata Containers `2.0.x` releases, the `kata-runtime exec` command depends on the`kata-monitor` running, in order to get the sandbox's `vsock` address to connect to. Thus, first start the `kata-monitor` process.
```
$ sudo kata-monitor
```
`kata-monitor` will serve at `localhost:8090` by default.
#### Connect to debug console
Command `kata-runtime exec` is used to connect to the debug console.
@@ -619,7 +657,7 @@ VMM solution.
In case of cloud-hypervisor, connect to the `vsock` as shown:
```
$ sudo su -c 'cd /var/run/vc/vm/{sandbox_id}/root/ && socat stdin unix-connect:clh.sock'
$ sudo su -c 'cd /var/run/vc/vm/${sandbox_id}/root/ && socat stdin unix-connect:clh.sock'
CONNECT 1026
```
@@ -627,7 +665,7 @@ CONNECT 1026
For firecracker, connect to the `hvsock` as shown:
```
$ sudo su -c 'cd /var/run/vc/firecracker/{sandbox_id}/root/ && socat stdin unix-connect:kata.hvsock'
$ sudo su -c 'cd /var/run/vc/firecracker/${sandbox_id}/root/ && socat stdin unix-connect:kata.hvsock'
CONNECT 1026
```
@@ -636,7 +674,7 @@ CONNECT 1026
For QEMU, connect to the `vsock` as shown:
```
$ sudo su -c 'cd /var/run/vc/vm/{sandbox_id} && socat "stdin,raw,echo=0,escape=0x11" "unix-connect:console.sock"
$ sudo su -c 'cd /var/run/vc/vm/${sandbox_id} && socat "stdin,raw,echo=0,escape=0x11" "unix-connect:console.sock"'
```
To disconnect from the virtual machine, type `CONTROL+q` (hold down the

View File

@@ -25,7 +25,7 @@ All documents must:
- Have a `.md` file extension.
- Include a TOC (table of contents) at the top of the document with links to
all heading sections. We recommend using the
[`kata-check-markdown`](https://github.com/kata-containers/tests/tree/master/cmd/check-markdown)
[`kata-check-markdown`](https://github.com/kata-containers/tests/tree/main/cmd/check-markdown)
tool to generate the TOC.
- Be linked to from another document in the same repository.
@@ -118,7 +118,7 @@ This section lists requirements for displaying commands and command output.
The requirements must be adhered to since documentation containing code blocks
is validated by the CI system, which executes the command blocks with the help
of the
[doc-to-script](https://github.com/kata-containers/tests/tree/master/.ci/kata-doc-to-script.sh)
[doc-to-script](https://github.com/kata-containers/tests/tree/main/.ci/kata-doc-to-script.sh)
utility.
- If a document includes commands the user should run, they **MUST** be shown
@@ -202,7 +202,7 @@ and compare them with standard tools (e.g. `diff(1)`).
Since this project uses a number of terms not found in conventional
dictionaries, we have a
[spell checking tool](https://github.com/kata-containers/tests/tree/master/cmd/check-spelling)
[spell checking tool](https://github.com/kata-containers/tests/tree/main/cmd/check-spelling)
that checks both dictionary words and the additional terms we use.
Run the spell checking tool on your document before raising a PR to ensure it

View File

@@ -28,7 +28,7 @@
* [Appendices](#appendices)
* [The constraints challenge](#the-constraints-challenge)
---
***
# Overview
@@ -94,7 +94,9 @@ This section lists items that might be possible to fix.
### checkpoint and restore
The runtime does not provide `checkpoint` and `restore` commands. There
are discussions about using VM save and restore to give [`criu`](https://github.com/checkpoint-restore/criu)-like functionality, which might provide a solution.
are discussions about using VM save and restore to give us a
`[criu](https://github.com/checkpoint-restore/criu)`-like functionality,
which might provide a solution.
Note that the OCI standard does not specify `checkpoint` and `restore`
commands.

View File

@@ -29,6 +29,7 @@
## Release Process
### Bump all Kata repositories
Bump the repositories using a script in the Kata packaging repo, where:
@@ -41,6 +42,23 @@
$ ./update-repository-version.sh -p "$NEW_VERSION" "$BRANCH"
```
### Point tests repository to stable branch
If you create a new stable branch, i.e. if your release changes a major or minor version number (not a patch release), then
you should modify the `tests` repository to point to that newly created stable branch and not the `main` branch.
The objective is that changes in the CI on the main branch will not impact the stable branch.
In the test directory, change references the main branch in:
* `README.md`
* `versions.yaml`
* `cmd/github-labels/labels.yaml.in`
* `cmd/pmemctl/pmemctl.sh`
* `.ci/lib.sh`
* `.ci/static-checks.sh`
See the commits in [the corresponding PR for stable-2.1](https://github.com/kata-containers/tests/pull/3504) for an example of the changes.
### Merge all bump version Pull requests
- The above step will create a GitHub pull request in the Kata projects. Trigger the CI using `/test` command on each bump Pull request.
@@ -50,7 +68,7 @@
### Tag all Kata repositories
Once all the pull requests to bump versions in all Kata repositories are merged,
tag all the repositories as shown below.
tag all the repositories as shown below.
```
$ cd ${GOPATH}/src/github.com/kata-containers/kata-containers/tools/packaging/release
$ git checkout <kata-branch-to-release>
@@ -60,7 +78,7 @@
### Check Git-hub Actions
We make use of [GitHub actions](https://github.com/features/actions) in this [file](https://github.com/kata-containers/kata-containers/blob/master/.github/workflows/main.yaml) in the `kata-containers/kata-containers` repository to build and upload release artifacts. This action is auto triggered with the above step when a new tag is pushed to the `kata-containers/kata-conatiners` repository.
We make use of [GitHub actions](https://github.com/features/actions) in this [file](https://github.com/kata-containers/kata-containers/blob/main/.github/workflows/main.yaml) in the `kata-containers/kata-containers` repository to build and upload release artifacts. This action is auto triggered with the above step when a new tag is pushed to the `kata-containers/kata-containers` repository.
Check the [actions status page](https://github.com/kata-containers/kata-containers/actions) to verify all steps in the actions workflow have completed successfully. On success, a static tarball containing Kata release artifacts will be uploaded to the [Release page](https://github.com/kata-containers/kata-containers/releases).

View File

@@ -32,16 +32,16 @@ provides additional information regarding release `99.123.77` in the previous ex
changing the existing behavior*.
- When `MAJOR` increases, the new release adds **new features, bug fixes, or
both** and which *changes the behavior from the previous release* (incompatible with previous releases).
both** and which **changes the behavior from the previous release** (incompatible with previous releases).
A major release will also likely require a change of the container manager version used,
for example Docker\*. Please refer to the release notes for further details.
for example Containerd or CRI-O. Please refer to the release notes for further details.
## Release Strategy
Any new features added since the last release will be available in the next minor
release. These will include bug fixes as well. To facilitate a stable user environment,
Kata provides stable branch-based releases and a master branch release.
Kata provides stable branch-based releases and a main branch release.
## Stable branch patch criteria
@@ -49,9 +49,10 @@ No new features should be introduced to stable branches. This is intended to li
providing only bug and security fixes.
## Branch Management
Kata Containers will maintain two stable release branches in addition to the master branch.
Once a new MAJOR or MINOR release is created from master, a new stable branch is created for
the prior MAJOR or MINOR release and the older stable branch is no longer maintained. End of
Kata Containers will maintain **one** stable release branch, in addition to the main branch, for
each active major release.
Once a new MAJOR or MINOR release is created from main, a new stable branch is created for
the prior MAJOR or MINOR release and the previous stable branch is no longer maintained. End of
maintenance for a branch is announced on the Kata Containers mailing list. Users can determine
the version currently installed by running `kata-runtime kata-env`. It is recommended to use the
latest stable branch available.
@@ -61,59 +62,59 @@ A couple of examples follow to help clarify this process.
### New bug fix introduced
A bug fix is submitted against the runtime which does not introduce new inter-component dependencies.
This fix is applied to both the master and stable branches, and there is no need to create a new
This fix is applied to both the main and stable branches, and there is no need to create a new
stable branch.
| Branch | Original version | New version |
|--|--|--|
| `master` | `1.3.0-rc0` | `1.3.0-rc1` |
| `stable-1.2` | `1.2.0` | `1.2.1` |
| `stable-1.1` | `1.1.2` | `1.1.3` |
| `main` | `2.3.0-rc0` | `2.3.0-rc1` |
| `stable-2.2` | `2.2.0` | `2.2.1` |
| `stable-2.1` | (unmaintained) | (unmaintained) |
### New release made feature or change adding new inter-component dependency
A new feature is introduced, which adds a new inter-component dependency. In this case a new stable
branch is created (stable-1.3) starting from master and the older stable branch (stable-1.1)
branch is created (stable-2.3) starting from main and the previous stable branch (stable-2.2)
is dropped from maintenance.
| Branch | Original version | New version |
|--|--|--|
| `master` | `1.3.0-rc1` | `1.3.0` |
| `stable-1.3` | N/A| `1.3.0` |
| `stable-1.2` | `1.2.1` | `1.2.2` |
| `stable-1.1` | `1.1.3` | (unmaintained) |
| `main` | `2.3.0-rc1` | `2.3.0` |
| `stable-2.3` | N/A| `2.3.0` |
| `stable-2.2` | `2.2.1` | (unmaintained) |
| `stable-2.1` | (unmaintained) | (unmaintained) |
Note, the stable-1.1 branch will still exist with tag 1.1.3, but under current plans it is
not maintained further. The next tag applied to master will be 1.4.0-alpha0. We would then
Note, the stable-2.2 branch will still exist with tag 2.2.1, but under current plans it is
not maintained further. The next tag applied to main will be 2.4.0-alpha0. We would then
create a couple of alpha releases gathering features targeted for that particular release (in
this case 1.4.0), followed by a release candidate. The release candidate marks a feature freeze.
this case 2.4.0), followed by a release candidate. The release candidate marks a feature freeze.
A new stable branch is created for the release candidate. Only bug fixes and any security issues
are added to the branch going forward until release 1.4.0 is made.
are added to the branch going forward until release 2.4.0 is made.
## Backporting Process
Development that occurs against the master branch and applicable code commits should also be submitted
Development that occurs against the main branch and applicable code commits should also be submitted
against the stable branches. Some guidelines for this process follow::
1. Only bug and security fixes which do not introduce inter-component dependencies are
candidates for stable branches. These PRs should be marked with "bug" in GitHub.
2. Once a PR is created against master which meets requirement of (1), a comparable one
2. Once a PR is created against main which meets requirement of (1), a comparable one
should also be submitted against the stable branches. It is the responsibility of the submitter
to apply their pull request against stable, and it is the responsibility of the
reviewers to help identify stable-candidate pull requests.
## Continuous Integration Testing
The test repository is forked to create stable branches from master. Full CI
runs on each stable and master PR using its respective tests repository branch.
The test repository is forked to create stable branches from main. Full CI
runs on each stable and main PR using its respective tests repository branch.
### An alternative method for CI testing:
Ideally, the continuous integration infrastructure will run the same test suite on both master
Ideally, the continuous integration infrastructure will run the same test suite on both main
and the stable branches. When tests are modified or new feature tests are introduced, explicit
logic should exist within the testing CI to make sure only applicable tests are executed against
stable and master. While this is not in place currently, it should be considered in the long term.
stable and main. While this is not in place currently, it should be considered in the long term.
## Release Management
@@ -121,7 +122,7 @@ stable and master. While this is not in place currently, it should be considered
Releases are made every three weeks, which include a GitHub release as
well as binary packages. These patch releases are made for both stable branches, and a "release candidate"
for the next `MAJOR` or `MINOR` is created from master. If there are no changes across all the repositories, no
for the next `MAJOR` or `MINOR` is created from main. If there are no changes across all the repositories, no
release is created and an announcement is made on the developer mailing list to highlight this.
If a release is being made, each repository is tagged for this release, regardless
of whether changes are introduced. The release schedule can be seen on the
@@ -142,10 +143,10 @@ maturity, we have increased the cadence from six weeks to twelve weeks. The rele
### Compatibility
Kata guarantees compatibility between components that are within one minor release of each other.
This is critical for dependencies which cross between host (runtime, shim, proxy) and
This is critical for dependencies which cross between host (shimv2 runtime) and
the guest (hypervisor, rootfs and agent). For example, consider a cluster with a long-running
deployment, workload-never-dies, all on Kata version 1.1.3 components. If the operator updates
the Kata components to the next new minor release (i.e. 1.2.0), we need to guarantee that the 1.2.0
runtime still communicates with 1.1.3 agent within workload-never-dies.
deployment, workload-never-dies, all on Kata version 2.1.3 components. If the operator updates
the Kata components to the next new minor release (i.e. 2.2.0), we need to guarantee that the 2.2.0
shimv2 runtime still communicates with 2.1.3 agent within workload-never-dies.
Handling live-update is out of the scope of this document. See this [`kata-runtime` issue](https://github.com/kata-containers/runtime/issues/492) for details.

View File

@@ -8,4 +8,5 @@ Kata Containers design documents:
- [VSocks](VSocks.md)
- [VCPU handling](vcpu-handling.md)
- [Host cgroups](host-cgroups.md)
- [`Inotify` support](inotify.md)
- [Metrics(Kata 2.0)](kata-2-0-metrics.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

30
docs/design/inotify.md Normal file
View File

@@ -0,0 +1,30 @@
# Kata Containers support for `inotify`
## Background on `inotify` usage
A common pattern in Kubernetes is to watch for changes to files/directories passed in as `ConfigMaps`
or `Secrets`. Sidecar's normally use `inotify` to watch for changes and then signal the primary container to reload
the updated configuration. Kata Containers typically will pass these host files into the guest using `virtiofs`, which
does not support `inotify` today. While we work to enable this use case in `virtiofs`, we introduced a workaround in Kata Containers.
This document describes how Kata Containers implements this workaround.
### Detecting a `watchable` mount
Kubernetes creates `secrets` and `ConfigMap` mounts at very specific locations on the host filesystem. For container mounts,
the `Kata Containers` runtime will check the source of the mount to identify these special cases. For these use cases, only a single file
or very few would typically need to be watched. To avoid excessive overheads in making a mount watchable,
we enforce a limit of eight files per mount. If a `secret` or `ConfigMap` mount contains more than 8 files, it will not be
considered watchable. We similarly enforce a limit of 1 MB per mount to be considered watchable. Non-watchable mounts will
continue to propagate changes from the mount on the host to the container workload, but these updates will not trigger an
`inotify` event.
If at any point a mount grows beyond the eight file or 1MB limit, it will no longer be `watchable.`
### Presenting a `watchable` mount to the workload
For mounts that are considered `watchable`, inside the guest, the `kata-agent` will poll the mount presented from
the host through `virtiofs` and copy any changed files to a `tmpfs` mount that is presented to the container. In this way,
for `watchable` mounts, Kata will do the polling on behalf of the workload and existing workloads needn't change their usage
of `inotify`.
![drawing](arch-images/inotify-workaround.png)

View File

@@ -37,3 +37,4 @@
- [How to use Kata Containers with `virtio-mem`](how-to-use-virtio-mem-with-kata.md)
- [How to set sandbox Kata Containers configurations with pod annotations](how-to-set-sandbox-config-kata.md)
- [How to monitor Kata Containers in K8s](how-to-set-prometheus-in-k8s.md)
- [How to use hotplug memory on arm64 in Kata Containers](how-to-hotplug-memory-arm64.md)

View File

@@ -0,0 +1,32 @@
# How to use memory hotplug feature in Kata Containers on arm64
- [Introduction](#introduction)
- [Install UEFI ROM](#install-uefi-rom)
- [Run for test](#run-for-test)
## Introduction
Memory hotplug is a key feature for containers to allocate memory dynamically in deployment.
As Kata Container bases on VM, this feature needs support both from VMM and guest kernel. Luckily, it has been fully supported for the current default version of QEMU and guest kernel used by Kata on arm64. For other VMMs, e.g, Cloud Hypervisor, the enablement work is on the road. Apart from VMM and guest kernel, memory hotplug also depends on ACPI which depends on firmware either. On x86, you can boot a VM using QEMU with ACPI enabled directly, because it boots up with firmware implicitly. For arm64, however, you need specify firmware explicitly. That is to say, if you are ready to run a normal Kata Container on arm64, what you need extra to do is to install the UEFI ROM before use the memory hotplug feature.
## Install UEFI ROM
We have offered a helper script for you to install the UEFI ROM. If you have installed Kata normally on your host, you just need to run the script as fellows:
```bash
$ pushd $GOPATH/src/github.com/kata-containers/tests
$ sudo .ci/aarch64/install_rom_aarch64.sh
$ popd
```
## Run for test
Let's test if the memory hotplug is ready for Kata after install the UEFI ROM. Make sure containerd is ready to run Kata before test.
```bash
$ sudo ctr image pull docker.io/library/ubuntu:latest
$ sudo ctr run --runtime io.containerd.run.kata.v2 -t --rm docker.io/library/ubuntu:latest hello sh -c "free -h"
$ sudo ctr run --runtime io.containerd.run.kata.v2 -t --memory-limit 536870912 --rm docker.io/library/ubuntu:latest hello sh -c "free -h"
```
Compare the results between the two tests. If the latter is 0.5G larger than the former, you have done what you want, and congratulation!

View File

@@ -26,6 +26,7 @@ There are several kinds of Kata configurations and they are listed below.
| `io.katacontainers.config.runtime.disable_new_netns` | `boolean` | determines if a new netns is created for the hypervisor process |
| `io.katacontainers.config.runtime.internetworking_model` | string| determines how the VM should be connected to the container network interface. Valid values are `macvtap`, `tcfilter` and `none` |
| `io.katacontainers.config.runtime.sandbox_cgroup_only`| `boolean` | determines if Kata processes are managed only in sandbox cgroup |
| `io.katacontainers.config.runtime.enable_pprof` | `boolean` | enables Golang `pprof` for `containerd-shim-kata-v2` process |
## Agent Options
| Key | Value Type | Comments |
@@ -78,7 +79,7 @@ There are several kinds of Kata configurations and they are listed below.
| `io.katacontainers.config.hypervisor.kernel` | string | the kernel used to boot the container VM |
| `io.katacontainers.config.hypervisor.machine_accelerators` | string | machine specific accelerators for the hypervisor |
| `io.katacontainers.config.hypervisor.machine_type` | string | the type of machine being emulated by the hypervisor |
| `io.katacontainers.config.hypervisor.memory_offset` | uint32| the memory space used for `nvdimm` device by the hypervisor |
| `io.katacontainers.config.hypervisor.memory_offset` | uint64| the memory space used for `nvdimm` device by the hypervisor |
| `io.katacontainers.config.hypervisor.memory_slots` | uint32| the memory slots assigned to the VM by the hypervisor |
| `io.katacontainers.config.hypervisor.msize_9p` | uint32 | the `msize` for 9p shares |
| `io.katacontainers.config.hypervisor.path` | string | the hypervisor that will run the container VM |

View File

@@ -16,11 +16,10 @@ To get a complete list of kernel parameters, run:
$ sudo sysctl -a
```
Both Docker and Kubernetes provide mechanisms for setting namespaced sysctls.
Namespaced sysctls can be set per pod in the case of Kubernetes or per container
in case of Docker.
Kubernetes provide mechanisms for setting namespaced sysctls.
Namespaced sysctls can be set per pod in the case of Kubernetes.
The following sysctls are known to be namespaced and can be set with
Docker and Kubernetes:
Kubernetes:
- `kernel.shm*`
- `kernel.msg*`
@@ -30,31 +29,10 @@ Docker and Kubernetes:
### Namespaced Sysctls:
Kata Containers supports setting namespaced sysctls with Docker and Kubernetes.
Kata Containers supports setting namespaced sysctls with Kubernetes.
All namespaced sysctls can be set in the same way as regular Linux based
containers, the difference being, in the case of Kata they are set inside the guest.
#### Setting Namespaced Sysctls with Docker:
```
$ sudo docker run --runtime=kata-runtime -it alpine cat /proc/sys/fs/mqueue/queues_max
256
$ sudo docker run --runtime=kata-runtime --sysctl fs.mqueue.queues_max=512 -it alpine cat /proc/sys/fs/mqueue/queues_max
512
```
... and:
```
$ sudo docker run --runtime=kata-runtime -it alpine cat /proc/sys/kernel/shmmax
18446744073692774399
$ sudo docker run --runtime=kata-runtime --sysctl kernel.shmmax=1024 -it alpine cat /proc/sys/kernel/shmmax
1024
```
For additional documentation on setting sysctls with Docker please refer to [Docker-sysctl-doc](https://docs.docker.com/engine/reference/commandline/run/#configure-namespaced-kernel-parameters-sysctls-at-runtime).
#### Setting Namespaced Sysctls with Kubernetes:
Kubernetes considers certain sysctls as safe and others as unsafe. For detailed
@@ -100,7 +78,7 @@ spec:
### Non-Namespaced Sysctls:
Docker and Kubernetes disallow sysctls without a namespace.
Kubernetes disallow sysctls without a namespace.
The recommendation is to set them directly on the host or use a privileged
container in the case of Kubernetes.

View File

@@ -9,4 +9,4 @@ Container deployments utilize explicit or implicit file sharing between host fil
As of the 2.0 release of Kata Containers, [virtio-fs](https://virtio-fs.gitlab.io/) is the default filesystem sharing mechanism.
virtio-fs support works out of the box for `cloud-hypervisor` and `qemu`, when Kata Containers is deployed using `kata-deploy`. Learn more about `kata-deploy` and how to use `kata-deploy` in Kubernetes [here](https://github.com/kata-containers/packaging/tree/master/kata-deploy#kubernetes-quick-start).
virtio-fs support works out of the box for `cloud-hypervisor` and `qemu`, when Kata Containers is deployed using `kata-deploy`. Learn more about `kata-deploy` and how to use `kata-deploy` in Kubernetes [here](https://github.com/kata-containers/kata-containers/tree/main/tools/packaging/kata-deploy#kubernetes-quick-start).

View File

@@ -13,26 +13,23 @@ Kata Containers with `virtio-mem` supports memory resize.
## Requisites
Kata Containers with `virtio-mem` requires Linux and the QEMU that support `virtio-mem`.
The Linux kernel and QEMU upstream version still not support `virtio-mem`. @davidhildenbrand is working on them.
Please use following unofficial version of the Linux kernel and QEMU that support `virtio-mem` with Kata Containers.
Kata Containers just supports `virtio-mem` with QEMU.
Install and setup Kata Containers as shown [here](../install/README.md).
The Linux kernel is at https://github.com/davidhildenbrand/linux/tree/virtio-mem-rfc-v4.
The Linux kernel config that can work with Kata Containers is at https://gist.github.com/teawater/016194ee84748c768745a163d08b0fb9.
The QEMU is at https://github.com/teawater/qemu/tree/kata-virtio-mem. (The original source is at https://github.com/davidhildenbrand/qemu/tree/virtio-mem. Its base version of QEMU cannot work with Kata Containers. So merge the commit of `virtio-mem` to upstream QEMU.)
Set Linux and the QEMU that support `virtio-mem` with following line in the Kata Containers QEMU configuration `configuration-qemu.toml`:
```toml
[hypervisor.qemu]
path = "qemu-dir"
kernel = "vmlinux-dir"
### With x86_64
The `virtio-mem` config of the x86_64 Kata Linux kernel is open.
Enable `virtio-mem` as follows:
```
$ sudo sed -i -e 's/^#enable_virtio_mem.*$/enable_virtio_mem = true/g' /etc/kata-containers/configuration.toml
```
Enable `virtio-mem` with following line in the Kata Containers configuration:
```toml
enable_virtio_mem = true
### With other architectures
The `virtio-mem` config of the others Kata Linux kernel is not open.
You can open `virtio-mem` config as follows:
```
CONFIG_VIRTIO_MEM=y
```
Then you can build and install the guest kernel image as shown [here](../../tools/packaging/kernel/README.md#build-kata-containers-kernel).
## Run a Kata Container utilizing `virtio-mem`
@@ -41,13 +38,35 @@ Use following command to enable memory overcommitment of a Linux kernel. Becaus
$ echo 1 | sudo tee /proc/sys/vm/overcommit_memory
```
Use following command start a Kata Container.
Use following command to start a Kata Container.
```
$ docker run --rm -it --runtime=kata --name test busybox
$ pod_yaml=pod.yaml
$ container_yaml=${REPORT_DIR}/container.yaml
$ image="quay.io/prometheus/busybox:latest"
$ cat << EOF > "${pod_yaml}"
metadata:
name: busybox-sandbox1
EOF
$ cat << EOF > "${container_yaml}"
metadata:
name: busybox-killed-vmm
image:
image: "$image"
command:
- top
EOF
$ sudo crictl pull $image
$ podid=$(sudo crictl runp $pod_yaml)
$ cid=$(sudo crictl create $podid $container_yaml $pod_yaml)
$ sudo crictl start $cid
```
Use following command set the memory size of test to default_memory + 512m.
Use the following command to set the container memory limit to 2g and the memory size of the VM to its default_memory + 2g.
```
$ docker update -m 512m --memory-swap -1 test
$ sudo crictl update --memory $((2*1024*1024*1024)) $cid
```
Use the following command to set the container memory limit to 1g and the memory size of the VM to its default_memory + 1g.
```
$ sudo crictl update --memory $((1*1024*1024*1024)) $cid
```

View File

@@ -171,10 +171,10 @@ $ sudo systemctl daemon-reload
$ sudo systemctl restart kubelet
# If using CRI-O
$ sudo kubeadm init --skip-preflight-checks --cri-socket /var/run/crio/crio.sock --pod-network-cidr=10.244.0.0/16
$ sudo kubeadm init --ignore-preflight-errors=all --cri-socket /var/run/crio/crio.sock --pod-network-cidr=10.244.0.0/16
# If using CRI-containerd
$ sudo kubeadm init --skip-preflight-checks --cri-socket /run/containerd/containerd.sock --pod-network-cidr=10.244.0.0/16
$ sudo kubeadm init --ignore-preflight-errors=all --cri-socket /run/containerd/containerd.sock --pod-network-cidr=10.244.0.0/16
$ export KUBECONFIG=/etc/kubernetes/admin.conf
```

View File

@@ -18,7 +18,7 @@
cluster locally. It creates a single node Kubernetes stack in a local VM.
[Kata Containers](https://github.com/kata-containers) can be installed into a Minikube cluster using
[`kata-deploy`](https://github.com/kata-containers/packaging/tree/master/kata-deploy).
[`kata-deploy`](https://github.com/kata-containers/kata-containers/tree/main/tools/packaging/kata-deploy).
This document details the pre-requisites, installation steps, and how to check
the installation has been successful.
@@ -135,7 +135,7 @@ $ kubectl apply -f kata-deploy/base/kata-deploy.yaml
This installs the Kata Containers components into `/opt/kata` inside the Minikube node. It can take
a few minutes for the operation to complete. You can check the installation has worked by checking
the status of the `kata-deploy` pod, which will be executing
[this script](https://github.com/kata-containers/packaging/blob/master/kata-deploy/scripts/kata-deploy.sh),
[this script](https://github.com/kata-containers/kata-containers/tree/main/tools/packaging/kata-deploy/scripts/kata-deploy.sh),
and will be executing a `sleep infinity` once it has successfully completed its work.
You can accomplish this by running the following:

View File

@@ -14,7 +14,7 @@ Kata Containers can be installed in any Linux distribution that supports
Run the following command to install **Kata Containers**:
```sh
$ sudo snap install kata-containers --candidate --classic
$ sudo snap install kata-containers --stable --classic
```
## Configure Kata Containers

View File

@@ -65,8 +65,8 @@ configuration in the Kata `configuration.toml` file as shown below.
$ sudo sed -i -e 's/^# *\(hotplug_vfio_on_root_bus\).*=.*$/\1 = true/g' /usr/share/defaults/kata-containers/configuration.toml
```
Make sure you are using the `pc` machine type by verifying `machine_type = "pc"` is
set in the `configuration.toml`.
Make sure you are using the `q35` machine type by verifying `machine_type = "q35"` is
set in the `configuration.toml`. Make sure `pcie_root_port` is set to a positive value.
## Build Kata Containers kernel with GPU support

View File

@@ -75,13 +75,6 @@ To use non-large BARs devices (for example, Nvidia Tesla T4), you need Kata vers
Follow the [Kata Containers setup instructions](../install/README.md)
to install the latest version of Kata.
The following configuration in the Kata `configuration.toml` file as shown below can work:
```
machine_type = "pc"
hotplug_vfio_on_root_bus = true
```
To use large BARs devices (for example, Nvidia Tesla P100), you need Kata version 1.11.0 or above.
The following configuration in the Kata `configuration.toml` file as shown below can work:

View File

@@ -74,7 +74,7 @@ Make sure to check [`01.org`](https://01.org/intel-quickassist-technology) for
the latest driver.
```bash
$ export QAT_DRIVER_VER=qat1.7.l.4.12.0-00011.tar.gz
$ export QAT_DRIVER_VER=qat1.7.l.4.14.0-00031.tar.gz
$ export QAT_DRIVER_URL=https://downloadmirror.intel.com/30178/eng/${QAT_DRIVER_VER}
$ export QAT_CONF_LOCATION=~/QAT_conf
$ export QAT_DOCKERFILE=https://raw.githubusercontent.com/intel/intel-device-plugins-for-kubernetes/master/demo/openssl-qat-engine/Dockerfile
@@ -402,7 +402,7 @@ different hypervisor, different install method for Kata, or a different
Intel® QAT chipset then the command will need to be modified.
> **Note: The following was tested with
[containerd v1.3.9](https://github.com/containerd/containerd/releases/tag/v1.3.9).**
[containerd v1.4.6](https://github.com/containerd/containerd/releases/tag/v1.4.6).**
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/configuration-qemu.toml"

View File

@@ -80,6 +80,8 @@ parts:
- uidmap
- gnupg2
override-build: |
[ "$(uname -m)" = "ppc64le" ] || [ "$(uname -m)" = "s390x" ] && sudo apt-get --no-install-recommends install -y protobuf-compiler
yq=${SNAPCRAFT_STAGE}/yq
# set GOPATH
@@ -88,6 +90,7 @@ parts:
export GOROOT=${SNAPCRAFT_STAGE}
export PATH="${GOROOT}/bin:${PATH}"
export GO111MODULE="auto"
http_proxy=${http_proxy:-""}
https_proxy=${https_proxy:-""}
@@ -117,9 +120,13 @@ parts:
export USE_DOCKER=1
export DEBUG=1
case "$(uname -m)" in
aarch64|ppc64le|s390x)
aarch64)
sudo -E PATH=$PATH make initrd DISTRO=alpine
;;
ppc64le|s390x)
# Cannot use alpine on ppc64le/s390x because it would require a musl agent
sudo -E PATH=$PATH make initrd DISTRO=ubuntu
;;
x86_64)
# In some build systems it's impossible to build a rootfs image, try with the initrd image
sudo -E PATH=$PATH make image DISTRO=clearlinux || sudo -E PATH=$PATH make initrd DISTRO=alpine
@@ -141,6 +148,7 @@ parts:
export GOPATH=${SNAPCRAFT_STAGE}/gopath
export GOROOT=${SNAPCRAFT_STAGE}
export PATH="${GOROOT}/bin:${PATH}"
export GO111MODULE="auto"
kata_dir=${GOPATH}/src/github.com/${SNAPCRAFT_PROJECT_NAME}/${SNAPCRAFT_PROJECT_NAME}
cd ${kata_dir}/src/runtime
@@ -180,7 +188,10 @@ parts:
- bison
- flex
override-build: |
[ "$(uname -m)" = "s390x" ] && sudo apt-get --no-install-recommends install -y libssl-dev
export GOPATH=${SNAPCRAFT_STAGE}/gopath
export GO111MODULE="auto"
kata_dir=${GOPATH}/src/github.com/${SNAPCRAFT_PROJECT_NAME}/${SNAPCRAFT_PROJECT_NAME}
cd ${kata_dir}/tools/packaging/kernel
@@ -202,8 +213,10 @@ parts:
ln -sf ${vmlinuz_name} ${kata_kernel_dir}/vmlinuz.container
# Install raw kernel
vmlinux_path=vmlinux
[ "$(uname -m)" = "s390x" ] && vmlinux_path=arch/s390/boot/compressed/vmlinux
vmlinux_name=vmlinux-${kernel_suffix}
cp vmlinux ${kata_kernel_dir}/${vmlinux_name}
cp ${vmlinux_path} ${kata_kernel_dir}/${vmlinux_name}
ln -sf ${vmlinux_name} ${kata_kernel_dir}/vmlinux.container
qemu:
@@ -227,11 +240,13 @@ parts:
- libblkid-dev
- libffi-dev
- libmount-dev
- libseccomp-dev
- libselinux1-dev
- ninja-build
override-build: |
yq=${SNAPCRAFT_STAGE}/yq
export GOPATH=${SNAPCRAFT_STAGE}/gopath
export GO111MODULE="auto"
kata_dir=${GOPATH}/src/github.com/${SNAPCRAFT_PROJECT_NAME}/${SNAPCRAFT_PROJECT_NAME}
versions_file="${kata_dir}/versions.yaml"
@@ -267,7 +282,7 @@ parts:
${kata_dir}/tools/packaging/scripts/apply_patches.sh "${patches_version_dir}"
# Only x86_64 supports libpmem
[ "$(uname -m)" = "x86_64" ] && sudo apt-get --no-install-recommends install -y apt-utils ca-certificates libpmem-dev libseccomp-dev
[ "$(uname -m)" = "x86_64" ] && sudo apt-get --no-install-recommends install -y apt-utils ca-certificates libpmem-dev
configure_hypervisor=${kata_dir}/tools/packaging/scripts/configure-hypervisor.sh
chmod +x ${configure_hypervisor}

View File

@@ -1 +1,2 @@
tarpaulin-report.html
vendor/

829
src/agent/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,20 +13,25 @@ lazy_static = "1.3.0"
ttrpc = { version = "0.5.0", features = ["async", "protobuf-codec"], default-features = false }
protobuf = "=2.14.0"
libc = "0.2.58"
nix = "0.17.0"
prctl = "1.0.0"
nix = "0.21.0"
capctl = "0.2.0"
serde_json = "1.0.39"
scan_fmt = "0.2.3"
scopeguard = "1.0.0"
regex = "1"
# Async helpers
async-trait = "0.1.42"
tokio = { version = "1.2.0", features = ["rt", "rt-multi-thread", "sync", "macros", "io-util", "time", "signal", "io-std", "process", "fs"] }
async-recursion = "0.3.2"
futures = "0.3.12"
netlink-sys = { version = "0.6.0", features = ["tokio_socket",]}
tokio-vsock = "0.3.0"
rtnetlink = "0.7.0"
netlink-packet-utils = "0.4.0"
# Async runtime
tokio = { version = "1.2.0", features = ["full"] }
tokio-vsock = "0.3.1"
netlink-sys = { version = "0.7.0", features = ["tokio_socket",]}
rtnetlink = "0.8.0"
netlink-packet-utils = "0.4.1"
ipnetwork = "0.17.0"
# slog:
@@ -40,13 +45,21 @@ slog-scope = "4.1.2"
slog-stdlog = "4.0.0"
log = "0.4.11"
# for testing
tempfile = "3.1.0"
prometheus = { version = "0.9.0", features = ["process"] }
procfs = "0.7.9"
anyhow = "1.0.32"
cgroups = { package = "cgroups-rs", version = "0.2.5" }
# Tracing
tracing = "0.1.26"
tracing-subscriber = "0.2.18"
tracing-opentelemetry = "0.13.0"
opentelemetry = "0.14.0"
vsock-exporter = { path = "vsock-exporter" }
[dev-dependencies]
tempfile = "3.1.0"
[workspace]
members = [
"oci",

View File

@@ -27,40 +27,7 @@ COMMIT_MSG = $(if $(COMMIT),$(COMMIT),unknown)
# Exported to allow cargo to see it
export VERSION_COMMIT := $(if $(COMMIT),$(VERSION)-$(COMMIT),$(VERSION))
##VAR BUILD_TYPE=release|debug type of rust build
BUILD_TYPE = release
##VAR ARCH=arch target to build (format: uname -m)
ARCH = $(shell uname -m)
##VAR LIBC=musl|gnu
LIBC ?= musl
ifneq ($(LIBC),musl)
ifeq ($(LIBC),gnu)
override LIBC = gnu
else
$(error "ERROR: A non supported LIBC value was passed. Supported values are musl and gnu")
endif
endif
ifeq ($(ARCH), ppc64le)
override ARCH = powerpc64le
override LIBC = gnu
$(warning "WARNING: powerpc64le-unknown-linux-musl target is unavailable")
endif
ifeq ($(ARCH), s390x)
override LIBC = gnu
$(warning "WARNING: s390x-unknown-linux-musl target is unavailable")
endif
EXTRA_RUSTFLAGS :=
ifeq ($(ARCH), aarch64)
override EXTRA_RUSTFLAGS = -C link-arg=-lgcc
$(warning "WARNING: aarch64-musl needs extra symbols from libgcc")
endif
TRIPLE = $(ARCH)-unknown-linux-$(LIBC)
include ../../utils.mk
TARGET_PATH = target/$(TRIPLE)/$(BUILD_TYPE)/$(TARGET)
@@ -154,6 +121,10 @@ clean:
@rm -f $(GENERATED_FILES)
@rm -f tarpaulin-report.html
vendor:
@cargo vendor
#TARGET test: run cargo tests
test:
@cargo test --all --target $(TRIPLE)
@@ -223,7 +194,8 @@ codecov-html: check_tarpaulin
help \
show-header \
show-summary \
optimize
optimize \
vendor
##TARGET generate-protocols: generate/update grpc agent protocols
generate-protocols:

View File

@@ -15,7 +15,7 @@ Wants=kata-containers.target
StandardOutput=tty
Type=simple
ExecStart=@BINDIR@/@AGENT_NAME@
LimitNOFILE=infinity
LimitNOFILE=1048576
# ExecStop is required for static agent tracing; in all other scenarios
# the runtime handles shutting down the VM.
ExecStop=/bin/sync ; /usr/bin/systemctl --force poweroff

View File

@@ -11,9 +11,9 @@ serde_derive = "1.0.91"
oci = { path = "../oci" }
protocols = { path ="../protocols" }
caps = "0.5.0"
nix = "0.17.0"
nix = "0.21.0"
scopeguard = "1.0.0"
prctl = "1.0.0"
capctl = "0.2.0"
lazy_static = "1.3.0"
libc = "0.2.58"
protobuf = "=2.14.0"
@@ -24,7 +24,6 @@ regex = "1.1"
path-absolutize = "1.2.0"
anyhow = "1.0.32"
cgroups = { package = "cgroups-rs", version = "0.2.5" }
tempfile = "3.1.0"
rlimit = "0.5.3"
tokio = { version = "1.2.0", features = ["sync", "io-util", "process", "time", "macros"] }
@@ -34,3 +33,4 @@ inotify = "0.9.2"
[dev-dependencies]
serial_test = "0.5.0"
tempfile = "3.1.0"

View File

@@ -349,14 +349,34 @@ fn set_memory_resources(cg: &cgroups::Cgroup, memory: &LinuxMemory, update: bool
mem_controller.set_kmem_limit(-1)?;
}
set_resource!(mem_controller, set_limit, memory, limit);
set_resource!(mem_controller, set_soft_limit, memory, reservation);
set_resource!(mem_controller, set_kmem_limit, memory, kernel);
set_resource!(mem_controller, set_tcp_limit, memory, kernel_tcp);
// If the memory update is set to -1 we should also
// set swap to -1, it means unlimited memory.
let mut swap = memory.swap.unwrap_or(0);
if memory.limit == Some(-1) {
swap = -1;
}
if let Some(swap) = memory.swap {
// set memory swap
let swap = if cg.v2() {
if memory.limit.is_some() && swap != 0 {
let memstat = get_memory_stats(cg)
.into_option()
.ok_or_else(|| anyhow!("failed to get the cgroup memory stats"))?;
let memusage = memstat.get_usage();
// When update memory limit, the kernel would check the current memory limit
// set against the new swap setting, if the current memory limit is large than
// the new swap, then set limit first, otherwise the kernel would complain and
// refused to set; on the other hand, if the current memory limit is smaller than
// the new swap, then we should set the swap first and then set the memor limit.
if swap == -1 || memusage.get_limit() < swap as u64 {
mem_controller.set_memswap_limit(swap)?;
set_resource!(mem_controller, set_limit, memory, limit);
} else {
set_resource!(mem_controller, set_limit, memory, limit);
mem_controller.set_memswap_limit(swap)?;
}
} else {
set_resource!(mem_controller, set_limit, memory, limit);
swap = if cg.v2() {
convert_memory_swap_to_v2_value(swap, memory.limit.unwrap_or(0))?
} else {
swap
@@ -366,6 +386,10 @@ fn set_memory_resources(cg: &cgroups::Cgroup, memory: &LinuxMemory, update: bool
}
}
set_resource!(mem_controller, set_soft_limit, memory, reservation);
set_resource!(mem_controller, set_kmem_limit, memory, kernel);
set_resource!(mem_controller, set_tcp_limit, memory, kernel_tcp);
if let Some(swappiness) = memory.swappiness {
if (0..=100).contains(&swappiness) {
mem_controller.set_swappiness(swappiness as u64)?;
@@ -899,12 +923,12 @@ pub fn get_mounts() -> Result<HashMap<String, String>> {
let paths = get_paths()?;
for l in fs::read_to_string(MOUNTS)?.lines() {
let p: Vec<&str> = l.split(" - ").collect();
let p: Vec<&str> = l.splitn(2, " - ").collect();
let pre: Vec<&str> = p[0].split(' ').collect();
let post: Vec<&str> = p[1].split(' ').collect();
if post.len() != 3 {
warn!(sl!(), "mountinfo corrupted!");
warn!(sl!(), "can't parse {} line {:?}", MOUNTS, l);
continue;
}

View File

@@ -139,19 +139,6 @@ async fn notify_on_oom(cid: &str, dir: String) -> Result<Receiver<String>> {
register_memory_event(cid, dir, "memory.oom_control", "").await
}
// level is one of "low", "medium", or "critical"
async fn notify_memory_pressure(cid: &str, dir: String, level: &str) -> Result<Receiver<String>> {
if dir.is_empty() {
return Err(anyhow!("memory controller missing"));
}
if level != "low" && level != "medium" && level != "critical" {
return Err(anyhow!("invalid pressure level {}", level));
}
register_memory_event(cid, dir, "memory.pressure_level", level).await
}
async fn register_memory_event(
cid: &str,
cg_dir: String,

View File

@@ -1,56 +0,0 @@
// Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use libc::*;
use serde;
#[macro_use]
use serde_derive;
use serde_json;
#[derive(Serialize, Deserialize, Debug)]
pub struct Device {
#[serde(default)]
r#type: char,
#[serde(default)]
path: String,
#[serde(default)]
major: i64,
#[serde(default)]
minor: i64,
#[serde(default)]
permissions: String,
#[serde(default)]
file_mode: mode_t,
#[serde(default)]
uid: i32,
#[serde(default)]
gid: i32,
#[serde(default)]
allow: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BlockIODevice {
#[serde(default)]
major: i64,
#[serde(default)]
minor: i64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct WeightDevice {
block: BlockIODevice,
#[serde(default)]
weight: u16,
#[serde(default, rename = "leafWeight")]
leaf_weight: u16,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ThrottleDevice {
block: BlockIODevice,
#[serde(default)]
rate: u64,
}

View File

@@ -1,372 +0,0 @@
// Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use serde;
#[macro_use]
use serde_derive;
use serde_json;
use protocols::oci::State as OCIState;
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use nix::unistd;
use self::device::{Device, ThrottleDevice, WeightDevice};
use self::namespaces::Namespaces;
use crate::specconv::CreateOpts;
pub mod device;
pub mod namespaces;
pub mod validator;
#[derive(Serialize, Deserialize, Debug)]
pub struct Rlimit {
#[serde(default)]
r#type: i32,
#[serde(default)]
hard: i32,
#[serde(default)]
soft: i32,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct IDMap {
#[serde(default)]
container_id: i32,
#[serde(default)]
host_id: i32,
#[serde(default)]
size: i32,
}
type Action = i32;
#[derive(Serialize, Deserialize, Debug)]
pub struct Seccomp {
#[serde(default)]
default_action: Action,
#[serde(default)]
architectures: Vec<String>,
#[serde(default)]
flags: Vec<String>,
#[serde(default)]
syscalls: Vec<Syscall>,
}
type Operator = i32;
#[derive(Serialize, Deserialize, Debug)]
pub struct Arg {
#[serde(default)]
index: u32,
#[serde(default)]
value: u64,
#[serde(default)]
value_two: u64,
#[serde(default)]
op: Operator,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Syscall {
#[serde(default, skip_serializing_if = "String::is_empty")]
names: String,
#[serde(default)]
action: Action,
#[serde(default, rename = "errnoRet")]
errno_ret: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
args: Vec<Arg>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Config<'a> {
#[serde(default)]
no_pivot_root: bool,
#[serde(default)]
parent_death_signal: i32,
#[serde(default)]
rootfs: String,
#[serde(default)]
readonlyfs: bool,
#[serde(default, rename = "rootPropagation")]
root_propagation: i32,
#[serde(default)]
mounts: Vec<Mount>,
#[serde(default)]
devices: Vec<Device>,
#[serde(default)]
mount_label: String,
#[serde(default)]
hostname: String,
#[serde(default)]
namespaces: Namespaces,
#[serde(default)]
capabilities: Option<Capabilities>,
#[serde(default)]
networks: Vec<Network>,
#[serde(default)]
routes: Vec<Route>,
#[serde(default)]
cgroups: Option<Cgroup<'a>>,
#[serde(default, skip_serializing_if = "String::is_empty")]
apparmor_profile: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
process_label: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
rlimits: Vec<Rlimit>,
#[serde(default)]
oom_score_adj: Option<i32>,
#[serde(default)]
uid_mappings: Vec<IDMap>,
#[serde(default)]
gid_mappings: Vec<IDMap>,
#[serde(default)]
mask_paths: Vec<String>,
#[serde(default)]
readonly_paths: Vec<String>,
#[serde(default)]
sysctl: HashMap<String, String>,
#[serde(default)]
seccomp: Option<Seccomp>,
#[serde(default)]
no_new_privileges: bool,
hooks: Option<Hooks>,
#[serde(default)]
version: String,
#[serde(default)]
labels: Vec<String>,
#[serde(default)]
no_new_keyring: bool,
#[serde(default)]
intel_rdt: Option<IntelRdt>,
#[serde(default)]
rootless_euid: bool,
#[serde(default)]
rootless_cgroups: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Hooks {
prestart: Vec<Box<Hook>>,
poststart: Vec<Box<Hook>>,
poststop: Vec<Box<Hook>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Capabilities {
bounding: Vec<String>,
effective: Vec<String>,
inheritable: Vec<String>,
permitted: Vec<String>,
ambient: Vec<String>,
}
pub trait Hook {
fn run(&self, state: &OCIState) -> Result<()>;
}
pub struct FuncHook {
// run: fn(&OCIState) -> Result<()>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Command {
#[serde(default)]
path: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: Vec<String>,
#[serde(default)]
dir: String,
#[serde(default)]
timeout: Duration,
}
pub struct CommandHook {
command: Command,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Mount {
#[serde(default)]
source: String,
#[serde(default)]
destination: String,
#[serde(default)]
device: String,
#[serde(default)]
flags: i32,
#[serde(default)]
propagation_flags: Vec<i32>,
#[serde(default)]
data: String,
#[serde(default)]
relabel: String,
#[serde(default)]
extensions: i32,
#[serde(default)]
premount_cmds: Vec<Command>,
#[serde(default)]
postmount_cmds: Vec<Command>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct HugepageLimit {
#[serde(default)]
page_size: String,
#[serde(default)]
limit: u64,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct IntelRdt {
#[serde(default, skip_serializing_if = "String::is_empty")]
l3_cache_schema: String,
#[serde(
default,
rename = "memBwSchema",
skip_serializing_if = "String::is_empty"
)]
mem_bw_schema: String,
}
pub type FreezerState = String;
#[derive(Serialize, Deserialize, Debug)]
pub struct Cgroup<'a> {
#[serde(default, skip_serializing_if = "String::is_empty")]
name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
parent: String,
#[serde(default)]
path: String,
#[serde(default)]
scope_prefix: String,
paths: HashMap<String, String>,
resource: &'a Resources<'a>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Resources<'a> {
#[serde(default)]
allow_all_devices: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
allowed_devices: Vec<&'a Device>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
denied_devices: Vec<&'a Device>,
#[serde(default)]
devices: Vec<&'a Device>,
#[serde(default)]
memory: i64,
#[serde(default)]
memory_reservation: i64,
#[serde(default)]
memory_swap: i64,
#[serde(default)]
kernel_memory: i64,
#[serde(default)]
kernel_memory_tcp: i64,
#[serde(default)]
cpu_shares: u64,
#[serde(default)]
cpu_quota: i64,
#[serde(default)]
cpu_period: u64,
#[serde(default)]
cpu_rt_quota: i64,
#[serde(default)]
cpu_rt_period: u64,
#[serde(default)]
cpuset_cpus: String,
#[serde(default)]
cpuset_mems: String,
#[serde(default)]
pids_limit: i64,
#[serde(default)]
blkio_weight: u64,
#[serde(default)]
blkio_leaf_weight: u64,
#[serde(default)]
blkio_weight_device: Vec<&'a WeightDevice>,
#[serde(default)]
blkio_throttle_read_bps_device: Vec<&'a ThrottleDevice>,
#[serde(default)]
blkio_throttle_write_bps_device: Vec<&'a ThrottleDevice>,
#[serde(default)]
blkio_throttle_read_iops_device: Vec<&'a ThrottleDevice>,
#[serde(default)]
blkio_throttle_write_iops_device: Vec<&'a ThrottleDevice>,
#[serde(default)]
freezer: FreezerState,
#[serde(default)]
hugetlb_limit: Vec<&'a HugepageLimit>,
#[serde(default)]
oom_kill_disable: bool,
#[serde(default)]
memory_swapiness: u64,
#[serde(default)]
net_prio_ifpriomap: Vec<&'a IfPrioMap>,
#[serde(default)]
net_cls_classid_u: u32,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Network {
#[serde(default)]
r#type: String,
#[serde(default)]
name: String,
#[serde(default)]
bridge: String,
#[serde(default)]
mac_address: String,
#[serde(default)]
address: String,
#[serde(default)]
gateway: String,
#[serde(default)]
ipv6_address: String,
#[serde(default)]
ipv6_gateway: String,
#[serde(default)]
mtu: i32,
#[serde(default)]
txqueuelen: i32,
#[serde(default)]
host_interface_name: String,
#[serde(default)]
hairpin_mode: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Route {
#[serde(default)]
destination: String,
#[serde(default)]
source: String,
#[serde(default)]
gateway: String,
#[serde(default)]
interface_name: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct IfPrioMap {
#[serde(default)]
interface: String,
#[serde(default)]
priority: i32,
}
impl IfPrioMap {
fn cgroup_string(&self) -> String {
format!("{} {}", self.interface, self.priority)
}
}

View File

@@ -1,46 +0,0 @@
// Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use serde;
#[macro_use]
use serde_derive;
use serde_json;
use std::collections::HashMap;
#[macro_use]
use lazy_static;
pub type NamespaceType = String;
pub type Namespaces = Vec<Namespace>;
#[derive(Serialize, Deserialize, Debug)]
pub struct Namespace {
#[serde(default)]
r#type: NamespaceType,
#[serde(default)]
path: String,
}
pub const NEWNET: &'static str = "NEWNET";
pub const NEWPID: &'static str = "NEWPID";
pub const NEWNS: &'static str = "NEWNS";
pub const NEWUTS: &'static str = "NEWUTS";
pub const NEWUSER: &'static str = "NEWUSER";
pub const NEWCGROUP: &'static str = "NEWCGROUP";
pub const NEWIPC: &'static str = "NEWIPC";
lazy_static! {
static ref TYPETONAME: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("pid", "pid");
m.insert("network", "net");
m.insert("mount", "mnt");
m.insert("user", "user");
m.insert("uts", "uts");
m.insert("ipc", "ipc");
m.insert("cgroup", "cgroup");
m
};
}

View File

@@ -1,23 +0,0 @@
// Copyright (c) 2019 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::configs::Config;
use std::io::Result;
pub trait Validator {
fn validate(&self, config: &Config) -> Result<()> {
Ok(())
}
}
pub struct ConfigValidator {}
impl Validator for ConfigValidator {}
impl ConfigValidator {
fn new() -> Self {
ConfigValidator {}
}
}

View File

@@ -8,7 +8,7 @@ use libc::pid_t;
use oci::{ContainerState, LinuxDevice, LinuxIdMapping};
use oci::{Hook, Linux, LinuxNamespace, LinuxResources, Spec};
use std::clone::Clone;
use std::ffi::{CStr, CString};
use std::ffi::CString;
use std::fmt::Display;
use std::fs;
use std::os::unix::io::RawFd;
@@ -48,6 +48,7 @@ use oci::State as OCIState;
use std::collections::HashMap;
use std::os::unix::io::FromRawFd;
use std::str::FromStr;
use std::sync::Arc;
use slog::{info, o, Logger};
@@ -57,13 +58,11 @@ use crate::sync_with_async::{read_async, write_async};
use async_trait::async_trait;
use rlimit::{setrlimit, Resource, Rlim};
use tokio::io::AsyncBufReadExt;
use tokio::sync::Mutex;
use crate::utils;
const STATE_FILENAME: &str = "state.json";
const EXEC_FIFO_FILENAME: &str = "exec.fifo";
const VER_MARKER: &str = "1.2.5";
const PID_NS_PATH: &str = "/proc/self/ns/pid";
const INIT: &str = "INIT";
const NO_PIVOT: &str = "NO_PIVOT";
@@ -92,10 +91,6 @@ impl ContainerStatus {
self.cur_status
}
fn pre_status(&self) -> ContainerState {
self.pre_status
}
fn transition(&mut self, to: ContainerState) {
self.pre_status = self.status();
self.cur_status = to;
@@ -106,6 +101,9 @@ pub type Config = CreateOpts;
type NamespaceType = String;
lazy_static! {
// This locker ensures the child exit signal will be received by the right receiver.
pub static ref WAIT_PID_LOCKER: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
static ref NAMESPACES: HashMap<&'static str, CloneFlags> = {
let mut m = HashMap::new();
m.insert("user", CloneFlags::CLONE_NEWUSER);
@@ -341,7 +339,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
Err(_e) => sched::unshare(CloneFlags::CLONE_NEWPID)?,
}
match fork() {
match unsafe { fork() } {
Ok(ForkResult::Parent { child, .. }) => {
log_child!(
cfd_log,
@@ -464,7 +462,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
// Ref: https://github.com/opencontainers/runc/commit/50a19c6ff828c58e5dab13830bd3dacde268afe5
//
if !nses.is_empty() {
prctl::set_dumpable(false)
capctl::prctl::set_dumpable(false)
.map_err(|e| anyhow!(e).context("set process non-dumpable failed"))?;
}
@@ -540,7 +538,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
// notify parent to run prestart hooks
write_sync(cwfd, SYNC_SUCCESS, "")?;
// wait parent run prestart hooks
let _ = read_sync(crfd)?;
read_sync(crfd)?;
}
if mount_fd != -1 {
@@ -597,7 +595,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
// NoNewPeiviledges, Drop capabilities
if oci_process.no_new_privileges {
prctl::set_no_new_privileges(true).map_err(|_| anyhow!("cannot set no new privileges"))?;
capctl::prctl::set_no_new_privs().map_err(|_| anyhow!("cannot set no new privileges"))?;
}
if oci_process.capabilities.is_some() {
@@ -607,8 +605,6 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
if init {
// notify parent to run poststart hooks
// cfd is closed when return from join_namespaces
// should retunr cfile instead of cfd?
write_sync(cwfd, SYNC_SUCCESS, "")?;
}
@@ -817,7 +813,7 @@ impl BaseContainer for LinuxContainer {
if stat::stat(fifo_file.as_str()).is_ok() {
return Err(anyhow!("exec fifo exists"));
}
unistd::mkfifo(fifo_file.as_str(), Mode::from_bits(0o622).unwrap())?;
unistd::mkfifo(fifo_file.as_str(), Mode::from_bits(0o644).unwrap())?;
fifofd = fcntl::open(
fifo_file.as_str(),
@@ -1076,9 +1072,8 @@ fn do_exec(args: &[String]) -> ! {
.iter()
.map(|s| CString::new(s.to_string()).unwrap_or_default())
.collect();
let a: Vec<&CStr> = sa.iter().map(|s| s.as_c_str()).collect();
let _ = unistd::execvp(p.as_c_str(), a.as_slice()).map_err(|e| match e {
let _ = unistd::execvp(p.as_c_str(), &sa).map_err(|e| match e {
nix::Error::Sys(errno) => {
std::process::exit(errno as i32);
}
@@ -1251,7 +1246,7 @@ async fn join_namespaces(
if p.init {
info!(logger, "notify child parent ready to run prestart hook!");
let _ = read_async(pipe_r).await?;
read_async(pipe_r).await?;
info!(logger, "get ready to run prestart hook!");
@@ -1311,7 +1306,7 @@ fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIdMapping]) -> Resul
fn setid(uid: Uid, gid: Gid) -> Result<()> {
// set uid/gid
prctl::set_keep_capabilities(true)
capctl::prctl::set_keepcaps(true)
.map_err(|e| anyhow!(e).context("set keep capabilities returned"))?;
{
@@ -1325,7 +1320,7 @@ fn setid(uid: Uid, gid: Gid) -> Result<()> {
capabilities::reset_effective()?;
}
prctl::set_keep_capabilities(false)
capctl::prctl::set_keepcaps(false)
.map_err(|e| anyhow!(e).context("set keep capabilities returned"))?;
Ok(())
@@ -1399,18 +1394,8 @@ impl LinuxContainer {
logger: logger.new(o!("module" => "rustjail", "subsystem" => "container", "cid" => id)),
})
}
fn load<T: Into<String>>(_id: T, _base: T) -> Result<Self> {
Err(anyhow!("not supported"))
}
}
// Handle the differing rlimit types for different targets
#[cfg(target_env = "musl")]
type RlimitsType = libc::c_int;
#[cfg(target_env = "gnu")]
type RlimitsType = libc::__rlimit_resource_t;
fn setgroups(grps: &[libc::gid_t]) -> Result<()> {
let ret = unsafe { libc::setgroups(grps.len(), grps.as_ptr() as *const libc::gid_t) };
Errno::result(ret).map(drop)?;
@@ -1467,6 +1452,8 @@ async fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> {
})
.collect();
// Avoid the exit signal to be reaped by the global reaper.
let _wait_locker = WAIT_PID_LOCKER.lock().await;
let mut child = tokio::process::Command::new(path)
.args(args.iter())
.envs(env.iter())
@@ -1550,6 +1537,7 @@ mod tests {
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use tempfile::tempdir;
use tokio::process::Command;
macro_rules! sl {
() => {
@@ -1557,12 +1545,27 @@ mod tests {
};
}
async fn which(cmd: &str) -> String {
let output: std::process::Output = Command::new("which")
.arg(cmd)
.output()
.await
.expect("which command failed to run");
match String::from_utf8(output.stdout) {
Ok(v) => v.trim_end_matches('\n').to_string(),
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
}
}
#[tokio::test]
async fn test_execute_hook() {
let xargs = which("xargs").await;
execute_hook(
&slog_scope::logger(),
&Hook {
path: "/usr/bin/xargs".to_string(),
path: xargs,
args: vec![],
env: vec![],
timeout: None,
@@ -1582,10 +1585,12 @@ mod tests {
#[tokio::test]
async fn test_execute_hook_with_timeout() {
let sleep = which("sleep").await;
let res = execute_hook(
&slog_scope::logger(),
&Hook {
path: "/usr/bin/sleep".to_string(),
path: sleep,
args: vec!["2".to_string()],
env: vec![],
timeout: Some(1),
@@ -1622,7 +1627,7 @@ mod tests {
let pre_status = status.status();
status.transition(*s);
assert_eq!(pre_status, status.pre_status());
assert_eq!(pre_status, status.pre_status);
}
}

View File

@@ -3,15 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
// #![allow(unused_attributes)]
// #![allow(unused_imports)]
// #![allow(unused_variables)]
// #![allow(unused_mut)]
#![allow(dead_code)]
// #![allow(deprecated)]
// #![allow(unused_must_use)]
#![allow(non_upper_case_globals)]
// #![allow(unused_comparisons)]
#[macro_use]
#[cfg(test)]
extern crate serial_test;
@@ -23,7 +15,7 @@ extern crate caps;
extern crate protocols;
#[macro_use]
extern crate scopeguard;
extern crate prctl;
extern crate capctl;
#[macro_use]
extern crate lazy_static;
extern crate libc;
@@ -47,16 +39,6 @@ pub mod sync;
pub mod sync_with_async;
pub mod utils;
pub mod validator;
// pub mod factory;
//pub mod configs;
// pub mod devices;
// pub mod init;
// pub mod rootfs;
// pub mod capabilities;
// pub mod console;
// pub mod stats;
// pub mod user;
//pub mod intelrdt;
use std::collections::HashMap;
@@ -474,10 +456,6 @@ fn linux_grpc_to_oci(l: &grpc::Linux) -> oci::Linux {
}
}
fn linux_oci_to_grpc(_l: &oci::Linux) -> grpc::Linux {
grpc::Linux::default()
}
pub fn grpc_to_oci(grpc: &grpc::Spec) -> oci::Spec {
// process
let process = if grpc.Process.is_some() {
@@ -533,7 +511,6 @@ pub fn grpc_to_oci(grpc: &grpc::Spec) -> oci::Spec {
#[cfg(test)]
mod tests {
#[allow(unused_macros)]
#[macro_export]
macro_rules! skip_if_not_root {
() => {

View File

@@ -62,58 +62,56 @@ const PROC_SUPER_MAGIC: libc::c_uint = 0x00009fa0;
lazy_static! {
static ref PROPAGATION: HashMap<&'static str, MsFlags> = {
let mut m = HashMap::new();
m.insert("shared", MsFlags::MS_SHARED);
m.insert("rshared", MsFlags::MS_SHARED | MsFlags::MS_REC);
m.insert("private", MsFlags::MS_PRIVATE);
m.insert("rprivate", MsFlags::MS_PRIVATE | MsFlags::MS_REC);
m.insert("slave", MsFlags::MS_SLAVE);
m.insert("rshared", MsFlags::MS_SHARED | MsFlags::MS_REC);
m.insert("rslave", MsFlags::MS_SLAVE | MsFlags::MS_REC);
m.insert("runbindable", MsFlags::MS_UNBINDABLE | MsFlags::MS_REC);
m.insert("shared", MsFlags::MS_SHARED);
m.insert("slave", MsFlags::MS_SLAVE);
m.insert("unbindable", MsFlags::MS_UNBINDABLE);
m
};
static ref OPTIONS: HashMap<&'static str, (bool, MsFlags)> = {
let mut m = HashMap::new();
m.insert("acl", (false, MsFlags::MS_POSIXACL));
m.insert("async", (true, MsFlags::MS_SYNCHRONOUS));
m.insert("atime", (true, MsFlags::MS_NOATIME));
m.insert("bind", (false, MsFlags::MS_BIND));
m.insert("defaults", (false, MsFlags::empty()));
m.insert("dev", (true, MsFlags::MS_NODEV));
m.insert("diratime", (true, MsFlags::MS_NODIRATIME));
m.insert("dirsync", (false, MsFlags::MS_DIRSYNC));
m.insert("exec", (true, MsFlags::MS_NOEXEC));
m.insert("iversion", (false, MsFlags::MS_I_VERSION));
m.insert("lazytime", (false, MsFlags::MS_LAZYTIME));
m.insert("loud", (true, MsFlags::MS_SILENT));
m.insert("mand", (false, MsFlags::MS_MANDLOCK));
m.insert("noacl", (true, MsFlags::MS_POSIXACL));
m.insert("noatime", (false, MsFlags::MS_NOATIME));
m.insert("nodev", (false, MsFlags::MS_NODEV));
m.insert("nodiratime", (false, MsFlags::MS_NODIRATIME));
m.insert("noexec", (false, MsFlags::MS_NOEXEC));
m.insert("noiversion", (true, MsFlags::MS_I_VERSION));
m.insert("nolazytime", (true, MsFlags::MS_LAZYTIME));
m.insert("nomand", (true, MsFlags::MS_MANDLOCK));
m.insert("norelatime", (true, MsFlags::MS_RELATIME));
m.insert("nostrictatime", (true, MsFlags::MS_STRICTATIME));
m.insert("nosuid", (false, MsFlags::MS_NOSUID));
m.insert("rbind", (false, MsFlags::MS_BIND | MsFlags::MS_REC));
m.insert("relatime", (false, MsFlags::MS_RELATIME));
m.insert("remount", (false, MsFlags::MS_REMOUNT));
m.insert("ro", (false, MsFlags::MS_RDONLY));
m.insert("rw", (true, MsFlags::MS_RDONLY));
m.insert("suid", (true, MsFlags::MS_NOSUID));
m.insert("nosuid", (false, MsFlags::MS_NOSUID));
m.insert("dev", (true, MsFlags::MS_NODEV));
m.insert("nodev", (false, MsFlags::MS_NODEV));
m.insert("exec", (true, MsFlags::MS_NOEXEC));
m.insert("noexec", (false, MsFlags::MS_NOEXEC));
m.insert("sync", (false, MsFlags::MS_SYNCHRONOUS));
m.insert("async", (true, MsFlags::MS_SYNCHRONOUS));
m.insert("dirsync", (false, MsFlags::MS_DIRSYNC));
m.insert("remount", (false, MsFlags::MS_REMOUNT));
m.insert("mand", (false, MsFlags::MS_MANDLOCK));
m.insert("nomand", (true, MsFlags::MS_MANDLOCK));
m.insert("atime", (true, MsFlags::MS_NOATIME));
m.insert("noatime", (false, MsFlags::MS_NOATIME));
m.insert("diratime", (true, MsFlags::MS_NODIRATIME));
m.insert("nodiratime", (false, MsFlags::MS_NODIRATIME));
m.insert("bind", (false, MsFlags::MS_BIND));
m.insert("rbind", (false, MsFlags::MS_BIND | MsFlags::MS_REC));
m.insert("unbindable", (false, MsFlags::MS_UNBINDABLE));
m.insert(
"runbindable",
(false, MsFlags::MS_UNBINDABLE | MsFlags::MS_REC),
);
m.insert("private", (false, MsFlags::MS_PRIVATE));
m.insert("rprivate", (false, MsFlags::MS_PRIVATE | MsFlags::MS_REC));
m.insert("shared", (false, MsFlags::MS_SHARED));
m.insert("rshared", (false, MsFlags::MS_SHARED | MsFlags::MS_REC));
m.insert("slave", (false, MsFlags::MS_SLAVE));
m.insert("rslave", (false, MsFlags::MS_SLAVE | MsFlags::MS_REC));
m.insert("relatime", (false, MsFlags::MS_RELATIME));
m.insert("norelatime", (true, MsFlags::MS_RELATIME));
m.insert("silent", (false, MsFlags::MS_SILENT));
m.insert("strictatime", (false, MsFlags::MS_STRICTATIME));
m.insert("nostrictatime", (true, MsFlags::MS_STRICTATIME));
m.insert("suid", (true, MsFlags::MS_NOSUID));
m.insert("sync", (false, MsFlags::MS_SYNCHRONOUS));
m
};
}
#[inline(always)]
#[allow(unused_variables)]
pub fn mount<
P1: ?Sized + NixPath,
P2: ?Sized + NixPath,
@@ -133,7 +131,6 @@ pub fn mount<
}
#[inline(always)]
#[allow(unused_variables)]
pub fn umount2<P: ?Sized + NixPath>(
target: &P,
flags: MntFlags,
@@ -192,7 +189,7 @@ pub fn init_rootfs(
let mut bind_mount_dev = false;
for m in &spec.mounts {
let (mut flags, data) = parse_mount(&m);
let (mut flags, pgflags, data) = parse_mount(&m);
if !m.destination.starts_with('/') || m.destination.contains("..") {
return Err(anyhow!(
"the mount destination {} is invalid",
@@ -234,13 +231,15 @@ pub fn init_rootfs(
// effective.
// first check that we have non-default options required before attempting a
// remount
if m.r#type == "bind" {
for o in &m.options {
if let Some(fl) = PROPAGATION.get(o.as_str()) {
let dest = secure_join(rootfs, &m.destination);
mount(None::<&str>, dest.as_str(), None::<&str>, *fl, None::<&str>)?;
}
}
if m.r#type == "bind" && !pgflags.is_empty() {
let dest = secure_join(rootfs, &m.destination);
mount(
None::<&str>,
dest.as_str(),
None::<&str>,
pgflags,
None::<&str>,
)?;
}
}
}
@@ -451,7 +450,6 @@ fn mount_cgroups(
Ok(())
}
#[allow(unused_variables)]
fn pivot_root<P1: ?Sized + NixPath, P2: ?Sized + NixPath>(
new_root: &P1,
put_old: &P2,
@@ -584,7 +582,6 @@ fn parse_mount_table() -> Result<Vec<Info>> {
}
#[inline(always)]
#[allow(unused_variables)]
fn chroot<P: ?Sized + NixPath>(path: &P) -> Result<(), nix::Error> {
#[cfg(not(test))]
return unistd::chroot(path);
@@ -657,26 +654,27 @@ pub fn ms_move_root(rootfs: &str) -> Result<bool> {
Ok(true)
}
fn parse_mount(m: &Mount) -> (MsFlags, String) {
fn parse_mount(m: &Mount) -> (MsFlags, MsFlags, String) {
let mut flags = MsFlags::empty();
let mut pgflags = MsFlags::empty();
let mut data = Vec::new();
for o in &m.options {
match OPTIONS.get(o.as_str()) {
Some(v) => {
let (clear, fl) = *v;
if clear {
flags &= !fl;
} else {
flags |= fl;
}
if let Some(v) = OPTIONS.get(o.as_str()) {
let (clear, fl) = *v;
if clear {
flags &= !fl;
} else {
flags |= fl;
}
None => data.push(o.clone()),
} else if let Some(fl) = PROPAGATION.get(o.as_str()) {
pgflags |= *fl;
} else {
data.push(o.clone());
}
}
(flags, data.join(","))
(flags, pgflags, data.join(","))
}
// This function constructs a canonicalized path by combining the `rootfs` and `unsafe_path` elements.
@@ -922,7 +920,7 @@ pub fn finish_rootfs(cfd_log: RawFd, spec: &Spec) -> Result<()> {
for m in spec.mounts.iter() {
if m.destination == "/dev" {
let (flags, _) = parse_mount(m);
let (flags, _, _) = parse_mount(m);
if flags.contains(MsFlags::MS_RDONLY) {
mount(
Some("/dev"),

View File

@@ -28,16 +28,6 @@ fn contain_namespace(nses: &[LinuxNamespace], key: &str) -> bool {
false
}
fn get_namespace_path(nses: &[LinuxNamespace], key: &str) -> Result<String> {
for ns in nses {
if ns.r#type.as_str() == key {
return Ok(ns.path.clone());
}
}
Err(einval())
}
fn rootfs(root: &str) -> Result<()> {
let path = PathBuf::from(root);
// not absolute path or not exists
@@ -166,31 +156,6 @@ lazy_static! {
};
}
fn check_host_ns(path: &str) -> Result<()> {
let cpath = PathBuf::from(path);
let hpath = PathBuf::from("/proc/self/ns/net");
let real_hpath = hpath
.read_link()
.context(format!("read link {:?}", hpath))?;
let meta = cpath
.symlink_metadata()
.context(format!("symlink metadata {:?}", cpath))?;
let file_type = meta.file_type();
if !file_type.is_symlink() {
return Ok(());
}
let real_cpath = cpath
.read_link()
.context(format!("read link {:?}", cpath))?;
if real_cpath == real_hpath {
return Err(einval());
}
Ok(())
}
fn sysctl(oci: &Spec) -> Result<()> {
let linux = get_linux(oci)?;
@@ -334,19 +299,6 @@ mod tests {
assert_eq!(contain_namespace(&namespaces, ""), false);
assert_eq!(contain_namespace(&namespaces, "Net"), false);
assert_eq!(contain_namespace(&namespaces, "ipc"), false);
assert_eq!(
get_namespace_path(&namespaces, "net").unwrap(),
"/sys/cgroups/net"
);
assert_eq!(
get_namespace_path(&namespaces, "uts").unwrap(),
"/sys/cgroups/uts"
);
get_namespace_path(&namespaces, "").unwrap_err();
get_namespace_path(&namespaces, "Uts").unwrap_err();
get_namespace_path(&namespaces, "ipc").unwrap_err();
}
#[test]
@@ -528,12 +480,6 @@ mod tests {
rootless_euid(&spec).unwrap();
}
#[test]
fn test_check_host_ns() {
check_host_ns("/proc/self/ns/net").unwrap_err();
check_host_ns("/proc/sys/net/ipv4/tcp_sack").unwrap();
}
#[test]
fn test_sysctl() {
let mut spec = Spec::default();

140
src/agent/src/ccw.rs Normal file
View File

@@ -0,0 +1,140 @@
// Copyright (c) IBM Corp. 2021
//
// SPDX-License-Identifier: Apache-2.0
//
use std::fmt;
use std::str::FromStr;
use anyhow::anyhow;
// CCW bus ID follow the format <xx>.<d>.<xxxx> [1, p. 11], where
// - <xx> is the channel subsystem ID, which is always 0 from the guest side, but different from
// the host side, e.g. 0xfe for virtio-*-ccw [1, p. 435],
// - <d> is the subchannel set ID, which ranges from 0-3 [2], and
// - <xxxx> is the device number (0000-ffff; leading zeroes can be omitted,
// e.g. 3 instead of 0003).
// [1] https://www.ibm.com/docs/en/linuxonibm/pdf/lku4dd04.pdf
// [2] https://qemu.readthedocs.io/en/latest/system/s390x/css.html
// Maximum subchannel set ID
const SUBCHANNEL_SET_MAX: u8 = 3;
// CCW device. From the guest side, the first field is always 0 and can therefore be omitted.
#[derive(Copy, Clone, Debug)]
pub struct Device {
subchannel_set_id: u8,
device_number: u16,
}
impl Device {
pub fn new(subchannel_set_id: u8, device_number: u16) -> anyhow::Result<Self> {
if subchannel_set_id > SUBCHANNEL_SET_MAX {
return Err(anyhow!(
"Subchannel set ID {:?} should be in range [0..{}]",
subchannel_set_id,
SUBCHANNEL_SET_MAX
));
}
Ok(Device {
subchannel_set_id,
device_number,
})
}
}
impl FromStr for Device {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
let split: Vec<&str> = s.split('.').collect();
if split.len() != 3 {
return Err(anyhow!(
"Wrong bus format. It needs to be in the form 0.<d>.<xxxx>, got {:?}",
s
));
}
if split[0] != "0" {
return Err(anyhow!(
"Wrong bus format. First digit needs to be 0, but is {:?}",
split[0]
));
}
let subchannel_set_id = match split[1].parse::<u8>() {
Ok(id) => id,
Err(_) => {
return Err(anyhow!(
"Wrong bus format. Second digit needs to be 0-3, but is {:?}",
split[1]
))
}
};
let device_number = match u16::from_str_radix(split[2], 16) {
Ok(id) => id,
Err(_) => {
return Err(anyhow!(
"Wrong bus format. Third digit needs to be 0-ffff, but is {:?}",
split[2]
))
}
};
Device::new(subchannel_set_id, device_number)
}
}
impl fmt::Display for Device {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "0.{}.{:04x}", self.subchannel_set_id, self.device_number)
}
}
#[cfg(test)]
mod tests {
use crate::ccw::Device;
use std::str::FromStr;
#[test]
fn test_new_device() {
// Valid devices
let device = Device::new(0, 0).unwrap();
assert_eq!(format!("{}", device), "0.0.0000");
let device = Device::new(3, 0xffff).unwrap();
assert_eq!(format!("{}", device), "0.3.ffff");
// Invalid device
let device = Device::new(4, 0);
assert!(device.is_err());
}
#[test]
fn test_device_from_str() {
// Valid devices
let device = Device::from_str("0.0.0").unwrap();
assert_eq!(format!("{}", device), "0.0.0000");
let device = Device::from_str("0.0.0000").unwrap();
assert_eq!(format!("{}", device), "0.0.0000");
let device = Device::from_str("0.3.ffff").unwrap();
assert_eq!(format!("{}", device), "0.3.ffff");
// Invalid devices
let device = Device::from_str("0.0");
assert!(device.is_err());
let device = Device::from_str("1.0.0");
assert!(device.is_err());
let device = Device::from_str("0.not_a_subchannel_set_id.0");
assert!(device.is_err());
let device = Device::from_str("0.0.not_a_device_number");
assert!(device.is_err());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -145,9 +145,10 @@ fn run_in_child(slave_fd: libc::c_int, shell: String) -> Result<()> {
}
let cmd = CString::new(shell).unwrap();
let args: Vec<CString> = Vec::new();
// run shell
let _ = unistd::execvp(cmd.as_c_str(), &[]).map_err(|e| match e {
let _ = unistd::execvp(cmd.as_c_str(), &args).map_err(|e| match e {
nix::Error::Sys(errno) => {
std::process::exit(errno as i32);
}
@@ -205,7 +206,7 @@ async fn run_debug_console_vsock<T: AsyncRead + AsyncWrite>(
let slave_fd = pseudo.slave;
match fork() {
match unsafe { fork() } {
Ok(ForkResult::Child) => run_in_child(slave_fd, shell),
Ok(ForkResult::Parent { child: child_pid }) => {
run_in_parent(logger.clone(), stream, pseudo, child_pid).await

View File

@@ -14,14 +14,20 @@ use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
#[cfg(target_arch = "s390x")]
use crate::ccw;
use crate::linux_abi::*;
use crate::mount::{DRIVER_BLK_TYPE, DRIVER_MMIO_BLK_TYPE, DRIVER_NVDIMM_TYPE, DRIVER_SCSI_TYPE};
use crate::mount::{
DRIVER_BLK_CCW_TYPE, DRIVER_BLK_TYPE, DRIVER_MMIO_BLK_TYPE, DRIVER_NVDIMM_TYPE,
DRIVER_SCSI_TYPE,
};
use crate::pci;
use crate::sandbox::Sandbox;
use crate::uevent::{wait_for_uevent, Uevent, UeventMatcher};
use anyhow::{anyhow, Result};
use oci::{LinuxDeviceCgroup, LinuxResources, Spec};
use protocols::agent::Device;
use tracing::instrument;
// Convenience macro to obtain the scope logger
macro_rules! sl {
@@ -32,17 +38,21 @@ macro_rules! sl {
const VM_ROOTFS: &str = "/";
#[derive(Debug)]
struct DevIndexEntry {
idx: usize,
residx: Vec<usize>,
}
#[derive(Debug)]
struct DevIndex(HashMap<String, DevIndexEntry>);
#[instrument]
pub fn rescan_pci_bus() -> Result<()> {
online_device(SYSFS_PCI_BUS_RESCAN_FILE)
}
#[instrument]
pub fn online_device(path: &str) -> Result<()> {
fs::write(path, "1")?;
Ok(())
@@ -51,6 +61,7 @@ pub fn online_device(path: &str) -> Result<()> {
// pcipath_to_sysfs fetches the sysfs path for a PCI path, relative to
// the sysfs path for the PCI host bridge, based on the PCI path
// provided.
#[instrument]
fn pcipath_to_sysfs(root_bus_sysfs: &str, pcipath: &pci::Path) -> Result<String> {
let mut bus = "0000:00".to_string();
let mut relpath = String::new();
@@ -109,6 +120,7 @@ impl UeventMatcher for ScsiBlockMatcher {
}
}
#[instrument]
pub async fn get_scsi_device_name(
sandbox: &Arc<Mutex<Sandbox>>,
scsi_addr: &str,
@@ -141,6 +153,7 @@ impl UeventMatcher for VirtioBlkPciMatcher {
}
}
#[instrument]
pub async fn get_virtio_blk_pci_device_name(
sandbox: &Arc<Mutex<Sandbox>>,
pcipath: &pci::Path,
@@ -155,6 +168,47 @@ pub async fn get_virtio_blk_pci_device_name(
Ok(format!("{}/{}", SYSTEM_DEV_PATH, &uev.devname))
}
#[cfg(target_arch = "s390x")]
#[derive(Debug)]
struct VirtioBlkCCWMatcher {
rex: Regex,
}
#[cfg(target_arch = "s390x")]
impl VirtioBlkCCWMatcher {
fn new(root_bus_path: &str, device: &ccw::Device) -> Self {
let re = format!(
r"^{}/0\.[0-3]\.[0-9a-f]{{1,4}}/{}/virtio[0-9]+/block/",
root_bus_path, device
);
VirtioBlkCCWMatcher {
rex: Regex::new(&re).unwrap(),
}
}
}
#[cfg(target_arch = "s390x")]
impl UeventMatcher for VirtioBlkCCWMatcher {
fn is_match(&self, uev: &Uevent) -> bool {
uev.action == "add" && self.rex.is_match(&uev.devpath) && !uev.devname.is_empty()
}
}
#[cfg(target_arch = "s390x")]
#[instrument]
pub async fn get_virtio_blk_ccw_device_name(
sandbox: &Arc<Mutex<Sandbox>>,
device: &ccw::Device,
) -> Result<String> {
let matcher = VirtioBlkCCWMatcher::new(&create_ccw_root_bus_path(), device);
let uev = wait_for_uevent(sandbox, matcher).await?;
let devname = uev.devname;
return match Path::new(SYSTEM_DEV_PATH).join(&devname).to_str() {
Some(path) => Ok(String::from(path)),
None => Err(anyhow!("CCW device name {} is not valid UTF-8", &devname)),
};
}
#[derive(Debug)]
struct PmemBlockMatcher {
suffix: String,
@@ -177,6 +231,7 @@ impl UeventMatcher for PmemBlockMatcher {
}
}
#[instrument]
pub async fn wait_for_pmem_device(sandbox: &Arc<Mutex<Sandbox>>, devpath: &str) -> Result<()> {
let devname = match devpath.strip_prefix("/dev/") {
Some(dev) => dev,
@@ -201,6 +256,7 @@ pub async fn wait_for_pmem_device(sandbox: &Arc<Mutex<Sandbox>>, devpath: &str)
}
/// Scan SCSI bus for the given SCSI address(SCSI-Id and LUN)
#[instrument]
fn scan_scsi_bus(scsi_addr: &str) -> Result<()> {
let tokens: Vec<&str> = scsi_addr.split(':').collect();
if tokens.len() != 2 {
@@ -235,6 +291,7 @@ fn scan_scsi_bus(scsi_addr: &str) -> Result<()> {
// the same device in the list of devices provided through the OCI spec.
// This is needed to update information about minor/major numbers that cannot
// be predicted from the caller.
#[instrument]
fn update_spec_device_list(device: &Device, spec: &mut Spec, devidx: &DevIndex) -> Result<()> {
let major_id: c_uint;
let minor_id: c_uint;
@@ -311,6 +368,7 @@ fn update_spec_device_list(device: &Device, spec: &mut Spec, devidx: &DevIndex)
// device.Id should be the predicted device name (vda, vdb, ...)
// device.VmPath already provides a way to send it in
#[instrument]
async fn virtiommio_blk_device_handler(
device: &Device,
spec: &mut Spec,
@@ -325,6 +383,7 @@ async fn virtiommio_blk_device_handler(
}
// device.Id should be a PCI path string
#[instrument]
async fn virtio_blk_device_handler(
device: &Device,
spec: &mut Spec,
@@ -339,7 +398,34 @@ async fn virtio_blk_device_handler(
update_spec_device_list(&dev, spec, devidx)
}
// device.id should be a CCW path string
#[cfg(target_arch = "s390x")]
#[instrument]
async fn virtio_blk_ccw_device_handler(
device: &Device,
spec: &mut Spec,
sandbox: &Arc<Mutex<Sandbox>>,
devidx: &DevIndex,
) -> Result<()> {
let mut dev = device.clone();
let ccw_device = ccw::Device::from_str(&device.id)?;
dev.vm_path = get_virtio_blk_ccw_device_name(sandbox, &ccw_device).await?;
update_spec_device_list(&dev, spec, devidx)
}
#[cfg(not(target_arch = "s390x"))]
#[instrument]
async fn virtio_blk_ccw_device_handler(
_: &Device,
_: &mut Spec,
_: &Arc<Mutex<Sandbox>>,
_: &DevIndex,
) -> Result<()> {
Err(anyhow!("CCW is only supported on s390x"))
}
// device.Id should be the SCSI address of the disk in the format "scsiID:lunID"
#[instrument]
async fn virtio_scsi_device_handler(
device: &Device,
spec: &mut Spec,
@@ -351,6 +437,7 @@ async fn virtio_scsi_device_handler(
update_spec_device_list(&dev, spec, devidx)
}
#[instrument]
async fn virtio_nvdimm_device_handler(
device: &Device,
spec: &mut Spec,
@@ -389,6 +476,7 @@ impl DevIndex {
}
}
#[instrument]
pub async fn add_devices(
devices: &[Device],
spec: &mut Spec,
@@ -403,6 +491,7 @@ pub async fn add_devices(
Ok(())
}
#[instrument]
async fn add_device(
device: &Device,
spec: &mut Spec,
@@ -427,6 +516,7 @@ async fn add_device(
match device.field_type.as_str() {
DRIVER_BLK_TYPE => virtio_blk_device_handler(device, spec, sandbox, devidx).await,
DRIVER_BLK_CCW_TYPE => virtio_blk_ccw_device_handler(device, spec, sandbox, devidx).await,
DRIVER_MMIO_BLK_TYPE => virtiommio_blk_device_handler(device, spec, sandbox, devidx).await,
DRIVER_NVDIMM_TYPE => virtio_nvdimm_device_handler(device, spec, sandbox, devidx).await,
DRIVER_SCSI_TYPE => virtio_scsi_device_handler(device, spec, sandbox, devidx).await,
@@ -437,6 +527,7 @@ async fn add_device(
// update_device_cgroup update the device cgroup for container
// to not allow access to the guest root partition. This prevents
// the container from being able to access the VM rootfs.
#[instrument]
pub fn update_device_cgroup(spec: &mut Spec) -> Result<()> {
let meta = fs::metadata(VM_ROOTFS)?;
let rdev = meta.dev();
@@ -888,6 +979,66 @@ mod tests {
assert!(!matcher_a.is_match(&uev_b));
}
#[cfg(target_arch = "s390x")]
#[tokio::test]
async fn test_virtio_blk_ccw_matcher() {
let root_bus = create_ccw_root_bus_path();
let subsystem = "block";
let devname = "vda";
let relpath = "0.0.0002";
let mut uev = crate::uevent::Uevent::default();
uev.action = crate::linux_abi::U_EVENT_ACTION_ADD.to_string();
uev.subsystem = subsystem.to_string();
uev.devname = devname.to_string();
uev.devpath = format!(
"{}/0.0.0001/{}/virtio1/{}/{}",
root_bus, relpath, subsystem, devname
);
// Valid path
let device = ccw::Device::from_str(relpath).unwrap();
let matcher = VirtioBlkCCWMatcher::new(&root_bus, &device);
assert!(matcher.is_match(&uev));
// Invalid paths
uev.devpath = format!(
"{}/0.0.0001/0.0.0003/virtio1/{}/{}",
root_bus, subsystem, devname
);
assert!(!matcher.is_match(&uev));
uev.devpath = format!("0.0.0001/{}/virtio1/{}/{}", relpath, subsystem, devname);
assert!(!matcher.is_match(&uev));
uev.devpath = format!(
"{}/0.0.0001/{}/virtio/{}/{}",
root_bus, relpath, subsystem, devname
);
assert!(!matcher.is_match(&uev));
uev.devpath = format!("{}/0.0.0001/{}/virtio1", root_bus, relpath);
assert!(!matcher.is_match(&uev));
uev.devpath = format!(
"{}/1.0.0001/{}/virtio1/{}/{}",
root_bus, relpath, subsystem, devname
);
assert!(!matcher.is_match(&uev));
uev.devpath = format!(
"{}/0.4.0001/{}/virtio1/{}/{}",
root_bus, relpath, subsystem, devname
);
assert!(!matcher.is_match(&uev));
uev.devpath = format!(
"{}/0.0.10000/{}/virtio1/{}/{}",
root_bus, relpath, subsystem, devname
);
assert!(!matcher.is_match(&uev));
}
#[tokio::test]
async fn test_scsi_block_matcher() {
let root_bus = create_pci_root_bus_path();

View File

@@ -65,6 +65,10 @@ pub fn create_pci_root_bus_path() -> String {
ret
}
#[cfg(target_arch = "s390x")]
pub fn create_ccw_root_bus_path() -> String {
String::from("/devices/css0")
}
// From https://www.kernel.org/doc/Documentation/acpi/namespace.txt
// The Linux kernel's core ACPI subsystem creates struct acpi_device
// objects for ACPI namespace objects representing devices, power resources

View File

@@ -5,8 +5,8 @@
#[macro_use]
extern crate lazy_static;
extern crate capctl;
extern crate oci;
extern crate prctl;
extern crate prometheus;
extern crate protocols;
extern crate regex;
@@ -32,7 +32,10 @@ use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::process::exit;
use std::sync::Arc;
use tracing::{instrument, span};
#[cfg(target_arch = "s390x")]
mod ccw;
mod config;
mod console;
mod device;
@@ -51,11 +54,12 @@ mod test_utils;
mod uevent;
mod util;
mod version;
mod watcher;
use mount::{cgroups_mount, general_mount};
use sandbox::Sandbox;
use signal::setup_signal_handler;
use slog::Logger;
use slog::{error, info, o, warn, Logger};
use uevent::watch_uevents;
use futures::future::join_all;
@@ -70,6 +74,7 @@ use tokio::{
};
mod rpc;
mod tracer;
const NAME: &str = "kata-agent";
const KERNEL_CMDLINE_FILE: &str = "/proc/cmdline";
@@ -79,6 +84,7 @@ lazy_static! {
Arc::new(RwLock::new(config::AgentConfig::new()));
}
#[instrument]
fn announce(logger: &Logger, config: &AgentConfig) {
info!(logger, "announce";
"agent-commit" => version::VERSION_COMMIT,
@@ -199,6 +205,17 @@ async fn real_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
ttrpc_log_guard = Ok(slog_stdlog::init().map_err(|e| e)?);
}
if config.tracing != tracer::TraceType::Disabled {
let _ = tracer::setup_tracing(NAME, &logger, &config)?;
}
let root = span!(tracing::Level::TRACE, "root-span", work_units = 2);
// XXX: Start the root trace transaction.
//
// XXX: Note that *ALL* spans needs to start after this point!!
let _enter = root.enter();
// Start the sandbox and wait for its ttRPC server to end
start_sandbox(&logger, &config, init_mode, &mut tasks, shutdown_rx.clone()).await?;
@@ -227,6 +244,10 @@ async fn real_main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
}
if config.tracing != tracer::TraceType::Disabled {
tracer::end_tracing();
}
eprintln!("{} shutdown complete", NAME);
Ok(())
@@ -248,6 +269,7 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
if args.len() == 2 && args[1] == "init" {
reset_sigpipe();
rustjail::container::init_child();
exit(0);
}
@@ -259,6 +281,7 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
rt.block_on(real_main())
}
#[instrument]
async fn start_sandbox(
logger: &Logger,
config: &AgentConfig,
@@ -305,7 +328,7 @@ async fn start_sandbox(
let mut server = rpc::start(sandbox.clone(), config.server_addr.as_str());
server.start().await?;
let _ = rx.await?;
rx.await?;
server.shutdown().await?;
Ok(())
@@ -345,6 +368,7 @@ fn init_agent_as_init(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result
Ok(())
}
#[instrument]
fn sethostname(hostname: &OsStr) -> Result<()> {
let size = hostname.len() as usize;
@@ -358,5 +382,16 @@ fn sethostname(hostname: &OsStr) -> Result<()> {
}
}
// The Rust standard library had suppressed the default SIGPIPE behavior,
// see https://github.com/rust-lang/rust/pull/13158.
// Since the parent's signal handler would be inherited by it's child process,
// thus we should re-enable the standard SIGPIPE behavior as a workaround to
// fix the issue of https://github.com/kata-containers/kata-containers/issues/1887.
fn reset_sigpipe() {
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
}
use crate::config::AgentConfig;
use std::os::unix::io::{FromRawFd, RawFd};

View File

@@ -8,6 +8,7 @@ extern crate procfs;
use prometheus::{Encoder, Gauge, GaugeVec, IntCounter, TextEncoder};
use anyhow::Result;
use tracing::instrument;
const NAMESPACE_KATA_AGENT: &str = "kata_agent";
const NAMESPACE_KATA_GUEST: &str = "kata_guest";
@@ -68,6 +69,7 @@ lazy_static! {
prometheus::register_gauge_vec!(format!("{}_{}",NAMESPACE_KATA_GUEST,"meminfo").as_ref() , "Statistics about memory usage in the system.", &["item"]).unwrap();
}
#[instrument]
pub fn get_metrics(_: &protocols::agent::GetMetricsRequest) -> Result<String> {
AGENT_SCRAPE_COUNT.inc();
@@ -87,6 +89,7 @@ pub fn get_metrics(_: &protocols::agent::GetMetricsRequest) -> Result<String> {
Ok(String::from_utf8(buffer).unwrap())
}
#[instrument]
fn update_agent_metrics() {
let me = procfs::process::Process::myself();
@@ -136,6 +139,7 @@ fn update_agent_metrics() {
}
}
#[instrument]
fn update_guest_metrics() {
// try get load and task info
match procfs::LoadAverage::new() {
@@ -218,6 +222,7 @@ fn update_guest_metrics() {
}
}
#[instrument]
fn set_gauge_vec_meminfo(gv: &prometheus::GaugeVec, meminfo: &procfs::Meminfo) {
gv.with_label_values(&["mem_total"])
.set(meminfo.mem_total as f64);
@@ -332,6 +337,7 @@ fn set_gauge_vec_meminfo(gv: &prometheus::GaugeVec, meminfo: &procfs::Meminfo) {
.set(meminfo.k_reclaimable.unwrap_or(0) as f64);
}
#[instrument]
fn set_gauge_vec_cpu_time(gv: &prometheus::GaugeVec, cpu: &str, cpu_time: &procfs::CpuTime) {
gv.with_label_values(&[cpu, "user"])
.set(cpu_time.user as f64);
@@ -355,6 +361,7 @@ fn set_gauge_vec_cpu_time(gv: &prometheus::GaugeVec, cpu: &str, cpu_time: &procf
.set(cpu_time.guest_nice.unwrap_or(0.0) as f64);
}
#[instrument]
fn set_gauge_vec_diskstat(gv: &prometheus::GaugeVec, diskstat: &procfs::DiskStat) {
gv.with_label_values(&[diskstat.name.as_str(), "reads"])
.set(diskstat.reads as f64);
@@ -393,6 +400,7 @@ fn set_gauge_vec_diskstat(gv: &prometheus::GaugeVec, diskstat: &procfs::DiskStat
}
// set_gauge_vec_netdev set gauge for NetDevLine
#[instrument]
fn set_gauge_vec_netdev(gv: &prometheus::GaugeVec, status: &procfs::net::DeviceStatus) {
gv.with_label_values(&[status.name.as_str(), "recv_bytes"])
.set(status.recv_bytes as f64);
@@ -429,6 +437,7 @@ fn set_gauge_vec_netdev(gv: &prometheus::GaugeVec, status: &procfs::net::DeviceS
}
// set_gauge_vec_proc_status set gauge for ProcStatus
#[instrument]
fn set_gauge_vec_proc_status(gv: &prometheus::GaugeVec, status: &procfs::process::Status) {
gv.with_label_values(&["vmpeak"])
.set(status.vmpeak.unwrap_or(0) as f64);
@@ -469,6 +478,7 @@ fn set_gauge_vec_proc_status(gv: &prometheus::GaugeVec, status: &procfs::process
}
// set_gauge_vec_proc_io set gauge for ProcIO
#[instrument]
fn set_gauge_vec_proc_io(gv: &prometheus::GaugeVec, io_stat: &procfs::process::Io) {
gv.with_label_values(&["rchar"]).set(io_stat.rchar as f64);
gv.with_label_values(&["wchar"]).set(io_stat.wchar as f64);
@@ -483,6 +493,7 @@ fn set_gauge_vec_proc_io(gv: &prometheus::GaugeVec, io_stat: &procfs::process::I
}
// set_gauge_vec_proc_stat set gauge for ProcStat
#[instrument]
fn set_gauge_vec_proc_stat(gv: &prometheus::GaugeVec, stat: &procfs::process::Stat) {
gv.with_label_values(&["utime"]).set(stat.utime as f64);
gv.with_label_values(&["stime"]).set(stat.stime as f64);

View File

@@ -6,13 +6,16 @@
use std::collections::HashMap;
use std::ffi::CString;
use std::fs;
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
use std::iter;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path;
use std::ptr::null;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
use libc::{c_void, mount};
@@ -20,8 +23,6 @@ use nix::mount::{self, MsFlags};
use nix::unistd::Gid;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
use crate::device::{
get_scsi_device_name, get_virtio_blk_pci_device_name, online_device, wait_for_pmem_device,
@@ -30,17 +31,22 @@ use crate::linux_abi::*;
use crate::pci;
use crate::protocols::agent::Storage;
use crate::Sandbox;
#[cfg(target_arch = "s390x")]
use crate::{ccw, device::get_virtio_blk_ccw_device_name};
use anyhow::{anyhow, Context, Result};
use slog::Logger;
use tracing::instrument;
pub const DRIVER_9P_TYPE: &str = "9p";
pub const DRIVER_VIRTIOFS_TYPE: &str = "virtio-fs";
pub const DRIVER_BLK_TYPE: &str = "blk";
pub const DRIVER_BLK_CCW_TYPE: &str = "blk-ccw";
pub const DRIVER_MMIO_BLK_TYPE: &str = "mmioblk";
pub const DRIVER_SCSI_TYPE: &str = "scsi";
pub const DRIVER_NVDIMM_TYPE: &str = "nvdimm";
pub const DRIVER_EPHEMERAL_TYPE: &str = "ephemeral";
pub const DRIVER_LOCAL_TYPE: &str = "local";
pub const DRIVER_WATCHABLE_BIND_TYPE: &str = "watchable-bind";
pub const TYPE_ROOTFS: &str = "rootfs";
@@ -131,7 +137,7 @@ lazy_static! {
];
}
pub const STORAGE_HANDLER_LIST: [&str; 8] = [
pub const STORAGE_HANDLER_LIST: &[&str] = &[
DRIVER_BLK_TYPE,
DRIVER_9P_TYPE,
DRIVER_VIRTIOFS_TYPE,
@@ -140,6 +146,7 @@ pub const STORAGE_HANDLER_LIST: [&str; 8] = [
DRIVER_LOCAL_TYPE,
DRIVER_SCSI_TYPE,
DRIVER_NVDIMM_TYPE,
DRIVER_WATCHABLE_BIND_TYPE,
];
#[derive(Debug, Clone)]
@@ -156,6 +163,7 @@ pub struct BareMount<'a> {
// * evaluate all symlinks
// * ensure the source exists
impl<'a> BareMount<'a> {
#[instrument]
pub fn new(
s: &'a str,
d: &'a str,
@@ -174,6 +182,7 @@ impl<'a> BareMount<'a> {
}
}
#[instrument]
pub fn mount(&self) -> Result<()> {
let source;
let dest;
@@ -232,6 +241,7 @@ impl<'a> BareMount<'a> {
}
}
#[instrument]
async fn ephemeral_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -278,6 +288,7 @@ async fn ephemeral_storage_handler(
Ok("".to_string())
}
#[instrument]
async fn local_storage_handler(
_logger: &Logger,
storage: &Storage,
@@ -324,6 +335,7 @@ async fn local_storage_handler(
Ok("".to_string())
}
#[instrument]
async fn virtio9p_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -333,6 +345,7 @@ async fn virtio9p_storage_handler(
}
// virtiommio_blk_storage_handler handles the storage for mmio blk driver.
#[instrument]
async fn virtiommio_blk_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -343,6 +356,7 @@ async fn virtiommio_blk_storage_handler(
}
// virtiofs_storage_handler handles the storage for virtio-fs.
#[instrument]
async fn virtiofs_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -352,6 +366,7 @@ async fn virtiofs_storage_handler(
}
// virtio_blk_storage_handler handles the storage for blk driver.
#[instrument]
async fn virtio_blk_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -377,7 +392,33 @@ async fn virtio_blk_storage_handler(
common_storage_handler(logger, &storage)
}
// virtio_scsi_storage_handler handles the storage for scsi driver.
// virtio_blk_ccw_storage_handler handles storage for the blk-ccw driver (s390x)
#[cfg(target_arch = "s390x")]
#[instrument]
async fn virtio_blk_ccw_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<String> {
let mut storage = storage.clone();
let ccw_device = ccw::Device::from_str(&storage.source)?;
let dev_path = get_virtio_blk_ccw_device_name(&sandbox, &ccw_device).await?;
storage.source = dev_path;
common_storage_handler(logger, &storage)
}
#[cfg(not(target_arch = "s390x"))]
#[instrument]
async fn virtio_blk_ccw_storage_handler(
_: &Logger,
_: &Storage,
_: Arc<Mutex<Sandbox>>,
) -> Result<String> {
Err(anyhow!("CCW is only supported on s390x"))
}
// virtio_scsi_storage_handler handles the storage for scsi driver.
#[instrument]
async fn virtio_scsi_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -392,6 +433,7 @@ async fn virtio_scsi_storage_handler(
common_storage_handler(logger, &storage)
}
#[instrument]
fn common_storage_handler(logger: &Logger, storage: &Storage) -> Result<String> {
// Mount the storage device.
let mount_point = storage.mount_point.to_string();
@@ -400,6 +442,7 @@ fn common_storage_handler(logger: &Logger, storage: &Storage) -> Result<String>
}
// nvdimm_storage_handler handles the storage for NVDIMM driver.
#[instrument]
async fn nvdimm_storage_handler(
logger: &Logger,
storage: &Storage,
@@ -413,7 +456,22 @@ async fn nvdimm_storage_handler(
common_storage_handler(logger, &storage)
}
async fn bind_watcher_storage_handler(
logger: &Logger,
storage: &Storage,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<()> {
let mut locked = sandbox.lock().await;
let container_id = locked.id.clone();
locked
.bind_watcher
.add_container(container_id, iter::once(storage.clone()), logger)
.await
}
// mount_storage performs the mount described by the storage structure.
#[instrument]
fn mount_storage(logger: &Logger, storage: &Storage) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
@@ -464,7 +522,8 @@ fn mount_storage(logger: &Logger, storage: &Storage) -> Result<()> {
}
/// Looks for `mount_point` entry in the /proc/mounts.
fn is_mounted(mount_point: &str) -> Result<bool> {
#[instrument]
pub fn is_mounted(mount_point: &str) -> Result<bool> {
let mount_point = mount_point.trim_end_matches('/');
let found = fs::metadata(mount_point).is_ok()
// Looks through /proc/mounts and check if the mount exists
@@ -481,6 +540,7 @@ fn is_mounted(mount_point: &str) -> Result<bool> {
Ok(found)
}
#[instrument]
fn parse_mount_flags_and_options(options_vec: Vec<&str>) -> (MsFlags, String) {
let mut flags = MsFlags::empty();
let mut options: String = "".to_string();
@@ -509,6 +569,7 @@ fn parse_mount_flags_and_options(options_vec: Vec<&str>) -> (MsFlags, String) {
// associated operations such as waiting for the device to show up, and mount
// it to a specific location, according to the type of handler chosen, and for
// each storage.
#[instrument]
pub async fn add_storages(
logger: Logger,
storages: Vec<Storage>,
@@ -524,6 +585,9 @@ pub async fn add_storages(
let res = match handler_name.as_str() {
DRIVER_BLK_TYPE => virtio_blk_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_BLK_CCW_TYPE => {
virtio_blk_ccw_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_9P_TYPE => virtio9p_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_VIRTIOFS_TYPE => {
virtiofs_storage_handler(&logger, &storage, sandbox.clone()).await
@@ -539,6 +603,11 @@ pub async fn add_storages(
virtio_scsi_storage_handler(&logger, &storage, sandbox.clone()).await
}
DRIVER_NVDIMM_TYPE => nvdimm_storage_handler(&logger, &storage, sandbox.clone()).await,
DRIVER_WATCHABLE_BIND_TYPE => {
bind_watcher_storage_handler(&logger, &storage, sandbox.clone()).await?;
// Don't register watch mounts, they're hanlded separately by the watcher.
Ok(String::new())
}
_ => {
return Err(anyhow!(
"Failed to find the storage handler {}",
@@ -558,6 +627,7 @@ pub async fn add_storages(
Ok(mount_list)
}
#[instrument]
fn mount_to_rootfs(logger: &Logger, m: &InitMount) -> Result<()> {
let options_vec: Vec<&str> = m.options.clone();
@@ -583,6 +653,7 @@ fn mount_to_rootfs(logger: &Logger, m: &InitMount) -> Result<()> {
Ok(())
}
#[instrument]
pub fn general_mount(logger: &Logger) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
@@ -600,6 +671,7 @@ pub fn get_mount_fs_type(mount_point: &str) -> Result<String> {
// get_mount_fs_type_from_file returns the FS type corresponding to the passed mount point and
// any error ecountered.
#[instrument]
pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Result<String> {
if mount_point.is_empty() {
return Err(anyhow!("Invalid mount point {}", mount_point));
@@ -630,6 +702,7 @@ pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Resul
))
}
#[instrument]
pub fn get_cgroup_mounts(
logger: &Logger,
cg_path: &str,
@@ -720,6 +793,7 @@ pub fn get_cgroup_mounts(
Ok(cg_mounts)
}
#[instrument]
pub fn cgroups_mount(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result<()> {
let logger = logger.new(o!("subsystem" => "mount"));
@@ -735,6 +809,7 @@ pub fn cgroups_mount(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result<
Ok(())
}
#[instrument]
pub fn remove_mounts(mounts: &[String]) -> Result<()> {
for m in mounts.iter() {
mount::umount(m.as_str()).context(format!("failed to umount {:?}", m))?;
@@ -744,6 +819,7 @@ pub fn remove_mounts(mounts: &[String]) -> Result<()> {
// ensure_destination_exists will recursively create a given mountpoint. If directories
// are created, their permissions are initialized to mountPerm(0755)
#[instrument]
fn ensure_destination_exists(destination: &str, fs_type: &str) -> Result<()> {
let d = Path::new(destination);
if !d.exists() {
@@ -764,6 +840,7 @@ fn ensure_destination_exists(destination: &str, fs_type: &str) -> Result<()> {
Ok(())
}
#[instrument]
fn parse_options(option_list: Vec<String>) -> HashMap<String, String> {
let mut options = HashMap::new();
for opt in option_list.iter() {

View File

@@ -11,6 +11,7 @@ use std::fmt;
use std::fs;
use std::fs::File;
use std::path::{Path, PathBuf};
use tracing::instrument;
use crate::mount::{BareMount, FLAGS};
use slog::Logger;
@@ -20,6 +21,7 @@ pub const NSTYPEIPC: &str = "ipc";
pub const NSTYPEUTS: &str = "uts";
pub const NSTYPEPID: &str = "pid";
#[instrument]
pub fn get_current_thread_ns_path(ns_type: &str) -> String {
format!(
"/proc/{}/task/{}/ns/{}",
@@ -40,6 +42,7 @@ pub struct Namespace {
}
impl Namespace {
#[instrument]
pub fn new(logger: &Logger) -> Self {
Namespace {
logger: logger.clone(),
@@ -50,11 +53,13 @@ impl Namespace {
}
}
#[instrument]
pub fn get_ipc(mut self) -> Self {
self.ns_type = NamespaceType::Ipc;
self
}
#[instrument]
pub fn get_uts(mut self, hostname: &str) -> Self {
self.ns_type = NamespaceType::Uts;
if !hostname.is_empty() {
@@ -63,6 +68,7 @@ impl Namespace {
self
}
#[instrument]
pub fn get_pid(mut self) -> Self {
self.ns_type = NamespaceType::Pid;
self
@@ -76,6 +82,7 @@ impl Namespace {
// setup creates persistent namespace without switching to it.
// Note, pid namespaces cannot be persisted.
#[instrument]
pub async fn setup(mut self) -> Result<Self> {
fs::create_dir_all(&self.persistent_ns_dir)?;

View File

@@ -9,6 +9,7 @@ use nix::fcntl::{self, OFlag};
use nix::sys::stat::Mode;
use std::fs;
use std::os::unix::io::{AsRawFd, FromRawFd};
use tracing::instrument;
pub const RNGDEV: &str = "/dev/random";
pub const RNDADDTOENTCNT: libc::c_int = 0x40045201;
@@ -20,6 +21,7 @@ type IoctlRequestType = libc::c_int;
#[cfg(target_env = "gnu")]
type IoctlRequestType = libc::c_ulong;
#[instrument]
pub fn reseed_rng(data: &[u8]) -> Result<()> {
let len = data.len() as libc::c_long;
fs::write(RNGDEV, data)?;
@@ -37,10 +39,10 @@ pub fn reseed_rng(data: &[u8]) -> Result<()> {
&len as *const libc::c_long,
)
};
let _ = Errno::result(ret).map(drop)?;
Errno::result(ret).map(drop)?;
let ret = unsafe { libc::ioctl(f.as_raw_fd(), RNDRESEEDRNG as IoctlRequestType, 0) };
let _ = Errno::result(ret).map(drop)?;
Errno::result(ret).map(drop)?;
Ok(())
}

View File

@@ -51,6 +51,14 @@ use crate::sandbox::Sandbox;
use crate::version::{AGENT_VERSION, API_VERSION};
use crate::AGENT_CONFIG;
use crate::trace_rpc_call;
use crate::tracer::extract_carrier_from_ttrpc;
use opentelemetry::global;
use tracing::span;
use tracing_opentelemetry::OpenTelemetrySpanExt;
use tracing::instrument;
use libc::{self, c_ushort, pid_t, winsize, TIOCSWINSZ};
use std::convert::TryFrom;
use std::fs;
@@ -74,7 +82,7 @@ macro_rules! sl {
};
}
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct AgentService {
sandbox: Arc<Mutex<Sandbox>>,
}
@@ -97,13 +105,14 @@ fn verify_cid(id: &str) -> Result<()> {
}
impl AgentService {
#[instrument]
async fn do_create_container(
&self,
req: protocols::agent::CreateContainerRequest,
) -> Result<()> {
let cid = req.container_id.clone();
let _ = verify_cid(&cid)?;
verify_cid(&cid)?;
let mut oci_spec = req.OCI.clone();
let use_sandbox_pidns = req.get_sandbox_pidns();
@@ -196,6 +205,7 @@ impl AgentService {
Ok(())
}
#[instrument]
async fn do_start_container(&self, req: protocols::agent::StartContainerRequest) -> Result<()> {
let cid = req.container_id;
@@ -221,6 +231,7 @@ impl AgentService {
Ok(())
}
#[instrument]
async fn do_remove_container(
&self,
req: protocols::agent::RemoveContainerRequest,
@@ -253,11 +264,14 @@ impl AgentService {
if req.timeout == 0 {
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
let ctr = sandbox
.get_container(&cid)
.ok_or_else(|| anyhow!("Invalid container id"))?;
ctr.destroy().await?;
sandbox.bind_watcher.remove_container(&cid).await;
sandbox
.get_container(&cid)
.ok_or_else(|| anyhow!("Invalid container id"))?
.destroy()
.await?;
remove_container_resources(&mut sandbox)?;
@@ -273,6 +287,7 @@ impl AgentService {
let mut sandbox = s.lock().await;
if let Some(ctr) = sandbox.get_container(&cid2) {
ctr.destroy().await.unwrap();
sandbox.bind_watcher.remove_container(&cid2).await;
tx.send(1).unwrap();
};
});
@@ -298,6 +313,7 @@ impl AgentService {
Ok(())
}
#[instrument]
async fn do_exec_process(&self, req: protocols::agent::ExecProcessRequest) -> Result<()> {
let cid = req.container_id.clone();
let exec_id = req.exec_id.clone();
@@ -326,6 +342,7 @@ impl AgentService {
Ok(())
}
#[instrument]
async fn do_signal_process(&self, req: protocols::agent::SignalProcessRequest) -> Result<()> {
let cid = req.container_id.clone();
let eid = req.exec_id.clone();
@@ -360,6 +377,7 @@ impl AgentService {
Ok(())
}
#[instrument]
async fn do_wait_process(
&self,
req: protocols::agent::WaitProcessRequest,
@@ -509,9 +527,10 @@ impl AgentService {
impl protocols::agent_ttrpc::AgentService for AgentService {
async fn create_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::CreateContainerRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "create_container", req);
match self.do_create_container(req).await {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(_) => Ok(Empty::new()),
@@ -520,9 +539,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn start_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::StartContainerRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "start_container", req);
match self.do_start_container(req).await {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(_) => Ok(Empty::new()),
@@ -531,9 +551,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn remove_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::RemoveContainerRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "remove_container", req);
match self.do_remove_container(req).await {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(_) => Ok(Empty::new()),
@@ -542,9 +563,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn exec_process(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::ExecProcessRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "exec_process", req);
match self.do_exec_process(req).await {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(_) => Ok(Empty::new()),
@@ -553,9 +575,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn signal_process(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::SignalProcessRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "signal_process", req);
match self.do_signal_process(req).await {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(_) => Ok(Empty::new()),
@@ -564,9 +587,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn wait_process(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::WaitProcessRequest,
) -> ttrpc::Result<WaitProcessResponse> {
trace_rpc_call!(ctx, "wait_process", req);
self.do_wait_process(req)
.await
.map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))
@@ -574,9 +598,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn update_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::UpdateContainerRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "update_container", req);
let cid = req.container_id.clone();
let res = req.resources;
@@ -608,9 +633,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn stats_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::StatsContainerRequest,
) -> ttrpc::Result<StatsContainerResponse> {
trace_rpc_call!(ctx, "stats_container", req);
let cid = req.container_id;
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
@@ -628,9 +654,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn pause_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::PauseContainerRequest,
) -> ttrpc::Result<protocols::empty::Empty> {
trace_rpc_call!(ctx, "pause_container", req);
let cid = req.get_container_id();
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
@@ -650,9 +677,10 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn resume_container(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::ResumeContainerRequest,
) -> ttrpc::Result<protocols::empty::Empty> {
trace_rpc_call!(ctx, "resume_container", req);
let cid = req.get_container_id();
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
@@ -702,9 +730,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn close_stdin(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::CloseStdinRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "close_stdin", req);
let cid = req.container_id.clone();
let eid = req.exec_id;
let s = Arc::clone(&self.sandbox);
@@ -736,9 +766,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn tty_win_resize(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::TtyWinResizeRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "tty_win_resize", req);
let cid = req.container_id.clone();
let eid = req.exec_id.clone();
let s = Arc::clone(&self.sandbox);
@@ -774,9 +806,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn update_interface(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::UpdateInterfaceRequest,
) -> ttrpc::Result<Interface> {
trace_rpc_call!(ctx, "update_interface", req);
let interface = req.interface.into_option().ok_or_else(|| {
ttrpc_error(
ttrpc::Code::INVALID_ARGUMENT,
@@ -799,9 +833,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn update_routes(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::UpdateRoutesRequest,
) -> ttrpc::Result<Routes> {
trace_rpc_call!(ctx, "update_routes", req);
let new_routes = req
.routes
.into_option()
@@ -837,9 +873,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn list_interfaces(
&self,
_ctx: &TtrpcContext,
_req: protocols::agent::ListInterfacesRequest,
ctx: &TtrpcContext,
req: protocols::agent::ListInterfacesRequest,
) -> ttrpc::Result<Interfaces> {
trace_rpc_call!(ctx, "list_interfaces", req);
let list = self
.sandbox
.lock()
@@ -862,9 +900,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn list_routes(
&self,
_ctx: &TtrpcContext,
_req: protocols::agent::ListRoutesRequest,
ctx: &TtrpcContext,
req: protocols::agent::ListRoutesRequest,
) -> ttrpc::Result<Routes> {
trace_rpc_call!(ctx, "list_routes", req);
let list = self
.sandbox
.lock()
@@ -899,9 +939,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn create_sandbox(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::CreateSandboxRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "create_sandbox", req);
{
let sandbox = self.sandbox.clone();
let mut s = sandbox.lock().await;
@@ -926,7 +968,7 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
}
for m in req.kernel_modules.iter() {
let _ = load_kernel_module(m)
load_kernel_module(m)
.map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?;
}
@@ -962,9 +1004,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn destroy_sandbox(
&self,
_ctx: &TtrpcContext,
_req: protocols::agent::DestroySandboxRequest,
ctx: &TtrpcContext,
req: protocols::agent::DestroySandboxRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "destroy_sandbox", req);
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
// destroy all containers, clean up, notify agent to exit
@@ -981,9 +1025,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn add_arp_neighbors(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::AddARPNeighborsRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "add_arp_neighbors", req);
let neighs = req
.neighbors
.into_option()
@@ -1013,11 +1059,12 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn online_cpu_mem(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::OnlineCPUMemRequest,
) -> ttrpc::Result<Empty> {
let s = Arc::clone(&self.sandbox);
let sandbox = s.lock().await;
trace_rpc_call!(ctx, "online_cpu_mem", req);
sandbox
.online_cpu_memory(&req)
@@ -1028,9 +1075,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn reseed_random_dev(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::ReseedRandomDevRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "reseed_random_dev", req);
random::reseed_rng(req.data.as_slice())
.map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?;
@@ -1039,9 +1088,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn get_guest_details(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::GuestDetailsRequest,
) -> ttrpc::Result<GuestDetailsResponse> {
trace_rpc_call!(ctx, "get_guest_details", req);
info!(sl!(), "get guest details!");
let mut resp = GuestDetailsResponse::new();
// to get memory block size
@@ -1065,9 +1116,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn mem_hotplug_by_probe(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::MemHotplugByProbeRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "mem_hotplug_by_probe", req);
do_mem_hotplug_by_probe(&req.memHotplugProbeAddr)
.map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?;
@@ -1076,9 +1129,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn set_guest_date_time(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::SetGuestDateTimeRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "set_guest_date_time", req);
do_set_guest_date_time(req.Sec, req.Usec)
.map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?;
@@ -1087,9 +1142,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn copy_file(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::CopyFileRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "copy_file", req);
do_copy_file(&req).map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?;
Ok(Empty::new())
@@ -1097,9 +1154,11 @@ impl protocols::agent_ttrpc::AgentService for AgentService {
async fn get_metrics(
&self,
_ctx: &TtrpcContext,
ctx: &TtrpcContext,
req: protocols::agent::GetMetricsRequest,
) -> ttrpc::Result<Metrics> {
trace_rpc_call!(ctx, "get_metrics", req);
match get_metrics(&req) {
Err(e) => Err(ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())),
Ok(s) => {
@@ -1529,22 +1588,22 @@ fn setup_bundle(cid: &str, spec: &mut Spec) -> Result<PathBuf> {
fn cleanup_process(p: &mut Process) -> Result<()> {
if p.parent_stdin.is_some() {
p.close_stream(StreamType::ParentStdin);
let _ = unistd::close(p.parent_stdin.unwrap())?;
unistd::close(p.parent_stdin.unwrap())?;
}
if p.parent_stdout.is_some() {
p.close_stream(StreamType::ParentStdout);
let _ = unistd::close(p.parent_stdout.unwrap())?;
unistd::close(p.parent_stdout.unwrap())?;
}
if p.parent_stderr.is_some() {
p.close_stream(StreamType::ParentStderr);
let _ = unistd::close(p.parent_stderr.unwrap())?;
unistd::close(p.parent_stderr.unwrap())?;
}
if p.term_master.is_some() {
p.close_stream(StreamType::TermMaster);
let _ = unistd::close(p.term_master.unwrap())?;
unistd::close(p.term_master.unwrap())?;
}
p.notify_term_close();

View File

@@ -9,6 +9,7 @@ use crate::namespace::Namespace;
use crate::netlink::Handle;
use crate::network::Network;
use crate::uevent::{Uevent, UeventMatcher};
use crate::watcher::BindWatcher;
use anyhow::{anyhow, Context, Result};
use libc::pid_t;
use oci::{Hook, Hooks};
@@ -28,6 +29,7 @@ use std::{thread, time};
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::sync::oneshot;
use tokio::sync::Mutex;
use tracing::instrument;
type UeventWatcher = (Box<dyn UeventMatcher>, oneshot::Sender<Uevent>);
@@ -53,9 +55,11 @@ pub struct Sandbox {
pub hooks: Option<Hooks>,
pub event_rx: Arc<Mutex<Receiver<String>>>,
pub event_tx: Option<Sender<String>>,
pub bind_watcher: BindWatcher,
}
impl Sandbox {
#[instrument]
pub fn new(logger: &Logger) -> Result<Self> {
let fs_type = get_mount_fs_type("/")?;
let logger = logger.new(o!("subsystem" => "sandbox"));
@@ -83,6 +87,7 @@ impl Sandbox {
hooks: None,
event_rx,
event_tx: Some(tx),
bind_watcher: BindWatcher::new(),
})
}
@@ -94,6 +99,7 @@ impl Sandbox {
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
#[instrument]
pub fn set_sandbox_storage(&mut self, path: &str) -> bool {
match self.storages.get_mut(path) {
None => {
@@ -116,6 +122,7 @@ impl Sandbox {
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
#[instrument]
pub fn unset_sandbox_storage(&mut self, path: &str) -> Result<bool> {
match self.storages.get_mut(path) {
None => Err(anyhow!("Sandbox storage with path {} not found", path)),
@@ -135,6 +142,7 @@ impl Sandbox {
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
#[instrument]
pub fn remove_sandbox_storage(&self, path: &str) -> Result<()> {
let mounts = vec![path.to_string()];
remove_mounts(&mounts)?;
@@ -148,6 +156,7 @@ impl Sandbox {
//
// It's assumed that caller is calling this method after
// acquiring a lock on sandbox.
#[instrument]
pub fn unset_and_remove_sandbox_storage(&mut self, path: &str) -> Result<()> {
if self.unset_sandbox_storage(path)? {
return self.remove_sandbox_storage(path);
@@ -156,6 +165,7 @@ impl Sandbox {
Ok(())
}
#[instrument]
pub async fn setup_shared_namespaces(&mut self) -> Result<bool> {
// Set up shared IPC namespace
self.shared_ipcns = Namespace::new(&self.logger)
@@ -178,6 +188,7 @@ impl Sandbox {
self.containers.insert(c.id.clone(), c);
}
#[instrument]
pub fn update_shared_pidns(&mut self, c: &LinuxContainer) -> Result<()> {
// Populate the shared pid path only if this is an infra container and
// sandbox_pidns has not been passed in the create_sandbox request.
@@ -215,6 +226,7 @@ impl Sandbox {
None
}
#[instrument]
pub async fn destroy(&mut self) -> Result<()> {
for ctr in self.containers.values_mut() {
ctr.destroy().await?;
@@ -222,6 +234,7 @@ impl Sandbox {
Ok(())
}
#[instrument]
pub fn online_cpu_memory(&self, req: &OnlineCPUMemRequest) -> Result<()> {
if req.nb_cpus > 0 {
// online cpus
@@ -265,6 +278,7 @@ impl Sandbox {
Ok(())
}
#[instrument]
pub fn add_hooks(&mut self, dir: &str) -> Result<()> {
let mut hooks = Hooks::default();
if let Ok(hook) = self.find_hooks(dir, "prestart") {
@@ -280,6 +294,7 @@ impl Sandbox {
Ok(())
}
#[instrument]
fn find_hooks(&self, hook_path: &str, hook_type: &str) -> Result<Vec<Hook>> {
let mut hooks = Vec::new();
for entry in fs::read_dir(Path::new(hook_path).join(hook_type))? {
@@ -316,6 +331,7 @@ impl Sandbox {
Ok(hooks)
}
#[instrument]
pub async fn run_oom_event_monitor(&self, mut rx: Receiver<String>, container_id: String) {
let logger = self.logger.clone();
@@ -348,6 +364,7 @@ impl Sandbox {
}
}
#[instrument]
fn online_resources(logger: &Logger, path: &str, pattern: &str, num: i32) -> Result<i32> {
let mut count = 0;
let re = Regex::new(pattern)?;
@@ -393,6 +410,7 @@ fn online_resources(logger: &Logger, path: &str, pattern: &str, num: i32) -> Res
const ONLINE_CPUMEM_WATI_MILLIS: u64 = 50;
const ONLINE_CPUMEM_MAX_RETRIES: u32 = 100;
#[instrument]
fn online_cpus(logger: &Logger, num: i32) -> Result<i32> {
let mut onlined_count: i32 = 0;
@@ -422,6 +440,7 @@ fn online_cpus(logger: &Logger, num: i32) -> Result<i32> {
))
}
#[instrument]
fn online_memory(logger: &Logger) -> Result<()> {
online_resources(logger, SYSFS_MEMORY_ONLINE_PATH, r"memory[0-9]+", -1)?;
Ok(())
@@ -537,7 +556,6 @@ mod tests {
}
#[tokio::test]
#[allow(unused_assignments)]
async fn unset_and_remove_sandbox_storage() {
skip_if_not_root!();
@@ -571,7 +589,7 @@ mod tests {
assert_eq!(s.set_sandbox_storage(&destdir_path), true);
assert!(s.unset_and_remove_sandbox_storage(&destdir_path).is_ok());
let mut other_dir_str = String::new();
let other_dir_str;
{
// Create another folder in a separate scope to ensure that is
// deleted

View File

@@ -6,10 +6,10 @@
use crate::sandbox::Sandbox;
use anyhow::{anyhow, Result};
use capctl::prctl::set_subreaper;
use nix::sys::wait::WaitPidFlag;
use nix::sys::wait::{self, WaitStatus};
use nix::unistd;
use prctl::set_child_subreaper;
use slog::{error, info, o, Logger};
use std::sync::Arc;
use tokio::select;
@@ -22,6 +22,9 @@ async fn handle_sigchild(logger: Logger, sandbox: Arc<Mutex<Sandbox>>) -> Result
info!(logger, "handling signal"; "signal" => "SIGCHLD");
loop {
// Avoid reaping the undesirable child's signal, e.g., execute_hook's
// The lock should be released immediately.
rustjail::container::WAIT_PID_LOCKER.lock().await;
let result = wait::waitpid(
Some(Pid::from_raw(-1)),
Some(WaitPidFlag::WNOHANG | WaitPidFlag::__WALL),
@@ -85,7 +88,7 @@ pub async fn setup_signal_handler(
) -> Result<()> {
let logger = logger.new(o!("subsystem" => "signals"));
set_child_subreaper(true)
set_subreaper(true)
.map_err(|err| anyhow!(err).context("failed to setup agent as a child subreaper"))?;
let mut sigchild_stream = signal(SignalKind::child())?;

View File

@@ -7,7 +7,6 @@
#[cfg(test)]
mod test_utils {
#[macro_export]
#[allow(unused_macros)]
macro_rules! skip_if_root {
() => {
if nix::unistd::Uid::effective().is_root() {
@@ -18,7 +17,6 @@ mod test_utils {
}
#[macro_export]
#[allow(unused_macros)]
macro_rules! skip_if_not_root {
() => {
if !nix::unistd::Uid::effective().is_root() {
@@ -29,7 +27,6 @@ mod test_utils {
}
#[macro_export]
#[allow(unused_macros)]
macro_rules! skip_loop_if_root {
($msg:expr) => {
if nix::unistd::Uid::effective().is_root() {
@@ -44,7 +41,6 @@ mod test_utils {
}
#[macro_export]
#[allow(unused_macros)]
macro_rules! skip_loop_if_not_root {
($msg:expr) => {
if !nix::unistd::Uid::effective().is_root() {

122
src/agent/src/tracer.rs Normal file
View File

@@ -0,0 +1,122 @@
// Copyright (c) 2020-2021 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::config::AgentConfig;
use anyhow::Result;
use opentelemetry::sdk::propagation::TraceContextPropagator;
use opentelemetry::{global, sdk::trace::Config, trace::TracerProvider};
use slog::{info, o, Logger};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::str::FromStr;
use tracing_opentelemetry::OpenTelemetryLayer;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::Registry;
use ttrpc::r#async::TtrpcContext;
#[derive(Debug, PartialEq)]
pub enum TraceType {
Disabled,
Isolated,
}
#[derive(Debug)]
pub struct TraceTypeError {
details: String,
}
impl TraceTypeError {
fn new(msg: &str) -> TraceTypeError {
TraceTypeError {
details: msg.into(),
}
}
}
impl Error for TraceTypeError {}
impl fmt::Display for TraceTypeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.details)
}
}
impl FromStr for TraceType {
type Err = TraceTypeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"isolated" => Ok(TraceType::Isolated),
"disabled" => Ok(TraceType::Disabled),
_ => Err(TraceTypeError::new("invalid trace type")),
}
}
}
pub fn setup_tracing(name: &'static str, logger: &Logger, _agent_cfg: &AgentConfig) -> Result<()> {
let logger = logger.new(o!("subsystem" => "vsock-tracer"));
let exporter = vsock_exporter::Exporter::builder()
.with_logger(&logger)
.init();
let config = Config::default();
let builder = opentelemetry::sdk::trace::TracerProvider::builder()
.with_simple_exporter(exporter)
.with_config(config);
let provider = builder.build();
// We don't need a versioned tracer.
let version = None;
let tracer = provider.get_tracer(name, version);
let _global_provider = global::set_tracer_provider(provider);
let layer = OpenTelemetryLayer::new(tracer);
let subscriber = Registry::default().with(layer);
tracing::subscriber::set_global_default(subscriber)?;
global::set_text_map_propagator(TraceContextPropagator::new());
info!(logger, "tracing setup");
Ok(())
}
pub fn end_tracing() {
global::shutdown_tracer_provider();
}
pub fn extract_carrier_from_ttrpc(ttrpc_context: &TtrpcContext) -> HashMap<String, String> {
let mut carrier = HashMap::new();
for (k, v) in &ttrpc_context.metadata {
carrier.insert(k.clone(), v.join(","));
}
carrier
}
#[macro_export]
macro_rules! trace_rpc_call {
($ctx: ident, $name:literal, $req: ident) => {
// extract context from request context
let parent_context = global::get_text_map_propagator(|propagator| {
propagator.extract(&extract_carrier_from_ttrpc($ctx))
});
// generate tracing span
let rpc_span = span!(tracing::Level::INFO, $name, "mod"="rpc.rs", req=?$req);
// assign parent span from external context
rpc_span.set_parent(parent_context);
let _enter = rpc_span.enter();
};
}

View File

@@ -18,6 +18,7 @@ use std::sync::Arc;
use tokio::select;
use tokio::sync::watch::Receiver;
use tokio::sync::Mutex;
use tracing::instrument;
// Convenience macro to obtain the scope logger
macro_rules! sl {
@@ -64,6 +65,7 @@ impl Uevent {
event
}
#[instrument]
async fn process_add(&self, logger: &Logger, sandbox: &Arc<Mutex<Sandbox>>) {
// Special case for memory hot-adds first
let online_path = format!("{}/{}/online", SYSFS_DIR, &self.devpath);
@@ -95,6 +97,7 @@ impl Uevent {
}
}
#[instrument]
async fn process(&self, logger: &Logger, sandbox: &Arc<Mutex<Sandbox>>) {
if self.action == U_EVENT_ACTION_ADD {
return self.process_add(logger, sandbox).await;
@@ -103,6 +106,7 @@ impl Uevent {
}
}
#[instrument]
pub async fn wait_for_uevent(
sandbox: &Arc<Mutex<Sandbox>>,
matcher: impl UeventMatcher,
@@ -110,7 +114,7 @@ pub async fn wait_for_uevent(
let mut sb = sandbox.lock().await;
for uev in sb.uevent_map.values() {
if matcher.is_match(uev) {
info!(sl!(), "Device {:?} found in pci device map", uev);
info!(sl!(), "Device {:?} found in device map", uev);
return Ok(uev.clone());
}
}
@@ -145,6 +149,7 @@ pub async fn wait_for_uevent(
Ok(uev)
}
#[instrument]
pub async fn watch_uevents(
sandbox: Arc<Mutex<Sandbox>>,
mut shutdown: Receiver<bool>,

View File

@@ -11,6 +11,7 @@ use std::os::unix::io::{FromRawFd, RawFd};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::watch::Receiver;
use tokio_vsock::{Incoming, VsockListener, VsockStream};
use tracing::instrument;
// Size of I/O read buffer
const BUF_SIZE: usize = 8192;
@@ -56,10 +57,12 @@ where
Ok(total_bytes)
}
#[instrument]
pub fn get_vsock_incoming(fd: RawFd) -> Incoming {
unsafe { VsockListener::from_raw_fd(fd).incoming() }
}
#[instrument]
pub async fn get_vsock_stream(fd: RawFd) -> Result<VsockStream> {
let stream = get_vsock_incoming(fd).next().await.unwrap()?;
Ok(stream)

771
src/agent/src/watcher.rs Normal file
View File

@@ -0,0 +1,771 @@
// Copyright (c) 2021 Apple Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use tokio::fs;
use tokio::sync::Mutex;
use tokio::task;
use tokio::time::{self, Duration};
use anyhow::{ensure, Context, Result};
use async_recursion::async_recursion;
use nix::mount::{umount, MsFlags};
use slog::{debug, error, Logger};
use crate::mount::BareMount;
use crate::protocols::agent as protos;
/// The maximum number of file system entries agent will watch for each mount.
const MAX_ENTRIES_PER_STORAGE: usize = 8;
/// The maximum size of a watchable mount in bytes.
const MAX_SIZE_PER_WATCHABLE_MOUNT: u64 = 1024 * 1024;
/// How often to check for modified files.
const WATCH_INTERVAL_SECS: u64 = 2;
/// Destination path for tmpfs
const WATCH_MOUNT_POINT_PATH: &str = "/run/kata-containers/shared/containers/watchable/";
/// Represents a single watched storage entry which may have multiple files to watch.
#[derive(Default, Debug, Clone)]
struct Storage {
/// A mount point without inotify capabilities.
source_mount_point: PathBuf,
/// The target mount point, where the watched files will be copied/mirrored
/// when being changed, added or removed. This will be subdirectory of a tmpfs
target_mount_point: PathBuf,
/// Flag to indicate that the Storage should be watched. Storage will be watched until
/// the source becomes too large, either in number of files (>8) or total size (>1MB).
watch: bool,
/// The list of files to watch from the source mount point and updated in the target one.
watched_files: HashMap<PathBuf, SystemTime>,
}
impl Drop for Storage {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.target_mount_point);
}
}
impl Storage {
async fn new(storage: protos::Storage) -> Result<Storage> {
let entry = Storage {
source_mount_point: PathBuf::from(&storage.source),
target_mount_point: PathBuf::from(&storage.mount_point),
watch: true,
watched_files: HashMap::new(),
};
Ok(entry)
}
async fn update_target(&self, logger: &Logger, source_path: impl AsRef<Path>) -> Result<()> {
let source_file_path = source_path.as_ref();
let dest_file_path = if self.source_mount_point.is_file() {
// Simple file to file copy
// Assume target mount is a file path
self.target_mount_point.clone()
} else {
let dest_file_path = self.make_target_path(&source_file_path)?;
if let Some(path) = dest_file_path.parent() {
debug!(logger, "Creating destination directory: {}", path.display());
fs::create_dir_all(path)
.await
.with_context(|| format!("Unable to mkdir all for {}", path.display()))?;
}
dest_file_path
};
debug!(
logger,
"Copy from {} to {}",
source_file_path.display(),
dest_file_path.display()
);
fs::copy(&source_file_path, &dest_file_path)
.await
.with_context(|| {
format!(
"Copy from {} to {} failed",
source_file_path.display(),
dest_file_path.display()
)
})?;
Ok(())
}
async fn scan(&mut self, logger: &Logger) -> Result<usize> {
debug!(logger, "Scanning for changes");
let mut remove_list = Vec::new();
let mut updated_files: Vec<PathBuf> = Vec::new();
// Remove deleted files for tracking list
self.watched_files.retain(|st, _| {
if st.exists() {
true
} else {
remove_list.push(st.to_path_buf());
false
}
});
// Delete from target
for path in remove_list {
// File has been deleted, remove it from target mount
let target = self.make_target_path(path)?;
debug!(logger, "Removing file from mount: {}", target.display());
let _ = fs::remove_file(target).await;
}
// Scan new & changed files
self.scan_path(
logger,
self.source_mount_point.clone().as_path(),
&mut updated_files,
)
.await
.with_context(|| "Scan path failed")?;
// Update identified files:
for path in &updated_files {
self.update_target(logger, path.as_path()).await?;
}
Ok(updated_files.len())
}
#[async_recursion]
async fn scan_path(
&mut self,
logger: &Logger,
path: &Path,
update_list: &mut Vec<PathBuf>,
) -> Result<u64> {
let mut size: u64 = 0;
debug!(logger, "Scanning path: {}", path.display());
if path.is_file() {
let metadata = path
.metadata()
.with_context(|| format!("Failed to query metadata for: {}", path.display()))?;
let modified = metadata
.modified()
.with_context(|| format!("Failed to get modified date for: {}", path.display()))?;
size += metadata.len();
ensure!(
self.watched_files.len() <= MAX_ENTRIES_PER_STORAGE,
"Too many file system entries to watch (must be < {})",
MAX_ENTRIES_PER_STORAGE
);
// Insert will return old entry if any
if let Some(old_st) = self.watched_files.insert(path.to_path_buf(), modified) {
if modified > old_st {
update_list.push(PathBuf::from(&path))
}
} else {
// Storage just added, copy to target
debug!(logger, "New entry: {}", path.display());
update_list.push(PathBuf::from(&path))
}
} else {
// Scan dir recursively
let mut entries = fs::read_dir(path)
.await
.with_context(|| format!("Failed to read dir: {}", path.display()))?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
let res_size = self
.scan_path(logger, path.as_path(), update_list)
.await
.with_context(|| format!("Unable to scan inner path: {}", path.display()))?;
size += res_size;
}
}
ensure!(
size <= MAX_SIZE_PER_WATCHABLE_MOUNT,
"Too many file system entries to watch (must be < {})",
MAX_SIZE_PER_WATCHABLE_MOUNT,
);
Ok(size)
}
fn make_target_path(&self, source_file_path: impl AsRef<Path>) -> Result<PathBuf> {
let relative_path = source_file_path
.as_ref()
.strip_prefix(&self.source_mount_point)
.with_context(|| {
format!(
"Failed to strip prefix: {} - {}",
source_file_path.as_ref().display().to_string(),
&self.source_mount_point.display()
)
})?;
let dest_file_path = Path::new(&self.target_mount_point).join(relative_path);
Ok(dest_file_path)
}
}
#[derive(Default, Debug)]
struct SandboxStorages(Vec<Storage>);
impl SandboxStorages {
async fn add(
&mut self,
list: impl IntoIterator<Item = protos::Storage>,
logger: &Logger,
) -> Result<()> {
for storage in list.into_iter() {
let entry = Storage::new(storage)
.await
.with_context(|| "Failed to add storage")?;
self.0.push(entry);
}
// Perform initial copy
self.check(logger)
.await
.with_context(|| "Failed to perform initial check")?;
Ok(())
}
async fn check(&mut self, logger: &Logger) -> Result<()> {
for entry in self.0.iter_mut().filter(|e| e.watch) {
if let Err(e) = entry.scan(logger).await {
// If an error was observed, we will stop treating this Storage as being watchable, and
// instead clean up the target-mount files on the tmpfs and bind mount the source_mount_point
// to target_mount_point.
error!(logger, "error observed when watching: {:?}", e);
entry.watch = false;
// Remove destination contents, but not the directory itself, since this is
// assumed to be bind-mounted into a container. If source/mount is a file, no need to cleanup
if entry.target_mount_point.as_path().is_dir() {
for dir_entry in std::fs::read_dir(entry.target_mount_point.as_path())? {
let dir_entry = dir_entry?;
let path = dir_entry.path();
if dir_entry.file_type()?.is_dir() {
tokio::fs::remove_dir_all(path).await?;
} else {
tokio::fs::remove_file(path).await?;
}
}
}
// - Create bind mount from source to destination
BareMount::new(
entry.source_mount_point.to_str().unwrap(),
entry.target_mount_point.to_str().unwrap(),
"bind",
MsFlags::MS_BIND,
"bind",
logger,
)
.mount()?;
}
}
Ok(())
}
}
/// Handles watchable mounts. The watcher will manage one or more mounts for one or more containers. For each
/// mount that is added, the watcher will maintain a list of files to monitor, and periodically checks for new,
/// removed or changed (modified date) files. When a change is identified, the watcher will either copy the new
/// or updated file to a target mount point, or remove the removed file from the target mount point. All WatchableStorage
/// target mount points are expected to reside within a single tmpfs, whose root is created by the BindWatcher.
///
/// This is a temporary workaround to handle config map updates until we get inotify on 9p/virtio-fs.
/// More context on this:
/// - https://github.com/kata-containers/runtime/issues/1505
/// - https://github.com/kata-containers/kata-containers/issues/1879
#[derive(Debug, Default)]
pub struct BindWatcher {
/// Container ID -> Vec of watched entries
sandbox_storages: Arc<Mutex<HashMap<String, SandboxStorages>>>,
watch_thread: Option<task::JoinHandle<()>>,
}
impl Drop for BindWatcher {
fn drop(&mut self) {
self.cleanup();
}
}
impl BindWatcher {
pub fn new() -> BindWatcher {
Default::default()
}
pub async fn add_container(
&mut self,
id: String,
mounts: impl IntoIterator<Item = protos::Storage>,
logger: &Logger,
) -> Result<()> {
if self.watch_thread.is_none() {
// Virtio-fs shared path is RO by default, so we back the target-mounts by tmpfs.
self.mount(logger).await?;
// Spawn background thread to monitor changes
self.watch_thread = Some(Self::spawn_watcher(
logger.clone(),
Arc::clone(&self.sandbox_storages),
WATCH_INTERVAL_SECS,
));
}
self.sandbox_storages
.lock()
.await
.entry(id)
.or_insert_with(SandboxStorages::default)
.add(mounts, logger)
.await
.with_context(|| "Failed to add container")?;
Ok(())
}
pub async fn remove_container(&self, id: &str) {
self.sandbox_storages.lock().await.remove(id);
}
fn spawn_watcher(
logger: Logger,
sandbox_storages: Arc<Mutex<HashMap<String, SandboxStorages>>>,
interval_secs: u64,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(interval_secs));
loop {
interval.tick().await;
debug!(&logger, "Looking for changed files");
for (_, entries) in sandbox_storages.lock().await.iter_mut() {
if let Err(err) = entries.check(&logger).await {
// We don't fail background loop, but rather log error instead.
error!(logger, "Check failed: {}", err);
}
}
}
})
}
async fn mount(&self, logger: &Logger) -> Result<()> {
fs::create_dir_all(WATCH_MOUNT_POINT_PATH).await?;
BareMount::new(
"tmpfs",
WATCH_MOUNT_POINT_PATH,
"tmpfs",
MsFlags::empty(),
"",
logger,
)
.mount()?;
Ok(())
}
fn cleanup(&mut self) {
if let Some(handle) = self.watch_thread.take() {
// Stop our background thread
handle.abort();
}
let _ = umount(WATCH_MOUNT_POINT_PATH);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mount::is_mounted;
use crate::skip_if_not_root;
use std::fs;
use std::thread;
#[tokio::test]
async fn watch_entries() {
skip_if_not_root!();
// If there's an error with an entry, let's make sure it is removed, and that the
// mount-destination behaves like a standard bind-mount.
// Create an entries vector with three storage objects: storage, storage1, storage2.
// We'll first verify each are evaluated correctly, then increase the first entry's contents
// so it fails mount size check (>1MB) (test handling for failure on mount that is a directory).
// We'll then similarly cause failure with storage2 (test handling for failure on mount that is
// a single file). We'll then verify that storage1 continues to be watchable.
let source_dir = tempfile::tempdir().unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let storage = protos::Storage {
source: source_dir.path().display().to_string(),
mount_point: dest_dir.path().display().to_string(),
..Default::default()
};
std::fs::File::create(source_dir.path().join("small.txt"))
.unwrap()
.set_len(10)
.unwrap();
let source_dir1 = tempfile::tempdir().unwrap();
let dest_dir1 = tempfile::tempdir().unwrap();
let storage1 = protos::Storage {
source: source_dir1.path().display().to_string(),
mount_point: dest_dir1.path().display().to_string(),
..Default::default()
};
std::fs::File::create(source_dir1.path().join("large.txt"))
.unwrap()
.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT)
.unwrap();
// And finally, create a single file mount:
let source_dir2 = tempfile::tempdir().unwrap();
let dest_dir2 = tempfile::tempdir().unwrap();
let source_path = source_dir2.path().join("mounted-file");
let dest_path = dest_dir2.path().join("mounted-file");
let mounted_file = std::fs::File::create(&source_path).unwrap();
mounted_file.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT).unwrap();
let storage2 = protos::Storage {
source: source_path.display().to_string(),
mount_point: dest_path.display().to_string(),
..Default::default()
};
let logger = slog::Logger::root(slog::Discard, o!());
let mut entries = SandboxStorages {
..Default::default()
};
entries
.add(std::iter::once(storage), &logger)
.await
.unwrap();
entries
.add(std::iter::once(storage1), &logger)
.await
.unwrap();
entries
.add(std::iter::once(storage2), &logger)
.await
.unwrap();
// Check that there are three entries, and that the
// destination (mount point) matches what we expect for
// the first:
assert!(entries.check(&logger).await.is_ok());
assert_eq!(entries.0.len(), 3);
assert_eq!(std::fs::read_dir(dest_dir.path()).unwrap().count(), 1);
// Add a second file which will trip file size check:
std::fs::File::create(source_dir.path().join("big.txt"))
.unwrap()
.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT)
.unwrap();
assert!(entries.check(&logger).await.is_ok());
// Verify Storage 0 is no longer going to be watched:
assert!(!entries.0[0].watch);
// Verify that the directory has two entries:
assert_eq!(std::fs::read_dir(dest_dir.path()).unwrap().count(), 2);
// Verify that the directory is a bind mount. Add an entry without calling check,
// and verify that the destination directory includes these files in the case of
// mount that is no longer being watched (storage), but not within the still-being
// watched (storage1):
fs::write(source_dir.path().join("1.txt"), "updated").unwrap();
fs::write(source_dir1.path().join("2.txt"), "updated").unwrap();
assert_eq!(std::fs::read_dir(source_dir.path()).unwrap().count(), 3);
assert_eq!(std::fs::read_dir(dest_dir.path()).unwrap().count(), 3);
assert_eq!(std::fs::read_dir(source_dir1.path()).unwrap().count(), 2);
assert_eq!(std::fs::read_dir(dest_dir1.path()).unwrap().count(), 1);
// Verify that storage1 is still working. After running check, we expect that the number
// of entries to increment
assert!(entries.check(&logger).await.is_ok());
assert_eq!(std::fs::read_dir(dest_dir1.path()).unwrap().count(), 2);
// Break storage2 by increasing the file size
mounted_file
.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT + 10)
.unwrap();
assert!(entries.check(&logger).await.is_ok());
// Verify Storage 2 is no longer going to be watched:
assert!(!entries.0[2].watch);
// Verify bind mount is working -- let's write to the file and observe output:
fs::write(&source_path, "updated").unwrap();
assert_eq!(fs::read_to_string(&source_path).unwrap(), "updated");
}
#[tokio::test]
async fn watch_directory_too_large() {
let source_dir = tempfile::tempdir().unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let mut entry = Storage::new(protos::Storage {
source: source_dir.path().display().to_string(),
mount_point: dest_dir.path().display().to_string(),
..Default::default()
})
.await
.unwrap();
let logger = slog::Logger::root(slog::Discard, o!());
// Create a file that is too large:
std::fs::File::create(source_dir.path().join("big.txt"))
.unwrap()
.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT + 1)
.unwrap();
thread::sleep(Duration::from_secs(1));
assert!(entry.scan(&logger).await.is_err());
fs::remove_file(source_dir.path().join("big.txt")).unwrap();
std::fs::File::create(source_dir.path().join("big.txt"))
.unwrap()
.set_len(MAX_SIZE_PER_WATCHABLE_MOUNT - 1)
.unwrap();
thread::sleep(Duration::from_secs(1));
assert!(entry.scan(&logger).await.is_ok());
std::fs::File::create(source_dir.path().join("too-big.txt"))
.unwrap()
.set_len(2)
.unwrap();
thread::sleep(Duration::from_secs(1));
assert!(entry.scan(&logger).await.is_err());
fs::remove_file(source_dir.path().join("big.txt")).unwrap();
fs::remove_file(source_dir.path().join("too-big.txt")).unwrap();
// Up to eight files should be okay:
fs::write(source_dir.path().join("1.txt"), "updated").unwrap();
fs::write(source_dir.path().join("2.txt"), "updated").unwrap();
fs::write(source_dir.path().join("3.txt"), "updated").unwrap();
fs::write(source_dir.path().join("4.txt"), "updated").unwrap();
fs::write(source_dir.path().join("5.txt"), "updated").unwrap();
fs::write(source_dir.path().join("6.txt"), "updated").unwrap();
fs::write(source_dir.path().join("7.txt"), "updated").unwrap();
fs::write(source_dir.path().join("8.txt"), "updated").unwrap();
assert_eq!(entry.scan(&logger).await.unwrap(), 8);
// Nine files is too many:
fs::write(source_dir.path().join("9.txt"), "updated").unwrap();
thread::sleep(Duration::from_secs(1));
assert!(entry.scan(&logger).await.is_err());
}
#[tokio::test]
async fn watch_directory() {
// Prepare source directory:
// ./tmp/1.txt
// ./tmp/A/B/2.txt
let source_dir = tempfile::tempdir().unwrap();
fs::write(source_dir.path().join("1.txt"), "one").unwrap();
fs::create_dir_all(source_dir.path().join("A/B")).unwrap();
fs::write(source_dir.path().join("A/B/1.txt"), "two").unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let mut entry = Storage::new(protos::Storage {
source: source_dir.path().display().to_string(),
mount_point: dest_dir.path().display().to_string(),
..Default::default()
})
.await
.unwrap();
let logger = slog::Logger::root(slog::Discard, o!());
assert_eq!(entry.scan(&logger).await.unwrap(), 2);
// Should copy no files since nothing is changed since last check
assert_eq!(entry.scan(&logger).await.unwrap(), 0);
// Should copy 1 file
thread::sleep(Duration::from_secs(1));
fs::write(source_dir.path().join("A/B/1.txt"), "updated").unwrap();
assert_eq!(entry.scan(&logger).await.unwrap(), 1);
assert_eq!(
fs::read_to_string(dest_dir.path().join("A/B/1.txt")).unwrap(),
"updated"
);
// Should copy no new files after copy happened
assert_eq!(entry.scan(&logger).await.unwrap(), 0);
// Update another file
fs::write(source_dir.path().join("1.txt"), "updated").unwrap();
assert_eq!(entry.scan(&logger).await.unwrap(), 1);
}
#[tokio::test]
async fn watch_file() {
let source_dir = tempfile::tempdir().unwrap();
let source_file = source_dir.path().join("1.txt");
fs::write(&source_file, "one").unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let dest_file = dest_dir.path().join("1.txt");
let mut entry = Storage::new(protos::Storage {
source: source_file.display().to_string(),
mount_point: dest_file.display().to_string(),
..Default::default()
})
.await
.unwrap();
let logger = slog::Logger::root(slog::Discard, o!());
assert_eq!(entry.scan(&logger).await.unwrap(), 1);
thread::sleep(Duration::from_secs(1));
fs::write(&source_file, "two").unwrap();
assert_eq!(entry.scan(&logger).await.unwrap(), 1);
assert_eq!(fs::read_to_string(&dest_file).unwrap(), "two");
assert_eq!(entry.scan(&logger).await.unwrap(), 0);
}
#[tokio::test]
async fn delete_file() {
let source_dir = tempfile::tempdir().unwrap();
let source_file = source_dir.path().join("1.txt");
fs::write(&source_file, "one").unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let target_file = dest_dir.path().join("1.txt");
let mut entry = Storage::new(protos::Storage {
source: source_dir.path().display().to_string(),
mount_point: dest_dir.path().display().to_string(),
..Default::default()
})
.await
.unwrap();
let logger = slog::Logger::root(slog::Discard, o!());
assert_eq!(entry.scan(&logger).await.unwrap(), 1);
assert_eq!(entry.watched_files.len(), 1);
assert!(target_file.exists());
assert!(entry.watched_files.contains_key(&source_file));
// Remove source file
fs::remove_file(&source_file).unwrap();
assert_eq!(entry.scan(&logger).await.unwrap(), 0);
assert_eq!(entry.watched_files.len(), 0);
assert!(!target_file.exists());
}
#[tokio::test]
async fn make_target_path() {
let source_dir = tempfile::tempdir().unwrap();
let target_dir = tempfile::tempdir().unwrap();
let source_dir = source_dir.path();
let target_dir = target_dir.path();
let entry = Storage::new(protos::Storage {
source: source_dir.display().to_string(),
mount_point: target_dir.display().to_string(),
..Default::default()
})
.await
.unwrap();
assert_eq!(
entry.make_target_path(source_dir.join("1.txt")).unwrap(),
target_dir.join("1.txt")
);
assert_eq!(
entry
.make_target_path(source_dir.join("a/b/2.txt"))
.unwrap(),
target_dir.join("a/b/2.txt")
);
}
#[tokio::test]
async fn create_tmpfs() {
skip_if_not_root!();
let logger = slog::Logger::root(slog::Discard, o!());
let mut watcher = BindWatcher::default();
watcher.mount(&logger).await.unwrap();
assert!(is_mounted(WATCH_MOUNT_POINT_PATH).unwrap());
watcher.cleanup();
assert!(!is_mounted(WATCH_MOUNT_POINT_PATH).unwrap());
}
#[tokio::test]
async fn spawn_thread() {
skip_if_not_root!();
let source_dir = tempfile::tempdir().unwrap();
fs::write(source_dir.path().join("1.txt"), "one").unwrap();
let dest_dir = tempfile::tempdir().unwrap();
let storage = protos::Storage {
source: source_dir.path().display().to_string(),
mount_point: dest_dir.path().display().to_string(),
..Default::default()
};
let logger = slog::Logger::root(slog::Discard, o!());
let mut watcher = BindWatcher::default();
watcher
.add_container("test".into(), std::iter::once(storage), &logger)
.await
.unwrap();
thread::sleep(Duration::from_secs(WATCH_INTERVAL_SECS));
let out = fs::read_to_string(dest_dir.path().join("1.txt")).unwrap();
assert_eq!(out, "one");
}
}

View File

@@ -0,0 +1,19 @@
[package]
name = "vsock-exporter"
version = "0.1.0"
authors = ["James O. D. Hunt <james.o.hunt@intel.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nix = "0.21.0"
libc = "0.2.94"
thiserror = "1.0.24"
opentelemetry = { version = "0.14.0", features=["serialize"] }
serde = { version = "1.0.126", features = ["derive"] }
vsock = "0.2.3"
bincode = "1.3.3"
byteorder = "1.4.3"
slog = { version = "2.5.2", features = ["dynamic-keys", "max_level_trace", "release_max_level_info"] }
async-trait = "0.1.50"

View File

@@ -0,0 +1,196 @@
// Copyright (c) 2020-2021 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
// The VSOCK Exporter sends trace spans "out" to the forwarder running on the
// host (which then forwards them on to a trace collector). The data is sent
// via a VSOCK socket that the forwarder process is listening on. To allow the
// forwarder to know how much data to each for each trace span the simplest
// protocol is employed which uses a header packet and the payload (trace
// span) data. The header packet is a simple count of the number of bytes in the
// payload, which allows the forwarder to know how many bytes it must read to
// consume the trace span. The payload is a serialised version of the trace span.
use async_trait::async_trait;
use byteorder::{ByteOrder, NetworkEndian};
use opentelemetry::sdk::export::trace::{ExportResult, SpanData, SpanExporter};
use opentelemetry::sdk::export::ExportError;
use slog::{error, o, Logger};
use std::io::{ErrorKind, Write};
use std::net::Shutdown;
use std::sync::Mutex;
use vsock::{SockAddr, VsockStream};
const ANY_CID: &str = "any";
// Must match the value of the variable of the same name in the trace forwarder.
const HEADER_SIZE_BYTES: u64 = std::mem::size_of::<u64>() as u64;
// By default, the VSOCK exporter should talk "out" to the host where the
// forwarder is running.
const DEFAULT_CID: u32 = libc::VMADDR_CID_HOST;
// The VSOCK port the forwarders listens on by default
const DEFAULT_PORT: u32 = 10240;
#[derive(Debug)]
pub struct Exporter {
port: u32,
cid: u32,
conn: Mutex<VsockStream>,
logger: Logger,
}
impl Exporter {
/// Create a new exporter builder.
pub fn builder() -> Builder {
Builder::default()
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("connection error: {0}")]
ConnectionError(String),
#[error("serialisation error: {0}")]
SerialisationError(#[from] bincode::Error),
#[error("I/O error: {0}")]
IOError(#[from] std::io::Error),
}
impl ExportError for Error {
fn exporter_name(&self) -> &'static str {
"vsock-exporter"
}
}
fn make_io_error(desc: String) -> std::io::Error {
std::io::Error::new(ErrorKind::Other, desc)
}
// Send a trace span to the forwarder running on the host.
fn write_span(writer: &mut dyn Write, span: &SpanData) -> Result<(), std::io::Error> {
let encoded_payload: Vec<u8> =
bincode::serialize(&span).map_err(|e| make_io_error(e.to_string()))?;
let payload_len: u64 = encoded_payload.len() as u64;
let mut payload_len_as_bytes: [u8; HEADER_SIZE_BYTES as usize] =
[0; HEADER_SIZE_BYTES as usize];
// Encode the header
NetworkEndian::write_u64(&mut payload_len_as_bytes, payload_len);
// Send the header
writer
.write_all(&payload_len_as_bytes)
.map_err(|e| make_io_error(format!("failed to write trace header: {:?}", e)))?;
writer
.write_all(&encoded_payload)
.map_err(|e| make_io_error(format!("failed to write trace payload: {:?}", e)))
}
fn handle_batch(writer: &mut dyn Write, batch: Vec<SpanData>) -> ExportResult {
for span_data in batch {
write_span(writer, &span_data).map_err(Error::IOError)?;
}
Ok(())
}
#[async_trait]
impl SpanExporter for Exporter {
async fn export(&mut self, batch: Vec<SpanData>) -> ExportResult {
let conn = self.conn.lock();
match conn {
Ok(mut c) => handle_batch(&mut *c, batch),
Err(e) => {
error!(self.logger, "failed to obtain connection";
"error" => format!("{}", e));
return Err(Error::ConnectionError(e.to_string()).into());
}
}
}
fn shutdown(&mut self) {
let conn = match self.conn.lock() {
Ok(conn) => conn,
Err(e) => {
error!(self.logger, "failed to obtain connection";
"error" => format!("{}", e));
return;
}
};
conn.shutdown(Shutdown::Write)
.expect("failed to shutdown VSOCK connection");
}
}
#[derive(Debug)]
pub struct Builder {
port: u32,
cid: u32,
logger: Logger,
}
impl Default for Builder {
fn default() -> Self {
let logger = Logger::root(slog::Discard, o!());
Builder {
cid: DEFAULT_CID,
port: DEFAULT_PORT,
logger,
}
}
}
impl Builder {
pub fn with_cid(self, cid: u32) -> Self {
Builder { cid, ..self }
}
pub fn with_port(self, port: u32) -> Self {
Builder { port, ..self }
}
pub fn with_logger(self, logger: &Logger) -> Self {
Builder {
logger: logger.new(o!()),
..self
}
}
pub fn init(self) -> Exporter {
let Builder { port, cid, logger } = self;
let sock_addr = SockAddr::new_vsock(self.cid, self.port);
let cid_str: String;
if self.cid == libc::VMADDR_CID_ANY {
cid_str = ANY_CID.to_string();
} else {
cid_str = format!("{}", self.cid);
}
let msg = format!(
"failed to connect to VSOCK server (port: {}, cid: {}) - {}",
self.port, cid_str, "ensure trace forwarder is running on host"
);
let conn = VsockStream::connect(&sock_addr).expect(&msg);
Exporter {
port,
cid,
conn: Mutex::new(conn),
logger: logger.new(o!("cid" => cid_str, "port" => port)),
}
}
}

View File

@@ -582,7 +582,8 @@ $(MONITOR_OUTPUT): $(SOURCES) $(GENERATED_FILES) $(MAKEFILE_LIST) .git-commit
install \
show-header \
show-summary \
show-variables
show-variables \
vendor
$(TARGET).coverage: $(SOURCES) $(GENERATED_FILES) $(MAKEFILE_LIST)
$(QUIET_TEST)go test -o $@ -covermode count
@@ -647,6 +648,14 @@ install-scripts: $(SCRIPTS)
install-completions:
$(QUIET_INST)install --mode 0644 -D $(BASH_COMPLETIONS) $(DESTDIR)/$(BASH_COMPLETIONSDIR)/$(notdir $(BASH_COMPLETIONS));
handle_vendor:
go mod tidy
go mod vendor
go mod verify
vendor: handle_vendor
./hack/tree_status.sh
clean:
$(QUIET_CLEAN)rm -f \
$(CONFIGS) \

View File

@@ -1,7 +1,4 @@
[![Build Status](https://travis-ci.org/kata-containers/kata-containers.svg?branch=master)](https://travis-ci.org/kata-containers/kata-containers)
[![Build Status](http://jenkins.katacontainers.io/job/kata-containers-runtime-ubuntu-18-04-master/badge/icon)](http://jenkins.katacontainers.io/job/kata-containers-runtime-ubuntu-18-04-master/)
[![Go Report Card](https://goreportcard.com/badge/github.com/kata-containers/kata-containers)](https://goreportcard.com/report/github.com/kata-containers/kata-containers)
[![GoDoc](https://godoc.org/github.com/kata-containers/runtime?status.svg)](https://godoc.org/github.com/kata-containers/runtime)
# Runtime
@@ -84,7 +81,7 @@ $ kata-runtime check
[![Get it from the Snap Store](https://snapcraft.io/static/images/badges/en/snap-store-black.svg)](https://snapcraft.io/kata-containers)
See the [installation guides](https://github.com/kata-containers/documentation/tree/master/install/README.md)
See the [installation guides](https://github.com/kata-containers/kata-containers/blob/main/docs/install/README.md)
available for various operating systems.
## Quick start for developers

View File

@@ -5,7 +5,7 @@
# Intel x86-64 settings
MACHINETYPE := pc
MACHINETYPE := q35
KERNELPARAMS :=
MACHINEACCELERATORS :=
CPUFEATURES := pmu=off

View File

@@ -11,3 +11,10 @@ MACHINEACCELERATORS :=
CPUFEATURES :=
QEMUCMD := qemu-system-s390x
# See https://github.com/kata-containers/osbuilder/issues/217
NEEDS_CC_SETTING = $(shell grep -E "\<(fedora|suse)\>" /etc/os-release 2> /dev/null)
ifneq (,$(NEEDS_CC_SETTING))
CC := gcc
export CC
endif

View File

@@ -150,6 +150,10 @@ block_device_driver = "@DEFBLOCKSTORAGEDRIVER_ACRN@"
#debug_console_enabled = true
# Agent connection dialing timeout value in seconds
# (default: 30)
#dial_timeout = 30
[netmon]
# If enabled, the network monitoring process gets started when the
# sandbox is created. This allows for the detection of some additional

View File

@@ -165,6 +165,10 @@ block_device_driver = "virtio-blk"
#debug_console_enabled = true
# Agent connection dialing timeout value in seconds
# (default: 30)
#dial_timeout = 30
[netmon]
# If enabled, the network monitoring process gets started when the
# sandbox is created. This allows for the detection of some additional

View File

@@ -178,7 +178,7 @@ block_device_driver = "@DEFBLOCKSTORAGEDRIVER_FC@"
# VFIO devices are hotplugged on a bridge by default.
# Enable hotplugging on root bus. This may be required for devices with
# a large PCI bar, as this is a current limitation with hotplugging on
# a bridge. This value is valid for "pc" machine type.
# a bridge.
# Default false
#hotplug_vfio_on_root_bus = true
@@ -287,6 +287,10 @@ kernel_modules=[]
#debug_console_enabled = true
# Agent connection dialing timeout value in seconds
# (default: 30)
#dial_timeout = 30
[netmon]
# If enabled, the network monitoring process gets started when the
# sandbox is created. This allows for the detection of some additional

View File

@@ -16,6 +16,14 @@ kernel = "@KERNELPATH@"
image = "@IMAGEPATH@"
machine_type = "@MACHINETYPE@"
# Enable confidential guest support.
# Toggling that setting may trigger different hardware features, ranging
# from memory encryption to both memory and CPU-state encryption and integrity.
# The Kata Containers runtime dynamically detects the available feature set and
# aims at enabling the largest possible one.
# Default false
# confidential_guest = true
# List of valid annotation names for the hypervisor
# Each member of the list is a regular expression, which is the base name
# of the annotation, e.g. "path" for io.katacontainers.config.hypervisor.path"
@@ -269,7 +277,7 @@ pflashes = []
# VFIO devices are hotplugged on a bridge by default.
# Enable hotplugging on root bus. This may be required for devices with
# a large PCI bar, as this is a current limitation with hotplugging on
# a bridge. This value is valid for "pc" machine type.
# a bridge.
# Default false
#hotplug_vfio_on_root_bus = true
@@ -437,6 +445,10 @@ kernel_modules=[]
#debug_console_enabled = true
# Agent connection dialing timeout value in seconds
# (default: 30)
#dial_timeout = 30
[netmon]
# If enabled, the network monitoring process gets started when the
# sandbox is created. This allows for the detection of some additional
@@ -532,3 +544,30 @@ experimental=@DEFAULTEXPFEATURES@
# If enabled, user can run pprof tools with shim v2 process through kata-monitor.
# (default: false)
# enable_pprof = true
# WARNING: All the options in the following section have not been implemented yet.
# This section was added as a placeholder. DO NOT USE IT!
[image]
# Container image service.
#
# Offload the CRI image management service to the Kata agent.
# (default: false)
#service_offload = true
# Container image decryption keys provisioning.
# Applies only if service_offload is true.
# Keys can be provisioned locally (e.g. through a special command or
# a local file) or remotely (usually after the guest is remotely attested).
# The provision setting is a complete URL that lets the Kata agent decide
# which method to use in order to fetch the keys.
#
# Keys can be stored in a local file, in a measured and attested initrd:
#provision=data:///local/key/file
#
# Keys could be fetched through a special command or binary from the
# initrd (guest) image, e.g. a firmware call:
#provision=file:///path/to/bin/fetcher/in/guest
#
# Keys can be remotely provisioned. The Kata agent fetches them from e.g.
# a HTTPS URL:
#provision=https://my-key-broker.foo/tenant/<tenant-id>

View File

@@ -25,6 +25,7 @@ import (
"strings"
"syscall"
"github.com/containerd/cgroups"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/oci"
@@ -389,13 +390,6 @@ EXAMPLES:
if verbose {
kataLog.Logger.SetLevel(logrus.InfoLevel)
}
ctx, err := cliContextToContext(context)
if err != nil {
return err
}
span, _ := katautils.Trace(ctx, "check")
defer span.End()
if !context.Bool("no-network-checks") && os.Getenv(noNetworkEnvVar) == "" {
cmd := RelCmdCheck
@@ -407,8 +401,7 @@ EXAMPLES:
if os.Geteuid() == 0 {
kataLog.Warn("Not running network checks as super user")
} else {
err = HandleReleaseVersions(cmd, version, context.Bool("include-all-releases"))
err := HandleReleaseVersions(cmd, version, context.Bool("include-all-releases"))
if err != nil {
return err
}
@@ -424,7 +417,12 @@ EXAMPLES:
return errors.New("check: cannot determine runtime config")
}
err = setCPUtype(runtimeConfig.HypervisorType)
// check if cgroup can work use the same logic for creating containers
if _, err := vc.V1Constraints(); err != nil && err == cgroups.ErrMountPointNotExist && !runtimeConfig.SandboxCgroupOnly {
return fmt.Errorf("Cgroup v2 requires the following configuration: `sandbox_cgroup_only=true`.")
}
err := setCPUtype(runtimeConfig.HypervisorType)
if err != nil {
return err
}
@@ -437,7 +435,6 @@ EXAMPLES:
}
err = hostIsVMContainerCapable(details)
if err != nil {
return err
}

View File

@@ -13,7 +13,6 @@ import (
"strings"
"github.com/BurntSushi/toml"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/kata-containers/kata-containers/src/runtime/pkg/utils"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
exp "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/experimental"
@@ -266,9 +265,9 @@ func getMemoryInfo() MemoryInfo {
}
return MemoryInfo{
Total: mi.MemTotal,
Free: mi.MemFree,
Available: mi.MemAvailable,
Total: *mi.MemTotal,
Free: *mi.MemFree,
Available: *mi.MemAvailable,
}
}
@@ -448,14 +447,6 @@ var kataEnvCLICommand = cli.Command{
},
},
Action: func(context *cli.Context) error {
ctx, err := cliContextToContext(context)
if err != nil {
return err
}
span, _ := katautils.Trace(ctx, "kata-env")
defer span.End()
return handleSettings(defaultOutputFile, context)
},
}

View File

@@ -14,7 +14,6 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
@@ -26,7 +25,6 @@ import (
clientUtils "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/agent/protocols/client"
"github.com/pkg/errors"
"github.com/urfave/cli"
"go.opentelemetry.io/otel/label"
)
const (
@@ -38,10 +36,8 @@ const (
subCommandName = "exec"
// command-line parameters name
paramRuntimeNamespace = "runtime-namespace"
paramDebugConsolePort = "kata-debug-port"
defaultKernelParamDebugConsoleVPortValue = 1026
defaultRuntimeNamespace = "k8s.io"
)
var (
@@ -57,34 +53,16 @@ var kataExecCLICommand = cli.Command{
Name: subCommandName,
Usage: "Enter into guest by debug console",
Flags: []cli.Flag{
cli.StringFlag{
Name: paramRuntimeNamespace,
Usage: "Namespace that containerd or CRI-O are using for containers. (Default: k8s.io, only works for containerd)",
},
cli.Uint64Flag{
Name: paramDebugConsolePort,
Usage: "Port that debug console is listening on. (Default: 1026)",
},
},
Action: func(context *cli.Context) error {
ctx, err := cliContextToContext(context)
if err != nil {
return err
}
span, _ := katautils.Trace(ctx, subCommandName)
defer span.End()
namespace := context.String(paramRuntimeNamespace)
if namespace == "" {
namespace = defaultRuntimeNamespace
}
span.SetAttributes(label.Key("namespace").String(namespace))
port := context.Uint64(paramDebugConsolePort)
if port == 0 {
port = defaultKernelParamDebugConsoleVPortValue
}
span.SetAttributes(label.Key("port").Uint64(port))
sandboxID := context.Args().Get(0)
@@ -92,9 +70,8 @@ var kataExecCLICommand = cli.Command{
return err
}
span.SetAttributes(label.Key("sandbox").String(sandboxID))
conn, err := getConn(sandboxID, port)
conn, err := getConn(namespace, sandboxID, port)
if err != nil {
return err
}
@@ -177,9 +154,8 @@ func (s *iostream) Read(data []byte) (n int, err error) {
return s.conn.Read(data)
}
func getConn(namespace, sandboxID string, port uint64) (net.Conn, error) {
socketAddr := filepath.Join(string(filepath.Separator), "containerd-shim", namespace, sandboxID, "shim-monitor.sock")
client, err := kataMonitor.BuildUnixSocketClient(socketAddr, defaultTimeout)
func getConn(sandboxID string, port uint64) (net.Conn, error) {
client, err := kataMonitor.BuildShimClient(sandboxID, defaultTimeout)
if err != nil {
return nil, err
}
@@ -190,7 +166,7 @@ func getConn(namespace, sandboxID string, port uint64) (net.Conn, error) {
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Failed to get %s: %d", socketAddr, resp.StatusCode)
return nil, fmt.Errorf("Failure from %s shim-monitor: %d", sandboxID, resp.StatusCode)
}
defer resp.Body.Close()

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2021 Apple Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"fmt"
kataMonitor "github.com/kata-containers/kata-containers/src/runtime/pkg/kata-monitor"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/urfave/cli"
)
var kataMetricsCLICommand = cli.Command{
Name: "metrics",
Usage: "gather metrics associated with infrastructure used to run a sandbox",
UsageText: "metrics <sandbox id>",
Action: func(context *cli.Context) error {
sandboxID := context.Args().Get(0)
if err := katautils.VerifyContainerID(sandboxID); err != nil {
return err
}
// Get the metrics!
metrics, err := kataMonitor.GetSandboxMetrics(sandboxID)
if err != nil {
return err
}
fmt.Printf("%s\n", metrics)
return nil
},
}

View File

@@ -22,14 +22,12 @@ import (
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
exp "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/experimental"
vf "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/factory"
tl "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/factory/template"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/oci"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/rootless"
specs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label"
otelTrace "go.opentelemetry.io/otel/trace"
)
// specConfig is the name of the file holding the containers configuration
@@ -125,6 +123,7 @@ var runtimeCommands = []cli.Command{
kataCheckCLICommand,
kataEnvCLICommand,
kataExecCLICommand,
kataMetricsCLICommand,
factoryCLICommand,
}
@@ -132,10 +131,6 @@ var runtimeCommands = []cli.Command{
// parsing occurs.
var runtimeBeforeSubcommands = beforeSubcommands
// runtimeAfterSubcommands is the function to run after the command-line
// has been parsed.
var runtimeAfterSubcommands = afterSubcommands
// runtimeCommandNotFound is the function to handle an invalid sub-command.
var runtimeCommandNotFound = commandNotFound
@@ -168,10 +163,6 @@ func init() {
// setupSignalHandler sets up signal handling, starting a go routine to deal
// with signals as they arrive.
//
// Note that the specified context is NOT used to create a trace span (since the
// first (root) span must be created in beforeSubcommands()): it is simply
// used to pass to the crash handling functions to finalise tracing.
func setupSignalHandler(ctx context.Context) {
signals.SetLogger(kataLog)
@@ -181,10 +172,6 @@ func setupSignalHandler(ctx context.Context) {
signal.Notify(sigCh, sig)
}
dieCb := func() {
katautils.StopTracing(ctx)
}
go func() {
for {
sig := <-sigCh
@@ -198,7 +185,6 @@ func setupSignalHandler(ctx context.Context) {
if signals.FatalSignal(nativeSignal) {
kataLog.WithField("signal", sig).Error("received fatal signal")
signals.Die(dieCb)
} else if debug && signals.NonFatalSignal(nativeSignal) {
kataLog.WithField("signal", sig).Debug("handling signal")
signals.Backtrace()
@@ -210,24 +196,15 @@ func setupSignalHandler(ctx context.Context) {
// setExternalLoggers registers the specified logger with the external
// packages which accept a logger to handle their own logging.
func setExternalLoggers(ctx context.Context, logger *logrus.Entry) {
var span otelTrace.Span
// Only create a new span if a root span already exists. This is
// required to ensure that this function will not disrupt the root
// span logic by creating a span before the proper root span has been
// created.
if otelTrace.SpanFromContext(ctx) != nil {
span, ctx = katautils.Trace(ctx, "setExternalLoggers")
defer span.End()
}
// Set virtcontainers logger.
vci.SetLogger(ctx, logger)
// Set vm factory logger.
vf.SetLogger(ctx, logger)
// Set vm factory template logger.
tl.SetLogger(ctx, logger)
// Set the OCI package logger.
oci.SetLogger(ctx, logger)
@@ -244,7 +221,6 @@ func beforeSubcommands(c *cli.Context) error {
var configFile string
var runtimeConfig oci.RuntimeConfig
var err error
var traceFlushFunc func()
katautils.SetConfigOptions(name, defaultRuntimeConfiguration, defaultSysConfRuntimeConfiguration)
@@ -270,7 +246,6 @@ func beforeSubcommands(c *cli.Context) error {
// Issue: https://github.com/kata-containers/runtime/issues/2428
ignoreConfigLogs := false
var traceRootSpan string
subCmdIsCheckCmd := (c.NArg() >= 1 && ((c.Args()[0] == "kata-check") || (c.Args()[0] == "check")))
if subCmdIsCheckCmd {
@@ -302,16 +277,13 @@ func beforeSubcommands(c *cli.Context) error {
cmdName := c.Args().First()
if c.App.Command(cmdName) != nil {
kataLog = kataLog.WithField("command", cmdName)
// Name for the root span (used for tracing) now the
// sub-command name is known.
traceRootSpan = name + " " + cmdName
}
// Since a context is required, pass a new (throw-away) one - we
// cannot use the main context as tracing hasn't been enabled yet
// (meaning any spans created at this point will be silently ignored).
setExternalLoggers(context.Background(), kataLog)
ctx, err := cliContextToContext(c)
if err != nil {
return err
}
setExternalLoggers(ctx, kataLog)
if c.NArg() == 1 && (c.Args()[0] == "kata-env" || c.Args()[0] == "env") {
// simply report the logging setup
@@ -325,20 +297,6 @@ func beforeSubcommands(c *cli.Context) error {
}
if !subCmdIsCheckCmd {
debug = runtimeConfig.Debug
if traceRootSpan != "" {
// Create the tracer.
//
// Note: no spans are created until the command-line has been parsed.
// This delays collection of trace data slightly but benefits the user by
// ensuring the first span is the name of the sub-command being
// invoked from the command-line.
traceFlushFunc, err = setupTracing(c, traceRootSpan, &runtimeConfig)
if err != nil {
return err
}
defer traceFlushFunc()
}
}
args := strings.Join(c.Args(), " ")
@@ -377,36 +335,6 @@ func handleShowConfig(context *cli.Context) {
}
}
func setupTracing(context *cli.Context, rootSpanName string, config *oci.RuntimeConfig) (func(), error) {
flush, err := katautils.CreateTracer(name, config)
if err != nil {
return nil, err
}
ctx, err := cliContextToContext(context)
if err != nil {
return nil, err
}
// Create the root span now that the sub-command name is
// known.
//
// Note that this "Before" function is called (and returns)
// before the subcommand handler is called. As such, we cannot
// "Finish()" the span here - that is handled in the .After
// function.
tracer := otel.Tracer("kata")
newCtx, span := tracer.Start(ctx, rootSpanName)
span.SetAttributes(label.Key("subsystem").String("runtime"))
// Add tracer to metadata and update the context
context.App.Metadata["tracer"] = tracer
context.App.Metadata["context"] = newCtx
return flush, nil
}
// add supported experimental features in context
func addExpFeatures(clictx *cli.Context, runtimeConfig oci.RuntimeConfig) error {
ctx, err := cliContextToContext(clictx)
@@ -420,22 +348,11 @@ func addExpFeatures(clictx *cli.Context, runtimeConfig oci.RuntimeConfig) error
}
ctx = exp.ContextWithExp(ctx, exps)
// Add tracer to metadata and update the context
// Add experimental features to metadata and update the context
clictx.App.Metadata["context"] = ctx
return nil
}
func afterSubcommands(c *cli.Context) error {
ctx, err := cliContextToContext(c)
if err != nil {
return err
}
katautils.StopTracing(ctx)
return nil
}
// function called when an invalid command is specified which causes the
// runtime to error.
func commandNotFound(c *cli.Context, command string) {
@@ -502,7 +419,6 @@ func createRuntimeApp(ctx context.Context, args []string) error {
app.Flags = runtimeFlags
app.Commands = runtimeCommands
app.Before = runtimeBeforeSubcommands
app.After = runtimeAfterSubcommands
app.EnableBashCompletion = true
// allow sub-commands to access context
@@ -578,12 +494,5 @@ func cliContextToContext(c *cli.Context) (context.Context, error) {
func main() {
// create a new empty context
ctx := context.Background()
dieCb := func() {
katautils.StopTracing(ctx)
}
defer signals.HandlePanic(dieCb)
createRuntime(ctx)
}

View File

@@ -20,7 +20,6 @@ import (
"strings"
"testing"
"github.com/dlespiau/covertool/pkg/cover"
ktu "github.com/kata-containers/kata-containers/src/runtime/pkg/katatestutils"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/kata-containers/kata-containers/src/runtime/pkg/utils"
@@ -152,16 +151,6 @@ func runUnitTests(m *testing.M) {
// TestMain is the common main function used by ALL the test functions
// for this package.
func TestMain(m *testing.M) {
// Parse the command line using the stdlib flag package so the flags defined
// in the testing package get populated.
cover.ParseAndStripTestFlags()
// Make sure we have the opportunity to flush the coverage report to disk when
// terminating the process.
defer func() {
cover.FlushProfiles()
}()
// If the test binary name is kata-runtime.coverage, we've are being asked to
// run the coverage-instrumented kata-runtime.
if path.Base(os.Args[0]) == name+".coverage" ||

View File

@@ -6,7 +6,6 @@
package main
import (
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/urfave/cli"
)
@@ -14,14 +13,6 @@ var versionCLICommand = cli.Command{
Name: "version",
Usage: "display version details",
Action: func(context *cli.Context) error {
ctx, err := cliContextToContext(context)
if err != nil {
return err
}
span, _ := katautils.Trace(ctx, "version")
defer span.End()
cli.VersionPrinter(context)
return nil
},

View File

@@ -19,14 +19,15 @@ import (
"github.com/containerd/typeurl"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
otelTrace "go.opentelemetry.io/otel/trace"
// only register the proto type
crioption "github.com/containerd/containerd/pkg/runtimeoptions/v1"
_ "github.com/containerd/containerd/runtime/linux/runctypes"
_ "github.com/containerd/containerd/runtime/v2/runc/options"
crioption "github.com/containerd/cri-containerd/pkg/api/runtimeoptions/v1"
oldcrioption "github.com/containerd/cri-containerd/pkg/api/runtimeoptions/v1"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils/katatrace"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/compatoci"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/oci"
@@ -69,19 +70,24 @@ func create(ctx context.Context, s *service, r *taskAPI.CreateTaskRequest) (*con
// create tracer
// This is the earliest location we can create the tracer because we must wait
// until the runtime config is loaded
_, err = katautils.CreateTracer("kata", s.config)
jaegerConfig := &katatrace.JaegerConfig{
JaegerEndpoint: s.config.JaegerEndpoint,
JaegerUser: s.config.JaegerUser,
JaegerPassword: s.config.JaegerPassword,
}
_, err = katatrace.CreateTracer("kata", jaegerConfig)
if err != nil {
return nil, err
}
// create root span
var rootSpan otelTrace.Span
rootSpan, s.rootCtx = trace(s.ctx, "root span")
rootSpan, newCtx := katatrace.Trace(s.ctx, shimLog, "root span", shimTracingTags)
s.rootCtx = newCtx
defer rootSpan.End()
// create span
var span otelTrace.Span
span, s.ctx = trace(s.rootCtx, "create")
span, newCtx := katatrace.Trace(s.rootCtx, shimLog, "create", shimTracingTags)
s.ctx = newCtx
defer span.End()
if rootFs.Mounted, err = checkAndMount(s, r); err != nil {
@@ -116,8 +122,7 @@ func create(ctx context.Context, s *service, r *taskAPI.CreateTaskRequest) (*con
go s.startManagementServer(ctx, ociSpec)
case vc.PodContainer:
var span otelTrace.Span
span, ctx = trace(s.ctx, "create")
span, ctx := katatrace.Trace(s.ctx, shimLog, "create", shimTracingTags)
defer span.End()
if s.sandbox == nil {
@@ -184,6 +189,16 @@ func loadRuntimeConfig(s *service, r *taskAPI.CreateTaskRequest, anno map[string
// and we'll ignore it.
if ok {
configPath = option.ConfigPath
} else {
// Some versions of containerd, such as 1.4.3, and 1.4.4
// still rely on the runtime options coming from
// github.com/containerd/cri-containerd/pkg/api/runtimeoptions/v1
// Knowing that, instead of breaking compatibility with such
// versions, let's work this around on our side
oldOption, ok := v.(*oldcrioption.Options)
if ok {
configPath = oldOption.ConfigPath
}
}
}

View File

@@ -8,7 +8,7 @@ package containerdshim
import (
"context"
"github.com/containerd/cgroups"
cgroupsv1 "github.com/containerd/cgroups/stats/v1"
"github.com/containerd/typeurl"
google_protobuf "github.com/gogo/protobuf/types"
@@ -31,11 +31,11 @@ func marshalMetrics(ctx context.Context, s *service, containerID string) (*googl
return data, nil
}
func statsToMetrics(stats *vc.ContainerStats) *cgroups.Metrics {
metrics := &cgroups.Metrics{}
func statsToMetrics(stats *vc.ContainerStats) *cgroupsv1.Metrics {
metrics := &cgroupsv1.Metrics{}
if stats.CgroupStats != nil {
metrics = &cgroups.Metrics{
metrics = &cgroupsv1.Metrics{
Hugetlb: setHugetlbStats(stats.CgroupStats.HugetlbStats),
Pids: setPidsStats(stats.CgroupStats.PidsStats),
CPU: setCPUStats(stats.CgroupStats.CPUStats),
@@ -49,12 +49,12 @@ func statsToMetrics(stats *vc.ContainerStats) *cgroups.Metrics {
return metrics
}
func setHugetlbStats(vcHugetlb map[string]vc.HugetlbStats) []*cgroups.HugetlbStat {
var hugetlbStats []*cgroups.HugetlbStat
func setHugetlbStats(vcHugetlb map[string]vc.HugetlbStats) []*cgroupsv1.HugetlbStat {
var hugetlbStats []*cgroupsv1.HugetlbStat
for _, v := range vcHugetlb {
hugetlbStats = append(
hugetlbStats,
&cgroups.HugetlbStat{
&cgroupsv1.HugetlbStat{
Usage: v.Usage,
Max: v.MaxUsage,
Failcnt: v.Failcnt,
@@ -64,8 +64,8 @@ func setHugetlbStats(vcHugetlb map[string]vc.HugetlbStats) []*cgroups.HugetlbSta
return hugetlbStats
}
func setPidsStats(vcPids vc.PidsStats) *cgroups.PidsStat {
pidsStats := &cgroups.PidsStat{
func setPidsStats(vcPids vc.PidsStats) *cgroupsv1.PidsStat {
pidsStats := &cgroupsv1.PidsStat{
Current: vcPids.Current,
Limit: vcPids.Limit,
}
@@ -73,19 +73,19 @@ func setPidsStats(vcPids vc.PidsStats) *cgroups.PidsStat {
return pidsStats
}
func setCPUStats(vcCPU vc.CPUStats) *cgroups.CPUStat {
func setCPUStats(vcCPU vc.CPUStats) *cgroupsv1.CPUStat {
var perCPU []uint64
perCPU = append(perCPU, vcCPU.CPUUsage.PercpuUsage...)
cpuStats := &cgroups.CPUStat{
Usage: &cgroups.CPUUsage{
cpuStats := &cgroupsv1.CPUStat{
Usage: &cgroupsv1.CPUUsage{
Total: vcCPU.CPUUsage.TotalUsage,
Kernel: vcCPU.CPUUsage.UsageInKernelmode,
User: vcCPU.CPUUsage.UsageInUsermode,
PerCPU: perCPU,
},
Throttling: &cgroups.Throttle{
Throttling: &cgroupsv1.Throttle{
Periods: vcCPU.ThrottlingData.Periods,
ThrottledPeriods: vcCPU.ThrottlingData.ThrottledPeriods,
ThrottledTime: vcCPU.ThrottlingData.ThrottledTime,
@@ -95,27 +95,27 @@ func setCPUStats(vcCPU vc.CPUStats) *cgroups.CPUStat {
return cpuStats
}
func setMemoryStats(vcMemory vc.MemoryStats) *cgroups.MemoryStat {
memoryStats := &cgroups.MemoryStat{
Usage: &cgroups.MemoryEntry{
func setMemoryStats(vcMemory vc.MemoryStats) *cgroupsv1.MemoryStat {
memoryStats := &cgroupsv1.MemoryStat{
Usage: &cgroupsv1.MemoryEntry{
Limit: vcMemory.Usage.Limit,
Usage: vcMemory.Usage.Usage,
Max: vcMemory.Usage.MaxUsage,
Failcnt: vcMemory.Usage.Failcnt,
},
Swap: &cgroups.MemoryEntry{
Swap: &cgroupsv1.MemoryEntry{
Limit: vcMemory.SwapUsage.Limit,
Usage: vcMemory.SwapUsage.Usage,
Max: vcMemory.SwapUsage.MaxUsage,
Failcnt: vcMemory.SwapUsage.Failcnt,
},
Kernel: &cgroups.MemoryEntry{
Kernel: &cgroupsv1.MemoryEntry{
Limit: vcMemory.KernelUsage.Limit,
Usage: vcMemory.KernelUsage.Usage,
Max: vcMemory.KernelUsage.MaxUsage,
Failcnt: vcMemory.KernelUsage.Failcnt,
},
KernelTCP: &cgroups.MemoryEntry{
KernelTCP: &cgroupsv1.MemoryEntry{
Limit: vcMemory.KernelTCPUsage.Limit,
Usage: vcMemory.KernelTCPUsage.Usage,
Max: vcMemory.KernelTCPUsage.MaxUsage,
@@ -145,8 +145,8 @@ func setMemoryStats(vcMemory vc.MemoryStats) *cgroups.MemoryStat {
return memoryStats
}
func setBlkioStats(vcBlkio vc.BlkioStats) *cgroups.BlkIOStat {
blkioStats := &cgroups.BlkIOStat{
func setBlkioStats(vcBlkio vc.BlkioStats) *cgroupsv1.BlkIOStat {
blkioStats := &cgroupsv1.BlkIOStat{
IoServiceBytesRecursive: copyBlkio(vcBlkio.IoServiceBytesRecursive),
IoServicedRecursive: copyBlkio(vcBlkio.IoServicedRecursive),
IoQueuedRecursive: copyBlkio(vcBlkio.IoQueuedRecursive),
@@ -160,10 +160,10 @@ func setBlkioStats(vcBlkio vc.BlkioStats) *cgroups.BlkIOStat {
return blkioStats
}
func copyBlkio(s []vc.BlkioStatEntry) []*cgroups.BlkIOEntry {
ret := make([]*cgroups.BlkIOEntry, len(s))
func copyBlkio(s []vc.BlkioStatEntry) []*cgroupsv1.BlkIOEntry {
ret := make([]*cgroupsv1.BlkIOEntry, len(s))
for i, v := range s {
ret[i] = &cgroups.BlkIOEntry{
ret[i] = &cgroupsv1.BlkIOEntry{
Op: v.Op,
Major: v.Major,
Minor: v.Minor,
@@ -174,10 +174,10 @@ func copyBlkio(s []vc.BlkioStatEntry) []*cgroups.BlkIOEntry {
return ret
}
func setNetworkStats(vcNetwork []*vc.NetworkStats) []*cgroups.NetworkStat {
networkStats := make([]*cgroups.NetworkStat, len(vcNetwork))
func setNetworkStats(vcNetwork []*vc.NetworkStats) []*cgroupsv1.NetworkStat {
networkStats := make([]*cgroupsv1.NetworkStat, len(vcNetwork))
for i, v := range vcNetwork {
networkStats[i] = &cgroups.NetworkStat{
networkStats[i] = &cgroupsv1.NetworkStat{
Name: v.Name,
RxBytes: v.RxBytes,
RxPackets: v.RxPackets,

View File

@@ -10,7 +10,7 @@ import (
"context"
"testing"
"github.com/containerd/cgroups"
"github.com/containerd/cgroups/stats/v1"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/vcmock"
"github.com/stretchr/testify/assert"
@@ -29,7 +29,7 @@ func TestStatNetworkMetric(t *testing.T) {
},
}
expectedNetwork := []*cgroups.NetworkStat{
expectedNetwork := []*v1.NetworkStat{
{
Name: "test-network",
RxBytes: 10,

View File

@@ -27,18 +27,22 @@ import (
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/label"
otelTrace "go.opentelemetry.io/otel/trace"
"golang.org/x/sys/unix"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils/katatrace"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/compatoci"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/oci"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/types"
)
// shimTracingTags defines tags for the trace span
var shimTracingTags = map[string]string{
"source": "runtime",
"package": "containerdshim",
}
const (
// Define the service's channel size, which is used for
// reaping the exited processes exit state and forwarding
@@ -68,7 +72,7 @@ var shimLog = logrus.WithFields(logrus.Fields{
})
// New returns a new shim service that can be used via GRPC
func New(ctx context.Context, id string, publisher events.Publisher) (cdshim.Shim, error) {
func New(ctx context.Context, id string, publisher cdshim.Publisher, shutdown func()) (cdshim.Shim, error) {
shimLog = shimLog.WithFields(logrus.Fields{
"sandbox": id,
"pid": os.Getpid(),
@@ -84,8 +88,6 @@ func New(ctx context.Context, id string, publisher events.Publisher) (cdshim.Shi
vci.SetLogger(ctx, shimLog)
katautils.SetLogger(ctx, shimLog, shimLog.Logger.Level)
ctx, cancel := context.WithCancel(ctx)
s := &service{
id: id,
pid: uint32(os.Getpid()),
@@ -93,7 +95,7 @@ func New(ctx context.Context, id string, publisher events.Publisher) (cdshim.Shi
containers: make(map[string]*container),
events: make(chan interface{}, chSize),
ec: make(chan exit, bufferSize),
cancel: cancel,
cancel: shutdown,
}
go s.processExits()
@@ -138,7 +140,7 @@ type service struct {
id string
}
func newCommand(ctx context.Context, containerdBinary, id, containerdAddress string) (*sysexec.Cmd, error) {
func newCommand(ctx context.Context, id, containerdBinary, containerdAddress string) (*sysexec.Cmd, error) {
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return nil, err
@@ -176,13 +178,13 @@ func newCommand(ctx context.Context, containerdBinary, id, containerdAddress str
// StartShim willl start a kata shimv2 daemon which will implemented the
// ShimV2 APIs such as create/start/update etc containers.
func (s *service) StartShim(ctx context.Context, id, containerdBinary, containerdAddress string) (string, error) {
func (s *service) StartShim(ctx context.Context, opts cdshim.StartOpts) (_ string, retErr error) {
bundlePath, err := os.Getwd()
if err != nil {
return "", err
}
address, err := getAddress(ctx, bundlePath, id)
address, err := getAddress(ctx, bundlePath, opts.Address, opts.ID)
if err != nil {
return "", err
}
@@ -193,26 +195,41 @@ func (s *service) StartShim(ctx context.Context, id, containerdBinary, container
return address, nil
}
cmd, err := newCommand(ctx, containerdBinary, id, containerdAddress)
cmd, err := newCommand(ctx, opts.ID, opts.ContainerdBinary, opts.Address)
if err != nil {
return "", err
}
address, err = cdshim.SocketAddress(ctx, id)
address, err = cdshim.SocketAddress(ctx, opts.Address, opts.ID)
if err != nil {
return "", err
}
socket, err := cdshim.NewSocket(address)
if err != nil {
return "", err
if !cdshim.SocketEaddrinuse(err) {
return "", err
}
if err := cdshim.RemoveSocket(address); err != nil {
return "", errors.Wrap(err, "remove already used socket")
}
if socket, err = cdshim.NewSocket(address); err != nil {
return "", err
}
}
defer socket.Close()
defer func() {
if retErr != nil {
socket.Close()
_ = cdshim.RemoveSocket(address)
}
}()
f, err := socket.File()
if err != nil {
return "", err
}
defer f.Close()
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
@@ -220,7 +237,7 @@ func (s *service) StartShim(ctx context.Context, id, containerdBinary, container
return "", err
}
defer func() {
if err != nil {
if retErr != nil {
cmd.Process.Kill()
}
}()
@@ -288,20 +305,8 @@ func getTopic(e interface{}) string {
return cdruntime.TaskUnknownTopic
}
func trace(ctx context.Context, name string) (otelTrace.Span, context.Context) {
if ctx == nil {
logrus.WithField("type", "bug").Error("trace called before context set")
ctx = context.Background()
}
tracer := otel.Tracer("kata")
ctx, span := tracer.Start(ctx, name)
span.SetAttributes([]label.KeyValue{label.Key("source").String("runtime"), label.Key("package").String("containerdshim")}...)
return span, ctx
}
func (s *service) Cleanup(ctx context.Context) (_ *taskAPI.DeleteResponse, err error) {
span, spanCtx := trace(s.rootCtx, "Cleanup")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Cleanup", shimTracingTags)
defer span.End()
//Since the binary cleanup will return the DeleteResponse from stdout to
@@ -416,7 +421,7 @@ func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (_ *
// Start a process
func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (_ *taskAPI.StartResponse, err error) {
span, spanCtx := trace(s.rootCtx, "Start")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Start", shimTracingTags)
defer span.End()
start := time.Now()
@@ -467,7 +472,7 @@ func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (_ *taskAP
// Delete the initial process and container
func (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (_ *taskAPI.DeleteResponse, err error) {
span, spanCtx := trace(s.rootCtx, "Delete")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Delete", shimTracingTags)
defer span.End()
start := time.Now()
@@ -519,7 +524,7 @@ func (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (_ *task
// Exec an additional process inside the container
func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (_ *ptypes.Empty, err error) {
span, _ := trace(s.rootCtx, "Exec")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Exec", shimTracingTags)
defer span.End()
start := time.Now()
@@ -557,7 +562,7 @@ func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (_ *p
// ResizePty of a process
func (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (_ *ptypes.Empty, err error) {
span, spanCtx := trace(s.rootCtx, "ResizePty")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "ResizePty", shimTracingTags)
defer span.End()
start := time.Now()
@@ -596,7 +601,7 @@ func (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (_
// State returns runtime state information for a process
func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (_ *taskAPI.StateResponse, err error) {
span, _ := trace(s.rootCtx, "State")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "State", shimTracingTags)
defer span.End()
start := time.Now()
@@ -624,6 +629,7 @@ func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (_ *taskAP
Stderr: c.stderr,
Terminal: c.terminal,
ExitStatus: c.exit,
ExitedAt: c.exitTime,
}, nil
}
@@ -643,12 +649,13 @@ func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (_ *taskAP
Stderr: execs.tty.stderr,
Terminal: execs.tty.terminal,
ExitStatus: uint32(execs.exitCode),
ExitedAt: execs.exitTime,
}, nil
}
// Pause the container
func (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (_ *ptypes.Empty, err error) {
span, spanCtx := trace(s.rootCtx, "Pause")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Pause", shimTracingTags)
defer span.End()
start := time.Now()
@@ -687,7 +694,7 @@ func (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (_ *ptypes
// Resume the container
func (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (_ *ptypes.Empty, err error) {
span, spanCtx := trace(s.rootCtx, "Resume")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Resume", shimTracingTags)
defer span.End()
start := time.Now()
@@ -724,7 +731,7 @@ func (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (_ *ptyp
// Kill a process with the provided signal
func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (_ *ptypes.Empty, err error) {
span, spanCtx := trace(s.rootCtx, "Kill")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Kill", shimTracingTags)
defer span.End()
start := time.Now()
@@ -785,7 +792,7 @@ func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (_ *ptypes.E
// Since for kata, it cannot get the process's pid from VM,
// thus only return the Shim's pid directly.
func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (_ *taskAPI.PidsResponse, err error) {
span, _ := trace(s.rootCtx, "Pids")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Pids", shimTracingTags)
defer span.End()
var processes []*task.ProcessInfo
@@ -808,7 +815,7 @@ func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (_ *taskAPI.
// CloseIO of a process
func (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (_ *ptypes.Empty, err error) {
span, _ := trace(s.rootCtx, "CloseIO")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "CloseIO", shimTracingTags)
defer span.End()
start := time.Now()
@@ -849,7 +856,7 @@ func (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (_ *pt
// Checkpoint the container
func (s *service) Checkpoint(ctx context.Context, r *taskAPI.CheckpointTaskRequest) (_ *ptypes.Empty, err error) {
span, _ := trace(s.rootCtx, "Checkpoint")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Checkpoint", shimTracingTags)
defer span.End()
start := time.Now()
@@ -863,7 +870,7 @@ func (s *service) Checkpoint(ctx context.Context, r *taskAPI.CheckpointTaskReque
// Connect returns shim information such as the shim's pid
func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (_ *taskAPI.ConnectResponse, err error) {
span, _ := trace(s.rootCtx, "Connect")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Connect", shimTracingTags)
defer span.End()
start := time.Now()
@@ -883,7 +890,7 @@ func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (_ *ta
}
func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (_ *ptypes.Empty, err error) {
span, _ := trace(s.rootCtx, "Shutdown")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Shutdown", shimTracingTags)
start := time.Now()
defer func() {
@@ -899,10 +906,15 @@ func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (_ *
s.mu.Unlock()
span.End()
katautils.StopTracing(s.ctx)
katatrace.StopTracing(s.ctx)
s.cancel()
// Since we only send an shutdown qmp command to qemu when do stopSandbox, and
// didn't wait until qemu process's exit, thus we'd better to make sure it had
// exited when shimv2 terminated. Thus here to do the last cleanup of the hypervisor.
syscall.Kill(int(s.hpid), syscall.SIGKILL)
os.Exit(0)
// This will never be called, but this is only there to make sure the
@@ -911,7 +923,7 @@ func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (_ *
}
func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (_ *taskAPI.StatsResponse, err error) {
span, spanCtx := trace(s.rootCtx, "Stats")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Stats", shimTracingTags)
defer span.End()
start := time.Now()
@@ -940,7 +952,7 @@ func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (_ *taskAP
// Update a running container
func (s *service) Update(ctx context.Context, r *taskAPI.UpdateTaskRequest) (_ *ptypes.Empty, err error) {
span, spanCtx := trace(s.rootCtx, "Update")
span, spanCtx := katatrace.Trace(s.rootCtx, shimLog, "Update", shimTracingTags)
defer span.End()
start := time.Now()
@@ -972,7 +984,7 @@ func (s *service) Update(ctx context.Context, r *taskAPI.UpdateTaskRequest) (_ *
// Wait for a process to exit
func (s *service) Wait(ctx context.Context, r *taskAPI.WaitRequest) (_ *taskAPI.WaitResponse, err error) {
span, _ := trace(s.rootCtx, "Wait")
span, _ := katatrace.Trace(s.rootCtx, shimLog, "Wait", shimTracingTags)
defer span.End()
var ret uint32

View File

@@ -16,7 +16,6 @@ import (
"strconv"
"strings"
"github.com/containerd/containerd/namespaces"
cdshim "github.com/containerd/containerd/runtime/v2/shim"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
vcAnnotations "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/annotations"
@@ -129,11 +128,7 @@ func decodeAgentMetrics(body string) []*dto.MetricFamily {
func (s *service) startManagementServer(ctx context.Context, ociSpec *specs.Spec) {
// metrics socket will under sandbox's bundle path
metricsAddress, err := socketAddress(ctx, s.id)
if err != nil {
shimMgtLog.WithError(err).Error("failed to create socket address")
return
}
metricsAddress := SocketAddress(s.id)
listener, err := cdshim.NewSocket(metricsAddress)
if err != nil {
@@ -166,7 +161,7 @@ func (s *service) startManagementServer(ctx context.Context, ociSpec *specs.Spec
svr.Serve(listener)
}
// mountServeDebug provides a debug endpoint
// mountPprofHandle provides a debug endpoint
func (s *service) mountPprofHandle(m *http.ServeMux, ociSpec *specs.Spec) {
// return if not enabled
@@ -188,10 +183,8 @@ func (s *service) mountPprofHandle(m *http.ServeMux, ociSpec *specs.Spec) {
m.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
}
func socketAddress(ctx context.Context, id string) (string, error) {
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return "", err
}
return filepath.Join(string(filepath.Separator), "containerd-shim", ns, id, "shim-monitor.sock"), nil
// SocketAddress returns the address of the abstract domain socket for communicating with the
// shim management endpoint
func SocketAddress(id string) string {
return filepath.Join(string(filepath.Separator), "run", "vc", id, "shim-monitor")
}

View File

@@ -13,8 +13,14 @@ import (
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils"
)
func startContainer(ctx context.Context, s *service, c *container) error {
//start a container
func startContainer(ctx context.Context, s *service, c *container) (retErr error) {
defer func() {
if retErr != nil {
// notify the wait goroutine to continue
c.exitCh <- exitCode255
}
}()
// start a container
if c.cType == "" {
err := fmt.Errorf("Bug, the container %s type is empty", c.id)
return err
@@ -37,8 +43,8 @@ func startContainer(ctx context.Context, s *service, c *container) error {
}
go watchSandbox(ctx, s)
// We don't rely on the context passed to startContainer as it can be cancelled after
// this rpc call.
// We use s.ctx(`ctx` derived from `s.ctx`) to check for cancellation of the
// shim context and the context passed to startContainer for tracing.
go watchOOMEvents(ctx, s)
} else {
_, err := s.sandbox.StartContainer(ctx, c.id)
@@ -74,10 +80,10 @@ func startContainer(ctx context.Context, s *service, c *container) error {
c.ttyio = tty
go ioCopy(c.exitIOch, c.stdinCloser, tty, stdin, stdout, stderr)
} else {
//close the io exit channel, since there is no io for this container,
//otherwise the following wait goroutine will hang on this channel.
// close the io exit channel, since there is no io for this container,
// otherwise the following wait goroutine will hang on this channel.
close(c.exitIOch)
//close the stdin closer channel to notify that it's safe to close process's
// close the stdin closer channel to notify that it's safe to close process's
// io.
close(c.stdinCloser)
}
@@ -87,8 +93,8 @@ func startContainer(ctx context.Context, s *service, c *container) error {
return nil
}
func startExec(ctx context.Context, s *service, containerID, execID string) (*exec, error) {
//start an exec
func startExec(ctx context.Context, s *service, containerID, execID string) (e *exec, retErr error) {
// start an exec
c, err := s.getContainer(containerID)
if err != nil {
return nil, err
@@ -99,6 +105,13 @@ func startExec(ctx context.Context, s *service, containerID, execID string) (*ex
return nil, err
}
defer func() {
if retErr != nil {
// notify the wait goroutine to continue
execs.exitCh <- exitCode255
}
}()
_, proc, err := s.sandbox.EnterContainer(ctx, containerID, *execs.cmds)
if err != nil {
err := fmt.Errorf("cannot enter container %s, with err %s", containerID, err)

View File

@@ -89,3 +89,191 @@ func TestNewTtyIOFifoReopen(t *testing.T) {
checkFifoRead(outr)
checkFifoRead(errr)
}
func TestIoCopy(t *testing.T) {
t.Skip("TestIoCopy is failing randonly, see https://github.com/kata-containers/kata-containers/issues/2042")
assert := assert.New(t)
ctx := context.TODO()
testBytes1 := []byte("Test1")
testBytes2 := []byte("Test2")
testBytes3 := []byte("Test3")
fifoPath, err := ioutil.TempDir(testDir, "fifo-path-")
assert.NoError(err)
dstStdoutPath := filepath.Join(fifoPath, "dststdout")
dstStderrPath := filepath.Join(fifoPath, "dststderr")
// test function: create pipes, and use ioCopy() to copy data from one set to the other
// this function will be called multiple times, testing different combinations of closing order
// in order to verify that closing a pipe doesn't break the copy for the others
ioCopyTest := func(first, second, third string) {
var srcStdinPath string
if third != "" {
srcStdinPath = filepath.Join(fifoPath, "srcstdin")
}
logErrorMsg := func(msg string) string {
return "Error found while using order [" + first + " " + second + " " + third + "] - " + msg
}
exitioch := make(chan struct{})
stdinCloser := make(chan struct{})
createFifo := func(f string) (io.ReadCloser, io.WriteCloser) {
reader, err := fifo.OpenFifo(ctx, f, syscall.O_RDONLY|syscall.O_CREAT|syscall.O_NONBLOCK, 0700)
if err != nil {
t.Fatal(err)
}
writer, err := fifo.OpenFifo(ctx, f, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_NONBLOCK, 0700)
if err != nil {
reader.Close()
t.Fatal(err)
}
return reader, writer
}
// create two sets of stdin, stdout and stderr pipes, to copy data from one to the other
srcOutR, srcOutW := createFifo(filepath.Join(fifoPath, "srcstdout"))
defer srcOutR.Close()
defer srcOutW.Close()
srcErrR, srcErrW := createFifo(filepath.Join(fifoPath, "srcstderr"))
defer srcErrR.Close()
defer srcErrW.Close()
dstInR, dstInW := createFifo(filepath.Join(fifoPath, "dststdin"))
defer dstInR.Close()
defer dstInW.Close()
dstOutR, err := fifo.OpenFifo(ctx, dstStdoutPath, syscall.O_RDONLY|syscall.O_CREAT|syscall.O_NONBLOCK, 0700)
if err != nil {
t.Fatal(err)
}
defer dstOutR.Close()
dstErrR, err := fifo.OpenFifo(ctx, dstStderrPath, syscall.O_RDONLY|syscall.O_CREAT|syscall.O_NONBLOCK, 0700)
if err != nil {
t.Fatal(err)
}
defer dstErrR.Close()
var srcInW io.WriteCloser
if srcStdinPath != "" {
srcInW, err = fifo.OpenFifo(ctx, srcStdinPath, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_NONBLOCK, 0700)
if err != nil {
t.Fatal(err)
}
defer srcInW.Close()
}
tty, err := newTtyIO(ctx, srcStdinPath, dstStdoutPath, dstStderrPath, false)
assert.NoError(err)
defer tty.close()
// start the ioCopy threads : copy from src to dst
go ioCopy(exitioch, stdinCloser, tty, dstInW, srcOutR, srcErrR)
var firstW, secondW, thirdW io.WriteCloser
var firstR, secondR, thirdR io.Reader
getPipes := func(order string) (io.Reader, io.WriteCloser) {
switch order {
case "out":
return dstOutR, srcOutW
case "err":
return dstErrR, srcErrW
case "in":
return dstInR, srcInW
case "":
return nil, nil
}
t.Fatal("internal error")
return nil, nil
}
firstR, firstW = getPipes(first)
secondR, secondW = getPipes(second)
thirdR, thirdW = getPipes(third)
checkFifoWrite := func(w io.Writer, b []byte, name string) {
_, err := w.Write(b)
if name == "in" && (name == third || name == second && first == "out") {
// this is expected: when stdout is closed, ioCopy() will close stdin
// so if "in" is after "out", we will get here
} else {
assert.NoError(err, logErrorMsg("Write error on std"+name))
}
}
checkFifoRead := func(r io.Reader, b []byte, name string) {
var err error
buf := make([]byte, 5)
done := make(chan struct{})
timer := time.NewTimer(2 * time.Second)
go func() {
_, err = r.Read(buf)
close(done)
}()
select {
case <-done:
assert.NoError(err, logErrorMsg("Error reading from std"+name))
assert.Equal(b, buf, logErrorMsg("Value mismatch on std"+name))
case <-timer.C:
//t.Fatal(logErrorMsg("read fifo timeout on std" + name))
if name == "in" && (name == third || name == second && first == "out") {
// this is expected: when stdout is closed, ioCopy() will close stdin
// so if "in" is after "out", we will get here
} else {
assert.Fail(logErrorMsg("read fifo timeout on std" + name))
}
return
}
}
// write to each pipe, and close them immediately
// the ioCopy function should copy the data, then stop the corresponding thread
checkFifoWrite(firstW, testBytes1, first)
firstW.Close()
// need to make sure the Close() above is done before we continue
time.Sleep(time.Second)
checkFifoWrite(secondW, testBytes2, second)
secondW.Close()
if thirdW != nil {
// need to make sure the Close() above is done before we continue
time.Sleep(time.Second)
checkFifoWrite(thirdW, testBytes3, third)
thirdW.Close()
}
// wait for the end of the ioCopy
timer := time.NewTimer(2 * time.Second)
select {
case <-exitioch:
// now check that all data has been copied properly
checkFifoRead(firstR, testBytes1, first)
checkFifoRead(secondR, testBytes2, second)
if thirdR != nil {
checkFifoRead(thirdR, testBytes3, third)
}
case <-timer.C:
t.Fatal(logErrorMsg("timeout waiting for ioCopy()"))
}
}
// try the different combinations
// tests without stdin
ioCopyTest("out", "err", "")
ioCopyTest("err", "out", "")
// tests with stdin
ioCopyTest("out", "err", "in")
ioCopyTest("out", "in", "err")
ioCopyTest("err", "out", "in")
ioCopyTest("err", "in", "out")
ioCopyTest("in", "out", "err")
ioCopyTest("in", "err", "out")
}

View File

@@ -78,7 +78,7 @@ func validBundle(containerID, bundlePath string) (string, error) {
return resolved, nil
}
func getAddress(ctx context.Context, bundlePath, id string) (string, error) {
func getAddress(ctx context.Context, bundlePath, address, id string) (string, error) {
var err error
// Checks the MUST and MUST NOT from OCI runtime specification
@@ -101,7 +101,7 @@ func getAddress(ctx context.Context, bundlePath, id string) (string, error) {
if err != nil {
return "", err
}
address, err := cdshim.SocketAddress(ctx, sandboxID)
address, err := cdshim.SocketAddress(ctx, address, sandboxID)
if err != nil {
return "", err
}

View File

@@ -73,7 +73,7 @@ func init() {
var err error
fmt.Printf("INFO: creating test directory\n")
testDir, err = ioutil.TempDir("", fmt.Sprintf("shimV2-"))
testDir, err = ioutil.TempDir("", "shimV2-")
if err != nil {
panic(fmt.Sprintf("ERROR: failed to create test directory: %v", err))
}

View File

@@ -142,7 +142,7 @@ func watchOOMEvents(ctx context.Context, s *service) {
for {
select {
case <-ctx.Done():
case <-s.ctx.Done():
return
default:
containerID, err := s.sandbox.GetOOMEvent(ctx)

View File

@@ -4,67 +4,54 @@ go 1.14
require (
github.com/BurntSushi/toml v0.3.1
github.com/blang/semver v0.0.0-20190414102917-ba2c2ddd8906
github.com/cilium/ebpf v0.0.0-20200421083123-d05ecd062fb1 // indirect
github.com/containerd/cgroups v0.0.0-20190717030353-c4b9ac5c7601
github.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e
github.com/containerd/containerd v1.2.1-0.20181210191522-f05672357f56
github.com/containerd/continuity v0.0.0-20200413184840-d3ef23f19fbb // indirect
github.com/containerd/cri v1.11.1 // indirect
github.com/blang/semver v3.5.1+incompatible
github.com/blang/semver/v4 v4.0.0
github.com/containerd/cgroups v1.0.1
github.com/containerd/console v1.0.2
github.com/containerd/containerd v1.5.2
github.com/containerd/cri-containerd v1.11.1-0.20190125013620-4dd6735020f5
github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448
github.com/containerd/go-runc v0.0.0-20200220073739-7016d3ce2328 // indirect
github.com/containerd/ttrpc v1.0.0
github.com/containerd/typeurl v1.0.1-0.20190228175220-2a93cfde8c20
github.com/containernetworking/plugins v0.8.2
github.com/containerd/fifo v1.0.0
github.com/containerd/ttrpc v1.0.2
github.com/containerd/typeurl v1.0.2
github.com/containernetworking/plugins v0.9.1
github.com/cri-o/cri-o v1.0.0-rc2.0.20170928185954-3394b3b2d6af
github.com/dlespiau/covertool v0.0.0-20180314162135-b0c4c6d0583a
github.com/docker/distribution v2.7.1+incompatible // indirect
github.com/docker/docker v1.13.1 // indirect
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
github.com/go-ini/ini v1.28.2
github.com/go-openapi/errors v0.18.0
github.com/go-openapi/runtime v0.18.0
github.com/go-openapi/strfmt v0.18.0
github.com/go-openapi/swag v0.18.0
github.com/go-openapi/swag v0.19.5
github.com/go-openapi/validate v0.18.0
github.com/gogo/googleapis v1.4.0 // indirect
github.com/gogo/protobuf v1.3.1
github.com/gogo/protobuf v1.3.2
github.com/hashicorp/go-multierror v1.0.0
github.com/kata-containers/govmm v0.0.0-20210428163604-f0e9a35308ee
github.com/intel-go/cpuid v0.0.0-20210602155658-5747e5cec0d9
github.com/kata-containers/govmm v0.0.0-20210622075516-263136e69ac8
github.com/mdlayher/vsock v0.0.0-20191108225356-d9c65923cb8f
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/opencontainers/runc v1.0.0-rc9.0.20200102164712-2b52db75279c
github.com/opencontainers/runtime-spec v1.0.2-0.20190408193819-a1b50f621a48
github.com/opencontainers/selinux v1.4.0
github.com/opencontainers/runc v1.0.0-rc93
github.com/opencontainers/runtime-spec v1.0.3-0.20200929063507-e6143ca7d51d
github.com/opencontainers/selinux v1.8.0
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.7.1
github.com/prometheus/client_model v0.2.0
github.com/prometheus/common v0.10.0
github.com/prometheus/procfs v0.1.3
github.com/prometheus/procfs v0.6.0
github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8
github.com/seccomp/libseccomp-golang v0.9.1 // indirect
github.com/sirupsen/logrus v1.4.2
github.com/sirupsen/logrus v1.7.0
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/stretchr/testify v1.6.1
github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2 // indirect
github.com/urfave/cli v1.20.1-0.20170926034118-ac249472b7de
github.com/vishvananda/netlink v1.0.1-0.20190604022042-c8c507c80ea2
github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc
github.com/urfave/cli v1.22.2
github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852
github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae
go.opentelemetry.io/otel v0.15.0
go.opentelemetry.io/otel/exporters/trace/jaeger v0.15.0
go.opentelemetry.io/otel/sdk v0.15.0
golang.org/x/net v0.0.0-20200822124328-c89045814202
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43
golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f
google.golang.org/grpc v1.31.1
gotest.tools v2.2.0+incompatible // indirect
k8s.io/apimachinery v0.18.2
golang.org/x/sys v0.0.0-20210324051608-47abb6519492
google.golang.org/grpc v1.33.2
k8s.io/apimachinery v0.20.6
)
replace (
github.com/uber-go/atomic => go.uber.org/atomic v1.5.1
google.golang.org/genproto => google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8
google.golang.org/grpc => google.golang.org/grpc v1.19.0
gotest.tools/v3 => gotest.tools v2.2.0+incompatible
)

File diff suppressed because it is too large Load Diff

18
src/runtime/hack/tree_status.sh Executable file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env bash
#
# Copyright 2021 Red Hat Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
set -e
STATUS=$(git status --porcelain)
if [[ -z $STATUS ]]; then
echo "tree is clean"
else
echo "tree is dirty, please commit all changes"
echo ""
echo "$STATUS"
git diff
exit 1
fi

View File

@@ -176,7 +176,7 @@ func (km *KataMonitor) aggregateSandboxMetrics(encoder expfmt.Encoder) error {
for sandboxID, namespace := range sandboxes {
wg.Add(1)
go func(sandboxID, namespace string, results chan<- []*dto.MetricFamily) {
sandboxMetrics, err := km.getSandboxMetrics(sandboxID, namespace)
sandboxMetrics, err := getParsedMetrics(sandboxID)
if err != nil {
monitorLog.WithError(err).WithField("sandbox_id", sandboxID).Errorf("failed to get metrics for sandbox")
}
@@ -229,13 +229,12 @@ func (km *KataMonitor) aggregateSandboxMetrics(encoder expfmt.Encoder) error {
return err
}
}
return nil
}
// getSandboxMetrics will get sandbox's metrics from shim
func (km *KataMonitor) getSandboxMetrics(sandboxID, namespace string) ([]*dto.MetricFamily, error) {
body, err := km.doGet(sandboxID, namespace, defaultTimeout, "metrics")
func getParsedMetrics(sandboxID string) ([]*dto.MetricFamily, error) {
body, err := doGet(sandboxID, defaultTimeout, "metrics")
if err != nil {
return nil, err
}
@@ -243,6 +242,16 @@ func (km *KataMonitor) getSandboxMetrics(sandboxID, namespace string) ([]*dto.Me
return parsePrometheusMetrics(sandboxID, body)
}
// GetSandboxMetrics will get sandbox's metrics from shim
func GetSandboxMetrics(sandboxID string) (string, error) {
body, err := doGet(sandboxID, defaultTimeout, "metrics")
if err != nil {
return "", err
}
return string(body), nil
}
// parsePrometheusMetrics will decode metrics from Prometheus text format
// and return array of *dto.MetricFamily with an ASC order
func parsePrometheusMetrics(sandboxID string, body []byte) ([]*dto.MetricFamily, error) {

View File

@@ -87,13 +87,8 @@ func (km *KataMonitor) GetAgentURL(w http.ResponseWriter, r *http.Request) {
commonServeError(w, http.StatusBadRequest, err)
return
}
namespace, err := km.getSandboxNamespace(sandboxID)
if err != nil {
commonServeError(w, http.StatusBadRequest, err)
return
}
data, err := km.doGet(sandboxID, namespace, defaultTimeout, "agent-url")
data, err := doGet(sandboxID, defaultTimeout, "agent-url")
if err != nil {
commonServeError(w, http.StatusBadRequest, err)
return

View File

@@ -11,6 +11,8 @@ import (
"net"
"net/http"
"time"
shim "github.com/kata-containers/kata-containers/src/runtime/containerd-shim-v2"
)
const (
@@ -33,16 +35,13 @@ func getSandboxIDFromReq(r *http.Request) (string, error) {
return "", fmt.Errorf("sandbox not found in %+v", r.URL.Query())
}
func (km *KataMonitor) buildShimClient(sandboxID, namespace string, timeout time.Duration) (*http.Client, error) {
socketAddr, err := km.getMonitorAddress(sandboxID, namespace)
if err != nil {
return nil, err
}
return BuildUnixSocketClient(socketAddr, timeout)
// BuildShimClient builds and returns an http client for communicating with the provided sandbox
func BuildShimClient(sandboxID string, timeout time.Duration) (*http.Client, error) {
return buildUnixSocketClient(shim.SocketAddress(sandboxID), timeout)
}
// BuildUnixSocketClient build http client for Unix socket
func BuildUnixSocketClient(socketAddr string, timeout time.Duration) (*http.Client, error) {
// buildUnixSocketClient build http client for Unix socket
func buildUnixSocketClient(socketAddr string, timeout time.Duration) (*http.Client, error) {
transport := &http.Transport{
DisableKeepAlives: true,
Dial: func(proto, addr string) (conn net.Conn, err error) {
@@ -61,8 +60,8 @@ func BuildUnixSocketClient(socketAddr string, timeout time.Duration) (*http.Clie
return client, nil
}
func (km *KataMonitor) doGet(sandboxID, namespace string, timeoutInSeconds time.Duration, urlPath string) ([]byte, error) {
client, err := km.buildShimClient(sandboxID, namespace, timeoutInSeconds)
func doGet(sandboxID string, timeoutInSeconds time.Duration, urlPath string) ([]byte, error) {
client, err := BuildShimClient(sandboxID, timeoutInSeconds)
if err != nil {
return nil, err
}

View File

@@ -16,7 +16,7 @@ import (
"strings"
"testing"
"github.com/blang/semver"
semver "github.com/blang/semver/v4"
"github.com/stretchr/testify/assert"
)

View File

@@ -20,13 +20,13 @@ var defaultCPUFeatures = ""
var systemdUnitName = "kata-containers.target"
const defaultKernelParams = ""
const defaultMachineType = "pc"
const defaultMachineType = "q35"
const defaultVCPUCount uint32 = 1
const defaultMaxVCPUCount uint32 = 0
const defaultMemSize uint32 = 2048 // MiB
const defaultMemSlots uint32 = 10
const defaultMemOffset uint32 = 0 // MiB
const defaultMemOffset uint64 = 0 // MiB
const defaultVirtioMem bool = false
const defaultBridgesCount uint32 = 1
const defaultInterNetworkingModel = "tcfilter"
@@ -54,6 +54,7 @@ const defaultDisableImageNvdimm = false
const defaultVhostUserStorePath string = "/var/run/kata-containers/vhost-user/"
const defaultRxRateLimiterMaxRate = uint64(0)
const defaultTxRateLimiterMaxRate = uint64(0)
const defaultConfidentialGuest = false
var defaultSGXEPCSize = int64(0)

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2018 Intel Corporation
// Copyright (c) 2018-2021 Intel Corporation
// Copyright (c) 2018 HyperHQ Inc.
//
// SPDX-License-Identifier: Apache-2.0
@@ -16,6 +16,7 @@ import (
"github.com/BurntSushi/toml"
govmmQemu "github.com/kata-containers/govmm/qemu"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils/katatrace"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/device/config"
exp "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/experimental"
@@ -28,11 +29,6 @@ const (
defaultHypervisor = vc.QemuHypervisor
)
var (
// if true, enable opentracing support.
tracing = false
)
// The TOML configuration file contains a number of sections (or
// tables). The names of these tables are in dotted ("nested table")
// form:
@@ -61,6 +57,12 @@ type tomlConfig struct {
Runtime runtime
Factory factory
Netmon netmon
Image image
}
type image struct {
ServiceOffload bool `toml:"service_offload"`
Provision string `toml:"provision"`
}
type factory struct {
@@ -108,7 +110,7 @@ type hypervisor struct {
DefaultMaxVCPUs uint32 `toml:"default_maxvcpus"`
MemorySize uint32 `toml:"default_memory"`
MemSlots uint32 `toml:"memory_slots"`
MemOffset uint32 `toml:"memory_offset"`
MemOffset uint64 `toml:"memory_offset"`
DefaultBridges uint32 `toml:"default_bridges"`
Msize9p uint32 `toml:"msize_9p"`
PCIeRootPort uint32 `toml:"pcie_root_port"`
@@ -130,6 +132,7 @@ type hypervisor struct {
HotplugVFIOOnRootBus bool `toml:"hotplug_vfio_on_root_bus"`
DisableVhostNet bool `toml:"disable_vhost_net"`
GuestMemoryDumpPaging bool `toml:"guest_memory_dump_paging"`
ConfidentialGuest bool `toml:"confidential_guest"`
}
type runtime struct {
@@ -154,6 +157,7 @@ type agent struct {
Debug bool `toml:"enable_debug"`
Tracing bool `toml:"enable_tracing"`
DebugConsoleEnabled bool `toml:"debug_console_enabled"`
DialTimeout uint32 `toml:"dial_timeout"`
}
type netmon struct {
@@ -351,7 +355,7 @@ func (h hypervisor) defaultMemSlots() uint32 {
return slots
}
func (h hypervisor) defaultMemOffset() uint32 {
func (h hypervisor) defaultMemOffset() uint64 {
offset := h.MemOffset
if offset == 0 {
offset = defaultMemOffset
@@ -471,6 +475,10 @@ func (a agent) debugConsoleEnabled() bool {
return a.DebugConsoleEnabled
}
func (a agent) dialTimout() uint32 {
return a.DialTimeout
}
func (a agent) debug() bool {
return a.Debug
}
@@ -702,6 +710,7 @@ func newQemuHypervisorConfig(h hypervisor) (vc.HypervisorConfig, error) {
EnableAnnotations: h.EnableAnnotations,
GuestMemoryDumpPath: h.GuestMemoryDumpPath,
GuestMemoryDumpPaging: h.GuestMemoryDumpPaging,
ConfidentialGuest: h.ConfidentialGuest,
}, nil
}
@@ -920,6 +929,7 @@ func updateRuntimeConfigAgent(configPath string, tomlConf tomlConfig, config *oc
TraceType: agent.traceType(),
KernelModules: agent.kernelModules(),
EnableDebugConsole: agent.debugConsoleEnabled(),
DialTimeout: agent.dialTimout(),
}
}
@@ -1055,6 +1065,7 @@ func GetDefaultHypervisorConfig() vc.HypervisorConfig {
RxRateLimiterMaxRate: defaultRxRateLimiterMaxRate,
TxRateLimiterMaxRate: defaultTxRateLimiterMaxRate,
SGXEPCSize: defaultSGXEPCSize,
ConfidentialGuest: defaultConfidentialGuest,
}
}
@@ -1101,7 +1112,7 @@ func LoadConfiguration(configPath string, ignoreLogging bool) (resolvedConfigPat
}
config.Trace = tomlConf.Runtime.Tracing
tracing = config.Trace
katatrace.SetTracing(config.Trace)
if tomlConf.Runtime.InterNetworkModel != "" {
err = config.InterNetworkModel.SetModel(tomlConf.Runtime.InterNetworkModel)

View File

@@ -13,13 +13,20 @@ import (
"strconv"
"strings"
"github.com/kata-containers/kata-containers/src/runtime/pkg/katautils/katatrace"
vc "github.com/kata-containers/kata-containers/src/runtime/virtcontainers"
vf "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/factory"
"github.com/kata-containers/kata-containers/src/runtime/virtcontainers/pkg/oci"
specs "github.com/opencontainers/runtime-spec/specs-go"
"go.opentelemetry.io/otel/label"
)
// createTracingTags defines tags for the trace span
var createTracingTags = map[string]string{
"source": "runtime",
"package": "katautils",
"subsystem": "sandbox",
}
// GetKernelParamsFunc use a variable to allow tests to modify its value
var GetKernelParamsFunc = getKernelParams
@@ -104,7 +111,8 @@ func SetEphemeralStorageType(ociSpec specs.Spec) specs.Spec {
// CreateSandbox create a sandbox container
func CreateSandbox(ctx context.Context, vci vc.VC, ociSpec specs.Spec, runtimeConfig oci.RuntimeConfig, rootFs vc.RootFs,
containerID, bundlePath, console string, disableOutput, systemdCgroup bool) (_ vc.VCSandbox, _ vc.Process, err error) {
span, ctx := Trace(ctx, "createSandbox")
span, ctx := katatrace.Trace(ctx, nil, "CreateSandbox", createTracingTags)
katatrace.AddTag(span, "container_id", containerID)
defer span.End()
sandboxConfig, err := oci.SandboxConfig(ociSpec, runtimeConfig, bundlePath, containerID, console, disableOutput, systemdCgroup)
@@ -159,7 +167,7 @@ func CreateSandbox(ctx context.Context, vci vc.VC, ociSpec specs.Spec, runtimeCo
sid := sandbox.ID()
kataUtilsLogger = kataUtilsLogger.WithField("sandbox", sid)
span.SetAttributes(label.Key("sandbox").String(sid))
katatrace.AddTag(span, "sandbox_id", sid)
containers := sandbox.GetAllContainers()
if len(containers) != 1 {
@@ -202,7 +210,8 @@ func checkForFIPS(sandboxConfig *vc.SandboxConfig) error {
func CreateContainer(ctx context.Context, sandbox vc.VCSandbox, ociSpec specs.Spec, rootFs vc.RootFs, containerID, bundlePath, console string, disableOutput bool) (vc.Process, error) {
var c vc.VCContainer
span, ctx := Trace(ctx, "createContainer")
span, ctx := katatrace.Trace(ctx, nil, "CreateContainer", createTracingTags)
katatrace.AddTag(span, "container_id", containerID)
defer span.End()
ociSpec = SetEphemeralStorageType(ociSpec)
@@ -228,7 +237,7 @@ func CreateContainer(ctx context.Context, sandbox vc.VCSandbox, ociSpec specs.Sp
return vc.Process{}, err
}
span.SetAttributes(label.Key("sandbox").String(sandboxID))
katatrace.AddTag(span, "sandbox_id", sandboxID)
c, err = sandbox.CreateContainer(ctx, contConfig)
if err != nil {

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