Compare commits

..

539 Commits

Author SHA1 Message Date
Fabiano Fidêncio
d2e92c9ec9 Merge pull request #6892 from fidencio/3.2.0-alpha1-branch-bump
# Kata Containers 3.2.0-alpha1
2023-05-19 12:31:33 +02:00
Fabiano Fidêncio
f527f614c1 release: Kata Containers 3.2.0-alpha1
- runtime: Use static_sandbox_resource_mgmt=true for TEEs
- update tokio dependency
- resource-control: fix setting CPU affinities on Linux
- runtime: use enable_vcpus_pinning from toml
- gha: k8s: Make the tests more reliable
- gha: Enable SEV-SNP tests on main
- gha: tdx: Use the k3s overlay for kata-cleanup
- runtime: Port sev package to main
- gpu: Rename the last bits from `gpu` to `nvidia-gpu`
- deploy: fix shell script error
- ppc64le: switch virtiofsd from C to rust version
- osbuilder: Fix indentation in rootfs.sh
- virtcontainers/qemu_test.go: Improve coverage
- agent: Add context to errors that may occur when AgentConfig file is …
- virtcontainers/pkg/compatoci/: Improved coverage for  for Kata 2.0
- kata-manager: Fix '-o' syntax and logic error
- kata-ctl:  Add the option to install kata-ctl to a user specified directory
- runtime-rs: fix building instructions to use correct required Rust ve…
- Dragonball: use LinuxBootConfigurator::write_bootparams
- kata-deploy: Add http_proxy as part of the docker build
- kata-deploy: Do not ship the kata tarball
- kata-deploy: Build improvements
- deploy: Fix arch in image tag
- Revert "kata-deploy: Use readinessProbe to ensure everything is ready"
- virtcontainers: Improved test coverage for fc.go from 4.6% to 18.5%
- main | release: Fix multi-arch publishing is not supported
- cache: More fixes to nvidia-gpu kernels caching
- runtime: remove overriding ARCH value by default for ppc64le
- gha: Fix Body Line Length action flagging empty body commit messages
- gha: Fix snap creation workflow
- cache: Fix nvidia-gpu version
- cache: Update the KERNEL_FLAVOUR list to include nvidia-gpu
- packaging: Add SEV-SNP artifacts to main
- docs: Mark snap installation method as unmaintained
- packaging: Add sev artifacts to main
- kata-ctl: add generic kvm check & unit test
- Log-parser-rs
- warning_fix: fix warnings when build with cargo-1.68.0
- cross-compile: Include documentation and configuration for cross-compile
- runtime: Fix virtiofs fd leak
- gpu: cold plug VFIO devices
- pkg/signals: Improved test coverage 60% to 100%
- virtcontainers/persist: Improved test coverage 65% to 87.5%
- virtcontainers/clh_test.go: improve unit test coverage
- virtcontainers/factory: Improved test coverage
- gha: Also run k8s tests on qemu-snp
- gha: sev: fix for kata-deploy error
- gha: Also run k8s tests on qemu-sev
- Implement the "kata-ctl env" command
- runtime-rs: support keep_abnormal in toml config
- gpu: Build and Ship an GPU enabled Kernel
- kata-ctl: checks for kvm, kvm_intel modules loaded
- osbuilder: Fix D-Bus enabling in the dracut case
- snap: fix docker start fail issue
- kata-manager: Fix containerd download
- agent: Fix ut issue caused by fd double closed
- Bump ttrpc to 0.7.2 and protobuf to 3.2.0
- gpu: Add GPU enabled confguration and runtime
- gpu: Do not pass-through PCI (Host) Bridges
- cache-components: Fix caching of TDVF and QEMU for TDX
- gha: tdx: Ensure kata-deploy is removed after the tests run
- versions: Upgrade to Cloud Hypervisor v31.0
- osbuilder: Enable dbus in the dracut case
- runtime: Don't create socket file in /run/kata
- nydus_rootfs/prefetch_files: add prefetch_files for RAFS
- runtime-rs/virtio-fs: add support extra handler for cache mode.
- runtime-rs: enable nerdctl to setup cni plugin
- tdx: Add artefacts from the latest TDX tools release into main
- runtime: support non-root for clh
- gha: ci-on-push: Run k8s tests with dragonball
- rustjail: Use CPUWeight with systemd and CgroupsV2
- gha: k8s-on-aks: {create,delete} AKS must be a coded-in step
- docs: update the rust version from version.yaml
- gha: k8s-on-aks: Set {create,delete}_aks as steps
- gha: k8s-on-aks: Fix cluster name
- gha: Also run k8s tests on AKS with dragonball
- gha: Only push images to registry after merging a PR
- gha: aks: Use D4s_v5 instance
- tools: Avoid building the kernel twice
- rustjail: Fix panic when cgroup manager fails
- runtime: add filter metrics with specific names
- gha: Use ghcr.io for the k8s CI
- GHA |Switch "kubernetes tests" from jenkins to GitHub actions
- docs: Update CNM url in networking document
- kata-ctl: add function to get platform protection.

f6e1b1152 agent: update tokio dependency
4cb83dc21 kata-ctl: update tokio dependency
df615ff25 runk: update tokio dependency
ca6892ddb runtime-rs: update tokio dependency
ca1531fe9 runtime: Use static_sandbox_resource_mgmt=true for TEEs
fa832f470 gha: k8s: Make the tests more reliable
cbb9fe8b8 config: Use standard OVMF with SEV
724437efb kata-deploy: add kata-qemu-sev runtimeclass
521dad2a4 Tests: skip CPU constraints test on SEV and SNP
72308ddb0 gha: ci-on-push: Don't skip tests for SEV
da0f92cef gha: ci-on-push: Don't skip tests for SEV-SNP
12f43bea0 gha: tdx: Use the k3s overlay for kata-cleanup
1a3f8fc1a deploy: fix shell script error
87cb98c01 osbuilder: Fix indentation in rootfs.sh
c5a59caca ppc64le: switch virtiofsd from C to rust version
bfdf0144a versions: Bump virtiofsd to 1.6.1
dd7562522 runtime: pkg/sev: Add kbs utility package for SEV pre-attestation
05de7b260 runtime: Add sev package
3a9d3c72a gpu: Rename the last bits from `gpu` to `nvidia-gpu`
4cde844f7 local-build: Fix kernel-nvidia-gpu target name
593840e07 kata-ctl: Allow INSTALL_PATH= to be specified
bdb75fb21 runtime: use enable_vcpus_pinning from toml
20cb87508 virtcontainers/qemu_test.go: Improve test coverage
b9a1db260 kata-deploy: Add http_proxy as part of the docker build
3e85bf5b1 resource-control: fix setting CPU affinities on Linux
5f3f844a1 runtime-rs: fix building instructions with respect to required Rust version
777c3dc8d kata-deploy: Do not ship the kata tarball
50cc9c582 tests: Improve coverage for virtcontainers/pkg/compatoci/ for Kata 2.0
136e2415d static-build: Download firecracker instead of building it
3bf767cfc static-build: Adjust ARCH for nydus
ac88d34e0 static-build: Use relased binary for CLH (aarch64)
73913c8eb kata-manager: Fix '-o' syntax and logic error
2856d3f23 deploy: Fix arch in image tag
e8f81ee93 Revert "kata-deploy: Use readinessProbe to ensure everything is ready"
cfe63527c release: Fix multi-arch publishing is not supported
197c33651 Dragonball: use LinuxBootConfigurator::write_bootparams to writes the boot parameters into guest memory.
4d17ea4a0 cache: Fix nvidia-snp caching version
a133fadbf cache: Fix nvidia-gpu-tdx-experimental cache URL
b9990c201 cache: Fix nvidia-gpu version
c9bf7808b cache: Update the KERNEL_FLAVOUR list to include nvidia-gpu
3665b4204 gpu: Rename `gpu` targets to `nvidia-gpu`
2c90cac75 local-build: fixup alphabetization
4da6eb588 kata-deploy: Add qemu-snp shim
14dd05375 kata-deploy: add kata-qemu-snp runtimeclass
0bb37bff7 config: Add SNP configuration
af7f2519b versions: update SEV kernel description
dbcc3b5cc local-build: fix default values for OVMF build
b8bbe6325 gha: build OVMF for tests and release
cf0ca265f local-build: Add x86_64 OVMF target
db095ddeb cache: add SNP flavor to comments
f4ee00576 gha: Build and ship QEMU for SNP
7a58a91fa docs: update SNP guide
879333bfc versions: update SNP QEMU version
38ce4a32a local-build: add support to build QEMU for SEV-SNP
5f8008b69 kata-ctl: add unit test for kvm check
a085a6d7b kata-ctl: add generic kvm check
772d4db26 gha: Build and ship SEV initrd
45fa36692 gha: Build and ship SEV OVMF
4770d3064 gha: Build and ship SEV kernel.
fb9c1fc36 runtime: Add qemu-sev config
813e4c576 runtimeClasses: add sev runtime class
af18806a8 static-build: Add caching support to sev ovmf
76ae7a3ab packaging: adding caching capability for kernel
12c5ef902 packaging: add support to build OVMF for SEV
b87820ee8 packaging: add support to build initrd for sev
e1f3b871c docs: Mark snap installation method as unmaintained
022a33de9 agent: Add context to errors when AgentConfig file is missing
b0e6a094b packaging: Add sev kernel build capability
a4c0303d8 virtcontainers: Fixed static checks for improved test coverage for fc.go
8495f830b cross-compile: Include documentation and configuration for cross-compile
13d7f39c7 gpu: Check for VFIO port assignments
6594a9329 tools: made log-parser-rs
03a8cd69c virtcontainers: Improved test coverage for fc.go from 4.6% to 18.5%
9e2b7ff17 gha: sev: fix for kata-deploy error
5c9246db1 gha: Also run k8s tests on qemu-snp
c57a44436 gha: Add the ability to test qemu-snp
406419289 env: Utilize arch specific functionality to get cpu details
fb40c71a2 env: Check for root privileges
1016bc17b config: Add api to fetch config from default config path
b908a780a kata-env: Pass cmd option for file path
b1920198b config: Workaround the way agent and hypervisor configs are fetched
f2b2621de kata-env: Implement the kata-env command.
c849bdb0a gha: Also run k8s tests on qemu-sev
6bf1fc605 virtcontainers/factory: Improved test coverage
0d49ceee0 gha: Fix snap creation workflow warnings
138ada049 gpu: Cold Plug VFIO toml setting
defb64334 runtime: remove overriding ARCH value by default for ppc64le
f7ad75cb1 gpu: Cold-plug extend the api.md
0fec2e698 gpu: Add cold-plug test
f2ebdd81c utils: Get rid of spurious print statement left behind.
9a94f1f14 make: Export VERSION and COMMIT
2f81f48da config: Add file under /opt as another location to look for the config
07f7d17db config: Make the pipe_size field optional
68f635773 config: Make function to get the default conf file public
7565b3356 kata-ctl: Implement Display trait for GuestProtection enum
94a00f934 utils: Make certain constants in utils.rs public
572b338b3 gitignore: Ignore .swp and .swo editor backup files
376884b8a cargo: Update version of clap to 4.1.13
17daeb9dd warning_fix: fix warnings when build with cargo-1.68.0
521519d74 gha: Add the ability to test qemu-sev
205909fbe runtime: Fix virtiofs fd leak
5226f15c8 gha: Fix Body Line Length action flagging empty body commit messages
0f45b0faa virtcontainers/clh_test.go: improve unit test coverage
dded731db gpu: Add OVMF setting for MMIO aperture
2a830177c gpu: Add fwcfg helper function
131f056a1 gpu: Extract VFIO Functions to drivers
c8cf7ed3b gpu: Add ColdPlug of VFIO devices with devManager
e2b5e7f73 gpu: Add Rawdevices to hypervisor
6107c32d7 gpu: Assign default value to cold-plug
377ebc2ad gpu: Add configuration option for cold-plug VFIO
c18ceae10 gpu: Add new struct PCIePort
9c38204f1 virtcontainers/persist: Improved test coverage 65% to 87.5%
1c1ee8057 pkg/signals: Improved test coverage 60% to 100%
cc8ea3232 runtime-rs: support keep_abnormal in toml config
96e8470db kata-manager: Fix containerd download
432d40744 kata-ctl: checks for kvm, kvm_intel modules loaded
b1730e4a6 gpu: Add new kernel build option to usage()
3e7b90226 osbuilder: Fix D-Bus enabling in the dracut case
53c749a9d agent: Fix ut issue caused by fd double closed
2e3f19af9 agent: fix clippy warnings caused by protobuf3
4849c56fa agent: Fix unit test issue cuased by protobuf upgrade
0a582f781 trace-forwarder: remove unused crate protobuf
73253850e kata-ctl: remove unused crate ttrpc
76d2e3054 agent-ctl: Bump ttrpc from 0.6.0 to 0.7.1
eb3d20dcc protocols: Add ut for Serde
59568c79d protocols: add support for Serde
a6b4d92c8 runtime-rs: Bump ttrpc from 0.6.0 to 0.7.1
ac7c63bc6 gpu: Add containerd shim for qemu-gpu
a0cc8a75f gpu: Add a kube runtime class
a81fff706 gpu: Adding a GPU enabled configuration
8af6fc77c agent: Bump ttrpc from 0.6.0 to 0.7.1
009b42dbf protocols: Fix unit test
392732e21 protocols: Bump ttrpc from 0.6.0  to 0.7.1
f4f958d53 gpu: Do not pass-through PCI (Host) Bridges
825e76948 gpu: Add GPU support to default kernel without any TEE
e4ee07f7d gpu: Add GPU TDX experimental kernel
a1272bcf1 gha: tdx: Fix typo overlay -> overlays
3fa0890e5 cache-components: Fix TDVF caching
80e3a2d40 cache-components: Fix TDX QEMU caching
87ea43cd4 gpu: Add configuration fragment
aca6ff728 gpu: Build and Ship an GPU enabled Kernel
dc662333d runtime: Increase the dial_timeout
eb1762e81 osbuilder: Enable dbus in the dracut case
f478b9115 clh: tdx: Update timeouts for confidential guest
3b76abb36 kata-deploy: Ensure node is ready after CRI Engine restart
5ec9ae0f0 kata-deploy: Use readinessProbe to ensure everything is ready
ea386700f kata-deploy: Update podOverhead for TDX
e31efc861 gha: tdx: Use the k3s overlay
542bb0f3f gha: tdx: Set KUBECONFIG env at the job level
d7fdf19e9 gha: tdx: Delete kata-deploy after the tests finish
da35241a9 tests: k8s: Skip k8s-cpu-ns when testing TDX
db2cac34d runtime: Don't create socket file in /run/kata
6d315719f snap: fix docker start fail issue
e4b3b0887 gpu: Add proper CONFIG_LOCALVERSION depending on TEE
69ba2098f runtime-rs: remove network entities and netns
b31f103d1 runtime-rs: enable nerdctl cni plugin
69d7a959c gha: ci-on-push: Run tests on TDX
5a0727ecb kata-deploy: Ship kata-qemu-tdx runtimeClass
98682805b config: Add configuration for QEMU TDX
3e1580019 govmm: Directly pass the firmware using -bios with TDX
3c5ffb0c8 govmm: Set "sept-ve-disable=on"
ed145365e runtime/qemu: Drop "kvm-type=tdx"
25b3cdd38 virtcontainers: Drop check for the `tdx` CPU flag
01bdacb4e virtcontainers: Also check /sys/firmwares/tdx for TDX
9feec533c cache: Add ability to cache OVMF
ce8d98251 gha: Build and ship the OVMF for TDX
39c3fab7b local-build: Add support to build OVMF for TDX
054174d3e versions: Bump OVMF for TDX
800fb49da packaging: Add get_ovmf_image_name() helper
fbf03d7ac cache: Document kernel-tdx-experimental
5d79e9696 cache: Add a space to ease the reading of the kernel flavours
6e4726e45 cache: Fix typos
fc22ed0a8 gha: Build and ship the Kernel for TDX
502844ced local-build: Add support to build Kernel for TDX
b2585eecf local-build: Avoid code duplication building the kernel
f33345c31 versions: Update Kernel TDX version
20ab2c242 versions: Move Kernel TDX to its own experimental entry
3d9ce3982 cache: Allow specifying the QEMU_FLAVOUR
33dc6c65a gha: Build and ship QEMU for TDX
eceaae30a local-build: Add support to build QEMU for TDX
f7b7c187e static-build: Improve qemu-experimental build script
3018c9ad5 versions: Update QEMU TDX version
800ee5cd8 versions: Move QEMU TDX to its own experimental entry
1315bb45f local-build: Add dragonball kernel to the `all` target
73e108136 local-build: Rename non vanilla kernel build functions
1d851b4be local-build: Cosmetic changes in build targets
49ce685eb gha: k8s-on-aks: Always delete the AKS cluster
e2a770df5 gha: ci-on-push: Run k8s tests with dragonball
d1f550bd1 docs: update the rust version from versions.yaml
f3595e48b nydus_rootfs/prefetch_files: add prefetch_files for RAFS
3bfaafbf4 fix: oci hook
c1fbaae8d rustjail: Use CPUWeight with systemd and CgroupsV2
375187e04 versions: Upgrade to Cloud Hypervisor v31.0
79f3047f0 gha: k8s-on-aks: {create,delete} AKS must be a coded-in step
2f35b4d4e gha: ci-on-push: Only run on `main` branch
e7bd2545e Revert "gha: ci-on-push: Depend on Commit Message Check"
0d96d4963 Revert "gha: ci-on-push: Adjust to using workflow_run"
c7ee45f7e Revert "gha: ci-on-push: Adapt chained jobs to workflow_run"
5d4d72064 Revert "gha: k8s-on-aks: Fix cluster name"
13d857a56 gha: k8s-on-aks: Set {create,delete}_aks as steps
dc6569dbb runtime-rs/virtio-fs: add support extra handler for cache mode.
85cc5bb53 gha: k8s-on-aks: Fix cluster name
1688e4f3f gha: aks: Use D4s_v5 instance
108d80a86 gha: Add the ability to also test Dragonball
2550d4462 gha: build-kata-static-tarball: Only push to registry after merge
e81b8b8ee local-build: build-and-upload-payload is not quay.io specific
13929fc61 gha: publish-kata-deploy-payload: Improve registry login
41026f003 gha: payload-after-push: Pass registry / repo as inputs
7855b4306 gha: ci-on-push: Adapt chained jobs to workflow_run
3a760a157 gha: ci-on-push: Adjust to using workflow_run
a159ffdba gha: ci-on-push: Depend on Commit Message Check
8086c75f6 gha: Also run k8s tests on AKS with dragonball
fe86c08a6 tools: Avoid building the kernel twice
3215860a4 gha: Set ci-on-push to run on `pull_request_target`
d17dfe4cd gha: Use ghcr.io for the k8s CI
b661e0cf3 rustjail: Add anyhow context for D-Bus connections
60c62c3b6 gha: Remove kata-deploy-test.yaml
43894e945 gha: Remove kata-deploy-push.yaml
cab9ca043 gha: Add a CI pipeline for Kata Containers
53b526b6b gha: k8s: Add snippet to run k8s tests on aks clusters
c444c24bc gha: aks: Add snippets to create / delete aks clusters
11e0099fb tests: Move k8s tests to this repo
73be4bd3f gha: Update actions for release.yaml
d38d7fbf1 gha: Remove code duplication from release.yaml
56331bd7b gha: Split payload-after-push-*.yaml
a552a1953 docs: Update CNM url in networking document
7796e6ccc rustjail: Fix minor grammatical error in function name
41fdda1d8 rustjail: Do  not unwrap potential error with cgroup manager
a914283ce kata-ctl: add function to get platform protection.
0f7351556 runtime: add filter metrics with specific names
cbe6ad903 runtime: support non-root for clh
d3bb25418 utils: Add function to check vhost-vsock

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-19 09:26:36 +02:00
Fabiano Fidêncio
0364620844 Merge pull request #6819 from fidencio/topic/use-static-sandbox-resource-mgmt-for-TEEs
runtime: Use static_sandbox_resource_mgmt=true for TEEs
2023-05-18 22:38:31 +02:00
Fabiano Fidêncio
2ea8acaaa5 Merge pull request #6882 from bergwolf/github/tokio
update tokio dependency
2023-05-18 20:35:16 +02:00
Peng Tao
f6e1b1152c agent: update tokio dependency
To 1.28.1 to bring in the latest fixes.

Fixes: #6881
Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2023-05-18 09:36:06 +00:00
Peng Tao
4cb83dc219 kata-ctl: update tokio dependency
Update to 1.28.1 To pick up the latest fixes.

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2023-05-18 08:25:13 +00:00
Peng Tao
df615ff252 runk: update tokio dependency
Update to 1.28.1 to pick up latest fixes.

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2023-05-18 08:24:41 +00:00
Peng Tao
ca6892ddb1 runtime-rs: update tokio dependency
Unify it to the latest 1.28.1 version.

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2023-05-18 08:18:22 +00:00
Fabiano Fidêncio
3a4b924226 Merge pull request #6833 from rye-stripe/bugfix/vcpu-pinning
resource-control: fix setting CPU affinities on Linux
2023-05-18 08:12:39 +02:00
Fabiano Fidêncio
e762f70920 Merge pull request #6838 from rye-stripe/bugfix/use-enable-vcpus-pinning-from-toml
runtime: use enable_vcpus_pinning from toml
2023-05-17 21:30:44 +02:00
Fabiano Fidêncio
ca1531fe9d runtime: Use static_sandbox_resource_mgmt=true for TEEs
When this option is enabled the runtime will attempt to determine the
appropriate sandbox size (memory, CPU) before booting the virtual
machine.

As TEEs do not support memory and CPU hotplug, this approach must be
used.

Fixes: #6818

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-17 19:21:52 +02:00
Fabiano Fidêncio
851b97fa51 Merge pull request #6866 from fidencio/topic/gha-improve-actions
gha: k8s: Make the tests more reliable
2023-05-17 19:19:18 +02:00
Fabiano Fidêncio
8ce14e709a Merge pull request #6810 from fitzthum/snp-enable
gha: Enable SEV-SNP tests on main
2023-05-17 15:29:54 +02:00
Greg Kurz
206df04b99 Merge pull request #6858 from fidencio/topic/gha-tdx-fix-cleanup
gha: tdx: Use the k3s overlay for kata-cleanup
2023-05-17 15:04:56 +02:00
Wainer Moschetta
259158f1c3 Merge pull request #6789 from dubek/add-sev-package
runtime: Port sev package to main
2023-05-17 10:02:19 -03:00
Fabiano Fidêncio
fa832f4709 gha: k8s: Make the tests more reliable
We like it or not, every now and then we'll have to deal with flaky
tests, and our tests using GHA are not exempt from that fact.

With this simple commit, we're trying to improve the reliability of the
tests in a few different fronts:

* Giving enough time for the script used by kata-deploy to be executed
  * We've hit issues as the kata-deploy pod is considered "Ready" at the
    moment it starts running, not when it finishes the needed setup. We
    should also be looking on how to solve this on the kata-deploy side
    but, for now, let's ensure our tests do not break with the current
    kata-deploy behavior.

* Merging the "Deploy kata-deploy" and "Run tests" steps
  * We've hit issues re-running tests and seeing even more failures than
    the ones we're trying to debug, as a step will simply be taken as
    succeeded as part of the re-run, in case it was successful executed
    as part of the first run.  This causes issues with the kata-deploy
    deployment, as the tests would start running before even having the
    node set up for running Kata Containers.

Fixes: #6865 #6649

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-17 13:38:08 +02:00
Tobin Feldman-Fitzthum
cbb9fe8b81 config: Use standard OVMF with SEV
The AmdSev firmware package should be used with
measured direct boot. If the expected hashes are not
injected into the firmware binary by the VMM, the
guest will not boot. This is required for security.

Currently the main branch does not have the extended
shim support for SEV, which tells the VMM to inject
the expected hashes.

We ship the standard OVMF package to use with SNP,
so let's switch SEV to that for now. This will need
to be changed back when shim support for SEV(-ES)
is added to main.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-17 11:36:04 +02:00
Tobin Feldman-Fitzthum
724437efb3 kata-deploy: add kata-qemu-sev runtimeclass
In order to populate containerd config file with
support for SEV, we need to add the qemu-sev shim
to the kata-deploy script.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-17 11:36:02 +02:00
Tobin Feldman-Fitzthum
521dad2a47 Tests: skip CPU constraints test on SEV and SNP
Currently Kata does not support memory / CPU hotplug for SEV or
SEV-SNP so we need to skip tests that rely on it.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-17 11:35:13 +02:00
Tobin Feldman-Fitzthum
72308ddb07 gha: ci-on-push: Don't skip tests for SEV
Now that SEV artifacts are built by GHA, remove
conditional that skips tests when using qemu-sev.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-17 11:35:13 +02:00
Tobin Feldman-Fitzthum
da0f92cef8 gha: ci-on-push: Don't skip tests for SEV-SNP
Now that we have SNP artifacts in place and they are built via gha,
remove the condition that skips the tests for SNP.

Fixes: #6809

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-17 11:35:13 +02:00
Fabiano Fidêncio
12f43bea0f gha: tdx: Use the k3s overlay for kata-cleanup
As the TDX CI runs on k3s, we must ensure the cleanup, as already done
for the deploy, used the k3s overlay.

Fixes: #6857

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-17 09:50:29 +02:00
Fabiano Fidêncio
9630c13ac0 Merge pull request #6845 from fidencio/topic/yet-more-nvidia-gpu-naming-fixes
gpu: Rename the last bits from `gpu` to `nvidia-gpu`
2023-05-17 09:05:12 +02:00
Steve Horsman
e4a458035c Merge pull request #6852 from stevenhorsman/container-image-arch-consistency
deploy: fix shell script error
2023-05-17 08:01:39 +01:00
Amulya Meka
3ccc29030d Merge pull request #6780 from Amulyam24/rust-virtfs
ppc64le: switch virtiofsd from C to rust version
2023-05-17 09:36:28 +05:30
GabyCT
e0e46de12d Merge pull request #6849 from GabyCT/topic/fixtabs
osbuilder: Fix indentation in rootfs.sh
2023-05-16 16:47:09 -06:00
stevenhorsman
1a3f8fc1a2 deploy: fix shell script error
- Remove local introduced by bad copy-paste

Fixes: #6814
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2023-05-16 19:30:32 +01:00
Salvador Fuentes
b76058c979 Merge pull request #6721 from nedsouza/virtcontainers-qemu-go-coverage
virtcontainers/qemu_test.go: Improve coverage
2023-05-16 11:11:43 -06:00
Feng Wang
ebc8e8e2fd Merge pull request #6773 from jepio/agent-config-error-context
agent: Add context to errors that may occur when AgentConfig file is …
2023-05-16 09:21:34 -07:00
Gabriela Cervantes
87cb98c01d osbuilder: Fix indentation in rootfs.sh
This PR replaces single spaces to tabs in order to fix the
indentation of the rootfs script.

Fixes #6848

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-05-16 15:30:50 +00:00
James O. D. Hunt
a96fcfd5be Merge pull request #6735 from nedsouza/258/tests-coverage-compatoci
virtcontainers/pkg/compatoci/: Improved coverage for  for Kata 2.0
2023-05-16 15:36:35 +01:00
Amulyam24
c5a59caca1 ppc64le: switch virtiofsd from C to rust version
We have been using the C version of virtiofsd on ppc64le. Now that the issue with
rust virtiofsd have been fixed, let's switch to it.

Fixes: #4259

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2023-05-16 14:46:19 +02:00
Amulyam24
bfdf0144aa versions: Bump virtiofsd to 1.6.1
virtiofsd v1.6.1  has been released with the fixes required for running
successfully on ppc64le.

Fixes: #4259

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2023-05-16 14:46:16 +02:00
Dov Murik
dd7562522a runtime: pkg/sev: Add kbs utility package for SEV pre-attestation
Supports both online and offline modes of interaction with simple-kbs
for SEV/SEV-ES confidential guests.

Fixes: #6795

Signed-off-by: Dov Murik <dovmurik@linux.ibm.com>
2023-05-16 15:27:32 +03:00
Dov Murik
05de7b2607 runtime: Add sev package
The sev package provides utilities for launching AMD SEV and SEV-ES
confidential guests.

Fixes: #6795

Signed-off-by: Dov Murik <dovmurik@linux.ibm.com>
2023-05-16 15:27:32 +03:00
Fabiano Fidêncio
3a9d3c72aa gpu: Rename the last bits from gpu to nvidia-gpu
Let's specifically name the `gpu` runtime class as `nvidia-gpu`.  By
doing this we keep the door open and ease the life of the next vendor
adding GPU support for Kata Containers.

Fixes: #6553

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-16 13:47:52 +02:00
Fabiano Fidêncio
4cde844f70 local-build: Fix kernel-nvidia-gpu target name
It must have `-tarball` as part of its name.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-16 13:34:52 +02:00
Archana Shinde
8d10d157b3 Merge pull request #6823 from jodh-intel/utils-kata-manager-containerd-fix
kata-manager: Fix '-o' syntax and logic error
2023-05-15 21:44:35 -07:00
Bin Liu
47a02dcc7f Merge pull request #6767 from ngpatel6/Issue-5403
kata-ctl:  Add the option to install kata-ctl to a user specified directory
2023-05-16 10:43:40 +08:00
Chao Wu
911d8a5a7f Merge pull request #6804 from pmores/fix-rust-version-in-docs
runtime-rs: fix building instructions to use correct required Rust ve…
2023-05-16 10:14:05 +08:00
Bin Liu
2cd2d02d1f Merge pull request #6812 from ZhangShuaiyi/dev/write_bootparams
Dragonball: use LinuxBootConfigurator::write_bootparams
2023-05-16 09:54:41 +08:00
GabyCT
3d8185863d Merge pull request #6835 from GabyCT/topic/buildkataproxy
kata-deploy: Add http_proxy as part of the docker build
2023-05-15 16:15:27 -06:00
Narendra Patel
593840e075 kata-ctl: Allow INSTALL_PATH= to be specified
Update the kata-ctl install rule to allow it to be installed to a given directory

The Makefile was updated to use an INSTALL_PATH variable to track where the
kata-ctl binary should be installed.  If the user doesn't specify anything,
then it uses the default path that cargo uses.  Otherwise, it will install it
in the directory that the user specified.  The README.md file was also updated
to show how to use the new option.

Fixes #5403

Co-authored-by: Cesar Tamayo <cesar.tamayo@intel.com>
Co-authored-by: Kevin Mora Jimenez <kevin.mora.jimenez@intel.com>
Co-authored-by: Narendra Patel <narendra.g.patel@intel.com>
Co-authored-by: Ray Karrenbauer <ray.karrenbauer@intel.com>
Co-authored-by: Srinath Duraisamy <srinath.duraisamy@intel.com>
Signed-off-by: Narendra Patel <narendra.g.patel@intel.com>
2023-05-15 17:21:49 -04:00
Peteris Rudzusiks
bdb75fb21e runtime: use enable_vcpus_pinning from toml
Set the default value of runtime's EnableVCPUsPinning to value read from .toml.

Fixes: #6836

Signed-off-by: Peteris Rudzusiks <rye@stripe.com>
2023-05-15 21:41:20 +02:00
Tamas K Lengyel
20cb875087 virtcontainers/qemu_test.go: Improve test coverage
Rework TestQemuCreateVM routine to be a table driven test with
various config variations passed to it. After CreateVM a handful
of additional functions are exercised to improve code-coverage.
Also add partial coverage for StartVM routine.

Currently improving from 19.7% to 35.7%

Credit PR to Hackathon Team3

Fixes: #267

Signed-off-by: Tamas K Lengyel <tamas.lengyel@intel.com>
2023-05-15 15:26:35 -04:00
Fabiano Fidêncio
da877a603d Merge pull request #6829 from fidencio/topic/kata-deploy-remove-tarball-from-payload-image
kata-deploy: Do not ship the kata tarball
2023-05-15 19:01:14 +02:00
Gabriela Cervantes
b9a1db2601 kata-deploy: Add http_proxy as part of the docker build
Add http_proxy and https_proxy as part of the docker build arguments
in order to build properly when we are behind a proxy.

Fixes #6834

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-05-15 15:57:29 +00:00
Peteris Rudzusiks
3e85bf5b17 resource-control: fix setting CPU affinities on Linux
With this fix the vCPU pinning feature chooses the correct
physical cores to pin the vCPU threads on rather than always using core 0.

Fixes #6831

Signed-off-by: Peteris Rudzusiks <rye@stripe.com>
2023-05-15 16:46:36 +02:00
Pavel Mores
5f3f844a1e runtime-rs: fix building instructions with respect to required Rust version
Fixes: #6803

Signed-off-by: Pavel Mores <pmores@redhat.com>
2023-05-15 16:30:41 +02:00
Fabiano Fidêncio
9e83795fca Merge pull request #6825 from fidencio/topic/kata-deploy-build-improvements
kata-deploy: Build improvements
2023-05-15 13:49:15 +02:00
Fabiano Fidêncio
802cd2f673 Merge pull request #6821 from stevenhorsman/container-image-arch-consistency
deploy: Fix arch in image tag
2023-05-15 11:16:01 +02:00
Fabiano Fidêncio
815b4e8dac Merge pull request #6816 from fidencio/topic/kata-deploy-fixes
Revert "kata-deploy: Use readinessProbe to ensure everything is ready"
2023-05-15 10:24:58 +02:00
Fabiano Fidêncio
777c3dc8d2 kata-deploy: Do not ship the kata tarball
There's absolutely no reason to ship the kata-static tarball as part of
the payload image, as:
* The tarball is already part of the release process
* The payload image already has uncompressed content of the tarball
* The tarball itself is not used anywhere by the kata-deploy scripts

Fixes: #6828

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-15 09:22:39 +02:00
LiuWeijie
50cc9c582f tests: Improve coverage for virtcontainers/pkg/compatoci/ for Kata 2.0
Add test cases for ParseConfigJson function and GetContainerSpec function

Fixes: #258

Signed-off-by: LiuWeijie <weijie.liu@intel.com>
2023-05-15 11:58:17 +08:00
Fabiano Fidêncio
136e2415da static-build: Download firecracker instead of building it
There's no reason for us to build firecracker instead of simply
downloading the official released tarball, as tarballs are provided for
the architectures we want to use them.

Fixes: #6770

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-12 22:05:33 +02:00
Fabiano Fidêncio
3bf767cfcd static-build: Adjust ARCH for nydus
When building from aarch64, just use "arm64" as that's what's used in
the name of the released nydus tarballs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-12 22:05:33 +02:00
Fabiano Fidêncio
ac88d34e0c static-build: Use relased binary for CLH (aarch64)
There's no need to build Cloud Hypervisor aarch64 as, for a few releases
already, Cloud Hypervisor provides an official release binary for the
architecture.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-12 22:05:01 +02:00
Archana Shinde
32b39ee347 Merge pull request #6763 from nedsouza/266/tests_coverage_virtcontainers_fc
virtcontainers: Improved test coverage for fc.go from 4.6% to 18.5%
2023-05-12 11:53:27 -07:00
James O. D. Hunt
73913c8eb7 kata-manager: Fix '-o' syntax and logic error
Fix the syntax and logic error that is only displayed if the user runs
the script with `-o`. This option requests that "only" Kata Containers
is installed and stops containerd from being installed.

Fixes: #6822.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-05-12 16:44:24 +01:00
stevenhorsman
2856d3f23d deploy: Fix arch in image tag
`uname -m` produces `x86_64`, but container image convention
is to use `amd64`, so update this in the tag

Fixes: #6820
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2023-05-12 16:14:19 +01:00
Fabiano Fidêncio
42dce15b1f Merge pull request #6450 from singhwang/main
main | release: Fix multi-arch publishing is not supported
2023-05-12 15:25:59 +02:00
Fabiano Fidêncio
e8f81ee93d Revert "kata-deploy: Use readinessProbe to ensure everything is ready"
This reverts commit 5ec9ae0f04, for two
main reasons:
* The readinessProbe was misintepreted by myself when working on the
  original PR
* It's actually causing issues, as the pod ends up marked as not
  healthy.
2023-05-12 14:28:23 +02:00
SinghWang
cfe63527c5 release: Fix multi-arch publishing is not supported
When release is published, kata-deploy payload and kata-static package
can support multi-arch publishing.

Fixes: #6449

Signed-off-by: SinghWang <wangxin_0611@126.com>
Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-12 13:36:44 +02:00
Shuaiyi Zhang
197c336516 Dragonball: use LinuxBootConfigurator::write_bootparams to writes
the boot parameters into guest memory.

Fixes: #6813

Signed-off-by: Shuaiyi Zhang <zhang_syi@qq.com>
2023-05-12 16:07:44 +08:00
Fabiano Fidêncio
181017d1d8 Merge pull request #6811 from fidencio/topic/yet-more-fixes-for-nvidia-gpu-kernels
cache: More fixes to nvidia-gpu kernels caching
2023-05-12 10:02:08 +02:00
Amulya Meka
76f975e5e6 Merge pull request #6742 from Amulyam24/agent-build
runtime: remove overriding ARCH value by default for ppc64le
2023-05-12 12:34:50 +05:30
Archana Shinde
20ac3917ad Merge pull request #6739 from byron-marohn/fix_5561
gha: Fix Body Line Length action flagging empty body commit messages
2023-05-11 15:17:07 -07:00
Archana Shinde
1ad442e656 Merge pull request #6748 from nedsouza/fix-snap
gha: Fix snap creation workflow
2023-05-11 15:09:22 -07:00
Fabiano Fidêncio
4d17ea4a01 cache: Fix nvidia-snp caching version
All the kernel-foo instances, such as "kernel-sev" or "kernel-snp",
should be transformed into "kernel.foo" when looking at the
versions.yaml file.

This was already done for SEV, but missed on the SNP case.

Fixes: #6777

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-11 21:26:58 +02:00
Fabiano Fidêncio
a133fadbfa cache: Fix nvidia-gpu-tdx-experimental cache URL
We were passing "kernel-nvidia-gpu-tdx", missing the "-experimental"
part, leading to a non-valid URL.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-11 21:20:06 +02:00
Fabiano Fidêncio
a7dd6cbadd Merge pull request #6807 from fidencio/topic/fix-nvidia-gpu-cache
cache: Fix nvidia-gpu version
2023-05-11 17:40:41 +02:00
Fabiano Fidêncio
b9990c2017 cache: Fix nvidia-gpu version
c9bf7808b6 introduced the logic to
properly get the version of nvidia-gpu kernels, but one important part
was dropped during the rebase into main, which is actually getting the
correct version of the kernel.

Fixing this now, and using the old issue as reference.

Fixes: #6777

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-11 13:55:14 +02:00
Fabiano Fidêncio
14939d00ad Merge pull request #6778 from fidencio/topic/cache-gpu-related-kernels
cache: Update the KERNEL_FLAVOUR list to include nvidia-gpu
2023-05-11 13:14:45 +02:00
Fabiano Fidêncio
c9bf7808b6 cache: Update the KERNEL_FLAVOUR list to include nvidia-gpu
We need to make sure that, when caching a `-nvidia-gpu` kernel, we still
look at the version of the base kernel used to build the nvidia-gpu
drivers, as the ${vendor}-gpu kernels are based on already existing
entries in the versions.yaml file and do not require a new entry to be
added.

Fixes: #6777

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-11 10:56:13 +02:00
Fabiano Fidêncio
3665b42045 gpu: Rename gpu targets to nvidia-gpu
This will make it easier for other GPU vendors to add the needed bits in
the future.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-05-11 10:55:55 +02:00
Fabiano Fidêncio
edfaae85cb Merge pull request #6700 from fitzthum/snp-artifacts
packaging: Add SEV-SNP artifacts to main
2023-05-11 10:47:10 +02:00
James O. D. Hunt
fe33015075 Merge pull request #6794 from jodh-intel/docs-mark-snap-as-unmaintained
docs: Mark snap installation method as unmaintained
2023-05-11 09:14:25 +01:00
Fabiano Fidêncio
c937d0a5d4 Merge pull request #6591 from UnmeshDeodhar/add-sev-artifacts-to-main
packaging: Add sev artifacts to main
2023-05-11 09:09:36 +02:00
Tobin Feldman-Fitzthum
2c90cac751 local-build: fixup alphabetization
A few pieces of the local-build tooling are supposed to be
alphabetized. Fixup a couple minor issues that have accumulated.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 21:23:38 +00:00
Tobin Feldman-Fitzthum
4da6eb588d kata-deploy: Add qemu-snp shim
Now that we have the SNP components in place, make sure that
kata-deploy knows about the qemu-snp shim so that it will be
added to containerd config.

Fixes: #6575

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:55:36 +00:00
Tobin Feldman-Fitzthum
14dd053758 kata-deploy: add kata-qemu-snp runtimeclass
Since SEV-SNP has limited hotplug support, increase
the pod overhead to account for fixed resource usage.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:55:36 +00:00
Tobin Feldman-Fitzthum
0bb37bff78 config: Add SNP configuration
SNP requires many specific configurations, so let's make
a new SNP configuration file that we can use with the
kata-qemu-snp runtime class.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-05-10 20:55:36 +00:00
Chelsea Mafrica
13f9ba2298 Merge pull request #6379 from cmaf/kata-ctl-check-kvm-1
kata-ctl: add generic kvm check & unit test
2023-05-10 13:33:57 -07:00
Tobin Feldman-Fitzthum
af7f2519bf versions: update SEV kernel description
SNP and SEV will share a (guest) kernel. Update the description
in versions.yaml to mention this.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:27:12 +00:00
Tobin Feldman-Fitzthum
dbcc3b5cc8 local-build: fix default values for OVMF build
Existing value has wrong name and compression type
leading to installation failure.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:27:12 +00:00
Tobin Feldman-Fitzthum
b8bbe6325f gha: build OVMF for tests and release
The x86_64 package of OVMF is required for deployments
that don't use kernel hashes, which includes SEV-SNP
in the short term. We should keep this in the bundle
in the long term in case someone wants to disable
kernel hashes.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:27:12 +00:00
Tobin Feldman-Fitzthum
cf0ca265f9 local-build: Add x86_64 OVMF target
Add targets to build the "plain" x86_64 OVMF.

This will be used by anyone who is using SEV or SNP
without kernel hashes. The SNP QEMU does not yet
support kernel hashes so the OvmfPkg will be used
by default.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-05-10 20:24:51 +00:00
Tobin Feldman-Fitzthum
db095ddeb4 cache: add SNP flavor to comments
Update comments to include new SNP QEMU option

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:19:56 +00:00
Tobin Feldman-Fitzthum
f4ee00576a gha: Build and ship QEMU for SNP
Now that we can build SNP QEMU, let's do that for tests and release.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:19:56 +00:00
Tobin Feldman-Fitzthum
7a58a91fa6 docs: update SNP guide
Since we reshuffled versions.yaml, update the guide so that
we can find the SNP QEMU info.

Once runtime support is merged we should overhaul or remove
this guide, but let's keep it for now.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2023-05-10 20:19:56 +00:00
Tobin Feldman-Fitzthum
879333bfc7 versions: update SNP QEMU version
Refactor SNP QEMU entry in versions.yaml to match
qemu-experimental and qemu-tdx-experimental.

Also, update the version of QEMU to what we are using
in CCv0. This is the non-UPM QEMU and it does not
have kernel hashes support.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-05-10 20:19:56 +00:00
Tobin Feldman-Fitzthum
38ce4a32af local-build: add support to build QEMU for SEV-SNP
Add Make targets and helper functions to build the QEMU
needed for SEV-SNP.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-05-10 20:19:56 +00:00
Chelsea Mafrica
5f8008b69c kata-ctl: add unit test for kvm check
Check that kvm test fails when run as non-root and when device specified
is not /dev/kvm.

Fixes #5338

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2023-05-10 10:29:20 -07:00
Chelsea Mafrica
a085a6d7b4 kata-ctl: add generic kvm check
Add kvm check using ioctl macro to create a syscall that checks the kvm
api version and if creation of a vm is successful.

Fixes #5338

Signed-off-by: Chelsea Mafrica <chelsea.e.mafrica@intel.com>
2023-05-10 10:29:20 -07:00
Unmesh Deodhar
772d4db262 gha: Build and ship SEV initrd
We have code that builds initrd for SEV.
thus, adding that to the test and release process.

Fixes: #6572

Signed-off-by: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:56 -05:00
Unmesh Deodhar
45fa366926 gha: Build and ship SEV OVMF
SEV requires special OVMF to work. Thus, building that for test and release.

Fixes: #6572

Signed-Off-By: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:56 -05:00
Unmesh Deodhar
4770d3064a gha: Build and ship SEV kernel.
SEV requires custom kernel arguments when building.
Thus, adding it to the test and release process.

Fixes: #6572

Signed-off-by: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:56 -05:00
Unmesh Deodhar
fb9c1fc36e runtime: Add qemu-sev config
Adding config file that can be used with qemu-sev runtime class.
Since SEV has limited hotplug support, increase
the pod overhead to account for fixed resource usage.

Fixes: #6572

Signed-off-by: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:56 -05:00
Unmesh Deodhar
813e4c576f runtimeClasses: add sev runtime class
Adding kata-qemu-sev runtime class.

Fixes: #6572

Signed-off-by: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:56 -05:00
Unmesh Deodhar
af18806a8d static-build: Add caching support to sev ovmf
SEV requires special OVMF.
Now that we have ability to build this custom OVMF, let's optimize
it by caching so that we don't have to build it for every run.

Fixes: sev: #6572

Signed-Off-By: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:55 -05:00
Unmesh Deodhar
76ae7a3abe packaging: adding caching capability for kernel
The SEV initrd build requires kernel modules.
So, for SEV case, we need to cache kernel modules tarball in
addition to kernel tarball.

Fixes: #6572

Signed-Off-By: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:55 -05:00
Unmesh Deodhar
12c5ef9020 packaging: add support to build OVMF for SEV
SEV requires special OVMF to work with kernel hashes.
Thus, adding changes that builds this custom OVMF for SEV.

Fixes: #6572

Signed-Off-By: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:55 -05:00
Unmesh Deodhar
b87820ee8c packaging: add support to build initrd for sev
We need special initrd for SEV. The work on SEV initrd is based on
Ubuntu. Thus, adding another entry in versions.yaml
This binary will have '-sev' suffix to distinguish it from the generic
binary.

Fixes: #6572

Signed-Off-By: Unmesh Deodhar <udeodhar@amd.com>
2023-05-10 12:19:55 -05:00
James O. D. Hunt
e1f3b871cd docs: Mark snap installation method as unmaintained
The snap package is no longer being maintained so update the docs to
warn readers.

We'll remove the snap installation docs in a few weeks.

See: #6769.
Fixes: #6793.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-05-10 18:02:46 +01:00
Jeremi Piotrowski
022a33de92 agent: Add context to errors when AgentConfig file is missing
When the agent config file is missing, the panic message says "no such file or
directory" but doesn't inform the user about which file was missing. Add
context to the parsing (with filename) and to the from_config_file() calls
(with information where the path is coming from).

Fixes: #6771
Depends-on: github.com/kata-containers/tests#5627
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-05-10 08:43:16 +02:00
Fabiano Fidêncio
6881b9558b Merge pull request #6512 from gabevenberg/log-parser-rs
Log-parser-rs
2023-05-10 08:22:59 +02:00
Chao Wu
7218229af0 Merge pull request #6594 from Apokleos/warning_fix_1.68.0
warning_fix: fix warnings when build with cargo-1.68.0
2023-05-10 09:51:45 +08:00
Unmesh Deodhar
b0e6a094be packaging: Add sev kernel build capability
Adding code that builds sev kernel.

Fixes: #6572

Signed-off-by: Unmesh Deodhar <udeodhar@amd.com>
2023-05-09 13:47:22 -05:00
Tim Zhang
b0b5d7082e Merge pull request #6753 from amshinde/add-cross-building-with-cross
cross-compile: Include documentation and configuration for cross-compile
2023-05-09 16:31:40 +08:00
Feng Wang
4e0dce6802 Merge pull request #6738 from fengwang666/oss-fix-fd-leak
runtime: Fix virtiofs fd leak
2023-05-08 10:52:36 -07:00
Eduardo Berrocal
a4c0303d89 virtcontainers: Fixed static checks for improved test coverage for fc.go
Expanded tests on fc_test.go to cover more lines of code. Coverage went from 4.6% to 18.5%.
Fixed very simple static check fail on line 202.

Fixes: #266

Signed-off-by: Eduardo Berrocal <eduardo.berrocal@intel.com>
2023-05-07 00:17:36 -07:00
Peng Tao
65670e6b0a Merge pull request #6699 from zvonkok/cold-plug-vfio
gpu: cold plug VFIO devices
2023-05-05 10:04:29 +08:00
Archana Shinde
b86d32aba9 Merge pull request #6728 from nedsouza/256/tests_coverage_pkg_signals
pkg/signals: Improved test coverage 60% to 100%
2023-05-04 16:19:12 -07:00
Archana Shinde
9443c4aea7 Merge pull request #6729 from nedsouza/259/tests_coverage_virtcontainers_persist
virtcontainers/persist: Improved test coverage 65% to 87.5%
2023-05-04 16:18:55 -07:00
Archana Shinde
09134c30de Merge pull request #6737 from nedsouza/265/virtcontainers-clh-go-coverage
virtcontainers/clh_test.go: improve unit test coverage
2023-05-04 16:15:43 -07:00
Archana Shinde
8495f830b7 cross-compile: Include documentation and configuration for cross-compile
`cross` is an open source tool that provides zero-setup cross compile
for rust binaries. Add documentation on this tool for compiling
kata-ctl tool and Cross.toml file that provides required configuration
for installing dependencies for various targets.
This is pretty useful for a developer to make sure code compiles and
passes checks for various architectures.

Fixes: #6765

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-05-04 14:13:00 -07:00
Bin Liu
e57ac2ae18 Merge pull request #6749 from nedsouza/260/tests_coverage_virtcontainers_factory
virtcontainers/factory: Improved test coverage
2023-05-04 10:54:40 +08:00
Zvonko Kaiser
13d7f39c71 gpu: Check for VFIO port assignments
Bailing out early if the port is wrong, allowed port settings are
no-port, root-port, switch-port

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-05-03 12:32:33 +00:00
Gabe Venberg
6594a9329d tools: made log-parser-rs
Eventual replacement of kata-log-parser, but for now replicates its
functionaility for the new runtime-rs syntax. Takes in log files,
parses, sorts by timestamp, spits them out in json, csv, xml, toml, and
a few others.

Fixes #5350

Signed-off-by: Gabe Venberg <gabevenberg@gmail.com>
2023-05-02 13:16:54 -05:00
Wainer Moschetta
f5ff975560 Merge pull request #6723 from ryansavino/gha-k8s-also-test-snp
gha: Also run k8s tests on qemu-snp
2023-05-01 10:37:12 -03:00
Fabiano Fidêncio
b6e54676eb Merge pull request #6759 from ryansavino/gha-sev-kata-deploy-fix
gha: sev: fix for kata-deploy error
2023-05-01 11:42:16 +02:00
Eduardo Berrocal
03a8cd69c2 virtcontainers: Improved test coverage for fc.go from 4.6% to 18.5%
Expanded tests on fc_test.go to cover more lines of code. Coverage went from 4.6% to 18.5%.

Fixes: #266

Signed-off-by: Eduardo Berrocal <eduardo.berrocal@intel.com>
2023-04-28 15:40:45 -07:00
Ryan Savino
9e2b7ff177 gha: sev: fix for kata-deploy error
kubectl commands need a '-f' instead of a '-k'

Fixes: #6758

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2023-04-28 14:54:36 -05:00
Ryan Savino
5c9246db19 gha: Also run k8s tests on qemu-snp
Added the k8s tests for qemu-snp

Fixes: #6722

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2023-04-28 14:43:53 -05:00
Ryan Savino
c57a44436c gha: Add the ability to test qemu-snp
With the changes proposed as part of this PR, a qemu-snp cluster
will be created but no tests will be performed.

GitHub Actions will only run the tests using the workflows that are
part of the **target** branch, instead of the using the ones coming
from the PR. No way to work around this for now.

After this commit is merged, the tests (not the yaml files for the
actions) will be altered in order for the checkout action  to help in
this case.

Fixes: #6722

Signed-off-by: Ryan Savino <ryan.savino@amd.com>
2023-04-28 13:07:13 -05:00
Wainer Moschetta
29785a43d7 Merge pull request #6712 from ryansavino/gha-k8s-also-test-sev
gha: Also run k8s tests on qemu-sev
2023-04-28 14:22:03 -03:00
Archana Shinde
65c61785fc Merge pull request #6660 from amshinde/kata-ctl-cmd
Implement the "kata-ctl env" command
2023-04-28 01:33:28 -07:00
Archana Shinde
4064192896 env: Utilize arch specific functionality to get cpu details
Have kata-env call architecture specific function to get cpu details
instead of generic function to get cpu details that works only for
certain architectures. The functionality for cpu details has been fully
implemented for x86_64 and arm architectures, but needs to be
implemented for s390 and powerpc.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Archana Shinde
fb40c71a21 env: Check for root privileges
Check for root privileges early on.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Archana Shinde
1016bc17b7 config: Add api to fetch config from default config path
Add api to fetch config from default config path and use that in
kata-ctl tool.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Archana Shinde
b908a780a0 kata-env: Pass cmd option for file path
Add ability to write the environment information to a file
or stdout if file path is absent.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Archana Shinde
b1920198be config: Workaround the way agent and hypervisor configs are fetched
This is essentially a workaround for the issue:
https://github.com/kata-containers/kata-containers/issues/5954

runtime-rs chnages the Kata config format adding agent_name and
hypervisor_name which are then used as keys to fetch the agent and
hypervisor configs. This will not work for older configs.
So use the first entry in the hashmaps to fetch the configs as a
workaround while the config change issue is resolved.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Archana Shinde
f2b2621dec kata-env: Implement the kata-env command.
Command implements functionality to get user environment settings.

Fixes: #5339

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-27 16:45:41 -07:00
Ryan Savino
c849bdb0a5 gha: Also run k8s tests on qemu-sev
Added the k8s tests for qemu-sev

Fixes: #6711

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2023-04-27 15:24:08 -05:00
Eduardo Berrocal
6bf1fc6051 virtcontainers/factory: Improved test coverage
Expanded tests on factory_test.go to cover more lines of code. Coverage went from 34% to 41.5% in the case of user-mode run tests,
and from 77.7% to 84% in the case of priviledge-mode run tests.

Fixes: #260

Signed-off-by: Eduardo Berrocal <eduardo.berrocal@intel.com>
2023-04-27 13:08:35 -07:00
Tamas K Lengyel
0d49ceee0b gha: Fix snap creation workflow warnings
Fix recurring issues of failing to install dependencies due to stale apt cache.
Uprev actions/checkout to v3 to resolve issue "Node.js 12 actions are deprecated."

Fixes: #5659
Signed-off-by: Tamas K Lengyel <tamas.lengyel@intel.com>
2023-04-27 18:40:02 +00:00
Zvonko Kaiser
138ada049c gpu: Cold Plug VFIO toml setting
Added the cold_plug_vfio setting to the qemu-toml.in with some
epxlanation

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-27 11:04:45 +00:00
Amulyam24
defb643346 runtime: remove overriding ARCH value by default for ppc64le
Currently, ARCH value is being set to powerpc64le by default.
powerpc64le is only right in context of rust and any operation
which might use this variable for a different purpose would fail on ppc64le.

Fixes: #6741

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2023-04-27 16:17:48 +05:30
Zvonko Kaiser
f7ad75cb12 gpu: Cold-plug extend the api.md
Make the hypervisorconfig consistent in code and api.md

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-27 09:35:05 +00:00
Zvonko Kaiser
0fec2e6986 gpu: Add cold-plug test
Cold plug setting is now correctly decoded in toml

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-27 09:30:24 +00:00
Archana Shinde
f2ebdd81c2 utils: Get rid of spurious print statement left behind.
The print was used for debugging, get ris of it.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
9a94f1f149 make: Export VERSION and COMMIT
These will be consumed by kata-ctl, so export these so that
they can be used to replace variables available to the rust binary.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
2f81f48dae config: Add file under /opt as another location to look for the config
Most of kata installation tools use this path for installation, so
add this to the paths to look for the configuration.toml file.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
07f7d17db5 config: Make the pipe_size field optional
Add the serde default attribute to the field so that parsing
can continue if this field is not present.
The agent assumes a default value for this, so it is not required
by the user to provide a value here.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
68f6357731 config: Make function to get the default conf file public
This will be used by the kata-env command.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
7565b33568 kata-ctl: Implement Display trait for GuestProtection enum
Implement Display for enum to display in env output.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
94a00f9346 utils: Make certain constants in utils.rs public
These would be used outside of utils.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
572b338b3b gitignore: Ignore .swp and .swo editor backup files
Ignore temporary files created by vim editor.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
Archana Shinde
376884b8a4 cargo: Update version of clap to 4.1.13
This version includes macros related to using command options.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-26 22:12:30 -07:00
alex.lyn
17daeb9dd7 warning_fix: fix warnings when build with cargo-1.68.0
Fixes: #6593

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2023-04-27 10:29:50 +08:00
Ryan Savino
521519d745 gha: Add the ability to test qemu-sev
With the changes proposed as part of this PR, a qemu-sev cluster will
be created but no tests will be performed.

GitHub Actions will only run the tests using the workflows that are
part of the **target** branch, instead of the using the ones coming
from the PR. No way to work around this for now.

After this commit is merged, the tests (not the yaml files for the
actions) will be altered in order for the checkout action  to help in this
case.

Fixes: #6711

Signed-off-by: Ryan Savino <ryan.savino@amd.com>
2023-04-26 17:56:28 -05:00
Feng Wang
205909fbed runtime: Fix virtiofs fd leak
The kata runtime invokes removeStaleVirtiofsShareMounts after
a container is stopped to clean up the stale virtiofs file caches.

Fixes: #6455
Signed-off-by: Feng Wang <fwang@confluent.io>
2023-04-26 15:53:39 -07:00
Byron Marohn
5226f15c84 gha: Fix Body Line Length action flagging empty body commit messages
Change the Body Line Length workflow to not trigger when the commit
message contains only a message without a body. Other workflows will
flag the missing body sections, and it was confusing to have an error
message that said 'Body line too long (max 150)' when this was not
actually the case.

Fixes: #5561

Co-authored-by: Jayant Singh <jayant.singh@intel.com>
Co-authored-by: Luke Phillips <lucas.phillips@intel.com>
Signed-off-by: Byron Marohn <byron.marohn@intel.com>
Signed-off-by: Jayant Singh <jayant.singh@intel.com>
Signed-off-by: Luke Phillips <lucas.phillips@intel.com>
Signed-off-by: Kelby Madal-Hellmuth <kelby.madal-hellmuth@intel.com>
Signed-off-by: Liz Lawrens <liz.lawrens@intel.com>
2023-04-26 17:29:16 -04:00
Tamas K Lengyel
0f45b0faa9 virtcontainers/clh_test.go: improve unit test coverage
Credit PR to Hackathon Team3

Fixes: #265

Signed-off-by: Tamas K Lengyel <tamas.lengyel@intel.com>
2023-04-26 19:12:51 +00:00
Zvonko Kaiser
dded731db3 gpu: Add OVMF setting for MMIO aperture
The default size of OVMFs aperture is too low to
initialized PCIe devices with huge BARs

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
2a830177ca gpu: Add fwcfg helper function
Added driver util function for easier handling of VFIO
devices outside of the VFIO module. At the sandbox level
we may need to set options depending if we have a VFIO/PCIe
device, like the fwCfg for confiential guests.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
131f056a12 gpu: Extract VFIO Functions to drivers
Some functions may be used in other modules then only in
the VFIO module, extract them and make them available to
other layers like sandbox.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
c8cf7ed3bc gpu: Add ColdPlug of VFIO devices with devManager
If we have a VFIO device and cold-plug is enabled
we mark each device as ColdPlug=true and let the VFIO
module do the attaching.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
e2b5e7f73b gpu: Add Rawdevices to hypervisor
RawDevics are used to get PCIe device info early before the sandbox
is started to make better PCIe topology decisions

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
6107c32d70 gpu: Assign default value to cold-plug
Make sure the configuration is propagated to the right structs
and the default value is assigned.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
377ebc2ad1 gpu: Add configuration option for cold-plug VFIO
Users can set cold-plug="root-port" to cold plug a VFIO device in QEMU

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Zvonko Kaiser
c18ceae109 gpu: Add new struct PCIePort
For the hypervisor to distinguish between PCIe components, adding
a new enum that can be used for hot-plug and cold-plug of PCIe devices

Fixes: #6687

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-26 09:47:37 +00:00
Bin Liu
509bc8b6c8 Merge pull request #6718 from openanolis/mengze/keep_abnormal
runtime-rs: support keep_abnormal in toml config
2023-04-26 12:36:52 +08:00
Bin Liu
b6d880510a Merge pull request #6595 from zvonkok/gpu-snp-tdx-kernel
gpu: Build and Ship an GPU enabled Kernel
2023-04-26 12:33:51 +08:00
Eduardo Berrocal
9c38204f13 virtcontainers/persist: Improved test coverage 65% to 87.5%
Expanded tests on manager_test.go to cover more lines of code.

Fixes: #259

Signed-off-by: Eduardo Berrocal <eduardo.berrocal@intel.com>
2023-04-25 23:53:46 +00:00
Eduardo Berrocal
1c1ee8057c pkg/signals: Improved test coverage 60% to 100%
Expanded tests on signals_test.go to cover more lines of code. 'go test' won't show 100% coverage (only 66.7%), because one test need to spawn a new
process (since it is testing a function that calls os.Exit(1)).

Fixes: #256

Signed-off-by: Eduardo Berrocal <eduardo.berrocal@intel.com>
2023-04-25 23:34:13 +00:00
mengze
cc8ea3232e runtime-rs: support keep_abnormal in toml config
This patch adds keep_abnormal in runtime config. If keep_abnormal =
true, it means that 1) if the runtime exits abnormally, the cleanup
process will be skipped, and 2) the runtime will not exit even if the
health check fails.

This option is typically used to retain abnormal information for
debugging and should NOT be enabled by default.

Fixes: #6717

Signed-off-by: mengze <mengze@linux.alibaba.com>
Signed-off-by: quanweiZhou <quanweiZhou@linux.alibaba.com>
2023-04-25 13:47:44 +08:00
David Esparza
7fdaab49bc Merge pull request #6295 from dborquez/add_kernel_module_checks_kvm
kata-ctl: checks for kvm, kvm_intel modules loaded
2023-04-24 13:33:18 -06:00
Greg Kurz
0ca6d3b726 Merge pull request #6681 from Vlad1mir-D/6677-fix-kata-agent-dbus-connection
osbuilder: Fix D-Bus enabling in the dracut case
2023-04-24 17:31:13 +02:00
Bin Liu
3d8688f92e Merge pull request #6620 from jongwu/docker_fail_start_snap
snap: fix docker start fail issue
2023-04-24 10:53:16 +08:00
Archana Shinde
97291d88e9 Merge pull request #6696 from amshinde/kata-manager-containerd-fix
kata-manager: Fix containerd download
2023-04-21 09:54:30 -07:00
Archana Shinde
96e8470dbe kata-manager: Fix containerd download
Newer containerd releases have an additional static package published.
Because of this,  download_url contains two urls causing curl to fail.
To resolve this, pick the first url from the containerd releases to
download containerd.

Fixes: #6695

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-04-20 23:08:51 -07:00
David Esparza
432d407440 kata-ctl: checks for kvm, kvm_intel modules loaded
Ensure that kvm and kvm_intel modules are loaded.
Renames the get_cpu_info() function to read_file_contents()

Fixes #5332

Signed-off-by: David Esparza <david.esparza.borquez@intel.com>
2023-04-20 11:29:36 -06:00
Zvonko Kaiser
b1730e4a67 gpu: Add new kernel build option to usage()
With each release make sure we ship a GPU  enabled kernel

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-20 07:48:30 +00:00
Fupan Li
ceefd50bd0 Merge pull request #6680 from Tim-Zhang/fix-ut-bad-fd
agent: Fix ut issue caused by fd double closed
2023-04-20 11:18:27 +08:00
Fupan Li
a7b4b69230 Merge pull request #6673 from Tim-Zhang/upgrade-ttrpc-protobuf
Bump ttrpc to 0.7.2 and protobuf to 3.2.0
2023-04-20 10:13:43 +08:00
Fupan Li
a1568cd2f5 Merge pull request #6676 from zvonkok/gpu-runtime
gpu: Add GPU enabled confguration and runtime
2023-04-19 13:01:49 +08:00
Vladimir
3e7b902265 osbuilder: Fix D-Bus enabling in the dracut case
- D-Bus enabling now occurs only in setup_rootfs (instead of
prepare_overlay and setup_rootfs)
- Adjust permissions of / so dbus-broker will be able to traverse FS

These changes enables kata-agent to successfully communicate with D-Bus.

Fixes #6677

Signed-off-by: Vladimir <amigo.elite@gmail.com>
2023-04-18 23:17:34 +03:00
Tim Zhang
53c749a9de agent: Fix ut issue caused by fd double closed
Never ever try to close the same fd double times, even in a unit test.

A file descriptor is a number which will be reused, so when you close
the same number twice you may close another file descriptor in the second
time and then there will be an error 'Bad file descriptor (os error 9)'
while the wrongly closed fd is being used.

Fixes: #6679

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-18 23:19:10 +08:00
Hyounggyu Choi
5c032c64ac Merge pull request #6664 from zvonkok/vfio-fix
gpu: Do not pass-through PCI (Host) Bridges
2023-04-18 19:50:15 +09:00
Tim Zhang
2e3f19af92 agent: fix clippy warnings caused by protobuf3
Fix warnings introduced by protobuf upgrade.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 20:15:49 +08:00
Tim Zhang
4849c56faa agent: Fix unit test issue cuased by protobuf upgrade
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
0a582f7815 trace-forwarder: remove unused crate protobuf
Remove unused crate protobuf.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
73253850e6 kata-ctl: remove unused crate ttrpc
Remove unused crate ttrpc.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
76d2e30547 agent-ctl: Bump ttrpc from 0.6.0 to 0.7.1
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
eb3d20dccb protocols: Add ut for Serde
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
59568c79dd protocols: add support for Serde
rust-protobuf@3 does not support Serde natively anymore.
So we need to do it by ourselves.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:21 +08:00
Tim Zhang
a6b4d92c84 runtime-rs: Bump ttrpc from 0.6.0 to 0.7.1
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 19:49:20 +08:00
Zvonko Kaiser
ac7c63bc66 gpu: Add containerd shim for qemu-gpu
Last but not least add the continerd shim configuration
pointing to the correct configuration-<shim>.toml

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 10:45:04 +00:00
Zvonko Kaiser
a0cc8a75f2 gpu: Add a kube runtime class
With the added configuration add the corresponding kube
runtime class.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 10:42:04 +00:00
Zvonko Kaiser
a81fff706f gpu: Adding a GPU enabled configuration
We need to set hotplug on pci root port and enable at least one
root port. Also set the guest-hooks-dir to the correct path

Fixes: #6675

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 10:40:09 +00:00
Tim Zhang
8af6fc77cd agent: Bump ttrpc from 0.6.0 to 0.7.1
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 18:31:41 +08:00
Tim Zhang
009b42dbff protocols: Fix unit test
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 18:31:41 +08:00
Tim Zhang
392732e213 protocols: Bump ttrpc from 0.6.0 to 0.7.1
Fixes: #6646

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-04-17 18:31:35 +08:00
Zvonko Kaiser
f4f958d53c gpu: Do not pass-through PCI (Host) Bridges
On some systems a GPU is in a IOMMU group with a PCI Bridge and
PCI Host Bridge. Per default no PCI Bridge needs to be passed-through.
When scanning the IOMMU group, ignore devices with a 0x60 class ID prefix.

Fixes: #6663

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 10:08:23 +00:00
Zvonko Kaiser
825e769483 gpu: Add GPU support to default kernel without any TEE
With each release make sure we ship a GPU enabled kernel

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 09:58:58 +00:00
Zvonko Kaiser
e4ee07f7d4 gpu: Add GPU TDX experimental kernel
With each release make sure we ship a GPU and TEE enabled kernel
This adds tdx-experimental kernel support

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-17 09:58:52 +00:00
Fabiano Fidêncio
243cb2e3af Merge pull request #6670 from fidencio/topic/fix-caching-of-tdvf-and-tdx-qemu
cache-components: Fix caching of TDVF and QEMU for TDX
2023-04-16 09:04:04 +02:00
Fabiano Fidêncio
a1272bcf1d gha: tdx: Fix typo overlay -> overlays
The beauty of GHA not allowing us to easily test changes in the yaml
files as part of the PR has hit us again. :-/

The correct path for the k3s deployment is
tools/packaging/kata-deploy/kata-deploy/overlays/k3s instead of
tools/packaging/kata-deploy/kata-deploy/overlay/k3s.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-15 15:00:06 +02:00
Fabiano Fidêncio
3fa0890e5e cache-components: Fix TDVF caching
TDVF caching is not working as the tarball name is incorrect. The result
expected is kata-static-tdvf.tar.xz, but it's looking for
kata-static-tdx.tar.xz.

This happens as a logic to convert tdx -> tdvf has been added as part of
the building scripts, but I missed doing this as part of the caching
scripts.

Fixes: #6669

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-15 14:12:29 +02:00
Fabiano Fidêncio
80e3a2d408 cache-components: Fix TDX QEMU caching
TDX QEMU caching is not working as expected, as we're checking for its
version looking at "assets.hypervisor.${QEMU_FLAVOUR}.version", which is
correct for standard QEMU. However, for TDX QEMU we should be checking
for "assets.hypervisor.${QEMU_FLAVOUR}.tag"

Fixes: #6668

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-15 14:12:26 +02:00
Fabiano Fidêncio
fffe2c6082 Merge pull request #6648 from fidencio/topic/gha-tdx-improvements-and-fixes
gha: tdx: Ensure kata-deploy is removed after the tests run
2023-04-15 00:21:31 +02:00
Bo Chen
a819ce145f Merge pull request #6633 from likebreath/0406/clh_v31.0
versions: Upgrade to Cloud Hypervisor v31.0
2023-04-14 13:52:19 -07:00
Zvonko Kaiser
87ea43cd4e gpu: Add configuration fragment
Adding configuration fragment for the kernel,
depending on the TEE kernel update the LOCALVERSION

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-14 07:52:51 +00:00
Zvonko Kaiser
aca6ff7289 gpu: Build and Ship an GPU enabled Kernel
With each release make sure we ship a GPU and TEE enabled kernel

Fixes: #6553

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-14 07:52:42 +00:00
Fabiano Fidêncio
dc662333df runtime: Increase the dial_timeout
When testing on AKS, we've been hitting the dial_timeout every now and
then.  Let's increase it to 45 seconds (instead of 30) for all the VMMs,
and to 60 seconfs in case of TEEs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 22:42:52 +02:00
Greg Kurz
897c0bc67e Merge pull request #6658 from gkurz/osbuilder-dracut-dbus
osbuilder: Enable dbus in the dracut case
2023-04-13 19:03:15 +02:00
Greg Kurz
eb1762e813 osbuilder: Enable dbus in the dracut case
The agent now offloads cgroup configuration to systemd when
possible. This requires to enable D-Bus in order to communicate
with systemd.

Fixes #6657

Signed-off-by: Greg Kurz <groug@kaod.org>
2023-04-13 14:16:50 +02:00
Greg Kurz
f9a94f8fc5 Merge pull request #6623 from UiPath/fix-no-space-device
runtime: Don't create socket file in /run/kata
2023-04-13 10:36:20 +02:00
Fabiano Fidêncio
f478b9115e clh: tdx: Update timeouts for confidential guest
Booting up TDX takes more time than booting up a normal VM.  Those
values are being already used as part of the CCv0 branch, and we're just
bringing them to the `main` branch as well.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
3b76abb366 kata-deploy: Ensure node is ready after CRI Engine restart
Let's ensure the node is ready after the CRI Engine restart, otherwise
we may proceed and scripts may simply fail if they try to deploy a pod
while the CRI Engine is not yet restarted (and, consequently, the node
is not Ready).

Related: #6649

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
5ec9ae0f04 kata-deploy: Use readinessProbe to ensure everything is ready
readinessProbe will help us to only have the kata-deploy pod marked as
Ready when it finishes all the needed configurations in the node.

Related: #6649

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
ea386700fe kata-deploy: Update podOverhead for TDX
As TEEs cannot hotplug memory / CPU, we *must* consider the default
values for those as part of the podOverhead.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
e31efc861c gha: tdx: Use the k3s overlay
As the TDX machine is using k3s, let's make sure we're deploying
kat-deploy using the k3s overlay.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
542bb0f3f3 gha: tdx: Set KUBECONFIG env at the job level
By doing this we avoid having to set it up on every step.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
d7fdf19e9b gha: tdx: Delete kata-deploy after the tests finish
We must ensure that no kata-deploy is left behind after the tests
finish, otherwise it may interfere with the next run.

Fixes: #6647

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Fabiano Fidêncio
da35241a91 tests: k8s: Skip k8s-cpu-ns when testing TDX
TEEs do not support CPU / memory hotplug, thus this test must be
skipped.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-13 10:18:07 +02:00
Alexandru Matei
db2cac34d8 runtime: Don't create socket file in /run/kata
The socket file for shim management is created in /run/kata
and it isn't deleted after the container is stopped. After
running and stopping thousands of containers /run folder
will run out of space.

Fixes #6622
Signed-off-by: Alexandru Matei <alexandru.matei@uipath.com>
Co-authored-by: Greg Kurz <groug@kaod.org>
2023-04-13 10:21:29 +03:00
Jianyong Wu
6d315719f0 snap: fix docker start fail issue
In Arm baseline CI, docker starts fail with error: "no sockets found via
socket activation: make sure the service was started by systemd". I find
a solusion in [1] to fix it.

[1] https://forums.docker.com/t/failed-to-load-listeners-no-sockets-found-via-socket-activation-make-sure-the-service-was-started-by-systemd/62505

Fixes: #6619
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2023-04-13 09:35:40 +08:00
Zhongtao Hu
328793bb27 Merge pull request #6585 from Apokleos/nydus_prefetch_files
nydus_rootfs/prefetch_files: add prefetch_files for RAFS
2023-04-12 19:58:36 +08:00
Zvonko Kaiser
e4b3b08871 gpu: Add proper CONFIG_LOCALVERSION depending on TEE
If conf_guest is set we need to update the CONFIG_LOCALVERSION
to match the suffix created in install_kata
-nvidia-gpu-{snp|tdx}, the linux headers will be named the very
same if build with make deb-pkg for TDX or SNP.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-12 11:30:59 +00:00
Zhongtao Hu
fef531f565 Merge pull request #6618 from Apokleos/virtiofs_extra_cache_mode
runtime-rs/virtio-fs: add support extra handler for cache mode.
2023-04-12 14:40:05 +08:00
Bin Liu
9327bb0912 Merge pull request #6639 from openanolis/nerdctl
runtime-rs: enable nerdctl to setup cni plugin
2023-04-12 12:04:37 +08:00
Zhongtao Hu
69ba2098f8 runtime-rs: remove network entities and netns
remove network entities and netns

Fixes:#4693
Signed-off-by: Zhongtao Hu <zhongtaohu.tim@linux.alibaba.com>
2023-04-12 10:21:06 +08:00
Zhongtao Hu
b31f103d12 runtime-rs: enable nerdctl cni plugin
1. when we use nerdctl to setup network for kata, no netns is created by
nerdctl, kata need to create netns by its own

2. after start VM, nerdctl will call cni plugin via oci hook, we need to
rescan the netns after the interfaces have been created, and hotplug
the network device into the VM

Fixes:#4693
Signed-off-by: Zhongtao Hu <zhongtaohu.tim@linux.alibaba.com>
2023-04-12 10:21:04 +08:00
Fabiano Fidêncio
3b3656d96d Merge pull request #6522 from fidencio/topic/add-tdx-artefacts-from-2023ww01-to-main
tdx: Add artefacts from the latest TDX tools release into main
2023-04-11 20:43:02 +02:00
Fabiano Fidêncio
50ce33b02d Merge pull request #6205 from fengwang666/non-root-clh
runtime: support non-root for clh
2023-04-11 19:34:00 +02:00
Fabiano Fidêncio
4751adbea1 Merge pull request #6610 from fidencio/topic/gha-run-dragonball-k8s-tests
gha: ci-on-push: Run k8s tests with dragonball
2023-04-11 18:16:14 +02:00
Fabiano Fidêncio
69d7a959c8 gha: ci-on-push: Run tests on TDX
Now that we've added a TDX capable external runner, let's make sure we
also run the basic tests using TDX.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 16:10:35 +02:00
Fabiano Fidêncio
5a0727ecb4 kata-deploy: Ship kata-qemu-tdx runtimeClass
Let's make sure we configure containerd for the kata-qemu-tdx handler
and ship the kata-qemu-tdx runtime class for kubernetes.

Fixes: #6537

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 16:10:35 +02:00
Fabiano Fidêncio
98682805be config: Add configuration for QEMU TDX
As the QEMU configuration for TDX differs quite a lot from the normal
QEMU configuration, let's add a new configuration file for the QEMU TDX.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 16:10:35 +02:00
Fabiano Fidêncio
3e15800199 govmm: Directly pass the firmware using -bios with TDX
Since TDX doesn't support readonly memslot, TDVF cannot be mapped as
pflash device and it actually works as RAM. "-bios" option is chosen to
load TDVF.

OVMF is the opensource firmware that implements the TDVF support. Thus
the command line to specify and load TDVF is ``-bios OVMF.fd``

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
3c5ffb0c85 govmm: Set "sept-ve-disable=on"
This is needed since 22ww49.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
ed145365ec runtime/qemu: Drop "kvm-type=tdx"
This is not supported since 22ww49.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
25b3cdd38c virtcontainers: Drop check for the tdx CPU flag
In the recent kernels provided by Intel the `tdx` CPU flag is not
present anymore.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
01bdacb4e4 virtcontainers: Also check /sys/firmwares/tdx for TDX
Let's make sure we also check /sys/firmwares/tdx for TDX guest
protection, as the location may depend on whether TDX Seam is being used
or not.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
9feec533ce cache: Add ability to cache OVMF
Let's add the ability to cache OVMF, which right now we're only building
and shipping it for TDX.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
ce8d982512 gha: Build and ship the OVMF for TDX
Let's build the OVMF with TDX support as part of our tests, and let's
ship it as part of our releases.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
39c3fab7b1 local-build: Add support to build OVMF for TDX
Let's add the needed targets and modifications to be able to build
OVMF for TDX as part of the local-build scripts.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
054174d3e6 versions: Bump OVMF for TDX
Let's update the OVMF for TDX version to what's the latest tested
release of the Intel TDX tools with Kata Containers.

This change requires a newer version of `nasm` than the one provided by
the container used to build the project.  This change will also be
needed for SEV-SNP and was originally done by Alex Carter (thanks!).

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
800fb49da1 packaging: Add get_ovmf_image_name() helper
As we'll be using this from different places in the near future, let's
create a helper function as part of the libs.sh.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
fbf03d7aca cache: Document kernel-tdx-experimental
Let's make users aware of the cache_components_main.sh that they can
also cache the kernel-tdx-experimental builds.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
5d79e96966 cache: Add a space to ease the reading of the kernel flavours
Right now it's quite hard to read those, let's improve it a little bit.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
6e4726e454 cache: Fix typos
Let's just fix a few simple typos:
* kernek -> kernel
* experimetnal -> experimental

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
fc22ed0a8a gha: Build and ship the Kernel for TDX
Let's build the kernel with TDX support as part of our tests, and let's
ship it as part of our releases.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
502844ced9 local-build: Add support to build Kernel for TDX
Let's add the needed targets and modifications to be able to build
kernel-tdx-experimental as part of the local-build scripts.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
b2585eecff local-build: Avoid code duplication building the kernel
Let's create a `install_kernel_helper()` function, as it was already
done for QEMU, and rely on that when calling `install_kernel` and
`install_kernel_dragonball_experimental`.

This helps us to reduce the code duplication by a fair amount.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
f33345c311 versions: Update Kernel TDX version
Let's update the Kernel TDX version to what's the latest tested release
of the Intel TDX tools with Kata Containers.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
20ab2c2420 versions: Move Kernel TDX to its own experimental entry
Although we've been providing users a way to build kernel with TDX
support, this must be moved to its own experimental entry instead of how
it currently is.

The reason for that is because the patches are not yet merged into
kernel, and this is still an experimental build of the project.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
3d9ce3982b cache: Allow specifying the QEMU_FLAVOUR
Let's do what we already did when caching the kernel, and allow passing
a FLAVOUR of the project to build.

By doing this we can re-use the same function used to cache QEMU to also
cache any kind of experimental QEMU that we may happen to have.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
33dc6c65aa gha: Build and ship QEMU for TDX
Let's build QEMU TDX as part of our tests, and let's ship it as part of
our releases.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
eceaae30a5 local-build: Add support to build QEMU for TDX
Let's add the needed targets and modifications to be able to build
qemu-tdx-experimental as part of the local-build scripts.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:23:42 +02:00
Fabiano Fidêncio
f7b7c187ec static-build: Improve qemu-experimental build script
Let's make sure the `qemu_suffix` and `qemu_tarball_name` can be
specified.  With this we make it really easy to reuse this script for
any addition flavour of an experimental QEMU that ends up having to be
built (specifically looking at the ones for Confidential Containers
here).

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
3018c9ad51 versions: Update QEMU TDX version
Let's update the QEMU TDX version to what's the latest tested release of
the Intel TDX tools with Kata Containers.

In order to do such update, we had to relax the checks on the QEMU
version for some of the configuration options, as those were removed
right after the window was open for the 7.1.0 development (thus the
7.0.50 check).

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
800ee5cd88 versions: Move QEMU TDX to its own experimental entry
Although we've been providing users a way to build QEMU with TDX
support, this must be moved to its own experimental entry instead of how
it currently is.

The reason for that is because the patches are not yet merged into QEMU,
and this is still an experimental build of the project.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
1315bb45f9 local-build: Add dragonball kernel to the all target
As the dragonball kernel is shipped as part of our releases, it must be
added to the `all` target.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
73e108136a local-build: Rename non vanilla kernel build functions
In order to make it easier to read, let's just rename the
install_dragonball_experimental_kernel and install_experimental_kernel
to install_kernel_dragonball_experimental and
install_kernel_experimental, respectively.

This allows us to quickly get to those functions when looking for
`install_kernel`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
1d851b4be3 local-build: Cosmetic changes in build targets
This is a simple cosmetic change, adding a space between the function
call and the `;;`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 15:17:04 +02:00
Fabiano Fidêncio
49ce685ebf gha: k8s-on-aks: Always delete the AKS cluster
Regardless of the tests succeeding or failing, the AKS cluster **must be
deleted**.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 13:40:40 +02:00
Fabiano Fidêncio
e2a770df55 gha: ci-on-push: Run k8s tests with dragonball
Now that the infra for running dragonball tests has been enabled, let's
actually make sure to have them running on each PR.

The tests skipped are:
* `k8s-cpu-ns.bats`, as CPU resize doesn't seem to be yet properly
  supported on runtime-rs
  * https://github.com/kata-containers/kata-containers/issues/6621

Fixes: #6605

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-11 11:47:47 +02:00
Fabiano Fidêncio
aee6174a53 Merge pull request #6637 from gkurz/cpu-shares-to-weight
rustjail: Use CPUWeight with systemd and CgroupsV2
2023-04-11 10:55:48 +02:00
GabyCT
dc74133e74 Merge pull request #6631 from fidencio/topic/gha-create-delete-aks-cannot-be-workflows
gha: k8s-on-aks: {create,delete} AKS must be a coded-in step
2023-04-10 14:05:24 -06:00
Zhongtao Hu
8cdec5707e Merge pull request #6540 from houstar/main
docs: update the rust version from version.yaml
2023-04-10 16:53:21 +08:00
Qingyuan Hou
d1f550bd1e docs: update the rust version from versions.yaml
Fixes: #6539
Signed-off-by: Qingyuan Hou <lenohou@gmail.com>
2023-04-10 03:34:15 +00:00
alex.lyn
f3595e48b0 nydus_rootfs/prefetch_files: add prefetch_files for RAFS
A sandbox annotation used to specify prefetch_files.list
path the container image being used, and runtime will pass
it to Hypervisor to search for corresponding prefetch file:
format looks like:
"io.katacontainers.config.hypervisor.prefetch_files.list"
      = /path/to/<uid>/xyz.com/fedora:36/prefetch_file.list

Fixes: #6582

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2023-04-10 10:05:52 +08:00
Zhongtao Hu
3bfaafbf44 fix: oci hook
1. when do the deserialization for the oci hook, we should use camel
case for createRuntime

2. we should pass the dir of bundle path instead of the path of
config.json

Fixes:#4693
Signed-off-by: Zhongtao Hu <zhongtaohu.tim@linux.alibaba.com>
2023-04-10 09:53:43 +08:00
Greg Kurz
c1fbaae8d6 rustjail: Use CPUWeight with systemd and CgroupsV2
The CPU shares property belongs to CgroupsV1. CgroupsV2 uses CPU weight
instead. The correct value is computed in the latter case but it is passed
to systemd using the legacy property. Systemd rejects the request and the
agent exists with the following error :

        Value specified in CPUShares is out of range: unknown

Replace the "shares" wording with "weight" in the CgroupsV2 code to
avoid confusions. Use the "CPUWeight" property since this is what
systemd expects in this case.

Fixes #6636

References:

https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#CPUWeight=weight
https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#systemd%20252
https://github.com/containers/crun/blob/main/crun.1.md#cpu-controller

Signed-off-by: Greg Kurz <groug@kaod.org>
2023-04-07 17:57:26 +02:00
Bo Chen
375187e045 versions: Upgrade to Cloud Hypervisor v31.0
Details of this release can be found in our new roadmap project as
iteration v31.0: https://github.com/orgs/cloud-hypervisor/projects/6.

Fixes: #6632

Signed-off-by: Bo Chen <chen.bo@intel.com>
2023-04-06 14:35:26 -07:00
Fabiano Fidêncio
79f3047f06 gha: k8s-on-aks: {create,delete} AKS must be a coded-in step
I should have seen this coming, but currently the "create" and "delete"
AKS workflows cannot be imported and uses as a job's step, resulting on
an error trying to find the correspondent action.yaml file for those.

Fixes: #6630

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 22:56:08 +02:00
Fabiano Fidêncio
ee5dda012b Merge pull request #6629 from fidencio/topic/gha-refactor-run-k8s-tests-on-aks
gha: k8s-on-aks: Set {create,delete}_aks as steps
2023-04-06 22:02:34 +02:00
Fabiano Fidêncio
2f35b4d4e5 gha: ci-on-push: Only run on main branch
Let's ensure we're only running this workflow when PRs are opened
against the main branch.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 19:11:24 +02:00
Fabiano Fidêncio
e7bd2545ef Revert "gha: ci-on-push: Depend on Commit Message Check"
This reverts commit a159ffdba7.

Unfortunately we have to revert the PRs related to the switch done to
using `workflow_run` instead of `pull_request_target`.  The reason for
that being that we can only mark jobs as required if they are targetting
PRs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 19:11:14 +02:00
Fabiano Fidêncio
0d96d49633 Revert "gha: ci-on-push: Adjust to using workflow_run"
This reverts commit 3a760a157a.

Unfortunately we have to revert the PRs related to the switch done to
using `workflow_run` instead of `pull_request_target`.  The reason for
that being that we can only mark jobs as required if they are targetting
PRs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 19:11:06 +02:00
Fabiano Fidêncio
c7ee45f7e5 Revert "gha: ci-on-push: Adapt chained jobs to workflow_run"
This reverts commit 7855b43062.

Unfortunately we have to revert the PRs related to the switch done to
using `workflow_run` instead of `pull_request_target`.  The reason for
that being that we can only mark jobs as required if they are targetting
PRs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 19:09:54 +02:00
Fabiano Fidêncio
5d4d720647 Revert "gha: k8s-on-aks: Fix cluster name"
This reverts commit 85cc5bb534.

Unfortunately we have to revert the PRs related to the switch done to
using `workflow_run` instead of `pull_request_target`.  The reason for
that being that we can only mark jobs as required if they are targetting
PRs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 19:07:04 +02:00
Fabiano Fidêncio
13d857a56d gha: k8s-on-aks: Set {create,delete}_aks as steps
We've been currently using {create,delete}_aks as jobs.  However, it
means that if the tests fail we'll end up deleting the AKS cluster (as
expected), but not having a way to recreate the cluster without
re-running all jobs, which is a waste of resources.

Fixes: #6628

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 16:54:15 +02:00
Fabiano Fidêncio
abaf881f4a Merge pull request #6612 from fidencio/topic/gha-k8s-on-aks-fix-cluster-name
gha: k8s-on-aks: Fix cluster name
2023-04-06 10:48:38 +02:00
alex.lyn
dc6569dbbc runtime-rs/virtio-fs: add support extra handler for cache mode.
Add support for virtiofsd when virtio_fs_extra_args with
"-o cache auto, ..." users specified.

Fixes: #6615

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2023-04-06 16:31:02 +08:00
Fabiano Fidêncio
85cc5bb534 gha: k8s-on-aks: Fix cluster name
This was missed from the last series, as GHA will use the "target
branch" yaml file to start the workflow.

Basically we changed the name of the cluster created to stop relying on
the PR number, as that's not easily accessible on `workflow_run`.

Fixes: #6611

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-06 08:50:07 +02:00
Fabiano Fidêncio
68cb5689f5 Merge pull request #6584 from fidencio/topic/gha-k8s-also-test-dragonball
gha: Also run k8s tests on AKS with dragonball
2023-04-05 22:50:14 +02:00
Fabiano Fidêncio
ae488cc09f Merge pull request #6596 from fidencio/topic/gha-only-push-to-registry-when-merging-content
gha: Only push images to registry after merging a PR
2023-04-05 22:07:13 +02:00
Fabiano Fidêncio
2c38e17ef0 Merge pull request #6607 from fidencio/topic/gha-switch-to-using-a-D4_v5-instance
gha: aks: Use D4s_v5 instance
2023-04-05 22:06:40 +02:00
Archana Shinde
6af52cef3a Merge pull request #6590 from zvonkok/build-kernel-fix
tools: Avoid building the kernel twice
2023-04-05 11:45:59 -07:00
Greg Kurz
a3e3b0591f Merge pull request #6562 from c3d/issue/6561-unwrap-panic
rustjail: Fix panic when cgroup manager fails
2023-04-05 16:58:13 +02:00
James O. D. Hunt
cbe6f04194 Merge pull request #6501 from shippomx/dev_metrics
runtime: add filter metrics with specific names
2023-04-05 15:15:09 +01:00
Fabiano Fidêncio
1688e4f3f0 gha: aks: Use D4s_v5 instance
It's been pointed out that D4s_v5 instances are more powerful than the
D4s_v3 ones, and have the very same price.  With this in mind, let's
switch to the newer machines.

Fixes: #6606

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 16:02:17 +02:00
Fabiano Fidêncio
108d80a86d gha: Add the ability to also test Dragonball
With the changes proposed as part of this PR, an AKS cluster will be
created but no tests will be performed.

The reason we have to do this is because GitHub Actions will only run
the tests using the workflows that are part of the **target** branch,
instead of the using the ones coming from the PR, and we didn't find yet
a way to work this around.

Once this commit is in, we'll actually change the tests themselves (not
the yaml files for the actions), as those will be the ones we want as
the checkout action helps us on this case.

Fixes: #6583

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 15:53:03 +02:00
Fabiano Fidêncio
2550d4462d gha: build-kata-static-tarball: Only push to registry after merge
56331bd7bc oversaw the fact that we
mistakenly tried to push the build containers to the registry for a PR,
rather than doing so only when the code is merged.

As the workflow is now shared between different actions, let's introduce
an input variable to specify which are the cases we actually need to
perform a push to the registry.

Fixes: #6592

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 13:57:26 +02:00
Fabiano Fidêncio
e81b8b8ee5 local-build: build-and-upload-payload is not quay.io specific
Let's just print "to the registry" instead of printing "to quay.io", as
the registry used is not tied to quay.io.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:44 +02:00
Fabiano Fidêncio
13929fc610 gha: publish-kata-deploy-payload: Improve registry login
Let's only try to login to the registry that's being passed as an input
argument.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:44 +02:00
Fabiano Fidêncio
41026f003e gha: payload-after-push: Pass registry / repo as inputs
We made registry / repo mandatory, but we only adapted that to the amd64
job.  Let's fix it now and make sure this is also passed to the arm64
and s390x jobs.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:44 +02:00
Fabiano Fidêncio
7855b43062 gha: ci-on-push: Adapt chained jobs to workflow_run
As we're using the `workflow_run` event, the checkout action would
pull the **current target branch** instead of the PR one.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:44 +02:00
Fabiano Fidêncio
3a760a157a gha: ci-on-push: Adjust to using workflow_run
The way previously used to get the PR's commit sha can only be used with
`pull_request*` kind of events.

Let's adapt it to the `workflow_run` now that we're using it.

With this change we ended up dropping the PR number from the tarball
suffix, as that's not straightforward to get and, to be honest, not a
unique differentiator that would justify the effort.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:44 +02:00
Fabiano Fidêncio
a159ffdba7 gha: ci-on-push: Depend on Commit Message Check
Let's make this workflow dependent of the commit message check, and only
start it if the commit message check one passes.

As a side effect, this allows us to run this specific workflow using
secrets, without having to rely on `pull_request_target`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-05 12:54:40 +02:00
Fabiano Fidêncio
8086c75f61 gha: Also run k8s tests on AKS with dragonball
As already done for Cloud Hypervisor and QEMU, let's make sure we can
run the AKS tests using dragonball.

Fixes: #6583

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-04 10:58:47 +02:00
Fabiano Fidêncio
1c6d7cb0f7 Merge pull request #6589 from fidencio/topic/gha-k8s-use-ghcr-instead-of-quay
gha: Use ghcr.io for the k8s CI
2023-04-04 10:48:16 +02:00
Zvonko Kaiser
fe86c08a63 tools: Avoid building the kernel twice
Two different kernel build targets (build,install) have both instructions to
build the kernel, hence it was executed twice. Install should only do
install and build should only do build.

Fixes: #6588

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2023-04-04 05:44:44 +00:00
Fabiano Fidêncio
3215860a47 gha: Set ci-on-push to run on pull_request_target
This is less secure than running the PR on `pull_request`, and will
require using an additional `ok-to-test` label to make sure someone
deliverately ran the actions coming from a forked repo.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-03 20:50:36 +02:00
Fabiano Fidêncio
d17dfe4cdd gha: Use ghcr.io for the k8s CI
Let's switch to using the `ghcr.io` registry for the k8s CI, as this
will save us some troubles on running the CI with PRs coming from forked
repos.

Fixes: #6587

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-04-03 15:52:33 +02:00
Fabiano Fidêncio
e1f972fb1d Merge pull request #6568 from kata-containers/topic/add-k8s-tests-as-part-of-gha
GHA |Switch "kubernetes tests" from jenkins to GitHub actions
2023-04-03 14:25:35 +02:00
Christophe de Dinechin
b661e0cf3f rustjail: Add anyhow context for D-Bus connections
In cases where the D-Bus connection fails, add a little additional context about
the origin of the error.

Fixes: 6561

Signed-off-by: Christophe de Dinechin <dinechin@redhat.com>
Suggested-by: Archana Shinde <archana.m.shinde@intel.com>
Spell-checked-by: Greg Kurz <gkurz@redhat.com>
2023-04-03 14:09:34 +02:00
Fabiano Fidêncio
60c62c3b69 gha: Remove kata-deploy-test.yaml
This workflow becomes redundant as we're already testing kubernetes
using kata-deploy, and also testing it on AKS.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
Fabiano Fidêncio
43894e9459 gha: Remove kata-deploy-push.yaml
This becomes redundant now that its steps are covered as part of the
`ci-on-push.yaml`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
Fabiano Fidêncio
cab9ca0436 gha: Add a CI pipeline for Kata Containers
This is the very first step to replacing the Jenkins CI, and I've
decided to start with an x86_64 approach only (although easily
expansible for other arches as soon as they're ready to switch), and to
start running our kubernetes tests (now running on AKS).

Fixes: #6541

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
Fabiano Fidêncio
53b526b6bd gha: k8s: Add snippet to run k8s tests on aks clusters
This will be shortly used as part of a newly created GitHub action which
will replace our Jenkins CI.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
Fabiano Fidêncio
c444c24bc5 gha: aks: Add snippets to create / delete aks clusters
Those will be shortly used as part of a newly added GitHub action for
testing k8s tests on Azure.

They've been created using the secrets we already have exposed as part
of our GitHub, and they follow a similar way to authenticate to Azure /
create an AKS cluster as done in the `/test-kata-deploy` action.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
Fabiano Fidêncio
11e0099fb5 tests: Move k8s tests to this repo
The first part of simplifying things to have all our tests using GitHub
actions is moving the k8s tests to this repo, as those will be the first
vict^W targets to be migrated to GitHub actions.

Those tests have been slightly adapted, mainly related to what they load
/ import, so they are more self-contained and do not require us bringing
a lot of scripts from the tests repo here.

A few scripts were also dropped along the way, as we no longer plan to
deploy kubernetes as part of every single run, but rather assume there
will always be k8s running whenever we land to run those tests.

It's important to mention that a few tests were not added here:

* k8s-block-volume:
* k8s-file-volume:
* k8s-volume:
* k8s-ro-volume:
  These tests depend on some sort of volume being created on the
  kubernetes node where the test will run, and this won't fly as the
  tests will run from a GitHub runner, targetting a different machine
  where kubernetes will be running.
  * https://github.com/kata-containers/kata-containers/issues/6566

* k8s-hugepages: This test depends a whole lot on the host where it
  lands and right now we cannot assume anything about that anymore, as
  the tests will run from a GitHub runner, targetting a different
  machine where kubernetes will be running.
  * https://github.com/kata-containers/kata-containers/issues/6567

* k8s-expose-ip: This is simply hanging when running on AKS and has to
  be debugged in order to figure out the root cause of that, and then
  adapted to also work on AKS.
  * https://github.com/kata-containers/kata-containers/issues/6578

Till those issues are solved, we'll keep running a jenkins job with
hose tests to avoid any possible regression.

Last but not least, I've decided to **not** keep the history when
bringing those tests here, otherwise we'd end up polluting a lot the
history of this repo, without any clear benefit on doing so.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 21:55:41 +02:00
David Esparza
5d89d08fc4 Merge pull request #6564 from GabyCT/topic/updateneturl
docs: Update CNM url in networking document
2023-03-31 09:58:55 -06:00
Fabiano Fidêncio
73be4bd3f9 gha: Update actions for release.yaml
checkout@v2 should not be used anymore, please, see:
https://github.blog/changelog/2022-09-22-github-actions-all-actions-will-begin-running-on-node16-instead-of-node12/

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 13:24:26 +02:00
Fabiano Fidêncio
d38d7fbf1a gha: Remove code duplication from release.yaml
We can easily re-use the newly added build-kata-static-tarball-*.yaml as
part of the release.yaml file.

By doing this we consolidate on how we build the components accross our
actions.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 13:24:26 +02:00
Fabiano Fidêncio
56331bd7bc gha: Split payload-after-push-*.yaml
Let's split those actions into two different ones:
* Build the kata-static tarball
* Publish the kata-deploy payload

We're doing this as, later in this series we'll start taking advantage
of both pieces.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-31 13:24:26 +02:00
Gabriela Cervantes
a552a1953a docs: Update CNM url in networking document
This PR updates the url for the Container Network Model
in the network document.

Fixes #6563

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-30 16:20:33 +00:00
Christophe de Dinechin
7796e6ccc6 rustjail: Fix minor grammatical error in function name
Rename `unit_exist` function to `unit_exists` to match English grammar rule.

Fixes: #6561

Signed-off-by: Christophe de Dinechin <dinechin@redhat.com>
2023-03-30 16:13:37 +02:00
Christophe de Dinechin
41fdda1d84 rustjail: Do not unwrap potential error with cgroup manager
There can be an error while connecting to the cgroups managager, for
example a `ENOENT` if a file is not found. Make sure that this is
reported through the proper channels instead of causing a `panic()`
that does not provide much information.

Fixes: #6561

Signed-off-by: Christophe de Dinechin <dinechin@redhat.com>
Reported-by: Greg Kurz <gkurz@redhat.com>
2023-03-30 16:09:13 +02:00
Archana Shinde
07e49c63e1 Merge pull request #6257 from amshinde/kata-ctl-env
kata-ctl: add function to get platform protection.
2023-03-29 11:55:07 -07:00
Archana Shinde
a914283ce0 kata-ctl: add function to get platform protection.
This function checks for tdx, sev or snp protection on x86
platform.

Fixes: #1000

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-03-28 15:40:25 -07:00
Fabiano Fidêncio
245ed2cecf Merge pull request #6536 from gkurz/3.2.0-alpha0-branch-bump
# Kata Containers 3.2.0-alpha0
2023-03-28 16:05:10 +02:00
Wainer Moschetta
d0f79e66b9 Merge pull request #6513 from fidencio/topic/use-kata-deploy-local-build-as-part-of-the-snap-stuff
snap: Build the artefacts using kata-deploy
2023-03-28 09:59:31 -03:00
Miao Xia
0f73515561 runtime: add filter metrics with specific names
The kata monitor metrics API returns a huge size response,
if containers or sandboxs are a large number,
focus on what we need will be harder.

Fixes: #6500

Signed-off-by: Miao Xia <xia.miao1@zte.com.cn>
2023-03-28 14:56:13 +08:00
Greg Kurz
4a246309ee release: Kata Containers 3.2.0-alpha0
- nydus: upgrad to v2.2.0
- osbuilder: Add support for CBL-Mariner
- kata-deploy: Fix bash semantics error
- make only_kata work without -f
- runtime-rs: ch: Implement confidential guest handling
- qemu/arm64: disable image nvdimm once no firmware offered
- static checks workflow improvements
- A couple of kata-deploy fixes
- agent: Bring in VFIO-AP device handling again
- bugfix: set hostname in CreateSandboxRequest
- packaging / kata-deploy builds:  Add the ability to cache and consume cached components
- versions: Update firecracker version
- dependency: update cgroups-rs
- Built-in Sandbox: add more unit tests for dragonball. Part 6
- runtime: add support for Hyper-V
- runtime-rs: update load_config comment
- Add support for ephemeral mounts to occupy entire sandbox's memory
- runtime-rs: fix default kernel location and add more default config paths
- Implement direct-volume commands handler for shim-mgmt
- bugfix: modify tty_win info in runtime when handling ResizePtyRequest
- bugfix: add get_ns_path API for Hypervisor
- runtime-rs: add the missing default trait
- packaging: Simplify get_last_modification()
- utils: Make kata-manager.sh runs checks
- dragonball: support pmu on aarch64
- docs: fix typo in key filename in AWS installation guide
- backport rustjail systemd cgroup fix #6331 to 3.1
- main | kata-deploy: Fix kata deploy arm64 image build error
- workflows: Yet more fixes for publishing the kata-deploy payload after every PR merged
- rustjail: fix cgroup handling in agent-init mode
- runtime/Makefile: Fix install-containerd-shim-v2 dependency
- fix wrong notes for func GetSandboxesStoragePathRust()
- fix(runtime-rs): add exited state to ensure cleanup
- runtime-rs: add oci hook support
- utils: Remove kata-manager.sh cgroups v2 check
- workflows:  Fixes for the `payload-after-push` action
- Dragonball: update dependencies
- workflows: Do not install docker
- workflows: Publish kata-deploy payload after a merge
- src: Fixed typo mod.rs
- actions: Use `git-diff` to get changes in kernel dir
- agent: don't set permission of existing directory in copy_file
- runtime: use filepath.Clean() to clean the mount path
- Upgrade to Cloud Hypervisor v30.0
- feat(runtime): make static resource management consistent with 2.0
- osbuilder: Include minimal set of device nodes in ubuntu initrd
- kata-ctl/exec: add new command exec to enter guest VM.
- kernel: Add CONFIG_SEV_GUEST to SEV kernel config
- runtime-rs: Improve Cloud Hypervisor config handling
- virtiofsd: update to a valid path on ppc64le
- runtime-rs: cleanup kata host share path
- osbuilder: fix default build target in makefile
- devguide: Add link to the contribution guidelines
- kata-deploy: Ensure go binaries can run on Ubuntu 20.04
- dragonball: config_manager: preserve device when update
- Revert "workflows: Push the builder image to quay.io"
- Remove all remaining unsafe impl
- kata-deploy: Fix building the kata static firecracker arm64 package occurred an error
- shim-v2: Bump Ubuntu container image  to 22.04
- packaging: Cache the container used to build the kata-deploy artefacts
- utils: always check some dependencies.
- versions: Use ubuntu as the default distro for the rootfs-image
- github-action: Replace deprecated command with environment file
- docs: Change the order of release step
- runtime-rs: remove unnecessary Send/Sync trait implement
- runtime-rs: Don't build on Power, don't break on Power.
- runtime-rs: handle sys_dir bind volume
- sandbox: set the dns for the sandbox
- packaging/shim-v2: Only change the config if the file exists
- runtime-rs: Add basic CH implementation
- release: Revert kata-deploy changes after 3.1.0-rc0 release

8b008fc743 kata-deploy: fix bash semantics error
74ec38cf02 osbuilder: Add support for CBL-Mariner
ac58588682 runtime-rs: ch: Generate Cloud Hypervisor config for confidential guests
96555186b3 runtime-rs: ch: Honour debug setting
e3c2d727ba runtime-rs: ch: clippy fix
ece5edc641 qemu/arm64: disable image nvdimm if no firmware offered
dd23f452ab utils: renamed only_kata to skip_containerd
59c81ed2bb utils: informed pre-check about only_kata
4f0887ce42 kata-deploy: fix install failing to chmod runtime-rs/bin/*
09c4828ac3 workflows: add missing artifacts on payload-after-push
fbf891fdff packaging: Adapt `get_last_modification()`
82a04dbce1 local-build: Use cached VirtioFS when possible
3b99004897 local-build: Use cached shim v2 when possible
1b8c5474da local-build: Use cached RootFS when possible
09ce4ab893 local-build: Use cached QEMU when possible
1e1c843b8b local-build: Use cached Nydus when possible
64832ab65b local-build: Use cached Kernel when possible
04fb52f6c9 local-build: Use cached Firecracker when possible
8a40f6f234 local-build: Use cached Cloud Hypervisor when possible
194d5dc8a6 tools: Add support for caching VirtioFS artefacts
a34272cf20 tools: Add support for caching shim v2 artefacts
7898db5f79 tools: Add support for caching RootFS artefacts
e90891059b tools: Add support for caching QEMU artefacts
7aed8f8c80 tools: Add support for caching Nydus artefacts
cb4cbe2958 tools: Add support for caching Kernel artefacts
762f9f4c3e tools: Add support for caching Firecracker artefacts
6b1b424fc7 tools: Add support for caching Cloud Hypervisor artefacts
08fe49f708 versions: Adjust kernel names to match kata-deploy build targets
99505c0f4f versions: Update firecracker version
f4938c0d90 bugfix: set hostname
96baa83895 agent: Bring in VFIO-AP device handling again
f666f8e2df agent: Add VFIO-AP device handling
b546eca26f runtime: Generalize VFIO devices
4c527d00c7 agent: Rename VFIO handling to VFIO PCI handling
db89c88f4f agent: Use cfg-if for s390x CCW
68a586e52c agent: Use a constant for CCW root bus path
a8b55bf874 dependency: update cgroups-rs
97cdba97ea runtime-rs: update load_config comment
974a5c22f0 runtime: add support for Hyper-V
40f4eef535 build: Use the correct kernel name
a6c67a161e runtime: add support for ephemeral mounts to occupy entire sandbox memory
844bf053b2 runtime-rs: add the missing default trait
e7bca62c32 bugfix: modify tty_win info in runtime when handling ResizePtyRequest
30e235f0a1 runtime-rs: impl volume-resize trait for sandbox
e029988bc2 bugfix: add get_ns_path API for Hypervisor
42b8867148 runtime-rs: impl volume-stats trait for sandbox
462d4a1af2 workflows: static-checks: Free disk space before running checks
e68186d9af workflows: static-checks: Set GOPATH only once
439ff9d4c4 tools/osbuilder/tests: Remove TRAVIS variable
43ce3f7588 packaging: Simplify get_last_modification()
33c5c49719 packaging: Move repo_root_dir to lib.sh
16e2c3cc55 agent: implement update_ephemeral_mounts api
3896c7a22b protocol: add updateEphemeralMounts proto
23488312f5 agent: always use cgroupfs when running as init
8546387348 agent: determine value of use_systemd_cgroup before LinuxContainer::new()
736aae47a4 rustjail: print type of cgroup manager
dbae281924 workflows: Properly set the kata-tarball architecture
76b4591e2b tools: Adjust the build-and-upload-payload.sh script
cd2aaeda2a kata-deploy: Switch to using an ubuntu image
2d43e13102 docs: fix typo in AWS installation guide
760f78137d dragonball: support pmu on aarch64
9bc7bef3d6 kata-deploy: Fix path to the Dockerfile
78ba363f8e kata-deploy: Use different images for s390x and aarch64
6267909501 kata-deploy: Allow passing BASE_IMAGE_{NAME,TAG}
3443f558a6 nydus: upgrad nydus to v2.2.0
395645e1ce runtime: hybrid-mode cause error in the latest nydusd
f8e44172f6 utils: Make kata-manager.sh runs checks
f31c79d210 workflows: static-checks: Remove TRAVIS_XXX variables
8030e469b2 fix(runtime-rs): add exited state to ensure cleanup
7d292d7fc3 workflows: Fix the path of imported workflows
e07162e79d workflows: Fix action name
dd2713521e Dragonball: update dependencies
bd1ed26c8d workflows: Publish kata-deploy payload after a merge
fea7e8816f runtime-rs: Fixed typo mod.rs
a9e2fc8678 runtime/Makefile: Fix install-containerd-shim-v2 dependency
b6880c60d3 logging: Correct the code notes
12cfad4858 runtime-rs: modify the transfer to oci::Hooks
828d467222 workflows: Do not install docker
4b8a5a1a3d utils: Remove kata-manager.sh cgroups v2 check
2c4428ee02 runtime-rs: move pre-start hooks to sandbox_start
e80c9f7b74 runtime-rs: add StartContainer hook
977f281c5c runtime-rs: add CreateContainer hook support
875f2db528 runtime-rs: add oci hook support
ecac3a9e10 docs: add design doc for Hooks
3ac6f29e95 runtime: clh: Re-generate the client code
262daaa2ef versions: Upgrade to Cloud Hypervisor v30.0
192df84588 agent: always use cgroupfs when running as init
b0691806f1 agent: determine value of use_systemd_cgroup before LinuxContainer::new()
dc86d6dac3 runtime: use filepath.Clean() to clean the mount path
c4ef5fd325 agent: don't set permission of existing directory
3483272bbd runtime-rs: ch: Enable initrd usage
fbee6c820e runtime-rs: Improve Cloud Hypervisor config handling
1bff1ca30a kernel: Add CONFIG_SEV_GUEST to SEV kernel config Adding kernel config to sev case since it is needed for SNP and SNP will use the SEV kernel. Incrementing kernel config version to reflect changes
ad8968c8d9 rustjail: print type of cgroup manager
b4a1527aa6 kata-deploy: Fix static shim-v2 build on arm64
2c4f8077fd Revert "shim-v2: Bump Ubuntu container image  to 22.04"
afaccf924d Revert "workflows: Push the builder image to quay.io"
4c39c4ef9f devguide: Add link to the contribution guidelines
76e926453a osbuilder: Include minimal set of device nodes in ubuntu initrd
697ec8e578 kata-deploy: Fix kata static firecracker arm64 package build error
ced3c99895 dragonball: config_manager: preserve device when update
da8a6417aa runtime-rs: remove all remaining unsafe impl
0301194851 dragonball: use crossbeam_channel in VmmService instead of mpsc::channel
9d78bf9086 shim-v2: Bump Ubuntu container image  to 22.04
3cfce5a709 utils: improved unsupported distro message.
919d19f415 feat(runtime): make static resource management consistent with 2.0
b835c40bbd workflows: Push the builder image to quay.io
781ed2986a packaging: Allow passing a container builder to the scripts
45668fae15 packaging: Use existing image to build td-shim
e8c6bfbdeb packaging: Use existing image to build td-shim
3fa24f7acc packaging: Add infra to push the OVMF builder image
f076fa4c77 packaging: Use existing image to build OVMF
c7f515172d packaging: Add infra to push the QEMU builder image
fb7b86b8e0 packaging: Use existing image to build QEMU
d0181bb262 packaging: Add infra to push the virtiofsd builder image
7c93428a18 packaging: Use existing image to build virtiofsd
8c227e2471 virtiofsd: Pass the expected toolchain to the build container
7ee00d8e57 packaging: Add infra to push the shim-v2 builder image
24767d82aa packaging: Use existing image to build the shim-v2
e84af6a620 virtiofsd: update to a valid path on ppc64le
6c3c771a52 packaging: Add infra to push the kernel builder image
b9b23112bf packaging: Use existing image to build the kernel
869827d77f packaging: Add push_to_registry()
e69a6f5749 packaging: Add get_last_modification()
6c05e5c67a packaging: Add and export BUILDER_REGISTRY
1047840cf8 utils: always check some dependencies.
95e3364493 runtime-rs: remove unnecessary Send/Sync trait implement
a96ba99239 actions: Use `git-diff` to get changes in kernel dir
619ef54452 docs: Change the order of release step
a161d11920 versions: Use ubuntu as the default distro for the rootfs-image
be40683bc5 runtime-rs: Add a generic powerpc64le-options.mk
47c058599a packaging/shim-v2: Install the target depending on the arch/libc
b582c0db86 kata-ctl/exec: add new command exec to enter guest VM.
07802a19dc runtime-rs: handle sys_dir bind volume
04e930073c sandbox: set the dns for the sandbox
32ebe1895b agent: fix the issue of creating the dns file
44aaec9020 github-action: Replace deprecated command with environment file
a68c5004f8 packaging/shim-v2: Only change the config if the file exists
ee76b398b3 release: Revert kata-deploy changes after 3.1.0-rc0 release
bbc733d6c8 docs: runtime-rs: Add CH status details
37b594c0d2 runtime-rs: Add basic CH implementation
545151829d kata-types: Add Cloud Hypervisor (CH) definitions
2dd2421ad0 runtime-rs: cleanup kata host share path
0a21ad78b1 osbuilder: fix default build target in makefile
9a01d4e446 dragonball: add more unit test for virtio-blk device.

Signed-off-by: Greg Kurz <groug@kaod.org>
2023-03-28 08:40:06 +02:00
Bin Liu
75987aae72 Merge pull request #6408 from jongwu/nydus_rm_hybrid
nydus: upgrad to v2.2.0
2023-03-28 11:07:56 +08:00
Fabiano Fidêncio
4a95375dc8 Merge pull request #6465 from dallasd1/mariner-rootfs
osbuilder: Add support for CBL-Mariner
2023-03-27 22:18:31 +02:00
Fabiano Fidêncio
43dd4440f4 snap: Build the artefacts using kata-deploy
Our CI and release process are currently taking advantage of the
kata-deploy local build scripts to build the artefacts.

Having snap doing the same is the next logical step, and it will also
help to reduce, by a lot, the CI time as we only build the components
that a PR is touching (otherwise we just pull the cached component).

Fixes: #6514

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-27 17:34:43 +02:00
Fabiano Fidêncio
293119df78 Merge pull request #6515 from xyz-li/main
kata-deploy: Fix bash semantics error
2023-03-24 13:18:10 +01:00
Chelsea Mafrica
bbc699ddd8 Merge pull request #6419 from gabevenberg/containerd-pre-check
make only_kata work without -f
2023-03-23 10:02:32 -07:00
xyz-li
8b008fc743 kata-deploy: fix bash semantics error
The argument of return must be numeric.

Fixes: #6521

Signed-off-by: xyz-li <hui0787411@163.com>
2023-03-23 22:47:54 +08:00
James O. D. Hunt
da676872b1 Merge pull request #6439 from jodh-intel/runtime-rs-ch-confidential-guest
runtime-rs: ch: Implement confidential guest handling
2023-03-23 13:01:47 +00:00
Dallas Delaney
74ec38cf02 osbuilder: Add support for CBL-Mariner
Add osbuilder support to build a rootfs and image
based on the CBL-Mariner Linux distro

Fixes: #6462

Signed-off-by: Dallas Delaney <dadelan@microsoft.com>
2023-03-22 11:45:32 -07:00
James O. D. Hunt
ac58588682 runtime-rs: ch: Generate Cloud Hypervisor config for confidential guests
This change provides a preliminary implementation for the Cloud Hypervisor (CH) feature ([currently
disabled](https://github.com/kata-containers/kata-containers/pull/6201))
to allow it to generate the CH configuration for handling confidential guests.

This change also introduces concrete errors using the `thiserror` crate
(see `src/runtime-rs/crates/hypervisor/ch-config/src/errors.rs`) and a
lot of unit tests for the conversion code that generates the CH
configuration from the generic Hypervisor configuration.

Fixes: #6430.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-03-22 14:38:38 +00:00
James O. D. Hunt
96555186b3 runtime-rs: ch: Honour debug setting
Enable Cloud Hypervisor debug based on the specified configuration
rather than hard-coding debug to be disabled.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-03-22 14:38:38 +00:00
James O. D. Hunt
e3c2d727ba runtime-rs: ch: clippy fix
Simplify the code to keep rust's `clippy` happy.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-03-22 14:38:38 +00:00
James O. D. Hunt
f06f72b5e9 Merge pull request #6467 from jongwu/qemu-uefi-path
qemu/arm64: disable image nvdimm once no firmware offered
2023-03-22 08:43:01 +00:00
Steve Horsman
adaabd141a Merge pull request #6406 from jepio/jepio/static-checks-workflow-improvements
static checks workflow improvements
2023-03-20 17:12:54 +00:00
Wainer Moschetta
20da7f3ec8 Merge pull request #6495 from wainersm/fix-kata-deploy-ci
A couple of kata-deploy fixes
2023-03-20 13:48:02 -03:00
Fabiano Fidêncio
2fe0733dcb Merge pull request #4582 from BbolroC/vfio-ap
agent: Bring in VFIO-AP device handling again
2023-03-20 11:43:13 +01:00
Jianyong Wu
ece5edc641 qemu/arm64: disable image nvdimm if no firmware offered
For now, image nvdimm on qemu/arm64 depends on UEFI/ACPI, so if there
is no firmware offered, it should be disabled.

Fixes: #6468
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2023-03-20 18:03:05 +08:00
Zhongtao Hu
1e8005ff88 Merge pull request #6477 from openanolis/runtime-rs-hostname
bugfix: set hostname in CreateSandboxRequest
2023-03-20 12:43:29 +08:00
Gabe Venberg
dd23f452ab utils: renamed only_kata to skip_containerd
Renamed for greater clarity as to what that flag does.

Signed-off-by: Gabe Venberg <gabevenberg@gmail.com>
2023-03-17 16:09:45 -05:00
Gabe Venberg
59c81ed2bb utils: informed pre-check about only_kata
passed the only_kata variable through to pre_check, only_kata does not
abort the install when containerd is already installed.

fixes #6385

Signed-off-by: Gabe Venberg <gabevenberg@gmail.com>
2023-03-17 15:58:57 -05:00
Fabiano Fidêncio
96252db787 Merge pull request #6481 from fidencio/topic/cache-artefacts
packaging / kata-deploy builds:  Add the ability to cache and consume cached components
2023-03-17 20:54:42 +01:00
Wainer dos Santos Moschetta
4f0887ce42 kata-deploy: fix install failing to chmod runtime-rs/bin/*
The kata-deploy install method tried to `chmod +x /opt/kata/runtime-rs/bin/*` but it isn't
always true that /opt/kata/runtime-rs/bin/ exists. For example, the
s390x payload does not build the kernel-dragonball-experimental
artifacts. So let's ensure the dir exist before issuing the command.

Fixes #6494
Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2023-03-17 16:09:21 -03:00
Wainer dos Santos Moschetta
09c4828ac3 workflows: add missing artifacts on payload-after-push
The kata-deploy-ci payloads for amd64 and arm64 were missing the shim-v2
and kernel-dragonball-experimental artifacts.

Fixes #6493
Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2023-03-17 15:31:21 -03:00
Fabiano Fidêncio
fbf891fdff packaging: Adapt get_last_modification()
The function is returning "" when called from the script used to cache
the artefacts and one difference noted between this version and the
already working one from the CCv0 is that we make sure to `pushd
${repo_root_dir}` in the CCv0 version.

Let's give it a try here and see if it solves the issue.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
82a04dbce1 local-build: Use cached VirtioFS when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
3b99004897 local-build: Use cached shim v2 when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
1b8c5474da local-build: Use cached RootFS when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
09ce4ab893 local-build: Use cached QEMU when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
1e1c843b8b local-build: Use cached Nydus when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
64832ab65b local-build: Use cached Kernel when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
04fb52f6c9 local-build: Use cached Firecracker when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
8a40f6f234 local-build: Use cached Cloud Hypervisor when possible
As we've added the support for caching components, let's use them
whenever those are available.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 16:27:34 +01:00
Fabiano Fidêncio
194d5dc8a6 tools: Add support for caching VirtioFS artefacts
Let's add support for caching VirtioFS artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
a34272cf20 tools: Add support for caching shim v2 artefacts
Let's add support for caching shim v2 artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
7898db5f79 tools: Add support for caching RootFS artefacts
Let's add support for caching RootFS artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
e90891059b tools: Add support for caching QEMU artefacts
Let's add support for caching QEMU artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
7aed8f8c80 tools: Add support for caching Nydus artefacts
Let's add support for caching Nydus artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
cb4cbe2958 tools: Add support for caching Kernel artefacts
Let's add support for caching Kernel artefacts that are generated using
the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:43:01 +01:00
Fabiano Fidêncio
762f9f4c3e tools: Add support for caching Firecracker artefacts
Let's add support for caching Firecracker artefacts that are generated
using the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:28:56 +01:00
Fabiano Fidêncio
6b1b424fc7 tools: Add support for caching Cloud Hypervisor artefacts
Let's add support for caching Cloud Hypervisor artefacts that are
generated using the kata-deploy local-build scripts.

Right now those are not used, but we'll switch to using them very soon
as part of upcoming changes of how we build the components we test in
our CI.

Fixes: #6480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-17 11:28:56 +01:00
Fabiano Fidêncio
08fe49f708 versions: Adjust kernel names to match kata-deploy build targets
Let's adjust the kernel names in versions.yaml so those can match the
names used as part of the kata-deploy local build scripts.

Right now this doesn't bring any benefit nor drawback, but it'll make
our life easier later on in this same series.

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

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-17 11:28:56 +01:00
Fabiano Fidêncio
d281d1b90a Merge pull request #6483 from GabyCT/topic/updatefcv
versions: Update firecracker version
2023-03-17 10:37:22 +01:00
Gabriela Cervantes
99505c0f4f versions: Update firecracker version
This PR updates the firecracker version being used in kata containers
versions.yaml

The changes in version 1.3.1 are

Added

Introduced T2CL (Intel) and T2A (AMD) CPU templates to provide
instruction set feature parity between Intel and AMD CPUs when using
these templates.
Added Graviton3 support (c7g instance type).
Changed

Improved error message when invalid network backend provided.
Improved TCP throughput by between 5% and 15% (depending on CPU) by using
scatter-gather I/O in the net device's TX path.
Upgraded Rust toolchain from 1.64.0 to 1.66.0.
Made seccompiler output bit-reproducible.
Fixed

Fixed feature flags in T2 CPU template on Intel Ice Lake.

Fixes #6482

Signed-off-by: Gabriela Cervantes <gabriela.cervantes.tellez@intel.com>
2023-03-16 17:34:33 +00:00
Yushuo
f4938c0d90 bugfix: set hostname
Setting hostname according to the spec.

Fixes: #6247

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-03-16 17:16:06 +08:00
Hyounggyu Choi
96baa83895 agent: Bring in VFIO-AP device handling again
This PR is a continuing work for (kata-containers#3679).

This generalizes the previous VFIO device handling which only
focuses on PCI to include AP (IBM Z specific).

Fixes: kata-containers#3678
Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2023-03-16 18:14:12 +09:00
Greg Kurz
e6e719699f Merge pull request #6471 from etrunko/main
dependency: update cgroups-rs
2023-03-16 08:01:07 +01:00
QuanweiZhou
56c63a9b1c Merge pull request #6186 from wllenyj/dragonball-ut-6
Built-in Sandbox: add more unit tests for dragonball. Part 6
2023-03-16 11:02:05 +08:00
Jakob Naucke
f666f8e2df agent: Add VFIO-AP device handling
Initial VFIO-AP support (#578) was simple, but somewhat hacky; a
different code path would be chosen for performing the hotplug, and
agent-side device handling was bound to knowing the assigned queue
numbers (APQNs) through some other means; plus the code for awaiting
them was written for the Go agent and never released. This code also
artificially increased the hotplug timeout to wait for the (relatively
expensive, thus limited to 5 seconds at the quickest) AP rescan, which
is impractical for e.g. common k8s timeouts.

Since then, the general handling logic was improved (#1190), but it
assumed PCI in several places.

In the runtime, introduce and parse AP devices. Annotate them as such
when passing to the agent, and include information about the associated
APQNs.

The agent awaits the passed APQNs through uevents and triggers a
rescan directly.

Fixes: #3678
Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2023-03-16 10:07:48 +09:00
Jakob Naucke
b546eca26f runtime: Generalize VFIO devices
Generalize VFIO devices to allow for adding AP in the next patch.
The logic for VFIOPciDeviceMediatedType() has been changed and IsAPVFIOMediatedDevice() has been removed.

The rationale for the revomal is:

- VFIODeviceMediatedType is divided into 2 subtypes for AP and PCI
- Logic of checking a subtype of mediated device is included in GetVFIODeviceType()
- VFIOPciDeviceMediatedType() can simply fulfill the device addition based
on a type categorized by GetVFIODeviceType()

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2023-03-16 10:06:37 +09:00
Jakob Naucke
4c527d00c7 agent: Rename VFIO handling to VFIO PCI handling
e.g., split_vfio_option is PCI-specific and should instead be named
split_vfio_pci_option. This mutually affects the runtime, most notably
how the labels are named for the agent.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2023-03-16 07:43:39 +09:00
Jakob Naucke
db89c88f4f agent: Use cfg-if for s390x CCW
Uses fewer lines in upcoming VFIO-AP support.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2023-03-16 07:43:39 +09:00
Jakob Naucke
68a586e52c agent: Use a constant for CCW root bus path
used a function like PCI does, but this is not necessary

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2023-03-16 07:43:39 +09:00
Fabiano Fidêncio
814d07af58 Merge pull request #6463 from sprt/sprt/mshv-compat
runtime: add support for Hyper-V
2023-03-15 18:03:25 +01:00
Eduardo Lima (Etrunko)
a8b55bf874 dependency: update cgroups-rs
Huge pages failure with cgroups v2.
https://github.com/kata-containers/cgroups-rs/issues/112

Fixes: #6470

Signed-off-by: Eduardo Lima (Etrunko) <etrunko@redhat.com>
2023-03-15 12:21:12 -03:00
Chao Wu
530b2a7685 Merge pull request #6458 from openanolis/chao/update_comments
runtime-rs: update load_config comment
2023-03-15 19:32:07 +08:00
Chao Wu
97cdba97ea runtime-rs: update load_config comment
Since shimv2 create task option is already implemented, we need to update the
corresponding comments.

Also, the ordering is also updated to fit with the code.

fixes: #3961

Signed-off-by: Chao Wu <chaowu@linux.alibaba.com>
2023-03-15 14:44:47 +08:00
Eric Ernst
dc42f0a33b Merge pull request #6411 from wlan0/empty-dir
Add support for ephemeral mounts to occupy entire sandbox's memory
2023-03-13 20:07:27 -07:00
Henry Beberman
974a5c22f0 runtime: add support for Hyper-V
This adds /dev/mshv to the list of sandbox devices so that VMMs can
create Hyper-V VMs.

In our testing, this also doesn't error out in case /dev/mshv isn't
present.

Fixes #6454.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2023-03-13 17:13:51 -07:00
Fabiano Fidêncio
ab0bd7a1ee Merge pull request #6292 from fidencio/topic/runtime-rs-small-fixes
runtime-rs: fix default kernel location and add more default config paths
2023-03-13 16:53:30 +01:00
Fabiano Fidêncio
40f4eef535 build: Use the correct kernel name
When calling `MAKE_KERNEL_NAME` we're considering the default kernel
name will be `vmlinux.container` or `vmlinuz.container`, which is not
the case as the runtime-rs, when used with dragonball, relies on the
`vmlinu[zx]-dragonball-experimental.container` kernel.

Other hypervisors will have to introduce a similar
`MAKE_KERNEL_NAME_${HYPERVISOR}` to adapt this to the kernel they want
to use, similarly to what's already done for the go runtime.

By doing this we also ensure that no changes in the configuration file
will be required to run runtime-rs, with dragonball, as part of our CI
or as part of kata-deploy.

Fixes: #6290

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-13 13:47:20 +01:00
James O. D. Hunt
ae9be1d94b Merge pull request #5840 from tzY15368/feat-runtimers-direct-vol
Implement direct-volume commands handler for shim-mgmt
2023-03-13 07:58:40 +00:00
Chelsea Mafrica
4b877b0a3e Merge pull request #6426 from openanolis/runtime-rs-resize-pty
bugfix: modify tty_win info in runtime when handling ResizePtyRequest
2023-03-10 14:08:41 -08:00
Sidhartha Mani
a6c67a161e runtime: add support for ephemeral mounts to occupy entire sandbox memory
On hotplug of memory as containers are started, remount all ephemeral mounts with size option set to the total sandbox memory

Fixes: #6417

Signed-off-by: Sidhartha Mani <sidhartha_mani@apple.com>
2023-03-10 13:36:02 -08:00
James O. D. Hunt
99a4eaa898 Merge pull request #6443 from openanolis/runtime-rs-get-netns
bugfix: add get_ns_path API for Hypervisor
2023-03-10 20:16:22 +00:00
Fabiano Fidêncio
44bc222ca4 Merge pull request #5578 from Richardhongyu/main
runtime-rs: add the missing default trait
2023-03-10 18:01:43 +01:00
Li Hongyu
844bf053b2 runtime-rs: add the missing default trait
Some structs in the runtime-rs don't implement Default trait.
This commit adds the missing Default.

Fixes: #5463

Signed-off-by: Li Hongyu <lihongyu1999@bupt.edu.cn>
2023-03-10 08:19:56 +00:00
Yushuo
e7bca62c32 bugfix: modify tty_win info in runtime when handling ResizePtyRequest
Currently, we only create the new exec process in runtime, this will cause error
when the following requests needing to be handled:

- Task: exec process
- Task: resize process pty
- ...

The agent do not do_exec_process when we handle ExecProcess, thus we can not find
any process information in the guest when we handle ResizeProcessPty. This will
report an error.

In this commit, the handling process is modified to the:
* Modify process tty_win information in runtime
* If the exec process is not running, we just return. And the truly pty_resize will
happen when start_process

Fixes: #6248

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-03-10 14:33:51 +08:00
Tingzhou Yuan
30e235f0a1 runtime-rs: impl volume-resize trait for sandbox
Implements resize-volume handlers in shim-mgmt,
trait for sandbox and add RPC calls to agent.
Note the actual rpc handler for the resize request is currently not
implemented, refer to issue #3694.

Fixes #5369

Signed-off-by: Tingzhou Yuan <tzyuan15@bu.edu>
2023-03-10 01:27:06 -05:00
Yushuo
e029988bc2 bugfix: add get_ns_path API for Hypervisor
For external hypervisors(qemu, cloud-hypervisor, ...), the ns they launch vm in
is different from internal hypervisor(dragonball). And when we doing CreateContainer
hook, we will rely on the netns path. So we add a get_ns_path API.

Fixes: #6442

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-03-10 13:57:00 +08:00
Tingzhou Yuan
42b8867148 runtime-rs: impl volume-stats trait for sandbox
Implements get-volume-stats trait for sandbox,
handler for shim-mgmt and add RPC calls to
agent. Also added type conversions in trans.rs

Fixes #5369

Signed-off-by: Tingzhou Yuan <tzyuan15@bu.edu>
2023-03-10 00:48:02 -05:00
Jeremi Piotrowski
462d4a1af2 workflows: static-checks: Free disk space before running checks
We've been seeing the 'sudo make test' job occasionally run out of space in
/tmp, which is part of the root filesystem. Removing dotnet and
`AGENT_TOOLSDIRECTORY` frees around 10GB of space and in my tests the job still
has 13GB of space left after running.

Fixes: #6401
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-09 13:30:09 +01:00
Jeremi Piotrowski
e68186d9af workflows: static-checks: Set GOPATH only once
{{ runner.workspace }}/kata-containers and {{ github.workspace }} resolve to
the same value, but they're being used multiple times in the workflow. Remove
multiple definitions and define the GOPATH var at job level once.

Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-09 13:30:09 +01:00
Jeremi Piotrowski
439ff9d4c4 tools/osbuilder/tests: Remove TRAVIS variable
The last remaining user of the TRAVIS variable in this repo is
tools/osbuilder/tests and it is only used to skip spinning up VMs. Travis
didn't support virtualization and the same is true for github actions hosted
runners. Replace the variable with KVM_MISSING and determine availability of
/dev/kvm at runtime.

TRAVIS is also used by '.ci/setup.sh' in kata-containers/tests to reduce the
set of dependencies that gets installed, but this is also in the process of
being removed.

Fixes: #3544
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-09 13:29:49 +01:00
Christophe de Dinechin
7566a7eae4 Merge pull request #6432 from fidencio/topic/simplify-get-last-modification
packaging: Simplify get_last_modification()
2023-03-09 10:57:58 +01:00
Fabiano Fidêncio
43ce3f7588 packaging: Simplify get_last_modification()
There's no need to pass repo_root_dir to get_last_modification() as the
variable used everywhere is exported from that very same file.

Fixes: #6431

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-08 21:22:03 +01:00
Fabiano Fidêncio
33c5c49719 packaging: Move repo_root_dir to lib.sh
This is used in several parts of the code, and can have a single
declaration as part of the `lib.sh` file, which is already imported by
all the places where it's used.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-08 21:10:53 +01:00
James O. D. Hunt
614d1817ce Merge pull request #6410 from tg5788re/kata-manager-use-runtime-checks
utils: Make kata-manager.sh runs checks
2023-03-08 09:55:03 +00:00
Chao Wu
fef268a7de Merge pull request #6413 from xuejun-xj/xuejun/pmu
dragonball: support pmu on aarch64
2023-03-08 14:24:31 +08:00
Steve Horsman
cc1821fb8b Merge pull request #6409 from Sig00rd/patch-1
docs: fix typo in key filename in AWS installation guide
2023-03-07 15:19:46 +00:00
Fabiano Fidêncio
861552c305 Merge pull request #6414 from jepio/jepio/backport-3.1-rustjail-systemd-cgroup-fix-6331
backport rustjail systemd cgroup fix #6331 to 3.1
2023-03-07 12:51:08 +01:00
Sidhartha Mani
16e2c3cc55 agent: implement update_ephemeral_mounts api
- implement update_ephemeral_mounts rpc
- for each mountpoint passed in, remount it with new options

Signed-off-by: Sidhartha Mani <sidhartha_mani@apple.com>
2023-03-06 13:44:14 -08:00
Sidhartha Mani
3896c7a22b protocol: add updateEphemeralMounts proto
- adds a new rpc call to the agent service named `updateEphemeralMounts`
- this call takes a list of grpc.Storage objects

Signed-off-by: Sidhartha Mani <sidhartha_mani@apple.com>
2023-03-06 13:43:47 -08:00
Jeremi Piotrowski
23488312f5 agent: always use cgroupfs when running as init
The logic to decide which cgroup driver is used is currently based on the
cgroup path that the host provides. This requires host and guest to use the
same cgroup driver. If the guest uses kata-agent as init, then systemd can't be
used as the cgroup driver. If the host requests a systemd cgroup, this
currently results in a rustjail panic:

  thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: I/O error: No such file or directory (os error 2)

  Caused by:
      No such file or directory (os error 2)', rustjail/src/cgroups/systemd/manager.rs:44:51
  stack backtrace:
     0:     0x7ff0fe77a793 - std::backtrace_rs::backtrace::libunwind::trace::h8c197fa9a679d134
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/../../backtrace/src/backtrace/libunwind.rs:93:5
     1:     0x7ff0fe77a793 - std::backtrace_rs::backtrace::trace_unsynchronized::h9ee19d58b6d5934a
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
     2:     0x7ff0fe77a793 - std::sys_common::backtrace::_print_fmt::h4badc450600fc417
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:65:5
     3:     0x7ff0fe77a793 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::had334ddb529a2169
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:44:22
     4:     0x7ff0fdce815e - core::fmt::write::h1aa7694f03e44db2
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/fmt/mod.rs:1209:17
     5:     0x7ff0fe74e0c4 - std::io::Write::write_fmt::h61b2bdc565be41b5
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/io/mod.rs:1682:15
     6:     0x7ff0fe77cd3f - std::sys_common::backtrace::_print::h4ec69798b72ff254
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:47:5
     7:     0x7ff0fe77cd3f - std::sys_common::backtrace::print::h0e6c02048dec3c77
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:34:9
     8:     0x7ff0fe77c93f - std::panicking::default_hook::{{closure}}::hcdb7e705dc37ea6e
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:267:22
     9:     0x7ff0fe77d9b8 - std::panicking::default_hook::he03a933a0f01790f
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:286:9
    10:     0x7ff0fe77d9b8 - std::panicking::rust_panic_with_hook::he26b680bfd953008
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:688:13
    11:     0x7ff0fe77d482 - std::panicking::begin_panic_handler::{{closure}}::h559120d2dd1c6180
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:579:13
    12:     0x7ff0fe77d3ec - std::sys_common::backtrace::__rust_end_short_backtrace::h36db621fc93b005a
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:137:18
    13:     0x7ff0fe77d3c1 - rust_begin_unwind
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:575:5
    14:     0x7ff0fda52ee2 - core::panicking::panic_fmt::he7679b415d25c5f4
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:65:14
    15:     0x7ff0fda53182 - core::result::unwrap_failed::hb71caff146724b6b
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/result.rs:1791:5
    16:     0x7ff0fe5bd738 - <rustjail::cgroups::systemd::manager::Manager as rustjail::cgroups::Manager>::apply::hd46958d9d807d2ca
    17:     0x7ff0fe606d80 - <rustjail::container::LinuxContainer as rustjail::container::BaseContainer>::start::{{closure}}::h1de806d91fcb878f
    18:     0x7ff0fe604a76 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h1749c148adcc235f
    19:     0x7ff0fdc0c992 - kata_agent::rpc::AgentService::do_create_container::{{closure}}::{{closure}}::hc1b87a15dfdf2f64
    20:     0x7ff0fdb80ae4 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h846a8c9e4fb67707
    21:     0x7ff0fe3bb816 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h53de16ff66ed3972
    22:     0x7ff0fdb519cb - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h1cbece980286c0f4
    23:     0x7ff0fdf4019c - <tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll::hc8e72d155feb8d1f
    24:     0x7ff0fdfa5fd8 - tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut::h0a407ffe2559449a
    25:     0x7ff0fdf033a1 - tokio::runtime::task::raw::poll::h1045d9f1db9742de
    26:     0x7ff0fe7a8ce2 - tokio::runtime::scheduler::multi_thread::worker::Context::run_task::h4924ae3464af7fbd
    27:     0x7ff0fe7afb85 - tokio::runtime::task::raw::poll::h5c843be39646b833
    28:     0x7ff0fe7a05ee - std::sys_common::backtrace::__rust_begin_short_backtrace::ha7777c55b98a9bd1
    29:     0x7ff0fe7a9bdb - core::ops::function::FnOnce::call_once{{vtable.shim}}::h27ec83c953360cdd
    30:     0x7ff0fe7801d5 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::hed812350c5aef7a8
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/alloc/src/boxed.rs:1987:9
    31:     0x7ff0fe7801d5 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::hc7df8e435a658960
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/alloc/src/boxed.rs:1987:9
    32:     0x7ff0fe7801d5 - std::sys::unix::thread::Thread::new::thread_start::h575491a8a17dbb33
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys/unix/thread.rs:108:17

Forward the value of "init_mode" to AgentService, so that we can force cgroupfs
when systemd is unavailable.

Fixes: #5779
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-06 20:34:21 +01:00
Jeremi Piotrowski
8546387348 agent: determine value of use_systemd_cgroup before LinuxContainer::new()
Right now LinuxContainer::new() gets passed a CreateOpts struct, but then
modifies the use_systemd_cgroup field inside that struct. Pull the cgroups path
parsing logic into do_create_container, so that CreateOpts can be immutable in
LinuxContainer::new. This is just moving things around, there should be no
functional changes.

Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-06 20:34:21 +01:00
Jeremi Piotrowski
736aae47a4 rustjail: print type of cgroup manager
Since the cgroup manager is wrapped in a dyn now, the print in
LinuxContainer::new has been useless and just says "CgroupManager". Extend the
Debug trait for 'dyn Manager' to print the type of the cgroup manager so that
it's easier to debug issues.

Fixes: #5779
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-06 20:34:21 +01:00
Fabiano Fidêncio
0749657c73 Merge pull request #6359 from singhwang/main
main | kata-deploy: Fix kata deploy arm64 image build error
2023-03-06 16:48:03 +01:00
Fabiano Fidêncio
dbae281924 workflows: Properly set the kata-tarball architecture
Let's make sure the kata-tarball architecture upload / downloaded / used
is exactly the same one that we need as part of the architecture we're
using to generate the image.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-06 13:18:51 +01:00
Fabiano Fidêncio
76b4591e2b tools: Adjust the build-and-upload-payload.sh script
Now that we've switched the base container image to using Ubuntu instead
of CentOS, we don't need any kind of extra logic to correctly build the
image for different architectures, as Ubuntu is a multi-arch image that
supports all the architectures we're targetting.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-06 13:18:51 +01:00
SinghWang
cd2aaeda2a kata-deploy: Switch to using an ubuntu image
Let's make sure we use a multi-arch image for building kata-deploy.
A few changes were also added in order to get systemd working inside the
kata-deploy image, due to the switch from CentOS to Ubuntu.

Fixes: #6358
Signed-off-by: SinghWang <wangxin_0611@126.com>
2023-03-06 13:18:51 +01:00
Szymon Fugas
2d43e13102 docs: fix typo in AWS installation guide
Fixes referring to previously created key file with .pen extension instead of .pem.

Fixes: #6412
Signed-off-by: Sig00rd <sfugas@virtuslab.com>
2023-03-06 13:18:08 +01:00
xuejun-xj
760f78137d dragonball: support pmu on aarch64
This commit adds support for pmu virtualization on aarch64. The
initialization of pmu is in the following order:
1. Receive pmu parameter(vpmu_feature) from runtime-rs to determine the
VpmuFeatureLevel.
2. Judge whether to initialize pmu devices and add pmu device node into
fdt on aarch64, according to VpmuFeatureLevel.

Fixes: #6168

Signed-off-by: xuejun-xj <jiyunxue@linux.alibaba.com>
2023-03-06 18:55:13 +08:00
Fabiano Fidêncio
93a40cb35e Merge pull request #6402 from fidencio/topic/yet-more-fixes-for-the-publish-kata-deploy-payload-work
workflows: Yet more fixes for publishing the kata-deploy payload after every PR merged
2023-03-06 10:43:32 +01:00
Fabiano Fidêncio
df35f8f885 Merge pull request #6331 from jepio/jepio/fix-agent-init-cgroups
rustjail: fix cgroup handling in agent-init mode
2023-03-05 20:29:40 +01:00
Fabiano Fidêncio
98d611623f Merge pull request #6361 from etrunko/main
runtime/Makefile: Fix install-containerd-shim-v2 dependency
2023-03-04 13:47:11 +01:00
Fabiano Fidêncio
9bc7bef3d6 kata-deploy: Fix path to the Dockerfile
As part of bd1ed26c8d, we've pointed to
the Dockerfile that's used in the CC branch, which is wrong.

For what we're doing on main, we should be pointing to the one under the
`kata-deploy` folder, and not the one under the non-existent
`kata-deploy-cc` one.

Fixes: #6343

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-04 12:18:38 +01:00
Fabiano Fidêncio
78ba363f8e kata-deploy: Use different images for s390x and aarch64
As the image provided as part of registry.centos.org is not a multi-arch
one, at least not for CentOS 7, we need to expand the script used to
build the image to pass images that are known to work for s390x (ClefOS)
and aarch64 (CentOS, but coming from dockerhub).

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-04 12:18:32 +01:00
Fabiano Fidêncio
6267909501 kata-deploy: Allow passing BASE_IMAGE_{NAME,TAG}
Let's break the IMAGE build parameter into BASE_IMAGE_NAME and
BASE_IMAGE_TAG, as it makes it easier to replace the default CentOS
image by something else.

Spoiler alert, the default CentOS image is **not** multi-arch, and we do
want to support at least aarch64 and s390x in the near term future.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-04 12:16:41 +01:00
Jianyong Wu
3443f558a6 nydus: upgrad nydus to v2.2.0
Use the latest nydus, we may let nydus work on arm64.

Fixes: #6407
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2023-03-04 12:58:48 +08:00
Jianyong Wu
395645e1ce runtime: hybrid-mode cause error in the latest nydusd
When update the nydusd to 2.2, the argument "--hybrid-mode" cause
the following error:

thread 'main' panicked at 'ArgAction::SetTrue / ArgAction::SetFalse is defaulted'

Maybe we should remove it to upgrad nydusd

Fixes: #6407
Signed-off-by: Jianyong Wu <jianyong.wu@arm.com>
2023-03-04 12:58:48 +08:00
tg5788re
f8e44172f6 utils: Make kata-manager.sh runs checks
Updated the `kata-manager.sh` script to make it run all the checks on
the host system before attempting to create a container. If any checks
fail, they will indicate to the user what the problem is in a clearer
manner than those reported by the container manager.

Fixes: #6281.

Signed-off-by: tg5788re <jfokugas@gmail.com>
2023-03-03 09:56:12 -06:00
Chelsea Mafrica
ebe916b372 Merge pull request #6355 from yanggangtony/fix-wrong-notes
fix wrong notes for func GetSandboxesStoragePathRust()
2023-03-03 07:55:54 -08:00
Jeremi Piotrowski
f31c79d210 workflows: static-checks: Remove TRAVIS_XXX variables
These variables are unused since we don't use travis CI. This also allows to
remove two steps:

- 'Setup GOPATH' only printed variables
- 'Setup travis reference' modified some shell local variables that don't have
  any influence on the rest of the steps

The TRAVIS var is still used by tools/osbuilder/tests to determine if
virtualization is available.

Fixes: #3544
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-03-03 11:38:34 +01:00
Zhongtao Hu
60bb9d114a Merge pull request #6399 from yipengyin/fix-cleanup
fix(runtime-rs): add exited state to ensure cleanup
2023-03-03 17:41:16 +08:00
Chao Wu
6fc4c8b099 Merge pull request #5788 from openanolis/runtime-rs-ocihook
runtime-rs: add oci hook support
2023-03-03 01:06:21 +08:00
James O. D. Hunt
4a7a859592 Merge pull request #6377 from pembek01/remove-cgroupsv2-check
utils: Remove kata-manager.sh cgroups v2 check
2023-03-02 17:00:46 +00:00
Fabiano Fidêncio
b20d5289cb Merge pull request #6400 from fidencio/topic/fixes-for-generating-the-kata-deploy-payload
workflows:  Fixes for the `payload-after-push` action
2023-03-02 14:20:24 +01:00
Yipeng Yin
8030e469b2 fix(runtime-rs): add exited state to ensure cleanup
Set process status to exited at end of io wait, which indicate process
exited only, but stop process has not been finished. Otherwise, the
cleanup_container will be skipped.

Fixes: #6393

Signed-off-by: Yipeng Yin <yinyipeng@bytedance.com>
2023-03-02 18:14:20 +08:00
Fabiano Fidêncio
7d292d7fc3 workflows: Fix the path of imported workflows
In `payload-after-push.yaml` we ended up mentioning cc-*.yaml workflows,
which are non existent in the main branch.

Let's adapt the name to the correct ones.

Fixes: #6343

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-02 10:18:10 +01:00
Fabiano Fidêncio
e07162e79d workflows: Fix action name
We have a few actions in the `payload-after-push.*.yaml` that are
referring to Confidential Containers, but they should be referring to
Kata Containers instead.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-02 10:17:18 +01:00
Chao Wu
572c385774 Merge pull request #6269 from openanolis/chao/update_dragonball_version
Dragonball: update dependencies
2023-03-02 17:15:39 +08:00
Fabiano Fidêncio
7286f8f706 Merge pull request #6391 from fidencio/topic/do-not-install-docker-as-part-of-the-actions
workflows: Do not install docker
2023-03-02 10:12:15 +01:00
Fabiano Fidêncio
7201279647 Merge pull request #6344 from fidencio/topic/generate-a-kata-deploy-payload-on-each-PR-merged
workflows: Publish kata-deploy payload after a merge
2023-03-02 09:02:34 +01:00
Chao Wu
dd2713521e Dragonball: update dependencies
Since rust-vmm and dragonball-sandbox has introduced several updates
such as vPMU support for aarch64, we also need to update Dragonball
dependencies to include those changes.

Update:
virtio-queue to v0.6.0
kvm-ioctls to v0.12.0
dbs-upcall to v0.2.0
dbs-virtio-devices to v0.2.0
kvm-bindings to v0.6.0

Also, several aarch64 features are updated because of dependencies
changes:
1. update vcpu hotplug API.
2. update vpmu related API.
3. adjust unit test cases for aarch64 Dragonball.

fixes: #6268

Signed-off-by: Chao Wu <chaowu@linux.alibaba.com>
2023-03-02 14:53:04 +08:00
Chao Wu
2934ab4a3c Merge pull request #6380 from Christopher-C-Robinson/#6256-typo-fix
src: Fixed typo mod.rs
2023-03-02 14:31:33 +08:00
Fabiano Fidêncio
bd1ed26c8d workflows: Publish kata-deploy payload after a merge
For the architectures we know that `make kata-tarball` works as
expected, let's start publishing the kata-deploy payload after each
merge.

This will help to:
* Easily test the content of current `main` or `stable-*` branch
* Easily bisect issues
* Start providing some sort of CI/CD content pipeline for those who
  need that

This is a forward-port work from the `CCv0` and groups together patches
that I've worked on, with the work that Choi did in order to support
different architectures.

Fixes: #6343

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-03-02 02:19:10 +01:00
Domesticcadiz
fea7e8816f runtime-rs: Fixed typo mod.rs
Fixed the typo in comment in the delete method located in mod.rs file.

Fixes: #6256.

Signed-off-by: Domesticcadiz <christopher.cadiz.robinson@gmail.com>
2023-03-01 18:03:41 -06:00
Archana Shinde
65fa19fe92 Merge pull request #6305 from amshinde/update-action-kernel-check
actions: Use `git-diff` to get changes in kernel dir
2023-03-01 13:46:50 -08:00
Eduardo Lima (Etrunko)
a9e2fc8678 runtime/Makefile: Fix install-containerd-shim-v2 dependency
$ make install
make: *** No rule to make target 'containerd-shim-kata-v2', needed by 'install-containerd-shim-v2'.  Stop.

Spotted when building kata-runtime with a different name for
SHIMV2_OUTPUT. For instance, trying to keep different runtime binaries
installed at the same time, one from master and another from lets say,
the CCv0 branch, with the following small change applied.

diff --git a/src/runtime/Makefile b/src/runtime/Makefile
index 95efaff78..2bab9eb75 100644
--- a/src/runtime/Makefile
+++ b/src/runtime/Makefile
@@ -231,7 +231,7 @@ SED = sed

 CLI_DIR = cmd
 SHIMV2 = containerd-shim-kata-v2
-SHIMV2_OUTPUT = $(bCURDIR)/$(SHIMV2)
+SHIMV2_OUTPUT = $(CURDIR)/$(SHIMV2)-ccv0
 SHIMV2_DIR = $(CLI_DIR)/$(SHIMV2)

 MONITOR = kata-monitor

Fixes: #6398

Signed-off-by: Eduardo Lima (Etrunko) <etrunko@redhat.com>
2023-03-01 15:57:30 -03:00
yanggang
b6880c60d3 logging: Correct the code notes
Fix wrong notes for func GetSandboxesStoragePathRust()

Fixes: #6394

Signed-off-by: yanggang <gang.yang@daocloud.io>
2023-03-01 19:20:25 +08:00
Yushuo
12cfad4858 runtime-rs: modify the transfer to oci::Hooks
In this commit, we have done:
    * modify the tranfer process from grpc::Hooks to oci::Hooks, so the code
      can be more clean
    * add more tests for create_runtime, create_container, start_container hooks

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-03-01 10:35:10 +08:00
Fabiano Fidêncio
828d467222 workflows: Do not install docker
The latest ubuntu runners already have docker installed and trying to
install it manually will cause the following issue:
```
Run curl -fsSL https://test.docker.com/ -o test-docker.sh
Warning: the "docker" command appears to already exist on this system.

If you already have Docker installed, this script can cause trouble, which is
why we're displaying this warning and provide the opportunity to cancel the
installation.

If you installed the current Docker package using this script and are using it
again to update Docker, you can safely ignore this message.

You may press Ctrl+C now to abort this script.
+ sleep 20
+ sudo -E sh -c apt-get update -qq >/dev/null
E: The repository 'https://packages.microsoft.com/ubuntu/22.04/prod jammy Release' is no longer signed.
```

Fixes: #6390

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-28 23:53:28 +01:00
Alec Pemberton
4b8a5a1a3d utils: Remove kata-manager.sh cgroups v2 check
Removed the part in the `kata-manager.sh` script that checks if the host system only runs cgroups v2.

Fixes: #6259.

Signed-off-by: Alec Pemberton <pembek1901@gmail.com>
2023-02-28 11:23:51 -06:00
Steve Horsman
785310fe18 Merge pull request #6368 from yoheiueda/dir-perm
agent: don't set permission of existing directory in copy_file
2023-02-28 14:48:10 +00:00
Chelsea Mafrica
703589c279 Merge pull request #6369 from XDTG/6082/Fix-path-check-bypassed
runtime: use filepath.Clean() to clean the mount path
2023-02-27 17:24:50 -08:00
Bo Chen
ba9227184e Merge pull request #6376 from likebreath/0224/clh_v30.0
Upgrade to Cloud Hypervisor v30.0
2023-02-27 11:48:52 -08:00
Yushuo
2c4428ee02 runtime-rs: move pre-start hooks to sandbox_start
In some cases, network endpoints will be configured through Prestart
Hook. So network endpoints may need to be added(hotpluged) after vm
is started and also Prestart Hook is executed.

We move pre-start hook functions' execution to sandbox_start to allow
hooks running between vm_start and netns_scan easily, so that the
lifecycle API can be cleaner.

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-27 21:56:43 +08:00
Yushuo
e80c9f7b74 runtime-rs: add StartContainer hook
StartContainer will be execute in guest container namespace in Kata.
The Hook Path of this kind of hook is also in guest container namespace.

StartContainer is executed after start operation is called, and it
should be executed before user-specific command is executed.

Fixes: #5787

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-27 21:56:43 +08:00
Yushuo
977f281c5c runtime-rs: add CreateContainer hook support
CreateContainer hook is one kind of OCI hook. In kata, it will be
executed after VM is started, before container is created, and after
CreateRuntime is executed.

The hook path of CreateContainer hook is in host runtime namespace, but
it will be executed in host vmm namespace.

Fixes: #5787

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-27 21:56:43 +08:00
Yushuo
875f2db528 runtime-rs: add oci hook support
According to the runtime OCI Spec, there can be some hook
operations in the lifecycle of the container. In these hook
operations, the runtime can execute some commands. There are different
points in time in the container lifecycle  and different hook types
can be executed.

In this commit, we are now supporting 4 types of hooks(same in
runtime-go): Prestart hook, CreateRuntime hook, Poststart hook and
Poststop hook.

Fixes: #5787

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-27 21:56:43 +08:00
Yushuo
ecac3a9e10 docs: add design doc for Hooks
Fixes: #5787

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-27 21:56:43 +08:00
Bin Liu
e90989b16b Merge pull request #6314 from openanolis/static_doc
feat(runtime): make static resource management consistent with 2.0
2023-02-27 16:43:27 +08:00
Bo Chen
3ac6f29e95 runtime: clh: Re-generate the client code
This patch re-generates the client code for Cloud Hypervisor v30.0.
Note: The client code of cloud-hypervisor's OpenAPI is automatically
generated by openapi-generator.

Fixes: #6375

Signed-off-by: Bo Chen <chen.bo@intel.com>
2023-02-24 10:20:29 -08:00
Bo Chen
262daaa2ef versions: Upgrade to Cloud Hypervisor v30.0
Details of this release can be found in our new roadmap project as
iteration v30.0: https://github.com/orgs/cloud-hypervisor/projects/6.

Fixes: #6375

Signed-off-by: Bo Chen <chen.bo@intel.com>
2023-02-24 10:19:46 -08:00
Jeremi Piotrowski
192df84588 agent: always use cgroupfs when running as init
The logic to decide which cgroup driver is used is currently based on the
cgroup path that the host provides. This requires host and guest to use the
same cgroup driver. If the guest uses kata-agent as init, then systemd can't be
used as the cgroup driver. If the host requests a systemd cgroup, this
currently results in a rustjail panic:

  thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: I/O error: No such file or directory (os error 2)

  Caused by:
      No such file or directory (os error 2)', rustjail/src/cgroups/systemd/manager.rs:44:51
  stack backtrace:
     0:     0x7ff0fe77a793 - std::backtrace_rs::backtrace::libunwind::trace::h8c197fa9a679d134
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/../../backtrace/src/backtrace/libunwind.rs:93:5
     1:     0x7ff0fe77a793 - std::backtrace_rs::backtrace::trace_unsynchronized::h9ee19d58b6d5934a
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
     2:     0x7ff0fe77a793 - std::sys_common::backtrace::_print_fmt::h4badc450600fc417
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:65:5
     3:     0x7ff0fe77a793 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::had334ddb529a2169
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:44:22
     4:     0x7ff0fdce815e - core::fmt::write::h1aa7694f03e44db2
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/fmt/mod.rs:1209:17
     5:     0x7ff0fe74e0c4 - std::io::Write::write_fmt::h61b2bdc565be41b5
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/io/mod.rs:1682:15
     6:     0x7ff0fe77cd3f - std::sys_common::backtrace::_print::h4ec69798b72ff254
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:47:5
     7:     0x7ff0fe77cd3f - std::sys_common::backtrace::print::h0e6c02048dec3c77
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:34:9
     8:     0x7ff0fe77c93f - std::panicking::default_hook::{{closure}}::hcdb7e705dc37ea6e
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:267:22
     9:     0x7ff0fe77d9b8 - std::panicking::default_hook::he03a933a0f01790f
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:286:9
    10:     0x7ff0fe77d9b8 - std::panicking::rust_panic_with_hook::he26b680bfd953008
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:688:13
    11:     0x7ff0fe77d482 - std::panicking::begin_panic_handler::{{closure}}::h559120d2dd1c6180
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:579:13
    12:     0x7ff0fe77d3ec - std::sys_common::backtrace::__rust_end_short_backtrace::h36db621fc93b005a
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys_common/backtrace.rs:137:18
    13:     0x7ff0fe77d3c1 - rust_begin_unwind
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:575:5
    14:     0x7ff0fda52ee2 - core::panicking::panic_fmt::he7679b415d25c5f4
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:65:14
    15:     0x7ff0fda53182 - core::result::unwrap_failed::hb71caff146724b6b
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/result.rs:1791:5
    16:     0x7ff0fe5bd738 - <rustjail::cgroups::systemd::manager::Manager as rustjail::cgroups::Manager>::apply::hd46958d9d807d2ca
    17:     0x7ff0fe606d80 - <rustjail::container::LinuxContainer as rustjail::container::BaseContainer>::start::{{closure}}::h1de806d91fcb878f
    18:     0x7ff0fe604a76 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h1749c148adcc235f
    19:     0x7ff0fdc0c992 - kata_agent::rpc::AgentService::do_create_container::{{closure}}::{{closure}}::hc1b87a15dfdf2f64
    20:     0x7ff0fdb80ae4 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h846a8c9e4fb67707
    21:     0x7ff0fe3bb816 - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h53de16ff66ed3972
    22:     0x7ff0fdb519cb - <core::future::from_generator::GenFuture<T> as core::future::future::Future>::poll::h1cbece980286c0f4
    23:     0x7ff0fdf4019c - <tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll::hc8e72d155feb8d1f
    24:     0x7ff0fdfa5fd8 - tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut::h0a407ffe2559449a
    25:     0x7ff0fdf033a1 - tokio::runtime::task::raw::poll::h1045d9f1db9742de
    26:     0x7ff0fe7a8ce2 - tokio::runtime::scheduler::multi_thread::worker::Context::run_task::h4924ae3464af7fbd
    27:     0x7ff0fe7afb85 - tokio::runtime::task::raw::poll::h5c843be39646b833
    28:     0x7ff0fe7a05ee - std::sys_common::backtrace::__rust_begin_short_backtrace::ha7777c55b98a9bd1
    29:     0x7ff0fe7a9bdb - core::ops::function::FnOnce::call_once{{vtable.shim}}::h27ec83c953360cdd
    30:     0x7ff0fe7801d5 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::hed812350c5aef7a8
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/alloc/src/boxed.rs:1987:9
    31:     0x7ff0fe7801d5 - <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once::hc7df8e435a658960
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/alloc/src/boxed.rs:1987:9
    32:     0x7ff0fe7801d5 - std::sys::unix::thread::Thread::new::thread_start::h575491a8a17dbb33
                                 at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/sys/unix/thread.rs:108:17

Forward the value of "init_mode" to AgentService, so that we can force cgroupfs
when systemd is unavailable.

Fixes: #5779
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-02-24 14:02:11 +01:00
Jeremi Piotrowski
b0691806f1 agent: determine value of use_systemd_cgroup before LinuxContainer::new()
Right now LinuxContainer::new() gets passed a CreateOpts struct, but then
modifies the use_systemd_cgroup field inside that struct. Pull the cgroups path
parsing logic into do_create_container, so that CreateOpts can be immutable in
LinuxContainer::new. This is just moving things around, there should be no
functional changes.

Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-02-24 13:46:37 +01:00
XDTG
dc86d6dac3 runtime: use filepath.Clean() to clean the mount path
Fix path check bypassed issuse introduced by #6082,
use filepath.Clean() to clean path before check

Fixes: #6082

Signed-off-by: XDTG <click1799@163.com>
2023-02-24 15:48:09 +08:00
Yohei Ueda
c4ef5fd325 agent: don't set permission of existing directory
This patch fixes the issue that do_copy_file changes
the directory permission of the parent directory of
a target file, even when the parent directory already
exists.

Fixes #6367

Signed-off-by: Yohei Ueda <yohei@jp.ibm.com>
2023-02-24 16:43:59 +09:00
Feng Wang
cbe6ad9034 runtime: support non-root for clh
This change enables to run cloud-hypervisor VMM using a non-root user
when rootless flag is set true in the configuration

Fixes: #2567

Signed-off-by: Feng Wang <fwang@confluent.io>
2023-02-22 13:57:09 -08:00
Fabiano Fidêncio
44a780f262 Merge pull request #6262 from jepio/jepio/initrd-dev-nodes
osbuilder: Include minimal set of device nodes in ubuntu initrd
2023-02-22 20:34:13 +01:00
GabyCT
a0b1f81867 Merge pull request #5958 from Apokleos/kata-ctl-exec
kata-ctl/exec: add new command exec to enter guest VM.
2023-02-22 12:07:44 -06:00
Fabiano Fidêncio
109071855d Merge pull request #6124 from Alex-Carter01/snp-kernel-config
kernel: Add CONFIG_SEV_GUEST to SEV kernel config
2023-02-22 18:42:35 +01:00
David Esparza
5e2fe5f932 Merge pull request #6332 from jodh-intel/runtime-rs-ch-config-convert
runtime-rs: Improve Cloud Hypervisor config handling
2023-02-22 10:15:50 -06:00
GabyCT
5c6e56931f Merge pull request #6312 from Amulyam24/virtiofsd-fix
virtiofsd: update to a valid path on ppc64le
2023-02-22 08:57:51 -06:00
James O. D. Hunt
3483272bbd runtime-rs: ch: Enable initrd usage
Allow an initrd/initramfs image to be used with Cloud Hypervisor, which
is handled differently to the default rootfs image type.

Fixes: #6335.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-02-22 10:55:01 +00:00
James O. D. Hunt
fbee6c820e runtime-rs: Improve Cloud Hypervisor config handling
Replace `cloud_hypervisor_vm_create_cfg()` with a set of `TryFrom` trait
implementations in the new CH specific `convert.rs` to allow the generic
`Hypervisor` configuration to be converted into the CH specific
`VmConfig` type.

Note that device configuration is not currently handled in `convert.rs`
(it's handled in `inner_device.rs`).

This change removes the old hard-coded CH specific configuration.

Fixes: #6203.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-02-22 10:48:05 +00:00
Chao Wu
578f2e7c2e Merge pull request #6080 from openanolis/rem
runtime-rs: cleanup kata host share path
2023-02-22 17:45:24 +08:00
GabyCT
7aff118c82 Merge pull request #6236 from jepio/jepio/osbuilder-fix-default-make-target
osbuilder: fix default build target in makefile
2023-02-21 17:00:21 -06:00
Alex Carter
1bff1ca30a kernel: Add CONFIG_SEV_GUEST to SEV kernel config
Adding kernel config to sev case since it is needed for SNP and SNP will use the SEV kernel.
Incrementing kernel config version to reflect changes

Fixes: #6123
Signed-off-by: Alex Carter <Alex.Carter@ibm.com>
2023-02-21 16:48:45 +00:00
GabyCT
fc5c62a5a1 Merge pull request #6330 from c3d/issue/6329-contribution-link-in-devguide
devguide: Add link to the contribution guidelines
2023-02-21 09:17:20 -06:00
Fabiano Fidêncio
ab5b45f615 Merge pull request #6340 from fidencio/topic/ensure-go-binaries-can-still-run-on-ubuntu-2004
kata-deploy: Ensure go binaries can run on Ubuntu 20.04
2023-02-21 13:52:18 +01:00
Zhongtao Hu
4f20cb7ced Merge pull request #6325 from HerlinCoder/herlincoder/config-manager
dragonball: config_manager: preserve device when update
2023-02-21 17:51:41 +08:00
Jeremi Piotrowski
ad8968c8d9 rustjail: print type of cgroup manager
Since the cgroup manager is wrapped in a dyn now, the print in
LinuxContainer::new has been useless and just says "CgroupManager". Extend the
Debug trait for 'dyn Manager' to print the type of the cgroup manager so that
it's easier to debug issues.

Fixes: #5779
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-02-21 10:07:03 +01:00
SinghWang
b4a1527aa6 kata-deploy: Fix static shim-v2 build on arm64
Following Jong Wu suggestion, let's link /usr/bin/musl-gcc to
/usr/bin/aarch64-linux-musl-gcc.

Fixes: #6320
Signed-off-by: SinghWang <wangxin_0611@126.com>
Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-21 10:00:28 +01:00
Fabiano Fidêncio
2c4f8077fd Revert "shim-v2: Bump Ubuntu container image to 22.04"
This reverts commit 9d78bf9086.

Golang binaries are built statically by default, unless linking against
CGO, which we do.  In this case we dynamically link against glibc,
causing us troubles when running a binary built with Ubuntu 22.04 on
Ubuntu 20.04 (which will still be supported for the next few years ...)

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-21 10:00:28 +01:00
Fabiano Fidêncio
73d0ca0bd5 Merge pull request #6334 from fidencio/topic/fix-push-to-registry-behaviour
Revert "workflows: Push the builder image to quay.io"
2023-02-21 10:00:13 +01:00
Bin Liu
5c16e98d4f Merge pull request #6322 from Tim-Zhang/remove-remain-unsafe-impl
Remove all remaining unsafe impl
2023-02-21 14:08:05 +08:00
Fabiano Fidêncio
afaccf924d Revert "workflows: Push the builder image to quay.io"
This reverts commit b835c40bbd.

Right now I'm reverting this one as this should only run *after* commits
get pushed to our repo, not on very PR.
2023-02-20 18:37:28 +01:00
Fabiano Fidêncio
b1fd4b093b Merge pull request #6319 from singhwang/main
kata-deploy: Fix building the kata static firecracker arm64 package occurred an error
2023-02-20 18:04:31 +01:00
Christophe de Dinechin
4c39c4ef9f devguide: Add link to the contribution guidelines
New developers are often confused by some of our requirements, notably porting
labels. While our CONTRIBUTING.md file points to the solution, the developer's
guide does not. Add a link there.

Fixes: #6329

Signed-off-by: Christophe de Dinechin <christophe@dinechin.org>
2023-02-20 15:27:19 +01:00
Fabiano Fidêncio
a3b615919e Merge pull request #6323 from fidencio/topic/fix-make-shim-v2-tarball-on-aarch64
shim-v2: Bump Ubuntu container image  to 22.04
2023-02-20 14:57:34 +01:00
Jeremi Piotrowski
76e926453a osbuilder: Include minimal set of device nodes in ubuntu initrd
When starting an initrd the kernel expects to find /dev/console in the initrd,
so that it can connect it as stdin/stdout/stderr to the /init process. If the
device node is missing the kernel will complain that it was unable to open an
initial console. If kata-agent is the initrd init process, it will also result
in log messages not being logged to console and thus not forwarded to host
syslog.

Add a set of standard device nodes for completeness, so that console logging
works. To do that we install the makedev packge which provides a MAKEDEV helper
that knows the major/minor numbers. Unfortunately the debian package tries to
create devnodes from postinst, which can be suppressed if systemd-detect-virt
is present. That's why we create a small dummy script that matches what
systemd-detect-virt would output (anything is enough to suppress mknod).

Fixes: #6261
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-02-20 11:15:56 +01:00
Fabiano Fidêncio
6a0ac2b3a5 Merge pull request #6310 from kata-containers/topic/cache-artefacts-container-builder
packaging: Cache the container used to build the kata-deploy artefacts
2023-02-20 11:02:53 +01:00
James O. D. Hunt
0dea57c452 Merge pull request #6309 from gabevenberg/always-check-deps
utils: always check some dependencies.
2023-02-20 08:31:56 +00:00
SinghWang
697ec8e578 kata-deploy: Fix kata static firecracker arm64 package build error
When building the kata static arm64 package, the stages of firecracker report errors.

Fixes: #6318
Signed-off-by: SinghWang <wangxin_0611@126.com>
2023-02-20 16:10:18 +08:00
Helin Guo
ced3c99895 dragonball: config_manager: preserve device when update
DeviceConfigInfo contains config and device, so when we want to do
update we could simply update config part of the info, and device would
not be changed during update.

Fixes: #6324

Signed-off-by: Helin Guo <helinguo@linux.alibaba.com>
2023-02-20 14:34:09 +08:00
Tim Zhang
da8a6417aa runtime-rs: remove all remaining unsafe impl
Fixes: #6307

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-02-20 14:29:59 +08:00
Tim Zhang
0301194851 dragonball: use crossbeam_channel in VmmService instead of mpsc::channel
Because crossbeam_channel has more features and better performance than
mpsc::channel and finally rust replace its channel implementation with
crossbeam_channel on version 1.67

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-02-20 14:29:57 +08:00
Fabiano Fidêncio
9d78bf9086 shim-v2: Bump Ubuntu container image to 22.04
Let's bump the base container image to use the 22.04 version of Ubuntu,
as it does bring up-to-date package dependencies that we need to
statically build the runtime-rs on aarch64.

Fixes: #6320

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-20 07:14:09 +01:00
Fabiano Fidêncio
299fc35c37 Merge pull request #6304 from fidencio/topic/switch-the-default-x86_64-rootfs-image-to-ubuntu
versions: Use ubuntu as the default distro for the rootfs-image
2023-02-17 19:29:10 +01:00
Gabe Venberg
3cfce5a709 utils: improved unsupported distro message.
previously, if installing on unkown distro, script would tell user that
their distro was unsupported. Changed error message prompting user to
install dependecies manually, then retry.

Signed-off-by: Gabe Venberg <gabevenberg@gmail.com>
2023-02-17 09:06:26 -06:00
Bin Liu
f44dae75c9 Merge pull request #6267 from jongwooo/github-action/replace-deprecated-command-with-environment-file
github-action: Replace deprecated command with environment file
2023-02-17 22:54:12 +08:00
Fabiano Fidêncio
6a29088b81 Merge pull request #6298 from amshinde/update-release-doc
docs: Change the order of release step
2023-02-17 15:46:12 +01:00
Ji-Xinyou
919d19f415 feat(runtime): make static resource management consistent with 2.0
* add doc in the configuration
* make entry consistent with 2.0

Fixes: #6313
Signed-off-by: Ji-Xinyou <jerryji0414@outlook.com>
2023-02-17 21:36:56 +08:00
Bin Liu
b7fe29f033 Merge pull request #6308 from Tim-Zhang/remove-unnecessary-send-and-sync
runtime-rs: remove unnecessary Send/Sync trait implement
2023-02-17 19:53:54 +08:00
Fabiano Fidêncio
b835c40bbd workflows: Push the builder image to quay.io
Let's push the builder images to a registry, so we can take advantage of
those on each step of our building process.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
781ed2986a packaging: Allow passing a container builder to the scripts
This, combined with the effort of caching builder images *and* only
performing the build itself inside the builder images, is the very first
step for reproducible builds for the project.

Reproducible builds are quite important when we talk about Confidential
Containers, as users may want to verify the content used / provided by
the CSPs, and this is the first step towards that direction.

Fixes: #5517

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
45668fae15 packaging: Use existing image to build td-shim
Let's first try to pull a pre-existing image, instead of building our
own, to be used as a builder image for the td-shim.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
e8c6bfbdeb packaging: Use existing image to build td-shim
Let's first try to pull a pre-existing image, instead of building our
own, to be used as a builder image for the td-shim.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
3fa24f7acc packaging: Add infra to push the OVMF builder image
Let's add the needed infra for building and pushing the OVMF builder
image to the Kata Containers' quay.io registry.

Fixes: #5477

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
f076fa4c77 packaging: Use existing image to build OVMF
Let's first try to pull a pre-existing image, instead of buildinf our
own, to be used as a builder image for OVMF.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
c7f515172d packaging: Add infra to push the QEMU builder image
Let's add the needed infra for only building and pushing the QEMU
builder image to the Kata Containers' quay.io registry.

Fixes: #5481

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
fb7b86b8e0 packaging: Use existing image to build QEMU
Let's first try to pull a pre-existsing image, instead of building our
own, to be used as a builder image for QEMU.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
d0181bb262 packaging: Add infra to push the virtiofsd builder image
Let's add the needed infra for only building and pushing the virtiofsd
builder image to the Kata Containers' quay.io registry.

Fixes: #5480

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
7c93428a18 packaging: Use existing image to build virtiofsd
Let's first try to pull a pre-existing image, instead of building our
own, to be used as a builder image for the virtiofsd.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
8c227e2471 virtiofsd: Pass the expected toolchain to the build container
Let's ensure we're building virtiofsd with a specific toolchain that's
known to not cause any issues, instead of always using the latest one.

On each bump of the virtiofsd, we'll make sure to adjust this according
to what's been used by the virtiofsd community.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:48 +01:00
Fabiano Fidêncio
7ee00d8e57 packaging: Add infra to push the shim-v2 builder image
Let's add the needed infra for only building and pushing the shim-v2
builder image to the Kata Containers' quay.io registry.

Fixes: #5478

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:47 +01:00
Fabiano Fidêncio
24767d82aa packaging: Use existing image to build the shim-v2
Let's try to pull a pre-existing image, instead of building our own, to
be used as a builder for the shim-v2.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 12:06:24 +01:00
Amulyam24
e84af6a620 virtiofsd: update to a valid path on ppc64le
Currently the symbolic link for virtiofsd which is used as
a valid path is not updated on every CI run. Fix it by
using the actual path of installation.

Fixes: #6311

Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2023-02-17 16:22:39 +05:30
Fabiano Fidêncio
6c3c771a52 packaging: Add infra to push the kernel builder image
Let's add the needed infra for only building and pushing the kernel
builder image to the Kata Containers' quay.io registry.

Fixes: #5476

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 11:30:28 +01:00
Fabiano Fidêncio
b9b23112bf packaging: Use existing image to build the kernel
Let's first try to pull a pre-existing image, instead of building our
own, to be used as a builder image for the kernel.

This will save us some CI time.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 11:30:28 +01:00
Fabiano Fidêncio
869827d77f packaging: Add push_to_registry()
This function will push a specific tag to a registry, whenever the
PUSH_TO_REGISTRY environment variable is set, otherwise it's a no-op.

This will be used in the future to avoid replicating that logic in every
builder used by the kata-deploy scripts.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 11:30:21 +01:00
Fabiano Fidêncio
e69a6f5749 packaging: Add get_last_modification()
Let's add a function to get the hash of the last commit modifying a
specific file.

This will help to avoid writing `git rev-list ...` into every single
build script used by the kata-deploy.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 10:39:33 +01:00
Fabiano Fidêncio
6c05e5c67a packaging: Add and export BUILDER_REGISTRY
BUILD_REGISTRY, which points to quay.io/kata-containers/builder, will be
used for storing the builder images used to build the artefacts via the
kata-deploy scripts.

The plan is to tag, whenever it's possible and makes sense, images like:
* ${BUILDER_REGISTRY}:${component}-${unique_identifier}

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-17 10:39:33 +01:00
Fabiano Fidêncio
bd9af5569f Merge pull request #6296 from fidencio/topic/dont-build-runtime-rs-for-ppc64le-2nd-try
runtime-rs: Don't build on Power, don't break on Power.
2023-02-17 10:08:39 +01:00
Gabe Venberg
1047840cf8 utils: always check some dependencies.
Every dependency in check_deps is used inside the script (apart from
git, which may be a historical artifact), and therefore should be
checked even when the -f option is passed to the script. Simply changed
at what point check_deps is called in order to always run it.

Fixes #6302.

Signed-off-by: Gabe Venberg <gabevenberg@gmail.com>
2023-02-16 23:00:19 -06:00
Tim Zhang
95e3364493 runtime-rs: remove unnecessary Send/Sync trait implement
Send and Sync are automatically derived traits,
if a type is composed entirely of Send or Sync types, then it is Send or Sync.
Almost all primitives are Send and Sync,
so we don't need to implement them manually most of the time.

Fixes: #6307

Signed-off-by: Tim Zhang <tim@hyper.sh>
2023-02-17 11:51:13 +08:00
Archana Shinde
a96ba99239 actions: Use git-diff to get changes in kernel dir
Use `git-diff` instead of legacy `git-whatchanged` to get
differences in the packaging/kernel directory. This also fixes
a bug by grepping for the kernel directory in the output of the
git command.

Fixes: #6210

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-02-16 17:33:41 -08:00
Archana Shinde
619ef54452 docs: Change the order of release step
When a new stable branch is created, it is necessary to change the
references in the tests repo from main to the new stable branch.

However this step needs to be performed after the repos have been tagged
as the `tags_repos.sh` script is the one that creates the new branch.
Clarify this in the documentation and move the step to change branch
references in test repo after repos have been tagged.

Fixes: #1824

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-02-16 12:12:21 -08:00
Fabiano Fidêncio
a161d11920 versions: Use ubuntu as the default distro for the rootfs-image
Currently ubuntu is already the default distro for all the architectures
but x86_64, which uses clearlinux.  However, our CI does *not* test the
clearlinux image we ship.

Taking a look at our CI code [0], we've been using ubuntu as base for
the tests for a few years already, if not forever.

The minimum we can do is to switch to distributing ubuntu, as the tested
rootfs-image, and then decide later on whether we should switch back to
clearlinux (once we switch our CI to using that, and make sure all tests
will be green), or if we move to slimmer distro, such as alpine.

[0]: 0a39dd1a01/.ci/install_kata_image.sh (L44)

Fixes: #6303

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-16 20:30:40 +01:00
Fabiano Fidêncio
be40683bc5 runtime-rs: Add a generic powerpc64le-options.mk
There's a check in the runtime-rs Makefile that basically checks whether
the `arch/$arch-options.mk` exists or not and, if it doesn't, the build
is just aborted.

With this in mind, let's create a generic powerpc64le-options.mk file
and not bail when building for this architecture.

Fixes: #6142

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-16 16:29:24 +01:00
Fabiano Fidêncio
47c058599a packaging/shim-v2: Install the target depending on the arch/libc
In the `install_go_rust.sh` file we're adding a
x86_64-unknown-linux-musl target unconditionally.  That should be,
instead, based in the ARCH of the host and the appropriate LIBC to be
used with that host.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-16 16:29:24 +01:00
Fabiano Fidêncio
c1602c848a Merge pull request #6300 from openanolis/footloose
runtime-rs: handle sys_dir bind volume
2023-02-16 12:53:15 +01:00
alex.lyn
b582c0db86 kata-ctl/exec: add new command exec to enter guest VM.
The patchset will help users to easily enter guest VM by debug
console sock.

In order to enter guest VM smoothly, users needs to do some
configuration, options as below:
(1) Set debug_console_enabled = true with default vport 1026.
(2) Or add agent.debug_console agent.debug_console_vport=<PORT>
into kernel_params, and the vport is <PORT> you set.

The detail of usage:
$ kata-ctl exec -h
kata-ctl-exec
Enter into guest VM by debug console

USAGE:
kata-ctl exec [OPTIONS] <SANDBOX_ID>

ARGS:
<SANDBOX_ID> pod sandbox ID

Fixes: #5340

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2023-02-16 17:05:53 +08:00
Yushuo
07802a19dc runtime-rs: handle sys_dir bind volume
For some cases, users will mount system directories as bind volume.
We should not bind mount these kind of directories in the host as it does
not make sense.

Fixes: #6299

Signed-off-by: Yushuo <y-shuo@linux.alibaba.com>
2023-02-16 15:45:33 +08:00
Bin Liu
629a31ec6e Merge pull request #6287 from lifupan/main
sandbox: set the dns for the sandbox
2023-02-16 15:00:01 +08:00
Fabiano Fidêncio
f5b28736ce Merge pull request #6294 from fidencio/topic/only-change-configs-if-the-config-files-exist
packaging/shim-v2: Only change the config if the file exists
2023-02-16 07:13:28 +01:00
Fupan Li
04e930073c sandbox: set the dns for the sandbox
The rust agent had supported to set the guest dns
server in start sandbox request, thus add the dns
in the runtime side.

Fixes:#6286

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2023-02-16 11:25:02 +08:00
Fupan Li
32ebe1895b agent: fix the issue of creating the dns file
We should make sure the dns's source file's parent
directory exist, otherwise, it would failed to create
the file directly.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2023-02-16 11:24:54 +08:00
Peng Tao
139ad8e95f Merge pull request #6201 from jodh-intel/runtime-rs-add-cloud-hypervisor
runtime-rs: Add basic CH implementation
2023-02-16 11:23:04 +08:00
Archana Shinde
eba2bb275d Merge pull request #6284 from amshinde/revert-kata-deploy-changes-after-3.1.0-rc0-release
release: Revert kata-deploy changes after 3.1.0-rc0 release
2023-02-15 14:50:12 -08:00
jongwooo
44aaec9020 github-action: Replace deprecated command with environment file
In workflow, `set-output` command is deprecated and will be disabled soon.
This commit replaces the deprecated `set-output` command with putting a
value in the environment file `$GITHUB_OUTPUT`.

Fixes #6266

Signed-off-by: jongwooo <jongwooo.han@gmail.com>
2023-02-16 01:41:03 +09:00
Hyounggyu Choi
a68c5004f8 packaging/shim-v2: Only change the config if the file exists
Let's not try to sed a file that doesn't exist, which may be the case
depending on the architecture we're building the shim-v2 for.

This is a partial-forward port of
f24c47ea47.

Fixes: #6293

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2023-02-15 17:00:53 +01:00
Archana Shinde
ee76b398b3 release: Revert kata-deploy changes after 3.1.0-rc0 release
As 3.1.0-rc0 has been released, let's switch the kata-deploy / kata-cleanup
tags back to "latest", and re-add the kata-deploy-stable and the
kata-cleanup-stable files.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-02-14 15:47:51 -08:00
James O. D. Hunt
bbc733d6c8 docs: runtime-rs: Add CH status details
Add a few details about the current state of the Cloud Hypervisor (CH)
runtime-rs external hypervisor implementation with pointers to the
appropriate issues.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-02-14 15:38:46 +00:00
James O. D. Hunt
37b594c0d2 runtime-rs: Add basic CH implementation
Add a basic runtime-rs `Hypervisor` trait implementation for Cloud
Hypervisor (CH).

> **Notes:**
>
> - This only supports a default Kata configuration for CH currently.
>
> - Since this feature is still under development, `cargo` features have
>   been added to enable the feature optionally. The default is to not enable
>   currently since the code is not ready for general use.
>
>   To enable the feature for testing and development, enable the
>   `cloud-hypervisor` feature in the `virt_container` crate and enable the
>   `cloud-hypervisor` feature for its `hypervisor` dependency.

Fixes: #5242.

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-02-14 15:38:39 +00:00
James O. D. Hunt
545151829d kata-types: Add Cloud Hypervisor (CH) definitions
Implement `ConfigPlugin` trait for Cloud Hypervisor (CH).

Signed-off-by: James O. D. Hunt <james.o.hunt@intel.com>
2023-02-13 10:25:29 +00:00
Zhongtao Hu
2dd2421ad0 runtime-rs: cleanup kata host share path
cleanup the /run/kata-containers/shared/sandboxes/pid path

Fixes:#5975
Signed-off-by: Zhongtao Hu <zhongtaohu.tim@linux.alibaba.com>
2023-02-13 13:07:07 +08:00
Jeremi Piotrowski
0a21ad78b1 osbuilder: fix default build target in makefile
The .dracut_rootfs.done file is accidentally being picked up as the default
target, regardless of BUILD_METHOD. Move the 'all' target definition up, so
that it's the default (=first) target in the makefile. Additionally make the
.dracut_rootfs.done target conditional on the right BUILD_METHOD being
selected, as building it doesn't make sense with BUILD_METHOD=distro.

Fixes: #6235
Signed-off-by: Jeremi Piotrowski <jpiotrowski@microsoft.com>
2023-02-07 18:36:03 +01:00
wllenyj
9a01d4e446 dragonball: add more unit test for virtio-blk device.
Added more unit tests for virtio-blk device.

Fixes: #4899

Signed-off-by: wllenyj <wllenyj@linux.alibaba.com>
2023-02-07 17:16:11 +08:00
Archana Shinde
d3bb254188 utils: Add function to check vhost-vsock
Add function to check if the host-system has the vhost-vsock
kernel module.

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
2023-02-03 15:41:59 -08:00
435 changed files with 25552 additions and 4734 deletions

View File

@@ -62,15 +62,15 @@ jobs:
has_backport_needed_label=${{ contains(github.event.pull_request.labels.*.name, 'needs-backport') }}
has_no_backport_needed_label=${{ contains(github.event.pull_request.labels.*.name, 'no-backport-needed') }}
echo "::set-output name=add_backport_label::false"
echo "add_backport_label=false" >> $GITHUB_OUTPUT
if [ $has_backport_needed_label = true ] || [ $has_bug = true ]; then
if [[ $has_no_backport_needed_label = false ]]; then
echo "::set-output name=add_backport_label::true"
echo "add_backport_label=true" >> $GITHUB_OUTPUT
fi
fi
# Do not spam comment, only if auto-backport label is going to be newly added.
echo "::set-output name=auto_backport_added::$CONTAINS_AUTO_BACKPORT"
echo "auto_backport_added=$CONTAINS_AUTO_BACKPORT" >> $GITHUB_OUTPUT
- name: Add comment
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') && steps.add_label.outputs.add_backport_label == 'true' && steps.add_label.outputs.auto_backport_added == 'false' }}
@@ -97,4 +97,4 @@ jobs:
uses: andymckay/labeler@e6c4322d0397f3240f0e7e30a33b5c5df2d39e90
with:
add-labels: "auto-backport"
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,85 @@
name: CI | Build kata-static tarball for amd64
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
push-to-registry:
required: false
type: string
default: no
jobs:
build-asset:
runs-on: ubuntu-latest
strategy:
matrix:
asset:
- cloud-hypervisor
- firecracker
- kernel
- kernel-sev
- kernel-dragonball-experimental
- kernel-tdx-experimental
- kernel-nvidia-gpu
- kernel-nvidia-gpu-snp
- kernel-nvidia-gpu-tdx-experimental
- nydus
- ovmf
- ovmf-sev
- qemu
- qemu-snp-experimental
- qemu-tdx-experimental
- rootfs-image
- rootfs-initrd
- rootfs-initrd-sev
- shim-v2
- tdvf
- virtiofsd
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0 # This is needed in order to keep the commit ids history
- name: Build ${{ matrix.asset }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r "${build_dir}" "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
PUSH_TO_REGISTRY: ${{ inputs.push-to-registry }}
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v3
with:
name: kata-artifacts-amd64${{ inputs.tarball-suffix }}
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
retention-days: 1
if-no-files-found: error
create-kata-tarball:
runs-on: ubuntu-latest
needs: build-asset
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-artifacts
uses: actions/download-artifact@v3
with:
name: kata-artifacts-amd64${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: merge-artifacts
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-merge-builds.sh kata-artifacts
- name: store-artifacts
uses: actions/upload-artifact@v3
with:
name: kata-static-tarball-amd64${{ inputs.tarball-suffix }}
path: kata-static.tar.xz
retention-days: 1
if-no-files-found: error

View File

@@ -0,0 +1,82 @@
name: CI | Build kata-static tarball for arm64
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
push-to-registry:
required: false
type: string
default: no
jobs:
build-asset:
runs-on: arm64
strategy:
matrix:
asset:
- cloud-hypervisor
- firecracker
- kernel
- kernel-dragonball-experimental
- nydus
- qemu
- rootfs-image
- rootfs-initrd
- shim-v2
- virtiofsd
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0 # This is needed in order to keep the commit ids history
- name: Build ${{ matrix.asset }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r "${build_dir}" "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
PUSH_TO_REGISTRY: ${{ inputs.push-to-registry }}
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v3
with:
name: kata-artifacts-arm64${{ inputs.tarball-suffix }}
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
retention-days: 1
if-no-files-found: error
create-kata-tarball:
runs-on: arm64
needs: build-asset
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-artifacts
uses: actions/download-artifact@v3
with:
name: kata-artifacts-arm64${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: merge-artifacts
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-merge-builds.sh kata-artifacts
- name: store-artifacts
uses: actions/upload-artifact@v3
with:
name: kata-static-tarball-arm64${{ inputs.tarball-suffix }}
path: kata-static.tar.xz
retention-days: 1
if-no-files-found: error

View File

@@ -0,0 +1,79 @@
name: CI | Build kata-static tarball for s390x
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
push-to-registry:
required: false
type: string
default: no
jobs:
build-asset:
runs-on: s390x
strategy:
matrix:
asset:
- kernel
- qemu
- rootfs-image
- rootfs-initrd
- shim-v2
- virtiofsd
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0 # This is needed in order to keep the commit ids history
- name: Build ${{ matrix.asset }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r "${build_dir}" "kata-build"
sudo chown -R $(id -u):$(id -g) "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
PUSH_TO_REGISTRY: ${{ inputs.push-to-registry }}
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v3
with:
name: kata-artifacts-s390x${{ inputs.tarball-suffix }}
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
retention-days: 1
if-no-files-found: error
create-kata-tarball:
runs-on: s390x
needs: build-asset
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-artifacts
uses: actions/download-artifact@v3
with:
name: kata-artifacts-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: merge-artifacts
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-merge-builds.sh kata-artifacts
- name: store-artifacts
uses: actions/upload-artifact@v3
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-static.tar.xz
retention-days: 1
if-no-files-found: error

54
.github/workflows/ci-on-push.yaml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: Kata Containers CI
on:
pull_request_target:
branches:
- 'main'
jobs:
build-kata-static-tarball-amd64:
uses: ./.github/workflows/build-kata-static-tarball-amd64.yaml
with:
tarball-suffix: -${{ github.event.pull_request.number}}-${{ github.event.pull_request.head.sha }}
publish-kata-deploy-payload-amd64:
needs: build-kata-static-tarball-amd64
uses: ./.github/workflows/publish-kata-deploy-payload-amd64.yaml
with:
tarball-suffix: -${{ github.event.pull_request.number}}-${{ github.event.pull_request.head.sha }}
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-amd64
secrets: inherit
run-k8s-tests-on-aks:
needs: publish-kata-deploy-payload-amd64
uses: ./.github/workflows/run-k8s-tests-on-aks.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-amd64
secrets: inherit
run-k8s-tests-on-sev:
needs: publish-kata-deploy-payload-amd64
uses: ./.github/workflows/run-k8s-tests-on-sev.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-amd64
run-k8s-tests-on-snp:
needs: publish-kata-deploy-payload-amd64
uses: ./.github/workflows/run-k8s-tests-on-snp.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-amd64
run-k8s-tests-on-tdx:
needs: publish-kata-deploy-payload-amd64
uses: ./.github/workflows/run-k8s-tests-on-tdx.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-amd64

View File

@@ -62,6 +62,9 @@ jobs:
# to be specified at the start of the regex as the action is passed
# the entire commit message.
#
# - This check will pass if the commit message only contains a subject
# line, as other body message properties are enforced elsewhere.
#
# - Body lines *can* be longer than the maximum if they start
# with a non-alphabetic character or if there is no whitespace in
# the line.
@@ -75,7 +78,7 @@ jobs:
#
# - A SoB comment can be any length (as it is unreasonable to penalise
# people with long names/email addresses :)
pattern: '^.+(\n([a-zA-Z].{0,150}|[^a-zA-Z\n].*|[^\s\n]*|Signed-off-by:.*|))+$'
pattern: '(^[^\n]+$|^.+(\n([a-zA-Z].{0,150}|[^a-zA-Z\n].*|[^\s\n]*|Signed-off-by:.*|))+$)'
error: 'Body line too long (max 150)'
post_error: ${{ env.error_msg }}

View File

@@ -1,80 +0,0 @@
name: kata deploy build
on:
pull_request:
types:
- opened
- edited
- reopened
- synchronize
paths:
- tools/**
- versions.yaml
jobs:
build-asset:
runs-on: ubuntu-latest
strategy:
matrix:
asset:
- kernel
- kernel-dragonball-experimental
- shim-v2
- qemu
- cloud-hypervisor
- firecracker
- rootfs-image
- rootfs-initrd
- virtiofsd
- nydus
steps:
- uses: actions/checkout@v2
- name: Build ${{ matrix.asset }}
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r --preserve=all "${build_dir}" "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
- name: store-artifact ${{ matrix.asset }}
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: actions/upload-artifact@v2
with:
name: kata-artifacts
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
if-no-files-found: error
create-kata-tarball:
runs-on: ubuntu-latest
needs: build-asset
steps:
- uses: actions/checkout@v2
- name: get-artifacts
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: actions/download-artifact@v2
with:
name: kata-artifacts
path: build
- name: merge-artifacts
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
make merge-builds
- name: store-artifacts
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: actions/upload-artifact@v2
with:
name: kata-static-tarball
path: kata-static.tar.xz
make-kata-tarball:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: make kata-tarball
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
make kata-tarball
sudo make install-tarball

View File

@@ -1,164 +0,0 @@
on:
workflow_dispatch: # this is used to trigger the workflow on non-main branches
inputs:
pr:
description: 'PR number from the selected branch to test'
type: string
required: true
issue_comment:
types: [created, edited]
name: test-kata-deploy
jobs:
check-comment-and-membership:
runs-on: ubuntu-latest
if: |
github.event.issue.pull_request
&& github.event_name == 'issue_comment'
&& github.event.action == 'created'
&& startsWith(github.event.comment.body, '/test_kata_deploy')
|| github.event_name == 'workflow_dispatch'
steps:
- name: Check membership on comment or dispatch
uses: kata-containers/is-organization-member@1.0.1
id: is_organization_member
with:
organization: kata-containers
username: ${{ github.event.comment.user.login || github.event.sender.login }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Fail if not member
run: |
result=${{ steps.is_organization_member.outputs.result }}
if [ $result == false ]; then
user=${{ github.event.comment.user.login || github.event.sender.login }}
echo Either ${user} is not part of the kata-containers organization
echo or ${user} has its Organization Visibility set to Private at
echo https://github.com/orgs/kata-containers/people?query=${user}
echo
echo Ensure you change your Organization Visibility to Public and
echo trigger the test again.
exit 1
fi
build-asset:
runs-on: ubuntu-latest
needs: check-comment-and-membership
strategy:
matrix:
asset:
- cloud-hypervisor
- firecracker
- kernel
- kernel-dragonball-experimental
- nydus
- qemu
- rootfs-image
- rootfs-initrd
- shim-v2
- virtiofsd
steps:
- name: get-PR-ref
id: get-PR-ref
run: |
if [ ${{ github.event_name }} == 'issue_comment' ]; then
ref=$(cat $GITHUB_EVENT_PATH | jq -r '.issue.pull_request.url' | sed 's#^.*\/pulls#refs\/pull#' | sed 's#$#\/merge#')
else # workflow_dispatch
ref="refs/pull/${{ github.event.inputs.pr }}/merge"
fi
echo "reference for PR: " ${ref} "event:" ${{ github.event_name }}
echo "##[set-output name=pr-ref;]${ref}"
- uses: actions/checkout@v2
with:
ref: ${{ steps.get-PR-ref.outputs.pr-ref }}
- name: Build ${{ matrix.asset }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r "${build_dir}" "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v2
with:
name: kata-artifacts
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
if-no-files-found: error
create-kata-tarball:
runs-on: ubuntu-latest
needs: build-asset
steps:
- name: get-PR-ref
id: get-PR-ref
run: |
if [ ${{ github.event_name }} == 'issue_comment' ]; then
ref=$(cat $GITHUB_EVENT_PATH | jq -r '.issue.pull_request.url' | sed 's#^.*\/pulls#refs\/pull#' | sed 's#$#\/merge#')
else # workflow_dispatch
ref="refs/pull/${{ github.event.inputs.pr }}/merge"
fi
echo "reference for PR: " ${ref} "event:" ${{ github.event_name }}
echo "##[set-output name=pr-ref;]${ref}"
- uses: actions/checkout@v2
with:
ref: ${{ steps.get-PR-ref.outputs.pr-ref }}
- name: get-artifacts
uses: actions/download-artifact@v2
with:
name: kata-artifacts
path: kata-artifacts
- name: merge-artifacts
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-merge-builds.sh kata-artifacts
- name: store-artifacts
uses: actions/upload-artifact@v2
with:
name: kata-static-tarball
path: kata-static.tar.xz
kata-deploy:
needs: create-kata-tarball
runs-on: ubuntu-latest
steps:
- name: get-PR-ref
id: get-PR-ref
run: |
if [ ${{ github.event_name }} == 'issue_comment' ]; then
ref=$(cat $GITHUB_EVENT_PATH | jq -r '.issue.pull_request.url' | sed 's#^.*\/pulls#refs\/pull#' | sed 's#$#\/merge#')
else # workflow_dispatch
ref="refs/pull/${{ github.event.inputs.pr }}/merge"
fi
echo "reference for PR: " ${ref} "event:" ${{ github.event_name }}
echo "##[set-output name=pr-ref;]${ref}"
- uses: actions/checkout@v2
with:
ref: ${{ steps.get-PR-ref.outputs.pr-ref }}
- name: get-kata-tarball
uses: actions/download-artifact@v2
with:
name: kata-static-tarball
- name: build-and-push-kata-deploy-ci
id: build-and-push-kata-deploy-ci
run: |
PR_SHA=$(git log --format=format:%H -n1)
mv kata-static.tar.xz $GITHUB_WORKSPACE/tools/packaging/kata-deploy/kata-static.tar.xz
docker build --build-arg KATA_ARTIFACTS=kata-static.tar.xz -t quay.io/kata-containers/kata-deploy-ci:$PR_SHA $GITHUB_WORKSPACE/tools/packaging/kata-deploy
docker login -u ${{ secrets.QUAY_DEPLOYER_USERNAME }} -p ${{ secrets.QUAY_DEPLOYER_PASSWORD }} quay.io
docker push quay.io/kata-containers/kata-deploy-ci:$PR_SHA
mkdir -p packaging/kata-deploy
ln -s $GITHUB_WORKSPACE/tools/packaging/kata-deploy/action packaging/kata-deploy/action
echo "::set-output name=PKG_SHA::${PR_SHA}"
- name: test-kata-deploy-ci-in-aks
uses: ./packaging/kata-deploy/action
with:
packaging-sha: ${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}}
env:
PKG_SHA: ${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}}
AZ_APPID: ${{ secrets.AZ_APPID }}
AZ_PASSWORD: ${{ secrets.AZ_PASSWORD }}
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
AZ_TENANT_ID: ${{ secrets.AZ_TENANT_ID }}

View File

@@ -0,0 +1,71 @@
name: CI | Publish Kata Containers payload
on:
push:
branches:
- main
- stable-*
jobs:
build-assets-amd64:
uses: ./.github/workflows/build-kata-static-tarball-amd64.yaml
with:
push-to-registry: yes
build-assets-arm64:
uses: ./.github/workflows/build-kata-static-tarball-arm64.yaml
with:
push-to-registry: yes
build-assets-s390x:
uses: ./.github/workflows/build-kata-static-tarball-s390x.yaml
with:
push-to-registry: yes
publish-kata-deploy-payload-amd64:
needs: build-assets-amd64
uses: ./.github/workflows/publish-kata-deploy-payload-amd64.yaml
with:
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-amd64
secrets: inherit
publish-kata-deploy-payload-arm64:
needs: build-assets-arm64
uses: ./.github/workflows/publish-kata-deploy-payload-arm64.yaml
with:
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-arm64
secrets: inherit
publish-kata-deploy-payload-s390x:
needs: build-assets-s390x
uses: ./.github/workflows/publish-kata-deploy-payload-s390x.yaml
with:
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-s390x
secrets: inherit
publish-manifest:
runs-on: ubuntu-latest
needs: [publish-kata-deploy-payload-amd64, publish-kata-deploy-payload-arm64, publish-kata-deploy-payload-s390x]
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Login to Kata Containers quay.io
uses: docker/login-action@v2
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- name: Push multi-arch manifest
run: |
docker manifest create quay.io/kata-containers/kata-deploy-ci:kata-containers-latest \
--amend quay.io/kata-containers/kata-deploy-ci:kata-containers-amd64 \
--amend quay.io/kata-containers/kata-deploy-ci:kata-containers-arm64 \
--amend quay.io/kata-containers/kata-deploy-ci:kata-containers-s390x
docker manifest push quay.io/kata-containers/kata-deploy-ci:kata-containers-latest

View File

@@ -0,0 +1,52 @@
name: CI | Publish kata-deploy payload for amd64
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
kata-payload:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-amd64${{ inputs.tarball-suffix }}
- name: Login to Kata Containers quay.io
if: ${{ inputs.registry == 'quay.io' }}
uses: docker/login-action@v2
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- name: Login to Kata Containers ghcr.io
if: ${{ inputs.registry == 'ghcr.io' }}
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: build-and-push-kata-payload
id: build-and-push-kata-payload
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz \
${{ inputs.registry }}/${{ inputs.repo }} ${{ inputs.tag }}

View File

@@ -0,0 +1,57 @@
name: CI | Publish kata-deploy payload for arm64
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
kata-payload:
runs-on: arm64
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-arm64${{ inputs.tarball-suffix }}
- name: Login to Kata Containers quay.io
if: ${{ inputs.registry == 'quay.io' }}
uses: docker/login-action@v2
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- name: Login to Kata Containers ghcr.io
if: ${{ inputs.registry == 'ghcr.io' }}
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: build-and-push-kata-payload
id: build-and-push-kata-payload
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz \
${{ inputs.registry }}/${{ inputs.repo }} ${{ inputs.tag }}

View File

@@ -0,0 +1,56 @@
name: CI | Publish kata-deploy payload for s390x
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
kata-payload:
runs-on: s390x
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R $USER:$USER $GITHUB_WORKSPACE
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
- name: Login to Kata Containers quay.io
if: ${{ inputs.registry == 'quay.io' }}
uses: docker/login-action@v2
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- name: Login to Kata Containers ghcr.io
if: ${{ inputs.registry == 'ghcr.io' }}
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: build-and-push-kata-payload
id: build-and-push-kata-payload
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz \
${{ inputs.registry }}/${{ inputs.repo }} ${{ inputs.tag }}

63
.github/workflows/release-amd64.yaml vendored Normal file
View File

@@ -0,0 +1,63 @@
name: Publish Kata release artifacts for amd64
on:
workflow_call:
inputs:
target-arch:
required: true
type: string
jobs:
build-kata-static-tarball-amd64:
uses: ./.github/workflows/build-kata-static-tarball-amd64.yaml
kata-deploy:
needs: build-kata-static-tarball-amd64
runs-on: ubuntu-latest
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
with:
registry: docker.io
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- uses: actions/checkout@v3
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-amd64
- name: build-and-push-kata-deploy-ci-amd64
id: build-and-push-kata-deploy-ci-amd64
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
pushd $GITHUB_WORKSPACE
git checkout $tag
pkg_sha=$(git rev-parse HEAD)
popd
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "docker.io/katadocker/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "quay.io/kata-containers/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
- name: push-tarball
run: |
# tag the container image we created and push to DockerHub
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tags=($tag)
tags+=($([[ "$tag" =~ "alpha"|"rc" ]] && echo "latest" || echo "stable"))
for tag in ${tags[@]}; do
docker tag docker.io/katadocker/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-amd64.outputs.PKG_SHA}}-${{ inputs.target-arch }} docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker tag quay.io/kata-containers/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-amd64.outputs.PKG_SHA}}-${{ inputs.target-arch }} quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
done

63
.github/workflows/release-arm64.yaml vendored Normal file
View File

@@ -0,0 +1,63 @@
name: Publish Kata release artifacts for arm64
on:
workflow_call:
inputs:
target-arch:
required: true
type: string
jobs:
build-kata-static-tarball-arm64:
uses: ./.github/workflows/build-kata-static-tarball-arm64.yaml
kata-deploy:
needs: build-kata-static-tarball-arm64
runs-on: arm64
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
with:
registry: docker.io
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- uses: actions/checkout@v3
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-arm64
- name: build-and-push-kata-deploy-ci-arm64
id: build-and-push-kata-deploy-ci-arm64
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
pushd $GITHUB_WORKSPACE
git checkout $tag
pkg_sha=$(git rev-parse HEAD)
popd
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "docker.io/katadocker/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "quay.io/kata-containers/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
- name: push-tarball
run: |
# tag the container image we created and push to DockerHub
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tags=($tag)
tags+=($([[ "$tag" =~ "alpha"|"rc" ]] && echo "latest" || echo "stable"))
for tag in ${tags[@]}; do
docker tag docker.io/katadocker/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-arm64.outputs.PKG_SHA}}-${{ inputs.target-arch }} docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker tag quay.io/kata-containers/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-arm64.outputs.PKG_SHA}}-${{ inputs.target-arch }} quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
done

63
.github/workflows/release-s390x.yaml vendored Normal file
View File

@@ -0,0 +1,63 @@
name: Publish Kata release artifacts for s390x
on:
workflow_call:
inputs:
target-arch:
required: true
type: string
jobs:
build-kata-static-tarball-s390x:
uses: ./.github/workflows/build-kata-static-tarball-s390x.yaml
kata-deploy:
needs: create-kata-tarball
runs-on: s390x
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
with:
registry: docker.io
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- uses: actions/checkout@v3
- name: get-kata-tarball
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-s390x
- name: build-and-push-kata-deploy-ci-s390x
id: build-and-push-kata-deploy-ci-s390x
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
pushd $GITHUB_WORKSPACE
git checkout $tag
pkg_sha=$(git rev-parse HEAD)
popd
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "docker.io/katadocker/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \
$(pwd)/kata-static.tar.xz "quay.io/kata-containers/kata-deploy-ci" \
"${pkg_sha}-${{ inputs.target-arch }}"
- name: push-tarball
run: |
# tag the container image we created and push to DockerHub
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tags=($tag)
tags+=($([[ "$tag" =~ "alpha"|"rc" ]] && echo "latest" || echo "stable"))
for tag in ${tags[@]}; do
docker tag docker.io/katadocker/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-s390x.outputs.PKG_SHA}}-${{ inputs.target-arch }} docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker tag quay.io/kata-containers/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci-s390x.outputs.PKG_SHA}}-${{ inputs.target-arch }} quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push docker.io/katadocker/kata-deploy:${tag}-${{ inputs.target-arch }}
docker push quay.io/kata-containers/kata-deploy:${tag}-${{ inputs.target-arch }}
done

View File

@@ -5,124 +5,83 @@ on:
- '[0-9]+.[0-9]+.[0-9]+*'
jobs:
build-asset:
runs-on: ubuntu-latest
strategy:
matrix:
asset:
- cloud-hypervisor
- firecracker
- kernel
- kernel-dragonball-experimental
- nydus
- qemu
- rootfs-image
- rootfs-initrd
- shim-v2
- virtiofsd
steps:
- uses: actions/checkout@v2
- name: Build ${{ matrix.asset }}
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-copy-yq-installer.sh
./tools/packaging/kata-deploy/local-build/kata-deploy-binaries-in-docker.sh --build="${KATA_ASSET}"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
sudo cp -r "${build_dir}" "kata-build"
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
build-and-push-assets-amd64:
uses: ./.github/workflows/release-amd64.yaml
with:
target-arch: amd64
secrets: inherit
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v2
with:
name: kata-artifacts
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
if-no-files-found: error
build-and-push-assets-arm64:
uses: ./.github/workflows/release-arm64.yaml
with:
target-arch: arm64
secrets: inherit
create-kata-tarball:
runs-on: ubuntu-latest
needs: build-asset
steps:
- uses: actions/checkout@v2
- name: get-artifacts
uses: actions/download-artifact@v2
with:
name: kata-artifacts
path: kata-artifacts
- name: merge-artifacts
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-merge-builds.sh kata-artifacts
- name: store-artifacts
uses: actions/upload-artifact@v2
with:
name: kata-static-tarball
path: kata-static.tar.xz
build-and-push-assets-s390x:
uses: ./.github/workflows/release-s390x.yaml
with:
target-arch: s390x
secrets: inherit
kata-deploy:
needs: create-kata-tarball
publish-multi-arch-images:
runs-on: ubuntu-latest
needs: [build-and-push-assets-amd64, build-and-push-assets-arm64, build-and-push-assets-s390x]
steps:
- uses: actions/checkout@v2
- name: get-kata-tarball
uses: actions/download-artifact@v2
- name: Checkout repository
uses: actions/checkout@v3
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
with:
name: kata-static-tarball
- name: build-and-push-kata-deploy-ci
id: build-and-push-kata-deploy-ci
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
pushd $GITHUB_WORKSPACE
git checkout $tag
pkg_sha=$(git rev-parse HEAD)
popd
mv kata-static.tar.xz $GITHUB_WORKSPACE/tools/packaging/kata-deploy/kata-static.tar.xz
docker build --build-arg KATA_ARTIFACTS=kata-static.tar.xz -t katadocker/kata-deploy-ci:$pkg_sha -t quay.io/kata-containers/kata-deploy-ci:$pkg_sha $GITHUB_WORKSPACE/tools/packaging/kata-deploy
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker push katadocker/kata-deploy-ci:$pkg_sha
docker login -u ${{ secrets.QUAY_DEPLOYER_USERNAME }} -p ${{ secrets.QUAY_DEPLOYER_PASSWORD }} quay.io
docker push quay.io/kata-containers/kata-deploy-ci:$pkg_sha
mkdir -p packaging/kata-deploy
ln -s $GITHUB_WORKSPACE/tools/packaging/kata-deploy/action packaging/kata-deploy/action
echo "::set-output name=PKG_SHA::${pkg_sha}"
- name: test-kata-deploy-ci-in-aks
uses: ./packaging/kata-deploy/action
registry: docker.io
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
with:
packaging-sha: ${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}}
env:
PKG_SHA: ${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}}
AZ_APPID: ${{ secrets.AZ_APPID }}
AZ_PASSWORD: ${{ secrets.AZ_PASSWORD }}
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
AZ_TENANT_ID: ${{ secrets.AZ_TENANT_ID }}
- name: push-tarball
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- name: Push multi-arch manifest
run: |
# tag the container image we created and push to DockerHub
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tags=($tag)
tags+=($([[ "$tag" =~ "alpha"|"rc" ]] && echo "latest" || echo "stable"))
for tag in ${tags[@]}; do \
docker tag katadocker/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}} katadocker/kata-deploy:${tag} && \
docker tag quay.io/kata-containers/kata-deploy-ci:${{steps.build-and-push-kata-deploy-ci.outputs.PKG_SHA}} quay.io/kata-containers/kata-deploy:${tag} && \
docker push katadocker/kata-deploy:${tag} && \
docker push quay.io/kata-containers/kata-deploy:${tag}; \
# push to quay.io and docker.io
for tag in ${tags[@]}; do
docker manifest create quay.io/kata-containers/kata-deploy:${tag} \
--amend quay.io/kata-containers/kata-deploy:${tag}-amd64 \
--amend quay.io/kata-containers/kata-deploy:${tag}-arm64 \
--amend quay.io/kata-containers/kata-deploy:${tag}-s390x
docker manifest create docker.io/katadocker/kata-deploy:${tag} \
--amend docker.io/katadocker/kata-deploy:${tag}-amd64 \
--amend docker.io/katadocker/kata-deploy:${tag}-arm64 \
--amend docker.io/katadocker/kata-deploy:${tag}-s390x
docker manifest push quay.io/kata-containers/kata-deploy:${tag}
docker manifest push docker.io/katadocker/kata-deploy:${tag}
done
upload-static-tarball:
needs: kata-deploy
upload-multi-arch-static-tarball:
needs: publish-multi-arch-images
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: download-artifacts
uses: actions/download-artifact@v2
with:
name: kata-static-tarball
- uses: actions/checkout@v3
- name: install hub
run: |
HUB_VER=$(curl -s "https://api.github.com/repos/github/hub/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget -q -O- https://github.com/github/hub/releases/download/v$HUB_VER/hub-linux-amd64-$HUB_VER.tgz | \
tar xz --strip-components=2 --wildcards '*/bin/hub' && sudo mv hub /usr/local/bin/hub
- name: push static tarball to github
- name: download-artifacts-amd64
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-amd64
- name: push amd64 static tarball to github
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tarball="kata-static-$tag-x86_64.tar.xz"
@@ -132,11 +91,39 @@ jobs:
GITHUB_TOKEN=${{ secrets.GIT_UPLOAD_TOKEN }} hub release edit -m "" -a "${tarball}" "${tag}"
popd
- name: download-artifacts-arm64
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-arm64
- name: push arm64 static tarball to github
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tarball="kata-static-$tag-aarch64.tar.xz"
mv kata-static.tar.xz "$GITHUB_WORKSPACE/${tarball}"
pushd $GITHUB_WORKSPACE
echo "uploading asset '${tarball}' for tag: ${tag}"
GITHUB_TOKEN=${{ secrets.GIT_UPLOAD_TOKEN }} hub release edit -m "" -a "${tarball}" "${tag}"
popd
- name: download-artifacts-s390x
uses: actions/download-artifact@v3
with:
name: kata-static-tarball-s390x
- name: push s390x static tarball to github
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tarball="kata-static-$tag-s390x.tar.xz"
mv kata-static.tar.xz "$GITHUB_WORKSPACE/${tarball}"
pushd $GITHUB_WORKSPACE
echo "uploading asset '${tarball}' for tag: ${tag}"
GITHUB_TOKEN=${{ secrets.GIT_UPLOAD_TOKEN }} hub release edit -m "" -a "${tarball}" "${tag}"
popd
upload-cargo-vendored-tarball:
needs: upload-static-tarball
needs: upload-multi-arch-static-tarball
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: generate-and-upload-tarball
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
@@ -150,7 +137,7 @@ jobs:
needs: upload-cargo-vendored-tarball
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: download-and-upload-tarball
env:
GITHUB_TOKEN: ${{ secrets.GIT_UPLOAD_TOKEN }}

View File

@@ -0,0 +1,95 @@
name: CI | Run kubernetes tests on AKS
on:
workflow_call:
inputs:
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
run-k8s-tests:
strategy:
fail-fast: false
matrix:
vmm:
- clh
- dragonball
- qemu
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Download Azure CLI
run: |
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
- name: Log into the Azure account
run: |
az login \
--service-principal \
-u "${{ secrets.AZ_APPID }}" \
-p "${{ secrets.AZ_PASSWORD }}" \
--tenant "${{ secrets.AZ_TENANT_ID }}"
- name: Create AKS cluster
run: |
az aks create \
-g "kataCI" \
-n "${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-${{ matrix.vmm }}-amd64" \
-s "Standard_D4s_v5" \
--node-count 1 \
--generate-ssh-keys
- name: Install `bats`
run: |
sudo apt-get update
sudo apt-get -y install bats
- name: Install `kubectl`
run: |
sudo az aks install-cli
- name: Download credentials for the Kubernetes CLI to use them
run: |
az aks get-credentials -g "kataCI" -n ${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-${{ matrix.vmm }}-amd64
- name: Run tests
timeout-minutes: 30
run: |
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl apply -f tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
kubectl -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod
kubectl apply -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml
# This is needed as the kata-deploy pod will be set to "Ready" when it starts running,
# which may cause issues like not having the node properly labeled or the artefacts
# properly deployed when the tests actually start running.
sleep 60s
pushd tests/integration/kubernetes
sed -i -e 's|runtimeClassName: kata|runtimeClassName: kata-${{ matrix.vmm }}|' runtimeclass_workloads/*.yaml
bash run_kubernetes_tests.sh
popd
env:
KATA_HYPERVISOR: ${{ matrix.vmm }}
- name: Delete AKS cluster
if: always()
run: |
az aks delete \
-g "kataCI" \
-n "${{ github.event.pull_request.number }}-${{ github.event.pull_request.head.sha }}-${{ matrix.vmm }}-amd64" \
--yes \
--no-wait

View File

@@ -0,0 +1,68 @@
name: CI | Run kubernetes tests on SEV
on:
workflow_call:
inputs:
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
run-k8s-tests:
strategy:
fail-fast: false
matrix:
vmm:
- qemu-sev
runs-on: sev
env:
KUBECONFIG: /home/kata/.kube/config
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Run tests
timeout-minutes: 30
run: |
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl apply -f tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
kubectl -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod
kubectl apply -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml
# This is needed as the kata-deploy pod will be set to "Ready" when it starts running,
# which may cause issues like not having the node properly labeled or the artefacts
# properly deployed when the tests actually start running.
sleep 60s
pushd tests/integration/kubernetes
sed -i -e 's|runtimeClassName: kata|runtimeClassName: kata-${{ matrix.vmm }}|' runtimeclass_workloads/*.yaml
bash run_kubernetes_tests.sh
popd
env:
KATA_HYPERVISOR: ${{ matrix.vmm }}
- name: Delete kata-deploy
if: always()
run: |
kubectl delete -f tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
kubectl -n kube-system wait --timeout=10m --for=delete -l name=kata-deploy pod
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
sleep 180s
kubectl delete -f tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
kubectl delete -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl delete -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml

View File

@@ -0,0 +1,68 @@
name: CI | Run kubernetes tests on SEV-SNP
on:
workflow_call:
inputs:
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
run-k8s-tests:
strategy:
fail-fast: false
matrix:
vmm:
- qemu-snp
runs-on: sev-snp
env:
KUBECONFIG: /home/kata/.kube/config
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Run tests
timeout-minutes: 30
run: |
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl apply -f tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
kubectl -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod
kubectl apply -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml
# This is needed as the kata-deploy pod will be set to "Ready" when it starts running,
# which may cause issues like not having the node properly labeled or the artefacts
# properly deployed when the tests actually start running.
sleep 60s
pushd tests/integration/kubernetes
sed -i -e 's|runtimeClassName: kata|runtimeClassName: kata-${{ matrix.vmm }}|' runtimeclass_workloads/*.yaml
bash run_kubernetes_tests.sh
popd
env:
KATA_HYPERVISOR: ${{ matrix.vmm }}
- name: Delete kata-deploy
if: always()
run: |
kubectl delete -f tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
kubectl -n kube-system wait --timeout=10m --for=delete -l name=kata-deploy pod
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
sleep 180s
kubectl delete -f tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
kubectl delete -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl delete -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml

View File

@@ -0,0 +1,68 @@
name: CI | Run kubernetes tests on TDX
on:
workflow_call:
inputs:
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
jobs:
run-k8s-tests:
strategy:
fail-fast: false
matrix:
vmm:
- qemu-tdx
runs-on: tdx
env:
KUBECONFIG: /etc/rancher/k3s/k3s.yaml
steps:
- uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Run tests
timeout-minutes: 30
run: |
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml
cat tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl apply -k tools/packaging/kata-deploy/kata-deploy/overlays/k3s
kubectl -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod
kubectl apply -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml
# This is needed as the kata-deploy pod will be set to "Ready" when it starts running,
# which may cause issues like not having the node properly labeled or the artefacts
# properly deployed when the tests actually start running.
sleep 60s
pushd tests/integration/kubernetes
sed -i -e 's|runtimeClassName: kata|runtimeClassName: kata-${{ matrix.vmm }}|' runtimeclass_workloads/*.yaml
bash run_kubernetes_tests.sh
popd
env:
KATA_HYPERVISOR: ${{ matrix.vmm }}
- name: Delete kata-deploy
if: always()
run: |
kubectl delete -k tools/packaging/kata-deploy/kata-deploy/overlays/k3s
kubectl -n kube-system wait --timeout=10m --for=delete -l name=kata-deploy pod
sed -i -e "s|quay.io/kata-containers/kata-deploy:latest|${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}|g" tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
cat tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml | grep "${{ inputs.registry }}/${{ inputs.repo }}:${{ inputs.tag }}" || die "Failed to setup the tests image"
kubectl apply -k tools/packaging/kata-deploy/kata-cleanup/overlays/k3s
sleep 180s
kubectl delete -k tools/packaging/kata-deploy/kata-cleanup/overlays/k3s
kubectl delete -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
kubectl delete -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml

View File

@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-20.04
steps:
- name: Check out Git repository
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 0
@@ -32,6 +32,7 @@ jobs:
run: |
# Removing man-db, workflow kept failing, fixes: #4480
sudo apt -y remove --purge man-db
sudo apt-get update
sudo apt-get install -y git git-extras
kata_url="https://github.com/kata-containers/kata-containers"
latest_version=$(git ls-remote --tags ${kata_url} | egrep -o "refs.*" | egrep -v "\-alpha|\-rc|{}" | egrep -o "[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+" | sort -V -r | head -1)

View File

@@ -14,7 +14,7 @@ jobs:
steps:
- name: Check out
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 0

View File

@@ -19,13 +19,14 @@ jobs:
- "make test"
- "sudo -E PATH=\"$PATH\" make test"
env:
TRAVIS: "true"
TRAVIS_BRANCH: ${{ github.base_ref }}
TRAVIS_PULL_REQUEST_BRANCH: ${{ github.head_ref }}
TRAVIS_PULL_REQUEST_SHA : ${{ github.event.pull_request.head.sha }}
RUST_BACKTRACE: "1"
target_branch: ${{ github.base_ref }}
GOPATH: ${{ github.workspace }}
steps:
- name: Free disk space
run: |
sudo rm -rf /usr/share/dotnet
sudo rm -rf "$AGENT_TOOLSDIRECTORY"
- name: Checkout code
uses: actions/checkout@v3
with:
@@ -35,16 +36,13 @@ jobs:
uses: actions/setup-go@v3
with:
go-version: 1.19.3
env:
GOPATH: ${{ runner.workspace }}/kata-containers
- name: Check kernel config version
run: |
cd "${{ github.workspace }}/src/github.com/${{ github.repository }}"
kernel_dir="tools/packaging/kernel/"
kernel_version_file="${kernel_dir}kata_config_version"
modified_files=$(git diff --name-only origin/main..HEAD)
result=$(git whatchanged origin/main..HEAD "${kernel_dir}" >>"/dev/null")
if git whatchanged origin/main..HEAD "${kernel_dir}" >>"/dev/null"; then
if git diff --name-only origin/main..HEAD "${kernel_dir}" | grep "${kernel_dir}"; then
echo "Kernel directory has changed, checking if $kernel_version_file has been updated"
if echo "$modified_files" | grep -v "README.md" | grep "${kernel_dir}" >>"/dev/null"; then
echo "$modified_files" | grep "$kernel_version_file" >>/dev/null || ( echo "Please bump version in $kernel_version_file" && exit 1)
@@ -53,29 +51,14 @@ jobs:
fi
echo "Check passed"
fi
- name: Setup GOPATH
- name: Set PATH
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
echo "TRAVIS_BRANCH: ${TRAVIS_BRANCH}"
echo "TRAVIS_PULL_REQUEST_BRANCH: ${TRAVIS_PULL_REQUEST_BRANCH}"
echo "TRAVIS_PULL_REQUEST_SHA: ${TRAVIS_PULL_REQUEST_SHA}"
echo "TRAVIS: ${TRAVIS}"
- name: Set env
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV
echo "${{ github.workspace }}/bin" >> $GITHUB_PATH
- name: Setup travis references
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
echo "TRAVIS_BRANCH=${TRAVIS_BRANCH:-$(echo $GITHUB_REF | awk 'BEGIN { FS = \"/\" } ; { print $3 }')}"
target_branch=${TRAVIS_BRANCH}
- name: Setup
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |
cd ${GOPATH}/src/github.com/${{ github.repository }} && ./ci/setup.sh
env:
GOPATH: ${{ runner.workspace }}/kata-containers
- name: Installing rust
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
run: |

2
.gitignore vendored
View File

@@ -6,6 +6,8 @@
**/.vscode
**/.idea
**/.fleet
**/*.swp
**/*.swo
pkg/logging/Cargo.lock
src/agent/src/version.rs
src/agent/kata-agent.service

View File

@@ -18,6 +18,7 @@ TOOLS =
TOOLS += agent-ctl
TOOLS += kata-ctl
TOOLS += log-parser
TOOLS += log-parser-rs
TOOLS += runk
TOOLS += trace-forwarder

View File

@@ -134,6 +134,7 @@ The table below lists the remaining parts of the project:
| [osbuilder](tools/osbuilder) | infrastructure | Tool to create "mini O/S" rootfs and initrd images and kernel for the hypervisor. |
| [`agent-ctl`](src/tools/agent-ctl) | utility | Tool that provides low-level access for testing the agent. |
| [`kata-ctl`](src/tools/kata-ctl) | utility | Tool that provides advanced commands and debug facilities. |
| [`log-parser-rs`](src/tools/log-parser-rs) | utility | Tool that aid in analyzing logs from the kata runtime. |
| [`trace-forwarder`](src/tools/trace-forwarder) | utility | Agent tracing helper. |
| [`runk`](src/tools/runk) | utility | Standard OCI container runtime based on the agent. |
| [`ci`](https://github.com/kata-containers/ci) | CI | Continuous Integration configuration files and scripts. |

View File

@@ -1 +1 @@
3.1.2
3.2.0-alpha1

View File

@@ -2,6 +2,8 @@
This document is written **specifically for developers**: it is not intended for end users.
If you want to contribute changes that you have made, please read the [community guidelines](https://github.com/kata-containers/community/blob/main/CONTRIBUTING.md) for information about our processes.
# Assumptions
- You are working on a non-critical test or development system.
@@ -654,7 +656,7 @@ section when using rootfs, or when using initrd, complete the steps in the [Buil
Install the image:
>**Note**: When using an initrd image, replace the below rootfs image name `kata-containers.img`
>**Note**: When using an initrd image, replace the below rootfs image name `kata-containers.img`
>with the initrd image name `kata-containers-initrd.img`.
```bash
@@ -688,25 +690,25 @@ $ sudo crictl run -r kata container.yaml pod.yaml
The steps required to enable debug console for QEMU slightly differ with
those for firecracker / cloud-hypervisor.
##### Enabling debug console for QEMU
Add `agent.debug_console` to the guest kernel command line to allow the agent process to start a debug console.
Add `agent.debug_console` to the guest kernel command line to allow the agent process to start a debug console.
```bash
$ sudo sed -i -e 's/^kernel_params = "\(.*\)"/kernel_params = "\1 agent.debug_console"/g' "${kata_configuration_file}"
```
Here `kata_configuration_file` could point to `/etc/kata-containers/configuration.toml`
Here `kata_configuration_file` could point to `/etc/kata-containers/configuration.toml`
or `/usr/share/defaults/kata-containers/configuration.toml`
or `/opt/kata/share/defaults/kata-containers/configuration-{hypervisor}.toml`, if
you installed Kata Containers using `kata-deploy`.
##### Enabling debug console for cloud-hypervisor / firecracker
Slightly different configuration is required in case of firecracker and cloud hypervisor.
Firecracker and cloud-hypervisor don't have a UNIX socket connected to `/dev/console`.
Hence, the kernel command line option `agent.debug_console` will not work for them.
Slightly different configuration is required in case of firecracker and cloud hypervisor.
Firecracker and cloud-hypervisor don't have a UNIX socket connected to `/dev/console`.
Hence, the kernel command line option `agent.debug_console` will not work for them.
These hypervisors support `hybrid vsocks`, which can be used for communication
between the host and the guest. The kernel command line option `agent.debug_console_vport`
was added to allow developers specify on which `vsock` port the debugging console should be connected.
@@ -719,7 +721,7 @@ sudo sed -i -e 's/^kernel_params = "\(.*\)"/kernel_params = "\1 agent.debug_cons
```
> **Note** Ports 1024 and 1025 are reserved for communication with the agent
> and gathering of agent logs respectively.
> and gathering of agent logs respectively.
##### Connecting to the debug console

View File

@@ -28,23 +28,6 @@
$ ./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.
@@ -63,6 +46,24 @@
$ ./tag_repos.sh -p -b "$BRANCH" tag
```
### Point tests repository to stable branch
If your release changes a major or minor version number(not a patch release), then the above
`./tag_repos.sh` script will create a new stable branch in all the repositories in addition to tagging them.
This happens when you are making the first `rc` release for a new major or minor version in Kata.
In this case, you should modify the `tests` repository to point to the 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 of the `main` branch to the new stable 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.
### Check Git-hub Actions
We make use of [GitHub actions](https://github.com/features/actions) in this [file](../.github/workflows/release.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.

View File

@@ -11,6 +11,7 @@ Kata Containers design documents:
- [Host cgroups](host-cgroups.md)
- [Agent systemd cgroup](agent-systemd-cgroup.md)
- [`Inotify` support](inotify.md)
- [`Hooks` support](hooks-handling.md)
- [Metrics(Kata 2.0)](kata-2-0-metrics.md)
- [Design for Kata Containers `Lazyload` ability with `nydus`](kata-nydus-design.md)
- [Design for direct-assigned volume](direct-blk-device-assignment.md)

View File

@@ -36,7 +36,7 @@ compatibility, and performance on par with MACVTAP.
Kata Containers has deprecated support for bridge due to lacking performance relative to TC-filter and MACVTAP.
Kata Containers supports both
[CNM](https://github.com/docker/libnetwork/blob/master/docs/design.md#the-container-network-model)
[CNM](https://github.com/moby/libnetwork/blob/master/docs/design.md#the-container-network-model)
and [CNI](https://github.com/containernetworking/cni) for networking management.
## Network Hotplug

View File

@@ -0,0 +1,63 @@
# Kata Containers support for `Hooks`
## Introduction
During container's lifecycle, different Hooks can be executed to do custom actions. In Kata Containers, we support two types of Hooks, `OCI Hooks` and `Kata Hooks`.
### OCI Hooks
The OCI Spec stipulates six hooks that can be executed at different time points and namespaces, including `Prestart Hooks`, `CreateRuntime Hooks`, `CreateContainer Hooks`, `StartContainer Hooks`, `Poststart Hooks` and `Poststop Hooks`. We support these types of Hooks as compatible as possible in Kata Containers.
The path and arguments of these hooks will be passed to Kata for execution via `bundle/config.json`. For example:
```
...
"hooks": {
"prestart": [
{
"path": "/usr/bin/prestart-hook",
"args": ["prestart-hook", "arg1", "arg2"],
"env": [ "key1=value1"]
}
],
"createRuntime": [
{
"path": "/usr/bin/createRuntime-hook",
"args": ["createRuntime-hook", "arg1", "arg2"],
"env": [ "key1=value1"]
}
]
}
...
```
### Kata Hooks
In Kata, we support another three kinds of hooks executed in guest VM, including `Guest Prestart Hook`, `Guest Poststart Hook`, `Guest Poststop Hook`.
The executable files for Kata Hooks must be packaged in the *guest rootfs*. The file path to those guest hooks should be specified in the configuration file, and guest hooks must be stored in a subdirectory of `guest_hook_path` according to their hook type. For example:
+ In configuration file:
```
guest_hook_path="/usr/share/hooks"
```
+ In guest rootfs, prestart-hook is stored in `/usr/share/hooks/prestart/prestart-hook`.
## Execution
The table below summarized when and where those different hooks will be executed in Kata Containers:
| Hook Name | Hook Type | Hook Path | Exec Place | Exec Time |
|---|---|---|---|---|
| `Prestart(deprecated)` | OCI hook | host runtime namespace | host runtime namespace | After VM is started, before container is created. |
| `CreateRuntime` | OCI hook | host runtime namespace | host runtime namespace | After VM is started, before container is created, after `Prestart` hooks. |
| `CreateContainer` | OCI hook | host runtime namespace | host vmm namespace* | After VM is started, before container is created, after `CreateRuntime` hooks. |
| `StartContainer` | OCI hook | guest container namespace | guest container namespace | After container is created, before container is started. |
| `Poststart` | OCI hook | host runtime namespace | host runtime namespace | After container is started, before start operation returns. |
| `Poststop` | OCI hook | host runtime namespace | host runtime namespace | After container is deleted, before delete operation returns. |
| `Guest Prestart` | Kata hook | guest agent namespace | guest agent namespace | During start operation, before container command is executed. |
| `Guest Poststart` | Kata hook | guest agent namespace | guest agent namespace | During start operation, after container command is executed, before start operation returns. |
| `Guest Poststop` | Kata hook | guest agent namespace | guest agent namespace | During delete operation, after container is deleted, before delete operation returns. |
+ `Hook Path` specifies where hook's path be resolved.
+ `Exec Place` specifies in which namespace those hooks can be executed.
+ For `CreateContainer` Hooks, OCI requires to run them inside the container namespace while the hook executable path is in the host runtime, which is a non-starter for VM-based containers. So we design to keep them running in the *host vmm namespace.*
+ `Exec Time` specifies at which time point those hooks can be executed.

View File

@@ -44,12 +44,11 @@ $ popd
- Build a custom QEMU
```bash
$ source kata-containers/tools/packaging/scripts/lib.sh
$ qemu_url="$(get_from_kata_deps "assets.hypervisor.qemu.snp.url")"
$ qemu_branch="$(get_from_kata_deps "assets.hypervisor.qemu.snp.branch")"
$ qemu_commit="$(get_from_kata_deps "assets.hypervisor.qemu.snp.commit")"
$ git clone -b "${qemu_branch}" "${qemu_url}"
$ qemu_url="$(get_from_kata_deps "assets.hypervisor.qemu-snp-experimental.url")"
$ qemu_tag="$(get_from_kata_deps "assets.hypervisor.qemu-snp-experimental.tag")"
$ git clone "${qemu_url}"
$ pushd qemu
$ git checkout "${qemu_commit}"
$ git checkout "${qemu_tag}"
$ ./configure --enable-virtfs --target-list=x86_64-softmmu --enable-debug
$ make -j "$(nproc)"
$ popd

View File

@@ -1,5 +1,5 @@
## Introduction
To improve security, Kata Container supports running the VMM process (currently only QEMU) as a non-`root` user.
To improve security, Kata Container supports running the VMM process (QEMU and cloud-hypervisor) as a non-`root` user.
This document describes how to enable the rootless VMM mode and its limitations.
## Pre-requisites
@@ -27,7 +27,7 @@ Another necessary change is to move the hypervisor runtime files (e.g. `vhost-fs
## Limitations
1. Only the VMM process is running as a non-root user. Other processes such as Kata Container shimv2 and `virtiofsd` still run as the root user.
2. Currently, this feature is only supported in QEMU. Still need to bring it to Firecracker and Cloud Hypervisor (see https://github.com/kata-containers/kata-containers/issues/2567).
2. Currently, this feature is only supported in QEMU and cloud-hypervisor. For firecracker, you can use jailer to run the VMM process with a non-root user.
3. Certain features will not work when rootless VMM is enabled, including:
1. Passing devices to the guest (`virtio-blk`, `virtio-scsi`) will not work if the non-privileged user does not have permission to access it (leading to a permission denied error). A more permissive permission (e.g. 666) may overcome this issue. However, you need to be aware of the potential security implications of reducing the security on such devices.
2. `vfio` device will also not work because of permission denied error.

View File

@@ -19,7 +19,7 @@ Packaged installation methods uses your distribution's native package format (su
|------------------------------------------------------|----------------------------------------------------------------------------------------------|-------------------|-----------------------------------------------------------------------------------------------|
| [Using kata-deploy](#kata-deploy-installation) | The preferred way to deploy the Kata Containers distributed binaries on a Kubernetes cluster | **No!** | Best way to give it a try on kata-containers on an already up and running Kubernetes cluster. |
| [Using official distro packages](#official-packages) | Kata packages provided by Linux distributions official repositories | yes | Recommended for most users. |
| [Using snap](#snap-installation) | Easy to install | yes | Good alternative to official distro packages. |
| ~~[Using snap](#snap-installation)~~ | ~~Easy to install~~ | ~~yes~~ | **Snap is unmaintained!** ~~Good alternative to official distro packages.~~ |
| [Automatic](#automatic-installation) | Run a single command to install a full system | **No!** | For those wanting the latest release quickly. |
| [Manual](#manual-installation) | Follow a guide step-by-step to install a working system | **No!** | For those who want the latest release with more control. |
| [Build from source](#build-from-source-installation) | Build the software components manually | **No!** | Power users and developers only. |
@@ -44,9 +44,24 @@ Kata packages are provided by official distribution repositories for:
### Snap Installation
The snap installation is available for all distributions which support `snapd`.
> **WARNING:**
>
> The Snap package method is **unmaintained** and only provides an old
> version of Kata Containers:
> The [latest Kata Containers snap](https://snapcraft.io/kata-containers)
> provides Kata Containers
> [version 2.4.2](https://github.com/kata-containers/kata-containers/releases/tag/2.4.2)
> but the latest stable Kata Containers release at the time of writing is
> [version 3.1.0](https://github.com/kata-containers/kata-containers/releases/tag/3.1.0).
>
> We recommend strongly that you switch to an alternative Kata Containers installation method.
>
> See: https://github.com/kata-containers/kata-containers/issues/6769
> for further details.
[Use snap](snap-installation-guide.md) to install Kata Containers from https://snapcraft.io.
~~The snap installation is available for all distributions which support `snapd`.~~
~~[Use snap](snap-installation-guide.md) to install Kata Containers from https://snapcraft.io. ~~
### Automatic Installation

View File

@@ -123,7 +123,7 @@ Refer to [this guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-l
SSH into the machine
```bash
$ ssh -i MyKeyPair.pen ubuntu@${IP}
$ ssh -i MyKeyPair.pem ubuntu@${IP}
```
Go onto the next step.

View File

@@ -49,14 +49,14 @@ Follow the [`kata-deploy`](../../tools/packaging/kata-deploy/README.md).
* Download `Rustup` and install `Rust`
> **Notes:**
> Rust version 1.62.0 is needed
> For Rust version, please set `RUST_VERSION` to the value of `languages.rust.meta.newest-version key` in [`versions.yaml`](../../versions.yaml) or, if `yq` is available on your system, run `export RUST_VERSION=$(yq read versions.yaml languages.rust.meta.newest-version)`.
Example for `x86_64`
```
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
$ source $HOME/.cargo/env
$ rustup install 1.62.0
$ rustup default 1.62.0-x86_64-unknown-linux-gnu
$ rustup install ${RUST_VERSION}
$ rustup default ${RUST_VERSION}-x86_64-unknown-linux-gnu
```
* Musl support for fully static binary

View File

@@ -1,5 +1,20 @@
# Kata Containers snap package
> **WARNING:**
>
> The Snap package method is **unmaintained** and only provides an old
> version of Kata Containers:
> The [latest Kata Containers snap](https://snapcraft.io/kata-containers)
> provides Kata Containers
> [version 2.4.2](https://github.com/kata-containers/kata-containers/releases/tag/2.4.2)
> but the latest stable Kata Containers release at the time of writing is
> [version 3.1.0](https://github.com/kata-containers/kata-containers/releases/tag/3.1.0).
>
> We recommend strongly that you switch to an alternative Kata Containers installation method.
>
> See: https://github.com/kata-containers/kata-containers/issues/6769
> for further details.
## Install Kata Containers
Kata Containers can be installed in any Linux distribution that supports
@@ -7,6 +22,21 @@ Kata Containers can be installed in any Linux distribution that supports
Run the following command to install **Kata Containers**:
> **WARNING:**
>
> The Snap package method is **unmaintained** and only provides an old
> version of Kata Containers:
> The [latest Kata Containers snap](https://snapcraft.io/kata-containers)
> provides Kata Containers
> [version 2.4.2](https://github.com/kata-containers/kata-containers/releases/tag/2.4.2)
> but the latest stable Kata Containers release at the time of writing is
> [version 3.1.0](https://github.com/kata-containers/kata-containers/releases/tag/3.1.0).
>
> We recommend strongly that you switch to an alternative Kata Containers installation method.
>
> See: https://github.com/kata-containers/kata-containers/issues/6769
> for further details.
```sh
$ sudo snap install kata-containers --stable --classic
```

View File

@@ -34,54 +34,6 @@ parts:
mkdir -p $(dirname ${kata_dir})
ln -sf $(realpath "${SNAPCRAFT_STAGE}/..") ${kata_dir}
godeps:
after: [metadata]
plugin: nil
prime:
- -*
build-packages:
- curl
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
# put everything in stage
cd "${SNAPCRAFT_STAGE}"
version="$(${yq} r ${kata_dir}/versions.yaml languages.golang.meta.newest-version)"
tarfile="go${version}.${goos}-${goarch}.tar.gz"
curl -LO https://golang.org/dl/${tarfile}
tar -xf ${tarfile} --strip-components=1
rustdeps:
after: [metadata]
plugin: nil
prime:
- -*
build-packages:
- curl
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
# put everything in stage
cd "${SNAPCRAFT_STAGE}"
version="$(${yq} r ${kata_dir}/versions.yaml languages.rust.meta.newest-version)"
if ! command -v rustup > /dev/null; then
curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain ${version}
fi
export PATH=${PATH}:${HOME}/.cargo/bin
rustup toolchain install ${version}
rustup default ${version}
if [ "${arch}" == "ppc64le" ] || [ "${arch}" == "s390x" ] ; then
[ "${arch}" == "ppc64le" ] && arch="powerpc64le"
rustup target add ${arch}-unknown-linux-gnu
else
rustup target add ${arch}-unknown-linux-musl
$([ "$(whoami)" != "root" ] && echo sudo) ln -sf /usr/bin/g++ /bin/musl-g++
fi
rustup component add rustfmt
docker:
after: [metadata]
plugin: nil
@@ -111,240 +63,92 @@ parts:
echo "Adding $USER into docker group"
sudo -E gpasswd -a $USER docker
echo "Starting docker"
# docker may fail to start using "fd://" in docker.service
sudo sed -i 's/fd:\/\//unix:\/\//g' /lib/systemd/system/docker.service
sudo systemctl daemon-reload
sudo -E systemctl start docker || true
image:
after: [godeps, docker, qemu, kernel]
after: [docker]
plugin: nil
build-packages:
- docker.io
- cpio
- git
- iptables
- software-properties-common
- uidmap
- gnupg2
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
[ "${arch}" = "ppc64le" ] || [ "${arch}" = "s390x" ] && sudo apt-get --no-install-recommends install -y protobuf-compiler
cd "${SNAPCRAFT_PROJECT_DIR}"
sudo -E NO_TTY=true make rootfs-image-tarball
if [ -n "$http_proxy" ]; then
echo "Setting proxy $http_proxy"
sudo -E systemctl set-environment http_proxy="$http_proxy" || true
sudo -E systemctl set-environment https_proxy="$https_proxy" || true
fi
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-rootfs-image.tar.xz"
# Copy yq binary. It's used in the container
cp -a "${yq}" "${GOPATH}/bin/"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
cd "${kata_dir}/tools/osbuilder"
# build image
export AGENT_INIT=yes
export USE_DOCKER=1
export DEBUG=1
initrd_distro=$(${yq} r -X ${kata_dir}/versions.yaml assets.initrd.architecture.${arch}.name)
image_distro=$(${yq} r -X ${kata_dir}/versions.yaml assets.image.architecture.${arch}.name)
case "$arch" in
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="${image_distro}" || sudo -E PATH="$PATH" make initrd DISTRO="${initrd_distro}"
;;
sudo -E NO_TTY=true make rootfs-initrd-tarball
aarch64|ppc64le|s390x)
sudo -E PATH="$PATH" make initrd DISTRO="${initrd_distro}"
;;
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-rootfs-initrd.tar.xz"
*) die "unsupported architecture: ${arch}" ;;
esac
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
# Install image
kata_image_dir="${SNAPCRAFT_PART_INSTALL}/usr/share/kata-containers"
mkdir -p "${kata_image_dir}"
cp kata-containers*.img "${kata_image_dir}"
runtime:
after: [godeps, image, cloud-hypervisor]
after: [docker]
plugin: nil
build-attributes: [no-patchelf]
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
cd "${kata_dir}/src/runtime"
cd "${SNAPCRAFT_PROJECT_DIR}"
sudo -E NO_TTY=true make shim-v2-tarball
qemu_cmd="qemu-system-${qemu_arch}"
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-shim-v2.tar.xz"
# build and install runtime
make \
PREFIX="/snap/${SNAPCRAFT_PROJECT_NAME}/current/usr" \
SKIP_GO_VERSION_CHECK=1 \
QEMUCMD="${qemu_cmd}"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
make install \
PREFIX=/usr \
DESTDIR="${SNAPCRAFT_PART_INSTALL}" \
SKIP_GO_VERSION_CHECK=1 \
QEMUCMD="${qemu_cmd}"
if [ ! -f ${SNAPCRAFT_PART_INSTALL}/../../image/install/usr/share/kata-containers/kata-containers.img ]; then
sed -i -e "s|^image =.*|initrd = \"/snap/${SNAPCRAFT_PROJECT_NAME}/current/usr/share/kata-containers/kata-containers-initrd.img\"|" \
${SNAPCRAFT_PART_INSTALL}/usr/share/defaults/${SNAPCRAFT_PROJECT_NAME}/configuration.toml
fi
mkdir -p "${SNAPCRAFT_PART_INSTALL}/usr/bin"
ln -sf "${SNAPCRAFT_PART_INSTALL}/opt/kata/bin/containerd-shim-kata-v2" "${SNAPCRAFT_PART_INSTALL}/usr/bin/containerd-shim-kata-v2"
ln -sf "${SNAPCRAFT_PART_INSTALL}/opt/kata/bin/kata-runtime" "${SNAPCRAFT_PART_INSTALL}/usr/bin/kata-runtime"
ln -sf "${SNAPCRAFT_PART_INSTALL}/opt/kata/bin/kata-collect-data.sh" "${SNAPCRAFT_PART_INSTALL}/usr/bin/kata-collect-data.sh"
kernel:
after: [godeps]
after: [docker]
plugin: nil
build-packages:
- libelf-dev
- curl
- build-essential
- bison
- flex
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
kernel_version="$(${yq} r $versions_file assets.kernel.version)"
#Remove extra 'v'
kernel_version="${kernel_version#v}"
cd "${SNAPCRAFT_PROJECT_DIR}"
sudo -E NO_TTY=true make kernel-tarball
[ "${arch}" = "s390x" ] && sudo apt-get --no-install-recommends install -y libssl-dev
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-kernel.tar.xz"
cd "${kata_dir}/tools/packaging/kernel"
kernel_dir_prefix="kata-linux-"
# Setup and build kernel
./build-kernel.sh -v "${kernel_version}" -d setup
cd ${kernel_dir_prefix}*
make -j $(nproc ${CI:+--ignore 1}) EXTRAVERSION=".container"
kernel_suffix="${kernel_version}.container"
kata_kernel_dir="${SNAPCRAFT_PART_INSTALL}/usr/share/kata-containers"
mkdir -p "${kata_kernel_dir}"
# Install bz kernel
make install INSTALL_PATH="${kata_kernel_dir}" EXTRAVERSION=".container" || true
vmlinuz_name="vmlinuz-${kernel_suffix}"
ln -sf "${vmlinuz_name}" "${kata_kernel_dir}/vmlinuz.container"
# Install raw kernel
vmlinux_path="vmlinux"
[ "${arch}" = "s390x" ] && vmlinux_path="arch/s390/boot/vmlinux"
vmlinux_name="vmlinux-${kernel_suffix}"
cp "${vmlinux_path}" "${kata_kernel_dir}/${vmlinux_name}"
ln -sf "${vmlinux_name}" "${kata_kernel_dir}/vmlinux.container"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
qemu:
plugin: make
after: [godeps]
build-packages:
- gcc
- python3
- zlib1g-dev
- libcap-ng-dev
- libglib2.0-dev
- libpixman-1-dev
- libnuma-dev
- libltdl-dev
- libcap-dev
- libattr1-dev
- libfdt-dev
- curl
- libcapstone-dev
- bc
- libblkid-dev
- libffi-dev
- libmount-dev
- libseccomp-dev
- libselinux1-dev
- ninja-build
after: [docker]
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
branch="$(${yq} r ${versions_file} assets.hypervisor.qemu.version)"
url="$(${yq} r ${versions_file} assets.hypervisor.qemu.url)"
commit=""
patches_dir="${kata_dir}/tools/packaging/qemu/patches/$(echo ${branch} | sed -e 's/.[[:digit:]]*$//' -e 's/^v//').x"
patches_version_dir="${kata_dir}/tools/packaging/qemu/patches/tag_patches/${branch}"
cd "${SNAPCRAFT_PROJECT_DIR}"
sudo -E NO_TTY=true make qemu-tarball
# download source
qemu_dir="${SNAPCRAFT_STAGE}/qemu"
rm -rf "${qemu_dir}"
git clone --depth 1 --branch ${branch} --single-branch ${url} "${qemu_dir}"
cd "${qemu_dir}"
[ -z "${commit}" ] || git checkout "${commit}"
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-qemu.tar.xz"
[ -n "$(ls -A ui/keycodemapdb)" ] || git clone --depth 1 https://github.com/qemu/keycodemapdb ui/keycodemapdb/
[ -n "$(ls -A capstone)" ] || git clone --depth 1 https://github.com/qemu/capstone capstone
# Apply branch patches
[ -d "${patches_version_dir}" ] || mkdir "${patches_version_dir}"
${kata_dir}/tools/packaging/scripts/apply_patches.sh "${patches_dir}"
${kata_dir}/tools/packaging/scripts/apply_patches.sh "${patches_version_dir}"
# Only x86_64 supports libpmem
[ "${arch}" = "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}"
# static build. The --prefix, --libdir, --libexecdir, --datadir arguments are
# based on PREFIX and set by configure-hypervisor.sh
echo "$(PREFIX=/snap/${SNAPCRAFT_PROJECT_NAME}/current/usr ${configure_hypervisor} -s kata-qemu) \
--disable-rbd " \
| xargs ./configure
# Copy QEMU configurations (Kconfigs)
case "${branch}" in
"v5.1.0")
cp -a "${kata_dir}"/tools/packaging/qemu/default-configs/* default-configs
;;
*)
cp -a "${kata_dir}"/tools/packaging/qemu/default-configs/* configs/devices/
;;
esac
# build and install
make -j $(nproc ${CI:+--ignore 1})
make install DESTDIR="${SNAPCRAFT_PART_INSTALL}"
prime:
- -snap/
- -usr/bin/qemu-ga
- -usr/bin/qemu-pr-helper
- -usr/bin/virtfs-proxy-helper
- -usr/include/
- -usr/share/applications/
- -usr/share/icons/
- -usr/var/
- usr/*
- lib/*
organize:
# Hack: move qemu to /
"snap/kata-containers/current/": "./"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
virtiofsd:
plugin: nil
after: [godeps, rustdeps, docker]
after: [docker]
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
echo "INFO: Building rust version of virtiofsd"
cd "${SNAPCRAFT_PROJECT_DIR}"
# Clean-up build dir in case it already exists
sudo -E NO_TTY=true make virtiofsd-tarball
sudo install \
--owner='root' \
--group='root' \
--mode=0755 \
-D \
--target-directory="${SNAPCRAFT_PART_INSTALL}/usr/libexec/" \
build/virtiofsd/builddir/virtiofsd/virtiofsd
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-virtiofsd.tar.xz"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
cloud-hypervisor:
plugin: nil
after: [godeps, docker]
after: [docker]
override-build: |
source "${SNAPCRAFT_PROJECT_DIR}/snap/local/snap-common.sh"
@@ -353,13 +157,8 @@ parts:
sudo -E NO_TTY=true make cloud-hypervisor-tarball
tarfile="${SNAPCRAFT_PROJECT_DIR}/tools/packaging/kata-deploy/local-build/build/kata-static-cloud-hypervisor.tar.xz"
tmpdir=$(mktemp -d)
tar -xvJpf "${tarfile}" -C "${tmpdir}"
install -D "${tmpdir}/opt/kata/bin/cloud-hypervisor" "${SNAPCRAFT_PART_INSTALL}/usr/bin/cloud-hypervisor"
rm -rf "${tmpdir}"
tar -xvJpf "${tarfile}" -C "${SNAPCRAFT_PART_INSTALL}"
fi
apps:

88
src/agent/Cargo.lock generated
View File

@@ -801,6 +801,7 @@ dependencies = [
"async-recursion",
"async-trait",
"capctl",
"cfg-if 1.0.0",
"cgroups-rs",
"clap",
"futures",
@@ -818,7 +819,7 @@ dependencies = [
"opentelemetry",
"procfs",
"prometheus",
"protobuf",
"protobuf 3.2.0",
"protocols",
"regex",
"rtnetlink",
@@ -1430,7 +1431,7 @@ dependencies = [
"memchr",
"parking_lot 0.12.1",
"procfs",
"protobuf",
"protobuf 2.27.1",
"thiserror",
]
@@ -1490,9 +1491,16 @@ name = "protobuf"
version = "2.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf7e6d18738ecd0902d30d1ad232c9125985a3422929b16c65517b38adc14f96"
[[package]]
name = "protobuf"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b55bad9126f378a853655831eb7363b7b01b81d19f8cb1218861086ca4a1a61e"
dependencies = [
"serde",
"serde_derive",
"once_cell",
"protobuf-support",
"thiserror",
]
[[package]]
@@ -1501,17 +1509,47 @@ version = "2.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aec1632b7c8f2e620343439a7dfd1f3c47b18906c4be58982079911482b5d707"
dependencies = [
"protobuf",
"protobuf 2.27.1",
]
[[package]]
name = "protobuf-codegen-pure"
version = "2.27.1"
name = "protobuf-codegen"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f8122fdb18e55190c796b088a16bdb70cd7acdcd48f7a8b796b58c62e532cc6"
checksum = "0dd418ac3c91caa4032d37cb80ff0d44e2ebe637b2fb243b6234bf89cdac4901"
dependencies = [
"protobuf",
"protobuf-codegen",
"anyhow",
"once_cell",
"protobuf 3.2.0",
"protobuf-parse",
"regex",
"tempfile",
"thiserror",
]
[[package]]
name = "protobuf-parse"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d39b14605eaa1f6a340aec7f320b34064feb26c93aec35d6a9a2272a8ddfa49"
dependencies = [
"anyhow",
"indexmap",
"log",
"protobuf 3.2.0",
"protobuf-support",
"tempfile",
"thiserror",
"which",
]
[[package]]
name = "protobuf-support"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d4d7b8601c814cfb36bcebb79f0e61e45e1e93640cf778837833bbed05c372"
dependencies = [
"thiserror",
]
[[package]]
@@ -1520,7 +1558,7 @@ version = "0.1.0"
dependencies = [
"async-trait",
"oci",
"protobuf",
"protobuf 3.2.0",
"ttrpc",
"ttrpc-codegen",
]
@@ -1704,7 +1742,7 @@ dependencies = [
"nix 0.24.2",
"oci",
"path-absolutize",
"protobuf",
"protobuf 3.2.0",
"protocols",
"regex",
"rlimit",
@@ -2226,9 +2264,9 @@ dependencies = [
[[package]]
name = "ttrpc"
version = "0.6.1"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ecfff459a859c6ba6668ff72b34c2f1d94d9d58f7088414c2674ad0f31cc7d8"
checksum = "a35f22a2964bea14afee161665bb260b83cb48e665e0260ca06ec0e775c8b06c"
dependencies = [
"async-trait",
"byteorder",
@@ -2236,8 +2274,8 @@ dependencies = [
"libc",
"log",
"nix 0.23.1",
"protobuf",
"protobuf-codegen-pure",
"protobuf 3.2.0",
"protobuf-codegen 3.2.0",
"thiserror",
"tokio",
"tokio-vsock",
@@ -2245,28 +2283,28 @@ dependencies = [
[[package]]
name = "ttrpc-codegen"
version = "0.2.0"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809eda4e459820237104e4b61d6b41bbe6c9e1ce6adf4057955e6e6722a90408"
checksum = "94d7f7631d7a9ebed715a47cd4cb6072cbc7ae1d4ec01598971bbec0024340c2"
dependencies = [
"protobuf",
"protobuf-codegen",
"protobuf-codegen-pure",
"protobuf 2.27.1",
"protobuf-codegen 3.2.0",
"protobuf-support",
"ttrpc-compiler",
]
[[package]]
name = "ttrpc-compiler"
version = "0.4.1"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2978ed3fa047d8fd55cbeb4d4a61d461fb3021a90c9618519c73ce7e5bb66c15"
checksum = "ec3cb5dbf1f0865a34fe3f722290fe776cacb16f50428610b779467b76ddf647"
dependencies = [
"derive-new",
"prost",
"prost-build",
"prost-types",
"protobuf",
"protobuf-codegen",
"protobuf 2.27.1",
"protobuf-codegen 2.27.1",
"tempfile",
]

View File

@@ -10,8 +10,8 @@ oci = { path = "../libs/oci" }
rustjail = { path = "rustjail" }
protocols = { path = "../libs/protocols", features = ["async"] }
lazy_static = "1.3.0"
ttrpc = { version = "0.6.0", features = ["async"], default-features = false }
protobuf = "2.27.0"
ttrpc = { version = "0.7.1", features = ["async"], default-features = false }
protobuf = "3.2.0"
libc = "0.2.58"
nix = "0.24.2"
capctl = "0.2.0"
@@ -48,6 +48,7 @@ slog-scope = "4.1.2"
slog-stdlog = "4.0.0"
log = "0.4.11"
cfg-if = "1.0.0"
prometheus = { version = "0.13.0", features = ["process"] }
procfs = "0.12.0"
anyhow = "1.0.32"

View File

@@ -33,6 +33,12 @@ ifeq ($(SECCOMP),yes)
override EXTRA_RUSTFEATURES += seccomp
endif
include ../../utils.mk
ifeq ($(ARCH), ppc64le)
override ARCH = powerpc64le
endif
##VAR STANDARD_OCI_RUNTIME=yes|no define if agent enables standard oci runtime feature
STANDARD_OCI_RUNTIME := no
@@ -45,8 +51,6 @@ ifneq ($(EXTRA_RUSTFEATURES),)
override EXTRA_RUSTFEATURES := --features "$(EXTRA_RUSTFEATURES)"
endif
include ../../utils.mk
TARGET_PATH = target/$(TRIPLE)/$(BUILD_TYPE)/$(TARGET)
##VAR DESTDIR=<path> is a directory prepended to each installed target file

View File

@@ -18,7 +18,7 @@ scopeguard = "1.0.0"
capctl = "0.2.0"
lazy_static = "1.3.0"
libc = "0.2.58"
protobuf = "2.27.0"
protobuf = "3.2.0"
slog = "2.5.2"
slog-scope = "4.1.2"
scan_fmt = "0.2.6"

View File

@@ -27,7 +27,7 @@ use oci::{
LinuxNetwork, LinuxPids, LinuxResources,
};
use protobuf::{CachedSize, RepeatedField, SingularPtrField, UnknownFields};
use protobuf::MessageField;
use protocols::agent::{
BlkioStats, BlkioStatsEntry, CgroupStats, CpuStats, CpuUsage, HugetlbStats, MemoryData,
MemoryStats, PidsStats, ThrottlingData,
@@ -50,7 +50,7 @@ macro_rules! get_controller_or_return_singular_none {
($cg:ident) => {
match $cg.controller_of() {
Some(c) => c,
None => return SingularPtrField::none(),
None => return MessageField::none(),
}
};
}
@@ -134,11 +134,10 @@ impl CgroupManager for Manager {
let throttling_data = get_cpu_stats(&self.cgroup);
let cpu_stats = SingularPtrField::some(CpuStats {
let cpu_stats = MessageField::some(CpuStats {
cpu_usage,
throttling_data,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
// Memorystats
@@ -160,8 +159,7 @@ impl CgroupManager for Manager {
pids_stats,
blkio_stats,
hugetlb_stats,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}
@@ -446,14 +444,14 @@ fn set_memory_resources(cg: &cgroups::Cgroup, memory: &LinuxMemory, update: bool
let memstat = get_memory_stats(cg)
.into_option()
.ok_or_else(|| anyhow!("failed to get the cgroup memory stats"))?;
let memusage = memstat.get_usage();
let memusage = memstat.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 {
if swap == -1 || memusage.limit() < swap as u64 {
mem_controller.set_memswap_limit(swap)?;
set_resource!(mem_controller, set_limit, memory, limit);
} else {
@@ -657,21 +655,20 @@ lazy_static! {
};
}
fn get_cpu_stats(cg: &cgroups::Cgroup) -> SingularPtrField<ThrottlingData> {
fn get_cpu_stats(cg: &cgroups::Cgroup) -> MessageField<ThrottlingData> {
let cpu_controller: &CpuController = get_controller_or_return_singular_none!(cg);
let stat = cpu_controller.cpu().stat;
let h = lines_to_map(&stat);
SingularPtrField::some(ThrottlingData {
MessageField::some(ThrottlingData {
periods: *h.get("nr_periods").unwrap_or(&0),
throttled_periods: *h.get("nr_throttled").unwrap_or(&0),
throttled_time: *h.get("throttled_time").unwrap_or(&0),
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}
fn get_cpuacct_stats(cg: &cgroups::Cgroup) -> SingularPtrField<CpuUsage> {
fn get_cpuacct_stats(cg: &cgroups::Cgroup) -> MessageField<CpuUsage> {
if let Some(cpuacct_controller) = cg.controller_of::<CpuAcctController>() {
let cpuacct = cpuacct_controller.cpuacct();
@@ -685,13 +682,12 @@ fn get_cpuacct_stats(cg: &cgroups::Cgroup) -> SingularPtrField<CpuUsage> {
let percpu_usage = line_to_vec(&cpuacct.usage_percpu);
return SingularPtrField::some(CpuUsage {
return MessageField::some(CpuUsage {
total_usage,
percpu_usage,
usage_in_kernelmode,
usage_in_usermode,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
}
@@ -704,17 +700,16 @@ fn get_cpuacct_stats(cg: &cgroups::Cgroup) -> SingularPtrField<CpuUsage> {
let total_usage = *h.get("usage_usec").unwrap_or(&0);
let percpu_usage = vec![];
SingularPtrField::some(CpuUsage {
MessageField::some(CpuUsage {
total_usage,
percpu_usage,
usage_in_kernelmode,
usage_in_usermode,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}
fn get_memory_stats(cg: &cgroups::Cgroup) -> SingularPtrField<MemoryStats> {
fn get_memory_stats(cg: &cgroups::Cgroup) -> MessageField<MemoryStats> {
let memory_controller: &MemController = get_controller_or_return_singular_none!(cg);
// cache from memory stat
@@ -726,52 +721,48 @@ fn get_memory_stats(cg: &cgroups::Cgroup) -> SingularPtrField<MemoryStats> {
let use_hierarchy = value == 1;
// get memory data
let usage = SingularPtrField::some(MemoryData {
let usage = MessageField::some(MemoryData {
usage: memory.usage_in_bytes,
max_usage: memory.max_usage_in_bytes,
failcnt: memory.fail_cnt,
limit: memory.limit_in_bytes as u64,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
// get swap usage
let memswap = memory_controller.memswap();
let swap_usage = SingularPtrField::some(MemoryData {
let swap_usage = MessageField::some(MemoryData {
usage: memswap.usage_in_bytes,
max_usage: memswap.max_usage_in_bytes,
failcnt: memswap.fail_cnt,
limit: memswap.limit_in_bytes as u64,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
// get kernel usage
let kmem_stat = memory_controller.kmem_stat();
let kernel_usage = SingularPtrField::some(MemoryData {
let kernel_usage = MessageField::some(MemoryData {
usage: kmem_stat.usage_in_bytes,
max_usage: kmem_stat.max_usage_in_bytes,
failcnt: kmem_stat.fail_cnt,
limit: kmem_stat.limit_in_bytes as u64,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
SingularPtrField::some(MemoryStats {
MessageField::some(MemoryStats {
cache,
usage,
swap_usage,
kernel_usage,
use_hierarchy,
stats: memory.stat.raw,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}
fn get_pids_stats(cg: &cgroups::Cgroup) -> SingularPtrField<PidsStats> {
fn get_pids_stats(cg: &cgroups::Cgroup) -> MessageField<PidsStats> {
let pid_controller: &PidController = get_controller_or_return_singular_none!(cg);
let current = pid_controller.get_pid_current().unwrap_or(0);
@@ -785,11 +776,10 @@ fn get_pids_stats(cg: &cgroups::Cgroup) -> SingularPtrField<PidsStats> {
},
} as u64;
SingularPtrField::some(PidsStats {
MessageField::some(PidsStats {
current,
limit,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}
@@ -825,8 +815,8 @@ https://github.com/opencontainers/runc/blob/a5847db387ae28c0ca4ebe4beee1a76900c8
Total 0
*/
fn get_blkio_stat_blkiodata(blkiodata: &[BlkIoData]) -> RepeatedField<BlkioStatsEntry> {
let mut m = RepeatedField::new();
fn get_blkio_stat_blkiodata(blkiodata: &[BlkIoData]) -> Vec<BlkioStatsEntry> {
let mut m = Vec::new();
if blkiodata.is_empty() {
return m;
}
@@ -839,16 +829,15 @@ fn get_blkio_stat_blkiodata(blkiodata: &[BlkIoData]) -> RepeatedField<BlkioStats
minor: d.minor as u64,
op: op.clone(),
value: d.data,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
});
}
m
}
fn get_blkio_stat_ioservice(services: &[IoService]) -> RepeatedField<BlkioStatsEntry> {
let mut m = RepeatedField::new();
fn get_blkio_stat_ioservice(services: &[IoService]) -> Vec<BlkioStatsEntry> {
let mut m = Vec::new();
if services.is_empty() {
return m;
@@ -872,17 +861,16 @@ fn build_blkio_stats_entry(major: i16, minor: i16, op: &str, value: u64) -> Blki
minor: minor as u64,
op: op.to_string(),
value,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
}
}
fn get_blkio_stats_v2(cg: &cgroups::Cgroup) -> SingularPtrField<BlkioStats> {
fn get_blkio_stats_v2(cg: &cgroups::Cgroup) -> MessageField<BlkioStats> {
let blkio_controller: &BlkIoController = get_controller_or_return_singular_none!(cg);
let blkio = blkio_controller.blkio();
let mut resp = BlkioStats::new();
let mut blkio_stats = RepeatedField::new();
let mut blkio_stats = Vec::new();
let stat = blkio.io_stat;
for s in stat {
@@ -898,10 +886,10 @@ fn get_blkio_stats_v2(cg: &cgroups::Cgroup) -> SingularPtrField<BlkioStats> {
resp.io_service_bytes_recursive = blkio_stats;
SingularPtrField::some(resp)
MessageField::some(resp)
}
fn get_blkio_stats(cg: &cgroups::Cgroup) -> SingularPtrField<BlkioStats> {
fn get_blkio_stats(cg: &cgroups::Cgroup) -> MessageField<BlkioStats> {
if cg.v2() {
return get_blkio_stats_v2(cg);
}
@@ -934,7 +922,7 @@ fn get_blkio_stats(cg: &cgroups::Cgroup) -> SingularPtrField<BlkioStats> {
m.sectors_recursive = get_blkio_stat_blkiodata(&blkio.sectors_recursive);
}
SingularPtrField::some(m)
MessageField::some(m)
}
fn get_hugetlb_stats(cg: &cgroups::Cgroup) -> HashMap<String, HugetlbStats> {
@@ -958,8 +946,7 @@ fn get_hugetlb_stats(cg: &cgroups::Cgroup) -> HashMap<String, HugetlbStats> {
usage,
max_usage,
failcnt,
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
},
);
}

View File

@@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
use protobuf::{CachedSize, SingularPtrField, UnknownFields};
use protobuf::MessageField;
use crate::cgroups::Manager as CgroupManager;
use crate::protocols::agent::{BlkioStats, CgroupStats, CpuStats, MemoryStats, PidsStats};
@@ -33,13 +33,12 @@ impl CgroupManager for Manager {
fn get_stats(&self) -> Result<CgroupStats> {
Ok(CgroupStats {
cpu_stats: SingularPtrField::some(CpuStats::default()),
memory_stats: SingularPtrField::some(MemoryStats::new()),
pids_stats: SingularPtrField::some(PidsStats::new()),
blkio_stats: SingularPtrField::some(BlkioStats::new()),
cpu_stats: MessageField::some(CpuStats::default()),
memory_stats: MessageField::some(MemoryStats::new()),
pids_stats: MessageField::some(PidsStats::new()),
blkio_stats: MessageField::some(BlkioStats::new()),
hugetlb_stats: HashMap::new(),
unknown_fields: UnknownFields::default(),
cached_size: CachedSize::default(),
..Default::default()
})
}

View File

@@ -48,7 +48,7 @@ use nix::unistd::{self, fork, ForkResult, Gid, Pid, Uid, User};
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use protobuf::SingularPtrField;
use protobuf::MessageField;
use oci::State as OCIState;
use regex::Regex;
@@ -374,13 +374,18 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
let buf = read_sync(crfd)?;
let spec_str = std::str::from_utf8(&buf)?;
let spec: oci::Spec = serde_json::from_str(spec_str)?;
log_child!(cfd_log, "notify parent to send oci process");
write_sync(cwfd, SYNC_SUCCESS, "")?;
let buf = read_sync(crfd)?;
let process_str = std::str::from_utf8(&buf)?;
let oci_process: oci::Process = serde_json::from_str(process_str)?;
log_child!(cfd_log, "notify parent to send oci state");
write_sync(cwfd, SYNC_SUCCESS, "")?;
let buf = read_sync(crfd)?;
let state_str = std::str::from_utf8(&buf)?;
let mut state: oci::State = serde_json::from_str(state_str)?;
log_child!(cfd_log, "notify parent to send cgroup manager");
write_sync(cwfd, SYNC_SUCCESS, "")?;
@@ -743,6 +748,19 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
unistd::read(fd, buf)?;
}
if init {
// StartContainer Hooks:
// * should be run in container namespace
// * should be run after container is created and before container is started (before user-specific command is executed)
// * spec details: https://github.com/opencontainers/runtime-spec/blob/c1662686cff159595277b79322d0272f5182941b/config.md#startcontainer-hooks
state.pid = std::process::id() as i32;
state.status = oci::ContainerState::Created;
if let Some(hooks) = spec.hooks.as_ref() {
let mut start_container_states = HookStates::new();
start_container_states.execute_hooks(&hooks.start_container, Some(state))?;
}
}
// With NoNewPrivileges, we should set seccomp as close to
// do_exec as possible in order to reduce the amount of
// system calls in the seccomp profiles.
@@ -857,7 +875,7 @@ impl BaseContainer for LinuxContainer {
// what about network interface stats?
Ok(StatsContainerResponse {
cgroup_stats: SingularPtrField::some(self.cgroup_manager.as_ref().get_stats()?),
cgroup_stats: MessageField::some(self.cgroup_manager.as_ref().get_stats()?),
..Default::default()
})
}
@@ -1323,7 +1341,6 @@ async fn join_namespaces(
write_async(pipe_w, SYNC_DATA, spec_str.as_str()).await?;
info!(logger, "wait child received oci spec");
read_async(pipe_r).await?;
info!(logger, "send oci process from parent to child");
@@ -1333,6 +1350,13 @@ async fn join_namespaces(
info!(logger, "wait child received oci process");
read_async(pipe_r).await?;
info!(logger, "try to send state from parent to child");
let state_str = serde_json::to_string(st)?;
write_async(pipe_w, SYNC_DATA, state_str.as_str()).await?;
info!(logger, "wait child received oci state");
read_async(pipe_r).await?;
let cm_str = if use_systemd_cgroup {
serde_json::to_string(cm.as_any()?.downcast_ref::<SystemdManager>().unwrap())
} else {

View File

@@ -82,11 +82,11 @@ pub fn process_grpc_to_oci(p: &grpc::Process) -> oci::Process {
let cap = p.Capabilities.as_ref().unwrap();
Some(oci::LinuxCapabilities {
bounding: cap.Bounding.clone().into_vec(),
effective: cap.Effective.clone().into_vec(),
inheritable: cap.Inheritable.clone().into_vec(),
permitted: cap.Permitted.clone().into_vec(),
ambient: cap.Ambient.clone().into_vec(),
bounding: cap.Bounding.clone(),
effective: cap.Effective.clone(),
inheritable: cap.Inheritable.clone(),
permitted: cap.Permitted.clone(),
ambient: cap.Ambient.clone(),
})
} else {
None
@@ -108,8 +108,8 @@ pub fn process_grpc_to_oci(p: &grpc::Process) -> oci::Process {
terminal: p.Terminal,
console_size,
user,
args: p.Args.clone().into_vec(),
env: p.Env.clone().into_vec(),
args: p.Args.clone(),
env: p.Env.clone(),
cwd: p.Cwd.clone(),
capabilities,
rlimits,
@@ -130,9 +130,9 @@ fn root_grpc_to_oci(root: &grpc::Root) -> oci::Root {
fn mount_grpc_to_oci(m: &grpc::Mount) -> oci::Mount {
oci::Mount {
destination: m.destination.clone(),
r#type: m.field_type.clone(),
r#type: m.type_.clone(),
source: m.source.clone(),
options: m.options.clone().into_vec(),
options: m.options.clone(),
}
}
@@ -143,8 +143,8 @@ fn hook_grpc_to_oci(h: &[grpcHook]) -> Vec<oci::Hook> {
for e in h.iter() {
r.push(oci::Hook {
path: e.Path.clone(),
args: e.Args.clone().into_vec(),
env: e.Env.clone().into_vec(),
args: e.Args.clone(),
env: e.Env.clone(),
timeout: Some(e.Timeout as i32),
});
}
@@ -153,13 +153,17 @@ fn hook_grpc_to_oci(h: &[grpcHook]) -> Vec<oci::Hook> {
fn hooks_grpc_to_oci(h: &grpc::Hooks) -> oci::Hooks {
let prestart = hook_grpc_to_oci(h.Prestart.as_ref());
let create_runtime = hook_grpc_to_oci(h.CreateRuntime.as_ref());
let create_container = hook_grpc_to_oci(h.CreateContainer.as_ref());
let start_container = hook_grpc_to_oci(h.StartContainer.as_ref());
let poststart = hook_grpc_to_oci(h.Poststart.as_ref());
let poststop = hook_grpc_to_oci(h.Poststop.as_ref());
oci::Hooks {
prestart,
create_runtime,
create_container,
start_container,
poststart,
poststop,
}
@@ -355,7 +359,7 @@ fn seccomp_grpc_to_oci(sec: &grpc::LinuxSeccomp) -> oci::LinuxSeccomp {
let mut args = Vec::new();
let errno_ret: u32 = if sys.has_errnoret() {
sys.get_errnoret()
sys.errnoret()
} else {
libc::EPERM as u32
};
@@ -370,7 +374,7 @@ fn seccomp_grpc_to_oci(sec: &grpc::LinuxSeccomp) -> oci::LinuxSeccomp {
}
r.push(oci::LinuxSyscall {
names: sys.Names.clone().into_vec(),
names: sys.Names.clone(),
action: sys.Action.clone(),
errno_ret,
args,
@@ -381,8 +385,8 @@ fn seccomp_grpc_to_oci(sec: &grpc::LinuxSeccomp) -> oci::LinuxSeccomp {
oci::LinuxSeccomp {
default_action: sec.DefaultAction.clone(),
architectures: sec.Architectures.clone().into_vec(),
flags: sec.Flags.clone().into_vec(),
architectures: sec.Architectures.clone(),
flags: sec.Flags.clone(),
syscalls,
}
}
@@ -452,8 +456,8 @@ fn linux_grpc_to_oci(l: &grpc::Linux) -> oci::Linux {
devices,
seccomp,
rootfs_propagation: l.RootfsPropagation.clone(),
masked_paths: l.MaskedPaths.clone().into_vec(),
readonly_paths: l.ReadonlyPaths.clone().into_vec(),
masked_paths: l.MaskedPaths.clone(),
readonly_paths: l.ReadonlyPaths.clone(),
mount_label: l.MountLabel.clone(),
intel_rdt,
}
@@ -554,35 +558,30 @@ mod tests {
// All fields specified
grpcproc: grpc::Process {
Terminal: true,
ConsoleSize: protobuf::SingularPtrField::<grpc::Box>::some(grpc::Box {
ConsoleSize: protobuf::MessageField::<grpc::Box>::some(grpc::Box {
Height: 123,
Width: 456,
..Default::default()
}),
User: protobuf::SingularPtrField::<grpc::User>::some(grpc::User {
User: protobuf::MessageField::<grpc::User>::some(grpc::User {
UID: 1234,
GID: 5678,
AdditionalGids: Vec::from([910, 1112]),
Username: String::from("username"),
..Default::default()
}),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([String::from("env")])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env")]),
Cwd: String::from("cwd"),
Capabilities: protobuf::SingularPtrField::some(grpc::LinuxCapabilities {
Bounding: protobuf::RepeatedField::from(Vec::from([String::from("bnd")])),
Effective: protobuf::RepeatedField::from(Vec::from([String::from("eff")])),
Inheritable: protobuf::RepeatedField::from(Vec::from([String::from(
"inher",
)])),
Permitted: protobuf::RepeatedField::from(Vec::from([String::from("perm")])),
Ambient: protobuf::RepeatedField::from(Vec::from([String::from("amb")])),
Capabilities: protobuf::MessageField::some(grpc::LinuxCapabilities {
Bounding: Vec::from([String::from("bnd")]),
Effective: Vec::from([String::from("eff")]),
Inheritable: Vec::from([String::from("inher")]),
Permitted: Vec::from([String::from("perm")]),
Ambient: Vec::from([String::from("amb")]),
..Default::default()
}),
Rlimits: protobuf::RepeatedField::from(Vec::from([
Rlimits: Vec::from([
grpc::POSIXRlimit {
Type: String::from("r#type"),
Hard: 123,
@@ -595,7 +594,7 @@ mod tests {
Soft: 1011,
..Default::default()
},
])),
]),
NoNewPrivileges: true,
ApparmorProfile: String::from("apparmor profile"),
OOMScoreAdj: 123456,
@@ -645,7 +644,7 @@ mod tests {
TestData {
// None ConsoleSize
grpcproc: grpc::Process {
ConsoleSize: protobuf::SingularPtrField::<grpc::Box>::none(),
ConsoleSize: protobuf::MessageField::<grpc::Box>::none(),
OOMScoreAdj: 0,
..Default::default()
},
@@ -658,7 +657,7 @@ mod tests {
TestData {
// None User
grpcproc: grpc::Process {
User: protobuf::SingularPtrField::<grpc::User>::none(),
User: protobuf::MessageField::<grpc::User>::none(),
OOMScoreAdj: 0,
..Default::default()
},
@@ -676,7 +675,7 @@ mod tests {
TestData {
// None Capabilities
grpcproc: grpc::Process {
Capabilities: protobuf::SingularPtrField::none(),
Capabilities: protobuf::MessageField::none(),
OOMScoreAdj: 0,
..Default::default()
},
@@ -777,60 +776,57 @@ mod tests {
TestData {
// All specified
grpchooks: grpc::Hooks {
Prestart: protobuf::RepeatedField::from(Vec::from([
Prestart: Vec::from([
grpc::Hook {
Path: String::from("prestartpath"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
},
grpc::Hook {
Path: String::from("prestartpath2"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg3"),
String::from("arg4"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env3"),
String::from("env4"),
])),
Args: Vec::from([String::from("arg3"), String::from("arg4")]),
Env: Vec::from([String::from("env3"), String::from("env4")]),
Timeout: 25,
..Default::default()
},
])),
Poststart: protobuf::RepeatedField::from(Vec::from([grpc::Hook {
]),
Poststart: Vec::from([grpc::Hook {
Path: String::from("poststartpath"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}])),
Poststop: protobuf::RepeatedField::from(Vec::from([grpc::Hook {
}]),
Poststop: Vec::from([grpc::Hook {
Path: String::from("poststoppath"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}])),
}]),
CreateRuntime: Vec::from([grpc::Hook {
Path: String::from("createruntimepath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
CreateContainer: Vec::from([grpc::Hook {
Path: String::from("createcontainerpath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
StartContainer: Vec::from([grpc::Hook {
Path: String::from("startcontainerpath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
..Default::default()
},
result: oci::Hooks {
@@ -860,38 +856,65 @@ mod tests {
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
create_runtime: Vec::from([oci::Hook {
path: String::from("createruntimepath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
create_container: Vec::from([oci::Hook {
path: String::from("createcontainerpath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
start_container: Vec::from([oci::Hook {
path: String::from("startcontainerpath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
},
},
TestData {
// Prestart empty
grpchooks: grpc::Hooks {
Prestart: protobuf::RepeatedField::from(Vec::from([])),
Poststart: protobuf::RepeatedField::from(Vec::from([grpc::Hook {
Prestart: Vec::from([]),
Poststart: Vec::from([grpc::Hook {
Path: String::from("poststartpath"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}])),
Poststop: protobuf::RepeatedField::from(Vec::from([grpc::Hook {
}]),
Poststop: Vec::from([grpc::Hook {
Path: String::from("poststoppath"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}])),
}]),
CreateRuntime: Vec::from([grpc::Hook {
Path: String::from("createruntimepath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
CreateContainer: Vec::from([grpc::Hook {
Path: String::from("createcontainerpath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
StartContainer: Vec::from([grpc::Hook {
Path: String::from("startcontainerpath"),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
}]),
..Default::default()
},
result: oci::Hooks {
@@ -908,6 +931,24 @@ mod tests {
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
create_runtime: Vec::from([oci::Hook {
path: String::from("createruntimepath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
create_container: Vec::from([oci::Hook {
path: String::from("createcontainerpath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
start_container: Vec::from([oci::Hook {
path: String::from("startcontainerpath"),
args: Vec::from([String::from("arg1"), String::from("arg2")]),
env: Vec::from([String::from("env1"), String::from("env2")]),
timeout: Some(10),
}]),
},
},
];
@@ -945,11 +986,8 @@ mod tests {
grpcmount: grpc::Mount {
destination: String::from("destination"),
source: String::from("source"),
field_type: String::from("fieldtype"),
options: protobuf::RepeatedField::from(Vec::from([
String::from("option1"),
String::from("option2"),
])),
type_: String::from("fieldtype"),
options: Vec::from([String::from("option1"), String::from("option2")]),
..Default::default()
},
result: oci::Mount {
@@ -963,8 +1001,8 @@ mod tests {
grpcmount: grpc::Mount {
destination: String::from("destination"),
source: String::from("source"),
field_type: String::from("fieldtype"),
options: protobuf::RepeatedField::from(Vec::new()),
type_: String::from("fieldtype"),
options: Vec::new(),
..Default::default()
},
result: oci::Mount {
@@ -978,8 +1016,8 @@ mod tests {
grpcmount: grpc::Mount {
destination: String::new(),
source: String::from("source"),
field_type: String::from("fieldtype"),
options: protobuf::RepeatedField::from(Vec::from([String::from("option1")])),
type_: String::from("fieldtype"),
options: Vec::from([String::from("option1")]),
..Default::default()
},
result: oci::Mount {
@@ -993,8 +1031,8 @@ mod tests {
grpcmount: grpc::Mount {
destination: String::from("destination"),
source: String::from("source"),
field_type: String::new(),
options: protobuf::RepeatedField::from(Vec::from([String::from("option1")])),
type_: String::new(),
options: Vec::from([String::from("option1")]),
..Default::default()
},
result: oci::Mount {
@@ -1054,27 +1092,15 @@ mod tests {
grpchook: &[
grpc::Hook {
Path: String::from("path"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg1"),
String::from("arg2"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env1"),
String::from("env2"),
])),
Args: Vec::from([String::from("arg1"), String::from("arg2")]),
Env: Vec::from([String::from("env1"), String::from("env2")]),
Timeout: 10,
..Default::default()
},
grpc::Hook {
Path: String::from("path2"),
Args: protobuf::RepeatedField::from(Vec::from([
String::from("arg3"),
String::from("arg4"),
])),
Env: protobuf::RepeatedField::from(Vec::from([
String::from("env3"),
String::from("env4"),
])),
Args: Vec::from([String::from("arg3"), String::from("arg4")]),
Env: Vec::from([String::from("env3"), String::from("env4")]),
Timeout: 20,
..Default::default()
},

View File

@@ -35,7 +35,7 @@ use crate::log_child;
// struct is populated from the content in the /proc/<pid>/mountinfo file.
#[derive(std::fmt::Debug, PartialEq)]
pub struct Info {
mount_point: String,
pub mount_point: String,
optional: String,
fstype: String,
}
@@ -553,7 +553,7 @@ fn rootfs_parent_mount_private(path: &str) -> Result<()> {
// Parse /proc/self/mountinfo because comparing Dev and ino does not work from
// bind mounts
fn parse_mount_table(mountinfo_path: &str) -> Result<Vec<Info>> {
pub fn parse_mount_table(mountinfo_path: &str) -> Result<Vec<Info>> {
let file = File::open(mountinfo_path)?;
let reader = BufReader::new(file);
let mut infos = Vec::new();

79
src/agent/src/ap.rs Normal file
View File

@@ -0,0 +1,79 @@
// Copyright (c) IBM Corp. 2023
//
// SPDX-License-Identifier: Apache-2.0
//
use std::fmt;
use std::str::FromStr;
use anyhow::{anyhow, Context};
// IBM Adjunct Processor (AP) is used for cryptographic operations
// by IBM Crypto Express hardware security modules on IBM zSystem & LinuxONE (s390x).
// In Linux, virtual cryptographic devices are called AP queues.
// The name of an AP queue respects a format <xx>.<xxxx> in hexadecimal notation [1, p.467]:
// - <xx> is an adapter ID
// - <xxxx> is an adapter domain ID
// [1] https://www.ibm.com/docs/en/linuxonibm/pdf/lku5dd05.pdf
#[derive(Debug)]
pub struct Address {
pub adapter_id: u8,
pub adapter_domain: u16,
}
impl Address {
pub fn new(adapter_id: u8, adapter_domain: u16) -> Address {
Address {
adapter_id,
adapter_domain,
}
}
}
impl FromStr for Address {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
let split: Vec<&str> = s.split('.').collect();
if split.len() != 2 {
return Err(anyhow!(
"Wrong AP bus format. It needs to be in the form <xx>.<xxxx> (e.g. 0a.003f), got {:?}",
s
));
}
let adapter_id = u8::from_str_radix(split[0], 16).context(format!(
"Wrong AP bus format. AP ID needs to be in the form <xx> (e.g. 0a), got {:?}",
split[0]
))?;
let adapter_domain = u16::from_str_radix(split[1], 16).context(format!(
"Wrong AP bus format. AP domain needs to be in the form <xxxx> (e.g. 003f), got {:?}",
split[1]
))?;
Ok(Address::new(adapter_id, adapter_domain))
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{:02x}.{:04x}", self.adapter_id, self.adapter_domain)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str() {
let device = Address::from_str("a.1").unwrap();
assert_eq!(format!("{}", device), "0a.0001");
assert!(Address::from_str("").is_err());
assert!(Address::from_str(".").is_err());
assert!(Address::from_str("0.0.0").is_err());
assert!(Address::from_str("0g.0000").is_err());
assert!(Address::from_str("0a.10000").is_err());
}
}

View File

@@ -200,7 +200,7 @@ impl AgentConfig {
let config_position = args.iter().position(|a| a == "--config" || a == "-c");
if let Some(config_position) = config_position {
if let Some(config_file) = args.get(config_position + 1) {
return AgentConfig::from_config_file(config_file);
return AgentConfig::from_config_file(config_file).context("AgentConfig from args");
} else {
panic!("The config argument wasn't formed properly: {:?}", args);
}
@@ -216,7 +216,8 @@ impl AgentConfig {
// or if it can't be parsed properly.
if param.starts_with(format!("{}=", CONFIG_FILE).as_str()) {
let config_file = get_string_value(param)?;
return AgentConfig::from_config_file(&config_file);
return AgentConfig::from_config_file(&config_file)
.context("AgentConfig from kernel cmdline");
}
// parse cmdline flags
@@ -304,7 +305,8 @@ impl AgentConfig {
#[instrument]
pub fn from_config_file(file: &str) -> Result<AgentConfig> {
let config = fs::read_to_string(file)?;
let config = fs::read_to_string(file)
.with_context(|| format!("Failed to read config file {}", file))?;
AgentConfig::from_str(&config)
}

View File

@@ -16,13 +16,12 @@ 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::pci;
use crate::sandbox::Sandbox;
use crate::uevent::{wait_for_uevent, Uevent, UeventMatcher};
use anyhow::{anyhow, Context, Result};
use cfg_if::cfg_if;
use oci::{LinuxDeviceCgroup, LinuxResources, Spec};
use protocols::agent::Device;
use tracing::instrument;
@@ -46,14 +45,22 @@ 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";
// VFIO device to be bound to a guest kernel driver
pub const DRIVER_VFIO_GK_TYPE: &str = "vfio-gk";
// VFIO device to be bound to vfio-pci and made available inside the
// VFIO PCI device to be bound to a guest kernel driver
pub const DRIVER_VFIO_PCI_GK_TYPE: &str = "vfio-pci-gk";
// VFIO PCI device to be bound to vfio-pci and made available inside the
// container as a VFIO device node
pub const DRIVER_VFIO_TYPE: &str = "vfio";
pub const DRIVER_VFIO_PCI_TYPE: &str = "vfio-pci";
pub const DRIVER_VFIO_AP_TYPE: &str = "vfio-ap";
pub const DRIVER_OVERLAYFS_TYPE: &str = "overlayfs";
pub const FS_TYPE_HUGETLB: &str = "hugetlbfs";
cfg_if! {
if #[cfg(target_arch = "s390x")] {
use crate::ap;
use crate::ccw;
}
}
#[instrument]
pub fn online_device(path: &str) -> Result<()> {
fs::write(path, "1")?;
@@ -280,7 +287,7 @@ 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 matcher = VirtioBlkCCWMatcher::new(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() {
@@ -401,6 +408,39 @@ async fn get_vfio_device_name(sandbox: &Arc<Mutex<Sandbox>>, grp: IommuGroup) ->
Ok(format!("{}/{}", SYSTEM_DEV_PATH, &uev.devname))
}
#[cfg(target_arch = "s390x")]
#[derive(Debug)]
struct ApMatcher {
syspath: String,
}
#[cfg(target_arch = "s390x")]
impl ApMatcher {
fn new(address: ap::Address) -> ApMatcher {
ApMatcher {
syspath: format!(
"{}/card{:02x}/{}",
AP_ROOT_BUS_PATH, address.adapter_id, address
),
}
}
}
#[cfg(target_arch = "s390x")]
impl UeventMatcher for ApMatcher {
fn is_match(&self, uev: &Uevent) -> bool {
uev.action == "add" && uev.devpath == self.syspath
}
}
#[cfg(target_arch = "s390x")]
#[instrument]
async fn wait_for_ap_device(sandbox: &Arc<Mutex<Sandbox>>, address: ap::Address) -> Result<()> {
let matcher = ApMatcher::new(address);
wait_for_uevent(sandbox, matcher).await?;
Ok(())
}
/// Scan SCSI bus for the given SCSI address(SCSI-Id and LUN)
#[instrument]
fn scan_scsi_bus(scsi_addr: &str) -> Result<()> {
@@ -699,7 +739,7 @@ async fn virtio_nvdimm_device_handler(
Ok(DevNumUpdate::from_vm_path(&device.vm_path)?.into())
}
fn split_vfio_option(opt: &str) -> Option<(&str, &str)> {
fn split_vfio_pci_option(opt: &str) -> Option<(&str, &str)> {
let mut tokens = opt.split('=');
let hostbdf = tokens.next()?;
let path = tokens.next()?;
@@ -714,14 +754,18 @@ fn split_vfio_option(opt: &str) -> Option<(&str, &str)> {
// Each option should have the form "DDDD:BB:DD.F=<pcipath>"
// DDDD:BB:DD.F is the device's PCI address in the host
// <pcipath> is a PCI path to the device in the guest (see pci.rs)
async fn vfio_device_handler(device: &Device, sandbox: &Arc<Mutex<Sandbox>>) -> Result<SpecUpdate> {
let vfio_in_guest = device.field_type != DRIVER_VFIO_GK_TYPE;
#[instrument]
async fn vfio_pci_device_handler(
device: &Device,
sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<SpecUpdate> {
let vfio_in_guest = device.type_ != DRIVER_VFIO_PCI_GK_TYPE;
let mut pci_fixups = Vec::<(pci::Address, pci::Address)>::new();
let mut group = None;
for opt in device.options.iter() {
let (host, pcipath) =
split_vfio_option(opt).ok_or_else(|| anyhow!("Malformed VFIO option {:?}", opt))?;
let (host, pcipath) = split_vfio_pci_option(opt)
.ok_or_else(|| anyhow!("Malformed VFIO PCI option {:?}", opt))?;
let host =
pci::Address::from_str(host).context("Bad host PCI address in VFIO option {:?}")?;
let pcipath = pci::Path::from_str(pcipath)?;
@@ -763,6 +807,28 @@ async fn vfio_device_handler(device: &Device, sandbox: &Arc<Mutex<Sandbox>>) ->
})
}
// The VFIO AP (Adjunct Processor) device handler takes all the APQNs provided as device options
// and awaits them. It sets the minimum AP rescan time of 5 seconds and temporarily adds that
// amount to the hotplug timeout.
#[cfg(target_arch = "s390x")]
#[instrument]
async fn vfio_ap_device_handler(
device: &Device,
sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<SpecUpdate> {
// Force AP bus rescan
fs::write(AP_SCANS_PATH, "1")?;
for apqn in device.options.iter() {
wait_for_ap_device(sandbox, ap::Address::from_str(apqn)?).await?;
}
Ok(Default::default())
}
#[cfg(not(target_arch = "s390x"))]
async fn vfio_ap_device_handler(_: &Device, _: &Arc<Mutex<Sandbox>>) -> Result<SpecUpdate> {
Err(anyhow!("AP is only supported on s390x"))
}
#[instrument]
pub async fn add_devices(
devices: &[Device],
@@ -808,9 +874,9 @@ pub async fn add_devices(
async fn add_device(device: &Device, sandbox: &Arc<Mutex<Sandbox>>) -> Result<SpecUpdate> {
// log before validation to help with debugging gRPC protocol version differences.
info!(sl!(), "device-id: {}, device-type: {}, device-vm-path: {}, device-container-path: {}, device-options: {:?}",
device.id, device.field_type, device.vm_path, device.container_path, device.options);
device.id, device.type_, device.vm_path, device.container_path, device.options);
if device.field_type.is_empty() {
if device.type_.is_empty() {
return Err(anyhow!("invalid type for device {:?}", device));
}
@@ -822,14 +888,17 @@ async fn add_device(device: &Device, sandbox: &Arc<Mutex<Sandbox>>) -> Result<Sp
return Err(anyhow!("invalid container path for device {:?}", device));
}
match device.field_type.as_str() {
match device.type_.as_str() {
DRIVER_BLK_TYPE => virtio_blk_device_handler(device, sandbox).await,
DRIVER_BLK_CCW_TYPE => virtio_blk_ccw_device_handler(device, sandbox).await,
DRIVER_MMIO_BLK_TYPE => virtiommio_blk_device_handler(device, sandbox).await,
DRIVER_NVDIMM_TYPE => virtio_nvdimm_device_handler(device, sandbox).await,
DRIVER_SCSI_TYPE => virtio_scsi_device_handler(device, sandbox).await,
DRIVER_VFIO_GK_TYPE | DRIVER_VFIO_TYPE => vfio_device_handler(device, sandbox).await,
_ => Err(anyhow!("Unknown device type {}", device.field_type)),
DRIVER_VFIO_PCI_GK_TYPE | DRIVER_VFIO_PCI_TYPE => {
vfio_pci_device_handler(device, sandbox).await
}
DRIVER_VFIO_AP_TYPE => vfio_ap_device_handler(device, sandbox).await,
_ => Err(anyhow!("Unknown device type {}", device.type_)),
}
}
@@ -1378,7 +1447,7 @@ mod tests {
#[cfg(target_arch = "s390x")]
#[tokio::test]
async fn test_virtio_blk_ccw_matcher() {
let root_bus = create_ccw_root_bus_path();
let root_bus = CCW_ROOT_BUS_PATH;
let subsystem = "block";
let devname = "vda";
let relpath = "0.0.0002";
@@ -1487,13 +1556,13 @@ mod tests {
}
#[test]
fn test_split_vfio_option() {
fn test_split_vfio_pci_option() {
assert_eq!(
split_vfio_option("0000:01:00.0=02/01"),
split_vfio_pci_option("0000:01:00.0=02/01"),
Some(("0000:01:00.0", "02/01"))
);
assert_eq!(split_vfio_option("0000:01:00.0=02/01=rubbish"), None);
assert_eq!(split_vfio_option("0000:01:00.0"), None);
assert_eq!(split_vfio_pci_option("0000:01:00.0=02/01=rubbish"), None);
assert_eq!(split_vfio_pci_option("0000:01:00.0"), None);
}
#[test]
@@ -1572,4 +1641,35 @@ mod tests {
// Test dev2
assert!(pci_iommu_group(&syspci, dev2).is_err());
}
#[cfg(target_arch = "s390x")]
#[tokio::test]
async fn test_vfio_ap_matcher() {
let subsystem = "ap";
let card = "0a";
let relpath = format!("{}.0001", card);
let mut uev = Uevent::default();
uev.action = U_EVENT_ACTION_ADD.to_string();
uev.subsystem = subsystem.to_string();
uev.devpath = format!("{}/card{}/{}", AP_ROOT_BUS_PATH, card, relpath);
let ap_address = ap::Address::from_str(&relpath).unwrap();
let matcher = ApMatcher::new(ap_address);
assert!(matcher.is_match(&uev));
let mut uev_remove = uev.clone();
uev_remove.action = U_EVENT_ACTION_REMOVE.to_string();
assert!(!matcher.is_match(&uev_remove));
let mut uev_other_device = uev.clone();
uev_other_device.devpath = format!(
"{}/card{}/{}",
AP_ROOT_BUS_PATH,
card,
format!("{}.0002", card)
);
assert!(!matcher.is_match(&uev_other_device));
}
}

View File

@@ -3,6 +3,8 @@
// SPDX-License-Identifier: Apache-2.0
//
use cfg_if::cfg_if;
/// Linux ABI related constants.
#[cfg(target_arch = "aarch64")]
@@ -64,10 +66,14 @@ 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")
cfg_if! {
if #[cfg(target_arch = "s390x")] {
pub const CCW_ROOT_BUS_PATH: &str = "/devices/css0";
pub const AP_ROOT_BUS_PATH: &str = "/devices/ap";
pub const AP_SCANS_PATH: &str = "/sys/bus/ap/scans";
}
}
// 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

@@ -20,6 +20,7 @@ extern crate scopeguard;
extern crate slog;
use anyhow::{anyhow, Context, Result};
use cfg_if::cfg_if;
use clap::{AppSettings, Parser};
use nix::fcntl::OFlag;
use nix::sys::socket::{self, AddressFamily, SockFlag, SockType, VsockAddr};
@@ -34,8 +35,6 @@ use std::process::exit;
use std::sync::Arc;
use tracing::{instrument, span};
#[cfg(target_arch = "s390x")]
mod ccw;
mod config;
mod console;
mod device;
@@ -74,6 +73,13 @@ use tokio::{
mod rpc;
mod tracer;
cfg_if! {
if #[cfg(target_arch = "s390x")] {
mod ap;
mod ccw;
}
}
const NAME: &str = "kata-agent";
lazy_static! {

View File

@@ -211,10 +211,10 @@ async fn ephemeral_storage_handler(
// By now we only support one option field: "fsGroup" which
// isn't an valid mount option, thus we should remove it when
// do mount.
if storage.options.len() > 0 {
if !storage.options.is_empty() {
// ephemeral_storage didn't support mount options except fsGroup.
let mut new_storage = storage.clone();
new_storage.options = protobuf::RepeatedField::default();
new_storage.options = Default::default();
common_storage_handler(logger, &new_storage)?;
let opts_vec: Vec<String> = storage.options.to_vec();
@@ -240,6 +240,70 @@ async fn ephemeral_storage_handler(
Ok("".to_string())
}
// update_ephemeral_mounts takes a list of ephemeral mounts and remounts them
// with mount options passed by the caller
#[instrument]
pub async fn update_ephemeral_mounts(
logger: Logger,
storages: Vec<Storage>,
sandbox: Arc<Mutex<Sandbox>>,
) -> Result<()> {
for (_, storage) in storages.iter().enumerate() {
let handler_name = storage.driver.clone();
let logger = logger.new(o!(
"msg" => "updating tmpfs storage",
"subsystem" => "storage",
"storage-type" => handler_name.to_owned()));
match handler_name.as_str() {
DRIVER_EPHEMERAL_TYPE => {
fs::create_dir_all(Path::new(&storage.mount_point))?;
if storage.options.is_empty() {
continue;
} else {
// assume that fsGid has already been set
let mut opts = Vec::<&str>::new();
for (_, opt) in storage.options.iter().enumerate() {
if opt.starts_with(FS_GID) {
continue;
}
opts.push(opt)
}
let mount_path = Path::new(&storage.mount_point);
let src_path = Path::new(&storage.source);
let (flags, options) = parse_mount_flags_and_options(opts);
info!(logger, "mounting storage";
"mount-source" => src_path.display(),
"mount-destination" => mount_path.display(),
"mount-fstype" => storage.fstype.as_str(),
"mount-options" => options.as_str(),
);
return baremount(
src_path,
mount_path,
storage.fstype.as_str(),
flags,
options.as_str(),
&logger,
);
}
}
_ => {
return Err(anyhow!(
"Unsupported storage type for syncing mounts {}. Only ephemeral storage update is supported",
storage.driver.to_owned()
));
}
};
}
Ok(())
}
#[instrument]
async fn overlayfs_storage_handler(
logger: &Logger,
@@ -590,7 +654,7 @@ pub fn set_ownership(logger: &Logger, storage: &Storage) -> Result<()> {
if storage.fs_group.is_none() {
return Ok(());
}
let fs_group = storage.get_fs_group();
let fs_group = storage.fs_group();
let mut read_only = false;
let opts_vec: Vec<String> = storage.options.to_vec();
@@ -607,7 +671,7 @@ pub fn set_ownership(logger: &Logger, storage: &Storage) -> Result<()> {
err
})?;
if fs_group.group_change_policy == FSGroupChangePolicy::OnRootMismatch
if fs_group.group_change_policy == FSGroupChangePolicy::OnRootMismatch.into()
&& metadata.gid() == fs_group.group_id
{
let mut mask = if read_only { RO_MASK } else { RW_MASK };
@@ -1030,7 +1094,6 @@ fn parse_options(option_list: Vec<String>) -> HashMap<String, String> {
#[cfg(test)]
mod tests {
use super::*;
use protobuf::RepeatedField;
use protocols::agent::FSGroup;
use std::fs::File;
use std::fs::OpenOptions;
@@ -1951,9 +2014,8 @@ mod tests {
mount_path: "rw_mount",
fs_group: Some(FSGroup {
group_id: 3000,
group_change_policy: FSGroupChangePolicy::Always,
unknown_fields: Default::default(),
cached_size: Default::default(),
group_change_policy: FSGroupChangePolicy::Always.into(),
..Default::default()
}),
read_only: false,
expected_group_id: 3000,
@@ -1963,9 +2025,8 @@ mod tests {
mount_path: "ro_mount",
fs_group: Some(FSGroup {
group_id: 3000,
group_change_policy: FSGroupChangePolicy::OnRootMismatch,
unknown_fields: Default::default(),
cached_size: Default::default(),
group_change_policy: FSGroupChangePolicy::OnRootMismatch.into(),
..Default::default()
}),
read_only: true,
expected_group_id: 3000,
@@ -1985,10 +2046,7 @@ mod tests {
let directory_mode = mount_dir.as_path().metadata().unwrap().permissions().mode();
let mut storage_data = Storage::new();
if d.read_only {
storage_data.set_options(RepeatedField::from_slice(&[
"foo".to_string(),
"ro".to_string(),
]));
storage_data.set_options(vec!["foo".to_string(), "ro".to_string()]);
}
if let Some(fs_group) = d.fs_group.clone() {
storage_data.set_fs_group(fs_group);

View File

@@ -7,7 +7,6 @@ use anyhow::{anyhow, Context, Result};
use futures::{future, StreamExt, TryStreamExt};
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
use nix::errno::Errno;
use protobuf::RepeatedField;
use protocols::types::{ARPNeighbor, IPAddress, IPFamily, Interface, Route};
use rtnetlink::{new_connection, packet, IpVersion};
use std::convert::{TryFrom, TryInto};
@@ -83,8 +82,8 @@ impl Handle {
// Add new ip addresses from request
for ip_address in &iface.IPAddresses {
let ip = IpAddr::from_str(ip_address.get_address())?;
let mask = ip_address.get_mask().parse::<u8>()?;
let ip = IpAddr::from_str(ip_address.address())?;
let mask = ip_address.mask().parse::<u8>()?;
self.add_addresses(link.index(), std::iter::once(IpNetwork::new(ip, mask)?))
.await?;
@@ -152,7 +151,7 @@ impl Handle {
.map(|p| p.try_into())
.collect::<Result<Vec<IPAddress>>>()?;
iface.IPAddresses = RepeatedField::from_vec(ips);
iface.IPAddresses = ips;
list.push(iface);
}
@@ -334,7 +333,7 @@ impl Handle {
// `rtnetlink` offers a separate request builders for different IP versions (IP v4 and v6).
// This if branch is a bit clumsy because it does almost the same.
if route.get_family() == IPFamily::v6 {
if route.family() == IPFamily::v6 {
let dest_addr = if !route.dest.is_empty() {
Ipv6Network::from_str(&route.dest)?
} else {
@@ -368,9 +367,9 @@ impl Handle {
if Errno::from_i32(message.code.abs()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v6 route (src: {}, dst: {}, gtw: {},Err: {})",
route.get_source(),
route.get_dest(),
route.get_gateway(),
route.source(),
route.dest(),
route.gateway(),
message
));
}
@@ -409,9 +408,9 @@ impl Handle {
if Errno::from_i32(message.code.abs()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v4 route (src: {}, dst: {}, gtw: {},Err: {})",
route.get_source(),
route.get_dest(),
route.get_gateway(),
route.source(),
route.dest(),
route.gateway(),
message
));
}
@@ -506,7 +505,7 @@ impl Handle {
self.add_arp_neighbor(&neigh).await.map_err(|err| {
anyhow!(
"Failed to add ARP neighbor {}: {:?}",
neigh.get_toIPAddress().get_address(),
neigh.toIPAddress().address(),
err
)
})?;
@@ -725,7 +724,7 @@ impl TryFrom<Address> for IPAddress {
let mask = format!("{}", value.0.header.prefix_len);
Ok(IPAddress {
family,
family: family.into(),
address,
mask,
..Default::default()

View File

@@ -7,6 +7,7 @@ use anyhow::{anyhow, Result};
use nix::mount::{self, MsFlags};
use slog::Logger;
use std::fs;
use std::path;
const KATA_GUEST_SANDBOX_DNS_FILE: &str = "/run/kata-containers/sandbox/resolv.conf";
const GUEST_DNS_FILE: &str = "/etc/resolv.conf";
@@ -64,6 +65,12 @@ fn do_setup_guest_dns(logger: Logger, dns_list: Vec<String>, src: &str, dst: &st
.map(|x| x.trim())
.collect::<Vec<&str>>()
.join("\n");
// make sure the src file's parent path exist.
let file_path = path::Path::new(src);
if let Some(p) = file_path.parent() {
fs::create_dir_all(p)?;
}
fs::write(src, content)?;
// bind mount to /etc/resolv.conf

View File

@@ -21,22 +21,26 @@ use ttrpc::{
use anyhow::{anyhow, Context, Result};
use cgroups::freezer::FreezerState;
use oci::{LinuxNamespace, Root, Spec};
use protobuf::{Message, RepeatedField, SingularPtrField};
use protobuf::{MessageDyn, MessageField};
use protocols::agent::{
AddSwapRequest, AgentDetails, CopyFileRequest, GetIPTablesRequest, GetIPTablesResponse,
GuestDetailsResponse, Interfaces, Metrics, OOMEvent, ReadStreamResponse, Routes,
SetIPTablesRequest, SetIPTablesResponse, StatsContainerResponse, VolumeStatsRequest,
WaitProcessResponse, WriteStreamResponse,
};
use protocols::csi::{VolumeCondition, VolumeStatsResponse, VolumeUsage, VolumeUsage_Unit};
use protocols::csi::{
volume_usage::Unit as VolumeUsage_Unit, VolumeCondition, VolumeStatsResponse, VolumeUsage,
};
use protocols::empty::Empty;
use protocols::health::{
HealthCheckResponse, HealthCheckResponse_ServingStatus, VersionCheckResponse,
health_check_response::ServingStatus as HealthCheckResponse_ServingStatus, HealthCheckResponse,
VersionCheckResponse,
};
use protocols::types::Interface;
use protocols::{agent_ttrpc_async as agent_ttrpc, health_ttrpc_async as health_ttrpc};
use rustjail::cgroups::notifier;
use rustjail::container::{BaseContainer, Container, LinuxContainer, SYSTEMD_CGROUP_PATH_FORMAT};
use rustjail::mount::parse_mount_table;
use rustjail::process::Process;
use rustjail::specconv::CreateOpts;
@@ -51,7 +55,7 @@ use crate::device::{
};
use crate::linux_abi::*;
use crate::metrics::get_metrics;
use crate::mount::{add_storages, baremount, STORAGE_HANDLER_LIST};
use crate::mount::{add_storages, baremount, update_ephemeral_mounts, STORAGE_HANDLER_LIST};
use crate::namespace::{NSTYPEIPC, NSTYPEPID, NSTYPEUTS};
use crate::network::setup_guest_dns;
use crate::pci;
@@ -93,6 +97,7 @@ const USR_IP6TABLES_SAVE: &str = "/usr/sbin/ip6tables-save";
const IP6TABLES_SAVE: &str = "/sbin/ip6tables-save";
const USR_IP6TABLES_RESTORE: &str = "/usr/sbin/ip6tables-save";
const IP6TABLES_RESTORE: &str = "/sbin/ip6tables-restore";
const KATA_GUEST_SHARE_DIR: &str = "/run/kata-containers/shared/containers/";
const ERR_CANNOT_GET_WRITER: &str = "Cannot get writer";
const ERR_INVALID_BLOCK_SIZE: &str = "Invalid block size";
@@ -124,11 +129,11 @@ macro_rules! is_allowed {
if !AGENT_CONFIG
.read()
.await
.is_allowed_endpoint($req.descriptor().name())
.is_allowed_endpoint($req.descriptor_dyn().name())
{
return Err(ttrpc_error!(
ttrpc::Code::UNIMPLEMENTED,
format!("{} is blocked", $req.descriptor().name()),
format!("{} is blocked", $req.descriptor_dyn().name()),
));
}
};
@@ -151,7 +156,7 @@ impl AgentService {
kata_sys_util::validate::verify_id(&cid)?;
let mut oci_spec = req.OCI.clone();
let use_sandbox_pidns = req.get_sandbox_pidns();
let use_sandbox_pidns = req.sandbox_pidns();
let sandbox;
let mut s;
@@ -785,7 +790,7 @@ impl agent_ttrpc::AgentService for AgentService {
) -> ttrpc::Result<protocols::empty::Empty> {
trace_rpc_call!(ctx, "pause_container", req);
is_allowed!(req);
let cid = req.get_container_id();
let cid = req.container_id();
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
@@ -809,7 +814,7 @@ impl agent_ttrpc::AgentService for AgentService {
) -> ttrpc::Result<protocols::empty::Empty> {
trace_rpc_call!(ctx, "resume_container", req);
is_allowed!(req);
let cid = req.get_container_id();
let cid = req.container_id();
let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().await;
@@ -826,6 +831,29 @@ impl agent_ttrpc::AgentService for AgentService {
Ok(Empty::new())
}
async fn remove_stale_virtiofs_share_mounts(
&self,
ctx: &TtrpcContext,
req: protocols::agent::RemoveStaleVirtiofsShareMountsRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "remove_stale_virtiofs_share_mounts", req);
is_allowed!(req);
let mount_infos = parse_mount_table("/proc/self/mountinfo")
.map_err(|e| ttrpc_error!(ttrpc::Code::INTERNAL, e))?;
for m in &mount_infos {
if m.mount_point.starts_with(KATA_GUEST_SHARE_DIR) {
// stat the mount point, virtiofs daemon will remove the stale cache and release the fds if the mount point doesn't exist any more.
// More details in https://github.com/kata-containers/kata-containers/issues/6455#issuecomment-1477137277
match stat::stat(Path::new(&m.mount_point)) {
Ok(_) => info!(sl!(), "stat {} success", m.mount_point),
Err(e) => info!(sl!(), "stat {} failed: {}", m.mount_point, e),
}
}
}
Ok(Empty::new())
}
async fn write_stdin(
&self,
_ctx: &TtrpcContext,
@@ -964,16 +992,12 @@ impl agent_ttrpc::AgentService for AgentService {
trace_rpc_call!(ctx, "update_routes", req);
is_allowed!(req);
let new_routes = req
.routes
.into_option()
.map(|r| r.Routes.into_vec())
.ok_or_else(|| {
ttrpc_error!(
ttrpc::Code::INVALID_ARGUMENT,
"empty update routes request".to_string(),
)
})?;
let new_routes = req.routes.into_option().map(|r| r.Routes).ok_or_else(|| {
ttrpc_error!(
ttrpc::Code::INVALID_ARGUMENT,
"empty update routes request".to_string(),
)
})?;
let mut sandbox = self.sandbox.lock().await;
@@ -992,11 +1016,28 @@ impl agent_ttrpc::AgentService for AgentService {
})?;
Ok(protocols::agent::Routes {
Routes: RepeatedField::from_vec(list),
Routes: list,
..Default::default()
})
}
async fn update_ephemeral_mounts(
&self,
ctx: &TtrpcContext,
req: protocols::agent::UpdateEphemeralMountsRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "update_mounts", req);
is_allowed!(req);
match update_ephemeral_mounts(sl!(), req.storages.to_vec(), self.sandbox.clone()).await {
Ok(_) => Ok(Empty::new()),
Err(e) => Err(ttrpc_error!(
ttrpc::Code::INTERNAL,
format!("Failed to update mounts: {:?}", e),
)),
}
}
async fn get_ip_tables(
&self,
ctx: &TtrpcContext,
@@ -1174,7 +1215,7 @@ impl agent_ttrpc::AgentService for AgentService {
})?;
Ok(protocols::agent::Interfaces {
Interfaces: RepeatedField::from_vec(list),
Interfaces: list,
..Default::default()
})
}
@@ -1197,7 +1238,7 @@ impl agent_ttrpc::AgentService for AgentService {
.map_err(|e| ttrpc_error!(ttrpc::Code::INTERNAL, format!("list routes: {:?}", e)))?;
Ok(protocols::agent::Routes {
Routes: RepeatedField::from_vec(list),
Routes: list,
..Default::default()
})
}
@@ -1313,7 +1354,7 @@ impl agent_ttrpc::AgentService for AgentService {
let neighs = req
.neighbors
.into_option()
.map(|n| n.ARPNeighbors.into_vec())
.map(|n| n.ARPNeighbors)
.ok_or_else(|| {
ttrpc_error!(
ttrpc::Code::INVALID_ARGUMENT,
@@ -1397,7 +1438,7 @@ impl agent_ttrpc::AgentService for AgentService {
// to get agent details
let detail = get_agent_details();
resp.agent_details = SingularPtrField::some(detail);
resp.agent_details = MessageField::some(detail);
Ok(resp)
}
@@ -1522,8 +1563,8 @@ impl agent_ttrpc::AgentService for AgentService {
.map(|u| usage_vec.push(u))
.map_err(|e| ttrpc_error!(ttrpc::Code::INTERNAL, e))?;
resp.usage = RepeatedField::from_vec(usage_vec);
resp.volume_condition = SingularPtrField::some(condition);
resp.usage = usage_vec;
resp.volume_condition = MessageField::some(condition);
Ok(resp)
}
@@ -1627,7 +1668,7 @@ fn get_volume_capacity_stats(path: &str) -> Result<VolumeUsage> {
usage.total = stat.blocks() * block_size;
usage.available = stat.blocks_free() * block_size;
usage.used = usage.total - usage.available;
usage.unit = VolumeUsage_Unit::BYTES;
usage.unit = VolumeUsage_Unit::BYTES.into();
Ok(usage)
}
@@ -1639,7 +1680,7 @@ fn get_volume_inode_stats(path: &str) -> Result<VolumeUsage> {
usage.total = stat.files();
usage.available = stat.files_free();
usage.used = usage.total - usage.available;
usage.unit = VolumeUsage_Unit::INODES;
usage.unit = VolumeUsage_Unit::INODES.into();
Ok(usage)
}
@@ -1659,14 +1700,12 @@ fn get_agent_details() -> AgentDetails {
detail.set_supports_seccomp(have_seccomp());
detail.init_daemon = unistd::getpid() == Pid::from_raw(1);
detail.device_handlers = RepeatedField::new();
detail.storage_handlers = RepeatedField::from_vec(
STORAGE_HANDLER_LIST
.to_vec()
.iter()
.map(|x| x.to_string())
.collect(),
);
detail.device_handlers = Vec::new();
detail.storage_handlers = STORAGE_HANDLER_LIST
.to_vec()
.iter()
.map(|x| x.to_string())
.collect();
detail
}
@@ -1891,23 +1930,18 @@ fn do_copy_file(req: &CopyFileRequest) -> Result<()> {
));
}
let parent = path.parent();
let dir = if let Some(parent) = parent {
parent.to_path_buf()
} else {
PathBuf::from("/")
};
fs::create_dir_all(&dir).or_else(|e| {
if e.kind() != std::io::ErrorKind::AlreadyExists {
return Err(e);
if let Some(parent) = path.parent() {
if !parent.exists() {
let dir = parent.to_path_buf();
if let Err(e) = fs::create_dir_all(&dir) {
if e.kind() != std::io::ErrorKind::AlreadyExists {
return Err(e.into());
}
} else {
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(req.dir_mode))?;
}
}
Ok(())
})?;
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(req.dir_mode))?;
}
let mut tmpfile = path.clone();
tmpfile.set_extension("tmp");
@@ -2025,7 +2059,7 @@ fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> {
let mut args = vec!["-v".to_string(), module.name.clone()];
if module.parameters.len() > 0 {
if !module.parameters.is_empty() {
args.extend(module.parameters.to_vec())
}

File diff suppressed because it is too large Load Diff

View File

@@ -19,11 +19,11 @@ dbs-boot = "0.3.0"
dbs-device = "0.2.0"
dbs-interrupt = { version = "0.2.0", features = ["kvm-irq"] }
dbs-legacy-devices = "0.1.0"
dbs-upcall = { version = "0.1.0", optional = true }
dbs-upcall = { version = "0.2.0", optional = true }
dbs-utils = "0.2.0"
dbs-virtio-devices = { version = "0.1.0", optional = true, features = ["virtio-mmio"] }
kvm-bindings = "0.5.0"
kvm-ioctls = "0.11.0"
dbs-virtio-devices = { version = "0.2.0", optional = true, features = ["virtio-mmio"] }
kvm-bindings = "0.6.0"
kvm-ioctls = "0.12.0"
lazy_static = "1.2"
libc = "0.2.39"
linux-loader = "0.6.0"
@@ -37,8 +37,9 @@ slog = "2.5.2"
slog-scope = "4.4.0"
thiserror = "1"
vmm-sys-util = "0.11.0"
virtio-queue = { version = "0.4.0", optional = true }
virtio-queue = { version = "0.6.0", optional = true }
vm-memory = { version = "0.9.0", features = ["backend-mmap"] }
crossbeam-channel = "0.5.6"
[dev-dependencies]
slog-term = "2.9.0"
@@ -47,7 +48,7 @@ test-utils = { path = "../libs/test-utils" }
[features]
acpi = []
atomic-guest-memory = [ "vm-memory/backend-atomic" ]
atomic-guest-memory = ["vm-memory/backend-atomic"]
hotplug = ["virtio-vsock"]
virtio-vsock = ["dbs-virtio-devices/virtio-vsock", "virtio-queue"]
virtio-blk = ["dbs-virtio-devices/virtio-blk", "virtio-queue"]

View File

@@ -50,6 +50,8 @@ pub struct InstanceInfo {
pub vmm_version: String,
/// The pid of the current VMM process.
pub pid: u32,
/// The tid of the current VMM master thread.
pub master_tid: u32,
/// The state of async actions.
pub async_state: AsyncState,
/// List of tids of vcpu threads (vcpu index, tid)
@@ -66,6 +68,7 @@ impl InstanceInfo {
state: InstanceState::Uninitialized,
vmm_version,
pid: std::process::id(),
master_tid: 0,
async_state: AsyncState::Uninitialized,
tids: Vec::new(),
last_instance_downtime: 0,
@@ -80,6 +83,7 @@ impl Default for InstanceInfo {
state: InstanceState::Uninitialized,
vmm_version: env!("CARGO_PKG_VERSION").to_string(),
pid: std::process::id(),
master_tid: 0,
async_state: AsyncState::Uninitialized,
tids: Vec::new(),
last_instance_downtime: 0,

View File

@@ -7,8 +7,8 @@
// found in the THIRD-PARTY file.
use std::fs::File;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use crossbeam_channel::{Receiver, Sender, TryRecvError};
use log::{debug, error, info, warn};
use crate::error::{Result, StartMicroVmError, StopMicrovmError};
@@ -676,9 +676,9 @@ fn handle_cpu_topology(
#[cfg(test)]
mod tests {
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use crossbeam_channel::unbounded;
use dbs_utils::epoll_manager::EpollManager;
use test_utils::skip_if_not_root;
use vmm_sys_util::tempfile::TempFile;
@@ -702,8 +702,8 @@ mod tests {
}
fn check_request(&mut self) {
let (to_vmm, from_api) = channel();
let (to_api, from_vmm) = channel();
let (to_vmm, from_api) = unbounded();
let (to_api, from_vmm) = unbounded();
let epoll_mgr = EpollManager::default();
let vmm = Arc::new(Mutex::new(create_vmm_instance(epoll_mgr.clone())));
@@ -728,8 +728,8 @@ mod tests {
fn test_vmm_action_receive_unknown() {
skip_if_not_root!();
let (_to_vmm, from_api) = channel();
let (to_api, _from_vmm) = channel();
let (_to_vmm, from_api) = unbounded();
let (to_api, _from_vmm) = unbounded();
let epoll_mgr = EpollManager::default();
let vmm = Arc::new(Mutex::new(create_vmm_instance(epoll_mgr.clone())));
let mut vservice = VmmService::new(from_api, to_api);
@@ -742,8 +742,8 @@ mod tests {
#[should_panic]
#[test]
fn test_vmm_action_disconnected() {
let (to_vmm, from_api) = channel();
let (to_api, _from_vmm) = channel();
let (to_vmm, from_api) = unbounded();
let (to_api, _from_vmm) = unbounded();
let epoll_mgr = EpollManager::default();
let vmm = Arc::new(Mutex::new(create_vmm_instance(epoll_mgr.clone())));
let mut vservice = VmmService::new(from_api, to_api);

View File

@@ -231,7 +231,7 @@ where
info.config.check_conflicts(config)?;
}
}
self.info_list[index] = device_info;
self.info_list[index].config = config.clone();
index
}
None => {

View File

@@ -776,3 +776,587 @@ impl Default for BlockDeviceMgr {
}
}
}
#[cfg(test)]
mod tests {
use test_utils::skip_if_not_root;
use vmm_sys_util::tempfile::TempFile;
use super::*;
use crate::test_utils::tests::create_vm_for_test;
#[test]
fn test_block_device_type() {
let dev_type = BlockDeviceType::get_type("spool:/device1");
assert_eq!(dev_type, BlockDeviceType::Spool);
let dev_type = BlockDeviceType::get_type("/device1");
assert_eq!(dev_type, BlockDeviceType::RawBlock);
}
#[test]
fn test_create_block_devices_configs() {
let mgr = BlockDeviceMgr::default();
assert!(!mgr.has_root_block_device());
assert!(!mgr.has_part_uuid_root());
assert!(!mgr.is_read_only_root());
assert_eq!(mgr.get_index_of_drive_id(""), None);
assert_eq!(mgr.info_list.len(), 0);
}
#[test]
fn test_add_non_root_block_device() {
skip_if_not_root!();
let dummy_file = TempFile::new().unwrap();
let dummy_path = dummy_file.as_path().to_owned();
let dummy_id = String::from("1");
let dummy_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path.clone(),
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: dummy_id.clone(),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
assert!(BlockDeviceMgr::insert_device(
vm.device_manager_mut(),
ctx,
dummy_block_device.clone(),
)
.is_ok());
assert_eq!(vm.device_manager().block_manager.info_list.len(), 1);
assert!(!vm.device_manager().block_manager.has_root_block_device());
assert!(!vm.device_manager().block_manager.has_part_uuid_root());
assert!(!vm.device_manager().block_manager.is_read_only_root());
assert_eq!(vm.device_manager().block_manager.info_list.len(), 1);
assert_eq!(
vm.device_manager().block_manager.info_list[0]
.config
.device_type(),
BlockDeviceType::RawBlock
);
assert_eq!(
vm.device_manager().block_manager.info_list[0]
.config
.queue_sizes(),
[128u16]
);
let dev_config = vm.device_manager().block_manager.iter().next().unwrap();
assert_eq!(dev_config.config, dummy_block_device);
assert!(vm
.device_manager()
.block_manager
.get_index_of_drive_path(&dummy_path)
.is_some());
assert!(vm
.device_manager()
.block_manager
.get_index_of_drive_id(&dummy_id)
.is_some());
}
#[test]
fn test_update_blk_device_ratelimiters() {
skip_if_not_root!();
//Init vm for test.
let mut vm = create_vm_for_test();
let device_op_ctx = DeviceOpContext::new(
Some(vm.epoll_manager().clone()),
vm.device_manager(),
Some(vm.vm_as().unwrap().clone()),
None,
false,
);
let dummy_file = TempFile::new().unwrap();
let dummy_path = dummy_file.as_path().to_owned();
let dummy_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: true,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
BlockDeviceMgr::insert_device(vm.device_manager_mut(), device_op_ctx, dummy_block_device)
.unwrap();
let cfg = BlockDeviceConfigUpdateInfo {
drive_id: String::from("1"),
rate_limiter: None,
};
let mut device_op_ctx = DeviceOpContext::new(
Some(vm.epoll_manager().clone()),
vm.device_manager(),
Some(vm.vm_as().unwrap().clone()),
None,
false,
);
vm.device_manager_mut()
.block_manager
.attach_devices(&mut device_op_ctx)
.unwrap();
assert_eq!(vm.device_manager().block_manager.info_list.len(), 1);
//Patch while the epoll handler is invalid.
let expected_error = "could not send patch message to the block epoll handler".to_string();
assert_eq!(
BlockDeviceMgr::update_device_ratelimiters(vm.device_manager_mut(), cfg)
.unwrap_err()
.to_string(),
expected_error
);
//Invalid drive id
let cfg2 = BlockDeviceConfigUpdateInfo {
drive_id: String::from("2"),
rate_limiter: None,
};
let expected_error = format!("invalid block device id '{0}'", cfg2.drive_id);
assert_eq!(
BlockDeviceMgr::update_device_ratelimiters(vm.device_manager_mut(), cfg2)
.unwrap_err()
.to_string(),
expected_error
);
}
#[test]
fn test_add_one_root_block_device() {
skip_if_not_root!();
let dummy_file = TempFile::new().unwrap();
let dummy_path = dummy_file.as_path().to_owned();
let dummy_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: true,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
assert!(BlockDeviceMgr::insert_device(
vm.device_manager_mut(),
ctx,
dummy_block_device.clone(),
)
.is_ok());
assert_eq!(vm.device_manager().block_manager.info_list.len(), 1);
assert!(vm.device_manager().block_manager.has_root_block);
assert!(!vm.device_manager().block_manager.has_part_uuid_root);
assert!(vm.device_manager().block_manager.read_only_root);
assert_eq!(vm.device_manager().block_manager.info_list.len(), 1);
let dev_config = vm.device_manager().block_manager.iter().next().unwrap();
assert_eq!(dev_config.config, dummy_block_device);
assert!(vm.device_manager().block_manager.is_read_only_root());
}
#[test]
fn test_add_two_root_block_devices_configs() {
skip_if_not_root!();
let dummy_file_1 = TempFile::new().unwrap();
let dummy_path_1 = dummy_file_1.as_path().to_owned();
let root_block_device_1 = BlockDeviceConfigInfo {
path_on_host: dummy_path_1,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_2 = TempFile::new().unwrap();
let dummy_path_2 = dummy_file_2.as_path().to_owned();
let root_block_device_2 = BlockDeviceConfigInfo {
path_on_host: dummy_path_2,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("2"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device_1).unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
assert!(
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device_2)
.is_err()
);
}
#[test]
// Test BlockDevicesConfigs::add when you first add the root device and then the other devices.
fn test_add_root_block_device_first() {
skip_if_not_root!();
let dummy_file_1 = TempFile::new().unwrap();
let dummy_path_1 = dummy_file_1.as_path().to_owned();
let root_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path_1,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_2 = TempFile::new().unwrap();
let dummy_path_2 = dummy_file_2.as_path().to_owned();
let dummy_block_device_2 = BlockDeviceConfigInfo {
path_on_host: dummy_path_2,
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("2"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_3 = TempFile::new().unwrap();
let dummy_path_3 = dummy_file_3.as_path().to_owned();
let dummy_block_device_3 = BlockDeviceConfigInfo {
path_on_host: dummy_path_3,
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("3"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
vm.device_manager_mut()
.block_manager
.create(root_block_device.clone())
.unwrap();
vm.device_manager_mut()
.block_manager
.create(dummy_block_device_2.clone())
.unwrap();
vm.device_manager_mut()
.block_manager
.create(dummy_block_device_3.clone())
.unwrap();
assert!(vm.device_manager().block_manager.has_root_block_device(),);
assert!(!vm.device_manager().block_manager.has_part_uuid_root());
assert_eq!(vm.device_manager().block_manager.info_list.len(), 3);
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device).unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_2).unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_3).unwrap();
}
#[test]
// Test BlockDevicesConfigs::add when you add other devices first and then the root device.
fn test_root_block_device_add_last() {
skip_if_not_root!();
let dummy_file_1 = TempFile::new().unwrap();
let dummy_path_1 = dummy_file_1.as_path().to_owned();
let root_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path_1,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_2 = TempFile::new().unwrap();
let dummy_path_2 = dummy_file_2.as_path().to_owned();
let dummy_block_device_2 = BlockDeviceConfigInfo {
path_on_host: dummy_path_2,
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("2"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_3 = TempFile::new().unwrap();
let dummy_path_3 = dummy_file_3.as_path().to_owned();
let dummy_block_device_3 = BlockDeviceConfigInfo {
path_on_host: dummy_path_3,
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("3"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_2.clone())
.unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_3.clone())
.unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device.clone())
.unwrap();
assert!(vm.device_manager().block_manager.has_root_block_device(),);
assert!(!vm.device_manager().block_manager.has_part_uuid_root());
assert_eq!(vm.device_manager().block_manager.info_list.len(), 3);
let mut block_dev_iter = vm.device_manager().block_manager.iter();
// The root device should be first in the list no matter of the order in
// which the devices were added.
assert_eq!(
block_dev_iter.next().unwrap().config.drive_id,
root_block_device.drive_id
);
assert_eq!(
block_dev_iter.next().unwrap().config.drive_id,
dummy_block_device_2.drive_id
);
assert_eq!(
block_dev_iter.next().unwrap().config.drive_id,
dummy_block_device_3.drive_id
);
}
#[test]
fn test_block_device_update() {
skip_if_not_root!();
let dummy_file_1 = TempFile::new().unwrap();
let dummy_path_1 = dummy_file_1.as_path().to_owned();
let root_block_device = BlockDeviceConfigInfo {
path_on_host: dummy_path_1.clone(),
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let dummy_file_2 = TempFile::new().unwrap();
let dummy_path_2 = dummy_file_2.as_path().to_owned();
let mut dummy_block_device_2 = BlockDeviceConfigInfo {
path_on_host: dummy_path_2.clone(),
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("2"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let mut vm = crate::vm::tests::create_vm_instance();
// Add 2 block devices.
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device).unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_2.clone())
.unwrap();
// Get index zero.
assert_eq!(
vm.device_manager()
.block_manager
.get_index_of_drive_id(&String::from("1"))
.unwrap(),
0
);
// Get None.
assert!(vm
.device_manager()
.block_manager
.get_index_of_drive_id(&String::from("foo"))
.is_none());
// Test several update cases using dummy_block_device_2.
// Validate `dummy_block_device_2` is already in the list
assert!(vm
.device_manager()
.block_manager
.get_index_of_drive_id(&dummy_block_device_2.drive_id)
.is_some());
// Update OK.
dummy_block_device_2.is_read_only = true;
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_2.clone())
.unwrap();
let index = vm
.device_manager()
.block_manager
.get_index_of_drive_id(&dummy_block_device_2.drive_id)
.unwrap();
// Validate update was successful.
assert!(
vm.device_manager().block_manager.info_list[index]
.config
.is_read_only
);
// Update with invalid path.
let dummy_filename_3 = String::from("test_update_3");
let dummy_path_3 = PathBuf::from(dummy_filename_3);
dummy_block_device_2.path_on_host = dummy_path_3;
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
assert!(BlockDeviceMgr::insert_device(
vm.device_manager_mut(),
ctx,
dummy_block_device_2.clone(),
)
.is_err());
// Update with 2 root block devices.
dummy_block_device_2.path_on_host = dummy_path_2.clone();
dummy_block_device_2.is_root_device = true;
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
assert!(
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, dummy_block_device_2,)
.is_err(),
);
// Switch roots and add a PARTUUID for the new one.
let root_block_device_old = BlockDeviceConfigInfo {
path_on_host: dummy_path_1,
device_type: BlockDeviceType::RawBlock,
is_root_device: false,
part_uuid: None,
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("1"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let root_block_device_new = BlockDeviceConfigInfo {
path_on_host: dummy_path_2,
device_type: BlockDeviceType::RawBlock,
is_root_device: true,
part_uuid: Some("0eaa91a0-01".to_string()),
is_read_only: false,
is_direct: false,
no_drop: false,
drive_id: String::from("2"),
rate_limiter: None,
num_queues: BlockDeviceConfigInfo::default_num_queues(),
queue_size: 128,
use_shared_irq: None,
use_generic_irq: None,
};
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device_old).unwrap();
let ctx = DeviceOpContext::create_boot_ctx(&vm, None);
BlockDeviceMgr::insert_device(vm.device_manager_mut(), ctx, root_block_device_new).unwrap();
assert!(vm.device_manager().block_manager.has_part_uuid_root);
}
}

View File

@@ -147,17 +147,13 @@ pub type Result<T> = ::std::result::Result<T, DeviceMgrError>;
/// Type of the dragonball virtio devices.
#[cfg(feature = "dbs-virtio-devices")]
pub type DbsVirtioDevice = Box<
dyn VirtioDevice<
GuestAddressSpaceImpl,
virtio_queue::QueueStateSync,
vm_memory::GuestRegionMmap,
>,
dyn VirtioDevice<GuestAddressSpaceImpl, virtio_queue::QueueSync, vm_memory::GuestRegionMmap>,
>;
/// Type of the dragonball virtio mmio devices.
#[cfg(feature = "dbs-virtio-devices")]
pub type DbsMmioV2Device =
MmioV2Device<GuestAddressSpaceImpl, virtio_queue::QueueStateSync, vm_memory::GuestRegionMmap>;
MmioV2Device<GuestAddressSpaceImpl, virtio_queue::QueueSync, vm_memory::GuestRegionMmap>;
/// Struct to support transactional operations for device management.
pub struct DeviceManagerTx {

View File

@@ -9,6 +9,8 @@
//! Error codes for the virtual machine monitor subsystem.
#[cfg(target_arch = "aarch64")]
use dbs_arch::pmu::PmuError;
#[cfg(feature = "dbs-virtio-devices")]
use dbs_virtio_devices::Error as VirtIoError;
@@ -61,6 +63,11 @@ pub enum Error {
#[error("failed to write MP table to guest memory: {0}")]
MpTableSetup(#[source] dbs_boot::mptable::Error),
/// Create pmu device error
#[cfg(target_arch = "aarch64")]
#[error("Create pmu device error: {0}")]
PmuDeviceError(#[source] PmuError),
/// Fail to boot system
#[error("failed to boot system: {0}")]
BootSystem(#[source] dbs_boot::Error),

View File

@@ -11,7 +11,7 @@ use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use crate::IoManagerCached;
use dbs_arch::regs;
use dbs_arch::{regs, VpmuFeatureLevel};
use dbs_boot::get_fdt_addr;
use dbs_utils::time::TimestampUs;
use kvm_ioctls::{VcpuFd, VmFd};
@@ -81,7 +81,7 @@ impl Vcpu {
/// * `_pgtable_addr` - pgtable address for ap vcpu (not used in aarch64)
pub fn configure(
&mut self,
_vcpu_config: &VcpuConfig,
vcpu_config: &VcpuConfig,
vm_fd: &VmFd,
vm_as: &GuestAddressSpaceImpl,
kernel_load_addr: Option<GuestAddress>,
@@ -99,6 +99,9 @@ impl Vcpu {
if self.id > 0 {
kvi.features[0] |= 1 << kvm_bindings::KVM_ARM_VCPU_POWER_OFF;
}
if vcpu_config.vpmu_feature == VpmuFeatureLevel::FullyEnabled {
kvi.features[0] |= 1 << kvm_bindings::KVM_ARM_VCPU_PMU_V3;
}
self.fd.vcpu_init(&kvi).map_err(VcpuError::VcpuArmInit)?;

View File

@@ -7,9 +7,7 @@ mod sm;
mod vcpu_impl;
mod vcpu_manager;
#[cfg(target_arch = "x86_64")]
use dbs_arch::cpuid::VpmuFeatureLevel;
use dbs_arch::VpmuFeatureLevel;
pub use vcpu_manager::{VcpuManager, VcpuManagerError, VcpuResizeInfo};
#[cfg(feature = "hotplug")]
@@ -32,6 +30,6 @@ pub struct VcpuConfig {
/// if vpmu feature is Disabled, it means vpmu feature is off (by default)
/// if vpmu feature is LimitedlyEnabled, it means minimal vpmu counters are supported (cycles and instructions)
/// if vpmu feature is FullyEnabled, it means all vpmu counters are supported
#[cfg(target_arch = "x86_64")]
/// For aarch64, VpmuFeatureLevel only supports Disabled and FullyEnabled.
pub vpmu_feature: VpmuFeatureLevel,
}

View File

@@ -441,75 +441,77 @@ impl Vcpu {
/// Returns error or enum specifying whether emulation was handled or interrupted.
fn run_emulation(&mut self) -> Result<VcpuEmulation> {
match Vcpu::emulate(&self.fd) {
Ok(run) => match run {
#[cfg(target_arch = "x86_64")]
VcpuExit::IoIn(addr, data) => {
let _ = self.io_mgr.pio_read(addr, data);
METRICS.vcpu.exit_io_in.inc();
Ok(VcpuEmulation::Handled)
}
#[cfg(target_arch = "x86_64")]
VcpuExit::IoOut(addr, data) => {
if !self.check_io_port_info(addr, data)? {
let _ = self.io_mgr.pio_write(addr, data);
Ok(run) => {
match run {
#[cfg(target_arch = "x86_64")]
VcpuExit::IoIn(addr, data) => {
let _ = self.io_mgr.pio_read(addr, data);
METRICS.vcpu.exit_io_in.inc();
Ok(VcpuEmulation::Handled)
}
METRICS.vcpu.exit_io_out.inc();
Ok(VcpuEmulation::Handled)
}
VcpuExit::MmioRead(addr, data) => {
let _ = self.io_mgr.mmio_read(addr, data);
METRICS.vcpu.exit_mmio_read.inc();
Ok(VcpuEmulation::Handled)
}
VcpuExit::MmioWrite(addr, data) => {
let _ = self.io_mgr.mmio_write(addr, data);
METRICS.vcpu.exit_mmio_write.inc();
Ok(VcpuEmulation::Handled)
}
VcpuExit::Hlt => {
info!("Received KVM_EXIT_HLT signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::Shutdown => {
info!("Received KVM_EXIT_SHUTDOWN signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
// Documentation specifies that below kvm exits are considered errors.
VcpuExit::FailEntry => {
METRICS.vcpu.failures.inc();
error!("Received KVM_EXIT_FAIL_ENTRY signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::InternalError => {
METRICS.vcpu.failures.inc();
error!("Received KVM_EXIT_INTERNAL_ERROR signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::SystemEvent(event_type, event_flags) => match event_type {
KVM_SYSTEM_EVENT_RESET | KVM_SYSTEM_EVENT_SHUTDOWN => {
info!(
"Received KVM_SYSTEM_EVENT: type: {}, event: {}",
event_type, event_flags
);
Ok(VcpuEmulation::Stopped)
#[cfg(target_arch = "x86_64")]
VcpuExit::IoOut(addr, data) => {
if !self.check_io_port_info(addr, data)? {
let _ = self.io_mgr.pio_write(addr, data);
}
METRICS.vcpu.exit_io_out.inc();
Ok(VcpuEmulation::Handled)
}
_ => {
METRICS.vcpu.failures.inc();
error!(
"Received KVM_SYSTEM_EVENT signal type: {}, flag: {}",
event_type, event_flags
);
VcpuExit::MmioRead(addr, data) => {
let _ = self.io_mgr.mmio_read(addr, data);
METRICS.vcpu.exit_mmio_read.inc();
Ok(VcpuEmulation::Handled)
}
VcpuExit::MmioWrite(addr, data) => {
let _ = self.io_mgr.mmio_write(addr, data);
METRICS.vcpu.exit_mmio_write.inc();
Ok(VcpuEmulation::Handled)
}
VcpuExit::Hlt => {
info!("Received KVM_EXIT_HLT signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::Shutdown => {
info!("Received KVM_EXIT_SHUTDOWN signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
// Documentation specifies that below kvm exits are considered errors.
VcpuExit::FailEntry(reason, cpu) => {
METRICS.vcpu.failures.inc();
error!("Received KVM_EXIT_FAIL_ENTRY signal, reason {reason}, cpu number {cpu}");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::InternalError => {
METRICS.vcpu.failures.inc();
error!("Received KVM_EXIT_INTERNAL_ERROR signal");
Err(VcpuError::VcpuUnhandledKvmExit)
}
VcpuExit::SystemEvent(event_type, event_flags) => match event_type {
KVM_SYSTEM_EVENT_RESET | KVM_SYSTEM_EVENT_SHUTDOWN => {
info!(
"Received KVM_SYSTEM_EVENT: type: {}, event: {}",
event_type, event_flags
);
Ok(VcpuEmulation::Stopped)
}
_ => {
METRICS.vcpu.failures.inc();
error!(
"Received KVM_SYSTEM_EVENT signal type: {}, flag: {}",
event_type, event_flags
);
Err(VcpuError::VcpuUnhandledKvmExit)
}
},
r => {
METRICS.vcpu.failures.inc();
// TODO: Are we sure we want to finish running a vcpu upon
// receiving a vm exit that is not necessarily an error?
error!("Unexpected exit reason on vcpu run: {:?}", r);
Err(VcpuError::VcpuUnhandledKvmExit)
}
},
r => {
METRICS.vcpu.failures.inc();
// TODO: Are we sure we want to finish running a vcpu upon
// receiving a vm exit that is not necessarily an error?
error!("Unexpected exit reason on vcpu run: {:?}", r);
Err(VcpuError::VcpuUnhandledKvmExit)
}
},
}
// The unwrap on raw_os_error can only fail if we have a logic
// error in our code in which case it is better to panic.
Err(ref e) => {
@@ -758,6 +760,11 @@ impl Vcpu {
// State machine reached its end.
StateMachine::finish(Self::exited)
}
/// Get vcpu file descriptor.
pub fn vcpu_fd(&self) -> &VcpuFd {
self.fd.as_ref()
}
}
impl Drop for Vcpu {
@@ -786,7 +793,7 @@ pub mod tests {
MmioWrite,
Hlt,
Shutdown,
FailEntry,
FailEntry(u64, u32),
InternalError,
Unknown,
SystemEvent(u32, u64),
@@ -807,7 +814,9 @@ pub mod tests {
EmulationCase::MmioWrite => Ok(VcpuExit::MmioWrite(0, &[])),
EmulationCase::Hlt => Ok(VcpuExit::Hlt),
EmulationCase::Shutdown => Ok(VcpuExit::Shutdown),
EmulationCase::FailEntry => Ok(VcpuExit::FailEntry),
EmulationCase::FailEntry(error_type, cpu_num) => {
Ok(VcpuExit::FailEntry(*error_type, *cpu_num))
}
EmulationCase::InternalError => Ok(VcpuExit::InternalError),
EmulationCase::Unknown => Ok(VcpuExit::Unknown),
EmulationCase::SystemEvent(event_type, event_flags) => {
@@ -850,6 +859,8 @@ pub mod tests {
#[cfg(target_arch = "aarch64")]
fn create_vcpu() -> (Vcpu, Receiver<VcpuStateEvent>) {
use kvm_ioctls::Kvm;
use std::os::fd::AsRawFd;
// Call for kvm too frequently would cause error in some host kernel.
std::thread::sleep(std::time::Duration::from_millis(5));
@@ -918,7 +929,7 @@ pub mod tests {
assert!(matches!(res, Err(VcpuError::VcpuUnhandledKvmExit)));
// KVM_EXIT_FAIL_ENTRY signal
*(EMULATE_RES.lock().unwrap()) = EmulationCase::FailEntry;
*(EMULATE_RES.lock().unwrap()) = EmulationCase::FailEntry(0, 0);
let res = vcpu.run_emulation();
assert!(matches!(res, Err(VcpuError::VcpuUnhandledKvmExit)));

View File

@@ -15,6 +15,7 @@ use std::sync::mpsc::{channel, Receiver, RecvError, RecvTimeoutError, Sender};
use std::sync::{Arc, Barrier, Mutex, RwLock};
use std::time::Duration;
use dbs_arch::VpmuFeatureLevel;
#[cfg(all(feature = "hotplug", feature = "dbs-upcall"))]
use dbs_upcall::{DevMgrService, UpcallClient};
use dbs_utils::epoll_manager::{EpollManager, EventOps, EventSet, Events, MutEventSubscriber};
@@ -281,11 +282,20 @@ impl VcpuManager {
let supported_cpuid = kvm_context
.supported_cpuid(kvm_bindings::KVM_MAX_CPUID_ENTRIES)
.map_err(VcpuManagerError::Kvm)?;
#[cfg(target_arch = "x86_64")]
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
let vpmu_feature_level = match vm_config_info.vpmu_feature {
1 => dbs_arch::cpuid::VpmuFeatureLevel::LimitedlyEnabled,
2 => dbs_arch::cpuid::VpmuFeatureLevel::FullyEnabled,
_ => dbs_arch::cpuid::VpmuFeatureLevel::Disabled,
#[cfg(target_arch = "x86_64")]
1 => VpmuFeatureLevel::LimitedlyEnabled,
#[cfg(target_arch = "aarch64")]
1 => {
log::warn!(
"Limitedly enabled vpmu feature isn't supported on aarch64 for now.\
This will be supported in the future. The vpmu_feature will be set disabled!"
);
VpmuFeatureLevel::Disabled
}
2 => VpmuFeatureLevel::FullyEnabled,
_ => VpmuFeatureLevel::Disabled,
};
let vcpu_manager = Arc::new(Mutex::new(VcpuManager {
@@ -297,7 +307,6 @@ impl VcpuManager {
cores_per_die: vm_config_info.cpu_topology.cores_per_die,
dies_per_socket: vm_config_info.cpu_topology.dies_per_socket,
sockets: vm_config_info.cpu_topology.sockets,
#[cfg(target_arch = "x86_64")]
vpmu_feature: vpmu_feature_level,
},
vcpu_seccomp_filter,
@@ -799,6 +808,11 @@ impl VcpuManager {
)
.map_err(VcpuManagerError::Vcpu)
}
/// get vpmu_feature config
pub fn vpmu_feature(&self) -> VpmuFeatureLevel {
self.vcpu_config.vpmu_feature
}
}
#[cfg(feature = "hotplug")]
@@ -887,7 +901,9 @@ mod hotplug {
cpu_ids_array[..cpu_ids.len()].copy_from_slice(&cpu_ids[..cpu_ids.len()]);
let req = DevMgrRequest::AddVcpu(CpuDevRequest {
count: cpu_ids.len() as u8,
#[cfg(target_arch = "x86_64")]
apic_ids: cpu_ids_array,
#[cfg(target_arch = "x86_64")]
apic_ver: APIC_VERSION,
});
self.send_upcall_action(upcall_client, req)?;
@@ -924,7 +940,9 @@ mod hotplug {
cpu_ids_array[..cpu_ids.len()].copy_from_slice(&cpu_ids[..cpu_ids.len()]);
let req = DevMgrRequest::DelVcpu(CpuDevRequest {
count: cpu_num_to_be_del as u8,
#[cfg(target_arch = "x86_64")]
apic_ids: cpu_ids_array,
#[cfg(target_arch = "x86_64")]
apic_ver: APIC_VERSION,
});
self.send_upcall_action(upcall_client, req)?;
@@ -969,7 +987,10 @@ mod hotplug {
vcpu_state_sender
.send(VcpuStateEvent::Hotplug((
result,
#[cfg(target_arch = "x86_64")]
resp.info.apic_id_index,
#[cfg(target_arch = "aarch64")]
resp.info.cpu_id,
)))
.unwrap();
vcpu_state_event.write(1).unwrap();

View File

@@ -11,7 +11,8 @@ use std::fmt::Debug;
use std::ops::Deref;
use dbs_arch::gic::GICDevice;
use dbs_arch::{DeviceInfoForFDT, DeviceType};
use dbs_arch::pmu::initialize_pmu;
use dbs_arch::{DeviceInfoForFDT, DeviceType, VpmuFeatureLevel};
use dbs_boot::InitrdConfig;
use dbs_utils::epoll_manager::EpollManager;
use dbs_utils::time::TimestampUs;
@@ -43,6 +44,7 @@ fn configure_system<T: DeviceInfoForFDT + Clone + Debug, M: GuestMemory>(
device_info: Option<&HashMap<(DeviceType, String), T>>,
gic_device: &Box<dyn GICDevice>,
initrd: &Option<super::InitrdConfig>,
vpmu_feature: &VpmuFeatureLevel,
) -> super::Result<()> {
dbs_boot::fdt::create_fdt(
guest_mem,
@@ -51,6 +53,7 @@ fn configure_system<T: DeviceInfoForFDT + Clone + Debug, M: GuestMemory>(
device_info,
gic_device,
initrd,
vpmu_feature,
)
.map_err(Error::BootSystem)?;
Ok(())
@@ -76,6 +79,23 @@ impl Vm {
Ok(())
}
/// Setup pmu devices for guest vm.
pub fn setup_pmu_devices(&mut self) -> std::result::Result<(), StartMicroVmError> {
let vm = self.vm_fd();
let mut vcpu_manager = self.vcpu_manager().map_err(StartMicroVmError::Vcpu)?;
let vpmu_feature = vcpu_manager.vpmu_feature();
if vpmu_feature == VpmuFeatureLevel::Disabled {
return Ok(());
}
for vcpu in vcpu_manager.vcpus_mut() {
initialize_pmu(vm, vcpu.vcpu_fd())
.map_err(|e| StartMicroVmError::ConfigureVm(VmError::SetupPmu(e)))?;
}
Ok(())
}
/// Initialize the virtual machine instance.
///
/// It initialize the virtual machine instance by:
@@ -113,6 +133,7 @@ impl Vm {
.create_boot_vcpus(request_ts, kernel_loader_result.kernel_load)
.map_err(StartMicroVmError::Vcpu)?;
self.setup_interrupt_controller()?;
self.setup_pmu_devices()?;
self.init_devices(epoll_mgr)?;
Ok(())
@@ -129,6 +150,7 @@ impl Vm {
initrd: Option<InitrdConfig>,
) -> std::result::Result<(), StartMicroVmError> {
let vcpu_manager = self.vcpu_manager().map_err(StartMicroVmError::Vcpu)?;
let vpmu_feature = vcpu_manager.vpmu_feature();
let vcpu_mpidr = vcpu_manager
.vcpus()
.into_iter()
@@ -143,6 +165,7 @@ impl Vm {
self.device_manager.get_mmio_device_info(),
self.get_irqchip(),
&initrd,
&vpmu_feature,
)
.map_err(StartMicroVmError::ConfigureSystem)
}

View File

@@ -10,6 +10,8 @@ use std::sync::{Arc, Mutex, RwLock};
use dbs_address_space::AddressSpace;
#[cfg(target_arch = "aarch64")]
use dbs_arch::gic::GICDevice;
#[cfg(target_arch = "aarch64")]
use dbs_arch::pmu::PmuError;
use dbs_boot::InitrdConfig;
use dbs_utils::epoll_manager::EpollManager;
use dbs_utils::time::TimestampUs;
@@ -69,6 +71,11 @@ pub enum VmError {
#[cfg(target_arch = "aarch64")]
#[error("failed to configure GIC")]
SetupGIC(GICError),
/// Cannot setup pmu device
#[cfg(target_arch = "aarch64")]
#[error("failed to setup pmu device")]
SetupPmu(#[source] PmuError),
}
/// Configuration information for user defined NUMA nodes.
@@ -1005,6 +1012,7 @@ pub mod tests {
assert!(vm.remove_devices().is_ok());
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_run_code() {
skip_if_not_root!();

View File

@@ -7,7 +7,6 @@
// found in the THIRD-PARTY file.
use std::convert::TryInto;
use std::mem;
use std::ops::Deref;
use dbs_address_space::AddressSpace;
@@ -16,8 +15,9 @@ use dbs_utils::epoll_manager::EpollManager;
use dbs_utils::time::TimestampUs;
use kvm_bindings::{kvm_irqchip, kvm_pit_config, kvm_pit_state2, KVM_PIT_SPEAKER_DUMMY};
use linux_loader::cmdline::Cmdline;
use linux_loader::configurator::{linux::LinuxBootConfigurator, BootConfigurator, BootParams};
use slog::info;
use vm_memory::{Address, Bytes, GuestAddress, GuestAddressSpace, GuestMemory};
use vm_memory::{Address, GuestAddress, GuestAddressSpace, GuestMemory};
use crate::address_space_manager::{GuestAddressSpaceImpl, GuestMemoryImpl};
use crate::error::{Error, Result, StartMicroVmError};
@@ -110,15 +110,11 @@ fn configure_system<M: GuestMemory>(
}
}
let zero_page_addr = GuestAddress(layout::ZERO_PAGE_START);
guest_mem
.checked_offset(zero_page_addr, mem::size_of::<bootparam::boot_params>())
.ok_or(Error::ZeroPagePastRamEnd)?;
guest_mem
.write_obj(params, zero_page_addr)
.map_err(|_| Error::ZeroPageSetup)?;
Ok(())
LinuxBootConfigurator::write_bootparams(
&BootParams::new(&params, GuestAddress(layout::ZERO_PAGE_START)),
guest_mem,
)
.map_err(|_| Error::ZeroPageSetup)
}
impl Vm {

85
src/libs/Cargo.lock generated
View File

@@ -703,9 +703,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.9.0"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "parking_lot"
@@ -845,9 +845,16 @@ name = "protobuf"
version = "2.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf7e6d18738ecd0902d30d1ad232c9125985a3422929b16c65517b38adc14f96"
[[package]]
name = "protobuf"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b55bad9126f378a853655831eb7363b7b01b81d19f8cb1218861086ca4a1a61e"
dependencies = [
"serde",
"serde_derive",
"once_cell",
"protobuf-support",
"thiserror",
]
[[package]]
@@ -856,17 +863,47 @@ version = "2.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aec1632b7c8f2e620343439a7dfd1f3c47b18906c4be58982079911482b5d707"
dependencies = [
"protobuf",
"protobuf 2.27.1",
]
[[package]]
name = "protobuf-codegen-pure"
version = "2.27.1"
name = "protobuf-codegen"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f8122fdb18e55190c796b088a16bdb70cd7acdcd48f7a8b796b58c62e532cc6"
checksum = "0dd418ac3c91caa4032d37cb80ff0d44e2ebe637b2fb243b6234bf89cdac4901"
dependencies = [
"protobuf",
"protobuf-codegen",
"anyhow",
"once_cell",
"protobuf 3.2.0",
"protobuf-parse",
"regex",
"tempfile",
"thiserror",
]
[[package]]
name = "protobuf-parse"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d39b14605eaa1f6a340aec7f320b34064feb26c93aec35d6a9a2272a8ddfa49"
dependencies = [
"anyhow",
"indexmap",
"log",
"protobuf 3.2.0",
"protobuf-support",
"tempfile",
"thiserror",
"which",
]
[[package]]
name = "protobuf-support"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d4d7b8601c814cfb36bcebb79f0e61e45e1e93640cf778837833bbed05c372"
dependencies = [
"thiserror",
]
[[package]]
@@ -875,7 +912,7 @@ version = "0.1.0"
dependencies = [
"async-trait",
"oci",
"protobuf",
"protobuf 3.2.0",
"serde",
"serde_json",
"ttrpc",
@@ -1314,9 +1351,9 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
[[package]]
name = "ttrpc"
version = "0.6.1"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ecfff459a859c6ba6668ff72b34c2f1d94d9d58f7088414c2674ad0f31cc7d8"
checksum = "a35f22a2964bea14afee161665bb260b83cb48e665e0260ca06ec0e775c8b06c"
dependencies = [
"async-trait",
"byteorder",
@@ -1324,8 +1361,8 @@ dependencies = [
"libc",
"log",
"nix 0.23.1",
"protobuf",
"protobuf-codegen-pure",
"protobuf 3.2.0",
"protobuf-codegen 3.2.0",
"thiserror",
"tokio",
"tokio-vsock",
@@ -1333,28 +1370,28 @@ dependencies = [
[[package]]
name = "ttrpc-codegen"
version = "0.2.0"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809eda4e459820237104e4b61d6b41bbe6c9e1ce6adf4057955e6e6722a90408"
checksum = "94d7f7631d7a9ebed715a47cd4cb6072cbc7ae1d4ec01598971bbec0024340c2"
dependencies = [
"protobuf",
"protobuf-codegen",
"protobuf-codegen-pure",
"protobuf 2.27.1",
"protobuf-codegen 3.2.0",
"protobuf-support",
"ttrpc-compiler",
]
[[package]]
name = "ttrpc-compiler"
version = "0.4.1"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2978ed3fa047d8fd55cbeb4d4a61d461fb3021a90c9618519c73ce7e5bb66c15"
checksum = "ec3cb5dbf1f0865a34fe3f722290fe776cacb16f50428610b779467b76ddf647"
dependencies = [
"derive-new",
"prost",
"prost-build",
"prost-types",
"protobuf",
"protobuf-codegen",
"protobuf 2.27.1",
"protobuf-codegen 2.27.1",
"tempfile",
]

View File

@@ -308,6 +308,14 @@ pub const KATA_ANNO_CFG_DISABLE_NEW_NETNS: &str =
/// A sandbox annotation to specify how attached VFIO devices should be treated.
pub const KATA_ANNO_CFG_VFIO_MODE: &str = "io.katacontainers.config.runtime.vfio_mode";
/// A sandbox annotation used to specify prefetch_files.list host path container image
/// being used,
/// and runtime will pass it to Hypervisor to search for corresponding prefetch list file.
/// "io.katacontainers.config.hypervisor.prefetch_files.list"
/// = "/path/to/<uid>/xyz.com/fedora:36/prefetch_file.list"
pub const KATA_ANNO_CFG_HYPERVISOR_PREFETCH_FILES_LIST: &str =
"io.katacontainers.config.hypervisor.prefetch_files.list";
/// A helper structure to query configuration information by check annotations.
#[derive(Debug, Default, Deserialize)]
pub struct Annotation {
@@ -409,10 +417,10 @@ impl Annotation {
match self.get_value::<u32>(KATA_ANNO_CONTAINER_RES_SWAPPINESS) {
Ok(r) => {
if r.unwrap_or_default() > 100 {
return Err(io::Error::new(
Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("{} greater than 100", r.unwrap_or_default()),
));
))
} else {
Ok(r)
}
@@ -673,6 +681,9 @@ impl Annotation {
hv.machine_info.validate_entropy_source(value)?;
hv.machine_info.entropy_source = value.to_string();
}
KATA_ANNO_CFG_HYPERVISOR_PREFETCH_FILES_LIST => {
hv.prefetch_list_path = value.to_string();
}
// Hypervisor Memory related annotations
KATA_ANNO_CFG_HYPERVISOR_DEFAULT_MEMORY => {
match byte_unit::Byte::from_str(value) {

View File

@@ -9,14 +9,16 @@ use crate::config::{ConfigOps, TomlConfig};
pub use vendor::AgentVendor;
use super::default::{DEFAULT_AGENT_LOG_PORT, DEFAULT_AGENT_VSOCK_PORT};
use super::default::{
DEFAULT_AGENT_DIAL_TIMEOUT_MS, DEFAULT_AGENT_LOG_PORT, DEFAULT_AGENT_VSOCK_PORT,
};
use crate::eother;
/// agent name of Kata agent.
pub const AGENT_NAME_KATA: &str = "kata";
/// Kata agent configuration information.
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Agent {
/// If enabled, the agent will log additional debug messages to the system log.
#[serde(default, rename = "enable_debug")]
@@ -78,9 +80,28 @@ pub struct Agent {
pub kernel_modules: Vec<String>,
/// container pipe size
#[serde(default)]
pub container_pipe_size: u32,
}
impl std::default::Default for Agent {
fn default() -> Self {
Self {
debug: true,
enable_tracing: false,
debug_console_enabled: false,
server_port: DEFAULT_AGENT_VSOCK_PORT,
log_port: DEFAULT_AGENT_LOG_PORT,
dial_timeout_ms: DEFAULT_AGENT_DIAL_TIMEOUT_MS,
reconnect_timeout_ms: 3_000,
request_timeout_ms: 30_000,
health_check_request_timeout_ms: 90_000,
kernel_modules: Default::default(),
container_pipe_size: 0,
}
}
}
fn default_server_port() -> u32 {
DEFAULT_AGENT_VSOCK_PORT
}

View File

@@ -16,6 +16,7 @@ lazy_static! {
pub static ref DEFAULT_RUNTIME_CONFIGURATIONS: Vec::<&'static str> = vec![
"/etc/kata-containers/configuration.toml",
"/usr/share/defaults/kata-containers/configuration.toml",
"/opt/kata/share/defaults/kata-containers/configuration.toml",
];
}
@@ -24,6 +25,7 @@ pub const DEFAULT_AGENT_VSOCK_PORT: u32 = 1024;
pub const DEFAULT_AGENT_LOG_PORT: u32 = 1025;
pub const DEFAULT_AGENT_DBG_CONSOLE_PORT: u32 = 1026;
pub const DEFAULT_AGENT_TYPE_NAME: &str = AGENT_NAME_KATA;
pub const DEFAULT_AGENT_DIAL_TIMEOUT_MS: u32 = 10;
pub const DEFAULT_RUNTIME_NAME: &str = RUNTIME_NAME_VIRTCONTAINER;
pub const DEFAULT_HYPERVISOR: &str = HYPERVISOR_NAME_DRAGONBALL;
@@ -42,6 +44,7 @@ pub const MIN_SHARED_9PFS_SIZE_MB: u32 = 4 * 1024;
pub const MAX_SHARED_9PFS_SIZE_MB: u32 = 8 * 1024 * 1024;
pub const DEFAULT_GUEST_HOOK_PATH: &str = "/opt/kata/hooks";
pub const DEFAULT_GUEST_DNS_FILE: &str = "/etc/resolv.conf";
pub const DEFAULT_GUEST_VCPUS: u32 = 1;
@@ -67,3 +70,18 @@ pub const DEFAULT_QEMU_PCI_BRIDGES: u32 = 2;
pub const MAX_QEMU_PCI_BRIDGES: u32 = 5;
pub const MAX_QEMU_VCPUS: u32 = 256;
pub const MIN_QEMU_MEMORY_SIZE_MB: u32 = 64;
// Default configuration for Cloud Hypervisor (CH)
pub const DEFAULT_CH_BINARY_PATH: &str = "/usr/bin/cloud-hypervisor";
pub const DEFAULT_CH_ROOTFS_TYPE: &str = "ext4";
pub const DEFAULT_CH_CONTROL_PATH: &str = "";
pub const DEFAULT_CH_ENTROPY_SOURCE: &str = "/dev/urandom";
pub const DEFAULT_CH_GUEST_KERNEL_IMAGE: &str = "vmlinuz";
pub const DEFAULT_CH_GUEST_KERNEL_PARAMS: &str = "";
pub const DEFAULT_CH_FIRMWARE_PATH: &str = "";
pub const DEFAULT_CH_MEMORY_SIZE_MB: u32 = 128;
pub const DEFAULT_CH_MEMORY_SLOTS: u32 = 128;
pub const DEFAULT_CH_PCI_BRIDGES: u32 = 2;
pub const MAX_CH_PCI_BRIDGES: u32 = 5;
pub const MAX_CH_VCPUS: u32 = 256;
pub const MIN_CH_MEMORY_SIZE_MB: u32 = 64;

View File

@@ -0,0 +1,146 @@
// Copyright (c) 2019-2021 Alibaba Cloud
// Copyright (c) 2022-2023 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use std::io::Result;
use std::path::Path;
use std::sync::Arc;
use super::{default, register_hypervisor_plugin};
use crate::config::default::MAX_CH_VCPUS;
use crate::config::default::MIN_CH_MEMORY_SIZE_MB;
use crate::config::hypervisor::VIRTIO_BLK_MMIO;
use crate::config::{ConfigPlugin, TomlConfig};
use crate::{eother, resolve_path, validate_path};
/// Hypervisor name for CH, used to index `TomlConfig::hypervisor`.
pub const HYPERVISOR_NAME_CH: &str = "cloud-hypervisor";
/// Configuration information for CH.
#[derive(Default, Debug)]
pub struct CloudHypervisorConfig {}
impl CloudHypervisorConfig {
/// Create a new instance of `CloudHypervisorConfig`.
pub fn new() -> Self {
CloudHypervisorConfig {}
}
/// Register the CH plugin.
pub fn register(self) {
let plugin = Arc::new(self);
register_hypervisor_plugin(HYPERVISOR_NAME_CH, plugin);
}
}
impl ConfigPlugin for CloudHypervisorConfig {
fn get_max_cpus(&self) -> u32 {
MAX_CH_VCPUS
}
fn get_min_memory(&self) -> u32 {
MIN_CH_MEMORY_SIZE_MB
}
fn name(&self) -> &str {
HYPERVISOR_NAME_CH
}
/// Adjust the configuration information after loading from configuration file.
fn adjust_config(&self, conf: &mut TomlConfig) -> Result<()> {
if let Some(ch) = conf.hypervisor.get_mut(HYPERVISOR_NAME_CH) {
if ch.path.is_empty() {
ch.path = default::DEFAULT_CH_BINARY_PATH.to_string();
}
resolve_path!(ch.path, "CH binary path `{}` is invalid: {}")?;
if ch.ctlpath.is_empty() {
ch.ctlpath = default::DEFAULT_CH_CONTROL_PATH.to_string();
}
resolve_path!(ch.ctlpath, "CH ctlpath `{}` is invalid: {}")?;
if ch.boot_info.kernel.is_empty() {
ch.boot_info.kernel = default::DEFAULT_CH_GUEST_KERNEL_IMAGE.to_string();
}
if ch.boot_info.kernel_params.is_empty() {
ch.boot_info.kernel_params = default::DEFAULT_CH_GUEST_KERNEL_PARAMS.to_string();
}
if ch.boot_info.firmware.is_empty() {
ch.boot_info.firmware = default::DEFAULT_CH_FIRMWARE_PATH.to_string();
}
if ch.device_info.default_bridges == 0 {
ch.device_info.default_bridges = default::DEFAULT_CH_PCI_BRIDGES;
}
if ch.machine_info.entropy_source.is_empty() {
ch.machine_info.entropy_source = default::DEFAULT_CH_ENTROPY_SOURCE.to_string();
}
if ch.memory_info.default_memory == 0 {
ch.memory_info.default_memory = default::DEFAULT_CH_MEMORY_SIZE_MB;
}
if ch.memory_info.memory_slots == 0 {
ch.memory_info.memory_slots = default::DEFAULT_CH_MEMORY_SLOTS;
}
}
Ok(())
}
/// Validate the configuration information.
fn validate(&self, conf: &TomlConfig) -> Result<()> {
if let Some(ch) = conf.hypervisor.get(HYPERVISOR_NAME_CH) {
validate_path!(ch.path, "CH binary path `{}` is invalid: {}")?;
validate_path!(ch.ctlpath, "CH control path `{}` is invalid: {}")?;
if !ch.jailer_path.is_empty() {
return Err(eother!("Path for CH jailer should be empty"));
}
if !ch.valid_jailer_paths.is_empty() {
return Err(eother!("Valid CH jailer path list should be empty"));
}
if !ch.blockdev_info.disable_block_device_use
&& ch.blockdev_info.block_device_driver == VIRTIO_BLK_MMIO
{
return Err(eother!("CH doesn't support virtio-blk-mmio"));
}
if ch.boot_info.kernel.is_empty() {
return Err(eother!("Guest kernel image for CH is empty"));
}
if ch.boot_info.image.is_empty() && ch.boot_info.initrd.is_empty() {
return Err(eother!("Both guest boot image and initrd for CH are empty"));
}
if (ch.cpu_info.default_vcpus > 0
&& ch.cpu_info.default_vcpus as u32 > default::MAX_CH_VCPUS)
|| ch.cpu_info.default_maxvcpus > default::MAX_CH_VCPUS
{
return Err(eother!(
"CH hypervisor cannot support {} vCPUs",
ch.cpu_info.default_maxvcpus
));
}
if ch.device_info.default_bridges > default::MAX_CH_PCI_BRIDGES {
return Err(eother!(
"CH hypervisor cannot support {} PCI bridges",
ch.device_info.default_bridges
));
}
if ch.memory_info.default_memory < MIN_CH_MEMORY_SIZE_MB {
return Err(eother!(
"CH hypervisor has minimal memory limitation {}",
MIN_CH_MEMORY_SIZE_MB
));
}
}
Ok(())
}
}

View File

@@ -40,6 +40,9 @@ pub use self::dragonball::{DragonballConfig, HYPERVISOR_NAME_DRAGONBALL};
mod qemu;
pub use self::qemu::{QemuConfig, HYPERVISOR_NAME_QEMU};
mod ch;
pub use self::ch::{CloudHypervisorConfig, HYPERVISOR_NAME_CH};
const VIRTIO_BLK: &str = "virtio-blk";
const VIRTIO_BLK_MMIO: &str = "virtio-mmio";
const VIRTIO_BLK_CCW: &str = "virtio-blk-ccw";
@@ -976,6 +979,13 @@ pub struct Hypervisor {
#[serde(default, flatten)]
pub shared_fs: SharedFsInfo,
/// A sandbox annotation used to specify prefetch_files.list host path container image
/// being used, and runtime will pass it to Hypervisor to search for corresponding
/// prefetch list file:
/// prefetch_list_path = /path/to/<uid>/xyz.com/fedora:36/prefetch_file.list
#[serde(default)]
pub prefetch_list_path: String,
/// Vendor customized runtime configuration.
#[serde(default, flatten)]
pub vendor: HypervisorVendor,
@@ -1019,6 +1029,10 @@ impl ConfigOps for Hypervisor {
hv.network_info.adjust_config()?;
hv.security_info.adjust_config()?;
hv.shared_fs.adjust_config()?;
resolve_path!(
hv.prefetch_list_path,
"prefetch_list_path `{}` is invalid: {}"
)?;
} else {
return Err(eother!("Can not find plugin for hypervisor {}", hypervisor));
}
@@ -1053,6 +1067,10 @@ impl ConfigOps for Hypervisor {
"Hypervisor control executable `{}` is invalid: {}"
)?;
validate_path!(hv.jailer_path, "Hypervisor jailer path `{}` is invalid: {}")?;
validate_path!(
hv.prefetch_list_path,
"prefetch_files.list path `{}` is invalid: {}"
)?;
} else {
return Err(eother!("Can not find plugin for hypervisor {}", hypervisor));
}

View File

@@ -25,8 +25,8 @@ pub mod hypervisor;
pub use self::agent::Agent;
use self::default::DEFAULT_AGENT_DBG_CONSOLE_PORT;
pub use self::hypervisor::{
BootInfo, DragonballConfig, Hypervisor, QemuConfig, HYPERVISOR_NAME_DRAGONBALL,
HYPERVISOR_NAME_QEMU,
BootInfo, CloudHypervisorConfig, DragonballConfig, Hypervisor, QemuConfig,
HYPERVISOR_NAME_DRAGONBALL, HYPERVISOR_NAME_QEMU,
};
mod runtime;
@@ -127,6 +127,14 @@ impl TomlConfig {
result
}
/// Load raw Kata configuration information from default configuration file.
///
/// Configuration file is probed according to the default configuration file list
/// default::DEFAULT_RUNTIME_CONFIGURATIONS.
pub fn load_from_default() -> Result<(TomlConfig, PathBuf)> {
Self::load_raw_from_file("")
}
/// Load raw Kata configuration information from configuration files.
///
/// If `config_file` is valid, it will used, otherwise a built-in default path list will be
@@ -196,7 +204,7 @@ impl TomlConfig {
}
/// Probe configuration file according to the default configuration file list.
fn get_default_config_file() -> Result<PathBuf> {
pub fn get_default_config_file() -> Result<PathBuf> {
for f in default::DEFAULT_RUNTIME_CONFIGURATIONS.iter() {
if let Ok(path) = fs::canonicalize(f) {
return Ok(path);

View File

@@ -103,8 +103,9 @@ pub struct Runtime {
pub enable_pprof: bool,
/// If enabled, static resource management will calculate the vcpu and memory for the sandbox/container
/// And pod configured this will not be able to further update its CPU/Memory resource
#[serde(default)]
pub static_resource_mgmt: bool,
pub static_sandbox_resource_mgmt: bool,
/// Determines whether container seccomp profiles are passed to the virtual machine and
/// applied by the kata agent. If set to true, seccomp is not applied within the guest.
@@ -129,6 +130,12 @@ pub struct Runtime {
/// Vendor customized runtime configuration.
#[serde(default, flatten)]
pub vendor: RuntimeVendor,
/// If keep_abnormal is enabled, it means that 1) if the runtime exits abnormally, the cleanup process
/// will be skipped, and 2) the runtime will not exit even if the health check fails.
/// This option is typically used to retain abnormal information for debugging.
#[serde(default)]
pub keep_abnormal: bool,
}
impl ConfigOps for Runtime {

View File

@@ -192,6 +192,24 @@ pub struct Hook {
pub struct Hooks {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub prestart: Vec<Hook>,
#[serde(
rename = "createRuntime",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub create_runtime: Vec<Hook>,
#[serde(
rename = "createContainer",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub create_container: Vec<Hook>,
#[serde(
rename = "startContainer",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub start_container: Vec<Hook>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub poststart: Vec<Hook>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -831,6 +849,8 @@ pub struct State {
#[cfg(test)]
mod tests {
use std::vec;
use super::*;
#[test]
@@ -1021,6 +1041,11 @@ mod tests {
"path": "/usr/bin/setup-network"
}
],
"createRuntime": [
{
"path": "/usr/local/bin/nerdctl"
}
],
"poststart": [
{
"path": "/usr/bin/notify-start",
@@ -1389,6 +1414,12 @@ mod tests {
timeout: None,
},
],
create_runtime: vec![crate::Hook {
path: "/usr/local/bin/nerdctl".to_string(),
args: vec![],
env: vec![],
timeout: None,
}],
poststart: vec![crate::Hook {
path: "/usr/bin/notify-start".to_string(),
args: vec![],
@@ -1401,6 +1432,7 @@ mod tests {
env: vec![],
timeout: None,
}],
..Default::default()
}),
annotations: [
("com.example.key1".to_string(), "value1".to_string()),

View File

@@ -1,11 +1,6 @@
Cargo.lock
src/agent.rs
src/agent_ttrpc.rs
src/agent_ttrpc_async.rs
src/csi.rs
src/empty.rs
src/health.rs
src/health_ttrpc.rs
src/health_ttrpc_async.rs
src/oci.rs
src/types.rs
src/*.rs
!src/lib.rs
!src/trans.rs
!src/serde_config.rs

View File

@@ -11,12 +11,13 @@ with-serde = [ "serde", "serde_json" ]
async = ["ttrpc/async", "async-trait"]
[dependencies]
ttrpc = { version = "0.6.0" }
ttrpc = { version = "0.7.1" }
async-trait = { version = "0.1.42", optional = true }
protobuf = { version = "2.27.0", features = ["with-serde"] }
protobuf = { version = "3.2.0" }
serde = { version = "1.0.130", features = ["derive"], optional = true }
serde_json = { version = "1.0.68", optional = true }
oci = { path = "../oci" }
[build-dependencies]
ttrpc-codegen = "0.2.0"
ttrpc-codegen = "0.4.2"
protobuf = { version = "3.2.0" }

View File

@@ -7,7 +7,46 @@ use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::Path;
use std::process::exit;
use ttrpc_codegen::{Codegen, Customize, ProtobufCustomize};
use protobuf::{
descriptor::field_descriptor_proto::Type,
reflect::{EnumDescriptor, FieldDescriptor, MessageDescriptor, OneofDescriptor},
};
use ttrpc_codegen::{Codegen, Customize, ProtobufCustomize, ProtobufCustomizeCallback};
struct GenSerde;
impl ProtobufCustomizeCallback for GenSerde {
fn message(&self, _message: &MessageDescriptor) -> ProtobufCustomize {
ProtobufCustomize::default().before("#[cfg_attr(feature = \"with-serde\", derive(::serde::Serialize, ::serde::Deserialize))]")
}
fn enumeration(&self, _enum_type: &EnumDescriptor) -> ProtobufCustomize {
ProtobufCustomize::default().before("#[cfg_attr(feature = \"with-serde\", derive(::serde::Serialize, ::serde::Deserialize))]")
}
fn oneof(&self, _oneof: &OneofDescriptor) -> ProtobufCustomize {
ProtobufCustomize::default().before("#[cfg_attr(feature = \"with-serde\", derive(::serde::Serialize, ::serde::Deserialize))]")
}
fn field(&self, field: &FieldDescriptor) -> ProtobufCustomize {
if field.proto().type_() == Type::TYPE_ENUM {
ProtobufCustomize::default().before(
"#[cfg_attr(feature = \"with-serde\", serde(serialize_with = \"crate::serialize_enum_or_unknown\", deserialize_with = \"crate::deserialize_enum_or_unknown\"))]",
)
} else if field.proto().type_() == Type::TYPE_MESSAGE && field.is_singular() {
ProtobufCustomize::default().before(
"#[cfg_attr(feature = \"with-serde\", serde(serialize_with = \"crate::serialize_message_field\", deserialize_with = \"crate::deserialize_message_field\"))]",
)
} else {
ProtobufCustomize::default()
}
}
fn special_field(&self, _message: &MessageDescriptor, _field: &str) -> ProtobufCustomize {
ProtobufCustomize::default().before("#[cfg_attr(feature = \"with-serde\", serde(skip))]")
}
}
fn replace_text_in_file(file_name: &str, from: &str, to: &str) -> Result<(), std::io::Error> {
let mut src = File::open(file_name)?;
@@ -103,10 +142,10 @@ fn codegen(path: &str, protos: &[&str], async_all: bool) -> Result<(), std::io::
..Default::default()
};
let protobuf_options = ProtobufCustomize {
serde_derive: Some(true),
..Default::default()
};
let protobuf_options = ProtobufCustomize::default()
.gen_mod_rs(false)
.generate_getter(true)
.generate_accessors(true);
let out_dir = Path::new("src");
@@ -117,6 +156,7 @@ fn codegen(path: &str, protos: &[&str], async_all: bool) -> Result<(), std::io::
.customize(ttrpc_options)
.rust_protobuf()
.rust_protobuf_customize(protobuf_options)
.rust_protobuf_customize_callback(GenSerde)
.run()?;
let autogen_comment = format!("\n//! Generated by {:?} ({:?})", file!(), module_path!());
@@ -147,6 +187,7 @@ fn real_main() -> Result<(), std::io::Error> {
"src",
&[
"protos/google/protobuf/empty.proto",
"protos/gogo/protobuf/gogoproto/gogo.proto",
"protos/oci.proto",
"protos/types.proto",
"protos/csi.proto",

View File

@@ -34,9 +34,11 @@ service AgentService {
rpc SignalProcess(SignalProcessRequest) returns (google.protobuf.Empty);
rpc WaitProcess(WaitProcessRequest) returns (WaitProcessResponse); // wait & reap like waitpid(2)
rpc UpdateContainer(UpdateContainerRequest) returns (google.protobuf.Empty);
rpc UpdateEphemeralMounts(UpdateEphemeralMountsRequest) returns (google.protobuf.Empty);
rpc StatsContainer(StatsContainerRequest) returns (StatsContainerResponse);
rpc PauseContainer(PauseContainerRequest) returns (google.protobuf.Empty);
rpc ResumeContainer(ResumeContainerRequest) returns (google.protobuf.Empty);
rpc RemoveStaleVirtiofsShareMounts(RemoveStaleVirtiofsShareMountsRequest) returns (google.protobuf.Empty);
// stdio
rpc WriteStdin(WriteStreamRequest) returns (WriteStreamResponse);
@@ -300,6 +302,8 @@ message CreateSandboxRequest {
message DestroySandboxRequest {
}
message RemoveStaleVirtiofsShareMountsRequest {}
message Interfaces {
repeated types.Interface Interfaces = 1;
}
@@ -316,6 +320,10 @@ message UpdateRoutesRequest {
Routes routes = 1;
}
message UpdateEphemeralMountsRequest {
repeated Storage storages = 1;
}
message ListInterfacesRequest {
}

View File

@@ -166,6 +166,15 @@ message Hooks {
// Poststop is a list of hooks to be run after the container process exits.
repeated Hook Poststop = 3 [(gogoproto.nullable) = false];
// Createruntime is a list of hooks to be run during the creation of runtime(sandbox).
repeated Hook CreateRuntime = 4 [(gogoproto.nullable) = false];
// CreateContainer is a list of hooks to be run after VM is started, and before container is created.
repeated Hook CreateContainer = 5 [(gogoproto.nullable) = false];
// StartContainer is a list of hooks to be run after container is created, but before it is started.
repeated Hook StartContainer = 6 [(gogoproto.nullable) = false];
}
message Hook {

View File

@@ -11,10 +11,19 @@ pub mod agent_ttrpc;
pub mod agent_ttrpc_async;
pub mod csi;
pub mod empty;
mod gogo;
pub mod health;
pub mod health_ttrpc;
#[cfg(feature = "async")]
pub mod health_ttrpc_async;
pub mod oci;
#[cfg(feature = "with-serde")]
mod serde_config;
pub mod trans;
pub mod types;
#[cfg(feature = "with-serde")]
pub use serde_config::{
deserialize_enum_or_unknown, deserialize_message_field, serialize_enum_or_unknown,
serialize_message_field,
};

View File

@@ -0,0 +1,68 @@
// Copyright (c) 2023 Ant Group
//
// SPDX-License-Identifier: Apache-2.0
//
use protobuf::{EnumOrUnknown, MessageField};
use serde::{Deserialize, Serialize};
#[cfg(feature = "with-serde")]
pub fn serialize_enum_or_unknown<E: protobuf::EnumFull, S: serde::Serializer>(
e: &protobuf::EnumOrUnknown<E>,
s: S,
) -> Result<S::Ok, S::Error> {
e.value().serialize(s)
}
pub fn serialize_message_field<E: Serialize, S: serde::Serializer>(
e: &protobuf::MessageField<E>,
s: S,
) -> Result<S::Ok, S::Error> {
if e.is_some() {
e.as_ref().unwrap().serialize(s)
} else {
s.serialize_unit()
}
}
pub fn deserialize_enum_or_unknown<'de, E: Deserialize<'de>, D: serde::Deserializer<'de>>(
d: D,
) -> Result<protobuf::EnumOrUnknown<E>, D::Error> {
i32::deserialize(d).map(EnumOrUnknown::from_i32)
}
pub fn deserialize_message_field<'de, E: Deserialize<'de>, D: serde::Deserializer<'de>>(
d: D,
) -> Result<protobuf::MessageField<E>, D::Error> {
Option::deserialize(d).map(MessageField::from_option)
}
#[cfg(test)]
mod tests {
use crate::agent::{ExecProcessRequest, StringUser};
use crate::health::{health_check_response::ServingStatus, HealthCheckResponse};
#[test]
fn test_serde_for_enum_or_unknown() {
let mut hc = HealthCheckResponse::new();
hc.set_status(ServingStatus::SERVING);
let json = serde_json::to_string(&hc).unwrap();
let from_json: HealthCheckResponse = serde_json::from_str(&json).unwrap();
assert_eq!(from_json, hc);
}
#[test]
fn test_serde_for_message_field() {
let mut epr = ExecProcessRequest::new();
let mut str_user = StringUser::new();
str_user.uid = "Someone's id".to_string();
epr.set_string_user(str_user);
let json = serde_json::to_string(&epr).unwrap();
let from_json: ExecProcessRequest = serde_json::from_str(&json).unwrap();
assert_eq!(from_json, epr);
}
}

View File

@@ -15,19 +15,19 @@ use oci::{
};
// translate from interface to ttprc tools
fn from_option<F: Sized, T: From<F>>(from: Option<F>) -> ::protobuf::SingularPtrField<T> {
fn from_option<F: Sized, T: From<F>>(from: Option<F>) -> protobuf::MessageField<T> {
match from {
Some(f) => ::protobuf::SingularPtrField::from_option(Some(T::from(f))),
None => ::protobuf::SingularPtrField::none(),
Some(f) => protobuf::MessageField::from_option(Some(f.into())),
None => protobuf::MessageField::none(),
}
}
fn from_vec<F: Sized, T: From<F>>(from: Vec<F>) -> ::protobuf::RepeatedField<T> {
fn from_vec<F: Sized, T: From<F>>(from: Vec<F>) -> Vec<T> {
let mut to: Vec<T> = vec![];
for data in from {
to.push(T::from(data));
to.push(data.into());
}
::protobuf::RepeatedField::from_vec(to)
to
}
impl From<oci::Box> for crate::oci::Box {
@@ -35,8 +35,7 @@ impl From<oci::Box> for crate::oci::Box {
crate::oci::Box {
Height: from.height,
Width: from.width,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -48,8 +47,7 @@ impl From<oci::User> for crate::oci::User {
GID: from.gid,
AdditionalGids: from.additional_gids,
Username: from.username,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -57,13 +55,12 @@ impl From<oci::User> for crate::oci::User {
impl From<oci::LinuxCapabilities> for crate::oci::LinuxCapabilities {
fn from(from: LinuxCapabilities) -> Self {
crate::oci::LinuxCapabilities {
Bounding: from_vec(from.bounding),
Effective: from_vec(from.effective),
Inheritable: from_vec(from.inheritable),
Permitted: from_vec(from.permitted),
Ambient: from_vec(from.ambient),
unknown_fields: Default::default(),
cached_size: Default::default(),
Bounding: from.bounding,
Effective: from.effective,
Inheritable: from.inheritable,
Permitted: from.permitted,
Ambient: from.ambient,
..Default::default()
}
}
}
@@ -74,8 +71,7 @@ impl From<oci::PosixRlimit> for crate::oci::POSIXRlimit {
Type: from.r#type,
Hard: from.hard,
Soft: from.soft,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -86,8 +82,8 @@ impl From<oci::Process> for crate::oci::Process {
Terminal: from.terminal,
ConsoleSize: from_option(from.console_size),
User: from_option(Some(from.user)),
Args: from_vec(from.args),
Env: from_vec(from.env),
Args: from.args,
Env: from.env,
Cwd: from.cwd,
Capabilities: from_option(from.capabilities),
Rlimits: from_vec(from.rlimits),
@@ -95,8 +91,7 @@ impl From<oci::Process> for crate::oci::Process {
ApparmorProfile: from.apparmor_profile,
OOMScoreAdj: from.oom_score_adj.map_or(0, |t| t as i64),
SelinuxLabel: from.selinux_label,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -109,8 +104,7 @@ impl From<oci::LinuxDeviceCgroup> for crate::oci::LinuxDeviceCgroup {
Major: from.major.map_or(0, |t| t),
Minor: from.minor.map_or(0, |t| t),
Access: from.access,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -125,8 +119,7 @@ impl From<oci::LinuxMemory> for crate::oci::LinuxMemory {
KernelTCP: from.kernel_tcp.map_or(0, |t| t),
Swappiness: from.swappiness.map_or(0, |t| t),
DisableOOMKiller: from.disable_oom_killer.map_or(false, |t| t),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -141,8 +134,7 @@ impl From<oci::LinuxCpu> for crate::oci::LinuxCPU {
RealtimePeriod: from.realtime_period.map_or(0, |t| t),
Cpus: from.cpus,
Mems: from.mems,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -151,8 +143,7 @@ impl From<oci::LinuxPids> for crate::oci::LinuxPids {
fn from(from: LinuxPids) -> Self {
crate::oci::LinuxPids {
Limit: from.limit,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -165,8 +156,7 @@ impl From<oci::LinuxWeightDevice> for crate::oci::LinuxWeightDevice {
Minor: 0,
Weight: from.weight.map_or(0, |t| t as u32),
LeafWeight: from.leaf_weight.map_or(0, |t| t as u32),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -178,8 +168,7 @@ impl From<oci::LinuxThrottleDevice> for crate::oci::LinuxThrottleDevice {
Major: 0,
Minor: 0,
Rate: from.rate,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -194,8 +183,7 @@ impl From<oci::LinuxBlockIo> for crate::oci::LinuxBlockIO {
ThrottleWriteBpsDevice: from_vec(from.throttle_write_bps_device),
ThrottleReadIOPSDevice: from_vec(from.throttle_read_iops_device),
ThrottleWriteIOPSDevice: from_vec(from.throttle_write_iops_device),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -205,8 +193,7 @@ impl From<oci::LinuxHugepageLimit> for crate::oci::LinuxHugepageLimit {
crate::oci::LinuxHugepageLimit {
Pagesize: from.page_size,
Limit: from.limit,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -216,8 +203,7 @@ impl From<oci::LinuxInterfacePriority> for crate::oci::LinuxInterfacePriority {
crate::oci::LinuxInterfacePriority {
Name: from.name,
Priority: from.priority,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -227,8 +213,7 @@ impl From<oci::LinuxNetwork> for crate::oci::LinuxNetwork {
crate::oci::LinuxNetwork {
ClassID: from.class_id.map_or(0, |t| t),
Priorities: from_vec(from.priorities),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -243,8 +228,7 @@ impl From<oci::LinuxResources> for crate::oci::LinuxResources {
BlockIO: from_option(from.block_io),
HugepageLimits: from_vec(from.hugepage_limits),
Network: from_option(from.network),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -254,8 +238,7 @@ impl From<oci::Root> for crate::oci::Root {
crate::oci::Root {
Path: from.path,
Readonly: from.readonly,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -265,10 +248,9 @@ impl From<oci::Mount> for crate::oci::Mount {
crate::oci::Mount {
destination: from.destination,
source: from.source,
field_type: from.r#type,
options: from_vec(from.options),
unknown_fields: Default::default(),
cached_size: Default::default(),
type_: from.r#type,
options: from.options,
..Default::default()
}
}
}
@@ -281,11 +263,10 @@ impl From<oci::Hook> for crate::oci::Hook {
}
crate::oci::Hook {
Path: from.path,
Args: from_vec(from.args),
Env: from_vec(from.env),
Args: from.args,
Env: from.env,
Timeout: timeout,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -294,10 +275,12 @@ impl From<oci::Hooks> for crate::oci::Hooks {
fn from(from: Hooks) -> Self {
crate::oci::Hooks {
Prestart: from_vec(from.prestart),
CreateRuntime: from_vec(from.create_runtime),
CreateContainer: from_vec(from.create_container),
StartContainer: from_vec(from.start_container),
Poststart: from_vec(from.poststart),
Poststop: from_vec(from.poststop),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -308,8 +291,7 @@ impl From<oci::LinuxIdMapping> for crate::oci::LinuxIDMapping {
HostID: from.host_id,
ContainerID: from.container_id,
Size: from.size,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -319,8 +301,7 @@ impl From<oci::LinuxNamespace> for crate::oci::LinuxNamespace {
crate::oci::LinuxNamespace {
Type: from.r#type,
Path: from.path,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -335,8 +316,7 @@ impl From<oci::LinuxDevice> for crate::oci::LinuxDevice {
FileMode: from.file_mode.map_or(0, |v| v),
UID: from.uid.map_or(0, |v| v),
GID: from.gid.map_or(0, |v| v),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -348,8 +328,7 @@ impl From<oci::LinuxSeccompArg> for crate::oci::LinuxSeccompArg {
Value: from.value,
ValueTwo: from.value_two,
Op: from.op,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -357,14 +336,13 @@ impl From<oci::LinuxSeccompArg> for crate::oci::LinuxSeccompArg {
impl From<oci::LinuxSyscall> for crate::oci::LinuxSyscall {
fn from(from: LinuxSyscall) -> Self {
crate::oci::LinuxSyscall {
Names: from_vec(from.names),
Names: from.names,
Action: from.action,
Args: from_vec(from.args),
ErrnoRet: Some(crate::oci::LinuxSyscall_oneof_ErrnoRet::errnoret(
ErrnoRet: Some(crate::oci::linux_syscall::ErrnoRet::Errnoret(
from.errno_ret,
)),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -373,11 +351,10 @@ impl From<oci::LinuxSeccomp> for crate::oci::LinuxSeccomp {
fn from(from: LinuxSeccomp) -> Self {
crate::oci::LinuxSeccomp {
DefaultAction: from.default_action,
Architectures: from_vec(from.architectures),
Architectures: from.architectures,
Syscalls: from_vec(from.syscalls),
Flags: from_vec(from.flags),
unknown_fields: Default::default(),
cached_size: Default::default(),
Flags: from.flags,
..Default::default()
}
}
}
@@ -386,8 +363,7 @@ impl From<oci::LinuxIntelRdt> for crate::oci::LinuxIntelRdt {
fn from(from: LinuxIntelRdt) -> Self {
crate::oci::LinuxIntelRdt {
L3CacheSchema: from.l3_cache_schema,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -404,12 +380,11 @@ impl From<oci::Linux> for crate::oci::Linux {
Devices: from_vec(from.devices),
Seccomp: from_option(from.seccomp),
RootfsPropagation: from.rootfs_propagation,
MaskedPaths: from_vec(from.masked_paths),
ReadonlyPaths: from_vec(from.readonly_paths),
MaskedPaths: from.masked_paths,
ReadonlyPaths: from.readonly_paths,
MountLabel: from.mount_label,
IntelRdt: from_option(from.intel_rdt),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -427,8 +402,7 @@ impl From<oci::Spec> for crate::oci::Spec {
Linux: from_option(from.linux),
Solaris: Default::default(),
Windows: Default::default(),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -446,7 +420,7 @@ impl From<crate::oci::Mount> for oci::Mount {
fn from(mut from: crate::oci::Mount) -> Self {
let options = from.take_options().to_vec();
Self {
r#type: from.take_field_type(),
r#type: from.take_type_(),
destination: from.take_destination(),
source: from.take_source(),
options,
@@ -457,9 +431,9 @@ impl From<crate::oci::Mount> for oci::Mount {
impl From<crate::oci::LinuxIDMapping> for oci::LinuxIdMapping {
fn from(from: crate::oci::LinuxIDMapping) -> Self {
LinuxIdMapping {
container_id: from.get_ContainerID(),
host_id: from.get_HostID(),
size: from.get_Size(),
container_id: from.ContainerID(),
host_id: from.HostID(),
size: from.Size(),
}
}
}
@@ -467,17 +441,17 @@ impl From<crate::oci::LinuxIDMapping> for oci::LinuxIdMapping {
impl From<crate::oci::LinuxDeviceCgroup> for oci::LinuxDeviceCgroup {
fn from(mut from: crate::oci::LinuxDeviceCgroup) -> Self {
let mut major = None;
if from.get_Major() > 0 {
major = Some(from.get_Major());
if from.Major() > 0 {
major = Some(from.Major());
}
let mut minor = None;
if from.get_Minor() > 0 {
minor = Some(from.get_Minor())
if from.Minor() > 0 {
minor = Some(from.Minor())
}
oci::LinuxDeviceCgroup {
allow: from.get_Allow(),
allow: from.Allow(),
r#type: from.take_Type(),
major,
minor,
@@ -489,36 +463,36 @@ impl From<crate::oci::LinuxDeviceCgroup> for oci::LinuxDeviceCgroup {
impl From<crate::oci::LinuxMemory> for oci::LinuxMemory {
fn from(from: crate::oci::LinuxMemory) -> Self {
let mut limit = None;
if from.get_Limit() > 0 {
limit = Some(from.get_Limit());
if from.Limit() > 0 {
limit = Some(from.Limit());
}
let mut reservation = None;
if from.get_Reservation() > 0 {
reservation = Some(from.get_Reservation());
if from.Reservation() > 0 {
reservation = Some(from.Reservation());
}
let mut swap = None;
if from.get_Swap() > 0 {
swap = Some(from.get_Swap());
if from.Swap() > 0 {
swap = Some(from.Swap());
}
let mut kernel = None;
if from.get_Kernel() > 0 {
kernel = Some(from.get_Kernel());
if from.Kernel() > 0 {
kernel = Some(from.Kernel());
}
let mut kernel_tcp = None;
if from.get_KernelTCP() > 0 {
kernel_tcp = Some(from.get_KernelTCP());
if from.KernelTCP() > 0 {
kernel_tcp = Some(from.KernelTCP());
}
let mut swappiness = None;
if from.get_Swappiness() > 0 {
swappiness = Some(from.get_Swappiness());
if from.Swappiness() > 0 {
swappiness = Some(from.Swappiness());
}
let disable_oom_killer = Some(from.get_DisableOOMKiller());
let disable_oom_killer = Some(from.DisableOOMKiller());
oci::LinuxMemory {
limit,
@@ -535,28 +509,28 @@ impl From<crate::oci::LinuxMemory> for oci::LinuxMemory {
impl From<crate::oci::LinuxCPU> for oci::LinuxCpu {
fn from(mut from: crate::oci::LinuxCPU) -> Self {
let mut shares = None;
if from.get_Shares() > 0 {
shares = Some(from.get_Shares());
if from.Shares() > 0 {
shares = Some(from.Shares());
}
let mut quota = None;
if from.get_Quota() > 0 {
quota = Some(from.get_Quota());
if from.Quota() > 0 {
quota = Some(from.Quota());
}
let mut period = None;
if from.get_Period() > 0 {
period = Some(from.get_Period());
if from.Period() > 0 {
period = Some(from.Period());
}
let mut realtime_runtime = None;
if from.get_RealtimeRuntime() > 0 {
realtime_runtime = Some(from.get_RealtimeRuntime());
if from.RealtimeRuntime() > 0 {
realtime_runtime = Some(from.RealtimeRuntime());
}
let mut realtime_period = None;
if from.get_RealtimePeriod() > 0 {
realtime_period = Some(from.get_RealtimePeriod());
if from.RealtimePeriod() > 0 {
realtime_period = Some(from.RealtimePeriod());
}
let cpus = from.take_Cpus();
@@ -577,7 +551,7 @@ impl From<crate::oci::LinuxCPU> for oci::LinuxCpu {
impl From<crate::oci::LinuxPids> for oci::LinuxPids {
fn from(from: crate::oci::LinuxPids) -> Self {
oci::LinuxPids {
limit: from.get_Limit(),
limit: from.Limit(),
}
}
}
@@ -585,35 +559,35 @@ impl From<crate::oci::LinuxPids> for oci::LinuxPids {
impl From<crate::oci::LinuxBlockIO> for oci::LinuxBlockIo {
fn from(from: crate::oci::LinuxBlockIO) -> Self {
let mut weight = None;
if from.get_Weight() > 0 {
weight = Some(from.get_Weight() as u16);
if from.Weight() > 0 {
weight = Some(from.Weight() as u16);
}
let mut leaf_weight = None;
if from.get_LeafWeight() > 0 {
leaf_weight = Some(from.get_LeafWeight() as u16);
if from.LeafWeight() > 0 {
leaf_weight = Some(from.LeafWeight() as u16);
}
let mut weight_device = Vec::new();
for wd in from.get_WeightDevice() {
for wd in from.WeightDevice() {
weight_device.push(wd.clone().into());
}
let mut throttle_read_bps_device = Vec::new();
for td in from.get_ThrottleReadBpsDevice() {
for td in from.ThrottleReadBpsDevice() {
throttle_read_bps_device.push(td.clone().into());
}
let mut throttle_write_bps_device = Vec::new();
for td in from.get_ThrottleWriteBpsDevice() {
for td in from.ThrottleWriteBpsDevice() {
throttle_write_bps_device.push(td.clone().into());
}
let mut throttle_read_iops_device = Vec::new();
for td in from.get_ThrottleReadIOPSDevice() {
for td in from.ThrottleReadIOPSDevice() {
throttle_read_iops_device.push(td.clone().into());
}
let mut throttle_write_iops_device = Vec::new();
for td in from.get_ThrottleWriteIOPSDevice() {
for td in from.ThrottleWriteIOPSDevice() {
throttle_write_iops_device.push(td.clone().into());
}
@@ -658,7 +632,7 @@ impl From<crate::oci::LinuxInterfacePriority> for oci::LinuxInterfacePriority {
fn from(mut from: crate::oci::LinuxInterfacePriority) -> Self {
oci::LinuxInterfacePriority {
name: from.take_Name(),
priority: from.get_Priority(),
priority: from.Priority(),
}
}
}
@@ -666,11 +640,11 @@ impl From<crate::oci::LinuxInterfacePriority> for oci::LinuxInterfacePriority {
impl From<crate::oci::LinuxNetwork> for oci::LinuxNetwork {
fn from(mut from: crate::oci::LinuxNetwork) -> Self {
let mut class_id = None;
if from.get_ClassID() > 0 {
class_id = Some(from.get_ClassID());
if from.ClassID() > 0 {
class_id = Some(from.ClassID());
}
let mut priorities = Vec::new();
for p in from.take_Priorities().to_vec() {
for p in from.take_Priorities() {
priorities.push(p.into())
}
@@ -685,7 +659,7 @@ impl From<crate::oci::LinuxHugepageLimit> for oci::LinuxHugepageLimit {
fn from(mut from: crate::oci::LinuxHugepageLimit) -> Self {
oci::LinuxHugepageLimit {
page_size: from.take_Pagesize(),
limit: from.get_Limit(),
limit: from.Limit(),
}
}
}
@@ -693,7 +667,7 @@ impl From<crate::oci::LinuxHugepageLimit> for oci::LinuxHugepageLimit {
impl From<crate::oci::LinuxResources> for oci::LinuxResources {
fn from(mut from: crate::oci::LinuxResources) -> Self {
let mut devices = Vec::new();
for d in from.take_Devices().to_vec() {
for d in from.take_Devices() {
devices.push(d.into());
}
@@ -709,16 +683,16 @@ impl From<crate::oci::LinuxResources> for oci::LinuxResources {
let mut pids = None;
if from.has_Pids() {
pids = Some(from.get_Pids().clone().into())
pids = Some(from.Pids().clone().into())
}
let mut block_io = None;
if from.has_BlockIO() {
block_io = Some(from.get_BlockIO().clone().into());
block_io = Some(from.BlockIO().clone().into());
}
let mut hugepage_limits = Vec::new();
for hl in from.get_HugepageLimits() {
for hl in from.HugepageLimits() {
hugepage_limits.push(hl.clone().into());
}
@@ -747,11 +721,11 @@ impl From<crate::oci::LinuxDevice> for oci::LinuxDevice {
oci::LinuxDevice {
path: from.take_Path(),
r#type: from.take_Type(),
major: from.get_Major(),
minor: from.get_Minor(),
file_mode: Some(from.get_FileMode()),
uid: Some(from.get_UID()),
gid: Some(from.get_GID()),
major: from.Major(),
minor: from.Minor(),
file_mode: Some(from.FileMode()),
uid: Some(from.UID()),
gid: Some(from.GID()),
}
}
}
@@ -759,9 +733,9 @@ impl From<crate::oci::LinuxDevice> for oci::LinuxDevice {
impl From<crate::oci::LinuxSeccompArg> for oci::LinuxSeccompArg {
fn from(mut from: crate::oci::LinuxSeccompArg) -> Self {
oci::LinuxSeccompArg {
index: from.get_Index() as u32,
value: from.get_Value(),
value_two: from.get_ValueTwo(),
index: from.Index() as u32,
value: from.Value(),
value_two: from.ValueTwo(),
op: from.take_Op(),
}
}
@@ -770,14 +744,14 @@ impl From<crate::oci::LinuxSeccompArg> for oci::LinuxSeccompArg {
impl From<crate::oci::LinuxSyscall> for oci::LinuxSyscall {
fn from(mut from: crate::oci::LinuxSyscall) -> Self {
let mut args = Vec::new();
for ag in from.take_Args().to_vec() {
for ag in from.take_Args() {
args.push(ag.into());
}
oci::LinuxSyscall {
names: from.take_Names().to_vec(),
action: from.take_Action(),
args,
errno_ret: from.get_errnoret(),
errno_ret: from.errnoret(),
}
}
}
@@ -785,7 +759,7 @@ impl From<crate::oci::LinuxSyscall> for oci::LinuxSyscall {
impl From<crate::oci::LinuxSeccomp> for oci::LinuxSeccomp {
fn from(mut from: crate::oci::LinuxSeccomp) -> Self {
let mut syscalls = Vec::new();
for s in from.take_Syscalls().to_vec() {
for s in from.take_Syscalls() {
syscalls.push(s.into());
}
@@ -810,16 +784,16 @@ impl From<crate::oci::LinuxNamespace> for oci::LinuxNamespace {
impl From<crate::oci::Linux> for oci::Linux {
fn from(mut from: crate::oci::Linux) -> Self {
let mut uid_mappings = Vec::new();
for id_map in from.take_UIDMappings().to_vec() {
for id_map in from.take_UIDMappings() {
uid_mappings.push(id_map.into())
}
let mut gid_mappings = Vec::new();
for id_map in from.take_GIDMappings().to_vec() {
for id_map in from.take_GIDMappings() {
gid_mappings.push(id_map.into())
}
let sysctl = from.get_Sysctl().clone();
let sysctl = from.Sysctl().clone();
let mut resources = None;
if from.has_Resources() {
resources = Some(from.take_Resources().into());
@@ -827,12 +801,12 @@ impl From<crate::oci::Linux> for oci::Linux {
let cgroups_path = from.take_CgroupsPath();
let mut namespaces = Vec::new();
for ns in from.take_Namespaces().to_vec() {
for ns in from.take_Namespaces() {
namespaces.push(ns.into())
}
let mut devices = Vec::new();
for d in from.take_Devices().to_vec() {
for d in from.take_Devices() {
devices.push(d.into());
}
@@ -871,8 +845,8 @@ impl From<crate::oci::POSIXRlimit> for oci::PosixRlimit {
fn from(mut from: crate::oci::POSIXRlimit) -> Self {
oci::PosixRlimit {
r#type: from.take_Type(),
hard: from.get_Hard(),
soft: from.get_Soft(),
hard: from.Hard(),
soft: from.Soft(),
}
}
}
@@ -892,8 +866,8 @@ impl From<crate::oci::LinuxCapabilities> for oci::LinuxCapabilities {
impl From<crate::oci::User> for oci::User {
fn from(mut from: crate::oci::User) -> Self {
oci::User {
uid: from.get_UID(),
gid: from.get_GID(),
uid: from.UID(),
gid: from.GID(),
additional_gids: from.take_AdditionalGids().to_vec(),
username: from.take_Username(),
}
@@ -903,8 +877,8 @@ impl From<crate::oci::User> for oci::User {
impl From<crate::oci::Box> for oci::Box {
fn from(from: crate::oci::Box) -> Self {
oci::Box {
height: from.get_Height(),
width: from.get_Width(),
height: from.Height(),
width: from.Width(),
}
}
}
@@ -917,22 +891,22 @@ impl From<crate::oci::Process> for oci::Process {
}
let user = from.take_User().into();
let args = from.take_Args().into_vec();
let env = from.take_Env().into_vec();
let args = from.take_Args();
let env = from.take_Env();
let cwd = from.take_Cwd();
let mut capabilities = None;
if from.has_Capabilities() {
capabilities = Some(from.take_Capabilities().into());
}
let mut rlimits = Vec::new();
for rl in from.take_Rlimits().to_vec() {
for rl in from.take_Rlimits() {
rlimits.push(rl.into());
}
let no_new_privileges = from.get_NoNewPrivileges();
let no_new_privileges = from.NoNewPrivileges();
let apparmor_profile = from.take_ApparmorProfile();
let mut oom_score_adj = None;
if from.get_OOMScoreAdj() != 0 {
oom_score_adj = Some(from.get_OOMScoreAdj() as i32);
if from.OOMScoreAdj() != 0 {
oom_score_adj = Some(from.OOMScoreAdj() as i32);
}
let selinux_label = from.take_SelinuxLabel();
@@ -956,8 +930,8 @@ impl From<crate::oci::Process> for oci::Process {
impl From<crate::oci::Hook> for oci::Hook {
fn from(mut from: crate::oci::Hook) -> Self {
let mut timeout = None;
if from.get_Timeout() > 0 {
timeout = Some(from.get_Timeout() as i32);
if from.Timeout() > 0 {
timeout = Some(from.Timeout() as i32);
}
oci::Hook {
path: from.take_Path(),
@@ -970,20 +944,34 @@ impl From<crate::oci::Hook> for oci::Hook {
impl From<crate::oci::Hooks> for oci::Hooks {
fn from(mut from: crate::oci::Hooks) -> Self {
let mut prestart = Vec::new();
for hook in from.take_Prestart().to_vec() {
prestart.push(hook.into())
}
let mut poststart = Vec::new();
for hook in from.take_Poststart().to_vec() {
poststart.push(hook.into());
}
let mut poststop = Vec::new();
for hook in from.take_Poststop().to_vec() {
poststop.push(hook.into());
}
let prestart = from.take_Prestart().into_iter().map(|i| i.into()).collect();
let create_runtime = from
.take_CreateRuntime()
.into_iter()
.map(|i| i.into())
.collect();
let create_container = from
.take_CreateContainer()
.into_iter()
.map(|i| i.into())
.collect();
let start_container = from
.take_StartContainer()
.into_iter()
.map(|i| i.into())
.collect();
let poststart = from
.take_Poststart()
.into_iter()
.map(|i| i.into())
.collect();
let poststop = from.take_Poststop().into_iter().map(|i| i.into()).collect();
oci::Hooks {
prestart,
create_runtime,
create_container,
start_container,
poststart,
poststop,
}
@@ -1003,7 +991,7 @@ impl From<crate::oci::Spec> for oci::Spec {
}
let mut mounts = Vec::new();
for m in from.take_Mounts().into_vec() {
for m in from.take_Mounts() {
mounts.push(m.into())
}
@@ -1068,7 +1056,7 @@ mod tests {
#[test]
fn test_from_vec_len_0() {
let from: Vec<TestA> = vec![];
let to: ::protobuf::RepeatedField<TestB> = from_vec(from.clone());
let to: Vec<TestB> = from_vec(from.clone());
assert_eq!(from.len(), to.len());
}
@@ -1077,7 +1065,7 @@ mod tests {
let from: Vec<TestA> = vec![TestA {
from: "a".to_string(),
}];
let to: ::protobuf::RepeatedField<TestB> = from_vec(from.clone());
let to: Vec<TestB> = from_vec(from.clone());
assert_eq!(from.len(), to.len());
assert_eq!(from[0].from, to[0].to);

View File

@@ -53,7 +53,7 @@ impl MgmtClient {
.method(Method::GET)
.uri(url)
.body(Body::empty())?;
return self.send_request(req).await;
self.send_request(req).await
}
/// The HTTP Post method for client
@@ -72,7 +72,7 @@ impl MgmtClient {
.uri(url)
.header("content-type", content_type)
.body(body)?;
return self.send_request(req).await;
self.send_request(req).await
}
/// The http PUT method for client
@@ -82,7 +82,7 @@ impl MgmtClient {
.method(Method::PUT)
.uri(url)
.body(Body::from(data))?;
return self.send_request(req).await;
self.send_request(req).await
}
async fn send_request(&self, req: Request<Body>) -> Result<Response<Body>> {

1433
src/runtime-rs/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,10 @@ CONTAINERD_RUNTIME_NAME = io.containerd.kata.v2
include ../../utils.mk
ifeq ($(ARCH), ppc64le)
override ARCH = powerpc64le
endif
ARCH_DIR = arch
ARCH_FILE_SUFFIX = -options.mk
ARCH_FILE = $(ARCH_DIR)/$(ARCH)$(ARCH_FILE_SUFFIX)
@@ -203,7 +207,7 @@ ifneq (,$(DBCMD))
DEFNETWORKMODEL_DB := tcfilter
KERNELPARAMS = console=ttyS1 agent.log_vport=1025
KERNELTYPE_DB = uncompressed
KERNEL_NAME_DB = $(call MAKE_KERNEL_NAME,$(KERNELTYPE_DB))
KERNEL_NAME_DB = $(call MAKE_KERNEL_NAME_DB,$(KERNELTYPE_DB))
KERNELPATH_DB = $(KERNELDIR)/$(KERNEL_NAME_DB)
DEFSANDBOXCGROUPONLY = true
RUNTIMENAME := virt_container
@@ -371,8 +375,8 @@ endef
# Returns the name of the kernel file to use based on the provided KERNELTYPE.
# $1 : KERNELTYPE (compressed or uncompressed)
define MAKE_KERNEL_NAME
$(if $(findstring uncompressed,$1),vmlinux.container,vmlinuz.container)
define MAKE_KERNEL_NAME_DB
$(if $(findstring uncompressed,$1),vmlinux-dragonball-experimental.container,vmlinuz-dragonball-experimental.container)
endef
.DEFAULT_GOAL := default

View File

@@ -206,15 +206,22 @@ container_pipe_size=@PIPESIZE@
#debug_console_enabled = true
# Agent connection dialing timeout value in seconds
# (default: 30)
#dial_timeout = 30
# (default: 45)
dial_timeout = 45
[runtime]
# If enabled, the runtime will log additional debug messages to the
# system log
# (default: disabled)
#enable_debug = true
#
# If enabled, enabled, it means that 1) if the runtime exits abnormally,
# the cleanup process will be skipped, and 2) the runtime will not exit
# even if the health check fails.
# This option is typically used to retain abnormal information for debugging.
# (default: false)
#keep_abnormal = true
# Internetworking model
# Determines how the VM should be connected to the
# the container network interface
@@ -293,5 +300,12 @@ experimental=@DEFAULTEXPFEATURES@
# (default: false)
# enable_pprof = true
static_resource_mgmt=@DEFSTATICRESOURCEMGMT_DB@
# If enabled, the runtime will attempt to determine appropriate sandbox size (memory, CPU) before booting the virtual machine. In
# this case, the runtime will not dynamically update the amount of memory and CPU in the virtual machine. This is generally helpful
# when a hardware architecture or hypervisor solutions is utilized which does not support CPU and/or memory hotplug.
# Compatibility for determining appropriate sandbox (VM) size:
# - When running with pods, sandbox sizing information will only be available if using Kubernetes >= 1.23 and containerd >= 1.6. CRI-O
# does not yet support sandbox sizing annotations.
# - When running single containers using a tool like ctr, container sizing information will be available.
static_sandbox_resource_mgmt=@DEFSTATICRESOURCEMGMT_DB@

View File

@@ -12,12 +12,12 @@ futures = "0.1.27"
anyhow = "1.0.26"
async-trait = "0.1.48"
log = "0.4.14"
protobuf = "2.27.0"
protobuf = "3.2.0"
serde = { version = "^1.0", features = ["derive"] }
serde_json = ">=1.0.9"
slog = "2.5.2"
slog-scope = "4.4.0"
ttrpc = { version = "0.6.1" }
ttrpc = { version = "0.7.1" }
tokio = { version = "1.28.1", features = ["fs", "rt"] }
url = "2.2.2"
nix = "0.24.2"

View File

@@ -56,7 +56,7 @@ macro_rules! impl_health_service {
impl HealthService for KataAgent {
$(async fn $name(&self, req: $req) -> Result<$resp> {
let r = req.into();
let (mut client, timeout, _) = self.get_health_client().await.context("get health client")?;
let (client, timeout, _) = self.get_health_client().await.context("get health client")?;
let resp = client.$name(new_ttrpc_ctx(timeout * MILLISECOND_TO_NANOSECOND), &r).await?;
Ok(resp.into())
})*
@@ -75,7 +75,7 @@ macro_rules! impl_agent {
impl Agent for KataAgent {
$(async fn $name(&self, req: $req) -> Result<$resp> {
let r = req.into();
let (mut client, mut timeout, _) = self.get_agent_client().await.context("get client")?;
let (client, mut timeout, _) = self.get_agent_client().await.context("get client")?;
// update new timeout
if let Some(v) = $new_timeout {
@@ -115,5 +115,7 @@ impl_agent!(
copy_file | crate::CopyFileRequest | crate::Empty | None,
get_oom_event | crate::Empty | crate::OomEventResponse | Some(0),
get_ip_tables | crate::GetIPTablesRequest | crate::GetIPTablesResponse | None,
set_ip_tables | crate::SetIPTablesRequest | crate::SetIPTablesResponse | None
set_ip_tables | crate::SetIPTablesRequest | crate::SetIPTablesResponse | None,
get_volume_stats | crate::VolumeStatsRequest | crate::VolumeStatsResponse | None,
resize_volume | crate::ResizeVolumeRequest | crate::Empty | None
);

View File

@@ -8,7 +8,7 @@ use std::convert::Into;
use protocols::{
agent::{self, OOMEvent},
empty, health, types,
csi, empty, health, types,
};
use crate::{
@@ -20,39 +20,28 @@ use crate::{
GetIPTablesResponse, GuestDetailsResponse, HealthCheckResponse, HugetlbStats, IPAddress,
IPFamily, Interface, Interfaces, KernelModule, MemHotplugByProbeRequest, MemoryData,
MemoryStats, NetworkStats, OnlineCPUMemRequest, PidsStats, ReadStreamRequest,
ReadStreamResponse, RemoveContainerRequest, ReseedRandomDevRequest, Route, Routes,
SetGuestDateTimeRequest, SetIPTablesRequest, SetIPTablesResponse, SignalProcessRequest,
StatsContainerResponse, Storage, StringUser, ThrottlingData, TtyWinResizeRequest,
UpdateContainerRequest, UpdateInterfaceRequest, UpdateRoutesRequest, VersionCheckResponse,
WaitProcessRequest, WriteStreamRequest,
ReadStreamResponse, RemoveContainerRequest, ReseedRandomDevRequest, ResizeVolumeRequest,
Route, Routes, SetGuestDateTimeRequest, SetIPTablesRequest, SetIPTablesResponse,
SignalProcessRequest, StatsContainerResponse, Storage, StringUser, ThrottlingData,
TtyWinResizeRequest, UpdateContainerRequest, UpdateInterfaceRequest, UpdateRoutesRequest,
VersionCheckResponse, VolumeStatsRequest, VolumeStatsResponse, WaitProcessRequest,
WriteStreamRequest,
},
OomEventResponse, WaitProcessResponse, WriteStreamResponse,
};
fn from_vec<F: Into<T>, T: Sized>(from: Vec<F>) -> ::protobuf::RepeatedField<T> {
let mut to: Vec<T> = vec![];
for data in from {
to.push(data.into());
}
::protobuf::RepeatedField::from_vec(to)
fn trans_vec<F: Sized + Clone, T: From<F>>(from: Vec<F>) -> Vec<T> {
from.into_iter().map(|f| f.into()).collect()
}
fn into_vec<F: Sized + Clone, T: From<F>>(from: ::protobuf::RepeatedField<F>) -> Vec<T> {
let mut to: Vec<T> = vec![];
for data in from.to_vec() {
to.push(data.into());
}
to
}
fn from_option<F: Sized, T: From<F>>(from: Option<F>) -> ::protobuf::SingularPtrField<T> {
fn from_option<F: Sized, T: From<F>>(from: Option<F>) -> protobuf::MessageField<T> {
match from {
Some(f) => ::protobuf::SingularPtrField::from_option(Some(T::from(f))),
None => ::protobuf::SingularPtrField::none(),
Some(f) => protobuf::MessageField::from_option(Some(T::from(f))),
None => protobuf::MessageField::none(),
}
}
fn into_option<F: Into<T>, T: Sized>(from: ::protobuf::SingularPtrField<F>) -> Option<T> {
fn into_option<F: Into<T>, T: Sized>(from: protobuf::MessageField<F>) -> Option<T> {
from.into_option().map(|f| f.into())
}
@@ -83,9 +72,8 @@ impl From<FSGroup> for agent::FSGroup {
Self {
group_id: from.group_id,
group_change_policy: policy,
unknown_fields: Default::default(),
cached_size: Default::default(),
group_change_policy: policy.into(),
..Default::default()
}
}
}
@@ -95,9 +83,8 @@ impl From<StringUser> for agent::StringUser {
Self {
uid: from.uid,
gid: from.gid,
additionalGids: ::protobuf::RepeatedField::from_vec(from.additional_gids),
unknown_fields: Default::default(),
cached_size: Default::default(),
additionalGids: from.additional_gids,
..Default::default()
}
}
}
@@ -106,12 +93,11 @@ impl From<Device> for agent::Device {
fn from(from: Device) -> Self {
Self {
id: from.id,
field_type: from.field_type,
type_: from.field_type,
vm_path: from.vm_path,
container_path: from.container_path,
options: from_vec(from.options),
unknown_fields: Default::default(),
cached_size: Default::default(),
options: trans_vec(from.options),
..Default::default()
}
}
}
@@ -120,14 +106,13 @@ impl From<Storage> for agent::Storage {
fn from(from: Storage) -> Self {
Self {
driver: from.driver,
driver_options: from_vec(from.driver_options),
driver_options: trans_vec(from.driver_options),
source: from.source,
fstype: from.fs_type,
fs_group: from_option(from.fs_group),
options: from_vec(from.options),
options: trans_vec(from.options),
mount_point: from.mount_point,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -136,9 +121,8 @@ impl From<KernelModule> for agent::KernelModule {
fn from(from: KernelModule) -> Self {
Self {
name: from.name,
parameters: from_vec(from.parameters),
unknown_fields: Default::default(),
cached_size: Default::default(),
parameters: trans_vec(from.parameters),
..Default::default()
}
}
}
@@ -165,11 +149,10 @@ impl From<types::IPFamily> for IPFamily {
impl From<IPAddress> for types::IPAddress {
fn from(from: IPAddress) -> Self {
Self {
family: from.family.into(),
family: protobuf::EnumOrUnknown::new(from.family.into()),
address: from.address,
mask: from.mask,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -177,7 +160,7 @@ impl From<IPAddress> for types::IPAddress {
impl From<types::IPAddress> for IPAddress {
fn from(src: types::IPAddress) -> Self {
Self {
family: src.family.into(),
family: src.family.unwrap().into(),
address: "".to_string(),
mask: "".to_string(),
}
@@ -189,14 +172,13 @@ impl From<Interface> for types::Interface {
Self {
device: from.device,
name: from.name,
IPAddresses: from_vec(from.ip_addresses),
IPAddresses: trans_vec(from.ip_addresses),
mtu: from.mtu,
hwAddr: from.hw_addr,
pciPath: from.pci_addr,
field_type: from.field_type,
type_: from.field_type,
raw_flags: from.raw_flags,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -206,11 +188,11 @@ impl From<types::Interface> for Interface {
Self {
device: src.device,
name: src.name,
ip_addresses: into_vec(src.IPAddresses),
ip_addresses: trans_vec(src.IPAddresses),
mtu: src.mtu,
hw_addr: src.hwAddr,
pci_addr: src.pciPath,
field_type: src.field_type,
field_type: src.type_,
raw_flags: src.raw_flags,
}
}
@@ -219,7 +201,7 @@ impl From<types::Interface> for Interface {
impl From<agent::Interfaces> for Interfaces {
fn from(src: agent::Interfaces) -> Self {
Self {
interfaces: into_vec(src.Interfaces),
interfaces: trans_vec(src.Interfaces),
}
}
}
@@ -232,9 +214,8 @@ impl From<Route> for types::Route {
device: from.device,
source: from.source,
scope: from.scope,
family: from.family.into(),
unknown_fields: Default::default(),
cached_size: Default::default(),
family: protobuf::EnumOrUnknown::new(from.family.into()),
..Default::default()
}
}
}
@@ -247,7 +228,7 @@ impl From<types::Route> for Route {
device: src.device,
source: src.source,
scope: src.scope,
family: src.family.into(),
family: src.family.unwrap().into(),
}
}
}
@@ -255,9 +236,8 @@ impl From<types::Route> for Route {
impl From<Routes> for agent::Routes {
fn from(from: Routes) -> Self {
Self {
Routes: from_vec(from.routes),
unknown_fields: Default::default(),
cached_size: Default::default(),
Routes: trans_vec(from.routes),
..Default::default()
}
}
}
@@ -265,7 +245,7 @@ impl From<Routes> for agent::Routes {
impl From<agent::Routes> for Routes {
fn from(src: agent::Routes) -> Self {
Self {
routes: into_vec(src.Routes),
routes: trans_vec(src.Routes),
}
}
}
@@ -276,12 +256,11 @@ impl From<CreateContainerRequest> for agent::CreateContainerRequest {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
string_user: from_option(from.string_user),
devices: from_vec(from.devices),
storages: from_vec(from.storages),
devices: trans_vec(from.devices),
storages: trans_vec(from.storages),
OCI: from_option(from.oci),
sandbox_pidns: from.sandbox_pidns,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -291,8 +270,7 @@ impl From<RemoveContainerRequest> for agent::RemoveContainerRequest {
Self {
container_id: from.container_id,
timeout: from.timeout,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -301,8 +279,7 @@ impl From<ContainerID> for agent::StartContainerRequest {
fn from(from: ContainerID) -> Self {
Self {
container_id: from.container_id,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -311,8 +288,7 @@ impl From<ContainerID> for agent::StatsContainerRequest {
fn from(from: ContainerID) -> Self {
Self {
container_id: from.container_id,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -321,8 +297,7 @@ impl From<ContainerID> for agent::PauseContainerRequest {
fn from(from: ContainerID) -> Self {
Self {
container_id: from.container_id,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -331,8 +306,7 @@ impl From<ContainerID> for agent::ResumeContainerRequest {
fn from(from: ContainerID) -> Self {
Self {
container_id: from.container_id,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -343,8 +317,7 @@ impl From<SignalProcessRequest> for agent::SignalProcessRequest {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
signal: from.signal,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -354,8 +327,7 @@ impl From<WaitProcessRequest> for agent::WaitProcessRequest {
Self {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -365,8 +337,7 @@ impl From<UpdateContainerRequest> for agent::UpdateContainerRequest {
Self {
container_id: from.container_id,
resources: from_option(Some(from.resources)),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -377,8 +348,7 @@ impl From<WriteStreamRequest> for agent::WriteStreamRequest {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
data: from.data,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -401,7 +371,7 @@ impl From<GetIPTablesRequest> for agent::GetIPTablesRequest {
impl From<agent::GetIPTablesResponse> for GetIPTablesResponse {
fn from(from: agent::GetIPTablesResponse) -> Self {
Self {
data: from.get_data().to_vec(),
data: from.data().to_vec(),
}
}
}
@@ -419,7 +389,7 @@ impl From<SetIPTablesRequest> for agent::SetIPTablesRequest {
impl From<agent::SetIPTablesResponse> for SetIPTablesResponse {
fn from(from: agent::SetIPTablesResponse) -> Self {
Self {
data: from.get_data().to_vec(),
data: from.data().to_vec(),
}
}
}
@@ -431,8 +401,7 @@ impl From<ExecProcessRequest> for agent::ExecProcessRequest {
exec_id: from.process_id.exec_id(),
string_user: from_option(from.string_user),
process: from_option(from.process),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -514,14 +483,14 @@ impl From<agent::BlkioStatsEntry> for BlkioStatsEntry {
impl From<agent::BlkioStats> for BlkioStats {
fn from(src: agent::BlkioStats) -> Self {
Self {
io_service_bytes_recursive: into_vec(src.io_service_bytes_recursive),
io_serviced_recursive: into_vec(src.io_serviced_recursive),
io_queued_recursive: into_vec(src.io_queued_recursive),
io_service_time_recursive: into_vec(src.io_service_time_recursive),
io_wait_time_recursive: into_vec(src.io_wait_time_recursive),
io_merged_recursive: into_vec(src.io_merged_recursive),
io_time_recursive: into_vec(src.io_time_recursive),
sectors_recursive: into_vec(src.sectors_recursive),
io_service_bytes_recursive: trans_vec(src.io_service_bytes_recursive),
io_serviced_recursive: trans_vec(src.io_serviced_recursive),
io_queued_recursive: trans_vec(src.io_queued_recursive),
io_service_time_recursive: trans_vec(src.io_service_time_recursive),
io_wait_time_recursive: trans_vec(src.io_wait_time_recursive),
io_merged_recursive: trans_vec(src.io_merged_recursive),
io_time_recursive: trans_vec(src.io_time_recursive),
sectors_recursive: trans_vec(src.sectors_recursive),
}
}
}
@@ -569,7 +538,7 @@ impl From<agent::StatsContainerResponse> for StatsContainerResponse {
fn from(src: agent::StatsContainerResponse) -> Self {
Self {
cgroup_stats: into_option(src.cgroup_stats),
network_stats: into_vec(src.network_stats),
network_stats: trans_vec(src.network_stats),
}
}
}
@@ -580,8 +549,7 @@ impl From<ReadStreamRequest> for agent::ReadStreamRequest {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
len: from.len,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -597,8 +565,7 @@ impl From<CloseStdinRequest> for agent::CloseStdinRequest {
Self {
container_id: from.process_id.container_id(),
exec_id: from.process_id.exec_id(),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -610,8 +577,7 @@ impl From<TtyWinResizeRequest> for agent::TtyWinResizeRequest {
exec_id: from.process_id.exec_id(),
row: from.row,
column: from.column,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -620,8 +586,7 @@ impl From<UpdateInterfaceRequest> for agent::UpdateInterfaceRequest {
fn from(from: UpdateInterfaceRequest) -> Self {
Self {
interface: from_option(from.interface),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -629,8 +594,7 @@ impl From<UpdateInterfaceRequest> for agent::UpdateInterfaceRequest {
impl From<Empty> for agent::ListInterfacesRequest {
fn from(_: Empty) -> Self {
Self {
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -639,8 +603,7 @@ impl From<UpdateRoutesRequest> for agent::UpdateRoutesRequest {
fn from(from: UpdateRoutesRequest) -> Self {
Self {
routes: from_option(from.route),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -648,8 +611,7 @@ impl From<UpdateRoutesRequest> for agent::UpdateRoutesRequest {
impl From<Empty> for agent::ListRoutesRequest {
fn from(_: Empty) -> Self {
Self {
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -662,8 +624,7 @@ impl From<ARPNeighbor> for types::ARPNeighbor {
lladdr: from.ll_addr,
state: from.state,
flags: from.flags,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -671,9 +632,8 @@ impl From<ARPNeighbor> for types::ARPNeighbor {
impl From<ARPNeighbors> for agent::ARPNeighbors {
fn from(from: ARPNeighbors) -> Self {
Self {
ARPNeighbors: from_vec(from.neighbors),
unknown_fields: Default::default(),
cached_size: Default::default(),
ARPNeighbors: trans_vec(from.neighbors),
..Default::default()
}
}
}
@@ -682,8 +642,7 @@ impl From<AddArpNeighborRequest> for agent::AddARPNeighborsRequest {
fn from(from: AddArpNeighborRequest) -> Self {
Self {
neighbors: from_option(from.neighbors),
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -692,14 +651,13 @@ impl From<CreateSandboxRequest> for agent::CreateSandboxRequest {
fn from(from: CreateSandboxRequest) -> Self {
Self {
hostname: from.hostname,
dns: from_vec(from.dns),
storages: from_vec(from.storages),
dns: trans_vec(from.dns),
storages: trans_vec(from.storages),
sandbox_pidns: from.sandbox_pidns,
sandbox_id: from.sandbox_id,
guest_hook_path: from.guest_hook_path,
kernel_modules: from_vec(from.kernel_modules),
unknown_fields: Default::default(),
cached_size: Default::default(),
kernel_modules: trans_vec(from.kernel_modules),
..Default::default()
}
}
}
@@ -707,8 +665,7 @@ impl From<CreateSandboxRequest> for agent::CreateSandboxRequest {
impl From<Empty> for agent::DestroySandboxRequest {
fn from(_: Empty) -> Self {
Self {
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -719,8 +676,7 @@ impl From<OnlineCPUMemRequest> for agent::OnlineCPUMemRequest {
wait: from.wait,
nb_cpus: from.nb_cpus,
cpu_only: from.cpu_only,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -729,8 +685,7 @@ impl From<ReseedRandomDevRequest> for agent::ReseedRandomDevRequest {
fn from(from: ReseedRandomDevRequest) -> Self {
Self {
data: from.data,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -739,8 +694,7 @@ impl From<MemHotplugByProbeRequest> for agent::MemHotplugByProbeRequest {
fn from(from: MemHotplugByProbeRequest) -> Self {
Self {
memHotplugProbeAddr: from.mem_hotplug_probe_addr,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -750,8 +704,7 @@ impl From<SetGuestDateTimeRequest> for agent::SetGuestDateTimeRequest {
Self {
Sec: from.sec,
Usec: from.usec,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -761,8 +714,8 @@ impl From<agent::AgentDetails> for AgentDetails {
Self {
version: src.version,
init_daemon: src.init_daemon,
device_handlers: into_vec(src.device_handlers),
storage_handlers: into_vec(src.storage_handlers),
device_handlers: trans_vec(src.device_handlers),
storage_handlers: trans_vec(src.storage_handlers),
supports_seccomp: src.supports_seccomp,
}
}
@@ -789,8 +742,7 @@ impl From<CopyFileRequest> for agent::CopyFileRequest {
gid: from.gid,
offset: from.offset,
data: from.data,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -806,8 +758,7 @@ impl From<agent::WaitProcessResponse> for WaitProcessResponse {
impl From<Empty> for agent::GetOOMEventRequest {
fn from(_: Empty) -> Self {
Self {
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -816,8 +767,7 @@ impl From<CheckRequest> for health::CheckRequest {
fn from(from: CheckRequest) -> Self {
Self {
service: from.service,
unknown_fields: Default::default(),
cached_size: Default::default(),
..Default::default()
}
}
}
@@ -825,7 +775,7 @@ impl From<CheckRequest> for health::CheckRequest {
impl From<health::HealthCheckResponse> for HealthCheckResponse {
fn from(from: health::HealthCheckResponse) -> Self {
Self {
status: from.status as u32,
status: from.status.value() as u32,
}
}
}
@@ -846,3 +796,33 @@ impl From<agent::OOMEvent> for OomEventResponse {
}
}
}
impl From<VolumeStatsRequest> for agent::VolumeStatsRequest {
fn from(from: VolumeStatsRequest) -> Self {
Self {
volume_guest_path: from.volume_guest_path,
..Default::default()
}
}
}
impl From<csi::VolumeStatsResponse> for VolumeStatsResponse {
fn from(from: csi::VolumeStatsResponse) -> Self {
let result: String = format!(
"Usage: {:?} Volume Condition: {:?}",
from.usage(),
from.volume_condition()
);
Self { data: result }
}
}
impl From<ResizeVolumeRequest> for agent::ResizeVolumeRequest {
fn from(from: ResizeVolumeRequest) -> Self {
Self {
volume_guest_path: from.volume_guest_path,
size: from.size,
..Default::default()
}
}
}

View File

@@ -23,8 +23,8 @@ pub use types::{
ReseedRandomDevRequest, ResizeVolumeRequest, Route, Routes, SetGuestDateTimeRequest,
SetIPTablesRequest, SetIPTablesResponse, SignalProcessRequest, StatsContainerResponse, Storage,
TtyWinResizeRequest, UpdateContainerRequest, UpdateInterfaceRequest, UpdateRoutesRequest,
VersionCheckResponse, WaitProcessRequest, WaitProcessResponse, WriteStreamRequest,
WriteStreamResponse,
VersionCheckResponse, VolumeStatsRequest, VolumeStatsResponse, WaitProcessRequest,
WaitProcessResponse, WriteStreamRequest, WriteStreamResponse,
};
use anyhow::Result;
@@ -88,4 +88,6 @@ pub trait Agent: AgentManager + HealthService + Send + Sync {
async fn get_oom_event(&self, req: Empty) -> Result<OomEventResponse>;
async fn get_ip_tables(&self, req: GetIPTablesRequest) -> Result<GetIPTablesResponse>;
async fn set_ip_tables(&self, req: SetIPTablesRequest) -> Result<SetIPTablesResponse>;
async fn get_volume_stats(&self, req: VolumeStatsRequest) -> Result<VolumeStatsResponse>;
async fn resize_volume(&self, req: ResizeVolumeRequest) -> Result<Empty>;
}

View File

@@ -15,9 +15,6 @@ use tokio::{
use super::{ConnectConfig, Sock, Stream};
unsafe impl Send for HybridVsock {}
unsafe impl Sync for HybridVsock {}
#[derive(Debug, PartialEq)]
pub struct HybridVsock {
uds: String,

View File

@@ -16,9 +16,6 @@ use tokio::net::UnixStream;
use super::{ConnectConfig, Sock, Stream};
unsafe impl Send for Vsock {}
unsafe impl Sync for Vsock {}
#[derive(Debug, PartialEq)]
pub struct Vsock {
vsock_cid: u32,

View File

@@ -9,6 +9,8 @@ use std::convert::TryFrom;
use serde::{Deserialize, Serialize};
pub const DEFAULT_REMOVE_CONTAINER_REQUEST_TIMEOUT: u32 = 10;
#[derive(PartialEq, Clone, Default)]
pub struct Empty {}
@@ -18,14 +20,9 @@ impl Empty {
}
}
impl Default for FSGroupChangePolicy {
fn default() -> Self {
FSGroupChangePolicy::Always
}
}
#[derive(Debug, Clone, PartialEq)]
#[derive(Default, Debug, Clone, PartialEq)]
pub enum FSGroupChangePolicy {
#[default]
Always = 0,
OnRootMismatch = 1,
}
@@ -63,18 +60,13 @@ pub struct Storage {
pub mount_point: String,
}
#[derive(Deserialize, Clone, PartialEq, Eq, Debug, Hash)]
#[derive(Deserialize, Default, Clone, PartialEq, Eq, Debug, Hash)]
pub enum IPFamily {
#[default]
V4 = 0,
V6 = 1,
}
impl ::std::default::Default for IPFamily {
fn default() -> Self {
IPFamily::V4
}
}
#[derive(Deserialize, Debug, PartialEq, Clone, Default)]
pub struct IPAddress {
pub family: IPFamily,
@@ -124,7 +116,6 @@ pub struct CreateContainerRequest {
pub devices: Vec<Device>,
pub storages: Vec<Storage>,
pub oci: Option<oci::Spec>,
pub guest_hooks: Option<oci::Hooks>,
pub sandbox_pidns: bool,
pub rootfs_mounts: Vec<oci::Mount>,
}
@@ -165,7 +156,7 @@ impl ContainerProcessID {
}
}
#[derive(PartialEq, Clone, Debug, Default)]
#[derive(PartialEq, Clone, Debug)]
pub struct RemoveContainerRequest {
pub container_id: String,
pub timeout: u32,
@@ -180,6 +171,15 @@ impl RemoveContainerRequest {
}
}
impl std::default::Default for RemoveContainerRequest {
fn default() -> Self {
Self {
container_id: "".to_string(),
timeout: DEFAULT_REMOVE_CONTAINER_REQUEST_TIMEOUT,
}
}
}
#[derive(PartialEq, Clone, Default)]
pub struct SignalProcessRequest {
pub process_id: ContainerProcessID,
@@ -569,6 +569,16 @@ pub struct ResizeVolumeRequest {
pub size: u64,
}
#[derive(PartialEq, Clone, Default, Debug)]
pub struct VolumeStatsRequest {
pub volume_guest_path: String,
}
#[derive(PartialEq, Clone, Default, Debug)]
pub struct VolumeStatsResponse {
pub data: String,
}
#[cfg(test)]
mod test {
use std::convert::TryFrom;

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