1
0
mirror of https://github.com/kata-containers/kata-containers.git synced 2025-05-05 06:57:26 +00:00

Compare commits

...

505 Commits
3.14.0 ... main

Author SHA1 Message Date
Fabiano Fidêncio
fbf7faa9f4
Merge pull request from fidencio/topic/agent-only-try-ipv6-if-stack-is-supported
agent: netlink: Only add an ipv6 address if ipv6 is enabled
2025-05-02 12:31:40 +02:00
Xuewei Niu
a9b3c6a5a5
Merge pull request from lifupan/fix_slog
shimv2: fix the issue logger write failed
2025-05-02 17:25:44 +08:00
Fabiano Fidêncio
79ad68cce5
Merge pull request from kimullaa/remove-wrong-qemu-option
runtime: remove wrong qemu-system-x86_64 option
2025-05-02 11:18:45 +02:00
Fabiano Fidêncio
4ce00ea434 agent: netlink: Only add an ipv6 address if ipv6 is enabled
When running Kata Containers on CSPs, the CSPs may enforce their
clusters to be IPv4-only.

Checking the OCI spec passed down to container, on a GKE cluster, we can
see:
```
    "sysctl": {
      ...
      "net.ipv6.conf.all.disable_ipv6": "1",
      "net.ipv6.conf.default.disable_ipv6": "1",
      ...
    },
```

Even with ipv6 being explicitly disabled (behind our back ;-)), we've
noticed that IPv6 addresses would be received, but then as IPv6 was
disabled we'd break on CreatePodSandbox with the following error:
```
Warning  FailedCreatePodSandBox  4s    kubelet            Failed to
create pod sandbox: rpc error: code = Unknown desc = failed to create
containerd task: failed to create shim task: "update interface: Failed
to add address fe80::c44c:1cff:fe84:f6b7: NetlinkError(ErrorMessage {
code: Some(-13), header: [64, 0, 0, 0, 20, 0, 5, 5, 19, 0, 0, 0, 0, 0,
0, 0, 10, 64, 0, 0, 2, 0, 0, 0, 20, 0, 1, 0, 254, 128, 0, 0, 0, 0, 0, 0,
196, 76, 28, 255, 254, 132, 246, 183, 20, 0, 2, 0, 254, 128, 0, 0, 0, 0,
0, 0, 196, 76, 28, 255, 254, 132, 246, 183] })\n\nStack backtrace:\n
0: <unknown>\n   1: <unknown>\n   2: <unknown>\n   3: <unknown>\n   4:
<unknown>\n   5: <unknown>\n   6: <unknown>\n   7: <unknown>\n   8:
<unknown>\n   9: <unknown>\n  10: <unknown>": unknown
```

A huge shoutout to Fupan Li for helping with the debug on this one!

Fixes: 

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-05-02 09:10:45 +02:00
Shunsuke Kimura
3dba8ddd98 runtime: remove wrong qemu-system-x86_64 option
qemu-system-x86_64 does not support "-machine virt".
(this is only supported by arm,aarch64)
<https://people.redhat.com/~cohuck/2022/01/05/qemu-machine-types.html>

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-05-02 04:37:12 +09:00
Fabiano Fidêncio
7e404dd13f
Merge pull request from zvonkok/fix-kernel-modules-build
gpu: Set the ARCH explicilty for driver builds
2025-05-01 21:07:20 +02:00
Zvonko Kaiser
445cad7754 gpu: Set the ARCH explicilty for driver builds
Kernel Makefiles changed how to deduce the right arch
lets set it explicilty to enable arm and amd builds.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-05-01 17:13:20 +00:00
RuoqingHe
049a4ef3a8
Merge pull request from RuoqingHe/2025-04-14-dragonball-centralize-dbs
dragonball: Put local dependencies into workspace
2025-05-01 22:06:51 +08:00
RuoqingHe
bd1071aff8
Merge pull request from kata-containers/dependabot/cargo/src/mem-agent/crossbeam-channel-0.5.15
build(deps): bump crossbeam-channel from 0.5.13 to 0.5.15 in /src/mem-agent
2025-05-01 16:53:42 +08:00
Ruoqing He
61f2b6a733 dragonball: Put local dependencies into workspace
Put local dependencies (mostly `dbs` crates) into workspace to avoid
complex path dependencies all over the workspace. Simplify path
dependency referencing.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-05-01 08:40:22 +00:00
RuoqingHe
33c69fc8bf
Merge pull request from stevenhorsman/go-security-bump-april-25
versions: Bump golang.org/x/net
2025-05-01 16:36:24 +08:00
Fabiano Fidêncio
bc66d75fe9
Merge pull request from stevenhorsman/runtime-rs-centralise-workspace-config
Runtime rs centralise workspace config
2025-05-01 10:36:07 +02:00
Fupan Li
9924fbbc70 shimv2: fix the issue logger write failed
It's better to open the log pipe file with read & write option,
otherwise, once the containerd reboot and closed the read
endpoint, kata shim would write the log pipe with broken pipe error.

Fixes: 

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-05-01 16:15:18 +08:00
Fabiano Fidêncio
3dfabd42c2
Merge pull request from kimullaa/fix-xfs-rootfs-type
runtime: remove wrong xfs options
2025-05-01 09:05:17 +02:00
Fabiano Fidêncio
a2fbc598b8
Merge pull request from microsoft/cameronbaird/revert-aks-extension-pin
ci: revert temp: ci: Fix AKS cluster creation
2025-05-01 08:33:12 +02:00
Shunsuke Kimura
62639c861e runtime: remove wrong xfs options
"data=ordered" and "errors=remount-ro" are wrong options in xfs.
(they are ext4 options)
<https://manpages.ubuntu.com/manpages/focal/man5/xfs.5.html>

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-05-01 07:56:39 +09:00
Cameron Baird
6e21d14334 Revert "temp: ci: Fix AKS cluster creation"
This reverts commit 1de466fe84.

The latest release of the az aks extension fixes the issue https://github.com/Azure/azure-cli-extensions/blob/main/src/aks-preview/HISTORY.rst#1400b5

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-30 21:24:42 +00:00
stevenhorsman
a126884953 runtime-rs: Share workspace config
Update the runtime-rs workspace packages to
use workspace package versions where applicable
to centralise the config and reduce maintenance
when updating these

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-30 19:40:47 +01:00
stevenhorsman
f8fcd032ef workflow: Set RUST_LIB_BACKTRACE=0
As discussed in , with anyhow >=1.0.77 we have test failures due to backtrace behaviour
changing, so set RUST_LIB_BACKTRACE=0,
so that we only have backtrace on panics

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-30 19:38:13 +01:00
stevenhorsman
ffbaa793a3 versions: Update crossbeam-channel
Update all crossbeam-channel for all non-agent
packages (it was done separately in )
to 0.5.15 to get them on latest version and remove
the versions with a vulnerability

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-30 19:36:40 +01:00
Steve Horsman
b97bc03ecb
Merge pull request from stevenhorsman/dragonball-lockfiles
dragonball: Remove package lockfiles
2025-04-30 19:34:58 +01:00
stevenhorsman
f910c7535a ci: Workaround cargo deny issue
When a PR has no new files the cargo deny runner fails with:
```
[cargo-deny-generator.sh:17] ERROR: changed_files_status=
```
so add `|| true` to try and help this

Co-authored-by: Ruoqing He <heruoqing@iscas.ac.cn>
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-30 16:27:25 +01:00
stevenhorsman
97f7d49e8e dragonball: Remove package lockfiles
Since  the dbs crates are managed as members
of the dragonball workspace, so we can remove the lockfile
as it's now workspace managed now

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-30 09:14:07 +01:00
Steve Horsman
8045cb982c
Merge pull request from kata-containers/dependabot/cargo/src/runtime-rs/tokio-1.38.2
build(deps): bump tokio from 1.38.0 to 1.38.2 in /src/runtime-rs
2025-04-30 08:44:51 +01:00
Aurélien Bombo
46af7cf817
Merge pull request from microsoft/cameronbaird/address-gid-mismatch
genpolicy: Align GID behavior with CRI and enable GID policy checks.
2025-04-29 22:23:23 +01:00
Aurélien Bombo
19371e2d3b
Merge pull request from wainersm/fix_kbs_on_aks
tests/k8s: fix kbs installation on Azure AKS
2025-04-29 18:25:14 +01:00
Steve Horsman
6c1fafb651
Merge pull request from kata-containers/dependabot/cargo/src/tools/runk/tokio-1.44.2
build(deps): bump tokio from 1.38.0 to 1.44.2 in /src/tools/runk
2025-04-29 16:43:58 +01:00
Steve Horsman
3c8cc0cdbf
Merge pull request from BbolroC/add-cc-vfio-ap-test-s390x
GHA: Add VFIO-AP to s390x nightly tests for CoCo
2025-04-29 16:15:00 +01:00
Steve Horsman
a6d1dc7df3
Merge pull request from ldoktor/peer-pods
ci.ocp: Add peer-pods setup script
2025-04-29 15:57:30 +01:00
Hyounggyu Choi
63b9ae3ed0 GHA: Add VFIO-AP to s390x nightly tests for CoCo
As  introduces VFIO-AP bind/associate funtions for IBM Secure
Execution (SEL), a new internal nightly test has been established.
This PR adds a new entry `cc-vfio-ap-e2e-tests` to the existing matrix
to share the test result.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-04-29 16:06:12 +02:00
Steve Horsman
8b32846519
Merge pull request from stevenhorsman/kbs-logging-on-failure
tests: confidential: Add KBS logging
2025-04-29 13:29:21 +01:00
dependabot[bot]
7163d7d89b
build(deps): bump tokio from 1.38.0 to 1.38.2 in /src/runtime-rs
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.38.0 to 1.38.2.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.38.0...tokio-1.38.2)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.38.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-29 12:21:58 +00:00
dependabot[bot]
2992a279ab
build(deps): bump tokio from 1.38.0 to 1.44.2 in /src/tools/runk
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.38.0 to 1.44.2.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.38.0...tokio-1.44.2)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.44.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-29 12:14:41 +00:00
Fabiano Fidêncio
e5cc9acab8
Merge pull request from kata-containers/dependabot/cargo/src/agent/crossbeam-channel-0.5.15
build(deps): bump crossbeam-channel from 0.5.14 to 0.5.15 in /src/agent
2025-04-29 14:13:25 +02:00
Fabiano Fidêncio
a9893e83b8
Merge pull request from stevenhorsman/high-severity-security-bumps-april-25
rust: High severity security bumps april 25
2025-04-29 14:10:05 +02:00
stevenhorsman
52b2662b75 tests: confidential: Add KBS logging
For help with debugging add, logging of the KBS,
like the container system logs if the confidential test fails

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-29 09:48:18 +01:00
stevenhorsman
bcffe938ca versions: Bump golang.org/x/net
Bump golang.org/x/net to 0.38.0 as dependabot
isn't doing it for these packages to remediate
CVE-2025-22872

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-29 09:46:48 +01:00
Steve Horsman
57527c1ce4
Merge pull request from kata-containers/dependabot/go_modules/src/runtime/golang.org/x/net-0.38.0
build(deps): bump golang.org/x/net from 0.33.0 to 0.38.0 in /src/runtime
2025-04-29 09:39:30 +01:00
Cameron Baird
70ef0376fb genpolicy: Introduce special handling for clusters using nydus
Nydus+guest_pull has specific behavior where it improperly handles image layers on
the host, causing the CRI to not find /etc/passwd and /etc/group files
on container images which have them. The unfortunately causes different
outcomes w.r.t. GID used which we are trying to enforce with policy.

This behavior is observed/explained in https://github.com/kata-containers/kata-containers/issues/11162

Handle this exception with a config.settings.cluster_config.guest_pull
field. When this is true, simply ignore the /etc/* files in the
container image as they will not be parsed by the CRI.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 20:18:42 +00:00
Cameron Baird
d3b652014a genpolicy: Introduce genpolicy tests for security contexts
Add security context testcases for genpolicy, verifying that UID and GID
configurations controlled by the kubernetes security context are
enforced.

Also, fix the other CreateContainerRequest tests' expected contents to
reflect our new genpolicy parsing/enforcement of GIDs.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:31 +00:00
Cameron Baird
fc75aee13a ci: Add CI tests for runAsGroup, GID policy
Introduce tests to check for policy correctness on a redis deployment
with 1. a pod-level securityContext 2. a container-level securityContext
which shadows the pod-level securityContext 3. a pod-level
securityContext which selects an existing user (nobody), causing a new GID to be selected.

Redis is an interesting container image to test with because it includes
a /etc/passwd file with existing user/group configuration of 1000:1000 baked in.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:31 +00:00
Cameron Baird
938ddeaf1e genpolicy: Enable GID checks in rules.rego
With fixes to align policy GID parsing with the CRI behavior, we can now
enable policy verification of GIDs.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:31 +00:00
Cameron Baird
eb2c7f4150 genpolicy: Integrate /etc/passwd from OCI container when setting GIDs
The GID used for the running process in an OCI container is a function of
1. The securityContext.runAsGroup specified in a pod yaml, 2. The UID:GID mapping in
/etc/passwd, if present in the container image layers, 3. Zero, even if
the userstr specifies a GID.

Make our policy engine align with this behavior by:
1. At the registry level, always obtain the GID from the /etc/passwd
   file if present. Ignore GIDs specified in the userstr encoded in the
OCI container.
2. After an update to UID due to securityContexts, perform one final check against
   the /etc/passwd file if present. The GID used for the running
process is the mapping in this file from UID->GID.
3. Override everything above with the GID of the securityContext
   configuration if provided

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:31 +00:00
Cameron Baird
c13d7796ee genpolicy: Parse secContext runAsGroup and allowPrivilegeEscalation
Our policy should cover these fields for securityContexts at the pod or
container level of granularity.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:31 +00:00
Cameron Baird
349ce8c339 genpolicy: Refactor registry user/group parsing to account for all cases
The get_process logic in registry.rs did not account for all cases
(username:groupname), did not defer to contents of /etc/group,
/etc/passwd when it should, and was difficult to read.

Clean this implementation up, factoring the string parsing for
user/group strings into their own functions. Enable the
registry::Container class to query /etc/passwd and /etc/group, if they
exist.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-04-28 16:28:29 +00:00
Wainer dos Santos Moschetta
460c3394dd gha: run CoCo non-TEE tests on "all" host type
By running on "all" host type there are two consequences:

1) run the "normal" tests too (until now, it's only "small" tests), so
   increasing the coverage
2) create AKS cluster with larger VMs. This is a new requirement due to
   the current ingress controller for the KBS service eating too much
   vCPUs and lefting only few for the tests (resulting on failures)

Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2025-04-28 12:08:31 -03:00
Wainer dos Santos Moschetta
945482ff6e tests: make _print_instance_type() to handle "all" host type
_print_instance_type() returns the instance type of the AKS nodes, based
on the host type. Tests are grouped per host type in "small" and "normal"
sets based on the CPU requirements: "small" tests require few CPUs and
"normal" more.

There is an 3rd case: "all" host type maps to the union of "small"
and "normal" tests, which should be handled by _print_instance_type()
properly. In this case, it should return the largest instance type
possible because "normal" tests  will be executed too.

Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2025-04-28 12:08:31 -03:00
Wainer dos Santos Moschetta
a66aac0d77 tests/k8s: optimize nginx ingress for AKS small VM
It's used an AKS managed ingress controller which keeps two nginx pod
replicas where both request 500m of CPU. On small VMs like we've used on
CI for running the CoCo non-TEE tests, it left only a few amount of CPU
for the tests. Actually, one of these pod replicas won't even get
started. So let's patch the ingress controller to have only one replica
of nginx.

Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2025-04-28 12:08:31 -03:00
Wainer dos Santos Moschetta
14e74b8fc9 tests/k8s: fix kbs installation on Azure AKS
The Azure AKS addon-http-application-routing add-on is deprecated and
cannot be enabled on new clusters which has caused some CI jobs to fail.

Migrated our code to use approuting instead. Unlike
addon-http-application-routing, this add-on doesn't
configure a managed cluster DNS zone, but the created ingress has a
public IP. To avoid having to deal with DNS setup, we will be using that
address from now on. Thus, some functions no longer used are deleted.

Fixes 
Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2025-04-28 12:08:31 -03:00
stevenhorsman
c938c75af0 versions: kata-ctl: Bump rustls
Bump rustls version to > 0.21.11 to remediate
high severity CVE-2024-32650

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-28 14:55:59 +01:00
stevenhorsman
2ee7ef6aa3 versions: agent-ctl: Bump hashbrown
Bump hashbrown to >= 0.15.1 to remediate the high severity
security alert that was in v0.15.0

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-28 14:55:46 +01:00
stevenhorsman
e3d3a2843f versions: Bump mio to at least 0.8.11
Ensure that all the versions of mio we use are at
least 0.8.11 to remediate CVE-2024-27308

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-28 14:55:46 +01:00
stevenhorsman
973bd7c2b6 build(deps): bump golang.org/x/net from 0.33.0 to 0.38.0 in /src/runtime
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.33.0 to 0.38.0.
- [Commits](https://github.com/golang/net/compare/v0.33.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.38.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-28 14:09:54 +01:00
Steve Horsman
9248634baa
Merge pull request from stevenhorsman/golang-1.23.7
versions: Bump golang version
2025-04-28 13:46:11 +01:00
Fabiano Fidêncio
ee344aa4e9
Merge pull request from fidencio/topic/reclaim-guest-freed-memory-backport-from-runtime-rs
runtime: clh: Add reclaim_guest_freed_memory [BACKPORT]
2025-04-28 12:32:33 +02:00
Steve Horsman
4f703e376b
Merge pull request from BbolroC/remove-non-tee-from-required-tests
ci: Remove run-k8s-tests-coco-nontee from required tests
2025-04-28 10:05:07 +01:00
Hyounggyu Choi
9fe70151f7 ci: Remove run-k8s-tests-coco-nontee from required tests
In , `run-k8s-tests-coco-nontee` was set as requried by mistake.
This PR disables the test again.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-04-28 10:48:08 +02:00
Steve Horsman
83d31b142b
Merge pull request from Jakob-Naucke/basic-s390x-ci
ci: Extend basic s390x tests
2025-04-28 09:14:00 +01:00
Fupan Li
3457572130
Merge pull request from Apokleos/pcilibs-rs
kata-sys-utils: Introduce pcilibs for getting pci devices info
2025-04-27 16:39:40 +08:00
Alex Lyn
43b5a616f6
Merge pull request from Apokleos/memcfg-adjust
kata-types: Optimize memory adjuesting by only gathering memory info
2025-04-27 15:57:45 +08:00
Fabiano Fidêncio
b747f8380e clh: Rework CreateVM to reduce the amount of cycles
Otherwise the static checks will whip us as hard as possible.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-25 21:30:47 +02:00
Champ-Goblem
9f76467cb7 runtime: clh: Add reclaim_guest_freed_memory [BACKPORT]
We're bringing to *Cloud Hypervisor only* the reclaim_guest_freed_memory
option already present in the runtime-rs.

This allows us to use virtio-balloon for the hypervisor to reclaim
memory freed by the guest.

The reason we're not touching other hypervisors is because we're very
much aware of avoiding to clutter the go code at this point, so we'll
leave it for whoever really needs this on other hypervisor (and trust
me, we really do need it for Cloud Hypervisor right now ;-)).

Signed-off-by: Champ-Goblem <cameron@northflank.com>
Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-25 21:05:53 +02:00
Fabiano Fidêncio
1c72d22212
Merge pull request from fidencio/topic/kernel-add-taskstats-to-the-config
kernel: Add CONFIG_TASKSTATS (and related) configs
2025-04-25 15:28:04 +02:00
Steve Horsman
213f9ddd30
Merge pull request from fidencio/topic/release-3.16.0-bump
release: Bump version to 3.16.0
2025-04-25 09:04:31 +01:00
Fabiano Fidêncio
fc4e10b08d release: Bump version to 3.16.0
Bump VERSION and helm-chart versions

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-25 08:17:15 +02:00
Fabiano Fidêncio
b96685bf7a
Merge pull request from fidencio/topic/build-allow-choosing-which-runtime-will-be-built
build: Allow users to build the go, rust, or both runtimes
2025-04-25 08:13:07 +02:00
Fabiano Fidêncio
800c05fffe
Merge pull request from kata-containers/sprt/fix-create-cluster
temp: ci: Fix AKS cluster creation
2025-04-24 23:01:12 +02:00
Aurélien Bombo
1de466fe84 temp: ci: Fix AKS cluster creation
The AKS CLI recently introduced a regression that prevents using
aks-preview extensions (Azure/azure-cli#31345), and hence create
CI clusters.

To address this, we temporarily hardcode the last known good version of
aks-preview.

Note that I removed the comment about this being a Mariner requirement,
as aks-preview is also a requirement of AKS App Routing, which will
be introduced soon in .

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-04-24 15:06:14 -05:00
Dan Mihai
706c2e2d68
Merge pull request from microsoft/danmihai1/retry-genpolicy
ci: retry genpolicy execution
2025-04-24 08:01:22 -07:00
Champ-Goblem
cf4325b535 kernel: Add CONFIG_TASKSTATS (and related) configs
Knowing that the upstream project provides a "ready to use" version of
the kernel, it's good to include an easy way to users to monitor
performance, and that's what we're doing by enabling the TASKSTATS (and
related) kernel configs.

This has been present as part of older kernels, but I couldn't
reasonably find the reason why it's been dropped.

Signed-off-by: Champ-Goblem <cameron@northflank.com>
Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-24 11:51:21 +02:00
Fabiano Fidêncio
7e9e9263d1 build: Allow users to build the go, rust, or both runtimes
Let's add a RUNTIME_CHOICE env var that can be passed to be build
scripts, which allows the user to select whether they bulld the go
runtime, the rust runtime, or both.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-24 10:36:26 +02:00
Alex Lyn
8b49564c01
Merge pull request from Xynnn007/faet-initdata-rbd
Feat | Implement initdata for bare-metal/qemu hypervisor
2025-04-24 09:59:14 +08:00
Alex Lyn
e8f19609b9
Merge pull request from zvonkok/cdi-annotations
gpu: Fix CDI annotations
2025-04-24 09:58:16 +08:00
Dan Mihai
517d6201f5 ci: retry genpolicy execution
genpolicy is sending more HTTPS requests than other components during
CI so it's more likely to be affected by transient network errors
similar to:

ConnectError(
  "dns error",
  Custom {
     kind: Uncategorized,
     error: "failed to lookup address information: Try again",
  },
)

Note that genpolicy is not the only component hitting network errors
during CI. Recent example from a different component:

"Message:  failed to create containerd task: failed to create shim task:
 failed to async pull blob stream HTTP status server error (502 Bad Gateway)"

This CI change might help just with the genpolicy errors.

Fixes: 

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-04-23 21:38:12 +00:00
Zvonko Kaiser
3946435291 gpu: Handle VFIO devices with DevicePlugin and CDI
We can provide devices during cold-plug with CDI annotation on a Pod
level and add per container device information wit the device plugin.
Since the sandbox has already attached the VFIO device remove them
from consideration and just apply the inner runtime CDI annotation.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-04-23 21:02:06 +00:00
Zvonko Kaiser
486244b292 gpu: Remove unneeded parsing of CDI devices
The addition of CDI devices is now done for single_container
and pod_sandbox and pod_container before the devmanager creates
the deviceinfos no need for extra parsing.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-04-23 21:02:06 +00:00
Zvonko Kaiser
6713db8990 gpu: Add CDI parsing for Sandbox as well
Extend the CDI parsing for pod_sandbox as well, only single_container
was covered properly.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-04-23 21:02:06 +00:00
Zvonko Kaiser
97f4bcb456 gpu: Remove CDI annotations for outer runtime
After the outer runtime has processed the CDI annotation from the
spec we can delete them since they were converted into Linux
devices in the OCI spec.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-04-23 21:02:06 +00:00
Steve Horsman
6102976d2d
Merge pull request from stevenhorsman/gperf-mirror
versions: Switch gperf mirror
2025-04-23 20:21:42 +01:00
stevenhorsman
09052faaa0 versions: Switch gperf mirror
Every so often the main gnu site has an outage, so
we can't download gperf. GNU providesthe generic URL https://ftpmirror.gnu.org to
automatically choose a nearby and up-to-date mirror,
so switch to this to help avoid this problem

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-23 15:29:54 +01:00
stevenhorsman
ed56050a99 versions: Bump golangci-lint version
v1.60.0+ is needed for go 1.23 support, so
bump to the current latest 1.x version

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-23 12:37:48 +01:00
stevenhorsman
1c9d7ce0eb ci: cri-containerd: Remove source from install_go.sh
If the correct version of go is already installed then
install_go.sh runs `exit`. When calling this as source from
cri-containerd/gha-run.sh it means all dependencies after
are skipped, so remove this.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-23 12:37:48 +01:00
stevenhorsman
c37840ce80 versions: Bump golang version
Bump golang version to the latest minor 1.23.x release
now that 1.24 has been released and 1.22.x is no longer
stable and receiving security fixes

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-23 12:37:48 +01:00
dependabot[bot]
463fd4eda4
build(deps): bump crossbeam-channel from 0.5.14 to 0.5.15 in /src/agent
Bumps [crossbeam-channel](https://github.com/crossbeam-rs/crossbeam) from 0.5.14 to 0.5.15.
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-channel-0.5.14...crossbeam-channel-0.5.15)

---
updated-dependencies:
- dependency-name: crossbeam-channel
  dependency-version: 0.5.15
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-23 11:34:14 +00:00
Steve Horsman
1ffce3ff70
Merge pull request from stevenhorsman/update-before-install
workflows: Add apt update before install
2025-04-23 12:32:54 +01:00
stevenhorsman
ccfdf59607 workflows: Add apt update before install
Add apt/apt-get updates before we do
apt/apt-get installs to try and help with
issues where we fail to fetch packages

Co-authored-by: Fabiano Fidêncio <fidencio@northflank.com>
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-23 09:06:08 +01:00
Xynnn007
b1c72c7094 test: add integration test for initdata
This test we will test initdata in the following logic
1. Enable image signature verification via kernel commandline
2. Set Trustee address via initdata
3. Pull an image from a banned registry
4. Check if the pulling fails with log `image security validation
failed` the initdata works.

Note that if initdata does not work, the pod still fails to launch. But
the error information is `[CDH] [ERROR]: Get Resource failed` which
internally means that the KBS URL has not been set correctly.

This test now only runs on qemu-coco-dev+x86_64 and qemu-tdx

Signed-off-by: Xynnn007 <xynnn@linux.alibaba.com>
2025-04-23 15:55:04 +08:00
RuoqingHe
ef12dcd7da
Merge pull request from RuoqingHe/2025-04-15-fix-flag-calc
runtime-rs: Use bitwise or assign for bitflags
2025-04-23 15:20:33 +08:00
alex.lyn
9eb3fcb84b kata-types: Clean up noise caused by unformatted code
For a long time, there has been unformatted code in the kata-types
codebase, for example:
```
if qemu.memory_info.enable_guest_swap {
-                return Err(eother!(
-                    "Qemu hypervisor doesn't support enable_guest_swap"
-                ));
+                return Err(eother!("Qemu hypervisor doesn't support
enable_guest_swap"));
             }
...
-    }, device::DRIVER_NVDIMM_TYPE, eother, resolve_path
+    },
+    device::DRIVER_NVDIMM_TYPE,
+    eother, resolve_path,
-use std::collections::HashMap;
-use anyhow::{Result, anyhow};
+use anyhow::{anyhow, Result};
 use std::collections::hash_map::Entry;
+use std::collections::HashMap;
-/// DRIVER_VFIO_PCI_GK_TYPE is the device driver for vfio-pci 
+/// DRIVER_VFIO_PCI_GK_TYPE is the device driver for vfio-pci
```
This has brought unnecessary difficulties in version maintenance and
commit difficulties. This commit will address this issue.

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:40:07 +08:00
alex.lyn
97a1942f86 kata-types: Optimize memory adjuesting by only gathering memory info
The Coniguration initialization was observed to be significantly slow
due to the extensive system information gathering performed by
`sysinfo::System::new_all()`. This function collects data on CPU,
memory, disks, and network, most of which is unnecessary for Kata's
memory adjusting config phase, where only the total system memory is
required.

This commit optimizes the initialization process by implementing a more
targeted approach to retrieve only the total system memory. This avoids
the overhead of collecting a large amount of irrelevant data, resulting
in a noticeable performance improvement.

Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:40:07 +08:00
alex.lyn
3e77377be0 kata-sys-utils: Add test cases for devices
In this, the crate mockall is introduced to help
mock get_all_devices.

Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:32:04 +08:00
alex.lyn
f714b6c049 kata-sys-utils: Add test cases for pci manager
Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:32:04 +08:00
alex.lyn
0cdc05ce0a kata-sys-utils: Introduce method to help handle proper BAR memory
We need more information (BAR memory and other future
ures...)for
PCI devices when vfio devices passed through.
So the method get_bars_max_addressable_memory is introduced for vfio
devices to deduce the memory_reserve and pref64_reserve for NVIDIA

devices. But it will be extended for other devices.

Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:32:04 +08:00
alex.lyn
f5eaaa41d5 kata-sys-utils: Introduce pcilibs to help get pci device info
It's the basic framework for getting information of pci devices.
Currently, we focus on the PCI Max bar memory size, but it'll be
extended in the future.

Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-23 09:32:04 +08:00
Ruoqing He
d7f4b6cbef runtime-rs: Use bitwise or assign for bitflags
Use `|=` instead of `+=` while calculating and iterating through a
vector of flags, which makes more sense and prevents situations like
duplicated flags in vector, which would cause problems.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-04-22 23:55:11 +00:00
Jakob Naucke
1c3b1f5adb ci: Extend basic s390x tests
Currently, s390x only tests cri-containerd. Partially converge to the
feature set of basic-ci-amd64:

- containerd-sandboxapi
- containerd-stability
- docker

with the appropriate hypervisors.
Do not run tests currently skipped on amd64, as well as

- agent-ctl, which we don't package for s390x
- nerdctl, does not package the `full` image for s390x
- nydus, does not package for s390x

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
Co-authored-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-04-22 21:34:02 +02:00
Aurélien Bombo
bf93b5daf1
Merge pull request from Sumynwa/sumsharma/policy_execprocess_container_id
genpolicy: Add container_id & related policy container data to state.
2025-04-22 18:37:58 +01:00
Aurélien Bombo
318c409ed6
Merge pull request from gkurz/rootfs-systemd-files
rootfs: Don't remove files from the rootfs by default
2025-04-22 18:17:14 +01:00
Aurélien Bombo
12594a9f9e
Merge pull request from wainersm/make_nontee_job_not_required
ci: demote CoCo non-TEE to non-required from gatekeeper
2025-04-22 18:15:28 +01:00
Greg Kurz
734e7e8c54 rootfs: Don't remove files from the rootfs by default
Recent PR  moved the deletion of systemd files and units that were
deemed uneccessary by 02b3b3b977 from `image_builder.sh` to `rootfs.sh`.
This unfortunately broke `rootfs.sh centos` and `rootfs.sh -r` as used by
some other downstream users like fedora and RHEL, with the following error :

  Warning  FailedCreatePodSandBox  1s (x5 over 63s)  kubelet
   Failed to create pod sandbox: rpc error: code = Unknown
     desc = CreateContainer failed: Establishing a D-Bus connection

Caused by:
    0: I/O error: Connection reset by peer (os error 104)
    1: Connection reset by peer (os error 104)

This is because the aforementioned distros use dbus-broker [1] that requires
systemd-journald to be present.

It is questionable that systemd units or files should be deemed unnecessary
for _all_ distros but this has been around since 2019. There's now also a
long-standing expectation from CI that `make rootfs && make image` does
remove these files.

In order to accomodate all the expectations, add a `-d` flag to `rootfs.sh`
to delete the systemd files and have `make rootfs` to use it.

[1] https://github.com/bus1/dbus-broker

Reported-by: Niteesh Dubey <niteesh@us.ibm.com>
Signed-off-by: Greg Kurz <groug@kaod.org>
2025-04-17 16:53:05 +02:00
Zvonko Kaiser
497ab9faaf
Merge pull request from zvonkok/rootfs-updates
gpu: Update creation permissions
2025-04-16 10:15:38 -04:00
Wainer dos Santos Moschetta
90397ca4fe ci: demote CoCo non-TEE to non-required from gatekeeper
The CoCo non-TEE job has failed due the removal of an add-on
from AKS, causing KBS to not get installed (see ).

The fix should be done in this repo as well as in trustee, which can
take some time. We don't want to hold kata-containers PRs from getting
merged anylonger, so removing the job from required list.

Signed-off-by: Wainer dos Santos Moschetta <wainersm@redhat.com>
2025-04-15 19:00:30 -03:00
Wainer Moschetta
ff9fb19f11
Merge pull request from ldoktor/e2e-resources
ci.ocp: Override default runtimeclass CPU resources
2025-04-15 10:33:35 -03:00
Lukáš Doktor
bfdf4e7a6a
ci.ocp: Add peer-pods setup script
this script will be used in a new OCP integration pipeline to monitor
basic workflows of OCP+peer-pods.

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-04-15 12:13:22 +02:00
Xynnn007
91bb6b7c34 runtime: add support for io.katacontainers.config.runtime.cc_init_data
io.katacontainers.config.runtime.cc_init_data specifies initdata used by
the pod in base64(gzip(initdata toml)) format. The initdata will be
encapsulated into an initdata image and mount it as a raw block device
to the guest.

The initdata image will be aligned with 512 bytes, which is chosen as a
usual sector size supported by different hypervisors like qemu, clh and
dragonball.

Note that this patch only adds support for qemu hypervisor.

Signed-off-by: Xynnn007 <xynnn@linux.alibaba.com>
2025-04-15 16:35:59 +08:00
Sumedh Sharma
2a17628591 genpolicy: Add container_id & related policy container data to state.
This commit adds changes to add input container_id and related
container data to state after a CreateContainerRequest is allowed. This
helps constrain reference container data for evaluating request
inputs to one instead of matching against every policy container data,
Ex: in ExecProcessRequest inputs.

Fixes 

Signed-off-by: Sumedh Sharma <sumsharma@microsoft.com>
2025-04-15 14:02:59 +05:30
Zvonko Kaiser
2f28be3ad9 gpu: Update creation permissions
We need to make sure the device files are created correctly
in the rootfs otherwise kata-agent will apply permission 0o000.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-04-14 21:02:34 +00:00
Fabiano Fidêncio
bfd4b98355
Merge pull request from fidencio/topic/build-scripts-improvements-for-users
build: User-facing improvements for the build scripts
2025-04-14 19:28:12 +02:00
Fabiano Fidêncio
5e363dc277 virtiofsd: Update to v1.13.1
It's been released for some time already ... and although we did have
the necessary patches in, we better to stick to a released version of
the project.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-14 13:23:31 +02:00
Fabiano Fidêncio
2fef594f14 build: Allow users to define AGENT_POLICY
This is mostly used for Kata Containers backing up Confidential
Computing use cases, this also has benefits for the normal Kata
Containers use cases, this it's left enabled by default.

However, let's allow users to specify whether or not they want to have
it enabled, as depending on their use-case, it just does not make sense.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-14 10:02:22 +02:00
Fabiano Fidêncio
5d0688079a build: Allow users to specificy EXTRA_PKGS
Right now we've had some logic to add EXTRA_PKGS, but those were
restrict to the nvidia builds, and would require changing the file
manually.

Let's make sure a user can add this just by specifying an env var.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-14 10:02:22 +02:00
Fabiano Fidêncio
40a15ac760 build: Allow adding a guest-hook to the rootfs
Kata Containers provides, since forever, a way to run OCI guest-hooks
from the rootfs, as long as the files are dropped in a specific location
defined in the configuration.toml.

However, so far, it's been up to the ones using it to hack the generated
image in order to add those guest hooks, which is far from handy.

Let's add a way for the ones interested on this feature to just drop a
tarball file under the same known build directory, spcificy an env var,
and let the guest hooks be installed during the rootfs build.

Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-14 10:02:16 +02:00
RuoqingHe
0b4fea9382
Merge pull request from stevenhorsman/rust-toolchain
rust: Add rust-toolchain.toml
2025-04-12 15:03:29 +08:00
Steve Horsman
792180a740
Merge pull request from stevenhorsman/required-tests-process-update
doc: Update required job process
2025-04-11 14:53:27 +01:00
stevenhorsman
93830cbf4d rust: Add rust-toolchain.toml
Add a top-level rust-toolchain.toml with the version
that matches version.yaml to ensure that we stay in sync

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-11 09:24:04 +01:00
Steve Horsman
ad68cb9afa
Merge pull request from stevenhorsman/rust-workspace-settings
agent: Inherit rust workspace settings
2025-04-10 09:47:53 +01:00
Xynnn007
17d0db9865 agent: add initdata parse logic
Kata-agent now will check if a device /dev/vd* with 'initdata' magic
number exists. If it exists, kata-agent will try to read it. Bytes 9~16
are the length of the compressed initdata toml in little endine.
Bytes starting from 17 is the compressed initdata.

The initdata image device layout looks like

0        8      16    16+length ...         EOF
'initdata'  length gzip(initdata toml) paddings

The initdata will be parsed and put as aa.toml, cdh.toml and
policy.rego to /run/confidential-containers/initdata.

When AgentPolicy is initialized, the default policy will be overwritten
by that.

When AA is to be launched, if initdata is once processed, the launch arg
will include --initdata parameter.

Also, if
/run/confidential-containers/initdata/aa.toml exists, the launch args
will include -c /run/confidential-containers/initdata/aa.toml.

When CDH is to be launched, if initdata is once processed, the launch
args will include -c /run/confidential-containers/initdata/cdh.toml

Signed-off-by: Xynnn007 <xynnn@linux.alibaba.com>
2025-04-10 13:09:51 +08:00
stevenhorsman
75dc4ce3bf doc: Update required job process
Add information about using required-tests.yaml
as a way to track jobs that are required.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 18:13:45 +01:00
Steve Horsman
0dbf4ec39f
Merge pull request from stevenhorsman/update-gatekeeper-rules-for-md-only-PRs
ci: Update gatekeeper tests for md files
2025-04-09 18:10:05 +01:00
stevenhorsman
d1d60cfe89 ci: Update gatekeeper tests for md files
Update the required-tests.yaml so that .md files only
trigger the static tests, not the build, or CI

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 17:55:27 +01:00
Steve Horsman
9b401cd250
Merge pull request from stevenhorsman/required-test-updates
ci: required-tests fixes/updates
2025-04-09 14:41:57 +01:00
stevenhorsman
576747b060 ci: Skip tests if we only update the required list
When making new tests required, or removing existing tests
from required, this doesn't impact the CI jobs, so we don't need
to run all the tests.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 14:22:47 +01:00
stevenhorsman
9a7c5b914e ci: required-tests fixes/updates
- Remove metrics setup job
- Update some truncation typos of job names
- Add shellcheck-required
- Remove the ok-to-test as a required label on the build test
as it isn't needed as a trigger

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 14:22:37 +01:00
Xuewei Niu
5774f131ec
Merge pull request from Apokleos/fix-iommugrp-symlink
runtime-rs: Simplify iommu group base name extraction from symlink
2025-04-09 19:23:48 +08:00
Xuewei Niu
fd9a4548ab
Merge pull request from RuoqingHe/entend-runtime-rs-workspace
runtime-rs: Extend runtime-rs workspace and centralize local dependencies
2025-04-09 19:23:15 +08:00
stevenhorsman
6603cf7872 agent: Update vsock-exporter to use workspace settings
To reduce duplication, we could update
the vsock-exporter crate to use settings and versions
 from the agent, where applicable.
> [!NOTE]
> In order to use the workspace, this has bumped some crate versions

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 12:02:43 +01:00
stevenhorsman
2cb9fd3c69 agent: Update rustjail to use workspace settings
- To reduce duplication, we could update
the rustjail crate to use settings and versions
from the agent, where applicable.
- Also switch to using the derive feature in serde crate
rather than the separate serde_derive to avoid keeping
both versions in sync

> [!NOTE]
> In order to use the workspace, this has bumped
some crate versions

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 12:02:43 +01:00
stevenhorsman
655255b50c agent: Update policy to use workspace settings
To reduce duplication, we could update
the policy crate to use settings and versions
from the agent, where applicable.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 11:42:05 +01:00
stevenhorsman
1bec432ffa agent: Create workspace package and dependencies
- Create agent workspace dependencies and packge info
so that the packages in the workspace can use them
- Group the local dependencies together for clarity
(like in )

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-09 11:42:00 +01:00
Ruoqing He
28c09ae645 runtime-rs: Put local dependencies into workspace
Put local dependencies into workspace to avoid complex path dependencies all
over the workspace. This gives an overview of local dependencies this workspace
uses, where those crates are located, and simplifies the local dependencies
referencing process.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-04-09 07:30:29 +00:00
Ruoqing He
3769ad9c0d runtime-rs: Group local dependencies
Judging by the layout of the `Cargo.toml` files, local dependencies are
intentionally separated from other dependencies, let's enforce it
workspace-wise.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-04-09 03:52:16 +00:00
Ruoqing He
abb5fb127b runtime-rs: Extend workspace to cover all crates
Only `shim` and `shim-ctl` are incorporated in `runtime-rs`'s workspace, let's
extend it to cover all crates in `runtime-rs/crates`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-04-09 03:51:48 +00:00
alex.lyn
58bebe332a runtime-rs: Simplify iommu group base name extraction from symlink
Just get base name from iommu group symlink is enough. As the
validation will be handled in subsequent steps when constructing
the full path /sys/kernel/iommu_groups/$iommu_group.

In this PR, it will remove dupicalted validation of iommu_group.

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-09 09:28:00 +08:00
Steve Horsman
8df271358e
Merge pull request from stevenhorsman/disable-metrics-jobs
ci: Remove metric jobs
2025-04-08 18:16:35 +01:00
stevenhorsman
e6cca9da6d ci: Remove metric jobs
The metrics runner is broken, so skip the metrics
jobs to stop the CI being stuck waiting.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-04-08 17:55:07 +01:00
RuoqingHe
713cbb0c62
Merge pull request from fidencio/topic/bump-kernel-lts
versions: Bump LTS kernel
2025-04-08 17:28:31 +08:00
Xuewei Niu
d3c9cc4e36
Merge pull request from teawater/mem-agent-doc
docs: Add how-to-use-memory-agent.md to howto
2025-04-08 17:20:25 +08:00
Fabiano Fidêncio
a40b919afe
Merge pull request from likebreath/0109/upgrade_clh_v43.0
versions: Upgrade to Cloud Hypervisor v45.0
2025-04-08 08:11:30 +02:00
Fabiano Fidêncio
bc04c390bd versions: Bump LTS kernel
6.12.22 has been released Yesterday, let's bump to it.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-04-07 21:46:29 +02:00
Bo Chen
ee84068aed versions: Upgrade to Cloud Hypervisor v45.0
Details of this release can be found in our roadmap project as iteration
v45.0: https://github.com/orgs/cloud-hypervisor/projects/6.

Fixes: 

Signed-off-by: Bo Chen <bchen@crusoe.ai>
Signed-off-by: Fabiano Fidêncio <fidencio@northflank.com>
2025-04-07 20:33:34 +02:00
Dan Mihai
8779abd0a1
Merge pull request from mythi/tdx-qgs-uds
runtime: qemu: add support to use TDX QGS via Unix Domain Sockets
2025-04-07 07:27:48 -07:00
Dan Mihai
e606a8deb5
Merge pull request from Ankita13-code/ankitapareek/policy-input-validation
policy: Add missing input validations for ExecProcessRequest
2025-04-07 07:26:24 -07:00
Steve Horsman
ba92639481
Merge pull request from RuoqingHe/2025-03-28-enable-riscv-assets-build
ci: Enable `build-kata-static-tarball-riscv64.yaml`
2025-04-07 11:26:15 +01:00
Fabiano Fidêncio
c75ea2582e
Merge pull request from fidencio/topic/allow-building-the-agent-without-enabling-guest-pull
agent: Allow users to build without guest-pull
2025-04-06 12:17:27 +01:00
Fabiano Fidêncio
e3c98a5ac7 agent: Allow users to build without guest-pull
For those not interested in CoCo, let's at least allow them to easily
build the agent without the guest-pull feature.

This reduces the binary size (already stripped) from 25M to 18M.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-04-04 22:58:43 +01:00
Ankita Pareek
7e450bc1c2 policy: Add missing input validations for ExecProcessRequest
This commit introduces missing validations for input fields in ExecProcessRequest to
harden the security policy.

The changes include:
- Update rules.rego to add null/empty field enforcements for String_user, SelinuxLabel and ApparmorProfile
- Add unit test cases for ExecProcessRequest for each of the validations

Signed-off-by: Ankita Pareek <ankitapareek@microsoft.com>
2025-04-03 12:53:59 +00:00
Hui Zhu
17af28acad docs: Add how-to-use-memory-agent.md to howto
Add how-to-use-memory-agent.md (How to use mem-agent to decrease the
memory usage of Kata container) to docs to show how to use mem-agent.

Fixes: 

Signed-off-by: Hui Zhu <teawater@gmail.com>
2025-04-02 17:45:59 +08:00
Lukáš Doktor
009aa6257b
ci.ocp: Override default runtimeclass CPU resources
some of the e2e tests spawn a lot of workers which are mainly idle, but
the scheduler fails to schedule them due to cpu resource overcommit. For
our testing we are more focused on having actual pods running than the
speed of the scheduled pods so let's increase the amount of schedulable
pods by decreasing the default cpu requests.

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-04-02 10:30:40 +02:00
RuoqingHe
2f134514b0
Merge pull request from kimullaa/robust-user-input
kata-deploy: add INSTALLATION_PREFIX validation
2025-04-02 10:05:03 +08:00
Ruoqing He
96e43fbee5 ci: Enable build-kata-static-tarball-riscv64.yaml
Previously we introduced `build-kata-static-tarball-riscv64.yaml`,
enable that workflow in `ci.yaml`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-04-01 16:35:14 +08:00
RuoqingHe
10ceeb0930
Merge pull request from fidencio/topic/kata-deploy-create-runtimeclasses-by-default
kata-deploy: Create runtimeclasses by default
2025-04-01 10:55:44 +08:00
RuoqingHe
b19a8c7b1c
Merge pull request from kimullaa/update-command-sample
kernel: Update the usage in readme
2025-04-01 09:12:43 +08:00
RuoqingHe
b046f79d06
Merge pull request from kimullaa/remove-double-slash
kata-deploy: remove the double "/"
2025-04-01 08:17:00 +08:00
Shunsuke Kimura
a05f5f1827 kata-deploy: add INSTALLATION_PREFIX validation
INSTALLATION_PREFIX must begin with a "/"
because it is being concatenated with /host.

If there is no /, displays a message and makes an error.

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-04-01 06:47:30 +09:00
Shunsuke Kimura
a49b6f8634 kata-deploy: Moves the function to the top
Move functions that may be used in validation to the top.

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-04-01 06:47:30 +09:00
Zvonko Kaiser
d81a1747bd
Merge pull request from kevinzs2048/fix-virtiomem
runtime-go: qemu: Fix sandbox start failing with virtio-mem enable on arm64
2025-03-31 17:09:43 -04:00
Zvonko Kaiser
e5c4cfb8a1
Merge pull request from BbolroC/unsealed-secret-fix
tests: Enable sealed secrets for all TEEs
2025-03-31 11:19:52 -04:00
Shunsuke Kimura
c0af0b43e0 kernel: Update the outdated usage in the readme
Since it is difficult to update the README when modifying the options of ./build-kernel.sh,
instead of update the README, we encourage users to run the -h command.

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-03-31 23:29:58 +09:00
Shunsuke Kimura
902cb5f205 kata-deploy: remove the double "/"
Currently, ConfigPath in containerd.toml is a double "/" as follows.

```
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-clh.options]
ConfigPath = "/opt/kata/share/defaults/kata-containers//configuration-clh.toml"
...
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-cloud-hypervisor.options]
ConfigPath = "/opt/kata/share/defaults/kata-containers//runtime-rs/configuration-cloud-hypervisor.toml"
...
```

So, removed the double "/".

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-03-31 22:31:36 +09:00
Fabiano Fidêncio
28be53ac92 kata-deploy: Create runtimeclasses by default
Let's make the life of the users easier and create the runtimeclasses
for them by default.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-31 11:29:44 +01:00
Xuewei Niu
abbc9c6b50
Merge pull request from RuoqingHe/runtime-rs-fix-fmt-check
runtime-rs: Remove redundant empty line
2025-03-31 16:28:55 +08:00
Ruoqing He
3c78c42ea5 runtime-rs: Remove redundant empty line
While running `cargo fmt -- --check` in `src/runtime-rs` directory, it
errors out and suggesting these is an redundant empty line, which
prevents `make check` of `runtime-rs` component from passing.

Remove redundant empty line to fix this.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-31 00:39:04 +08:00
Steve Horsman
44bab5afc4
Merge pull request from fidencio/topic/ci-add-kata-deploy-tests-as-required
gatekeeper: Add kata-deploy tests as required
2025-03-28 11:05:03 +00:00
Fabiano Fidêncio
5a08d748b9
Merge pull request from kimullaa/fix-cleanup-failure
kata-deploy: Fix kata-cleanup's CrashLoopBackOff
2025-03-27 20:33:52 +01:00
Fabiano Fidêncio
700944c420 gatekeeper: Add kata-deploy tests as required
kata-deploy tests have been quite stable, working for more than 10 days
without any nightly failure (or any failure reported at all), and I'll
be the one maintaining those.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-27 19:47:38 +01:00
Steve Horsman
97bd311a66
Merge pull request from stevenhorsman/required-static-checks-rename
ci: Update static-checks strings
2025-03-27 12:56:28 +00:00
Xuewei Niu
54dcf0d342
Merge pull request from RuoqingHe/runtime-qemu-riscv
runtime: Support and enable build on riscv64
2025-03-27 17:02:21 +08:00
Fabiano Fidêncio
047b7e1fb7
Merge pull request from lifupan/fix_compile
runtime-rs: update the protobuf to 3.7.1
2025-03-27 09:52:20 +01:00
Fabiano Fidêncio
41b536d487
Merge pull request from microsoft/danmihai1/tests-common
tests: k8s: clean-up shellcheck warnings in tests_common.sh
2025-03-27 09:51:49 +01:00
Shunsuke Kimura
9ab6ab9897 kata-deploy: Fix kata-cleanup's CrashLoopBackOff
Since kata-deploy.sh references an undefined variable,
kata-cleanup.yaml enters a CrashLoopBackOff state.

```
$ kubectl apply -f https://raw.githubusercontent.com/kata-containers/kata-containers/main/tools/packaging/kata-deploy/kata-cleanup/base/kata-cleanup.yaml
daemonset.apps/kubelet-kata-cleanup created

$ kubectl get pods -n kube-system
kubelet-kata-cleanup-zzbd2        0/1     CrashLoopBackOff   3 (33s ago)     80s

$ kubectl logs -n kube-system daemonsets/kubelet-kata-cleanup
/opt/kata-artifacts/scripts/kata-deploy.sh: line 19: SHIMS: unbound variable
```

Therefore, set an initial value for the environment variables.

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-03-27 15:00:19 +09:00
Hyounggyu Choi
0432d2fcdf
Merge pull request from BbolroC/fix-overwrite-containerd-config
tests: Make sure /etc/containerd before writing config
2025-03-27 05:57:31 +01:00
Ruoqing He
46caa986bb ci: Skip tests depend on virtualization on riscv64
`VMContainerCapable` requires a present `kvm` device, which is not yet
available in our RISC-V runners. Skipped related tests if it is running
on `riscv-builder`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:47:49 +08:00
Ruoqing He
7f0b1946c5 ci: Enable build-check for runtime on riscv64
`runtime` support for riscv64 is now ready, let enable building and
testing on that component.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:38:30 +08:00
Yuting Nie
1f52f83309 runtime: Enable kata-check test on riscv64
Provide according tests to cover `kata-runtime` package, test
`kata-runtime`'s `check` functionality on riscv64 platforms.

Signed-off-by: Yuting Nie <nieyuting@iscas.ac.cn>
2025-03-27 10:36:55 +08:00
Yuting Nie
b6924ef5e5 runtime: Add getExpectedHostDetails for riscv64
Add `getExpectedHostDetails` with expected value according to template
defined in `kata-check_data_riscv64_test.go`. This provides necessary
`HostInfo` for tests to cover `kata-check_riscv64.go`.

Signed-off-by: Yuting Nie <nieyuting@iscas.ac.cn>
2025-03-27 10:34:34 +08:00
Yuting Nie
594c5e36a6 runtime: Add mock data for kata-check
Add definition of `testCPUInfoTemplate` which is retrieved from
`/proc/cpuinfo` of a QEMU emulated virtual machine on virt board.

Signed-off-by: Yuting Nie <nieyuting@iscas.ac.cn>
2025-03-27 10:33:42 +08:00
Yuting Nie
0ff5cb1e66 runtime: Enable testSetCPUTypeGeneric for riscv64
`testSetCPUTypeGeneric` will be used for writting `kata-check` in
`kata-runtime` on riscv64 platforms, enable building for later testing.

Signed-off-by: Yuting Nie <nieyuting@iscas.ac.cn>
2025-03-27 10:32:29 +08:00
Ruoqing He
2329aeec38 runtime: Disable race flag for riscv64
`-race` flag used for `go test` is not yet supported on riscv64
platforms, disable it for now.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:28:53 +08:00
Ruoqing He
1b4dbebb1b runtime: Enable runtime to build on riscv64
Convert Rust arch to Go arch in Makefile, and add `riscv64-options.mk`
to provide definitions required for runtime to build on riscv64.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:22:55 +08:00
Ruoqing He
805da14634 runtime: Enable runtime check for riscv64
Enable `kata-runtime check` command to work on riscv64 platforms to make
sure required features/devices presents.

Co-authored-by: Yuting Nie <nieyuting@iscas.ac.cn>
Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:07:09 +08:00
Ruoqing He
96b2d25508 runtime: Define default values for QEMU riscv
Provide default values while invoking QEMU as the hypervisor for Go
runtime on riscv64 platform.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 10:05:36 +08:00
Ruoqing He
1662595146 runtime: Introduce riscv64 to govmm pkg
Define `vmm` for riscv64, set `MaxVCPUs` to 512 as QEMU RISC-V virt
Generic Virtual Platform [1] define.

[1] https://www.qemu.org/docs/master/system/riscv/virt.html

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 09:57:49 +08:00
Ruoqing He
1e4963a3b2 runtime: Define availableGuestProtection for riscv64
`GuestProtection` feature is not made available yet, return
`noneProtection` for now.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 09:34:53 +08:00
Ruoqing He
4947938ce8 runtime: Introduce riscv64 template for vm factory
Set `templateDeviceStateSize` to 8 as other architectures did.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-27 09:28:32 +08:00
Zvonko Kaiser
b7cf4fd2e6
Merge pull request from ldoktor/ci
ci: shellcheck fixes
2025-03-26 13:22:56 -04:00
Hyounggyu Choi
1e187482d4 tests: Make sure /etc/containerd before writing config
We get the following error while writing containerd config
if a base dir `/etc/containerd` does not exist like:

```
sudo tee /etc/containerd/config.toml << EOF
...
EOF
tee: /etc/containerd/config.toml: No such file or directory
```

The commit makes sure a base directory for containerd before
writing config and drops the config file deletion because a
default behaviour of `tee` is overwriting.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-26 18:19:45 +01:00
Hyounggyu Choi
0aa76f7206 tests: Enable sealed secrets for TEEs
Fixes: 

This commit allows all TEEs to run the sealed secret test.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-26 17:50:41 +01:00
Hyounggyu Choi
423ad8341d agent: Call cdh_handler for sealed secrets after add_storage()
As reported in , mounted secrets are available after
a container image is pulled by add_storage() for IBM SE.
But secure mount should be handled before the `add_storage()`.
Therefore, this commit divides cdh_handler() into:

- cdh_handler_trusted_storage()
- cdh_handler_sealed_secrets()

and calls cdh_handler_sealed_secrets() after add_storage()
while keeping cdh_handler_trusted_storage() unchanged.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-26 17:50:41 +01:00
Fabiano Fidêncio
7a0ac55f22
Merge pull request from fidencio/topic/tests-kata-deploy-ground-work-to-rewrite-the-tests
tests: kata-deploy: The rest of the ground work to rewrite the kata-deploy tests
2025-03-26 17:47:48 +01:00
Hyounggyu Choi
8088064b8b tests: Set default policy before running sealed secrets tests
The test `Cannot get CDH resource when deny-all policy is set`
completes with a KBS policy set to deny-all. This affects the
future TEE test (e.g. k8s-sealed-secrets.bats) which makes a
request against KBS.
This commit introduces kbs_set_default_policy() and puts it to
the setup() in k8s-sealed-secrets.bats.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-26 17:44:38 +01:00
Kevin Zhao
211a36559c runtime-go: qemu: Fix sandbox start failing with virtio-mem enable on arm64
Also add CONFIG_VIRTIO_MEM to arm64 platform

Signed-off-by: Kevin Zhao <kevin.zhao@linaro.org>
2025-03-26 22:31:00 +08:00
Fabiano Fidêncio
404e212102 tests: kata-deploy: Use helm_helper()
With this we switch to fully testing with helm, instead of testimg with
the kustomizations (which will soon be removed).

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-26 13:30:15 +01:00
Fabiano Fidêncio
f7976a40e4 tests: Create a helm_helper() common function
Let's use what we have in the k8s functional tests to create a common
function to deploy kata containers using our helm charts.  This will
help us immensely in the kata-deploy testing side in the near future.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-26 13:30:11 +01:00
Fabiano Fidêncio
eb884d33a8 tests: k8s: Export all the default env vars on gha-run.sh
This is not strictly needed, but it does help a lot when setting up a
cluster manually, while still relying on those scripts.

While here, let's also ensure the assignment is between quotes, to make
shellchecker happier.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-26 13:23:16 +01:00
Saul Paredes
ae5c587efc
Merge pull request from Sumynwa/sumsharma/genpolicy_test
genpolicy: Refactor tests to allow different request types in a testcases json.
2025-03-25 12:38:19 -07:00
Sumedh Sharma
3406df9133 genpolicy: Refactor tests to add different request types in testcases json
This commit introduces changes to add test data for multiple request
type in a single testcases.json file. This allows for stateful testing,
for ex: enable testing ExecProcessRequest using policy state set after testing
a CreateContainerRequest.

Fixes .

Signed-off-by: Sumedh Sharma <sumsharma@microsoft.com>
2025-03-25 13:52:17 +05:30
Mikko Ylinen
85f3391bcf runtime: qemu: add support to use TDX QGS via Unix Domain Sockets
TDX Quote Generation Service (QGS) signs TDREPORT sent to it from
Qemu (GetQuote hypercall). Qemu needs quote-generation-socket
address configured for IPC.

Currently, Kata govmm only enables vsock based IPC for QGS but
QGS supports Unix Domain Sockets too which works well for host
process to process IPC (Qemu <-> QGS).

The QGS configuration to enable UDS is to run the service with "-port=0"
parameter. The same works well here too: setting
"tdx_quote_generation_service_socket_port=0" let's users to enable
UDS based IPC.

The socket path is fixed in QGS and cannot be configured: when "-port=0"
is used, the socket appears in /var/run/tdx-qgs/qgs.socket.

Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
2025-03-25 10:18:40 +02:00
RuoqingHe
7a704453b6
Merge pull request from microsoft/danmihai1/genpolicy-debug-build
genpolicy: add support for BUILD_TYPE=debug
2025-03-25 14:59:15 +08:00
RuoqingHe
5d68600c06
Merge pull request from stevenhorsman/metrics-containerd-debugging
metrics: Test improvements
2025-03-25 11:38:28 +08:00
Dan Mihai
15c9035254 genpolicy: add support for BUILD_TYPE=debug
Use "cargo build --release" when BUILD_TYPE was not specified, or when
BUILD_TYPE=release. The default "cargo build" behavior is to build in
debug mode.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-24 16:10:20 +00:00
RuoqingHe
f6a1c6d0e0
Merge pull request from kimullaa/exit-if-action-is-invalid
kata-deploy: return exit code for invalid argument
2025-03-24 09:40:39 +08:00
Shunsuke Kimura
e5d7414c33 kata-deploy: Return exit code for invalid argument
It hangs when invalid arguments are specified.

```bash
kata-deploy-6sr2p:/# /opt/kata-artifacts/scripts/kata-deploy.sh xxx
Action:
* xxx
...
Usage: /opt/kata-artifacts/scripts/kata-deploy.sh [install/cleanup/reset]
ERROR: invalid arguments
...
^C <- hang
```

I changed it to behave the same as when there are no arguments.

```bash
kata-deploy-6sr2p:/# /opt/kata-artifacts/scripts/kata-deploy.sh
Usage: /opt/kata-artifacts/scripts/kata-deploy.sh [install/cleanup/reset]
ERROR: invalid arguments
kata-deploy-6sr2p:/# echo $?
1
```

Fixes: 

Signed-off-by: Shunsuke Kimura <pbrehpuum@gmail.com>
2025-03-22 21:32:38 +09:00
Aurélien Bombo
17baa6199b
Merge pull request from RuoqingHe/2025-03-21-generalize-non-kvm
ci: Generalize `GITHUB_RUNNER_CI_ARM64`
2025-03-21 15:23:51 -05:00
Fupan Li
4b93176225 runtime-rs: update the protobuf to 3.7.1
Since some files generated by protobuf were share between
runtime-rs and kata agent, and the kata agent's dependency
image-rs dependened protobuf@3.7.1, thus we'd better to keep
the protobuf version aligned between runtime-rs and agent,
otherwise, we couldn't compile the runtime-rs and agent
at the same time.

Fixes: https://github.com/kata-containers/kata-containers/issues/10650

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-21 17:46:12 +08:00
Ruoqing He
5e81f67ceb ci: Generalize GITHUB_RUNNER_CI_ARM64
`GITHUB_RUNNER_CI_ARM64` is turned on for self hosted runners without
virtualization to skipped those tests depend on virtualization. This may
happen to other archs/runners as well, let's generalize it to
`GITHUB_RUNNER_CI_NON_VIRT` so we can reuse it on other archs.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-21 09:49:44 +08:00
RuoqingHe
e84f7c2c4b
Merge pull request from mythi/drop-dcap-libs
build: drop libtdx-attest
2025-03-21 09:23:33 +08:00
Dan Mihai
835c6814d7 tests: k8s/tests_common: avoid using regex
More straightforward implementation of hard_coded_policy_tests_enabled,
that avoids ShellCheck warning:

warning: Remove quotes from right-hand side of =~ to match as a regex rather than literally. [SC2076]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 22:23:19 +00:00
Dan Mihai
d83b8349a2 tests: policy: avoid using caller's variable
Fix unintended use of caller's variable. Use the corresponding function
parameter instead. ShellCheck:

warning: policy_settings_dir is referenced but not assigned. [SC2154]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:29 +00:00
Dan Mihai
59a70a2b28 tests: k8s/tests_common: avoid masking return values
Avoid masking command return values by declaring and only then assigning.

ShellCheck:

warning: Declare and assign separately to avoid masking return values. [SC2155]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:29 +00:00
Dan Mihai
b895e3b3e5 tests: k8s/tests_common.sh: add variable assignments
Pick the the values exported by other scripts. ShellCheck:

warning: AUTO_GENERATE_POLICY is referenced but not assigned. [SC2154]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:29 +00:00
Dan Mihai
0f4de1c94a tests: tests_common: remove useless assignment
ShellCheck:

warning: This assignment is only seen by the forked process. [SC2097]
warning: This expansion will not see the mentioned assignment. [SC2098]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:29 +00:00
Dan Mihai
9c0d069ac7 tests: tests_common: prevent globbing and word splitting
ShellCheck:

note: Double quote to prevent globbing and word splitting. [SC2086]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
15961b03f7 tests: k8s/tests_common.sh: -n instead of ! -z
ShellCheck:

note: Use -n instead of ! -z. [SC2236]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
4589dc96ef tests: k8s/tests_common.sh: add double quoting
ShellCheck:

note: Prefer double quoting even when variables don't contain special characters. [SC2248]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
cc5f8d31d2 tests: k8s/tests_common.sh: add braces
ShellCheck: add braces around variable references:

note: Prefer putting braces around variable references even when not strictly required. [SC2250]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
0d3f9fcee1 tests: tests_common: export variables used externally
ShellCheck: export variables used outside of tests_common.sh - e.g.,

warning: timeout appears unused. Verify use (or export if used externally). [SC2034]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
5df43ffc7c tests: k8s/tests_common.sh: Prefer [[ ]] over [ ]
Replace [ ] with [[ ]] as advised by shellcheck:

note: Prefer [[ ]] over [ ] for tests in Bash/Ksh. [SC2292]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-20 19:02:28 +00:00
Dan Mihai
f79fabab24
Merge pull request from microsoft/danmihai1/empty-exec-output
tests: k8s: retry "kubectl exec" on empty output
2025-03-20 11:03:08 -07:00
stevenhorsman
70d32afbb7 ci: Remove metrics tests from required list
The metrics tests haven't been stable, or required through
github for many week now, so update the required-tests.yaml
list to re-sync

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-20 16:03:03 +00:00
stevenhorsman
607b27fd7f ci: Update static-checks strings
With the refactor in  the names of
the static checks has changed, so update these.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-20 13:45:57 +00:00
Mikko Ylinen
f52a565834 build: drop libtdx-attest
with the latest CoCo guest-components, tdx-attester no longer
depends on libtdx attest. Stop installing it to the rootfs.

Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
2025-03-20 10:45:30 +02:00
Steve Horsman
c0632f847f
Merge pull request from stevenhorsman/3.15.0-release
release: Bump version to 3.15.0
2025-03-20 07:38:20 +00:00
Greg Kurz
e19b81225c
Merge pull request from kata-containers/sprt/fix-gha-tag
security: ci: Pin third-party actions to commit hashes
2025-03-20 08:14:06 +01:00
Aurélien Bombo
a678046d13 gha: Pin third-party actions to commit hashes
A popular third-party action has recently been compromised [1][2] and
the attacker managed to point multiple git version tags to a malicious
commit containing code to exfiltrate secrets.

This PR follows GitHub's recommendation [3] to pin third-party actions
to a full-length commit hash, to mitigate such attacks.

Hopefully actionlint starts warning about this soon [4].

 [1] https://www.cve.org/CVERecord?id=CVE-2025-30066
 [2] https://www.stepsecurity.io/blog/harden-runner-detection-tj-actions-changed-files-action-is-compromised
 [3] https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions#using-third-party-actions
 [4] https://github.com/rhysd/actionlint/pull/436

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-19 13:52:49 -05:00
stevenhorsman
fad248ef09 release: Bump version to 3.15.0
Bump VERSION and helm-chart versions

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-19 17:28:06 +00:00
Fabiano Fidêncio
a6e5d28a15
Merge pull request from stevenhorsman/bump-github.com/containerd/containerd/v1.7.27
runtime: Update github.com/containerd/containerd
2025-03-19 18:19:10 +01:00
stevenhorsman
cb7c599180 runtime: Switch from deprecated tracer
`go.opentelemetry.io/otel/trace.NewNoopTracerProvider`
is deprectated now, so switch to
`go.opentelemetry.io/otel/trace/noop.NewTracerProvider`

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-19 14:22:06 +00:00
stevenhorsman
8f22b07aba runtime: Update github.com/containerd/containerd
Update to 1.7.27 to resolve CVE-2024-40635

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-19 13:48:04 +00:00
Lukáš Doktor
d708866b2a
ci.ocp: shellcheck various fixes
various manual fixes.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:28 +01:00
Lukáš Doktor
7e11489daf
ci: shellcheck - collection of fixes
manual fixes of various issues.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:23 +01:00
Lukáš Doktor
f62e08998c
ci: shellcheck - remove unused argument
the "-a" argument was introduced with this tool but never was actually
used.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:19 +01:00
Lukáš Doktor
02deb1d782
ci: shellcheck SC2248
SC2248 (style): Prefer double quoting even when variables don't contain
special characters, might result in arguments difference, shouldn't in
our cases.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:16 +01:00
Lukáš Doktor
d80e7c7644
ci: shellcheck SC2155
SC2155 (warning): Declare and assign separately to avoid masking return
values, should be harmless.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:12 +01:00
Lukáš Doktor
6552ac41e0
ci: shellcheck SC2086
SC2086 Double quote to prevent globbing and word splitting, might break
places where we deliberately use word splitting, but we are not using it
here.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:08 +01:00
Lukáš Doktor
154a4ddc00
ci: shellcheck SC2292
SC2292 (style): Prefer [[ ]] over [ ] for tests in Bash/Ksh. This might
result in different handling of globs and some ops which we don't use.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:26:03 +01:00
Lukáš Doktor
667e26036c
ci: shellcheck SC2250
Treat the SC2250 require-variable-braces in CI. There are no functional
changes.

Related to: 

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-03-19 12:25:44 +01:00
Zvonko Kaiser
d37d9feee9
Merge pull request from kata-containers/sprt/fix-dependabot
security: ci: Remove `replace` directives in go.mod files
2025-03-18 12:43:46 -04:00
Steve Horsman
ba5b0777b5
Merge pull request from fitzthum/bump-gc-0130
Bump Trustee and Guest Components for coco v0.13.0
2025-03-17 16:31:23 +00:00
RuoqingHe
36d2dee3a4
Merge pull request from RuoqingHe/runtime-rs-riscv
runtime-rs: Support and enable build on riscv64
2025-03-17 21:42:15 +08:00
Ruoqing He
cb7508ffdc ci: Enable runtime-rs component build-check on riscv64
`runtime-rs` is now buildable and testable on riscv64 platforms, enable
`build-check` on `runtime-rs`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-17 17:38:59 +08:00
Steve Horsman
f308cbba93
Merge pull request from AdithyaKrishnan/main
CI: Mark SNP as a Required test
2025-03-17 09:27:28 +00:00
Ruoqing He
084fb2d780 runtime-rs: Enable RISC-V build
Define `riscv64gc-options.mk` to enable `runtime-rs` to be built on
RISC-V platforms.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-17 17:22:48 +08:00
Ruoqing He
fd6c16e209 kata-sys-util: Set NoProtection for riscv64
`available_guets_protection` is required for `runtime-rs` to infer while
building it on riscv64 platforms. Set it to `NoProtection` as riscv64
does not support guest protection for now.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-17 17:22:48 +08:00
Aurélien Bombo
26bd7989b3 csi-kata-directvolume: Remove replace in go.mod
Running `go mod tidy` and `go mod vendor` after this resulted in no-ops.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Aurélien Bombo
b965fe8239 tests: Run go mod vendor
`go mod tidy` was a no-op.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Aurélien Bombo
e9f88757ba tests: Remove replace directives in go.mod
Same rationale as for runtime. With tests, the blackfriday replacement was
actually meaningful, so I refactored some imports.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Aurélien Bombo
35c92aa6ad runtime: Run go mod vendor
Regenerating go module files.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Aurélien Bombo
fa0f85e8b0 runtime: Run go mod tidy
Tidying up go.mod.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Aurélien Bombo
c3a9c70d45 runtime: Remove replace directives in go.mod
These replace directives aren't understood by dependabot, hence dependabot can
claim to upgrade a dependency, while a replace directive still makes the
dependency point to an old version.

Fixes: 

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-03-14 18:00:36 +00:00
Adithya Krishnan Kannan
32dbee8d7e CI: Mark SNP as a Required test
The SNP CI has been consistently passing and we request the @kata-containers/architecture-committee to mark this test as a required test.

Signed-Off-By: Adithya Krishnan Kannan <AdithyaKrishnan.Kannan@amd.com>
2025-03-14 12:48:55 -05:00
Dan Mihai
dab981b0bc tests: k8s: retry "kubectl exec" on empty output
Retry "kubectl exec" a few times if it unexpectedly produced an empty
output string.

This is an attempt to work around test failures similar to:

https://github.com/kata-containers/kata-containers/actions/runs/13840930994/job/38730153687?pr=10983

not ok 1 Environment variables
(from function `grep_pod_exec_output' in file tests_common.sh, line 394,
 in test file k8s-env.bats, line 36)
`grep_pod_exec_output "${pod_name}" "HOST_IP=\([0-9]\+\(\.\|$\)\)\{4\}" "${exec_command[@]}"' failed

That test obtained correct ouput from "sh -c printenv" one time, but the
second execution of the same command returned an empty output string.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-14 17:03:03 +00:00
Tobin Feldman-Fitzthum
b7786fbcf0 agent: update image-rs for coco v0.13.0
image-rs has gotten a number of significant updates, eliminating corner
cases with obscure containers, improving support for local certs, and
more.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2025-03-14 10:44:10 -05:00
Tobin Feldman-Fitzthum
63ec1609bc versions: update guest-components for coco v0.13.0
Update to the latest hash of guest-components. This will pick up some
nice new features including using ec key for the rcar handshake.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2025-03-14 10:44:10 -05:00
Tobin Feldman-Fitzthum
c352905998 versions: bump trustee for coco v0.13.0
Update to new hashes for Trustee. The MSRV for Trustee is now 1.80.0 so
bump the rust toolchain as well.

Signed-off-by: Tobin Feldman-Fitzthum <tobin@ibm.com>
2025-03-14 10:44:04 -05:00
Steve Horsman
7968a3c09d
Merge pull request from Amulyam24/hooks
gha: use runner hooks instead of pre/post scripts for ppc64le runners
2025-03-14 15:43:27 +00:00
stevenhorsman
1022d8d260 metrics: Update range for clh tests
In ef0e8669fb we
had been seeing some significantly lower minvalues in
the jitter.Result test, so I lowered the mid-value rather
than having a very high minpercent, but it appears that the
variability of this result is very high, so we are still getting
the occasional high value, so reset the midval and just
have a bigger ranges on both sides, to try and keep the test
stable.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-14 14:54:30 +00:00
stevenhorsman
d77008b817 metrics: Further reduce repeats for boot time tests on qemu
I've seen failures on the third run, so reduce it further to
just run twice on qemu

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-14 14:53:26 +00:00
stevenhorsman
97151cce4e metrics: Improve iperf timeout
The kubectl wait has a built in timeout of 30s, so
wrapping it in waitForProcess, means we have
180/2 * 30 delay, which is much longer than intended,
so just set the timeout directly.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-14 14:53:26 +00:00
Amulyam24
becb760e32 gha: use runner hooks instead of pre/post scripts for ppc64le runners
This PR makes changes to remove steps to run scripts for
preparing and cleaning the runner and instead use runner
hooks env variables to manage them.

Fixes: 
Signed-off-by: Amulyam24 <amulmek1@in.ibm.com>
2025-03-14 17:12:54 +05:30
RuoqingHe
af4058fa82
Merge pull request from katexochen/p/config-idblock-qemu
runtime: make SNP IDBlock configurable
2025-03-14 16:23:05 +08:00
Paul Meyer
a994f142d0 runtime: make SNP IDBlock configurable
For a use case, we want to set the SNP IDBlock, which allows
configuring the AMD ASP to enforce parameters like expected launch
digest at launch. The struct with the config that should be enforced
(IDBlock) is signed. The public key is placed in the auth block and
the signature is verified by the ASP before launch. The digest of the
public key is also part of the attestation report (ID_KEY_DIGESTS).

Signed-off-by: Paul Meyer <katexochen0@gmail.com>
2025-03-14 07:50:54 +01:00
RuoqingHe
810a6dafad
Merge pull request from mchtech/fix-unbound-var
tools: initialize unbound variables in rootfs.sh
2025-03-14 08:22:05 +08:00
Saul Paredes
b7087eb0ea
Merge pull request from microsoft/cameronbaird/updateinterfacerequest-hardening-upstream
genpolicy: Introduce UpdateInterfaceRequest rules in genpolicy-settings
2025-03-13 16:12:03 -07:00
Dan Mihai
b910daf625
Merge pull request from microsoft/saulparedes/validate_generated_name_upstr
policy: validate pod generated name
2025-03-13 14:09:57 -07:00
Steve Horsman
199b16f053
Merge pull request from microsoft/danmihai1/polist-test-volume-path
tests: k8s-policy-pod: safer host path volume source
2025-03-13 20:26:06 +00:00
Dan Mihai
0e26dd4ce8 tests: k8s-policy-pod: safer host path volume source
Test using the host path /tmp/k8s-policy-pod-test instead of
/var/lib/kubelet/pods.

/var/lib/kubelet/pods might happen to contain files that CopyFileRequest
would try to send to the Guest before CreateContainerRequest. Such
CopyFileRequest was an unintended side effect of this test.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-13 18:56:57 +00:00
Cameron Baird
bceffd5ff6 genpolicy: Introduce UpdateInterfaceRequest rules in genpolicy-settings
Introduce rules for UpdateInterfaceRequest and genpolicy tests for them.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-03-13 17:30:01 +00:00
Saul Paredes
1c406e9c1d
Merge pull request from microsoft/cameronbaird/updateroutesrequest-hardening-upstream
genpolicy: Introduce UpdateRoutesRequest rules in genpolicy-settings
2025-03-13 10:11:39 -07:00
Saul Paredes
7a5db51c80 policy: validate pod generated name
Validate sandbox name using a regex. If the YAML specifies metadata.name, use a regex that exact matches.
If the YAML specifies metadata.generateName, use a regex that matches the prefix of the generated name.

Signed-off-by: Saul Paredes <saulparedes@microsoft.com>
2025-03-13 09:49:57 -07:00
Steve Horsman
e6a78e64e6
Merge pull request from stevenhorsman/coco-tests-required
ci: Add coco required tests
2025-03-13 15:10:22 +00:00
mchtech
0e61eb215d tools: initialize unbound variables in rootfs.sh
Initialize unbound variables in rootfs.sh for RHEL series OS.

Signed-off-by: mchtech <michu_an@126.com>
2025-03-13 22:57:43 +08:00
Fupan Li
592d58ca52
Merge pull request from RuoqingHe/enable-riscv-kernel-build
kernel: Support and enable riscv kernel build
2025-03-13 19:28:00 +08:00
Ruoqing He
e0fb8f08d8 ci: Add riscv-builder to actionlint.yaml
We have three SG2042 connected and labeled as `riscv-builder`, add that
entry to `actionlint.yaml` to help linting while setting up workflows.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
a7e953c7a7 ci: Enable static-tarball build for riscv64
Enable `kernel` and `virtiofsd` static-tarball build for riscv64. Since
`virtiofsd` was previously supported and `kernel` is supported now.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
3c8a8ca9c2 kernel: Enable riscv kernel build
Modify `build-kernel.sh` to enable building of riscv64 kernel.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
e316f633d8 kernel: Bump kata_config_version
Bump kata_config_version since riscv kernel build is introduced.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
31446b8be8 kernel: Skip ACPI common fragment for riscv
ACPI is not yet ratified and is still frequently evolving, disable
acpi.conf for riscv architecture.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
ebd1214b2e kernel: Introduce riscv mmu fragment conf
Memory hotplug and related features is required, enable them in
`mmu.conf`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
734f5d07a9 kernel: Introduce riscv pci fragment conf
AIA (Advanced Interrupt Architecture) is available and enabled by
default after v6.10 kernel, provide pci.conf to make proper use of IMSIC
of AIA.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Ruoqing He
19d78ca844 kernel: Introduce riscv base fragment conf
Create `riscv` folder for riscv64 architecture to be inferred while
constructing kernel configuration, and introduce `base.conf` which
builds 64-bit kernel and with KVM built-in to kernel.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-13 13:43:29 +08:00
Cameron Baird
cf129f3744 genpolicy: Introduce UpdateRoutesRequest rules in genpolicy-settings
Introduce rule to block routes from source addresses which are the
loopback. Block routes added to the lo device.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-03-12 19:03:57 +00:00
Dan Mihai
71d4ad5fca
Merge pull request from microsoft/mahuber/grpc-1-58-3
runtime: upgrade grpc vendor dependency
2025-03-12 09:23:07 -07:00
Wainer Moschetta
8c2d1b374c
Merge pull request from ldoktor/webhook
ci: Change the way we modify runtimeclass in webhook
2025-03-12 12:32:45 -03:00
RuoqingHe
386fed342c
Merge pull request from kata-containers/shell-check-vendor-skip
workflows: shellcheck: Expand vendor ignore
2025-03-12 21:34:26 +08:00
Alex Lyn
fdc0d81198
Merge pull request from teawater/swap7
runtime-rs: Add guest swap support
2025-03-12 17:59:00 +08:00
Hui Zhu
796eab3bef runtime-rs: Update swap option of configuration file
Remove swap configuration from qemu config file because runtime-rs
qemu support code doesn't support hotplug block device.
Add swap configuration to dragonball and cloud-hypervisor config file.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-12 13:51:35 +08:00
Dan Mihai
4f41989a6a
Merge pull request from mythi/e2e-skip-flaky-tests
tests: k8s: skip trusted storage tests for qemu-tdx
2025-03-11 12:13:35 -07:00
Dan Mihai
e40251d9f8
Merge pull request from ryansavino/fix-confidential-ssh-dockerfile
tests: fix confidential ssh Dockerfile
2025-03-11 11:22:23 -07:00
Aurélien Bombo
33f3a8cf5f
Merge pull request from microsoft/danmihai1/main
ci: temporarily avoid using the Mariner Host image
2025-03-11 10:24:00 -05:00
Steve Horsman
420b282279
Merge pull request from RuoqingHe/better-matrix
ci: Refactor matrix for `build-checks`
2025-03-11 14:13:10 +00:00
Mikko Ylinen
71531a82f4 tests: k8s: skip trusted storage tests for qemu-tdx
follow other TEEs to skip trusted storage tests due to .

Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
2025-03-11 15:14:03 +02:00
Hui Zhu
93cd30862d libs: Add AddSwapPath to service AgentService
AddSwap send the pci path to guest kernel to let it add swap device.
But some mmio device doesn't have pci path.  To support it add
AddSwapPath send virt_path to guest kernel as swap device.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-11 16:02:48 +08:00
Hui Zhu
7787340ab6 runtime-rs: Add guest swap support
This commit add guest swap support.

When configuration enable_guest_swap is enabled, runtime-rs will start a
swap task.
When the VM start or update the guest memory, the swap task will be
waked up to create and insert a swap file.

Before this job, swap task will sleep some seconds (set by configuration
guest_swap_create_threshold_secs) to reduce the impact on guest kernel
boot performance and prevent the insertion of multiple swap files due to
frequent memory elasticity within a short period.

The size of swap file is set by configuration guest_swap_size_percent.
The percentage of the total memory to be used as swap device.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-11 16:02:31 +08:00
Hui Zhu
4cd9d70c4d runtime-rs: Add is_direct to struct BlockConfig
Add is_direct to struct BlockConfig.
This option specifies cache-related options for block devices.
Denotes whether use of O_DIRECT (bypass the host page cache) is enabled.
If not set, use configurarion block_device_cache_direct.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-11 15:44:40 +08:00
Ryan Savino
1dbe3fb8bc tests: fix confidential ssh Dockerfile
Need to set correct permissions for ssh directories and files

Fixes: 

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2025-03-10 18:31:05 -05:00
Dan Mihai
e8405590c1 ci: temporarily avoid using the Mariner Host image
Disable the Mariner host during CI, while investigating test failures
with new Cloud Hypervisor v43.0.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-10 20:15:09 +00:00
Steve Horsman
730e007abd
Merge pull request from microsoft/danmihai1/print-exec-output2
tests: k8s: log kubectl exec ouput
2025-03-10 09:31:41 +00:00
Fupan Li
df9c6ae9d7
Merge pull request from teawater/ma_config
runtime-rs: Add mem-agent config to clh and qemu config file
2025-03-10 16:23:20 +08:00
Dan Mihai
509e6da965 tests: k8s-env.bats: log exec output
Log the "kubectl exec" ouput, just in case it helps investigate sporadic
test errors like:

https://github.com/kata-containers/kata-containers/actions/runs/13724022494/job/38387329321?pr=10973

not ok 1 Environment variables
(in test file k8s-env.bats, line 37)
 `grep "HOST_IP=\([0-9]\+\(\.\|$\)\)\{4\}"' failed

It appears that the first exec from this test case produced the expected
output:

MY_POD_NAME=test-env

but the second exec produced something else - that will be logged after
this change.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-07 19:37:20 +00:00
Dan Mihai
95d47e4d05 tests: k8s-configmap.bats: log exec output
Log the "kubectl exec" ouput, just in case it helps investigate sporadic
test errors like:

https://github.com/kata-containers/kata-containers/actions/runs/13724022494/job/38387329268?pr=10973

not ok 1 ConfigMap for a pod
(in test file k8s-configmap.bats, line 44)
`kubectl exec $pod_name -- "${exec_command[@]}" | grep "KUBE_CONFIG_2=value-2"' failed

It appears that the first exec from this test case produced the expected
output:

KUBE_CONFIG_1=value-1

but the second exec produced something else - that will be logged after
this change.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-07 19:35:45 +00:00
Dan Mihai
caee12c796 tests: k8s: add function to log exec output
grep_pod_exec_output invokes "kubectl exec", logs its output, and checks
that a grep pattern is present in the output.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-07 19:34:57 +00:00
Steve Horsman
014ff8476a
Merge pull request from microsoft/danmihai1/git-helper
gha: always delete workspace on rebase error
2025-03-07 14:26:00 +00:00
Steve Horsman
cb682ef3c8
Merge pull request from RuoqingHe/enable-docker-on-riscv
kata-deploy: Use docker.io for all architectures
2025-03-07 11:14:19 +00:00
Xuewei Niu
0671252466
Merge pull request from lifupan/route_flags_suport 2025-03-07 18:18:01 +08:00
Hui Zhu
691430ca95 runtime-rs: Add mem-agent config to clh and qemu config file
Add mem-agent config to clh and qemu config file.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-07 15:54:59 +08:00
Fupan Li
9a4c0a5c5c agent: add the route flags support when adding routes
Get the route entry's flags passed from host and
set it in the add route request.

Fixes: 

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Fupan Li
d929bc0224 agent: refactor the code of update routes/interfaces
We can use the netlink update method to add a route or an interface
address. There is no need to delete it first and then add it. This can
save two system commissions.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Fupan Li
aad915a7a1 agent: upgrade the netlink related crates
Upgrade rtnetlink and related crates to support
route flags.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Fupan Li
0995c6528e runtime-rs: add the route flags support
Get the route entry's flags from the host and
pass it into kata-agent to add route entries
with flags support.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Fupan Li
cda6d0e36c runtime-rs: upgrade the netlink related crates
Upgrade netlink-packet-route and rtnetlink to support
route flags.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Fupan Li
1ade2a874f runtime: add the flags support to the route setting
We should support the flags when add the route from
host to guest. Otherwise, some route would be set
failed.

Fixes: 

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-07 09:56:08 +08:00
Dan Mihai
7b63f256e5 gha: fix git-helper issues reported by shellcheck
./tests/git-helper.sh:20:5: note: Prefer [[ ]] over [ ] for tests in Bash/Ksh. [SC2292]
./tests/git-helper.sh:22:26: note: Double quote to prevent globbing and word splitting. [SC2086]
./tests/git-helper.sh:23:7: note: Prefer [[ ]] over [ ] for tests in Bash/Ksh. [SC2292]

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-06 20:28:41 +00:00
Dan Mihai
04adcdace6 gha: always delete workspace on rebase error
The workplace was already being deleted on non-x86_64 platforms, but
x86_64 can be affected by the same problem too. That might have been
the case with the SNP and TDX test runs from:

https://github.com/kata-containers/kata-containers/actions/runs/13687511270/job/38313758751?pr=10973
https://github.com/kata-containers/kata-containers/actions/runs/13687511270/job/38313760086?pr=10973

Rebase worked fine for the same patch/PR on other platforms.

Signed-off-by: Dan Mihai <dmihai@microsoft.com>
2025-03-06 20:24:09 +00:00
Ruoqing He
3a8131349e kata-deploy: Use docker.io for all archietcutres
Switch to `docker.io` provided by Ubuntu sources. It is not necessary
for us to install docker through `get-docker.sh`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-07 02:22:31 +08:00
RuoqingHe
8ef8109b2f
Merge pull request from RuoqingHe/remove-s390x-conditional-compilation
runtime-rs: Remove s390x conditional compilation
2025-03-06 23:13:11 +08:00
Pavel Mores
133528a63c runtime-rs: remove snp_certs_path support
SNP certs were apparently obsoleted by AMD.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-03-06 15:53:24 +01:00
stevenhorsman
a40d5d3daa ci: Add arm64 K8s tests as required
This is based on the request from @fidencio, who
is one of the maintainers
2025-03-06 14:39:04 +00:00
stevenhorsman
f45b398170 ci: Add coco required tests
Add the zvsi and nontee coco tests to the required jobs list

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-06 14:38:52 +00:00
stevenhorsman
ee0f0b7bfe workflows: shellcheck: Expand vendor ignore
- In the previous PR I only skipped the runtime/vendor
directory, but errors are showing up in other vendor
packages, so try a wildcard skip
- Also update the job step was we can distinguish between the
required and non-required versions

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-06 14:35:12 +00:00
Manuel Huber
c05b976ebe runtime: upgrade grpc vendor dependency
- remove hard link to v.1.47.0 in go.mod
- run go mod tidy, go mod vendor to actually update to v1.58.3
- addresses CVE-2023-44487

Signed-off-by: Manuel Huber <mahuber@microsoft.com>
2025-03-06 10:00:49 +00:00
Xuewei Niu
644af52968
Merge pull request from lifupan/fupan_containerd
ci: cri-containerd: upgrade the LTS / Active versions for containerd
2025-03-06 17:08:40 +08:00
Hyounggyu Choi
bf41618a84
Merge pull request from BbolroC/enable-ibm-se-for-qemu-runtime-rs
runtime-rs: Enable IBM SE for QEMU
2025-03-06 05:38:13 +01:00
Ruoqing He
ed6f57f8f6 runtime-rs: Restrict cloud-hypervisor feature
Cloud-Hypervisor currently only supports `x86_64` and `aarch64`, this
features should not be avaiable even if other architectures explicitly
requires it.

Restrict `cloud-hypervisor` feature to only `x86_64` and `aarch64`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-06 11:21:57 +08:00
Ruoqing He
6f894450fe runtime-rs: Drop s390x target predicates
Drop `target_arch = "s390x"` all over `runtime-rs`, it is strange to
have such predicates on features and code while we do not support it.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-06 11:20:28 +08:00
Xuewei Niu
a54eed6bab
Merge pull request from teawater/fix_log_level
runtime-rs: Fix log_level's comments in configuration-dragonball.toml.in
2025-03-06 10:05:09 +08:00
Alex Lyn
2619b57411
Merge pull request from Apokleos/bugfix-useless-annotation
kata-types: Fix bugs related to annotations in kata-types
2025-03-06 09:37:29 +08:00
Hyounggyu Choi
c3e3ef7b25
Merge pull request from BbolroC/remove-sclp-console-s390x
runtime: Remove console=ttysclp0 for s390x
2025-03-05 21:43:57 +01:00
Fabiano Fidêncio
80e95bd264
Merge pull request from kata-containers/topic/tests-bring-back-kata-deploy-tests
tests: Bring back kata-deploy tests
2025-03-05 21:11:21 +01:00
Zvonko Kaiser
ae63bbb824
Merge pull request from zvonkok/fix-zvonkos-fix
agent: fix permisssion according to runc
2025-03-05 15:08:48 -05:00
Fabiano Fidêncio
545780a83a shellcheck: tests: k8s: Fix gha-run.sh warnings
As we'll touch this file during this series, let's already make sure we
solve all the needed warnings.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Fabiano Fidêncio
50f765b19c shellcheck: tests: Fix gha-run-k8s-common.sh warnings
Let's fix all the warnings caught in this file, as we're already
touching it.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Fabiano Fidêncio
219db60071 tests: kata-deploy: microk8s: Re-work installation
So we can ensure that the user has enough permissions to access
microk8s.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Fabiano Fidêncio
c337a21a4e shellcheck: kata-deploy: Fix warnings
He were fixing the few warnings we found in the files present in the
functional tests for kata-deploy.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Fabiano Fidêncio
fd832d0feb tests: kata-deploy: Run installation with only one VMM
It doesn't make much sense to test different VMMs as that wouldn't
trigger a different code path.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Fabiano Fidêncio
14bf653c35 tests: kata-deploy: Re-add tests, now using github runners
As GitHub runners now support nested virt, we're don't depend on garm
for those anymore.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-03-05 19:44:27 +01:00
Zvonko Kaiser
3cea080185 agent: fix permisssion according to runc
The previous PR mistakenly set all perms to 0o666 we should follow
what runc does and fetch the permission from the guest aka host
if the file_mode == 0. If we do not find the device on the guest aka
host fallback to 0.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-03-05 17:33:40 +00:00
Fupan Li
7024d3c600 CI: cri-containerd: upgrade the LTS / Active versions for containerd
As we're testing against the LTS and the Active versions of
containers, let's upgrade the lts version from 1.6 to 1.7 and
active version from 1.7 to 2.0 to cover the sandboxapi tests.

Signed-off-by: Fupan Li <fupan.lfp@antgroup.com>
2025-03-05 23:09:24 +08:00
Hyounggyu Choi
624f7bfe0b runtime: Remove console=ttysclp0 for s390x
After the introduction of the following kernel parameters (see ):

```
CONFIG_SCLP_VT220_TTY=y
CONFIG_SCLP_VT220_CONSOLE=y
```

the system log for Kata components (e.g., the agent) no longer appeared
on the SCLP console (i.e., /dev/ttysclp0). Let's switch to the default
fallback console (likely /dev/console) for logging.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-05 15:06:08 +01:00
Zvonko Kaiser
a5629f9bfa
Merge pull request from zvonkok/host-guest-mapping
agent: Enable VFIO and initContainers
2025-03-05 08:58:45 -05:00
Fabiano Fidêncio
504d9e2b66
Merge pull request from zvonkok/fix-dev-permissions
agent: Fix default linux device permissions
2025-03-05 13:54:06 +01:00
Hyounggyu Choi
4ea7d274c4 runtime-rs: Add new runtimeClass qemu-se-runtime-rs
When `KATA_HYPERVISOR` is set to `qemu-se-runtime-rs`,
a configuration file is properly referenced and a runtime class
should be created via kata-deploy.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-05 13:50:38 +01:00
Hyounggyu Choi
2c72cf5891 runtime-rs: Add SE configuration
A configuration file, `configuration-qemu-se-runtime-rs.toml`,
is referenced when the `qemu-se-runtime-rs` runtime is configured.
This commit adds a template file and updates the Makefile configuration
accordingly.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-05 13:50:38 +01:00
Hyounggyu Choi
65021caca6
Merge pull request from RuoqingHe/remove-arch-predicates-in-runtime-rs
runtime-rs: Enable Dragonball only for x86_64 & aarch64
2025-03-05 09:10:33 +01:00
Zvonko Kaiser
c73ff7518e agent: Fix default linux device permissions
We had the default permissions set to 0o000 if the file_mode was not
present, for most container devices this is the wrong default. Since
those devices are meant also to be accessed by users and others add a
sane default of 0o666 to devices that do not have any permissions set.

Otherwise only root can acess those and we cannot run containers as a
user.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-03-05 02:22:24 +00:00
Ruoqing He
186c88b1d5 ci: Move musl-tools installation into Setup rust
`musl-tools` is only needed when a component needs `rust`, and the
`instance` running is of `x86_64` or `aarch64`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-05 09:43:19 +08:00
Zvonko Kaiser
4bb0eb4590
Merge pull request from kata-containers/topic/metrics-kata-deploy
Rework and fix metrics issues
2025-03-04 20:22:53 -05:00
Hui Zhu
c3c3f23b33 runtime-rs: Fix log_level's comments in configuration-dragonball.toml.in
Add double quotes to fix log_level's comments in
configuration-dragonball.toml.in.

Fixes: 

Signed-off-by: Hui Zhu <teawater@antgroup.com>
2025-03-05 09:21:08 +08:00
Dan Mihai
edf6af2a43
Merge pull request from microsoft/cameronbaird/hyp-loglevel-default-upstream
runtime: Properly set default hyp loglevel to 1
2025-03-04 16:44:08 -08:00
Cameron Baird
d48116114e runtime: Properly set default hyp loglevel to 1
Tweak default HypervisorLoglevel config option for clh to 1.

Signed-off-by: Cameron Baird <cameronbaird@microsoft.com>
2025-03-04 20:36:40 +00:00
Zvonko Kaiser
248d04c20c agent: Enable VFIO and initContainers
We had a static mapping of host guest PCI addresses, which prevented to
use VFIO devices in initContainers. We're tracking now the host-guest
mapping per container and removing this mapping if a container is
removed.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-03-04 19:53:52 +00:00
Fabiano Fidêncio
874129a11f
Merge pull request from stevenhorsman/shell-check-errors-fix
Shell check errors fix
2025-03-04 17:37:36 +01:00
stevenhorsman
02a2f6a9c1 tests: Sanitize K8S_TEST_ENTRY
Now we've added the double quotes around
`${K8S_TEST_UNION[@]}`, so platforms are
failing with:
```
Error: Test file "/home/ubuntu/runner/_layout/_work/kata-containers/kata-containers/tests/integration/kubernetes/k8s-nginx-connectivity.bats
" does not exist
```
due to the line continuation, so sanitise the value
to try and fix this.

Co-authored-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
e33ad56cf4 kernel: bump kata_config_version
Bump kernel version as the build-kernel script
was updated (even if there was no functional change).

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
2df3e5937a ci/openshift-ci: Fix script error
The space was missing before `]`, so fix this and also
swtich to double square brackets and variable braces

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
9a9e88a38d test: vfio: Attempt to fix logic
This was checking that a literal string was non-zero.
I'm assume it instead wanted to check if the file exists

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
b220cca253 shellcheck: Fix shellcheck SC2066
> Since you double-quoted this, it will not word split, and the loop will only run once.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
b8cfdd06fb shellcheck: Fix shellcheck SC2071
> > is for string comparisons. Use -gt instead.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
eb90b93e3f shellcheck: Fix shellcheck SC2104
> In functions, use return instead of break.
> rationale: break or continue are used to abort or
continue a loop, and are not the right way to exit
a function. Use return instead.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:10 +00:00
stevenhorsman
67bfd4793e shellcheck: Fix shellcheck SC2242
> Can only exit with status 0-255. Other data should be written to stdout/stderr.

Switch exit -1 to exit 1

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:39:01 +00:00
stevenhorsman
ed8347c868 shellcheck: Fix shellcheck SC2070
> -n doesn't work with unquoted arguments. Quote or use [[ ]]

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
dbba6b056b shellcheck: Fix shellcheck SC2148
> Tips depend on target shell and yours is unknown. Add a shebang.

Add
```
#!/usr/bin/env bash
```

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
c5ff513e0b shellcheck: Fix shellcheck SC2068
> Double quote array expansions to avoid re-splitting elements

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
58672068ff shellcheck: Fix shellcheck SC2145
> Argument mixes string and array. Use * or separate argument.

- Swap echos for printfs and improve formatting
- Replace $@ with $*
- Split arrays into separate arguments

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
bc2d7d9e1e osbuilder: Skip shellcheck on test_images.sh
I'm not sure if we use test_images anywhere, so before
we invest the time to fix the 120 shellcheck errors and warnings
we should decide if we want to keep it. See 

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
fb1d4b571f workflows: Add required shellcheck workflow
Start with a required smaller set of shellchecks
to try and prevent regressions whilst we fix
the current problems

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
stevenhorsman
b3972df3ca workflows: Shellcheck - ignore vendor
Ignore the vendor directories in our shellcheck
workflow as we can't fix them. If there is a way to
set this in shellcheckrc that would be better, but
it doesn't seem to be implemented yet.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-04 09:35:46 +00:00
Zvonko Kaiser
4df406f03c
Merge pull request from zvonkok/fix-init
gpu: fix init symlinks
2025-03-03 14:46:41 -05:00
Zvonko Kaiser
eb2f75ee61 gpu: fix init symlinks
With the recent changes we need to make sure NVRC is symlinked
for init and sbin/init

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-03-03 17:21:59 +00:00
Greg Kurz
545022f295
Merge pull request from Jakob-Naucke/virtio-net-ccw
Fix virtio-net-ccw
2025-03-03 17:37:46 +01:00
Hyounggyu Choi
e8aa5a5ab7 runtime-rs: Enable virtio-net-ccw for s390x
When using `virtio-net-pci` for IBM SE, the following error occurs:

```
update interface: Link not found (Address: f2:21:48:25:f4:10)
```

On s390x, it is more appropriate to use the CCW type of virtio
network device.
This commit ensures that a subchannel is configured accordingly.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-03 16:34:03 +01:00
Hyounggyu Choi
59c1f0b59b runtime-rs: Suppress kernel parameters for IBM SE
For IBM SE, the following kernel parameters are not required:

- Basic parameters (reboot and systemd-related)
- Rootfs parameters

This commit suppresses these parameters when IBM SE is configured.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-03 16:34:03 +01:00
Hyounggyu Choi
4c8e881a84 runtime-rs: Enable IBM SE support for QEMU
This commit configures the command line for IBM Secure Execution (SE)
and other TEEs. The following changes are made:

- Add a new item `Se` to ProtectionDeviceConfig and handle it at sandbox
- Introduce `add_se_protection_device()` for SE cmdline config
- Bypass rootfs image/initrd validity checks when SE is configured.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-03-03 16:32:18 +01:00
Ruoqing He
2ecb2fe519 runtime-rs: Enable Dragonball for x86_64 & aarch64
`USE_BUILDIN_DB` is turned on by default for architectures do not
support `Dragonball`, which leads `s390x` is building `runtime-rs` with
`--features dragonball` presents.

Let's restrict `USE_BUILDIN_DB` to be enable only for architectures
supported by `Dragonball` (namely x86_64 and aarch64 as of now).

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-03-03 12:10:58 +08:00
stevenhorsman
c69509be1c metrics: Reduce repeats for boot time tests on qemu
On qemu the run seems to error after ~4-7 runs, so try
a cut down version of repetitions to see if this helps us
get results in a stable way.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-02 08:42:00 +00:00
stevenhorsman
0962cd95bc metrics: Increase minpercent range for qemu iperf test
We have a new metrics machine and environment
and the iperf jitter result failed as it finished too quickly,
so increase the minpercent to try and get it stable

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-02 08:32:26 +00:00
stevenhorsman
ef0e8669fb metrics: Increase minpercent range for clh tests
We have a new metrics machine and environment
and the fio write.bw and iperf3 parallel.Results
tests failed for clh, as below
the minimum range, so increase the
minpercent to try and get it stable

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-02 08:32:26 +00:00
stevenhorsman
f81c85e73d metrics: Increase maxpercent range for clh boot times
We have a new metrics machine and environment
and the boot time test failed for clh, so increase the
maxpercent to try and get it stable

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
435ee86fdd metrics: Update iperf affinity
The iperf deployment is quite a lot out of date
and uses `master` for it's affinity and toleration,
so update this to control-plane, so it can run on
newer Kubernetes clusters

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
85bbc0e969 metrics: Increase wait time
The new metrics runner seems slower, so we are
seeing errors like:
The iperf3 tests are failing with:
```
pod rejected: RuntimeClass "kata" not found
```
so give more time for it to succeed

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
4ce94c2d1b Revert "metrics: Add init_env function to latency test"
This reverts commit 9ac29b8d38.
to remove the duplicate `init_env` call

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
658a5e032b metrics: Increase containerd start timeout
- Move `kill_kata_components` from common.bash
into the metrics code base as the only user of it
- Increase the timeout on the start of containerd as
the last 10 nightlies metric tests have failed with:
```
223478 Killed                  sudo timeout -s SIGKILL "${TIMEOUT}" systemctl start containerd
```

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
3fab7944a3 workflows: Improve metrics jobs
- As the metrics tests are largely independent
then allow subsequent tests to run even if previous
ones failed. The results might not be perfect if
clean-up is required, but we can work on that later.
- Move the test results check out of the latency
test that seems arbitrary and into it's own job step
- Add timeouts to steps that might fail/hang if there
are containerd/K8s issues

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
stevenhorsman
6f918d71f5 workflows: Update metrics jobs
Currently the run-metrics job runs a manual install
and does this in a separate job before the metrics
tests run. This doesn't make sense as if we have multiple
CI runs in parallel (like we often do), there is a high chance
that the setup for another PR runs between the metrics
setup and the runs, meaning it's not testing the correct
version of code. We want to remove this from happening,
so install (and delete to cleanup) kata as part of the metrics
test jobs.

Also switch to kata-deploy rather than manual install for
simplicity and in order to test what we recommend to users.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-03-01 17:50:05 +00:00
Zvonko Kaiser
3f13023f5f
Merge pull request from zvonkok/module-signing
gpu: add module signing
2025-03-01 09:51:24 -05:00
Zvonko Kaiser
d971e13446 gpu: Update rootfs.sh
Only source NV scripts if variant starts with "nvidia-gpu"

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-03-01 02:08:29 +00:00
Fabiano Fidêncio
4018079b55
Merge pull request from fidencio/topic/kata-deploy-fix-k0s-deployment
kata-deploy: k0s: Fix drop-in path
2025-02-28 18:49:46 +01:00
Zvonko Kaiser
94579517d4 shellcheck: Update nvidia_rootfs.sh
With the new rules we need more updates.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 16:36:05 +00:00
Zvonko Kaiser
af1d6c2407 shecllcheck: Update nvidia_chroot.sh
Make shellcheck happy with the new rules new updates
needed

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 16:27:51 +00:00
Fabiano Fidêncio
c95f9885ea kata-deploy: k0s: Fix drop-in path
The drop-in path should be /etc/containerd (from the containers'
perspective), which mounts to the host path /etc/k0s/containerd.d.

With what we had we ended up dropping the file under the
/etc/k0s/containerd.d/containerd.d/, which is wrong.

This is a regression introduce by: 94b3348d3c

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-28 16:32:00 +01:00
Zvonko Kaiser
c4e4e14b32 kernel: bump kata_config_version
Mandatory update to have a unique kernel version name

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 15:18:15 +00:00
Fabiano Fidêncio
d13be49f9b
Merge pull request from stalb/feature/microk8s-support
kata-deploy: Update kata-deploy to support microk8s
2025-02-28 13:57:44 +01:00
Stephane Talbot
f80e7370d5 test: Verify deployement of kata-deploy on microk8s
Enable fonctional test to verify deployment of kata-deploy on a Microk8s cluster

Signed-off-by: Stephane Talbot <Stephane.Talbot@univ-savoie.fr>
2025-02-28 10:10:29 +01:00
Stéphane Talbot
f2ba224e6c kata-deploy: Update kata-deploy to support microk8s
Change kata-deploy script and Helm chart in order to be able to use kata-deploy on a microk8s cluster deployed with snap.

Fixes: 

Signed-off-by: Stephane Talbot <Stephane.Talbot@univ-savoie.fr>
2025-02-28 10:10:29 +01:00
Ruoqing He
09030ee96e ci: Refactor build-checks workflow
Refator matrix setup and according dependencies installation logic in
`build-checks.yaml` and `build-checks-preview-riscv64.yaml` to provide
better readability and maintainability.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-28 09:47:25 +08:00
Ruoqing He
eb94700590 ci: Drop install-libseccomp matrix variant
`install-libseccomp` is applied only for `agent` component, and we are
already combining matrix with `if`s in steps, drop `install-libseccomp`
in matrix to reduce complexity.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-28 09:44:53 +08:00
Zvonko Kaiser
4dadd07699 gpu: Update rootfs.sh
Pass-through KBUILD_SIGN_PIN to the rootfs build

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
5ab3192c51 gpu: Update nvidia_rootfs.sh
We need to handle KBUILD_SIGN_PIN so that the kbuild
can decrypte the signing key

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
493ba63c77 gpu: Provide KBUILD_SIGN_PIN to the build.sh
At the proper step pass-through the var KBUILD_SIGN_PIN
so that the kernel_headers step has the PIN for encrypting
the signing key.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
0309b70522 gpu: Pass-through KBUILD_SIGN_PIN
In kata-deploy-binaries.sh we need to pass-through the var
KBUILD_SIGN_PIN to the other static builder scripts.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
9602ba6ccc gpu: Add proper KBUILD_SIGN_PIN to entry script
Update kata-deploy-binaries-in-docker.sh to read the
env variable KBUILD_SIGN_PIN that either can be set via
GHA or other means.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
39d3b7fb90 gpu: Update NVIDIA chroot script
We need to place the signing key and cert at the right place
and hide the KBUILD_SIGN_PIN from echo'ing or xtrace

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
d815fb6f46 gpu: Update kernel-headers
Use the kernel-headers as the extra_tarball to move the encrypted key
and cert from stage to stage

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
c2cb89532b gpu: Add the proper handling in build-kernel.sh
If KBUILD_SIGN_PIN is provided we can encrypt the signing key
for out-of-tree builds and second round jobs in GHA

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:35 +00:00
Zvonko Kaiser
bc8360e8a9 gpu: Add proper config for module signing
We want to enable module signing in Kata and Coco

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-28 01:31:34 +00:00
Zvonko Kaiser
f485e52f75
Merge pull request from zvonkok/shellcheckrc
ci: Add shellcheckrc
2025-02-27 13:35:23 -05:00
Fabiano Fidêncio
96ed706d20
Merge pull request from fidencio/topic/skip-arm-check-tests-that-depend-on-virt
ci: arm64: Skip tests that depend on virt on non-virt capable runners
2025-02-27 18:26:32 +01:00
Zvonko Kaiser
abfbc0ab60 ci: Add shellcheckrc
Let's have common rules over all shell files.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-27 17:11:24 +00:00
Zvonko Kaiser
33460386b9
Merge pull request from ryansavino/update-confidential-initrd-22.04
versions: update confidential initrd to 22.04
2025-02-27 09:29:36 -05:00
Fabiano Fidêncio
e18e1ec3a8 ci: arm64: Skip tests that depend on virt on non-virt capable runners
The GitHub hosted runners for ARM64 do not provide virtualisation
support, thus we're just skipping the tests as those would check whether
or not the system is "VMContainerCapable".

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-27 14:43:21 +01:00
Wainer Moschetta
5fda6b69e8
Merge pull request from stevenhorsman/k0s-version-pinning
ci: k8s: Pin k0s version to get cri-o tests back working
2025-02-27 10:11:59 -03:00
Steve Horsman
f3c22411fc
Merge pull request from stevenhorsman/codeql-config
workflows: Add codeql config
2025-02-27 12:43:41 +00:00
stevenhorsman
d08787774f ci: k8s: Use pinned k0s version
Update the code to install the version of k0s
that we have in our versions.yaml, rather than
just installing the latest, to help our CI being
less stable and prone to breaking due to things
we don't control.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-02-27 11:33:23 +00:00
stevenhorsman
3fe35c1594 version: Add k0s version
Add external versions support for k0s and
initially pin it at v1.31.5 as our cri-o tests
started failing when v1.32 became the latest

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-02-27 11:33:23 +00:00
Fabiano Fidêncio
6e236fd44c
Merge pull request from burgerdev/sysctls
genpolicy: support sysctls from PodSpec and environment defaults
2025-02-27 08:25:14 +01:00
Dan Mihai
cb382e1367
Merge pull request from katexochen/p/fail-on-layer-pull
genpolicy: fail when layer can't be processed
2025-02-26 13:28:38 -08:00
Ryan Savino
ceafa82f2e tests: skip trusted storage tests for qemu-snp
skip tests for trusted storage until  is resolved.

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2025-02-26 14:23:57 -06:00
Ryan Savino
a00a7c500a build: initrd rootfs init symlink directly to systemd when no AGENT_INIT
In some cases, /init is not following two levels of symlinks
i.e. /init to /sbin/init to /lib/systemd/systemd
Setting /init directly to /lib/systemd/systemd when AGENT_INIT is not mandated

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2025-02-26 14:23:56 -06:00
Markus Rudy
70709455ef genpolicy: support sysctl settings
Sysctls may be added to a container by the Kubernetes pod definition or
by containerd configuration. This commit adds support for the
corresponding PodSecurityContext field and an option to specify
environment-dependent sysctls in the settings file.

The sysctls requested in a CreateContainerRequest are checked against
the sysctls in the pod definition, or if not defined there in the
defaults in genpolicy-settings.json. There is no check for the presence
of expected sysctls, though, because Kubernetes might legitimately
omit unsafe syscalls itself and because default sysctls might not apply
to all containers.

Fixes: 
Signed-off-by: Markus Rudy <mr@edgeless.systems>
2025-02-26 18:56:17 +01:00
Steve Horsman
5aa89bc1d7
Merge pull request from RuoqingHe/ci-riscv64
ci: Enable partial components build-check on riscv
2025-02-26 17:50:47 +00:00
Fabiano Fidêncio
9d8026b4e5
Merge pull request from burgerdev/cronjob
genpolicy: add get_process_fields to CronJob
2025-02-26 15:13:40 +01:00
Fabiano Fidêncio
7b16df64c9
Merge pull request from burgerdev/error-messages
runtime: add cause to CDI errors
2025-02-26 14:01:22 +01:00
Jakob Naucke
c146980bcd
agent: Handle virtio-net-ccw devices separately
On s390x, a virtio-net device will use the CCW bus instead of PCI,
which impacts how its uevent should be handled. Take the respective
path accordingly.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:43 +01:00
Jakob Naucke
a084b99324
virtcontainers: Separate PCI/CCW for net devices
On s390x, virtio-net devices should use CCW, alongside a different
device path. Use accordingly.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:43 +01:00
Jakob Naucke
2aa523f08a
virtcontainers: Fix virtio-net-ccw address format
Hex device number was formatted as hex twice, thus encoding the string
as hex.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:43 +01:00
Jakob Naucke
2a992c4080
virtcontainers: Add CCW device to endpoint
To support virtio-net-ccw for s390x, add CCW devices to the Endpoint
interface. Add respective fields and functions to implementing structs.

Device paths may be empty. PciPath resolves this by being a list that
may be empty, but this design does not map to CcwDevice. Use a pointer
instead.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:42 +01:00
Jakob Naucke
b325069d72
agent: Update QEMU URL
Readthedocs URL was outdated.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:42 +01:00
Jakob Naucke
9935f9ea7e
proto: Rename Interface.pciPath to devicePath
Field is being used for both PCI and CCW devices. Name it devicePath
to avoid confusion when the device isn't a PCI device.

Signed-off-by: Jakob Naucke <jakob.naucke@ibm.com>
2025-02-26 11:36:42 +01:00
alex.lyn
a338af3f18 kata-types: Fix bugs related to annotations in kata-types
It will address two issuses:
(1) expected `,`:
  -->
/root/kata-containers/src/libs/kata-types/tests/test_config.rs:15:9
   |
14 |         KATA_ANNO_CFG_HYPERVISOR_ENABLE_IO_THREADS
   |                                                   -
   |                                                   |
   |                                                   expected one of
`,`, `::`, `as`, or `}`
   |                                                   help: missing `,`
15 |         KATA_ANNO_CFG_HYPERVISOR_FILE_BACKED_MEM_ROOT_DIR,
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
unexpected token
(2) remove useless annotation `KATA_ANNO_CFG_HYPERVISOR_CTLPATH`.

Fixes 

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-02-26 17:48:11 +08:00
Fabiano Fidêncio
47a5439a20
Merge pull request from fidencio/topic/agent-unbreak-non-guest-pull-build
agent: Fix non-guest-pull build
2025-02-26 09:45:22 +01:00
Pavel Mores
c5e560e2d1 runtime-rs: handle ProtectionDevice in resource manager and sandbox
As part of device preparation in Sandbox we check available protection
and create a corresponding ProtectionDeviceConfig if appropriate.  The
resource-side handling is trivial.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-02-26 09:11:35 +01:00
Pavel Mores
eb47f15b10 runtime-rs: support ProtectionDevice in qemu-rs
As an example, or a test case, we add some implementation of SEV/SEV-SNP.
Within the QEMU command line generation, the 'Cpu' object is extended to
accomodate the EPYC-v4 CPU type for SEV-SNP.

'Machine' is extended to support the confidential-guest-support parameter
which is useful for other TEEs as well.

Support for emitting the -bios command line switch is added as that seems
to be the preferred way of supplying a path to firmware for SEV/SEV-SNP.

Support for emitting '-object sev-guest' and '-object sev-snp-guest'
with an appropriate set of parameters is added as well.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-02-26 09:11:35 +01:00
Pavel Mores
87deb68ab7 runtime-rs: add implementation of ProtectionDevice
ProtectionDevice is a new device type whose implementation structure
matches the one of other devices in the device module.  It is split into
an inner "config" part which contains device details (we implement
SEV/SEV-SNP for now) and the customary outer "device" part which just adds
a device instance ID and the customary Device trait implementation.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-02-26 09:11:35 +01:00
Pavel Mores
a3f973db3b runtime-rs: extend SEV/SEV-SNP detection by including a details struct
This matches the existing TDX handling where additional details are
retrieved right away after TDX is detected.  Note that the actual details
(cbitpos) acquisition is NOT included at this time.

This change might seem bigger than it is.  The change itself is just in
protection.rs, the rest are corresponding adjustments.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-02-26 09:11:35 +01:00
Pavel Mores
c549d12da7 runtime-rs: parse SEV-SNP related config file settings
The 'sev_snp_guest' default value of 'false' is in compliance with the
golang runtime behaviour.

Signed-off-by: Pavel Mores <pmores@redhat.com>
2025-02-26 09:11:35 +01:00
Markus Rudy
d58f38dfab genpolicy: add get_process_fields to CronJob
This function was accidentally left unimplemented for CronJob, resulting
in runAsUser not being supported there.

Fixes: 
Signed-off-by: Markus Rudy <mr@edgeless.systems>
2025-02-26 09:00:04 +01:00
Ruoqing He
ec020399b9 ci: Enable partial components build-check on riscv
Since we have RISC-V builders available now, let's start with
`agent-ctl`, `trace-forwarder` and `genpolicy` components to run
build-checks on these `riscv-builder`s, and gradually add the rest
components when they are ready, to catch up with other architectures
eventually.

This workflow could be mannually triggered, `riscv-builder` will be the
default instance when that is the case.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-26 15:38:39 +08:00
Markus Rudy
1f6833bd0d runtime: add cause to CDI errors
Adding devices by CDI annotation can fail for a variety of reasons. If
that happens, it's helpful to know the root cause of the issue (CDI spec
missing, malformatted, requested device not present, etc.).

This commit adds the root cause of the CDI device addition to the errors
reported back to the caller. Since this error is bubbled up all the way
back to the shimv2 task.Create handler, it will be visible in Kubernetes
logs and enable fixing the root cause.

Signed-off-by: Markus Rudy <mr@edgeless.systems>
2025-02-26 08:36:15 +01:00
Paul Meyer
9981cdd8a8 genpolicy: fail when layer can't be processed
Currently, if a layer can't be processed, we log this a warning and
continue execution, finally exit with a zero exit code. This can lead
to the generation of invalid policies. One reason a layer might not be
processed is that the pull of that layer fails.

We need all layers to be processed successfully to generate a valid
policy, as otherwise we will miss the verity hash for that layer or
we might miss the USER information from a passwd stored in that layer.
This will cause our VM to not get through the agent's policy validation.

Returning an error instead of printing a warning will cause genpolicy
to fail in such cases.

Signed-off-by: Paul Meyer <katexochen0@gmail.com>
2025-02-26 08:30:59 +01:00
Fabiano Fidêncio
b3b570e4c4 agent: Fix non-guest-pull build
As the guest-pull is a very Confidental Containers specific feature,
let's make sure we, at least, don't break folks who decide to build Kata
Containers' agent without having this feature enabled (for instance, for
the sake of the agent size).

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-25 21:48:41 +01:00
Zvonko Kaiser
04c56a0aaf
Merge pull request from zvonkok/iommufd-fix
gpu: IOMMUFD fix
2025-02-25 12:50:24 -05:00
Ruoqing He
ed50e31625 build: Reorganize target selection
Architectures here with `musl` available are minority, which is more
suitable for enumeration.

With this change, we are implicitly choosing gnu target for `ppc64le`,
`riscv64` and `s390x`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-26 00:56:54 +08:00
Ruoqing He
562911e170 build: Add riscv mapping for common.bash
While installing Rust and Golang in our CI workflow, `arch_to_golang`
and `arch_to_rust` are needed for inferring the correct arch string for
riscv64 architecture.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-26 00:56:54 +08:00
Ruoqing He
62e2473c32 build: Add riscv64 to utils.mk
Since `ARCH` for `riscv64` is `riscv64gc`, we'll need to override it in
`utils.mk`, and forcing `gnu` target for `riscv64` because `musl` target
is not yet made ready.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-26 00:56:54 +08:00
Zvonko Kaiser
804e5cd332 gpu: IOMMUFD provide proper ID
We need a proper ID otherwise QEMU sometimes fails with invalid ID.
Use the same pattern as with the old VFIO implementation.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-25 16:24:17 +00:00
stevenhorsman
c97e9e1592 workflows: Add codeql config
I noticed that CodeQl using the default config hasn't
scanned since May 2024, so figured it would be worth
trying an explicit configuration to see if that gets better results.
It's mostly the template, but updated to be more relevant:
- Only scan PRs and pushes to the `main` branch
- Set a pinned runner version rather than latest (with mac support)
- Edit the list of languages to be scanned to be more relevant
for kata-containers

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-02-25 15:05:43 +00:00
Fabiano Fidêncio
e09ae2cc0b
Merge pull request from RuoqingHe/drop-redundant-override
build: Drop redundant ARCH override
2025-02-25 14:54:36 +01:00
Fabiano Fidêncio
c01e7f1ed5
Merge pull request from kata-containers/topic/consolidate-publish-workflow
workflows: Refactor publish workflows
2025-02-25 14:50:40 +01:00
stevenhorsman
5000fca664 workflows: Add build-checks to manual CI
Currently the ci-on-push workflow that runs on PRs runs
two jobs: gatekeeper-skipper.yaml and ci.yaml. In order
to test things like for the error
```
too many workflows are referenced, total: 21, limit: 20
```
on topic branches, we need ci-devel.yaml to have an
extra workflow to match ci-on-push, so add the build-checks
as this is helpful to run on topic branches anyway.

Signed-off-by: stevenhorsman <steven@uk.ibm.com>
2025-02-25 11:38:49 +00:00
stevenhorsman
23434791f2 workflows: Refactor publish workflows
Replace the four different publish workflows with
a single one that take input parameters of the arch
and runner, so reduce the amount of duplicated code
and try and avoid the
```
too many workflows are referenced, total: 21, limit: 20
```
error
2025-02-25 10:49:09 +00:00
Fabiano Fidêncio
e3eb9e4f28
Merge pull request from kata-containers/topic/enable-arm-tests
arm: ci: k8s: Enable CI
2025-02-24 19:34:28 +01:00
Fabiano Fidêncio
a6186b6244 ci: k8s: arm: Skip "Check the number vcpus are ..." test
See https://github.com/kata-containers/kata-containers/issues/10928

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-24 18:43:24 +01:00
Fabiano Fidêncio
1798804c32 ci: k8s: arm: Skip "Pod quota" test
See https://github.com/kata-containers/kata-containers/issues/10927

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-24 18:43:24 +01:00
Fabiano Fidêncio
053827cacc ci: k8s: arm: Skip "Running within memory constraints" test
See https://github.com/kata-containers/kata-containers/issues/10926

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-24 18:43:24 +01:00
Fabiano Fidêncio
7bd444fa52 ci: Run k8s tests on arm64
Let's take advantege of the current arm64 runners, and make sure we have
those tests running there as well.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
Signed-off-by: Kevin Zhao <kevin.zhao@linaro.org>
2025-02-24 18:43:20 +01:00
Aurélien Bombo
16aa6b9b4b
Merge pull request from kata-containers/sprt/fix-cgroup-race
agent: Fix race condition with cgroup watchers
2025-02-24 10:28:58 -06:00
Ruoqing He
265a751837 build: Drop redundant ARCH override
There are many `override ARCH = powerpc64le` after where `utils.mk` is
included, which are redundant.

Drop those redundant `override`s.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-24 22:04:28 +08:00
Fabiano Fidêncio
aa30f9ab1f versions: Use jammy for x86_64 confidential initrd
Set confidential initrd to use jammy rootfs

Signed-off-by: Ryan Savino <ryan.savino@amd.com>
2025-02-22 23:57:16 -06:00
Aurélien Bombo
adca339c3c ci: Fix GH throttling in run-nerdctl-tests
Specify a GH API token to avoid the below throttling error:

  https://github.com/kata-containers/kata-containers/actions/runs/13450787436/job/37585810679?pr=10911#step:4:96

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-21 17:52:17 -06:00
Aurélien Bombo
111803e168 runtime: cgroups: Remove commented out code
Doesn't seem like we're going to use this and it's confusing when inspecting
code.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-21 17:52:17 -06:00
Aurélien Bombo
1f8c15fa48 Revert "tests: Skip k8s job test on qemu-coco-dev"
This reverts commit a8ccd9a2ac.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-21 17:52:17 -06:00
Aurélien Bombo
7542dbffb8 Revert "tests: disable k8s-policy-job.bats on coco-dev"
This reverts commit 47ce5dad9d.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-21 17:52:17 -06:00
Aurélien Bombo
a1ed923740 agent: Fix race condition with cgroup watchers
In the CI, test containers intermittently fail to start after creation,
with an error like below (see  for more details):

  #     State:      Terminated
  #       Reason:   StartError
  #       Message:  failed to start containerd task "afd43e77fae0815afbc7205eac78f94859e247968a6a4e8bcbb987690fcf10a6": No such file or directory (os error 2)

I've observed this error to repro with the following containers, which
have in common that they're all *very short-lived* by design (more tests
might be affected):

 * k8s-job.bats
 * k8s-seccomp.bats
 * k8s-hostname.bats
 * k8s-policy-job.bats
 * k8s-policy-logs.bats

Furthermore, appending a `; sleep 1` to the command line for those
containers seemed to consistently get rid of the error.

Investigating further, I've uncovered a race between the end of the container
process and the setting up of the cgroup watchers (to report OOMs).

If the process terminates first, the agent will try to watch cgroup
paths that don't exist anymore, and it will fail to start the container.
The added error context in notifier.rs confirms that the error comes
from the missing cgroup:

  https://github.com/kata-containers/kata-containers/actions/runs/13450787436/job/37585901466#step:17:6536

The fix simply consists in creating the watchers *before* we start the
container but still *after* we create it -- this is non-blocking, and IIUC the
cgroup is guaranteed to already be present then.

Fixes: 

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-21 17:52:11 -06:00
Fabiano Fidêncio
aaa7008cad versions: Add a comment about "jammy" being 22.04
I missed that when I added the other comments, so, for the sake of
consistency, let's just add it there as well.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-21 16:02:38 -06:00
Fabiano Fidêncio
a7d33cc0cb build: Ensure MEASURED_ROOTFS is only used for images
We never ever tested MEASURED_ROOTFS with initrd, and I sincerely do not
know why we've been setting that to "yes" in the initrd cases.

Let's drop it, as it may be causing issues with the jobs that rely on
the rootfs-initrd-confidential.

Signed-off-by: Fabiano Fidêncio <fabiano@fidencio.org>
2025-02-21 15:32:20 -06:00
Dan Mihai
b90c537f79
Merge pull request from mythi/build-fixes
minor build fixes
2025-02-21 09:54:55 -08:00
Jeremi Piotrowski
304978ad47
Merge pull request from arvindskumar99/disable_nesting_checks
Disabling Nesting Check for SNP upstream
2025-02-21 12:39:18 +01:00
Xuewei Niu
cdb29a4fd1
Merge pull request from RuoqingHe/setup-dragonball-workspace
dragonball: Appease clippy, setup workspace and centralize RustVMM
2025-02-21 14:04:19 +08:00
Hyounggyu Choi
58647bb654
Merge pull request from zvonkok/iommufd-gpu-fix
IOMMUFD GPU enhancement
2025-02-20 23:43:00 +01:00
Zvonko Kaiser
7cca2c4925 gpu: Use a dedicated VFIO group vs iommufd entry
We do not want to abuse the sysfsentry lets use a dedicated
devfsentry.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-20 18:27:52 +00:00
Zvonko Kaiser
9add633258 qemu: Add command line for IOMMUFD
For each IOMMUFD device create an object and assign
it to the device, we need additional information that
is populated now correctly to decide if we run the old VFIO
or new VFIO backend.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-20 18:27:50 +00:00
Fabiano Fidêncio
19a7f27736
Merge pull request from BbolroC/remove-measured-rootfs-check-for-shimv2-on-s390x
shim-v2: Remove MEASURED_ROOTFS assignment for s390x
2025-02-20 15:53:50 +01:00
arvindskumar99
c0a3ecb27b config: Disabling nesting check for SNP
Adding disable_nesting_checks to accomodate SNP on Azure

Signed-off-by: arvindskumar99 <arvinkum@amd.com>
2025-02-20 12:24:08 +01:00
Hyounggyu Choi
1a9dabd433 shim-v2: Remove MEASURED_ROOTFS assignment for s390x
As a follow-up for , we do not need to set MEASURED_ROOTFS to no
on s390x explicitly. The GHA workflow already exports this variable.
This commit removes the redundant assignment.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-02-20 10:43:36 +01:00
Greg Kurz
f51d84b466
Merge pull request from BbolroC/turn-off-measured-rootfs-s390x-gha-workflows
GHA: Turn off MEASURED_ROOTFS in build-kata-static-tarball-s390x
2025-02-20 10:24:23 +01:00
Aurélien Bombo
601c403603
Merge pull request from burgerdev/plumbing
agent: clear log pipes if denied by policy
2025-02-19 16:28:58 -06:00
Aurélien Bombo
cb3467535c tests: Add policy test for ReadStreamRequest
This test verifies that, when ReadStreamRequest is blocked by the
policy, the logs are empty and the container does not deadlock.

Signed-off-by: Aurélien Bombo <abombo@microsoft.com>
2025-02-19 14:03:41 -06:00
Hyounggyu Choi
ca40462a1c
Merge pull request from BbolroC/fixes-for-cri-containerd-on-ubuntu24
tests: Support systemd unit files in /usr/lib as well as /lib
2025-02-19 19:45:55 +01:00
Hyounggyu Choi
d973d41efb GHA: Turn off MEASURED_ROOTFS in build-kata-static-tarball-s390x
This is the first attempt to remove the following code:

```
if [ "${ARCH}" == "s390x" ]; then
    export MEASURED_ROOTFS=no
fi
```

from install_shimv2() in kata-deploy-binaries.sh.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-02-19 18:19:19 +01:00
Zvonko Kaiser
238db32126
Merge pull request from zvonkok/qemu-tdx-experimental-workflow
QEMU TDX experimental workflow
2025-02-19 10:09:27 -05:00
Zvonko Kaiser
f0eef73a89 gpu: Add no_patches.txt for TDX flavour
As alwasy if we do not have any patches create the no_patches.txt
for the specific tag gpu_tdx_...

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-19 14:59:04 +00:00
Zvonko Kaiser
ca4d227562 gpu: Add qemu-tdx-experimental build
We need to introduce again the qemu-tdx build for the GPU

Depends-on: 

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-19 14:48:56 +00:00
Hyounggyu Choi
a8363c28ca tests: Support systemd unit files in /usr/lib as well as /lib
On Ubuntu 24.04, due to the /usr merge, system-provided unit files
now reside in `/usr/lib/systemd/system/` instead of `/lib/systemd/system/`.
For example, the command below now returns a different path:

```
$ systemctl show containerd.service -p FragmentPath
/usr/lib/systemd/system/containerd.service
```

Previously, on Ubuntu 22.04 and earlier, it returned:

```
/lib/systemd/system/containerd.service
```

The current pattern `if [[ $unit_file == /lib* ]]` fails to match the new path.
To ensure compatibility across versions, we update the pattern to match both
`/lib` and `/usr/lib` like:

```
if [[ $unit_file =~ ^/(usr/)?lib/ ]]
```

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-02-19 14:34:59 +01:00
Zvonko Kaiser
0d786577c6
Merge pull request from zvonkok/qemu-snp-tdx-experimental
gpu: QEMU SNP+TDX experimental updates
2025-02-19 08:26:37 -05:00
Ruoqing He
a8a096b20c dragonball: Centralize RustVMM crates
Centralize all RustVMM crates to workspace.dependencies to prevent
having multiple versions of each RustVMM crate, which is error-prone and
inconsistent. With this setup, updates on RustVMM crates would be much
easier.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-19 21:20:30 +08:00
Ruoqing He
b129972e12 dragonball: Setup workspace
Setup workspace in dragonball, move `dbs` crates one level up to be
managed as members of dragonball workspace.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-19 21:20:30 +08:00
Ruoqing He
a174e2be03 dragonball: Appease clippy introduced by 1.80.0
New clippy warnings show up after Rust Tool Chain bumped from 1.75.0 to
1.80.0, fix accrodingly.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-19 21:20:30 +08:00
Ruoqing He
6bb193bbc0 spell: Update dictionary for dbs crates
Add entries for dbs_* crates' README.md to pass `kata-spell-check.sh`
spell checking.

Changed British terms to American terms in README of `dbs_pci` to pass
`hunspell` check.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-19 21:20:30 +08:00
Zvonko Kaiser
73b7a3478c
Merge pull request from RuoqingHe/fix-static-check
ci: Fix spell_check and improve header_check
2025-02-19 08:08:40 -05:00
Mikko Ylinen
926119040c packaging: make install_oras.sh to run curl without sudo
sudo hides the environment variables that are sometimes
useful with the builds (for example: proxy settings).

While install_oras.sh could run completely without sudo in
the container it's COPY'd to, make minimal changes to it
to keep it functional outside the container too while still
addressing the problem of 'sudo curl' not working with proxy
env variables.

Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
2025-02-19 09:34:13 +02:00
Mikko Ylinen
0d8242aee4 agent: rename cargo config
To mitigate:

warning: `.../kata-containers/src/agent/.cargo/config` is deprecated in favor of `config.toml`
note: if you need to support cargo 1.38 or earlier, you can symlink `config` to `config.toml`

Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
2025-02-19 09:34:13 +02:00
Fabiano Fidêncio
c8db24468c
Merge pull request from BbolroC/use-multi-arch-for-qemu-sample
example: Use multi-arch image for test-deploy-kata-qemu.yaml
2025-02-18 23:43:52 +01:00
Dan Mihai
672462e6b8
Merge pull request from katexochen/p/agent-deps
agent: make policy feature optional again
2025-02-18 13:27:23 -08:00
Dan Mihai
6b389fdd4f
Merge pull request from katexochen/p/oci-client-genplicy
genpolicy: bump oci-distribution to v0.12.0
2025-02-18 12:42:23 -08:00
Markus Rudy
67fbad5f37 genpolicy: bump oci-distribution to v0.12.0
This picks up a security fix for confidential pulling of unsigned
images.

The crate moved permanently to oci-client, which required a few import
changes.

Co-authored-by: Paul Meyer <katexochen0@gmail.com>
Signed-off-by: Markus Rudy <mr@edgeless.systems>
2025-02-18 16:32:00 +01:00
Ruoqing He
d23284a0dc header_check: Check header for changed text files
We are running `header_check` for non-text files like binary files,
symbolic link files, image files (pictures) and etc., which does not
make sense.

Filter out non-text files and run `header_check` only for text files
changed.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-18 22:39:53 +08:00
Paul Meyer
80af09aae9 agent: make policy feature optional again
This was messed up a little when factoring out the policy crate.
Removing the dependencies no longer used by the agent and making the
import of kata-agent-policy optional again.

Signed-off-by: Paul Meyer <katexochen0@gmail.com>
2025-02-18 15:28:06 +01:00
Hyounggyu Choi
4646058c0c example: Use multi-arch image for test-deploy-kata-qemu.yaml
An image `registry.k8s.io/hpa-example` only supports amd64.
Let's use a multi-arch image `quay.io/prometheus/prometheus`
for the QEMU example instead.

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2025-02-18 14:23:09 +01:00
Ruoqing He
7e49e83779 spell: Add missing entries for kata-spell-check
`kata-dictionary.dic` changes after running `kata-spell-check.sh
make-dict`. This is due to someone forgot to first update entries in
data and run `make-dict`, but directly updated `kata-dictionary.dic`
instead.

Add mssing entries to data and re-run `make-dict` to generate correct
`kata-dictionary.dic`.

Signed-off-by: Ruoqing He <heruoqing@iscas.ac.cn>
2025-02-18 19:06:34 +08:00
Lukáš Doktor
d0ef78d3a4
ci: Change the way we modify runtimeclass in webhook
previously we used to deploy the webhook and then modified the cm from
our ci/openshift-ci/ script to the desired value, but sometimes it
happens that the webhook pod starts before we modify the cm and keeps
using the default value.

Let's change the approach and modify the deployments in-place. The only
cons is it leaves the git dirty, but since this script is only supposed
to be used in ci it should be safe.

Signed-off-by: Lukáš Doktor <ldoktor@redhat.com>
2025-02-18 11:39:22 +01:00
Zvonko Kaiser
2d8531cd20 gpu: Add TDX experimental target for GPUs
We have custom branches on coco/qemu to support GPUs
in TDX and SNP add experimental target.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-11 17:32:31 +00:00
Zvonko Kaiser
7ded74c068 gpu: Add version for QEMU+TDX+SNP
SNP and TDX patches for GPU are not compatible
hence we need an own build for TDX.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-11 17:32:31 +00:00
Zvonko Kaiser
e4679055c6 gpu: qemu-snp-experimental no patches
The branch has all the needed cherry-picks

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-11 17:32:31 +00:00
Zvonko Kaiser
7a219b3f03 gpu: Add GPU+SNP QEMU build
Since the CPU SNP is upstreamed and available via our
default QEMU target we're repurposing the SNP-experimental
for the GPU+SNP enablement.

First step is to update the version we're basing it off.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-02-11 17:32:31 +00:00
Markus Rudy
937fd90779 agent: clear log pipes if denied by policy
Container logs are forwarded to the agent through a unix pipe. These
pipes have limited capacity and block the writer when full. If reading
logs is blocked by policy, a common setup for confidential containers,
the pipes fill up and eventually block the container.

This commit changes the implementation of ReadStream such that it
returns empty log messages instead of a policy failure (in case reading
log messages is forbidden by policy). As long as the runtime does not
encounter a failure, it keeps pulling logs periodically. In turn, this
triggers the agent to flush the pipes.

Fixes: 

Co-Authored-By: Aurélien Bombo <abombo@microsoft.com>
Signed-off-by: Markus Rudy <mr@edgeless.systems>
2025-02-04 13:17:29 +01:00
Zvonko Kaiser
e82fdee20f runtime: Add proper IOMMUFD parsing
With newer kernels we have a new backend for VFIO
called IOMMUFD this is a departure from VFIO IOMMU Groups
since it has only one device associated with an IOMMUFD entry.

Signed-off-by: Zvonko Kaiser <zkaiser@nvidia.com>
2025-01-15 23:39:33 +00:00
1844 changed files with 322567 additions and 34521 deletions
.github
VERSION
ci
docs/how-to
rust-toolchain.tomlshellcheckrc
src

View File

@ -7,6 +7,7 @@
self-hosted-runner:
# Labels of self-hosted runner that linter should ignore
labels:
- arm64-k8s
- ubuntu-22.04-arm
- garm-ubuntu-2004
- garm-ubuntu-2004-smaller
@ -17,6 +18,7 @@ self-hosted-runner:
- k8s-ppc64le
- metrics
- ppc64le
- riscv-builder
- sev
- sev-snp
- s390x

View File

@ -21,7 +21,7 @@ runs:
override: true
- name: Cache
uses: Swatinem/rust-cache@v2
uses: Swatinem/rust-cache@f0deed1e0edfc6a9be95417288c0e1099b1eeec3 # v2.7.7
- name: Install Cargo deny
shell: bash

View File

@ -20,7 +20,7 @@ jobs:
steps:
- name: WIP Check
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: tim-actions/wip-check@1c2a1ca6c110026b3e2297bb2ef39e1747b5a755
uses: tim-actions/wip-check@1c2a1ca6c110026b3e2297bb2ef39e1747b5a755 # master (2021-06-10)
with:
labels: '["do-not-merge", "wip", "rfc"]'
keywords: '["WIP", "wip", "RFC", "rfc", "dnm", "DNM", "do-not-merge"]'

View File

@ -48,6 +48,6 @@ jobs:
pr=${{ github.event.number }}
# Removing man-db, workflow kept failing, fixes: #4480
sudo apt -y remove --purge man-db
sudo apt -y install diffstat patchutils
sudo apt update && sudo apt -y install diffstat patchutils
pr-add-size-label.sh -p "$pr"

View File

@ -63,15 +63,13 @@ jobs:
# all the tests due to a single flaky instance.
fail-fast: false
matrix:
containerd_version: ['latest']
containerd_version: ['active']
vmm: ['dragonball', 'cloud-hypervisor', 'qemu-runtime-rs']
runs-on: ubuntu-22.04
env:
CONTAINERD_VERSION: ${{ matrix.containerd_version }}
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
#the latest containerd from 2.0 need to set the CGROUP_DRIVER for e2e testing
CGROUP_DRIVER: ""
SANDBOXER: "shim"
steps:
- uses: actions/checkout@v4
@ -369,6 +367,8 @@ jobs:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
env:
GITHUB_API_TOKEN: ${{ github.token }}
run: bash tests/integration/nerdctl/gha-run.sh install-dependencies
- name: get-kata-tarball

178
.github/workflows/basic-ci-s390x.yaml vendored Normal file
View File

@ -0,0 +1,178 @@
name: CI | Basic s390x tests
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
run-cri-containerd:
strategy:
# We can set this to true whenever we're 100% sure that
# the all the tests are not flaky, otherwise we'll fail
# all the tests due to a single flaky instance
fail-fast: false
matrix:
containerd_version: ['active']
vmm: ['qemu', 'qemu-runtime-rs']
runs-on: s390x-large
env:
CONTAINERD_VERSION: ${{ matrix.containerd_version }}
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
run: bash tests/integration/cri-containerd/gha-run.sh install-dependencies
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/integration/cri-containerd/gha-run.sh install-kata kata-artifacts
- name: Run cri-containerd tests
run: bash tests/integration/cri-containerd/gha-run.sh run
run-containerd-sandboxapi:
strategy:
# We can set this to true whenever we're 100% sure that
# the all the tests are not flaky, otherwise we'll fail
# all the tests due to a single flaky instance.
fail-fast: false
matrix:
containerd_version: ['active']
vmm: ['qemu-runtime-rs']
runs-on: s390x-large
env:
CONTAINERD_VERSION: ${{ matrix.containerd_version }}
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
SANDBOXER: "shim"
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
run: bash tests/integration/cri-containerd/gha-run.sh install-dependencies
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/integration/cri-containerd/gha-run.sh install-kata kata-artifacts
- name: Run containerd-sandboxapi tests
timeout-minutes: 10
run: bash tests/integration/cri-containerd/gha-run.sh run
run-containerd-stability:
strategy:
fail-fast: false
matrix:
containerd_version: ['lts', 'active']
vmm: ['qemu']
runs-on: s390x-large
env:
CONTAINERD_VERSION: ${{ matrix.containerd_version }}
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
SANDBOXER: "podsandbox"
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
run: bash tests/stability/gha-run.sh install-dependencies
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/stability/gha-run.sh install-kata kata-artifacts
- name: Run containerd-stability tests
timeout-minutes: 15
run: bash tests/stability/gha-run.sh run
run-docker-tests:
strategy:
# We can set this to true whenever we're 100% sure that
# all the tests are not flaky, otherwise we'll fail them
# all due to a single flaky instance.
fail-fast: false
matrix:
vmm: ['qemu']
runs-on: s390x-large
env:
KATA_HYPERVISOR: ${{ matrix.vmm }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
run: bash tests/integration/docker/gha-run.sh install-dependencies
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/integration/docker/gha-run.sh install-kata kata-artifacts
- name: Run docker smoke test
timeout-minutes: 5
run: bash tests/integration/docker/gha-run.sh run

View File

@ -0,0 +1,120 @@
# This yaml is designed to be used until all components listed in
# `build-checks.yaml` are supported
on:
workflow_dispatch:
inputs:
instance:
default: "riscv-builder"
description: "Default instance when manually triggering"
workflow_call:
inputs:
instance:
required: true
type: string
name: Build checks preview riscv64
jobs:
check:
runs-on: ${{ inputs.instance }}
strategy:
fail-fast: false
matrix:
command:
- "make vendor"
- "make check"
- "make test"
- "sudo -E PATH=\"$PATH\" make test"
component:
- name: agent-ctl
path: src/tools/agent-ctl
needs:
- rust
- musl-tools
- protobuf-compiler
- clang
- name: trace-forwarder
path: src/tools/trace-forwarder
needs:
- rust
- musl-tools
- name: genpolicy
path: src/tools/genpolicy
needs:
- rust
- musl-tools
- protobuf-compiler
- name: runtime
path: src/runtime
needs:
- golang
- XDG_RUNTIME_DIR
- name: runtime-rs
path: src/runtime-rs
needs:
- rust
steps:
- name: Adjust a permission for repo
run: |
sudo chown -R "$USER":"$USER" "$GITHUB_WORKSPACE" "$HOME"
sudo rm -rf "$GITHUB_WORKSPACE"/* || { sleep 10 && sudo rm -rf "$GITHUB_WORKSPACE"/*; }
sudo rm -f /tmp/kata_hybrid* # Sometime we got leftover from test_setup_hvsock_failed()
- name: Checkout the code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install yq
run: |
./ci/install_yq.sh
env:
INSTALL_IN_GOPATH: false
- name: Install golang
if: contains(matrix.component.needs, 'golang')
run: |
./tests/install_go.sh -f -p
echo "/usr/local/go/bin" >> "$GITHUB_PATH"
- name: Setup rust
if: contains(matrix.component.needs, 'rust')
run: |
./tests/install_rust.sh
echo "${HOME}/.cargo/bin" >> "$GITHUB_PATH"
if [ "$(uname -m)" == "x86_64" ] || [ "$(uname -m)" == "aarch64" ]; then
sudo apt-get update && sudo apt-get -y install musl-tools
fi
- name: Install devicemapper
if: contains(matrix.component.needs, 'libdevmapper') && matrix.command == 'make check'
run: sudo apt-get update && sudo apt-get -y install libdevmapper-dev
- name: Install libseccomp
if: contains(matrix.component.needs, 'libseccomp') && matrix.command != 'make vendor' && matrix.command != 'make check'
run: |
libseccomp_install_dir=$(mktemp -d -t libseccomp.XXXXXXXXXX)
gperf_install_dir=$(mktemp -d -t gperf.XXXXXXXXXX)
./ci/install_libseccomp.sh "${libseccomp_install_dir}" "${gperf_install_dir}"
echo "Set environment variables for the libseccomp crate to link the libseccomp library statically"
echo "LIBSECCOMP_LINK_TYPE=static" >> "$GITHUB_ENV"
echo "LIBSECCOMP_LIB_PATH=${libseccomp_install_dir}/lib" >> "$GITHUB_ENV"
- name: Install protobuf-compiler
if: contains(matrix.component.needs, 'protobuf-compiler') && matrix.command != 'make vendor'
run: sudo apt-get update && sudo apt-get -y install protobuf-compiler
- name: Install clang
if: contains(matrix.component.needs, 'clang') && matrix.command == 'make check'
run: sudo apt-get update && sudo apt-get -y install clang
- name: Setup XDG_RUNTIME_DIR
if: contains(matrix.component.needs, 'XDG_RUNTIME_DIR') && matrix.command != 'make check'
run: |
XDG_RUNTIME_DIR=$(mktemp -d "/tmp/kata-tests-$USER.XXX" | tee >(xargs chmod 0700))
echo "XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR}" >> "$GITHUB_ENV"
- name: Skip tests that depend on virtualization capable runners when needed
if: inputs.instance == 'riscv-builder'
run: |
echo "GITHUB_RUNNER_CI_NON_VIRT=true" >> "$GITHUB_ENV"
- name: Running `${{ matrix.command }}` for ${{ matrix.component.name }}
run: |
cd ${{ matrix.component.path }}
${{ matrix.command }}
env:
RUST_BACKTRACE: "1"
RUST_LIB_BACKTRACE: "0"
SKIP_GO_VERSION_CHECK: "1"

View File

@ -12,40 +12,53 @@ jobs:
strategy:
fail-fast: false
matrix:
component:
- agent
- dragonball
- runtime
- runtime-rs
- agent-ctl
- kata-ctl
- trace-forwarder
- genpolicy
command:
- "make vendor"
- "make check"
- "make test"
- "sudo -E PATH=\"$PATH\" make test"
include:
- component: agent
component-path: src/agent
- component: dragonball
component-path: src/dragonball
- component: runtime
component-path: src/runtime
- component: runtime-rs
component-path: src/runtime-rs
- component: agent-ctl
component-path: src/tools/agent-ctl
- component: kata-ctl
component-path: src/tools/kata-ctl
- component: trace-forwarder
component-path: src/tools/trace-forwarder
- install-libseccomp: no
- component: agent
install-libseccomp: yes
- component: genpolicy
component-path: src/tools/genpolicy
component:
- name: agent
path: src/agent
needs:
- rust
- libdevmapper
- libseccomp
- protobuf-compiler
- clang
- name: dragonball
path: src/dragonball
needs:
- rust
- name: runtime
path: src/runtime
needs:
- golang
- XDG_RUNTIME_DIR
- name: runtime-rs
path: src/runtime-rs
needs:
- rust
- name: agent-ctl
path: src/tools/agent-ctl
needs:
- rust
- protobuf-compiler
- clang
- name: kata-ctl
path: src/tools/kata-ctl
needs:
- rust
- name: trace-forwarder
path: src/tools/trace-forwarder
needs:
- rust
- name: genpolicy
path: src/tools/genpolicy
needs:
- rust
- protobuf-compiler
steps:
- name: Adjust a permission for repo
run: |
@ -64,23 +77,23 @@ jobs:
env:
INSTALL_IN_GOPATH: false
- name: Install golang
if: ${{ matrix.component == 'runtime' }}
if: contains(matrix.component.needs, 'golang')
run: |
./tests/install_go.sh -f -p
echo "/usr/local/go/bin" >> "$GITHUB_PATH"
- name: Install rust
if: ${{ matrix.component != 'runtime' }}
- name: Setup rust
if: contains(matrix.component.needs, 'rust')
run: |
./tests/install_rust.sh
echo "${HOME}/.cargo/bin" >> "$GITHUB_PATH"
- name: Install musl-tools
if: ${{ matrix.component != 'runtime' }}
run: sudo apt-get -y install musl-tools
if [ "$(uname -m)" == "x86_64" ] || [ "$(uname -m)" == "aarch64" ]; then
sudo apt-get update && sudo apt-get -y install musl-tools
fi
- name: Install devicemapper
if: ${{ matrix.command == 'make check' && matrix.component == 'agent' }}
run: sudo apt-get -y install libdevmapper-dev
if: contains(matrix.component.needs, 'libdevmapper') && matrix.command == 'make check'
run: sudo apt-get update && sudo apt-get -y install libdevmapper-dev
- name: Install libseccomp
if: ${{ matrix.command != 'make vendor' && matrix.command != 'make check' && matrix.install-libseccomp == 'yes' }}
if: contains(matrix.component.needs, 'libseccomp') && matrix.command != 'make vendor' && matrix.command != 'make check'
run: |
libseccomp_install_dir=$(mktemp -d -t libseccomp.XXXXXXXXXX)
gperf_install_dir=$(mktemp -d -t gperf.XXXXXXXXXX)
@ -89,20 +102,25 @@ jobs:
echo "LIBSECCOMP_LINK_TYPE=static" >> "$GITHUB_ENV"
echo "LIBSECCOMP_LIB_PATH=${libseccomp_install_dir}/lib" >> "$GITHUB_ENV"
- name: Install protobuf-compiler
if: ${{ matrix.command != 'make vendor' && (matrix.component == 'agent' || matrix.component == 'genpolicy' || matrix.component == 'agent-ctl') }}
run: sudo apt-get -y install protobuf-compiler
if: contains(matrix.component.needs, 'protobuf-compiler') && matrix.command != 'make vendor'
run: sudo apt-get update && sudo apt-get -y install protobuf-compiler
- name: Install clang
if: ${{ matrix.command == 'make check' && (matrix.component == 'agent' || matrix.component == 'agent-ctl') }}
run: sudo apt-get -y install clang
- name: Setup XDG_RUNTIME_DIR for the `runtime` tests
if: ${{ matrix.command != 'make vendor' && matrix.command != 'make check' && matrix.component == 'runtime' }}
if: contains(matrix.component.needs, 'clang') && matrix.command == 'make check'
run: sudo apt-get update && sudo apt-get -y install clang
- name: Setup XDG_RUNTIME_DIR
if: contains(matrix.component.needs, 'XDG_RUNTIME_DIR') && matrix.command != 'make check'
run: |
XDG_RUNTIME_DIR=$(mktemp -d "/tmp/kata-tests-$USER.XXX" | tee >(xargs chmod 0700))
echo "XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR}" >> "$GITHUB_ENV"
- name: Running `${{ matrix.command }}` for ${{ matrix.component }}
- name: Skip tests that depend on virtualization capable runners when needed
if: ${{ endsWith(inputs.instance, '-arm') }}
run: |
cd ${{ matrix.component-path }}
echo "GITHUB_RUNNER_CI_NON_VIRT=true" >> "$GITHUB_ENV"
- name: Running `${{ matrix.command }}` for ${{ matrix.component.name }}
run: |
cd ${{ matrix.component.path }}
${{ matrix.command }}
env:
RUST_BACKTRACE: "1"
RUST_LIB_BACKTRACE: "0"
SKIP_GO_VERSION_CHECK: "1"

View File

@ -54,6 +54,7 @@ jobs:
- pause-image
- qemu
- qemu-snp-experimental
- qemu-tdx-experimental
- stratovirt
- trace-forwarder
- virtiofsd
@ -67,7 +68,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -109,13 +110,13 @@ jobs:
echo "oci-name=${oci_image%@*}" >> "$GITHUB_OUTPUT"
echo "oci-digest=${oci_image#*@}" >> "$GITHUB_OUTPUT"
- uses: oras-project/setup-oras@v1
- uses: oras-project/setup-oras@5c0b487ce3fe0ce3ab0d034e63669e426e294e4d # v1.2.2
if: ${{ env.PERFORM_ATTESTATION == 'yes' }}
with:
version: "1.2.0"
# for pushing attestations to the registry
- uses: docker/login-action@v3
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
if: ${{ env.PERFORM_ATTESTATION == 'yes' }}
with:
registry: ghcr.io
@ -162,7 +163,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -225,7 +226,7 @@ jobs:
- kernel-nvidia-gpu-confidential-headers
- pause-image
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
with:
name: kata-artifacts-amd64-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -238,7 +239,7 @@ jobs:
asset:
- agent
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
if: ${{ inputs.stage == 'release' }}
with:
name: kata-artifacts-amd64-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -249,7 +250,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -48,7 +48,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -89,13 +89,13 @@ jobs:
echo "oci-name=${oci_image%@*}" >> "$GITHUB_OUTPUT"
echo "oci-digest=${oci_image#*@}" >> "$GITHUB_OUTPUT"
- uses: oras-project/setup-oras@v1
- uses: oras-project/setup-oras@5c0b487ce3fe0ce3ab0d034e63669e426e294e4d # v1.2.2
if: ${{ env.PERFORM_ATTESTATION == 'yes' }}
with:
version: "1.2.0"
# for pushing attestations to the registry
- uses: docker/login-action@v3
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
if: ${{ env.PERFORM_ATTESTATION == 'yes' }}
with:
registry: ghcr.io
@ -138,7 +138,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -197,7 +197,7 @@ jobs:
- busybox
- kernel-nvidia-gpu-headers
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
with:
name: kata-artifacts-arm64-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -210,7 +210,7 @@ jobs:
asset:
- agent
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
if: ${{ inputs.stage == 'release' }}
with:
name: kata-artifacts-arm64-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -221,7 +221,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -34,15 +34,9 @@ jobs:
stage:
- ${{ inputs.stage }}
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
"${HOME}/scripts/prepare_runner.sh"
sudo rm -rf "$GITHUB_WORKSPACE"/*
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -93,15 +87,9 @@ jobs:
stage:
- ${{ inputs.stage }}
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
"${HOME}/scripts/prepare_runner.sh"
sudo rm -rf "$GITHUB_WORKSPACE"/*
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -159,7 +147,7 @@ jobs:
asset:
- agent
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
if: ${{ inputs.stage == 'release' }}
with:
name: kata-artifacts-ppc64le-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -168,15 +156,9 @@ jobs:
runs-on: ppc64le
needs: [build-asset, build-asset-rootfs, remove-rootfs-binary-artifacts]
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
"${HOME}/scripts/prepare_runner.sh"
sudo rm -rf "$GITHUB_WORKSPACE"/*
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -0,0 +1,79 @@
name: CI | Build kata-static tarball for riscv64
on:
workflow_call:
inputs:
stage:
required: false
type: string
default: test
tarball-suffix:
required: false
type: string
push-to-registry:
required: false
type: string
default: no
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
build-asset:
runs-on: riscv-builder
permissions:
contents: read
packages: write
id-token: write
attestations: write
strategy:
matrix:
asset:
- kernel
- virtiofsd
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
password: ${{ secrets.QUAY_DEPLOYER_PASSWORD }}
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0 # This is needed in order to keep the commit ids history
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Build ${{ matrix.asset }}
run: |
make "${KATA_ASSET}-tarball"
build_dir=$(readlink -f build)
# store-artifact does not work with symlink
mkdir -p kata-build && cp "${build_dir}"/kata-static-"${KATA_ASSET}"*.tar.* kata-build/.
env:
KATA_ASSET: ${{ matrix.asset }}
TAR_OUTPUT: ${{ matrix.asset }}.tar.gz
PUSH_TO_REGISTRY: ${{ inputs.push-to-registry }}
ARTEFACT_REGISTRY: ghcr.io
ARTEFACT_REGISTRY_USERNAME: ${{ github.actor }}
ARTEFACT_REGISTRY_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
TARGET_BRANCH: ${{ inputs.target-branch }}
RELEASE: ${{ inputs.stage == 'release' && 'yes' || 'no' }}
- name: store-artifact ${{ matrix.asset }}
uses: actions/upload-artifact@v4
with:
name: kata-artifacts-arm64-${{ matrix.asset }}${{ inputs.tarball-suffix }}
path: kata-build/kata-static-${{ matrix.asset }}.tar.xz
retention-days: 15
if-no-files-found: error

View File

@ -44,7 +44,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -87,7 +87,7 @@ jobs:
echo "oci-digest=${oci_image#*@}" >> "$GITHUB_OUTPUT"
# for pushing attestations to the registry
- uses: docker/login-action@v3
- uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
if: ${{ env.PERFORM_ATTESTATION == 'yes' }}
with:
registry: ghcr.io
@ -122,7 +122,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -227,7 +227,7 @@ jobs:
- coco-guest-components
- pause-image
steps:
- uses: geekyeggo/delete-artifact@v5
- uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
if: ${{ inputs.stage == 'release' }}
with:
name: kata-artifacts-s390x-${{ matrix.asset}}${{ inputs.tarball-suffix }}
@ -238,7 +238,7 @@ jobs:
steps:
- name: Login to Kata Containers quay.io
if: ${{ inputs.push-to-registry == 'yes' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -279,7 +279,7 @@ jobs:
ARTEFACT_REGISTRY_PASSWORD: ${{ secrets.GITHUB_TOKEN }}
TARGET_BRANCH: ${{ inputs.target-branch }}
RELEASE: ${{ inputs.stage == 'release' && 'yes' || 'no' }}
MEASURED_ROOTFS: yes
MEASURED_ROOTFS: no
- name: store-artifact shim-v2
uses: actions/upload-artifact@v4

View File

@ -11,3 +11,8 @@ jobs:
tag: ${{ github.sha }}-dev
target-branch: ${{ github.ref_name }}
secrets: inherit
build-checks:
uses: ./.github/workflows/build-checks.yaml
with:
instance: ubuntu-22.04

View File

@ -11,6 +11,7 @@ jobs:
matrix:
test_title:
- kata-vfio-ap-e2e-tests
- cc-vfio-ap-e2e-tests
- cc-se-e2e-tests
steps:
- name: Fetch a test result for {{ matrix.test_title }}

View File

@ -26,7 +26,7 @@ jobs:
publish-kata-deploy-payload-amd64:
needs: build-kata-static-tarball-amd64
uses: ./.github/workflows/publish-kata-deploy-payload-amd64.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
@ -34,6 +34,8 @@ jobs:
tag: ${{ inputs.tag }}-amd64
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
runner: ubuntu-22.04
arch: amd64
secrets: inherit
build-and-publish-tee-confidential-unencrypted-image:
@ -52,20 +54,20 @@ jobs:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
- name: Login to Kata Containers ghcr.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0
with:
tags: ghcr.io/kata-containers/test-images:unencrypted-${{ inputs.pr-number }}
push: true

View File

@ -30,7 +30,7 @@ jobs:
publish-kata-deploy-payload-amd64:
needs: build-kata-static-tarball-amd64
uses: ./.github/workflows/publish-kata-deploy-payload-amd64.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
@ -38,6 +38,8 @@ jobs:
tag: ${{ inputs.tag }}-amd64
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
runner: ubuntu-22.04
arch: amd64
secrets: inherit
build-kata-static-tarball-arm64:
@ -49,7 +51,7 @@ jobs:
publish-kata-deploy-payload-arm64:
needs: build-kata-static-tarball-arm64
uses: ./.github/workflows/publish-kata-deploy-payload-arm64.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
@ -57,6 +59,8 @@ jobs:
tag: ${{ inputs.tag }}-arm64
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
runner: ubuntu-22.04-arm
arch: arm64
secrets: inherit
build-kata-static-tarball-s390x:
@ -74,9 +78,17 @@ jobs:
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
build-kata-static-tarball-riscv64:
uses: ./.github/workflows/build-kata-static-tarball-riscv64.yaml
with:
tarball-suffix: -${{ inputs.tag }}
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
secrets: inherit
publish-kata-deploy-payload-s390x:
needs: build-kata-static-tarball-s390x
uses: ./.github/workflows/publish-kata-deploy-payload-s390x.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
@ -84,11 +96,13 @@ jobs:
tag: ${{ inputs.tag }}-s390x
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
runner: s390x
arch: s390x
secrets: inherit
publish-kata-deploy-payload-ppc64le:
needs: build-kata-static-tarball-ppc64le
uses: ./.github/workflows/publish-kata-deploy-payload-ppc64le.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
@ -96,6 +110,8 @@ jobs:
tag: ${{ inputs.tag }}-ppc64le
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
runner: ppc64le
arch: ppc64le
secrets: inherit
build-and-publish-tee-confidential-unencrypted-image:
@ -114,20 +130,20 @@ jobs:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
- name: Login to Kata Containers ghcr.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0
with:
tags: ghcr.io/kata-containers/test-images:unencrypted-${{ inputs.pr-number }}
push: true
@ -167,17 +183,17 @@ jobs:
cp /opt/kata/bin/csi-kata-directvolume src/tools/csi-kata-directvolume/bin/directvolplugin
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
- name: Login to Kata Containers ghcr.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0
with:
tags: ghcr.io/kata-containers/csi-kata-directvolume:${{ inputs.pr-number }}
push: true
@ -221,6 +237,18 @@ jobs:
target-branch: ${{ inputs.target-branch }}
secrets: inherit
run-k8s-tests-on-arm64:
if: ${{ inputs.skip-test != 'yes' }}
needs: publish-kata-deploy-payload-arm64
uses: ./.github/workflows/run-k8s-tests-on-arm64.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ inputs.tag }}-arm64
commit-hash: ${{ inputs.commit-hash }}
pr-number: ${{ inputs.pr-number }}
target-branch: ${{ inputs.target-branch }}
run-kata-coco-tests:
if: ${{ inputs.skip-test != 'yes' }}
needs:
@ -263,13 +291,30 @@ jobs:
pr-number: ${{ inputs.pr-number }}
target-branch: ${{ inputs.target-branch }}
run-metrics-tests:
run-kata-deploy-tests:
if: ${{ inputs.skip-test != 'yes' }}
needs: [publish-kata-deploy-payload-amd64]
uses: ./.github/workflows/run-kata-deploy-tests.yaml
with:
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ inputs.tag }}-amd64
commit-hash: ${{ inputs.commit-hash }}
pr-number: ${{ inputs.pr-number }}
target-branch: ${{ inputs.target-branch }}
run-metrics-tests:
# Skip metrics tests whilst runner is broken
if: false
# if: ${{ inputs.skip-test != 'yes' }}
needs: build-kata-static-tarball-amd64
uses: ./.github/workflows/run-metrics.yaml
with:
tarball-suffix: -${{ inputs.tag }}
registry: ghcr.io
repo: ${{ github.repository_owner }}/kata-deploy-ci
tag: ${{ inputs.tag }}-amd64
commit-hash: ${{ inputs.commit-hash }}
pr-number: ${{ inputs.pr-number }}
target-branch: ${{ inputs.target-branch }}
run-basic-amd64-tests:
@ -281,10 +326,10 @@ jobs:
commit-hash: ${{ inputs.commit-hash }}
target-branch: ${{ inputs.target-branch }}
run-cri-containerd-tests-s390x:
run-basic-s390x-tests:
if: ${{ inputs.skip-test != 'yes' }}
needs: build-kata-static-tarball-s390x
uses: ./.github/workflows/run-cri-containerd-tests-s390x.yaml
uses: ./.github/workflows/basic-ci-s390x.yaml
with:
tarball-suffix: -${{ inputs.tag }}
commit-hash: ${{ inputs.commit-hash }}

95
.github/workflows/codeql.yml vendored Normal file
View File

@ -0,0 +1,95 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL Advanced"
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '45 0 * * 1'
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ubuntu-24.04
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: go
build-mode: manual
- language: python
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Add any setup steps before running the `github/codeql-action/init` action.
# This includes steps like installing compilers or runtimes (`actions/setup-node`
# or others). This is typically only required for manual builds.
# - name: Setup runtime (example)
# uses: actions/setup-example@v1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual' && matrix.language == 'go'
shell: bash
run: |
make -C src/runtime
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"

View File

@ -26,7 +26,7 @@ jobs:
- name: Get PR Commits
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
id: 'get-pr-commits'
uses: tim-actions/get-pr-commits@v1.2.0
uses: tim-actions/get-pr-commits@c64db31d359214d244884dd68f971a110b29ab83 # v1.2.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
# Filter out revert commits
@ -41,19 +41,19 @@ jobs:
- name: DCO Check
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') }}
uses: tim-actions/dco@2fd0504dc0d27b33f542867c300c60840c6dcb20
uses: tim-actions/dco@2fd0504dc0d27b33f542867c300c60840c6dcb20 # master (2020-04-28)
with:
commits: ${{ steps.get-pr-commits.outputs.commits }}
- name: Commit Body Missing Check
if: ${{ !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') && ( success() || failure() ) }}
uses: tim-actions/commit-body-check@v1.0.2
uses: tim-actions/commit-body-check@d2e0e8e1f0332b3281c98867c42a2fbe25ad3f15 # v1.0.2
with:
commits: ${{ steps.get-pr-commits.outputs.commits }}
- name: Check Subject Line Length
if: ${{ (env.PR_AUTHOR != 'dependabot[bot]') && !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') && ( success() || failure() ) }}
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
uses: tim-actions/commit-message-checker-with-regex@d6d9770051dd6460679d1cab1dcaa8cffc5c2bbd # v0.3.1
with:
commits: ${{ steps.get-pr-commits.outputs.commits }}
pattern: '^.{0,75}(\n.*)*$'
@ -62,7 +62,7 @@ jobs:
- name: Check Body Line Length
if: ${{ (env.PR_AUTHOR != 'dependabot[bot]') && !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') && ( success() || failure() ) }}
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
uses: tim-actions/commit-message-checker-with-regex@d6d9770051dd6460679d1cab1dcaa8cffc5c2bbd # v0.3.1
with:
commits: ${{ steps.get-pr-commits.outputs.commits }}
# Notes:
@ -93,7 +93,7 @@ jobs:
- name: Check Subsystem
if: ${{ (env.PR_AUTHOR != 'dependabot[bot]') && !contains(github.event.pull_request.labels.*.name, 'force-skip-ci') && ( success() || failure() ) }}
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
uses: tim-actions/commit-message-checker-with-regex@d6d9770051dd6460679d1cab1dcaa8cffc5c2bbd # v0.3.1
with:
commits: ${{ steps.get-pr-commits.outputs.commits }}
pattern: '^[\s\t]*[^:\s\t]+[\s\t]*:'

View File

@ -18,7 +18,7 @@ jobs:
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 1.22.11
go-version: 1.23.7
- name: Checkout code
uses: actions/checkout@v4
- name: Build utils

View File

@ -14,7 +14,7 @@ jobs:
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 1.22.11
go-version: 1.23.7
env:
GOPATH: ${{ github.workspace }}/kata-containers
- name: Set env

View File

@ -32,7 +32,7 @@ jobs:
push-to-registry: yes
target-branch: ${{ github.ref_name }}
secrets: inherit
build-assets-ppc64le:
uses: ./.github/workflows/build-kata-static-tarball-ppc64le.yaml
with:
@ -43,46 +43,54 @@ jobs:
publish-kata-deploy-payload-amd64:
needs: build-assets-amd64
uses: ./.github/workflows/publish-kata-deploy-payload-amd64.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
commit-hash: ${{ github.sha }}
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-latest-amd64
target-branch: ${{ github.ref_name }}
runner: ubuntu-22.04
arch: amd64
secrets: inherit
publish-kata-deploy-payload-arm64:
needs: build-assets-arm64
uses: ./.github/workflows/publish-kata-deploy-payload-arm64.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
commit-hash: ${{ github.sha }}
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-latest-arm64
target-branch: ${{ github.ref_name }}
runner: ubuntu-22.04-arm
arch: arm64
secrets: inherit
publish-kata-deploy-payload-s390x:
needs: build-assets-s390x
uses: ./.github/workflows/publish-kata-deploy-payload-s390x.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
commit-hash: ${{ github.sha }}
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-latest-s390x
target-branch: ${{ github.ref_name }}
runner: s390x
arch: s390x
secrets: inherit
publish-kata-deploy-payload-ppc64le:
needs: build-assets-ppc64le
uses: ./.github/workflows/publish-kata-deploy-payload-ppc64le.yaml
uses: ./.github/workflows/publish-kata-deploy-payload.yaml
with:
commit-hash: ${{ github.sha }}
registry: quay.io
repo: kata-containers/kata-deploy-ci
tag: kata-containers-latest-ppc64le
target-branch: ${{ github.ref_name }}
runner: ppc64le
arch: ppc64le
secrets: inherit
publish-manifest:
@ -93,7 +101,7 @@ jobs:
uses: actions/checkout@v4
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -1,66 +0,0 @@
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
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
kata-payload:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: get-kata-tarball
uses: actions/download-artifact@v4
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@v3
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@v3
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

@ -1,66 +0,0 @@
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
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
kata-payload:
runs-on: ubuntu-22.04-arm
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: get-kata-tarball
uses: actions/download-artifact@v4
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@v3
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@v3
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

@ -1,66 +0,0 @@
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
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
kata-payload:
runs-on: s390x
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: get-kata-tarball
uses: actions/download-artifact@v4
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@v3
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@v3
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

@ -1,4 +1,4 @@
name: CI | Publish kata-deploy payload for ppc64le
name: CI | Publish kata-deploy payload
on:
workflow_call:
inputs:
@ -21,21 +21,20 @@ on:
required: false
type: string
default: ""
runner:
default: 'ubuntu-22.04'
description: The runner to execute the workflow on. Defaults to 'ubuntu-22.04'.
required: false
type: string
arch:
description: The arch of the tarball.
required: true
type: string
jobs:
kata-payload:
runs-on: ppc64le
runs-on: ${{ inputs.runner }}
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
"${HOME}/scripts/prepare_runner.sh"
sudo rm -rf "$GITHUB_WORKSPACE"/*
- name: Adjust a permission for repo
run: |
sudo chown -R "$USER":"$USER" "$GITHUB_WORKSPACE"
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
@ -47,14 +46,14 @@ jobs:
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: get-kata-tarball
- name: get-kata-tarball for ${{ inputs.arch }}
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-ppc64le${{ inputs.tarball-suffix }}
name: kata-static-tarball-${{ inputs.arch}}${{ inputs.tarball-suffix }}
- name: Login to Kata Containers quay.io
if: ${{ inputs.registry == 'quay.io' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -62,13 +61,13 @@ jobs:
- name: Login to Kata Containers ghcr.io
if: ${{ inputs.registry == 'ghcr.io' }}
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: build-and-push-kata-payload
- name: build-and-push-kata-payload for ${{ inputs.arch }}
id: build-and-push-kata-payload
run: |
./tools/packaging/kata-deploy/local-build/kata-deploy-build-and-upload-payload.sh \

View File

@ -19,13 +19,13 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -19,13 +19,13 @@ jobs:
runs-on: ubuntu-22.04-arm
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -18,20 +18,14 @@ jobs:
needs: build-kata-static-tarball-ppc64le
runs-on: ppc64le
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
bash "${HOME}/scripts/prepare_runner.sh"
sudo rm -rf "$GITHUB_WORKSPACE"/*
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -19,13 +19,13 @@ jobs:
runs-on: s390x
steps:
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}

View File

@ -53,13 +53,13 @@ jobs:
uses: actions/checkout@v4
- name: Login to Kata Containers docker.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Kata Containers quay.io
uses: docker/login-action@v3
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
with:
registry: quay.io
username: ${{ secrets.QUAY_DEPLOYER_USERNAME }}
@ -183,7 +183,7 @@ jobs:
uses: actions/checkout@v4
- name: Install helm
uses: azure/setup-helm@v4.2.0
uses: azure/setup-helm@fe7b79cd5ee1e45176fcad797de68ecaf3ca4814 # v4.2.0
id: install
- name: Generate and upload helm chart tarball

View File

@ -29,15 +29,6 @@ jobs:
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
steps:
- name: Adjust a permission for repo
run: sudo chown -R "$USER":"$USER" "$GITHUB_WORKSPACE"
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
bash "${HOME}/scripts/prepare_runner.sh" cri-containerd
sudo rm -rf "$GITHUB_WORKSPACE"/*
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
@ -64,6 +55,3 @@ jobs:
- name: Run cri-containerd tests
run: bash tests/integration/cri-containerd/gha-run.sh run
- name: Cleanup actions for the self hosted runner
run: bash "${HOME}/scripts/cleanup_runner.sh"

View File

@ -1,56 +0,0 @@
name: CI | Run cri-containerd tests
on:
workflow_call:
inputs:
tarball-suffix:
required: false
type: string
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
run-cri-containerd:
strategy:
# We can set this to true whenever we're 100% sure that
# the all the tests are not flaky, otherwise we'll fail
# all the tests due to a single flaky instance
fail-fast: false
matrix:
containerd_version: ['active']
vmm: ['qemu', 'qemu-runtime-rs']
runs-on: s390x-large
env:
CONTAINERD_VERSION: ${{ matrix.containerd_version }}
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Install dependencies
run: bash tests/integration/cri-containerd/gha-run.sh install-dependencies
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-s390x${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/integration/cri-containerd/gha-run.sh install-kata kata-artifacts
- name: Run cri-containerd tests
run: bash tests/integration/cri-containerd/gha-run.sh run

View File

@ -103,7 +103,7 @@ jobs:
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
- name: Create AKS cluster
uses: nick-fields/retry@v3
uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3.0.2
with:
timeout_minutes: 15
max_attempts: 20

View File

@ -0,0 +1,83 @@
name: CI | Run kubernetes tests on arm64
on:
workflow_call:
inputs:
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
pr-number:
required: true
type: string
commit-hash:
required: false
type: string
target-branch:
required: false
type: string
default: ""
jobs:
run-k8s-tests-on-arm64:
strategy:
fail-fast: false
matrix:
vmm:
- qemu
k8s:
- kubeadm
runs-on: arm64-k8s
env:
DOCKER_REGISTRY: ${{ inputs.registry }}
DOCKER_REPO: ${{ inputs.repo }}
DOCKER_TAG: ${{ inputs.tag }}
GH_PR_NUMBER: ${{ inputs.pr-number }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
KUBERNETES: ${{ matrix.k8s }}
USING_NFD: "false"
K8S_TEST_HOST_TYPE: all
TARGET_ARCH: "aarch64"
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Deploy Kata
timeout-minutes: 10
run: bash tests/integration/kubernetes/gha-run.sh deploy-kata
- name: Install `bats`
run: bash tests/integration/kubernetes/gha-run.sh install-bats
- name: Run tests
timeout-minutes: 30
run: bash tests/integration/kubernetes/gha-run.sh run-tests
- name: Collect artifacts ${{ matrix.vmm }}
if: always()
run: bash tests/integration/kubernetes/gha-run.sh collect-artifacts
continue-on-error: true
- name: Archive artifacts ${{ matrix.vmm }}
uses: actions/upload-artifact@v4
with:
name: k8s-tests-${{ matrix.vmm }}-${{ matrix.k8s }}-${{ inputs.tag }}
path: /tmp/artifacts
retention-days: 1
- name: Delete kata-deploy
if: always()
timeout-minutes: 5
run: bash tests/integration/kubernetes/gha-run.sh cleanup

View File

@ -43,12 +43,6 @@ jobs:
USING_NFD: "false"
TARGET_ARCH: "ppc64le"
steps:
- name: Prepare the self-hosted runner
timeout-minutes: 15
run: |
bash "${HOME}/scripts/prepare_runner.sh" kubernetes
sudo rm -rf "$GITHUB_WORKSPACE"/*
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}

View File

@ -87,7 +87,7 @@ jobs:
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
- name: Create AKS cluster
uses: nick-fields/retry@v3
uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3.0.2
with:
timeout_minutes: 15
max_attempts: 20

View File

@ -222,6 +222,11 @@ jobs:
AUTHENTICATED_IMAGE_USER: ${{ secrets.AUTHENTICATED_IMAGE_USER }}
AUTHENTICATED_IMAGE_PASSWORD: ${{ secrets.AUTHENTICATED_IMAGE_PASSWORD }}
SNAPSHOTTER: ${{ matrix.snapshotter }}
# Caution: current ingress controller used to expose the KBS service
# requires much vCPUs, lefting only a few for the tests. Depending on the
# host type chose it will result on the creation of a cluster with
# insufficient resources.
K8S_TEST_HOST_TYPE: "all"
USING_NFD: "false"
AUTO_GENERATE_POLICY: "yes"
steps:
@ -257,7 +262,7 @@ jobs:
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
- name: Create AKS cluster
uses: nick-fields/retry@v3
uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3.0.2
with:
timeout_minutes: 15
max_attempts: 20

View File

@ -71,7 +71,7 @@ jobs:
AZ_SUBSCRIPTION_ID: ${{ secrets.AZ_SUBSCRIPTION_ID }}
- name: Create AKS cluster
uses: nick-fields/retry@v3
uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3.0.2
with:
timeout_minutes: 15
max_attempts: 20

View File

@ -1,4 +1,4 @@
name: CI | Run kata-deploy tests on GARM
name: CI | Run kata-deploy tests
on:
workflow_call:
inputs:
@ -28,17 +28,13 @@ jobs:
fail-fast: false
matrix:
vmm:
- clh
- qemu
k8s:
- k0s
- k3s
- rke2
# TODO: There are a couple of vmm/k8s combination failing (https://github.com/kata-containers/kata-containers/issues/9854)
# and we will put the entire kata-deploy-tests on GARM on maintenance.
# TODO: Transition to free runner (see #9940).
if: false
runs-on: garm-ubuntu-2004-smaller
- microk8s
runs-on: ubuntu-22.04
env:
DOCKER_REGISTRY: ${{ inputs.registry }}
DOCKER_REPO: ${{ inputs.repo }}

View File

@ -2,8 +2,17 @@ name: CI | Run test metrics
on:
workflow_call:
inputs:
tarball-suffix:
required: false
registry:
required: true
type: string
repo:
required: true
type: string
tag:
required: true
type: string
pr-number:
required: true
type: string
commit-hash:
required: false
@ -14,34 +23,7 @@ on:
default: ""
jobs:
setup-kata:
name: Kata Setup
runs-on: metrics
env:
GOPATH: ${{ github.workspace }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: get-kata-tarball
uses: actions/download-artifact@v4
with:
name: kata-static-tarball-amd64${{ inputs.tarball-suffix }}
path: kata-artifacts
- name: Install kata
run: bash tests/metrics/gha-run.sh install-kata kata-artifacts
run-metrics:
needs: setup-kata
strategy:
# We can set this to true whenever we're 100% sure that
# the all the tests are not flaky, otherwise we'll fail
@ -54,34 +36,78 @@ jobs:
env:
GOPATH: ${{ github.workspace }}
KATA_HYPERVISOR: ${{ matrix.vmm }}
DOCKER_REGISTRY: ${{ inputs.registry }}
DOCKER_REPO: ${{ inputs.repo }}
DOCKER_TAG: ${{ inputs.tag }}
GH_PR_NUMBER: ${{ inputs.pr-number }}
K8S_TEST_HOST_TYPE: "baremetal"
USING_NFD: "false"
KUBERNETES: kubeadm
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.commit-hash }}
fetch-depth: 0
- name: Rebase atop of the latest target branch
run: |
./tests/git-helper.sh "rebase-atop-of-the-latest-target-branch"
env:
TARGET_BRANCH: ${{ inputs.target-branch }}
- name: Deploy Kata
timeout-minutes: 10
run: bash tests/integration/kubernetes/gha-run.sh deploy-kata-kubeadm
- name: Install check metrics
run: bash tests/metrics/gha-run.sh install-checkmetrics
- name: enabling the hypervisor
run: bash tests/metrics/gha-run.sh enabling-hypervisor
- name: run launch times test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-launchtimes
- name: run memory foot print test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-memory-usage
- name: run memory usage inside container test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-memory-usage-inside-container
- name: run blogbench test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-blogbench
- name: run tensorflow test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-tensorflow
- name: run fio test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-fio
- name: run iperf test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-iperf
- name: run latency test
timeout-minutes: 15
continue-on-error: true
run: bash tests/metrics/gha-run.sh run-test-latency
- name: check metrics
run: bash tests/metrics/gha-run.sh check-metrics
- name: make metrics tarball ${{ matrix.vmm }}
run: bash tests/metrics/gha-run.sh make-tarball-results
@ -92,3 +118,8 @@ jobs:
path: results-${{ matrix.vmm }}.tar.gz
retention-days: 1
if-no-files-found: error
- name: Delete kata-deploy
timeout-minutes: 10
if: always()
run: bash tests/integration/kubernetes/gha-run.sh cleanup-kubeadm

View File

@ -25,5 +25,6 @@ jobs:
- uses: actions/checkout@v4
- name: Run ShellCheck
uses: ludeeus/action-shellcheck@master
uses: ludeeus/action-shellcheck@00b27aa7cb85167568cb48a3838b75f4265f2bca # master (2024-06-20)
with:
ignore_paths: "**/vendor/**"

View File

@ -0,0 +1,32 @@
# https://github.com/marketplace/actions/shellcheck
name: Shellcheck required
on:
workflow_dispatch:
pull_request:
types:
- opened
- edited
- reopened
- synchronize
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
shellcheck-required:
runs-on: ubuntu-24.04
steps:
- name: Checkout the code
uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/checkout@v4
- name: Run ShellCheck
uses: ludeeus/action-shellcheck@00b27aa7cb85167568cb48a3838b75f4265f2bca # master (2024-06-20)
with:
severity: error
ignore_paths: "**/vendor/**"

View File

@ -32,3 +32,15 @@ jobs:
uses: ./.github/workflows/build-checks.yaml
with:
instance: ${{ matrix.instance }}
build-checks-preview:
needs: skipper
if: ${{ needs.skipper.outputs.skip_static != 'yes' }}
strategy:
fail-fast: false
matrix:
instance:
- "riscv-builder"
uses: ./.github/workflows/build-checks-preview-riscv64.yaml
with:
instance: ${{ matrix.instance }}

View File

@ -70,7 +70,7 @@ jobs:
fetch-depth: 0
- name: Install system deps
run: |
sudo apt-get install -y build-essential musl-tools
sudo apt-get update && sudo apt-get install -y build-essential musl-tools
- name: Install yq
run: |
sudo -E ./ci/install_yq.sh
@ -87,6 +87,7 @@ jobs:
${{ matrix.command }}
env:
RUST_BACKTRACE: "1"
RUST_LIB_BACKTRACE: "0"
static-checks:
runs-on: ubuntu-22.04
@ -118,7 +119,7 @@ jobs:
echo "/usr/local/go/bin" >> "$GITHUB_PATH"
- name: Install system dependencies
run: |
sudo apt-get -y install moreutils hunspell hunspell-en-gb hunspell-en-us pandoc
sudo apt-get update && sudo apt-get -y install moreutils hunspell hunspell-en-gb hunspell-en-us pandoc
- name: Run check
run: |
export PATH="${PATH}:${GOPATH}/bin"

View File

@ -1 +1 @@
3.14.0
3.16.0

View File

@ -172,12 +172,28 @@ For new jobs, or jobs that haven't been marked as required recently,
the criteria to be initially marked as required is ten days
of passing tests, with no relevant PR failures reported in that time.
Required jobs also need one or more nominated maintainers that are
responsible for the stability of their jobs.
responsible for the stability of their jobs. Maintainers can be registered
in [`maintainers.yml`](https://github.com/kata-containers/kata-containers.github.io/blob/main/maintainers.yml)
and will then show on the CI Dashboard.
> [!NOTE]
> We don't currently have a good place to record the job maintainers, but
> once we have this, the intention is to show it on the CI Dashboard so
> people can find the contact easily.
To add transparency to making jobs required/non-required and to keep the
GitHub UI in sync with the [Gatekeeper job](../tools/testing/gatekeeper),
the process to update a job's required state is as follows:
1. Create a PR to update `maintainers.yml`, if new maintainers are being
declared on a CI job.
1. Create a PR which updates
[`required-tests.yaml`](../tools/testing/gatekeeper/required-tests.yaml)
adding the new job and listing the evidence that the job meets the
requirements above. Ensure that all maintainers and
@kata-containers/architecture-committee are notified to give them the
opportunity to review the PR. See
[#11015](https://github.com/kata-containers/kata-containers/pull/11015)
as an example.
1. The maintainers and Architecture Committee get a chance to review the PR.
It can be discussed in an AC meeting to get broader input.
1. Once the PR has been merged, a Kata Containers admin should be notified
to ensure that the GitHub UI is updated to reflect the change in
`required-tests.yaml`.
#### Expectation of required job maintainers

View File

@ -7,16 +7,16 @@
set -e
cidir=$(dirname "$0")
runtimedir=$cidir/../src/runtime
runtimedir=${cidir}/../src/runtime
build_working_packages() {
# working packages:
device_api=$runtimedir/pkg/device/api
device_config=$runtimedir/pkg/device/config
device_drivers=$runtimedir/pkg/device/drivers
device_manager=$runtimedir/pkg/device/manager
rc_pkg_dir=$runtimedir/pkg/resourcecontrol/
utils_pkg_dir=$runtimedir/virtcontainers/utils
device_api=${runtimedir}/pkg/device/api
device_config=${runtimedir}/pkg/device/config
device_drivers=${runtimedir}/pkg/device/drivers
device_manager=${runtimedir}/pkg/device/manager
rc_pkg_dir=${runtimedir}/pkg/resourcecontrol/
utils_pkg_dir=${runtimedir}/virtcontainers/utils
# broken packages :( :
#katautils=$runtimedir/pkg/katautils
@ -24,15 +24,15 @@ build_working_packages() {
#vc=$runtimedir/virtcontainers
pkgs=(
"$device_api"
"$device_config"
"$device_drivers"
"$device_manager"
"$utils_pkg_dir"
"$rc_pkg_dir")
"${device_api}"
"${device_config}"
"${device_drivers}"
"${device_manager}"
"${utils_pkg_dir}"
"${rc_pkg_dir}")
for pkg in "${pkgs[@]}"; do
echo building "$pkg"
pushd "$pkg" &>/dev/null
echo building "${pkg}"
pushd "${pkg}" &>/dev/null
go build
go test
popd &>/dev/null

View File

@ -10,7 +10,7 @@ set -o errtrace
set -o nounset
set -o pipefail
[ -n "${DEBUG:-}" ] && set -o xtrace
[[ -n "${DEBUG:-}" ]] && set -o xtrace
script_name=${0##*/}
@ -25,7 +25,7 @@ die()
usage()
{
cat <<EOF
Usage: $script_name [OPTIONS] [command] [arguments]
Usage: ${script_name} [OPTIONS] [command] [arguments]
Description: Utility to expand the abilities of the GitHub CLI tool, gh.
@ -48,7 +48,7 @@ Examples:
- List issues for a Pull Request 123 in kata-containers/kata-containers repo
$ $script_name list-issues-for-pr 123
$ ${script_name} list-issues-for-pr 123
EOF
}
@ -57,11 +57,12 @@ list_issues_for_pr()
local pr="${1:-}"
local repo="${2:-kata-containers/kata-containers}"
[ -z "$pr" ] && die "need PR"
[[ -z "${pr}" ]] && die "need PR"
local commits=$(gh pr view ${pr} --repo ${repo} --json commits --jq .commits[].messageBody)
local commits
commits=$(gh pr view "${pr}" --repo "${repo}" --json commits --jq .commits[].messageBody)
[ -z "$commits" ] && die "cannot determine commits for PR $pr"
[[ -z "${commits}" ]] && die "cannot determine commits for PR ${pr}"
# Extract the issue number(s) from the commits.
#
@ -78,7 +79,8 @@ list_issues_for_pr()
#
# "<git-commit> <git-commit-msg>"
#
local issues=$(echo "$commits" |\
local issues
issues=$(echo "${commits}" |\
grep -v -E "^( | )" |\
grep -i -E "fixes:* *(#*[0-9][0-9]*)" |\
tr ' ' '\n' |\
@ -86,16 +88,16 @@ list_issues_for_pr()
sed 's/[.,\#]//g' |\
sort -nu || true)
[ -z "$issues" ] && die "cannot determine issues for PR $pr"
[[ -z "${issues}" ]] && die "cannot determine issues for PR ${pr}"
echo "# Issues linked to PR"
echo "#"
echo "# Fields: issue_number"
local issue
echo "$issues"|while read issue
echo "${issues}" | while read -r issue
do
printf "%s\n" "$issue"
printf "%s\n" "${issue}"
done
}
@ -103,20 +105,21 @@ list_labels_for_issue()
{
local issue="${1:-}"
[ -z "$issue" ] && die "need issue number"
[[ -z "${issue}" ]] && die "need issue number"
local labels=$(gh issue view ${issue} --repo kata-containers/kata-containers --json labels)
local labels
labels=$(gh issue view "${issue}" --repo kata-containers/kata-containers --json labels)
[ -z "$labels" ] && die "cannot determine labels for issue $issue"
[[ -z "${labels}" ]] && die "cannot determine labels for issue ${issue}"
printf "$labels"
echo "${labels}"
}
setup()
{
for cmd in gh jq
do
command -v "$cmd" &>/dev/null || die "need command: $cmd"
command -v "${cmd}" &>/dev/null || die "need command: ${cmd}"
done
}
@ -124,29 +127,28 @@ handle_args()
{
setup
local show_all="false"
local opt
while getopts "ahr:" opt "$@"
while getopts "hr:" opt "$@"
do
case "$opt" in
a) show_all="true" ;;
case "${opt}" in
h) usage && exit 0 ;;
r) repo="${OPTARG}" ;;
*) echo "use '-h' to get list of supprted aruments" && exit 1 ;;
esac
done
shift $(($OPTIND - 1))
shift $((OPTIND - 1))
local repo="${repo:-kata-containers/kata-containers}"
local cmd="${1:-}"
case "$cmd" in
case "${cmd}" in
list-issues-for-pr) ;;
list-labels-for-issue) ;;
"") usage && exit 0 ;;
*) die "invalid command: '$cmd'" ;;
*) die "invalid command: '${cmd}'" ;;
esac
# Consume the command name
@ -155,20 +157,20 @@ handle_args()
local issue=""
local pr=""
case "$cmd" in
case "${cmd}" in
list-issues-for-pr)
pr="${1:-}"
list_issues_for_pr "$pr" "${repo}"
list_issues_for_pr "${pr}" "${repo}"
;;
list-labels-for-issue)
issue="${1:-}"
list_labels_for_issue "$issue"
list_labels_for_issue "${issue}"
;;
*) die "impossible situation: cmd: '$cmd'" ;;
*) die "impossible situation: cmd: '${cmd}'" ;;
esac
exit 0

View File

@ -8,7 +8,6 @@
set -o errexit
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
script_name="$(basename "${BASH_SOURCE[0]}")"
source "${script_dir}/../tests/common.bash"
@ -22,11 +21,11 @@ workdir="$(mktemp -d --tmpdir build-libseccomp.XXXXX)"
# Variables for libseccomp
libseccomp_version="${LIBSECCOMP_VERSION:-""}"
if [ -z "${libseccomp_version}" ]; then
if [[ -z "${libseccomp_version}" ]]; then
libseccomp_version=$(get_from_kata_deps ".externals.libseccomp.version")
fi
libseccomp_url="${LIBSECCOMP_URL:-""}"
if [ -z "${libseccomp_url}" ]; then
if [[ -z "${libseccomp_url}" ]]; then
libseccomp_url=$(get_from_kata_deps ".externals.libseccomp.url")
fi
libseccomp_tarball="libseccomp-${libseccomp_version}.tar.gz"
@ -35,11 +34,11 @@ cflags="-O2"
# Variables for gperf
gperf_version="${GPERF_VERSION:-""}"
if [ -z "${gperf_version}" ]; then
if [[ -z "${gperf_version}" ]]; then
gperf_version=$(get_from_kata_deps ".externals.gperf.version")
fi
gperf_url="${GPERF_URL:-""}"
if [ -z "${gperf_url}" ]; then
if [[ -z "${gperf_url}" ]]; then
gperf_url=$(get_from_kata_deps ".externals.gperf.url")
fi
gperf_tarball="gperf-${gperf_version}.tar.gz"
@ -47,7 +46,7 @@ gperf_tarball_url="${gperf_url}/${gperf_tarball}"
# We need to build the libseccomp library from sources to create a static library for the musl libc.
# However, ppc64le and s390x have no musl targets in Rust. Hence, we do not set cflags for the musl libc.
if ([ "${arch}" != "ppc64le" ] && [ "${arch}" != "s390x" ]); then
if [[ "${arch}" != "ppc64le" ]] && [[ "${arch}" != "s390x" ]]; then
# Set FORTIFY_SOURCE=1 because the musl-libc does not have some functions about FORTIFY_SOURCE=2
cflags="-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2"
fi
@ -71,10 +70,10 @@ build_and_install_gperf() {
tar -xf "${gperf_tarball}"
pushd "gperf-${gperf_version}"
# Unset $CC for configure, we will always use native for gperf
CC= ./configure --prefix="${gperf_install_dir}"
CC="" ./configure --prefix="${gperf_install_dir}"
make
make install
export PATH=$PATH:"${gperf_install_dir}"/bin
export PATH=${PATH}:"${gperf_install_dir}"/bin
popd
echo "Gperf installed successfully"
}
@ -85,7 +84,7 @@ build_and_install_libseccomp() {
curl -sLO "${libseccomp_tarball_url}"
tar -xf "${libseccomp_tarball}"
pushd "libseccomp-${libseccomp_version}"
[ "${arch}" == $(uname -m) ] && cc_name="" || cc_name="${arch}-linux-gnu-gcc"
[[ "${arch}" == $(uname -m) ]] && cc_name="" || cc_name="${arch}-linux-gnu-gcc"
CC=${cc_name} ./configure --prefix="${libseccomp_install_dir}" CFLAGS="${cflags}" --enable-static --host="${arch}"
make
make install
@ -97,11 +96,11 @@ main() {
local libseccomp_install_dir="${1:-}"
local gperf_install_dir="${2:-}"
if [ -z "${libseccomp_install_dir}" ] || [ -z "${gperf_install_dir}" ]; then
if [[ -z "${libseccomp_install_dir}" ]] || [[ -z "${gperf_install_dir}" ]]; then
die "Usage: ${0} <libseccomp-install-dir> <gperf-install-dir>"
fi
pushd "$workdir"
pushd "${workdir}"
# gperf is required for building the libseccomp.
build_and_install_gperf
build_and_install_libseccomp

View File

@ -5,20 +5,20 @@
# SPDX-License-Identifier: Apache-2.0
#
[ -n "$DEBUG" ] && set -o xtrace
[[ -n "${DEBUG}" ]] && set -o xtrace
# If we fail for any reason a message will be displayed
die() {
msg="$*"
echo "ERROR: $msg" >&2
echo "ERROR: ${msg}" >&2
exit 1
}
function verify_yq_exists() {
local yq_path=$1
local yq_version=$2
local expected="yq (https://github.com/mikefarah/yq/) version $yq_version"
if [ -x "${yq_path}" ] && [ "$($yq_path --version)"X == "$expected"X ]; then
local expected="yq (https://github.com/mikefarah/yq/) version ${yq_version}"
if [[ -x "${yq_path}" ]] && [[ "$(${yq_path} --version)"X == "${expected}"X ]]; then
return 0
else
return 1
@ -34,20 +34,20 @@ function install_yq() {
local yq_path=""
INSTALL_IN_GOPATH=${INSTALL_IN_GOPATH:-true}
if [ "${INSTALL_IN_GOPATH}" == "true" ]; then
if [[ "${INSTALL_IN_GOPATH}" == "true" ]]; then
GOPATH=${GOPATH:-${HOME}/go}
mkdir -p "${GOPATH}/bin"
yq_path="${GOPATH}/bin/yq"
else
yq_path="/usr/local/bin/yq"
fi
if verify_yq_exists "$yq_path" "$yq_version"; then
if verify_yq_exists "${yq_path}" "${yq_version}"; then
echo "yq is already installed in correct version"
return
fi
if [ "${yq_path}" == "/usr/local/bin/yq" ]; then
if [[ "${yq_path}" == "/usr/local/bin/yq" ]]; then
# Check if we need sudo to install yq
if [ ! -w "/usr/local/bin" ]; then
if [[ ! -w "/usr/local/bin" ]]; then
# Check if we have sudo privileges
if ! sudo -n true 2>/dev/null; then
die "Please provide sudo privileges to install yq"
@ -76,7 +76,7 @@ function install_yq() {
# If we're on an apple silicon machine, just assign amd64.
# The version of yq we use doesn't have a darwin arm build,
# but Rosetta can come to the rescue here.
if [ $goos == "Darwin" ]; then
if [[ ${goos} == "Darwin" ]]; then
goarch=amd64
else
goarch=arm64
@ -107,8 +107,7 @@ function install_yq() {
## NOTE: ${var,,} => gives lowercase value of var
local yq_url="https://${yq_pkg}/releases/download/${yq_version}/yq_${goos}_${goarch}"
${precmd} curl -o "${yq_path}" -LSsf "${yq_url}"
[ $? -ne 0 ] && die "Download ${yq_url} failed"
${precmd} curl -o "${yq_path}" -LSsf "${yq_url}" || die "Download ${yq_url} failed"
${precmd} chmod +x "${yq_path}"
if ! command -v "${yq_path}" >/dev/null; then

View File

@ -147,3 +147,11 @@ all images with a single MCP update instead of per-image MCP update.
You can check the bisection progress during/after execution by running
``bisecter log`` from the current directory. Before starting a new
bisection you need to execute ``bisecter reset``.
Peer pods
=========
It's possible to run similar testing on peer-pods using cloud-api-adaptor.
Our CI configuration to run inside azure's OCP is in ``peer-pods-azure.sh``
and can be used to replace the `test.sh` step in snippets above.

View File

@ -3,25 +3,28 @@
#
# SPDX-License-Identifier: Apache-2.0
#
if [ "$#" -gt 2 ] || [ "$#" -lt 1 ] ; then
if [[ "$#" -gt 2 ]] || [[ "$#" -lt 1 ]] ; then
echo "Usage: $0 GOOD [BAD]"
echo "Prints list of available kata-deploy-ci tags between GOOD and BAD commits (by default BAD is the latest available tag)"
exit 255
fi
GOOD="$1"
[ -n "$2" ] && BAD="$2"
[[ -n "$2" ]] && BAD="$2"
ARCH=amd64
REPO="quay.io/kata-containers/kata-deploy-ci"
TAGS=$(skopeo list-tags "docker://$REPO")
TAGS=$(skopeo list-tags "docker://${REPO}")
# For testing
#echo "$TAGS" > tags
#TAGS=$(cat tags)
# Only amd64
TAGS=$(echo "$TAGS" | jq '.Tags' | jq "map(select(endswith(\"$ARCH\")))" | jq -r '.[]')
TAGS=$(echo "${TAGS}" | jq '.Tags' | jq "map(select(endswith(\"${ARCH}\")))" | jq -r '.[]')
# Sort by git
SORTED=""
[ -n "$BAD" ] && LOG_ARGS="$GOOD~1..$BAD" || LOG_ARGS="$GOOD~1.."
for TAG in $(git log --merges --pretty=format:%H --reverse $LOG_ARGS); do
[[ "$TAGS" =~ "$TAG" ]] && SORTED+="
kata-containers-$TAG-$ARCH"
[[ -n "${BAD}" ]] && LOG_ARGS="${GOOD}~1..${BAD}" || LOG_ARGS="${GOOD}~1.."
for TAG in $(git log --merges --pretty=format:%H --reverse "${LOG_ARGS}"); do
[[ "${TAGS}" =~ ${TAG} ]] && SORTED+="
kata-containers-${TAG}-${ARCH}"
done
# Comma separated tags with repo
echo "$SORTED" | tail -n +2 | sed -e "s@^@$REPO:@" | paste -s -d, -
echo "${SORTED}" | tail -n +2 | sed -e "s@^@${REPO}:@" | paste -s -d, -

View File

@ -7,11 +7,14 @@
# This script tries to removes most of the resources added by `test.sh` script
# from the cluster.
scripts_dir=$(dirname $0)
scripts_dir=$(dirname "$0")
deployments_dir=${scripts_dir}/cluster/deployments
configs_dir=${scripts_dir}/configs
source ${scripts_dir}/lib.sh
# shellcheck disable=SC1091 # import based on variable
source "${scripts_dir}/lib.sh"
# Set your katacontainers repo dir location
[[ -z "${katacontainers_repo_dir}" ]] && echo "Please set katacontainers_repo_dir variable to your kata repo"
# Set to 'yes' if you want to configure SELinux to permissive on the cluster
# workers.
@ -36,24 +39,23 @@ oc delete -f "${scripts_dir}/smoke/http-server.yaml"
# Delete test.sh resources
oc delete -f "${deployments_dir}/relabel_selinux.yaml"
if [[ "$WORKAROUND_9206_CRIO" == "yes" ]]; then
if [[ "${WORKAROUND_9206_CRIO}" == "yes" ]]; then
oc delete -f "${deployments_dir}/workaround-9206-crio-ds.yaml"
oc delete -f "${deployments_dir}/workaround-9206-crio.yaml"
fi
[ ${SELINUX_PERMISSIVE} == "yes" ] && oc delete -f "${deployments_dir}/machineconfig_selinux.yaml.in"
[[ ${SELINUX_PERMISSIVE} == "yes" ]] && oc delete -f "${deployments_dir}/machineconfig_selinux.yaml.in"
# Delete kata-containers
pushd "$katacontainers_repo_dir/tools/packaging/kata-deploy"
pushd "${katacontainers_repo_dir}/tools/packaging/kata-deploy" || { echo "Failed to push to ${katacontainers_repo_dir}/tools/packaging/kata-deploy"; exit 125; }
oc delete -f kata-deploy/base/kata-deploy.yaml
oc -n kube-system wait --timeout=10m --for=delete -l name=kata-deploy pod
oc apply -f kata-cleanup/base/kata-cleanup.yaml
echo "Wait for all related pods to be gone"
( repeats=1; for i in $(seq 1 600); do
( repeats=1; for _ in $(seq 1 600); do
oc get pods -l name="kubelet-kata-cleanup" --no-headers=true -n kube-system 2>&1 | grep "No resources found" -q && ((repeats++)) || repeats=1
[ "$repeats" -gt 5 ] && echo kata-cleanup finished && break
[[ "${repeats}" -gt 5 ]] && echo kata-cleanup finished && break
sleep 1
done) || { echo "There are still some kata-cleanup related pods after 600 iterations"; oc get all -n kube-system; exit -1; }
done) || { echo "There are still some kata-cleanup related pods after 600 iterations"; oc get all -n kube-system; exit 1; }
oc delete -f kata-cleanup/base/kata-cleanup.yaml
oc delete -f kata-rbac/base/kata-rbac.yaml
oc delete -f runtimeclasses/kata-runtimeClasses.yaml

View File

@ -13,8 +13,9 @@ set -e
set -o nounset
set -o pipefail
script_dir="$(realpath $(dirname $0))"
script_dir="$(realpath "$(dirname "$0")")"
webhook_dir="${script_dir}/../../../tools/testing/kata-webhook"
# shellcheck disable=SC1091 # import based on variable
source "${script_dir}/../lib.sh"
KATA_RUNTIME=${KATA_RUNTIME:-kata-ci}
@ -23,14 +24,11 @@ pushd "${webhook_dir}" >/dev/null
#
info "Builds the kata-webhook"
./create-certs.sh
info "Override our KATA_RUNTIME ConfigMap"
sed -i deploy/webhook.yaml -e "s/runtime_class: .*$/runtime_class: ${KATA_RUNTIME}/g"
info "Deploys the kata-webhook"
oc apply -f deploy/
info "Override our KATA_RUNTIME ConfigMap"
RUNTIME_CLASS="${KATA_RUNTIME}" \
envsubst < "${script_dir}/deployments/configmap_kata-webhook.yaml.in" \
| oc apply -f -
# Check the webhook was deployed and is working.
RUNTIME_CLASS="${KATA_RUNTIME}" ./webhook-check.sh
popd >/dev/null

View File

@ -1,12 +0,0 @@
# Copyright (c) 2021 Red Hat, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# Apply customizations to the kata-webhook.
#
apiVersion: v1
kind: ConfigMap
metadata:
name: kata-webhook
data:
runtime_class: ${RUNTIME_CLASS}

View File

@ -7,11 +7,15 @@
# This script installs the built kata-containers in the test cluster,
# and configure a runtime.
scripts_dir=$(dirname $0)
scripts_dir=$(dirname "$0")
deployments_dir=${scripts_dir}/deployments
configs_dir=${scripts_dir}/configs
source ${scripts_dir}/../lib.sh
# shellcheck disable=SC1091 # import based on variable
source "${scripts_dir}/../lib.sh"
# Set your katacontainers repo dir location
[[ -z "${katacontainers_repo_dir}" ]] && echo "Please set katacontainers_repo_dir variable to your kata repo"
# Set to 'yes' if you want to configure SELinux to permissive on the cluster
# workers.
@ -40,18 +44,18 @@ WORKAROUND_9206_CRIO=${WORKAROUND_9206_CRIO:-no}
#
apply_kata_deploy() {
local deploy_file="tools/packaging/kata-deploy/kata-deploy/base/kata-deploy.yaml"
pushd "$katacontainers_repo_dir"
sed -ri "s#(\s+image:) .*#\1 ${KATA_DEPLOY_IMAGE}#" "$deploy_file"
pushd "${katacontainers_repo_dir}" || die
sed -ri "s#(\s+image:) .*#\1 ${KATA_DEPLOY_IMAGE}#" "${deploy_file}"
info "Applying kata-deploy"
oc apply -f tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml
oc label --overwrite ns kube-system pod-security.kubernetes.io/enforce=privileged pod-security.kubernetes.io/warn=baseline pod-security.kubernetes.io/audit=baseline
oc apply -f "$deploy_file"
oc apply -f "${deploy_file}"
oc -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod
info "Adding the kata runtime classes"
oc apply -f tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml
popd
popd || die
}
@ -64,32 +68,32 @@ wait_for_reboot() {
local delta="${1:-900}"
local sleep_time=60
declare -A BOOTIDS
local workers=($(oc get nodes | \
awk '{if ($3 == "worker") { print $1 } }'))
local workers
mapfile -t workers < <(oc get nodes | awk '{if ($3 == "worker") { print $1 } }')
# Get the boot ID to compared it changed over time.
for node in ${workers[@]}; do
BOOTIDS[$node]=$(oc get -o jsonpath='{.status.nodeInfo.bootID}'\
node/$node)
echo "Wait $node reboot"
for node in "${workers[@]}"; do
BOOTIDS[${node}]=$(oc get -o jsonpath='{.status.nodeInfo.bootID}'\
"node/${node}")
echo "Wait ${node} reboot"
done
echo "Set timeout to $delta seconds"
echo "Set timeout to ${delta} seconds"
timer_start=$(date +%s)
while [ ${#workers[@]} -gt 0 ]; do
sleep $sleep_time
while [[ ${#workers[@]} -gt 0 ]]; do
sleep "${sleep_time}"
now=$(date +%s)
if [ $(($timer_start + $delta)) -lt $now ]; then
if [[ $((timer_start + delta)) -lt ${now} ]]; then
echo "Timeout: not all workers rebooted"
return 1
fi
echo "Checking after $(($now - $timer_start)) seconds"
for i in ${!workers[@]}; do
echo "Checking after $((now - timer_start)) seconds"
for i in "${!workers[@]}"; do
current_id=$(oc get \
-o jsonpath='{.status.nodeInfo.bootID}' \
node/${workers[i]})
if [ "$current_id" != ${BOOTIDS[${workers[i]}]} ]; then
"node/${workers[i]}")
if [[ "${current_id}" != "${BOOTIDS[${workers[i]}]}" ]]; then
echo "${workers[i]} rebooted"
unset workers[i]
unset "workers[i]"
fi
done
done
@ -102,32 +106,34 @@ wait_mcp_update() {
# and none are degraded.
local ready_count=0
local degraded_count=0
local machine_count=$(oc get mcp worker -o jsonpath='{.status.machineCount}')
local machine_count
machine_count=$(oc get mcp worker -o jsonpath='{.status.machineCount}')
if [[ -z "$machine_count" && "$machine_count" -lt 1 ]]; then
if [[ -z "${machine_count}" && "${machine_count}" -lt 1 ]]; then
warn "Unabled to obtain the machine count"
return 1
fi
echo "Set timeout to $delta seconds"
local deadline=$(($(date +%s) + $delta))
echo "Set timeout to ${delta} seconds"
local deadline=$(($(date +%s) + delta))
local now
# The ready count might not have changed yet, so wait a little.
while [[ "$ready_count" != "$machine_count" && \
"$degraded_count" == 0 ]]; do
while [[ "${ready_count}" != "${machine_count}" && \
"${degraded_count}" == 0 ]]; do
# Let's check it hit the timeout (or not).
local now=$(date +%s)
if [ $deadline -lt $now ]; then
now=$(date +%s)
if [[ ${deadline} -lt ${now} ]]; then
echo "Timeout: not all workers updated" >&2
return 1
fi
sleep $sleep_time
sleep "${sleep_time}"
ready_count=$(oc get mcp worker \
-o jsonpath='{.status.readyMachineCount}')
degraded_count=$(oc get mcp worker \
-o jsonpath='{.status.degradedMachineCount}')
echo "check machineconfigpool - ready_count: $ready_count degraded_count: $degraded_count"
echo "check machineconfigpool - ready_count: ${ready_count} degraded_count: ${degraded_count}"
done
[ $degraded_count -eq 0 ]
[[ ${degraded_count} -eq 0 ]]
}
# Enable the RHCOS extension for the Sandboxed Containers.
@ -135,10 +141,10 @@ wait_mcp_update() {
enable_sandboxedcontainers_extension() {
info "Enabling the RHCOS extension for Sandboxed Containers"
local deployment_file="${deployments_dir}/machineconfig_sandboxedcontainers_extension.yaml"
oc apply -f ${deployment_file}
oc get -f ${deployment_file} || \
oc apply -f "${deployment_file}"
oc get -f "${deployment_file}" || \
die "Sandboxed Containers extension machineconfig not found"
wait_mcp_update || die "Failed to update the machineconfigpool"
wait_mcp_update 3600 || die "Failed to update the machineconfigpool"
}
# Print useful information for debugging.
@ -148,8 +154,8 @@ enable_sandboxedcontainers_extension() {
debug_pod() {
local pod="$1"
info "Debug pod: ${pod}"
oc describe pods "$pod"
oc logs "$pod"
oc describe pods "${pod}"
oc logs "${pod}"
}
# Wait for all pods of the app label to contain expected message
@ -166,31 +172,32 @@ wait_for_app_pods_message() {
local message="$3"
local timeout="$4"
local namespace="$5"
[ -z "$pod_count" ] && pod_count=1
[ -z "$timeout" ] && timeout=60
[ -n "$namespace" ] && namespace=" -n $namespace "
[[ -z "${pod_count}" ]] && pod_count=1
[[ -z "${timeout}" ]] && timeout=60
[[ -n "${namespace}" ]] && namespace=" -n ${namespace} "
local pod
local pods
local i
SECONDS=0
while :; do
pods=($(oc get pods -l app="$app" --no-headers=true $namespace | awk '{print $1}'))
[ "${#pods}" -ge "$pod_count" ] && break
if [ "$SECONDS" -gt "$timeout" ]; then
echo "Unable to find ${pod_count} pods for '-l app=\"$app\"' in ${SECONDS}s (${pods[@]})"
return -1
mapfile -t pods < <(oc get pods -l app="${app}" --no-headers=true "${namespace}" | awk '{print $1}')
[[ "${#pods}" -ge "${pod_count}" ]] && break
if [[ "${SECONDS}" -gt "${timeout}" ]]; then
printf "Unable to find ${pod_count} pods for '-l app=\"${app}\"' in ${SECONDS}s (%s)" "${pods[@]}"
return 1
fi
done
local log
for pod in "${pods[@]}"; do
while :; do
local log=$(oc logs $namespace "$pod")
echo "$log" | grep "$message" -q && echo "Found $(echo "$log" | grep "$message") in $pod's log ($SECONDS)" && break;
if [ "$SECONDS" -gt "$timeout" ]; then
echo -n "Message '$message' not present in '${pod}' pod of the '-l app=\"$app\"' "
echo "pods after ${SECONDS}s (${pods[@]})"
echo "Pod $pod's output so far:"
echo "$log"
return -1
log=$(oc logs "${namespace}" "${pod}")
echo "${log}" | grep "${message}" -q && echo "Found $(echo "${log}" | grep "${message}") in ${pod}'s log (${SECONDS})" && break;
if [[ "${SECONDS}" -gt "${timeout}" ]]; then
echo -n "Message '${message}' not present in '${pod}' pod of the '-l app=\"${app}\"' "
printf "pods after ${SECONDS}s :(%s)\n" "${pods[@]}"
echo "Pod ${pod}'s output so far:"
echo "${log}"
return 1
fi
sleep 1;
done
@ -200,46 +207,45 @@ wait_for_app_pods_message() {
oc config set-context --current --namespace=default
worker_nodes=$(oc get nodes | awk '{if ($3 == "worker") { print $1 } }')
num_nodes=$(echo $worker_nodes | wc -w)
[ $num_nodes -ne 0 ] || \
num_nodes=$(echo "${worker_nodes}" | wc -w)
[[ ${num_nodes} -ne 0 ]] || \
die "No worker nodes detected. Something is wrong with the cluster"
if [ "${KATA_WITH_SYSTEM_QEMU}" == "yes" ]; then
if [[ "${KATA_WITH_SYSTEM_QEMU}" == "yes" ]]; then
# QEMU is deployed on the workers via RCHOS extension.
enable_sandboxedcontainers_extension
oc apply -f ${deployments_dir}/configmap_installer_qemu.yaml
oc apply -f "${deployments_dir}/configmap_installer_qemu.yaml"
fi
if [ "${KATA_WITH_HOST_KERNEL}" == "yes" ]; then
oc apply -f ${deployments_dir}/configmap_installer_kernel.yaml
if [[ "${KATA_WITH_HOST_KERNEL}" == "yes" ]]; then
oc apply -f "${deployments_dir}/configmap_installer_kernel.yaml"
fi
apply_kata_deploy
# Set SELinux to permissive mode
if [ ${SELINUX_PERMISSIVE} == "yes" ]; then
if [[ ${SELINUX_PERMISSIVE} == "yes" ]]; then
info "Configuring SELinux"
if [ -z "$SELINUX_CONF_BASE64" ]; then
export SELINUX_CONF_BASE64=$(echo \
$(cat $configs_dir/selinux.conf|base64) | \
sed -e 's/\s//g')
if [[ -z "${SELINUX_CONF_BASE64}" ]]; then
SELINUX_CONF_BASE64=$(base64 -w0 < "${configs_dir}/selinux.conf")
export SELINUX_CONF_BASE64
fi
envsubst < ${deployments_dir}/machineconfig_selinux.yaml.in | \
envsubst < "${deployments_dir}"/machineconfig_selinux.yaml.in | \
oc apply -f -
oc get machineconfig/51-kata-selinux || \
die "SELinux machineconfig not found"
# The new SELinux configuration will trigger another reboot.
wait_for_reboot
wait_for_reboot 900
fi
if [[ "$WORKAROUND_9206_CRIO" == "yes" ]]; then
if [[ "${WORKAROUND_9206_CRIO}" == "yes" ]]; then
info "Applying workaround to enable skip_mount_home in crio on OCP 4.13"
oc apply -f "${deployments_dir}/workaround-9206-crio.yaml"
oc apply -f "${deployments_dir}/workaround-9206-crio-ds.yaml"
wait_for_app_pods_message workaround-9206-crio-ds "$num_nodes" "Config file present" 1200 || echo "Failed to apply the workaround, proceeding anyway..."
wait_for_app_pods_message workaround-9206-crio-ds "${num_nodes}" "Config file present" 1200 || echo "Failed to apply the workaround, proceeding anyway..."
fi
# FIXME: Remove when https://github.com/kata-containers/kata-containers/pull/8417 is resolved
# Selinux context is currently not handled by kata-deploy
oc apply -f ${deployments_dir}/relabel_selinux.yaml
wait_for_app_pods_message restorecon "$num_nodes" "NSENTER_FINISHED_WITH:" 120 "kube-system" || echo "Failed to treat selinux, proceeding anyway..."
oc apply -f "${deployments_dir}/relabel_selinux.yaml"
wait_for_app_pods_message restorecon "${num_nodes}" "NSENTER_FINISHED_WITH:" 120 "kube-system" || echo "Failed to treat selinux, proceeding anyway..."

View File

@ -10,11 +10,12 @@ if command -v go > /dev/null; then
export GOPATH=${GOPATH:-$(go env GOPATH)}
else
# if go isn't installed, set default location for GOPATH
export GOPATH="${GOPATH:-$HOME/go}"
export GOPATH="${GOPATH:-${HOME}/go}"
fi
lib_dir=$(dirname "${BASH_SOURCE[0]}")
source "$lib_dir/../../tests/common.bash"
# shellcheck disable=SC1091 # import based on variable
source "${lib_dir}/../../tests/common.bash"
export katacontainers_repo=${katacontainers_repo:="github.com/kata-containers/kata-containers"}
export katacontainers_repo_dir="${GOPATH}/src/${katacontainers_repo}"

View File

@ -0,0 +1,217 @@
#!/bin/bash -e
# Setup peer-pods using cloud-api-adaptor on azure
#
# WARNING: When running outside "eastus" region this script creates a new
# resource group in "eastus" region and peers the network. You
# have to remove these manually (or use temporary accounts)
###############################
# Disable security to allow e2e
###############################
# Disable security
oc adm policy add-scc-to-group privileged system:authenticated system:serviceaccounts
oc adm policy add-scc-to-group anyuid system:authenticated system:serviceaccounts
oc label --overwrite ns default pod-security.kubernetes.io/enforce=privileged pod-security.kubernetes.io/warn=baseline pod-security.kubernetes.io/audit=baseline
####################################
# Get basic credentials from cluster
####################################
oc -n kube-system get secret azure-credentials -o json > azure_credentials.json
AZURE_CLIENT_ID="$(jq -r .data.azure_client_id azure_credentials.json|base64 -d)"
AZURE_CLIENT_SECRET="$(jq -r .data.azure_client_secret azure_credentials.json|base64 -d)"
AZURE_TENANT_ID="$(jq -r .data.azure_tenant_id azure_credentials.json|base64 -d)"
AZURE_SUBSCRIPTION_ID="$(jq -r .data.azure_subscription_id azure_credentials.json|base64 -d)"
rm -f azure_credentials.json
AZURE_RESOURCE_GROUP=$(oc get infrastructure/cluster -o jsonpath='{.status.platformStatus.azure.resourceGroupName}')
az login --service-principal -u "${AZURE_CLIENT_ID}" -p "${AZURE_CLIENT_SECRET}" --tenant "${AZURE_TENANT_ID}"
AZURE_VNET_NAME=$(az network vnet list --resource-group "${AZURE_RESOURCE_GROUP}" --query "[].{Name:name}" --output tsv)
AZURE_SUBNET_NAME=$(az network vnet subnet list --resource-group "${AZURE_RESOURCE_GROUP}" --vnet-name "${AZURE_VNET_NAME}" --query "[].{Id:name} | [? contains(Id, 'worker')]" --output tsv)
AZURE_SUBNET_ID=$(az network vnet subnet list --resource-group "${AZURE_RESOURCE_GROUP}" --vnet-name "${AZURE_VNET_NAME}" --query "[].{Id:id} | [? contains(Id, 'worker')]" --output tsv)
AZURE_REGION=$(az group show --resource-group "${AZURE_RESOURCE_GROUP}" --query "{Location:location}" --output tsv)
# Create workload identity
AZURE_WORKLOAD_IDENTITY_NAME="caa-${AZURE_CLIENT_ID}"
az identity create --name "${AZURE_WORKLOAD_IDENTITY_NAME}" --resource-group "${AZURE_RESOURCE_GROUP}" --location "${AZURE_REGION}"
USER_ASSIGNED_CLIENT_ID="$(az identity show --resource-group "${AZURE_RESOURCE_GROUP}" --name "${AZURE_WORKLOAD_IDENTITY_NAME}" --query 'clientId' -otsv)"
#############################
# Ensure we can run in eastus
#############################
PP_REGION=eastus
if [[ "${AZURE_REGION}" == "${PP_REGION}" ]]; then
echo "Using the current region ${AZURE_REGION}"
PP_RESOURCE_GROUP="${AZURE_RESOURCE_GROUP}"
PP_VNET_NAME="${AZURE_VNET_NAME}"
PP_SUBNET_NAME="${AZURE_SUBNET_NAME}"
PP_SUBNET_ID="${AZURE_SUBNET_ID}"
else
echo "Creating peering between ${AZURE_REGION} and ${PP_REGION}"
PP_RESOURCE_GROUP="${AZURE_RESOURCE_GROUP}-eastus"
PP_VNET_NAME="${AZURE_VNET_NAME}-eastus"
PP_SUBNET_NAME="${AZURE_SUBNET_NAME}-eastus"
PP_NSG_NAME="${AZURE_VNET_NAME}-nsg-eastus"
az group create --name "${PP_RESOURCE_GROUP}" --location "${PP_REGION}"
az network vnet create --resource-group "${PP_RESOURCE_GROUP}" --name "${PP_VNET_NAME}" --location "${PP_REGION}" --address-prefixes 10.2.0.0/16 --subnet-name "${PP_SUBNET_NAME}" --subnet-prefixes 10.2.1.0/24
az network nsg create --resource-group "${PP_RESOURCE_GROUP}" --name "${PP_NSG_NAME}" --location "${PP_REGION}"
az network vnet subnet update --resource-group "${PP_RESOURCE_GROUP}" --vnet-name "${PP_VNET_NAME}" --name "${PP_SUBNET_NAME}" --network-security-group "${PP_NSG_NAME}"
AZURE_VNET_ID=$(az network vnet show --resource-group "${AZURE_RESOURCE_GROUP}" --name "${AZURE_VNET_NAME}" --query id --output tsv)
PP_VNET_ID=$(az network vnet show --resource-group "${PP_RESOURCE_GROUP}" --name "${PP_VNET_NAME}" --query id --output tsv)
az network vnet peering create --name westus-to-eastus --resource-group "${AZURE_RESOURCE_GROUP}" --vnet-name "${AZURE_VNET_NAME}" --remote-vnet "${PP_VNET_ID}" --allow-vnet-access
az network vnet peering create --name eastus-to-westus --resource-group "${PP_RESOURCE_GROUP}" --vnet-name "${PP_VNET_NAME}" --remote-vnet "${AZURE_VNET_ID}" --allow-vnet-access
PP_SUBNET_ID=$(az network vnet subnet list --resource-group "${PP_RESOURCE_GROUP}" --vnet-name "${PP_VNET_NAME}" --query "[].{Id:id} | [? contains(Id, 'worker')]" --output tsv)
fi
# Peer-pod requires gateway
az network public-ip create \
--resource-group "${PP_RESOURCE_GROUP}" \
--name MyPublicIP \
--sku Standard \
--allocation-method Static
az network nat gateway create \
--resource-group "${PP_RESOURCE_GROUP}" \
--name MyNatGateway \
--public-ip-addresses MyPublicIP \
--idle-timeout 10
az network vnet subnet update \
--resource-group "${PP_RESOURCE_GROUP}" \
--vnet-name "${PP_VNET_NAME}" \
--name "${PP_SUBNET_NAME}" \
--nat-gateway MyNatGateway
##########################################
# Setup CAA
#########################################
# Label the nodes
for NODE_NAME in $(kubectl get nodes -o jsonpath='{.items[*].metadata.name}'); do [[ "${NODE_NAME}" =~ 'worker' ]] && kubectl label node "${NODE_NAME}" node.kubernetes.io/worker=; done
# CAA artifacts
CAA_IMAGE="quay.io/confidential-containers/cloud-api-adaptor"
TAGS="$(curl https://quay.io/api/v1/repository/confidential-containers/cloud-api-adaptor/tag/?onlyActiveTags=true)"
DIGEST=$(echo "${TAGS}" | jq -r '.tags[] | select(.name | contains("latest-amd64")) | .manifest_digest')
CAA_TAG="$(echo "${TAGS}" | jq -r '.tags[] | select(.manifest_digest | contains("'"${DIGEST}"'")) | .name' | grep -v "latest")"
# Get latest PP image
SUCCESS_TIME=$(curl -s \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/confidential-containers/cloud-api-adaptor/actions/workflows/azure-nightly-build.yml/runs?status=success" \
| jq -r '.workflow_runs[0].updated_at')
PP_IMAGE_ID="/CommunityGalleries/cocopodvm-d0e4f35f-5530-4b9c-8596-112487cdea85/Images/podvm_image0/Versions/$(date -u -jf "%Y-%m-%dT%H:%M:%SZ" "${SUCCESS_TIME}" "+%Y.%m.%d" 2>/dev/null || date -d "${SUCCESS_TIME}" +%Y.%m.%d)"
echo "AZURE_REGION: \"${AZURE_REGION}\""
echo "PP_REGION: \"${PP_REGION}\""
echo "AZURE_RESOURCE_GROUP: \"${AZURE_RESOURCE_GROUP}\""
echo "PP_RESOURCE_GROUP: \"${PP_RESOURCE_GROUP}\""
echo "PP_SUBNET_ID: \"${PP_SUBNET_ID}\""
echo "CAA_TAG: \"${CAA_TAG}\""
echo "PP_IMAGE_ID: \"${PP_IMAGE_ID}\""
# Clone and configure caa
git clone --depth 1 --no-checkout https://github.com/confidential-containers/cloud-api-adaptor.git
pushd cloud-api-adaptor
git sparse-checkout init --cone
git sparse-checkout set src/cloud-api-adaptor/install/
git checkout
echo "CAA_GIT_SHA: \"$(git rev-parse HEAD)\""
pushd src/cloud-api-adaptor
cat <<EOF > install/overlays/azure/workload-identity.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: cloud-api-adaptor-daemonset
namespace: confidential-containers-system
spec:
template:
metadata:
labels:
azure.workload.identity/use: "true"
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cloud-api-adaptor
namespace: confidential-containers-system
annotations:
azure.workload.identity/client-id: "${USER_ASSIGNED_CLIENT_ID}"
EOF
PP_INSTANCE_SIZE="Standard_D2as_v5"
DISABLECVM="true"
cat <<EOF > install/overlays/azure/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
bases:
- ../../yamls
images:
- name: cloud-api-adaptor
newName: "${CAA_IMAGE}"
newTag: "${CAA_TAG}"
generatorOptions:
disableNameSuffixHash: true
configMapGenerator:
- name: peer-pods-cm
namespace: confidential-containers-system
literals:
- CLOUD_PROVIDER="azure"
- AZURE_SUBSCRIPTION_ID="${AZURE_SUBSCRIPTION_ID}"
- AZURE_REGION="${PP_REGION}"
- AZURE_INSTANCE_SIZE="${PP_INSTANCE_SIZE}"
- AZURE_RESOURCE_GROUP="${PP_RESOURCE_GROUP}"
- AZURE_SUBNET_ID="${PP_SUBNET_ID}"
- AZURE_IMAGE_ID="${PP_IMAGE_ID}"
- DISABLECVM="${DISABLECVM}"
- PEERPODS_LIMIT_PER_NODE="50"
secretGenerator:
- name: peer-pods-secret
namespace: confidential-containers-system
envs:
- service-principal.env
- name: ssh-key-secret
namespace: confidential-containers-system
files:
- id_rsa.pub
patchesStrategicMerge:
- workload-identity.yaml
EOF
ssh-keygen -t rsa -f install/overlays/azure/id_rsa -N ''
echo "AZURE_CLIENT_ID=${AZURE_CLIENT_ID}" > install/overlays/azure/service-principal.env
echo "AZURE_CLIENT_SECRET=${AZURE_CLIENT_SECRET}" >> install/overlays/azure/service-principal.env
echo "AZURE_TENANT_ID=${AZURE_TENANT_ID}" >> install/overlays/azure/service-principal.env
# Deploy Operator
git clone --depth 1 --no-checkout https://github.com/confidential-containers/operator
pushd operator
git sparse-checkout init --cone
git sparse-checkout set "config/"
git checkout
echo "OPERATOR_SHA: \"$(git rev-parse HEAD)\""
oc apply -k "config/release"
oc apply -k "config/samples/ccruntime/peer-pods"
popd
# Deploy CAA
kubectl apply -k "install/overlays/azure"
popd
popd
# Wait for runtimeclass
SECONDS=0
( while [[ "${SECONDS}" -lt 360 ]]; do
kubectl get runtimeclass | grep -q kata-remote && exit 0
done; exit 1 ) || { echo "kata-remote runtimeclass not initialized in 60s"; kubectl -n confidential-containers-system get all; echo; echo CAA; kubectl -n confidential-containers-system logs daemonset.apps/cloud-api-adaptor-daemonset; echo pre-install; kubectl -n confidential-containers-system logs daemonset.apps/cc-operator-pre-install-daemon; echo install; kubectl -n confidential-containers-system logs daemonset.apps/cc-operator-daemon-install; exit 1; }
################
# Deploy webhook
################
pushd ci/openshift-ci/cluster/
kubectl create ns default || true
kubectl config set-context --current --namespace=default
KATA_RUNTIME=kata-remote ./deploy_webhook.sh
popd

View File

@ -7,15 +7,16 @@
# Run a smoke test.
#
script_dir=$(dirname $0)
source ${script_dir}/lib.sh
script_dir=$(dirname "$0")
# shellcheck disable=SC1091 # import based on variable
source "${script_dir}/lib.sh"
pod='http-server'
# Create a pod.
#
info "Creating the ${pod} pod"
[ -z "$KATA_RUNTIME" ] && die "Please set the KATA_RUNTIME first"
[[ -z "${KATA_RUNTIME}" ]] && die "Please set the KATA_RUNTIME first"
envsubst < "${script_dir}/smoke/${pod}.yaml.in" | \
oc apply -f - || \
die "failed to create ${pod} pod"
@ -27,10 +28,10 @@ sleep_time=5
cmd="oc get pod/${pod} -o jsonpath='{.status.containerStatuses[0].state}' | \
grep running > /dev/null"
info "Wait until the pod gets running"
waitForProcess $wait_time $sleep_time "$cmd" || timed_out=$?
if [ -n "$timed_out" ]; then
oc describe pod/${pod}
oc delete pod/${pod}
waitForProcess "${wait_time}" "${sleep_time}" "${cmd}" || timed_out=$?
if [[ -n "${timed_out}" ]]; then
oc describe "pod/${pod}"
oc delete "pod/${pod}"
die "${pod} not running"
fi
info "${pod} is running"
@ -39,13 +40,13 @@ info "${pod} is running"
#
hello_file=/tmp/hello
hello_msg='Hello World'
oc exec ${pod} -- sh -c "echo $hello_msg > $hello_file"
oc exec "${pod}" -- sh -c "echo ${hello_msg} > ${hello_file}"
info "Creating the service and route"
if oc apply -f ${script_dir}/smoke/service.yaml; then
if oc apply -f "${script_dir}/smoke/service.yaml"; then
# Likely on OCP, use service
is_ocp=1
host=$(oc get route/http-server-route -o jsonpath={.spec.host})
host=$(oc get route/http-server-route -o jsonpath="{.spec.host}")
port=80
else
# Likely on plain kubernetes, test using another container
@ -54,13 +55,13 @@ else
oc apply -f "${script_dir}/smoke/service_kubernetes.yaml"
# For some reason kcli's cluster lists external IP as internal IP, try both
host=$(oc get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="ExternalIP")].address}')
[ -z "$host"] && host=$(oc get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
[[ -z "${host}" ]] && host=$(oc get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
port=$(oc get service/http-server-service -o jsonpath='{.spec.ports[0].nodePort}')
fi
info "Wait for the HTTP server to respond"
tempfile=$(mktemp)
check_cmd="curl -vvv '${host}:${port}${hello_file}' 2>&1 | tee -a '$tempfile' | grep -q '$hello_msg'"
check_cmd="curl -vvv '${host}:${port}${hello_file}' 2>&1 | tee -a '${tempfile}' | grep -q '${hello_msg}'"
if waitForProcess 60 1 "${check_cmd}"; then
test_status=0
info "HTTP server is working"
@ -78,17 +79,17 @@ else
echo "::endgroup::"
info "HTTP server is unreachable"
fi
rm -f "$tempfile"
rm -f "${tempfile}"
# Delete the resources.
#
info "Deleting the service/route"
if [ "$is_ocp" -eq 0 ]; then
oc delete -f ${script_dir}/smoke/service_kubernetes.yaml
if [[ "${is_ocp}" -eq 0 ]]; then
oc delete -f "${script_dir}/smoke/service_kubernetes.yaml"
else
oc delete -f ${script_dir}/smoke/service.yaml
oc delete -f "${script_dir}/smoke/service.yaml"
fi
info "Deleting the ${pod} pod"
oc delete pod/${pod} || test_status=$?
oc delete "pod/${pod}" || test_status=$?
exit $test_status
exit "${test_status}"

View File

@ -7,7 +7,7 @@
# afterwards OCP cluster using kata-containers primarily created for use
# with https://github.com/ldoktor/bisecter
[ "$#" -ne 1 ] && echo "Provide image as the first and only argument" && exit 255
[[ "$#" -ne 1 ]] && echo "Provide image as the first and only argument" && exit 255
export KATA_DEPLOY_IMAGE="$1"
OCP_DIR="${OCP_DIR:-/path/to/your/openshift/release/}"
E2E_TEST="${E2E_TEST:-'"[sig-node] Container Runtime blackbox test on terminated container should report termination message as empty when pod succeeds and TerminationMessagePolicy FallbackToLogsOnError is set [NodeConformance] [Conformance] [Suite:openshift/conformance/parallel/minimal] [Suite:k8s]"'}"
@ -17,12 +17,12 @@ export KATA_RUNTIME="${KATA_RUNTIME:-kata-qemu}"
## SETUP
# Deploy kata
SETUP=0
pushd "$KATA_CI_DIR" || { echo "Failed to cd to '$KATA_CI_DIR'"; exit 255; }
pushd "${KATA_CI_DIR}" || { echo "Failed to cd to '${KATA_CI_DIR}'"; exit 255; }
./test.sh || SETUP=125
cluster/deploy_webhook.sh || SETUP=125
if [ $SETUP != 0 ]; then
if [[ ${SETUP} != 0 ]]; then
./cleanup.sh
exit "$SETUP"
exit "${SETUP}"
fi
popd || true
# Disable security
@ -32,19 +32,19 @@ oc label --overwrite ns default pod-security.kubernetes.io/enforce=privileged po
## TEST EXECUTION
# Run the testing
pushd "$OCP_DIR" || { echo "Failed to cd to '$OCP_DIR'"; exit 255; }
echo "$E2E_TEST" > /tmp/tsts
pushd "${OCP_DIR}" || { echo "Failed to cd to '${OCP_DIR}'"; exit 255; }
echo "${E2E_TEST}" > /tmp/tsts
# Remove previously-existing temporarily files as well as previous results
OUT=RESULTS/tmp
rm -Rf /tmp/*test* /tmp/e2e-*
rm -R $OUT
mkdir -p $OUT
rm -R "${OUT}"
mkdir -p "${OUT}"
# Run the tests ignoring the monitor health checks
./openshift-tests run --provider azure -o "$OUT/job.log" --junit-dir "$OUT" --file /tmp/tsts --max-parallel-tests 5 --cluster-stability Disruptive
./openshift-tests run --provider azure -o "${OUT}/job.log" --junit-dir "${OUT}" --file /tmp/tsts --max-parallel-tests 5 --cluster-stability Disruptive
RET=$?
popd || true
## CLEANUP
./cleanup.sh
exit "$RET"
exit "${RET}"

View File

@ -8,25 +8,29 @@
# The kata shim to be used
export KATA_RUNTIME=${KATA_RUNTIME:-kata-qemu}
script_dir=$(dirname $0)
source ${script_dir}/lib.sh
script_dir=$(dirname "$0")
# shellcheck disable=SC1091 # import based on variable
source "${script_dir}/lib.sh"
suite=$1
if [ -z "$1" ]; then
if [[ -z "$1" ]]; then
suite='smoke'
fi
# Make oc and kubectl visible
export PATH=/tmp/shared:$PATH
export PATH=/tmp/shared:${PATH}
oc version || die "Test cluster is unreachable"
info "Install and configure kata into the test cluster"
export SELINUX_PERMISSIVE="no"
${script_dir}/cluster/install_kata.sh || die "Failed to install kata-containers"
"${script_dir}/cluster/install_kata.sh" || die "Failed to install kata-containers"
info "Run test suite: $suite"
info "Overriding KATA_RUNTIME cpu resources"
oc patch "runtimeclass/${KATA_RUNTIME}" -p '{"overhead": {"podFixed": {"cpu": "50m"}}}'
info "Run test suite: ${suite}"
test_status='PASS'
${script_dir}/run_${suite}_test.sh || test_status='FAIL'
info "Test suite: $suite: $test_status"
[ "$test_status" == "PASS" ]
"${script_dir}/run_${suite}_test.sh" || test_status='FAIL'
info "Test suite: ${suite}: ${test_status}"
[[ "${test_status}" == "PASS" ]]

View File

@ -47,3 +47,4 @@
- [How to run Kata Containers with kinds of Block Volumes](how-to-run-kata-containers-with-kinds-of-Block-Volumes.md)
- [How to use the Kata Agent Policy](how-to-use-the-kata-agent-policy.md)
- [How to pull images in the guest](how-to-pull-images-in-guest-with-kata.md)
- [How to use mem-agent to decrease the memory usage of Kata container](how-to-use-memory-agent.md)

View File

@ -2,6 +2,8 @@
## Introduction
This document describes how to setup swap device with runtime-golang. See [How to use mem-agent to decrease the memory usage of Kata container](how-to-use-memory-agent.md#setup-guest-swap) to get how to setup and use guest swap with runtime-rs.
Setup swap device in guest kernel can help to increase memory capacity, handle some memory issues and increase file access speed sometimes.
Kata Containers can insert a raw file to the guest as the swap device.

View File

@ -0,0 +1,351 @@
# How to use mem-agent to decrease the memory usage of Kata container
## Introduction
mem-agent is a component designed for managing memory in Linux environments.<br>
The mem-agent has been integrated into the kata-agent to reduce memory usage in Kata containers.
## Open mem-agent in configuration
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/configuration.toml"
$ sudo sed -i -e 's/^#mem_agent_enable.*$/mem_agent_enable = true/g' $config_file
```
## Open reclaim_guest_freed_memory in configuration
Enabling this will result in the VM balloon device having f_reporting=on set.<br>
Then the hypervisor will use it to reclaim guest freed memory.
When mem-agent reclaim the memory of the guest, this function will reclaim guest freed memory in the host.
**To use mem-agent, must open reclaim_guest_freed_memory in configuration.**
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/configuration.toml"
$ sudo sed -i -e 's/^#reclaim_guest_freed_memory.*$/reclaim_guest_freed_memory = true/g' $config_file
```
## Sub-feature psi
During memory reclamation and compaction, mem-agent monitors system pressure using Pressure Stall Information (PSI).<br>
If the system pressure becomes too high, memory reclamation or compaction will automatically stop.
This feature helps the mem-agent reduce its overhead on system performance.
## Sub-feature memcg
Use the Linux kernel MgLRU feature to monitor each cgroup's memory usage and periodically reclaim cold memory.
During each run period, memcg calls the run_aging function of MgLRU for each cgroup to mark the hot and cold states of the pages within it.<br>
Then, it calls the run_eviction function of MgLRU for each cgroup to reclaim a portion of the cold pages that have not been accessed for three periods.
After the run period, the memcg will enter a sleep period. Once the sleep period is over, it will transition into the next run period, and this cycle will continue.
**The following are the configurations of the sub-feature memcg:**
### memcg_disable
Control the mem-agent memcg function disable or enable.<br>
Default to false.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_disable.*$/memcg_disable = true/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"disabled":true}'
```
### memcg_swap
If this feature is disabled, the mem-agent will only track and reclaim file cache pages. If this feature is enabled, the mem-agent will handle both file cache pages and anonymous pages.<br>
Default to false.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_swap.*$/memcg_swap = true/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"swap":true}'
```
#### setup guest swap
memcg_swap should use with guest swap function.<br>
The guest swap function will create a separate swap task that will create and insert swap files into the guest as needed.<br>
Just dragonball and cloud-hypervisor support guest swap.
Use following configuration to enable guest swap.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#enable_guest_swap.*$/enable_guest_swap = true/g' $config_file
```
By default, swap files are created in the /run/kata-containers/swap directory. You can use the following configuration to create swap files in a different directory.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#guest_swap_path.*$/guest_swap_path = \"\/run\/kata-containers\/swap\"/g' $config_file
```
By default, the inserted swap file will match the current memory size, which is set to 100%. You can modify the percentage of the swap size relative to the current memory size using the configuration below.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#guest_swap_size_percent.*$/guest_swap_size_percent = 100/g' $config_file
```
The swap task will wait for 60 seconds before determining the memory size and creating swap files. This approach helps prevent interference with the startup performance of the kata container during its initial creation and avoids frequent insertion of swap files when the guest memory size is adjusted frequently. You can configure the waiting time using the option below.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#guest_swap_create_threshold_secs.*$/guest_swap_create_threshold_secs = 60/g' $config_file
```
### memcg_swappiness_max
The usage of this value is similar to the swappiness in the Linux kernel, applying a ratio of swappiness_max/200 when utilized.<br>
At the beginning of the eviction memory process for a cgroup in each run period, the coldest anonymous pages are assigned a maximum eviction value based on swappiness_max/200.<br>
When the run_eviction function of MgLRU is actually called, if the comparison ratio between the current coldest anonymous pages and file cache pages exceeds this value, then this value will be used as the swappiness.<br>
Default to 50.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_swappiness_max.*$/memcg_swappiness_max = 50/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"swappiness_max":50}'
```
### memcg_period_secs
Control the mem-agent memcg function wait period seconds.<br>
Default to 600.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_period_secs.*$/memcg_period_secs = 600/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"period_secs":600}'
```
### memcg_period_psi_percent_limit
Control the mem-agent memcg wait period PSI percent limit.<br>
If the percentage of memory and IO PSI stall time within the memcg waiting period for a cgroup exceeds this value, then the memcg run period for this cgroup will not be executed after this waiting period.<br>
Default to 1
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_period_psi_percent_limit.*$/memcg_period_psi_percent_limit = 1/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"period_psi_percent_limit":1}'
```
### memcg_eviction_psi_percent_limit
Control the mem-agent memcg eviction PSI percent limit.<br>
If the percentage of memory and IO PSI stall time for a cgroup exceeds this value during an eviction cycle, the eviction for this cgroup will immediately stop and will not resume until the next memcg waiting period.<br>
Default to 1.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_eviction_psi_percent_limit.*$/memcg_eviction_psi_percent_limit = 1/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"eviction_psi_percent_limit":1}'
```
### memcg_eviction_run_aging_count_min
Control the mem-agent memcg eviction run aging count min.<br>
A cgroup will only perform eviction when the number of aging cycles in memcg is greater than or equal to memcg_eviction_run_aging_count_min.<br>
Default to 3.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#memcg_eviction_run_aging_count_min.*$/memcg_eviction_run_aging_count_min = 3/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentMemcgSet json://{"eviction_run_aging_count_min":3}'
```
## Sub-feature compact
The memory control group (memcg) functionality may release a significant number of small pages, but the VM balloon free page reporting feature used by reclaim_guest_freed_memory requires at least a contiguous block of order 10 pages(a page block) to be released from the host.<br>
The sub-feature compact is designed to address the issue of fragmented pages.<br>
During each run period, compact check the continuity of free pages within the system. If necessary, the compact will invoke the Linux compaction feature to reorganize fragmented pages.<br>
After the run period, the compact will enter a sleep period. Once the sleep period is over, it will transition into the next run period, and this cycle will continue.
*the VM balloon free page reporting feature in arm64_64k report order 5 pages. Following is the comments from Linux kernel.*
```
/*
* The default page reporting order is @pageblock_order, which
* corresponds to 512MB in size on ARM64 when 64KB base page
* size is used. The page reporting won't be triggered if the
* freeing page can't come up with a free area like that huge.
* So we specify the page reporting order to 5, corresponding
* to 2MB. It helps to avoid THP splitting if 4KB base page
* size is used by host.
*
* Ideally, the page reporting order is selected based on the
* host's base page size. However, it needs more work to report
* that value. The hard-coded order would be fine currently.
*/
```
**The following are the configurations of the sub-feature compact:**
### compact_disable
Control the mem-agent compact function disable or enable.<br>
Default to false.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_disable.*$/compact_disable = true/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"disabled":false}'
```
### compact_period_secs
Control the mem-agent compaction function wait period seconds.<br>
Default to 600.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_period_secs.*$/compact_period_secs = 600/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"period_secs":600}'
```
### compact_period_psi_percent_limit
Control the mem-agent compaction function wait period PSI percent limit.<br>
If the percentage of memory and IO PSI stall time within the compaction waiting period exceeds this value, then the compaction will not be executed after this waiting period.<br>
Default to 1.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_period_psi_percent_limit.*$/compact_period_psi_percent_limit = 1/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"period_psi_percent_limit":1}'
```
### compact_psi_percent_limit
Control the mem-agent compaction function compact PSI percent limit.<br>
During compaction, the percentage of memory and IO PSI stall time is checked every second. If this percentage exceeds compact_psi_percent_limit, the compaction process will stop.<br>
Default to 5
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_psi_percent_limit.*$/compact_psi_percent_limit = 5/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"compact_psi_percent_limit":5}'
```
### compact_sec_max
Control the maximum number of seconds for each compaction of mem-agent compact function.<br>
If compaction seconds is bigger than compact_sec_max during compact run period, stop compaction at once.
Default to 180.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_sec_max.*$/compact_sec_max = 180/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"compact_sec_max":180}'
```
### compact_order
compact_order is use with compact_threshold.<br>
compact_order parameter determines the size of contiguous pages that the mem-agent's compaction functionality aims to achieve.<br>
For example, if compact_order is set to 10 in a Kata container guest environment, the compaction function will target acquiring more contiguous pages of order 10, which will allow reclaim_guest_freed_memory to release additional pages.<br>
If the goal is to have more free pages of order 9 in the system to ensure a higher likelihood of obtaining transparent huge pages during memory allocation, then setting compact_order to 9 would be appropriate.
Default to 9.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_order.*$/compact_order = 9/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"compact_order":9}'
```
### compact_threshold
Control the mem-agent compaction function compact threshold.<br>
compact_threshold is the pages number.<br>
When examining the /proc/pagetypeinfo, if there's an increase in the number of movable pages of orders smaller than the compact_order compared to the amount following the previous compaction period, and this increase surpasses a certain threshold specifically, more than compact_threshold number of pages, or the number of free pages has decreased by compact_threshold since the previous compaction. Current compact run period will not do compaction because there is no enough fragmented pages to be compaction.<br>
This design aims to minimize the impact of unnecessary compaction calls on system performance.<br>
Default to 1024.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_threshold.*$/compact_threshold = 1024/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"compact_threshold":1024}'
```
### compact_force_times
Control the mem-agent compaction function force compact times.<br>
After one compaction during a run period, if there are consecutive instances of compact_force_times run periods where no compaction occurs, a compaction will be forced regardless of the system's memory state.<br>
If compact_force_times is set to 0, will do force compaction each period.<br>
If compact_force_times is set to 18446744073709551615, will never do force compaction.<br>
Default to 18446744073709551615.
```bash
$ config_file="/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml"
$ sudo sed -i -e 's/^#compact_force_times.*$/compact_force_times = 18446744073709551615/g' $config_file
```
For a running Kata container, this configuration can be dynamically modified using the kata-agent-ctl command.
```bash
$ PODID="12345"
$ kata-agent-ctl connect --server-address "unix:///var/run/kata/$PODID/root/kata.hvsock" --hybrid-vsock \
--cmd 'MemAgentCompactSet json://{"compact_force_times":18446744073709551615}'
```

3
rust-toolchain.toml Normal file
View File

@ -0,0 +1,3 @@
[toolchain]
# Keep in sync with versions.yaml
channel = "1.80.0"

17
shellcheckrc Normal file
View File

@ -0,0 +1,17 @@
# Allow opening any 'source'd file, even if not specified as input
external-sources=true
# Turn on warnings for unquoted variables with safe values
enable=quote-safe-variables
# Turn on warnings for unassigned uppercase variables
enable=check-unassigned-uppercase
# Enforces braces around variable expansions to avoid ambiguity or confusion.
# e.g. ${filename} rather than $filename
enable=require-variable-braces
# Requires double-bracket syntax [[ expr ]] for safer, more consistent tests.
# NO: if [ "$var" = "value" ]
# YES: if [[ $var == "value" ]]
enable=require-double-brackets

2016
src/agent/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,37 +1,31 @@
[package]
name = "kata-agent"
version = "0.1.0"
[workspace]
members = ["rustjail", "policy", "vsock-exporter"]
[workspace.package]
authors = ["The Kata Containers community <kata-dev@lists.katacontainers.io>"]
edition = "2018"
license = "Apache-2.0"
rust-version = "1.80.0"
[dependencies]
runtime-spec = { path = "../libs/runtime-spec" }
mem-agent = { path = "../mem-agent" }
[workspace.dependencies]
oci-spec = { version = "0.6.8", features = ["runtime"] }
rustjail = { path = "rustjail" }
protocols = { path = "../libs/protocols", features = ["async", "with-serde"] }
lazy_static = "1.3.0"
ttrpc = { version = "0.8.4", features = ["async"], default-features = false }
protobuf = "3.2.0"
libc = "0.2.58"
protobuf = "=3.7.1"
libc = "0.2.94"
nix = "0.24.2"
capctl = "0.2.0"
serde_json = "1.0.39"
scan_fmt = "0.2.3"
scan_fmt = "0.2.6"
scopeguard = "1.0.0"
thiserror = "1.0.26"
regex = "1.10.5"
serial_test = "0.5.1"
url = "2.5.0"
derivative = "2.2.0"
kata-sys-util = { path = "../libs/kata-sys-util" }
kata-types = { path = "../libs/kata-types" }
safe-path = { path = "../libs/safe-path" }
const_format = "0.2.30"
# Async helpers
async-trait = "0.1.42"
async-trait = "0.1.50"
async-recursion = "0.3.2"
futures = "0.3.30"
@ -40,13 +34,12 @@ tokio = { version = "1.39.0", features = ["full"] }
tokio-vsock = "0.3.4"
netlink-sys = { version = "0.7.0", features = ["tokio_socket"] }
rtnetlink = "0.8.0"
netlink-packet-utils = "0.4.1"
rtnetlink = "0.14.0"
netlink-packet-route = "0.19.0"
netlink-packet-core = "0.7.0"
ipnetwork = "0.17.0"
# Note: this crate sets the slog 'max_*' features which allows the log level
# to be modified at runtime.
logging = { path = "../libs/logging" }
slog = "2.5.2"
slog-scope = "4.1.2"
slog-term = "2.9.0"
@ -68,47 +61,149 @@ tracing = "0.1.26"
tracing-subscriber = "0.2.18"
tracing-opentelemetry = "0.13.0"
opentelemetry = { version = "0.14.0", features = ["rt-tokio-current-thread"] }
vsock-exporter = { path = "vsock-exporter" }
# Configuration
serde = { version = "1.0.129", features = ["derive"] }
serde_json = "1.0.39"
toml = "0.5.8"
clap = { version = "3.0.1", features = ["derive"] }
strum = "0.26.2"
strum_macros = "0.26.2"
# Image pull/decrypt
image-rs = { git = "https://github.com/confidential-containers/guest-components", rev = "514c561d933cb11a0f1628621a0b930157af76cd", default-features = false, optional = true }
# Agent Policy
regorus = { version = "0.2.6", default-features = false, features = [
"arc",
"regex",
"std",
], optional = true }
cdi = { git = "https://github.com/cncf-tags/container-device-interface-rs", rev = "fba5677a8e7cc962fc6e495fcec98d7d765e332a" }
json-patch = "2.0.0"
kata-agent-policy = { path = "policy" }
[dev-dependencies]
tempfile = "3.1.0"
test-utils = { path = "../libs/test-utils" }
which = "4.3.0"
rstest = "0.18.0"
async-std = { version = "1.12.0", features = ["attributes"] }
[workspace]
members = ["rustjail", "policy"]
# Local dependencies
kata-agent-policy = { path = "policy" }
rustjail = { path = "rustjail" }
vsock-exporter = { path = "vsock-exporter" }
mem-agent = { path = "../mem-agent" }
kata-sys-util = { path = "../libs/kata-sys-util" }
kata-types = { path = "../libs/kata-types" }
# Note: this crate sets the slog 'max_*' features which allows the log level
# to be modified at runtime.
logging = { path = "../libs/logging" }
protocols = { path = "../libs/protocols" }
runtime-spec = { path = "../libs/runtime-spec" }
safe-path = { path = "../libs/safe-path" }
test-utils = { path = "../libs/test-utils" }
[package]
name = "kata-agent"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
oci-spec.workspace = true
lazy_static.workspace = true
ttrpc.workspace = true
protobuf.workspace = true
libc.workspace = true
nix.workspace = true
capctl.workspace = true
serde_json.workspace = true
scan_fmt.workspace = true
scopeguard.workspace = true
thiserror.workspace = true
regex.workspace = true
serial_test.workspace = true
url.workspace = true
derivative.workspace = true
const_format.workspace = true
# Async helpers
async-trait.workspace = true
async-recursion.workspace = true
futures.workspace = true
# Async runtime
tokio.workspace = true
tokio-vsock.workspace = true
netlink-sys.workspace = true
rtnetlink.workspace = true
netlink-packet-route.workspace = true
netlink-packet-core.workspace = true
ipnetwork.workspace = true
slog.workspace = true
slog-scope.workspace = true
slog-term.workspace = true
# Redirect ttrpc log calls
slog-stdlog.workspace = true
log.workspace = true
cfg-if.workspace = true
prometheus.workspace = true
procfs.workspace = true
anyhow.workspace = true
cgroups.workspace = true
# Tracing
tracing.workspace = true
tracing-subscriber.workspace = true
tracing-opentelemetry.workspace = true
opentelemetry.workspace = true
# Configuration
serde.workspace = true
toml.workspace = true
clap.workspace = true
strum.workspace = true
strum_macros.workspace = true
# Image pull/decrypt
image-rs = { git = "https://github.com/confidential-containers/guest-components", rev = "1191f8257eb65f42892ab0328cec02e58d40de84", default-features = false, optional = true }
# Agent Policy
cdi = { git = "https://github.com/cncf-tags/container-device-interface-rs", rev = "fba5677a8e7cc962fc6e495fcec98d7d765e332a" }
# Local dependencies
kata-agent-policy = { workspace = true, optional = true }
mem-agent.workspace = true
rustjail.workspace = true
protocols = { workspace = true, features = ["async", "with-serde"] }
kata-sys-util.workspace = true
kata-types.workspace = true
runtime-spec.workspace = true
safe-path.workspace = true
# Note: this crate sets the slog 'max_*' features which allows the log level
# to be modified at runtime.
logging.workspace = true
vsock-exporter.workspace = true
# Initdata
base64 = "0.22"
sha2 = "0.10.8"
async-compression = { version = "0.4.22", features = ["tokio", "gzip"] }
[dev-dependencies]
tempfile.workspace = true
which.workspace = true
rstest.workspace = true
async-std.workspace = true
test-utils.workspace = true
[profile.release]
lto = true
[features]
# The default-pull feature would support all pull types, including sharing images by virtio-fs and pulling images in the guest
default-pull = ["guest-pull"]
# The default-pull feature supports all sharing images by virtio-fs, for guest-pull build with the guest-pull feature
default-pull = []
seccomp = ["rustjail/seccomp"]
standard-oci-runtime = ["rustjail/standard-oci-runtime"]
agent-policy = ["regorus"]
agent-policy = ["kata-agent-policy"]
guest-pull = ["image-rs/kata-cc-rustls-tls"]
[[bin]]

View File

@ -53,10 +53,6 @@ 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

View File

@ -1,20 +1,19 @@
[package]
name = "kata-agent-policy"
version = "0.1.0"
authors = ["The Kata Containers community <kata-dev@lists.katacontainers.io>"]
edition = "2018"
license = "Apache-2.0"
authors.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
# Async runtime
tokio = { version = "1.39.0", features = ["full"] }
tokio-vsock = "0.3.4"
tokio.workspace = true
anyhow = "1"
anyhow.workspace = true
# Configuration
serde = { version = "1.0.129", features = ["derive"] }
serde_json = "1.0.39"
serde.workspace = true
serde_json.workspace = true
# Agent Policy
regorus = { version = "0.2.8", default-features = false, features = [
@ -27,7 +26,5 @@ json-patch = "2.0.0"
# Note: this crate sets the slog 'max_*' features which allows the log level
# to be modified at runtime.
logging = { path = "../../libs/logging" }
slog = "2.5.2"
slog-scope = "4.1.2"
slog-term = "2.9.0"
slog.workspace = true
slog-scope.workspace = true

View File

@ -1,51 +1,62 @@
[package]
name = "rustjail"
version = "0.1.0"
authors = ["The Kata Containers community <kata-dev@lists.katacontainers.io>"]
edition = "2018"
license = "Apache-2.0"
authors.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
awaitgroup = "0.6.0"
serde = "1.0.91"
serde_json = "1.0.39"
serde_derive = "1.0.91"
runtime-spec = { path = "../../libs/runtime-spec" }
oci-spec = { version = "0.6.8", features = ["runtime"] }
protocols = { path ="../../libs/protocols" }
kata-sys-util = { path = "../../libs/kata-sys-util" }
serde.workspace = true
serde_json.workspace = true
oci-spec.workspace = true
caps = "0.5.0"
nix = "0.24.2"
scopeguard = "1.0.0"
capctl = "0.2.0"
lazy_static = "1.3.0"
libc = "0.2.58"
protobuf = "3.2.0"
slog = "2.5.2"
slog-scope = "4.1.2"
scan_fmt = "0.2.6"
regex = "1.5.6"
nix.workspace = true
scopeguard.workspace = true
capctl.workspace = true
lazy_static.workspace = true
libc.workspace = true
protobuf.workspace = true
slog.workspace = true
slog-scope.workspace = true
scan_fmt.workspace = true
regex.workspace = true
path-absolutize = "1.2.0"
anyhow = "1.0.32"
cgroups = { package = "cgroups-rs", version = "0.3.3" }
cgroups.workspace = true
rlimit = "0.5.3"
cfg-if = "0.1.0"
cfg-if.workspace = true
tokio = { version = "1.38.0", features = ["sync", "io-util", "process", "time", "macros", "rt", "fs"] }
tokio-vsock = "0.3.4"
futures = "0.3.17"
async-trait = "0.1.31"
tokio = { workspace = true, features = [
"sync",
"io-util",
"process",
"time",
"macros",
"rt",
"fs",
] }
tokio-vsock.workspace = true
futures.workspace = true
async-trait.workspace = true
inotify = "0.9.2"
libseccomp = { version = "0.3.0", optional = true }
zbus = "3.12.0"
bit-vec= "0.6.3"
bit-vec = "0.6.3"
xattr = "0.2.3"
# Local dependencies
protocols.workspace = true
kata-sys-util.workspace = true
runtime-spec.workspace = true
[dev-dependencies]
serial_test = "0.5.0"
tempfile = "3.1.0"
test-utils = { path = "../../libs/test-utils" }
protocols = { path ="../../libs/protocols" }
serial_test.workspace = true
tempfile.workspace = true
# Local dependencies
test-utils.workspace = true
[features]
seccomp = ["libseccomp"]

View File

@ -33,6 +33,7 @@ use protocols::agent::{
BlkioStats, BlkioStatsEntry, CgroupStats, CpuStats, CpuUsage, HugetlbStats, MemoryData,
MemoryStats, PidsStats, ThrottlingData,
};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::fs;

View File

@ -12,6 +12,7 @@ use cgroups::freezer::FreezerState;
use libc::{self, pid_t};
use oci::{LinuxResources, Spec};
use oci_spec::runtime as oci;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::string::String;

View File

@ -77,9 +77,17 @@ async fn register_memory_event_v2(
let mut inotify = Inotify::init().context("Failed to initialize inotify")?;
// watching oom kill
let ev_wd = inotify.add_watch(&event_control_path, WatchMask::MODIFY)?;
let ev_wd = inotify
.add_watch(&event_control_path, WatchMask::MODIFY)
.context(format!("failed to add watch for {:?}", &event_control_path))?;
// Because no `unix.IN_DELETE|unix.IN_DELETE_SELF` event for cgroup file system, so watching all process exited
let cg_wd = inotify.add_watch(&cgroup_event_control_path, WatchMask::MODIFY)?;
let cg_wd = inotify
.add_watch(&cgroup_event_control_path, WatchMask::MODIFY)
.context(format!(
"failed to add watch for {:?}",
&cgroup_event_control_path
))?;
info!(sl(), "ev_wd: {:?}", ev_wd);
info!(sl(), "cg_wd: {:?}", cg_wd);

View File

@ -6,6 +6,7 @@
use anyhow::{anyhow, Result};
use super::common::{DEFAULT_SLICE, SCOPE_SUFFIX, SLICE_SUFFIX};
use serde::{Deserialize, Serialize};
use std::string::String;
#[derive(Serialize, Deserialize, Debug, Clone)]

View File

@ -3,6 +3,8 @@
// SPDX-License-Identifier: Apache-2.0
//
use serde::{Deserialize, Serialize};
pub const DEFAULT_SLICE: &str = "system.slice";
pub const SLICE_SUFFIX: &str = ".slice";
pub const SCOPE_SUFFIX: &str = ".scope";

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
use serde::{Deserialize, Serialize};
use std::vec;
use super::common::{

View File

@ -10,6 +10,7 @@ use cgroups::freezer::FreezerState;
use libc::{self, pid_t};
use oci::LinuxResources;
use oci_spec::runtime as oci;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::convert::TryInto;

View File

@ -8,6 +8,7 @@ use libc::pid_t;
use oci::{Linux, LinuxDevice, LinuxIdMapping, LinuxNamespace, LinuxResources, Spec};
use oci_spec::runtime as oci;
use runtime_spec as spec;
use serde::{Deserialize, Serialize};
use spec::{ContainerState, State as OCIState};
use std::clone::Clone;
use std::ffi::CString;

View File

@ -7,12 +7,10 @@
#[macro_use]
#[cfg(test)]
extern crate serial_test;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate caps;
extern crate protocols;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate scopeguard;
extern crate capctl;

View File

@ -18,12 +18,13 @@ use std::collections::{HashMap, HashSet};
use std::fs::{self, OpenOptions};
use std::mem::MaybeUninit;
use std::os::unix;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::RawFd;
use std::path::{Component, Path, PathBuf};
use path_absolutize::*;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, ErrorKind};
use crate::container::DEFAULT_DEVICES;
use crate::selinux;
@ -1010,16 +1011,29 @@ lazy_static! {
};
}
fn permissions_from_path(path: &Path) -> Result<u32> {
match fs::metadata(path) {
Ok(metadata) => Ok(metadata.permissions().mode()),
Err(e) if e.kind() == ErrorKind::NotFound => Ok(0),
Err(e) => Err(e.into()),
}
}
fn mknod_dev(dev: &LinuxDevice, relpath: &Path) -> Result<()> {
let f = match LINUXDEVICETYPE.get(dev.typ().as_str()) {
Some(v) => v,
None => return Err(anyhow!("invalid spec".to_string())),
};
let file_mode = match dev.file_mode().unwrap_or(0) {
0 => permissions_from_path(Path::new(dev.path()))?,
x => x,
};
stat::mknod(
relpath,
*f,
Mode::from_bits_truncate(dev.file_mode().unwrap_or(0)),
Mode::from_bits_truncate(file_mode),
nix::sys::stat::makedev(dev.major() as u64, dev.minor() as u64),
)?;

View File

@ -4,6 +4,7 @@
//
use oci_spec::runtime::Spec;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct CreateOpts {

View File

@ -15,7 +15,7 @@ use anyhow::anyhow;
// - <xxxx> is the device number (0000-ffff; leading zeroes can be omitted,
// e.g. 3 instead of 0003).
// [1] https://www.ibm.com/docs/en/linuxonibm/pdf/lku4dd04.pdf
// [2] https://qemu.readthedocs.io/en/latest/system/s390x/css.html
// [2] https://qemu.readthedocs.io/en/master/system/s390x/css.html
// Maximum subchannel set ID
const SUBCHANNEL_SET_MAX: u8 = 3;

View File

@ -184,6 +184,7 @@ pub async fn unseal_file(path: &str) -> Result<()> {
Ok(())
}
#[cfg(feature = "guest-pull")]
pub async fn secure_mount(
volume_type: &str,
options: &std::collections::HashMap<String, String>,

View File

@ -9,6 +9,7 @@ use self::nvdimm_device_handler::VirtioNvdimmDeviceHandler;
use self::scsi_device_handler::ScsiDeviceHandler;
use self::vfio_device_handler::{VfioApDeviceHandler, VfioPciDeviceHandler};
use crate::pci;
use crate::sandbox::PciHostGuestMapping;
use crate::sandbox::Sandbox;
use anyhow::{anyhow, Context, Result};
use cdi::annotations::parse_annotations;
@ -180,6 +181,7 @@ lazy_static! {
#[instrument]
pub async fn add_devices(
cid: &String,
logger: &Logger,
devices: &[Device],
spec: &mut Spec,
@ -211,8 +213,9 @@ pub async fn add_devices(
}
let mut sb = sandbox.lock().await;
let mut host_guest: PciHostGuestMapping = HashMap::new();
for (host, guest) in update.pci {
if let Some(other_guest) = sb.pcimap.insert(host, guest) {
if let Some(other_guest) = host_guest.insert(host, guest) {
return Err(anyhow!(
"Conflicting guest address for host device {} ({} versus {})",
host,
@ -221,6 +224,9 @@ pub async fn add_devices(
));
}
}
// Save all the host -> guest mappings per container upon
// removal of the container, the mappings will be removed
sb.pcimap.insert(cid.clone(), host_guest);
}
Err(e) => {
error!(logger, "failed to add devices, error: {e:?}");
@ -238,7 +244,7 @@ pub async fn add_devices(
if let Some(process) = spec.process_mut() {
let env_vec: &mut Vec<String> =
&mut process.env_mut().get_or_insert_with(Vec::new).to_vec();
update_env_pci(env_vec, &sandbox.lock().await.pcimap)?
update_env_pci(cid, env_vec, &sandbox.lock().await.pcimap)?
}
update_spec_devices(logger, spec, dev_updates)
}
@ -391,8 +397,9 @@ pub fn insert_devices_cgroup_rule(
// given a map of (host address => guest address)
#[instrument]
pub fn update_env_pci(
cid: &String,
env: &mut [String],
pcimap: &HashMap<pci::Address, pci::Address>,
pcimap: &HashMap<String, PciHostGuestMapping>,
) -> Result<()> {
// SR-IOV device plugin may add two environment variables for one resource:
// - PCIDEVICE_<prefix>_<resource-name>: a list of PCI device ids separated by comma
@ -418,7 +425,10 @@ pub fn update_env_pci(
for host_addr_str in val.split(',') {
let host_addr = pci::Address::from_str(host_addr_str)
.with_context(|| format!("Can't parse {} environment variable", name))?;
let guest_addr = pcimap
let host_guest = pcimap
.get(cid)
.ok_or_else(|| anyhow!("No PCI mapping found for container {}", cid))?;
let guest_addr = host_guest
.get(&host_addr)
.ok_or_else(|| anyhow!("Unable to translate host PCI address {}", host_addr))?;
@ -1052,7 +1062,7 @@ mod tests {
"NOTAPCIDEVICE_blah=abcd:ef:01.0".to_string(),
];
let pci_fixups = example_map
let _pci_fixups = example_map
.iter()
.map(|(h, g)| {
(
@ -1062,7 +1072,11 @@ mod tests {
})
.collect();
let res = update_env_pci(&mut env, &pci_fixups);
let cid = "0".to_string();
let mut pci_fixups: HashMap<String, HashMap<pci::Address, pci::Address>> = HashMap::new();
pci_fixups.insert(cid.clone(), _pci_fixups);
let res = update_env_pci(&cid, &mut env, &pci_fixups);
assert!(res.is_ok(), "error: {}", res.err().unwrap());
assert_eq!(env[0], "PCIDEVICE_x=0000:01:01.0,0000:01:02.0");

View File

@ -3,35 +3,23 @@
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::device::pcipath_to_sysfs;
#[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};
#[cfg(not(target_arch = "s390x"))]
use crate::{device::pcipath_to_sysfs, pci};
use anyhow::{anyhow, Result};
use regex::Regex;
use std::fs;
use std::sync::Arc;
use tokio::sync::Mutex;
pub async fn wait_for_net_interface(
sandbox: &Arc<Mutex<Sandbox>>,
pcipath: &pci::Path,
) -> Result<()> {
let root_bus_sysfs = format!("{}{}", SYSFS_DIR, create_pci_root_bus_path());
let sysfs_rel_path = pcipath_to_sysfs(&root_bus_sysfs, pcipath)?;
let matcher = NetPciMatcher::new(&sysfs_rel_path);
fn check_existing(re: Regex) -> Result<bool> {
// Check if the interface is already added in case network is cold-plugged
// or the uevent loop is started before network is added.
// We check for the pci deive in the sysfs directory for network devices.
let pattern = format!(
r"[./]+{}/[a-z0-9/]*net/[a-z0-9/]*",
matcher.devpath.as_str()
);
let re = Regex::new(&pattern).expect("BUG: Failed to compile regex for NetPciMatcher");
// We check for the device in the sysfs directory for network devices.
for entry in fs::read_dir(SYSFS_NET_PATH)? {
let entry = entry?;
let path = entry.path();
@ -41,19 +29,41 @@ pub async fn wait_for_net_interface(
.ok_or_else(|| anyhow!("Expected symlink in dir {}", SYSFS_NET_PATH))?;
if re.is_match(target_path_str) {
return Ok(());
return Ok(true);
}
}
Ok(false)
}
#[cfg(not(target_arch = "s390x"))]
pub async fn wait_for_pci_net_interface(
sandbox: &Arc<Mutex<Sandbox>>,
pcipath: &pci::Path,
) -> Result<()> {
let root_bus_sysfs = format!("{}{}", SYSFS_DIR, create_pci_root_bus_path());
let sysfs_rel_path = pcipath_to_sysfs(&root_bus_sysfs, pcipath)?;
let matcher = NetPciMatcher::new(&sysfs_rel_path);
let pattern = format!(
r"[./]+{}/[a-z0-9/]*net/[a-z0-9/]*",
matcher.devpath.as_str()
);
let re = Regex::new(&pattern).expect("BUG: Failed to compile regex for NetPciMatcher");
if check_existing(re)? {
return Ok(());
}
let _uev = wait_for_uevent(sandbox, matcher).await?;
Ok(())
}
#[cfg(not(target_arch = "s390x"))]
#[derive(Debug)]
pub struct NetPciMatcher {
devpath: String,
}
#[cfg(not(target_arch = "s390x"))]
impl NetPciMatcher {
pub fn new(relpath: &str) -> NetPciMatcher {
let root_bus = create_pci_root_bus_path();
@ -64,6 +74,7 @@ impl NetPciMatcher {
}
}
#[cfg(not(target_arch = "s390x"))]
impl UeventMatcher for NetPciMatcher {
fn is_match(&self, uev: &Uevent) -> bool {
uev.devpath.starts_with(self.devpath.as_str())
@ -73,10 +84,53 @@ impl UeventMatcher for NetPciMatcher {
}
}
#[cfg(target_arch = "s390x")]
pub async fn wait_for_ccw_net_interface(
sandbox: &Arc<Mutex<Sandbox>>,
device: &ccw::Device,
) -> Result<()> {
let matcher = NetCcwMatcher::new(CCW_ROOT_BUS_PATH, device);
if check_existing(matcher.re.clone())? {
return Ok(());
}
let _uev = wait_for_uevent(sandbox, matcher).await?;
Ok(())
}
#[cfg(target_arch = "s390x")]
#[derive(Debug)]
struct NetCcwMatcher {
re: Regex,
}
#[cfg(target_arch = "s390x")]
impl NetCcwMatcher {
pub fn new(root_bus_path: &str, device: &ccw::Device) -> Self {
let re = format!(
r"{}/0\.[0-3]\.[0-9a-f]{{1,4}}/{}/virtio[0-9]+/net/",
root_bus_path, device
);
NetCcwMatcher {
re: Regex::new(&re).expect("BUG: failed to compile NetCCWMatcher regex"),
}
}
}
#[cfg(target_arch = "s390x")]
impl UeventMatcher for NetCcwMatcher {
fn is_match(&self, uev: &Uevent) -> bool {
self.re.is_match(&uev.devpath)
&& uev.subsystem == "net"
&& !uev.interface.is_empty()
&& uev.action == "add"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(target_arch = "s390x"))]
#[tokio::test]
#[allow(clippy::redundant_clone)]
async fn test_net_pci_matcher() {
@ -111,4 +165,34 @@ mod tests {
assert!(!matcher_a.is_match(&uev_c));
assert!(!matcher_b.is_match(&uev_c));
}
#[cfg(target_arch = "s390x")]
#[tokio::test]
async fn test_net_ccw_matcher() {
let dev_a = ccw::Device::new(0, 1).unwrap();
let dev_b = ccw::Device::new(1, 2).unwrap();
let mut uev_a = crate::uevent::Uevent::default();
uev_a.action = crate::linux_abi::U_EVENT_ACTION_ADD.to_string();
uev_a.subsystem = String::from("net");
uev_a.interface = String::from("eth0");
uev_a.devpath = format!(
"{}/0.0.0001/{}/virtio1/{}/{}",
CCW_ROOT_BUS_PATH, dev_a, uev_a.subsystem, uev_a.interface
);
let mut uev_b = uev_a.clone();
uev_b.devpath = format!(
"{}/0.0.0001/{}/virtio1/{}/{}",
CCW_ROOT_BUS_PATH, dev_b, uev_b.subsystem, uev_b.interface
);
let matcher_a = NetCcwMatcher::new(CCW_ROOT_BUS_PATH, &dev_a);
let matcher_b = NetCcwMatcher::new(CCW_ROOT_BUS_PATH, &dev_b);
assert!(matcher_a.is_match(&uev_a));
assert!(matcher_b.is_match(&uev_b));
assert!(!matcher_b.is_match(&uev_a));
assert!(!matcher_a.is_match(&uev_b));
}
}

191
src/agent/src/initdata.rs Normal file
View File

@ -0,0 +1,191 @@
//! # Initdata Module
//!
//! This module will do the following things if a proper initdata device with initdata exists.
//! 1. Parse the initdata block device and extract the config files to [`INITDATA_PATH`].
//! 2. Return the initdata and the policy (if any).
// Copyright (c) 2025 Alibaba Cloud
//
// SPDX-License-Identifier: Apache-2.0
//
use std::{os::unix::fs::FileTypeExt, path::Path};
use anyhow::{bail, Context, Result};
use async_compression::tokio::bufread::GzipDecoder;
use base64::{engine::general_purpose::STANDARD, Engine};
use const_format::concatcp;
use serde::Deserialize;
use sha2::{Digest, Sha256, Sha384, Sha512};
use slog::Logger;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
/// This is the target directory to store the extracted initdata.
pub const INITDATA_PATH: &str = "/run/confidential-containers/initdata";
/// The path of AA's config file
pub const AA_CONFIG_PATH: &str = concatcp!(INITDATA_PATH, "/aa.toml");
/// The path of CDH's config file
pub const CDH_CONFIG_PATH: &str = concatcp!(INITDATA_PATH, "/cdh.toml");
/// Magic number of initdata device
pub const INITDATA_MAGIC_NUMBER: &[u8] = b"initdata";
/// Now only initdata `0.1.0` is defined.
const INITDATA_VERSION: &str = "0.1.0";
/// Initdata defined in
/// <https://github.com/confidential-containers/trustee/blob/47d7a2338e0be76308ac19be5c0c172c592780aa/kbs/docs/initdata.md>
#[derive(Deserialize)]
pub struct Initdata {
version: String,
algorithm: String,
data: DefinedFields,
}
/// Well-defined keys for initdata of kata/CoCo
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct DefinedFields {
#[serde(rename = "aa.toml")]
aa_config: Option<String>,
#[serde(rename = "cdh.toml")]
cdh_config: Option<String>,
#[serde(rename = "policy.rego")]
policy: Option<String>,
}
async fn detect_initdata_device(logger: &Logger) -> Result<Option<String>> {
let dev_dir = Path::new("/dev");
let mut read_dir = tokio::fs::read_dir(dev_dir).await?;
while let Some(entry) = read_dir.next_entry().await? {
let filename = entry.file_name();
let filename = filename.to_string_lossy();
debug!(logger, "Initdata check device `{filename}`");
if !filename.starts_with("vd") {
continue;
}
let path = entry.path();
debug!(logger, "Initdata find potential device: `{path:?}`");
let metadata = std::fs::metadata(path.clone())?;
if !metadata.file_type().is_block_device() {
continue;
}
let mut file = tokio::fs::File::open(&path).await?;
let mut magic = [0; 8];
match file.read_exact(&mut magic).await {
Ok(_) => {
debug!(
logger,
"Initdata read device `{filename}` first 8 bytes: {magic:?}"
);
if magic == INITDATA_MAGIC_NUMBER {
let path = path.as_path().to_string_lossy().to_string();
debug!(logger, "Found initdata device {path}");
return Ok(Some(path));
}
}
Err(e) => debug!(logger, "Initdata read device `{filename}` failed: {e:?}"),
}
}
Ok(None)
}
pub async fn read_initdata(device_path: &str) -> Result<Vec<u8>> {
let initdata_devfile = tokio::fs::File::open(device_path).await?;
let mut buf_reader = tokio::io::BufReader::new(initdata_devfile);
// skip the magic number "initdata"
buf_reader.seek(std::io::SeekFrom::Start(8)).await?;
let mut len_buf = [0u8; 8];
buf_reader.read_exact(&mut len_buf).await?;
let length = u64::from_le_bytes(len_buf) as usize;
let mut buf = vec![0; length];
buf_reader.read_exact(&mut buf).await?;
let mut gzip_decoder = GzipDecoder::new(&buf[..]);
let mut initdata = Vec::new();
let _ = gzip_decoder.read_to_end(&mut initdata).await?;
Ok(initdata)
}
pub struct InitdataReturnValue {
pub digest: Vec<u8>,
pub _policy: Option<String>,
}
pub async fn initialize_initdata(logger: &Logger) -> Result<Option<InitdataReturnValue>> {
let logger = logger.new(o!("subsystem" => "initdata"));
let Some(initdata_device) = detect_initdata_device(&logger).await? else {
info!(
logger,
"Initdata device not found, skip initdata initialization"
);
return Ok(None);
};
tokio::fs::create_dir_all(INITDATA_PATH)
.await
.inspect_err(|e| error!(logger, "Failed to create initdata dir: {e:?}"))?;
let initdata_content = read_initdata(&initdata_device)
.await
.inspect_err(|e| error!(logger, "Failed to read initdata: {e:?}"))?;
let initdata: Initdata =
toml::from_slice(&initdata_content).context("parse initdata failed")?;
info!(logger, "Initdata version: {}", initdata.version);
if initdata.version != INITDATA_VERSION {
bail!("Unsupported initdata version");
}
let digest = match &initdata.algorithm[..] {
"sha256" => Sha256::digest(&initdata_content).to_vec(),
"sha384" => Sha384::digest(&initdata_content).to_vec(),
"sha512" => Sha512::digest(&initdata_content).to_vec(),
others => bail!("Unsupported hash algorithm {others}"),
};
if let Some(config) = initdata.data.aa_config {
tokio::fs::write(AA_CONFIG_PATH, config)
.await
.context("write aa config failed")?;
info!(logger, "write AA config from initdata");
}
if let Some(config) = initdata.data.cdh_config {
tokio::fs::write(CDH_CONFIG_PATH, config)
.await
.context("write cdh config failed")?;
info!(logger, "write CDH config from initdata");
}
debug!(logger, "Initdata digest: {}", STANDARD.encode(&digest));
let res = InitdataReturnValue {
digest,
_policy: initdata.data.policy,
};
Ok(Some(res))
}
#[cfg(test)]
mod tests {
use crate::initdata::read_initdata;
const INITDATA_IMG_PATH: &str = "testdata/initdata.img";
const INITDATA_PLAINTEXT: &[u8] = b"some content";
#[tokio::test]
async fn parse_initdata() {
let initdata = read_initdata(INITDATA_IMG_PATH).await.unwrap();
assert_eq!(initdata, INITDATA_PLAINTEXT);
}
}

View File

@ -18,10 +18,12 @@ extern crate scopeguard;
#[macro_use]
extern crate slog;
use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, bail, Context, Result};
use base64::Engine;
use cfg_if::cfg_if;
use clap::{AppSettings, Parser};
use const_format::{concatcp, formatcp};
use initdata::{InitdataReturnValue, AA_CONFIG_PATH, CDH_CONFIG_PATH};
use nix::fcntl::OFlag;
use nix::sys::reboot::{reboot, RebootMode};
use nix::sys::socket::{self, AddressFamily, SockFlag, SockType, VsockAddr};
@ -33,7 +35,6 @@ use std::os::unix::fs::{self as unixfs, FileTypeExt};
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::process::exit;
use std::process::Command;
use std::sync::Arc;
use tracing::{instrument, span};
@ -42,6 +43,7 @@ mod config;
mod console;
mod device;
mod features;
mod initdata;
mod linux_abi;
mod metrics;
mod mount;
@ -419,6 +421,8 @@ async fn start_sandbox(
let (tx, rx) = tokio::sync::oneshot::channel();
sandbox.lock().await.sender = Some(tx);
let initdata_return_value = initdata::initialize_initdata(logger).await?;
let gc_procs = config.guest_components_procs;
if !attestation_binaries_available(logger, &gc_procs) {
warn!(
@ -426,7 +430,21 @@ async fn start_sandbox(
"attestation binaries requested for launch not available"
);
} else {
init_attestation_components(logger, config).await?;
init_attestation_components(logger, config, &initdata_return_value).await?;
}
// if policy is given via initdata, use it
#[cfg(feature = "agent-policy")]
if let Some(initdata_return_value) = initdata_return_value {
if let Some(policy) = &initdata_return_value._policy {
info!(logger, "using policy from initdata");
AGENT_POLICY
.lock()
.await
.set_policy(policy)
.await
.context("Failed to set policy from initdata")?;
}
}
let mut oma = None;
@ -472,19 +490,34 @@ fn attestation_binaries_available(logger: &Logger, procs: &GuestComponentsProcs)
true
}
async fn launch_guest_component_procs(logger: &Logger, config: &AgentConfig) -> Result<()> {
async fn launch_guest_component_procs(
logger: &Logger,
config: &AgentConfig,
initdata_return_value: &Option<InitdataReturnValue>,
) -> Result<()> {
if config.guest_components_procs == GuestComponentsProcs::None {
return Ok(());
}
debug!(logger, "spawning attestation-agent process {}", AA_PATH);
let mut aa_args = vec!["--attestation_sock", AA_ATTESTATION_URI];
let initdata_parameter;
if let Some(initdata_return_value) = initdata_return_value {
initdata_parameter =
base64::engine::general_purpose::STANDARD.encode(&initdata_return_value.digest);
aa_args.push("--initdata");
aa_args.push(&initdata_parameter);
}
launch_process(
logger,
AA_PATH,
&vec!["--attestation_sock", AA_ATTESTATION_URI],
aa_args,
Some(AA_CONFIG_PATH),
AA_ATTESTATION_SOCKET,
DEFAULT_LAUNCH_PROCESS_TIMEOUT,
)
.await
.map_err(|e| anyhow!("launch_process {} failed: {:?}", AA_PATH, e))?;
// skip launch of confidential-data-hub and api-server-rest
@ -500,10 +533,12 @@ async fn launch_guest_component_procs(logger: &Logger, config: &AgentConfig) ->
launch_process(
logger,
CDH_PATH,
&vec![],
vec![],
Some(CDH_CONFIG_PATH),
CDH_SOCKET,
DEFAULT_LAUNCH_PROCESS_TIMEOUT,
)
.await
.map_err(|e| anyhow!("launch_process {} failed: {:?}", CDH_PATH, e))?;
// skip launch of api-server-rest
@ -519,10 +554,12 @@ async fn launch_guest_component_procs(logger: &Logger, config: &AgentConfig) ->
launch_process(
logger,
API_SERVER_PATH,
&vec!["--features", &features.to_string()],
vec!["--features", &features.to_string()],
None,
"",
0,
)
.await
.map_err(|e| anyhow!("launch_process {} failed: {:?}", API_SERVER_PATH, e))?;
Ok(())
@ -532,8 +569,12 @@ async fn launch_guest_component_procs(logger: &Logger, config: &AgentConfig) ->
// and the corresponding procs are enabled in the agent configuration. the process will be
// launched in the background and the function will return immediately.
// If the CDH is started, a CDH client will be instantiated and returned.
async fn init_attestation_components(logger: &Logger, config: &AgentConfig) -> Result<()> {
launch_guest_component_procs(logger, config).await?;
async fn init_attestation_components(
logger: &Logger,
config: &AgentConfig,
initdata_return_value: &Option<InitdataReturnValue>,
) -> Result<()> {
launch_guest_component_procs(logger, config, initdata_return_value).await?;
// If a CDH socket exists, initialize the CDH client and enable ocicrypt
match tokio::fs::metadata(CDH_SOCKET).await {
@ -555,11 +596,11 @@ async fn init_attestation_components(logger: &Logger, config: &AgentConfig) -> R
Ok(())
}
fn wait_for_path_to_exist(logger: &Logger, path: &str, timeout_secs: i32) -> Result<()> {
async fn wait_for_path_to_exist(logger: &Logger, path: &str, timeout_secs: i32) -> Result<()> {
let p = Path::new(path);
let mut attempts = 0;
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
if p.exists() {
return Ok(());
}
@ -576,22 +617,32 @@ fn wait_for_path_to_exist(logger: &Logger, path: &str, timeout_secs: i32) -> Res
Err(anyhow!("wait for {} to exist timeout.", path))
}
fn launch_process(
async fn launch_process(
logger: &Logger,
path: &str,
args: &Vec<&str>,
mut args: Vec<&str>,
config: Option<&str>,
unix_socket_path: &str,
timeout_secs: i32,
) -> Result<()> {
if !Path::new(path).exists() {
return Err(anyhow!("path {} does not exist.", path));
bail!("path {} does not exist.", path);
}
if let Some(config_path) = config {
if Path::new(config_path).exists() {
args.push("-c");
args.push(config_path);
}
}
if !unix_socket_path.is_empty() && Path::new(unix_socket_path).exists() {
fs::remove_file(unix_socket_path)?;
tokio::fs::remove_file(unix_socket_path).await?;
}
Command::new(path).args(args).spawn()?;
tokio::process::Command::new(path).args(args).spawn()?;
if !unix_socket_path.is_empty() && timeout_secs > 0 {
wait_for_path_to_exist(logger, unix_socket_path, timeout_secs)?;
wait_for_path_to_exist(logger, unix_socket_path, timeout_secs).await?;
}
Ok(())

View File

@ -6,11 +6,21 @@
use anyhow::{anyhow, Context, Result};
use futures::{future, StreamExt, TryStreamExt};
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
use netlink_packet_route::address::{AddressAttribute, AddressMessage};
use netlink_packet_route::link::{LinkAttribute, LinkMessage};
use netlink_packet_route::neighbour::{self, NeighbourFlag};
use netlink_packet_route::route::{RouteFlag, RouteHeader, RouteProtocol, RouteScope, RouteType};
use netlink_packet_route::{
neighbour::{NeighbourAddress, NeighbourAttribute, NeighbourState},
route::{RouteAddress, RouteAttribute, RouteMessage},
AddressFamily,
};
use nix::errno::Errno;
use protocols::types::{ARPNeighbor, IPAddress, IPFamily, Interface, Route};
use rtnetlink::{new_connection, packet, IpVersion};
use rtnetlink::{new_connection, IpVersion};
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::fs;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::ops::Deref;
use std::str::{self, FromStr};
@ -35,6 +45,36 @@ impl fmt::Display for LinkFilter<'_> {
}
}
const ALL_RULE_FLAGS: [NeighbourFlag; 8] = [
NeighbourFlag::Use,
NeighbourFlag::Own,
NeighbourFlag::Controller,
NeighbourFlag::Proxy,
NeighbourFlag::ExtLearned,
NeighbourFlag::Offloaded,
NeighbourFlag::Sticky,
NeighbourFlag::Router,
];
const ALL_ROUTE_FLAGS: [RouteFlag; 16] = [
RouteFlag::Dead,
RouteFlag::Pervasive,
RouteFlag::Onlink,
RouteFlag::Offload,
RouteFlag::Linkdown,
RouteFlag::Unresolved,
RouteFlag::Trap,
RouteFlag::Notify,
RouteFlag::Cloned,
RouteFlag::Equalize,
RouteFlag::Prefix,
RouteFlag::LookupTable,
RouteFlag::FibMatch,
RouteFlag::RtOffload,
RouteFlag::RtTrap,
RouteFlag::OffloadFailed,
];
/// A filter to query addresses.
pub enum AddressFilter {
/// Return addresses that belong to the given interface.
@ -74,18 +114,30 @@ impl Handle {
self.enable_link(link.index(), false).await?;
}
// Delete all addresses associated with the link
let addresses = self
.list_addresses(AddressFilter::LinkIndex(link.index()))
.await?;
self.delete_addresses(addresses).await?;
// Get whether the network stack has ipv6 enabled or disabled.
let supports_ipv6_all = fs::read_to_string("/proc/sys/net/ipv6/conf/all/disable_ipv6")
.map(|s| s.trim() == "0")
.unwrap_or(false);
let supports_ipv6_default =
fs::read_to_string("/proc/sys/net/ipv6/conf/default/disable_ipv6")
.map(|s| s.trim() == "0")
.unwrap_or(false);
let supports_ipv6 = supports_ipv6_default || supports_ipv6_all;
// Add new ip addresses from request
for ip_address in &iface.IPAddresses {
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)?))
let net = IpNetwork::new(ip, mask)?;
if !net.is_ipv4() && !supports_ipv6 {
// If we're dealing with an ipv6 address, but the stack does not
// support ipv6, skip adding it otherwise it will lead to an
// error at the "CreatePodSandbox" time.
continue;
}
self.add_addresses(link.index(), std::iter::once(net))
.await?;
}
@ -125,6 +177,7 @@ impl Handle {
}
// Update link
let link = self.find_link(LinkFilter::Address(&iface.hwAddr)).await?;
let mut request = self.handle.link().set(link.index());
request.message_mut().header = link.header.clone();
@ -172,26 +225,6 @@ impl Handle {
Ok(())
}
pub async fn update_routes<I>(&mut self, list: I) -> Result<()>
where
I: IntoIterator<Item = Route>,
{
let old_routes = self
.query_routes(None)
.await
.with_context(|| "Failed to query old routes")?;
self.delete_routes(old_routes)
.await
.with_context(|| "Failed to delete old routes")?;
self.add_routes(list)
.await
.with_context(|| "Failed to add new routes")?;
Ok(())
}
/// Retireve available network interfaces.
pub async fn list_interfaces(&self) -> Result<Vec<Interface>> {
let mut list = Vec::new();
@ -225,7 +258,7 @@ impl Handle {
let request = self.handle.link().get();
let filtered = match filter {
LinkFilter::Name(name) => request.set_name_filter(name.to_owned()),
LinkFilter::Name(name) => request.match_name(name.to_owned()),
LinkFilter::Index(index) => request.match_index(index),
_ => request, // Post filters
};
@ -233,7 +266,7 @@ impl Handle {
let mut stream = filtered.execute();
let next = if let LinkFilter::Address(addr) = filter {
use packet::link::nlas::Nla;
use LinkAttribute as Nla;
let mac_addr = parse_mac_address(addr)
.with_context(|| format!("Failed to parse MAC address: {}", addr))?;
@ -242,7 +275,7 @@ impl Handle {
// we may have to dump link list and then find the target link.
stream
.try_filter(|f| {
let result = f.nlas.iter().any(|n| match n {
let result = f.attributes.iter().any(|n| match n {
Nla::Address(data) => data.eq(&mac_addr),
_ => false,
});
@ -278,10 +311,7 @@ impl Handle {
Ok(())
}
async fn query_routes(
&self,
ip_version: Option<IpVersion>,
) -> Result<Vec<packet::RouteMessage>> {
async fn query_routes(&self, ip_version: Option<IpVersion>) -> Result<Vec<RouteMessage>> {
let list = if let Some(ip_version) = ip_version {
self.handle
.route()
@ -321,36 +351,46 @@ impl Handle {
for msg in self.query_routes(None).await? {
// Ignore non-main tables
if msg.header.table != packet::constants::RT_TABLE_MAIN {
if msg.header.table != RouteHeader::RT_TABLE_MAIN {
continue;
}
let mut route = Route {
scope: msg.header.scope as _,
scope: u8::from(msg.header.scope) as u32,
..Default::default()
};
if let Some((ip, mask)) = msg.destination_prefix() {
route.dest = format!("{}/{}", ip, mask);
}
if let Some((ip, mask)) = msg.source_prefix() {
route.source = format!("{}/{}", ip, mask);
}
if let Some(addr) = msg.gateway() {
route.gateway = addr.to_string();
// For gateway, destination is 0.0.0.0
route.dest = if addr.is_ipv4() {
String::from("0.0.0.0")
} else {
String::from("::1")
for attribute in &msg.attributes {
if let RouteAttribute::Destination(dest) = attribute {
if let Ok(dest) = parse_route_addr(dest) {
route.dest = format!("{}/{}", dest, msg.header.destination_prefix_length);
}
}
}
if let Some(index) = msg.output_interface() {
route.device = self.find_link(LinkFilter::Index(index)).await?.name();
if let RouteAttribute::Source(src) = attribute {
if let Ok(src) = parse_route_addr(src) {
route.source = format!("{}/{}", src, msg.header.source_prefix_length)
}
}
if let RouteAttribute::Gateway(g) = attribute {
if let Ok(addr) = parse_route_addr(g) {
// For gateway, destination is 0.0.0.0
if addr.is_ipv4() {
route.dest = String::from("0.0.0.0");
} else {
route.dest = String::from("::1");
}
}
route.gateway = parse_route_addr(g)
.map(|g| g.to_string())
.unwrap_or_default();
}
if let RouteAttribute::Oif(index) = attribute {
route.device = self.find_link(LinkFilter::Index(*index)).await?.name();
}
}
if !route.dest.is_empty() {
@ -361,10 +401,11 @@ impl Handle {
Ok(result)
}
/// Adds a list of routes from iterable object `I`.
/// Add a list of routes from iterable object `I`.
/// If the route existed, then replace it with the latest.
/// It can accept both a collection of routes or a single item (via `iter::once()`).
/// It'll also take care of proper order when adding routes (gateways first, everything else after).
async fn add_routes<I>(&mut self, list: I) -> Result<()>
pub async fn update_routes<I>(&mut self, list: I) -> Result<()>
where
I: IntoIterator<Item = Route>,
{
@ -377,24 +418,41 @@ impl Handle {
for route in list {
let link = self.find_link(LinkFilter::Name(&route.device)).await?;
const MAIN_TABLE: u8 = packet::constants::RT_TABLE_MAIN;
const UNICAST: u8 = packet::constants::RTN_UNICAST;
const BOOT_PROT: u8 = packet::constants::RTPROT_BOOT;
const MAIN_TABLE: u32 = libc::RT_TABLE_MAIN as u32;
let uni_cast: RouteType = RouteType::from(libc::RTN_UNICAST);
let boot_prot: RouteProtocol = RouteProtocol::from(libc::RTPROT_BOOT);
let scope = route.scope as u8;
let scope = RouteScope::from(route.scope as u8);
use packet::nlas::route::Nla;
use RouteAttribute as Nla;
// Build a common indeterminate ip request
let request = self
let mut request = self
.handle
.route()
.add()
.table(MAIN_TABLE)
.kind(UNICAST)
.protocol(BOOT_PROT)
.table_id(MAIN_TABLE)
.kind(uni_cast)
.protocol(boot_prot)
.scope(scope);
let message = request.message_mut();
// calculate the Flag vec from the u32 flags
let mut got: u32 = 0;
let mut flags = Vec::new();
for flag in ALL_ROUTE_FLAGS {
if (route.flags & (u32::from(flag))) > 0 {
flags.push(flag);
got += u32::from(flag);
}
}
if got != route.flags {
flags.push(RouteFlag::Other(route.flags - got));
}
message.header.flags = flags;
// `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.family() == IPFamily::v6 {
@ -408,7 +466,8 @@ impl Handle {
let mut request = request
.v6()
.destination_prefix(dest_addr.ip(), dest_addr.prefix())
.output_interface(link.index());
.output_interface(link.index())
.replace();
if !route.source.is_empty() {
let network = Ipv6Network::from_str(&route.source)?;
@ -417,8 +476,8 @@ impl Handle {
} else {
request
.message_mut()
.nlas
.push(Nla::PrefSource(network.ip().octets().to_vec()));
.attributes
.push(Nla::PrefSource(RouteAddress::from(network.ip())));
}
}
@ -428,14 +487,16 @@ impl Handle {
}
if let Err(rtnetlink::Error::NetlinkError(message)) = request.execute().await {
if Errno::from_i32(message.code.abs()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v6 route (src: {}, dst: {}, gtw: {},Err: {})",
route.source(),
route.dest(),
route.gateway(),
message
));
if let Some(code) = message.code {
if Errno::from_i32(code.get()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v6 route (src: {}, dst: {}, gtw: {},Err: {})",
route.source(),
route.dest(),
route.gateway(),
message
));
}
}
}
} else {
@ -449,7 +510,8 @@ impl Handle {
let mut request = request
.v4()
.destination_prefix(dest_addr.ip(), dest_addr.prefix())
.output_interface(link.index());
.output_interface(link.index())
.replace();
if !route.source.is_empty() {
let network = Ipv4Network::from_str(&route.source)?;
@ -458,8 +520,8 @@ impl Handle {
} else {
request
.message_mut()
.nlas
.push(Nla::PrefSource(network.ip().octets().to_vec()));
.attributes
.push(RouteAttribute::PrefSource(RouteAddress::from(network.ip())));
}
}
@ -469,14 +531,16 @@ impl Handle {
}
if let Err(rtnetlink::Error::NetlinkError(message)) = request.execute().await {
if Errno::from_i32(message.code.abs()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v4 route (src: {}, dst: {}, gtw: {},Err: {})",
route.source(),
route.dest(),
route.gateway(),
message
));
if let Some(code) = message.code {
if Errno::from_i32(code.get()) != Errno::EEXIST {
return Err(anyhow!(
"Failed to add IP v4 route (src: {}, dst: {}, gtw: {},Err: {})",
route.source(),
route.dest(),
route.gateway(),
message
));
}
}
}
}
@ -485,34 +549,6 @@ impl Handle {
Ok(())
}
async fn delete_routes<I>(&mut self, routes: I) -> Result<()>
where
I: IntoIterator<Item = packet::RouteMessage>,
{
for route in routes.into_iter() {
if route.header.protocol == packet::constants::RTPROT_KERNEL {
continue;
}
let index = if let Some(index) = route.output_interface() {
index
} else {
continue;
};
let link = self.find_link(LinkFilter::Index(index)).await?;
let name = link.name();
if name.contains("lo") || name.contains("::1") {
continue;
}
self.handle.route().del(route).execute().await?;
}
Ok(())
}
async fn list_addresses<F>(&self, filter: F) -> Result<Vec<Address>>
where
F: Into<Option<AddressFilter>>,
@ -534,6 +570,8 @@ impl Handle {
Ok(list)
}
// add the addresses to the specified interface, if the addresses existed,
// replace it with the latest one.
async fn add_addresses<I>(&mut self, index: u32, list: I) -> Result<()>
where
I: IntoIterator<Item = IpNetwork>,
@ -542,6 +580,7 @@ impl Handle {
self.handle
.address()
.add(index, net.ip(), net.prefix())
.replace()
.execute()
.await
.map_err(|err| anyhow!("Failed to add address {}: {:?}", net.ip(), err))?;
@ -550,17 +589,6 @@ impl Handle {
Ok(())
}
async fn delete_addresses<I>(&mut self, list: I) -> Result<()>
where
I: IntoIterator<Item = Address>,
{
for addr in list.into_iter() {
self.handle.address().del(addr.0).execute().await?;
}
Ok(())
}
pub async fn add_arp_neighbors<I>(&mut self, list: I) -> Result<()>
where
I: IntoIterator<Item = ARPNeighbor>,
@ -592,52 +620,57 @@ impl Handle {
.map_err(|e| anyhow!("Failed to parse IP {}: {:?}", ip_address, e))?;
// Import rtnetlink objects that make sense only for this function
use packet::constants::{
NDA_UNSPEC, NLM_F_ACK, NLM_F_CREATE, NLM_F_REPLACE, NLM_F_REQUEST,
};
use packet::neighbour::{NeighbourHeader, NeighbourMessage};
use packet::nlas::neighbour::Nla;
use packet::{NetlinkMessage, NetlinkPayload, RtnlMessage};
use libc::{NDA_UNSPEC, NLM_F_ACK, NLM_F_CREATE, NLM_F_REPLACE, NLM_F_REQUEST};
use neighbour::{NeighbourHeader, NeighbourMessage};
use netlink_packet_core::{NetlinkMessage, NetlinkPayload};
use netlink_packet_route::RouteNetlinkMessage as RtnlMessage;
use rtnetlink::Error;
const IFA_F_PERMANENT: u16 = 0x80; // See https://github.com/little-dude/netlink/blob/0185b2952505e271805902bf175fee6ea86c42b8/netlink-packet-route/src/rtnl/constants.rs#L770
let state = if neigh.state != 0 {
neigh.state as u16
} else {
IFA_F_PERMANENT
};
let link = self.find_link(LinkFilter::Name(&neigh.device)).await?;
let message = NeighbourMessage {
header: NeighbourHeader {
family: match ip {
IpAddr::V4(_) => packet::AF_INET,
IpAddr::V6(_) => packet::AF_INET6,
} as u8,
ifindex: link.index(),
state: if neigh.state != 0 {
neigh.state as u16
} else {
IFA_F_PERMANENT
},
flags: neigh.flags as u8,
ntype: NDA_UNSPEC as u8,
},
nlas: {
let mut nlas = vec![Nla::Destination(match ip {
IpAddr::V4(v4) => v4.octets().to_vec(),
IpAddr::V6(v6) => v6.octets().to_vec(),
})];
let mut flags = Vec::new();
for flag in ALL_RULE_FLAGS {
if (neigh.flags as u8 & (u8::from(flag))) > 0 {
flags.push(flag);
}
}
if !neigh.lladdr.is_empty() {
nlas.push(Nla::LinkLocalAddress(
parse_mac_address(&neigh.lladdr)?.to_vec(),
));
}
let mut message = NeighbourMessage::default();
nlas
message.header = NeighbourHeader {
family: match ip {
IpAddr::V4(_) => AddressFamily::Inet,
IpAddr::V6(_) => AddressFamily::Inet6,
},
ifindex: link.index(),
state: NeighbourState::from(state),
flags,
kind: RouteType::from(NDA_UNSPEC as u8),
};
let mut nlas = vec![NeighbourAttribute::Destination(match ip {
IpAddr::V4(ipv4_addr) => NeighbourAddress::from(ipv4_addr),
IpAddr::V6(ipv6_addr) => NeighbourAddress::from(ipv6_addr),
})];
if !neigh.lladdr.is_empty() {
nlas.push(NeighbourAttribute::LinkLocalAddress(
parse_mac_address(&neigh.lladdr)?.to_vec(),
));
}
message.attributes = nlas;
// Send request and ACK
let mut req = NetlinkMessage::from(RtnlMessage::NewNeighbour(message));
req.header.flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_REPLACE;
req.header.flags = (NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_REPLACE) as u16;
let mut response = self.handle.request(req)?;
while let Some(message) = response.next().await {
@ -700,13 +733,13 @@ fn parse_mac_address(addr: &str) -> Result<[u8; 6]> {
}
/// Wraps external type with the local one, so we can implement various extensions and type conversions.
struct Link(packet::LinkMessage);
struct Link(LinkMessage);
impl Link {
/// If name.
fn name(&self) -> String {
use packet::nlas::link::Nla;
self.nlas
use LinkAttribute as Nla;
self.attributes
.iter()
.find_map(|n| {
if let Nla::IfName(name) = n {
@ -720,8 +753,8 @@ impl Link {
/// Extract Mac address.
fn address(&self) -> String {
use packet::nlas::link::Nla;
self.nlas
use LinkAttribute as Nla;
self.attributes
.iter()
.find_map(|n| {
if let Nla::Address(data) = n {
@ -735,7 +768,12 @@ impl Link {
/// Returns whether the link is UP
fn is_up(&self) -> bool {
self.header.flags & packet::rtnl::constants::IFF_UP > 0
let mut flags: u32 = 0;
for flag in &self.header.flags {
flags += u32::from(*flag);
}
flags as i32 & libc::IFF_UP > 0
}
fn index(&self) -> u32 {
@ -743,8 +781,8 @@ impl Link {
}
fn mtu(&self) -> Option<u64> {
use packet::nlas::link::Nla;
self.nlas.iter().find_map(|n| {
use LinkAttribute as Nla;
self.attributes.iter().find_map(|n| {
if let Nla::Mtu(mtu) = n {
Some(*mtu as u64)
} else {
@ -754,21 +792,21 @@ impl Link {
}
}
impl From<packet::LinkMessage> for Link {
fn from(msg: packet::LinkMessage) -> Self {
impl From<LinkMessage> for Link {
fn from(msg: LinkMessage) -> Self {
Link(msg)
}
}
impl Deref for Link {
type Target = packet::LinkMessage;
type Target = LinkMessage;
fn deref(&self) -> &Self::Target {
&self.0
}
}
struct Address(packet::AddressMessage);
struct Address(AddressMessage);
impl TryFrom<Address> for IPAddress {
type Error = anyhow::Error;
@ -798,7 +836,7 @@ impl TryFrom<Address> for IPAddress {
impl Address {
fn is_ipv6(&self) -> bool {
self.0.header.family == packet::constants::AF_INET6 as u8
u8::from(self.0.header.family) == libc::AF_INET6 as u8
}
#[allow(dead_code)]
@ -807,13 +845,13 @@ impl Address {
}
fn address(&self) -> String {
use packet::nlas::address::Nla;
use AddressAttribute as Nla;
self.0
.nlas
.attributes
.iter()
.find_map(|n| {
if let Nla::Address(data) = n {
format_address(data).ok()
Some(data.to_string())
} else {
None
}
@ -822,13 +860,13 @@ impl Address {
}
fn local(&self) -> String {
use packet::nlas::address::Nla;
use AddressAttribute as Nla;
self.0
.nlas
.attributes
.iter()
.find_map(|n| {
if let Nla::Local(data) = n {
format_address(data).ok()
Some(data.to_string())
} else {
None
}
@ -837,10 +875,21 @@ impl Address {
}
}
fn parse_route_addr(ra: &RouteAddress) -> Result<IpAddr> {
let ipaddr = match ra {
RouteAddress::Inet6(ipv6_addr) => ipv6_addr.to_canonical(),
RouteAddress::Inet(ipv4_addr) => IpAddr::from(*ipv4_addr),
_ => return Err(anyhow!("got invalid route address")),
};
Ok(ipaddr)
}
#[cfg(test)]
mod tests {
use super::*;
use rtnetlink::packet;
use netlink_packet_route::address::AddressHeader;
use netlink_packet_route::link::LinkHeader;
use std::iter;
use std::process::Command;
use test_utils::skip_if_not_root;
@ -853,7 +902,7 @@ mod tests {
.await
.expect("Loopback not found");
assert_ne!(message.header, packet::LinkHeader::default());
assert_ne!(message.header, LinkHeader::default());
assert_eq!(message.name(), "lo");
}
@ -928,7 +977,7 @@ mod tests {
assert_ne!(list.len(), 0);
for addr in &list {
assert_ne!(addr.0.header, packet::AddressHeader::default());
assert_ne!(addr.0.header, AddressHeader::default());
}
}
@ -952,7 +1001,7 @@ mod tests {
}
#[tokio::test]
async fn add_delete_addresses() {
async fn add_update_addresses() {
skip_if_not_root!();
let list = vec![
@ -981,9 +1030,9 @@ mod tests {
assert!(result.is_some());
// Delete it
// Update it
handle
.delete_addresses(iter::once(result.unwrap()))
.add_addresses(lo.index(), iter::once(network))
.await
.expect("Failed to delete address");
}

View File

@ -28,9 +28,9 @@ use oci::{Hooks, LinuxNamespace, Spec};
use oci_spec::runtime as oci;
use protobuf::MessageField;
use protocols::agent::{
AddSwapRequest, AgentDetails, CopyFileRequest, GetIPTablesRequest, GetIPTablesResponse,
GuestDetailsResponse, Interfaces, Metrics, OOMEvent, ReadStreamResponse, Routes,
SetIPTablesRequest, SetIPTablesResponse, StatsContainerResponse, VolumeStatsRequest,
AddSwapPathRequest, AddSwapRequest, AgentDetails, CopyFileRequest, GetIPTablesRequest,
GetIPTablesResponse, GuestDetailsResponse, Interfaces, Metrics, OOMEvent, ReadStreamResponse,
Routes, SetIPTablesRequest, SetIPTablesResponse, StatsContainerResponse, VolumeStatsRequest,
WaitProcessResponse, WriteStreamResponse,
};
use protocols::csi::{
@ -55,11 +55,17 @@ use nix::sys::{stat, statfs};
use nix::unistd::{self, Pid};
use rustjail::process::ProcessOperations;
#[cfg(target_arch = "s390x")]
use crate::ccw;
use crate::cdh;
use crate::device::block_device_handler::get_virtio_blk_pci_device_name;
use crate::device::network_device_handler::wait_for_net_interface;
#[cfg(target_arch = "s390x")]
use crate::device::network_device_handler::wait_for_ccw_net_interface;
#[cfg(not(target_arch = "s390x"))]
use crate::device::network_device_handler::wait_for_pci_net_interface;
use crate::device::{add_devices, handle_cdi_devices, update_env_pci};
use crate::features::get_build_features;
#[cfg(feature = "guest-pull")]
use crate::image::KATA_IMAGE_WORK_DIR;
use crate::linux_abi::*;
use crate::metrics::get_metrics;
@ -106,6 +112,7 @@ use kata_types::k8s;
pub const CONTAINER_BASE: &str = "/run/kata-containers";
const MODPROBE_PATH: &str = "/sbin/modprobe";
#[cfg(feature = "guest-pull")]
const TRUSTED_IMAGE_STORAGE_DEVICE: &str = "/dev/trusted_store";
/// the iptables seriers binaries could appear either in /sbin
/// or /usr/sbin, we need to check both of them
@ -223,7 +230,7 @@ impl AgentService {
// updates the devices listed in the OCI spec, so that they actually
// match real devices inside the VM. This step is necessary since we
// cannot predict everything from the caller.
add_devices(&sl(), &req.devices, &mut oci, &self.sandbox).await?;
add_devices(&cid, &sl(), &req.devices, &mut oci, &self.sandbox).await?;
// In guest-kernel mode some devices need extra handling. Taking the
// GPU as an example the shim will inject CDI annotations that will
@ -234,7 +241,11 @@ impl AgentService {
// readonly
handle_cdi_devices(&sl(), &mut oci, "/var/run/cdi", AGENT_CONFIG.cdi_timeout).await?;
cdh_handler(&mut oci).await?;
// Handle trusted storage configuration before mounting any storage
#[cfg(feature = "guest-pull")]
cdh_handler_trusted_storage(&mut oci)
.await
.map_err(|e| anyhow!("failed to handle trusted storage: {}", e))?;
// Both rootfs and volumes (invoked with --volume for instance) will
// be processed the same way. The idea is to always mount any provided
@ -251,6 +262,11 @@ impl AgentService {
)
.await?;
// Handle sealed secrets after storage is mounted
cdh_handler_sealed_secrets(&mut oci)
.await
.map_err(|e| anyhow!("failed to handle sealed secrets: {}", e))?;
let mut s = self.sandbox.lock().await;
s.container_mounts.insert(cid.clone(), m);
@ -342,24 +358,25 @@ impl AgentService {
async fn do_start_container(&self, req: protocols::agent::StartContainerRequest) -> Result<()> {
let mut s = self.sandbox.lock().await;
let sid = s.id.clone();
let cid = req.container_id;
let cid = req.container_id.clone();
let ctr = s
.get_container(&cid)
.ok_or_else(|| anyhow!("Invalid container id"))?;
ctr.exec().await?;
if sid == cid {
return Ok(());
if sid != cid {
// start oom event loop
if let Ok(cg_path) = ctr.cgroup_manager.as_ref().get_cgroup_path("memory") {
let rx = notifier::notify_oom(cid.as_str(), cg_path.to_string()).await?;
s.run_oom_event_monitor(rx, cid.clone()).await;
}
}
// start oom event loop
if let Ok(cg_path) = ctr.cgroup_manager.as_ref().get_cgroup_path("memory") {
let rx = notifier::notify_oom(cid.as_str(), cg_path.to_string()).await?;
s.run_oom_event_monitor(rx, cid).await;
}
let ctr = s
.get_container(&cid)
.ok_or_else(|| anyhow!("Invalid container id"))?;
Ok(())
ctr.exec().await
}
#[instrument]
@ -369,6 +386,9 @@ impl AgentService {
) -> Result<()> {
let cid = req.container_id;
// Drop the host guest mapping for this container so we can reuse the
// PCI slots for the next containers
if req.timeout == 0 {
let mut sandbox = self.sandbox.lock().await;
sandbox.bind_watcher.remove_container(&cid).await;
@ -424,7 +444,7 @@ impl AgentService {
.ok_or_else(|| anyhow!("Unable to parse process from ExecProcessRequest"))?;
// Apply any necessary corrections for PCI addresses
update_env_pci(&mut process.Env, &sandbox.pcimap)?;
update_env_pci(&cid, &mut process.Env, &sandbox.pcimap)?;
let pipe_size = AGENT_CONFIG.container_pipe_size;
let ocip = process.into();
@ -647,11 +667,11 @@ impl AgentService {
async fn do_read_stream(
&self,
req: protocols::agent::ReadStreamRequest,
req: &protocols::agent::ReadStreamRequest,
stdout: bool,
) -> Result<protocols::agent::ReadStreamResponse> {
let cid = req.container_id;
let eid = req.exec_id;
let cid = &req.container_id;
let eid = &req.exec_id;
let term_exit_notifier;
let reader = {
@ -898,8 +918,12 @@ impl agent_ttrpc::AgentService for AgentService {
_ctx: &TtrpcContext,
req: protocols::agent::ReadStreamRequest,
) -> ttrpc::Result<ReadStreamResponse> {
is_allowed(&req).await?;
self.do_read_stream(req, true).await.map_ttrpc_err(same)
let mut response = self.do_read_stream(&req, true).await.map_ttrpc_err(same)?;
if is_allowed(&req).await.is_err() {
// Policy does not allow reading logs, so we redact the log messages.
response.clear_data();
}
Ok(response)
}
async fn read_stderr(
@ -907,8 +931,12 @@ impl agent_ttrpc::AgentService for AgentService {
_ctx: &TtrpcContext,
req: protocols::agent::ReadStreamRequest,
) -> ttrpc::Result<ReadStreamResponse> {
is_allowed(&req).await?;
self.do_read_stream(req, false).await.map_ttrpc_err(same)
let mut response = self.do_read_stream(&req, false).await.map_ttrpc_err(same)?;
if is_allowed(&req).await.is_err() {
// Policy does not allow reading logs, so we redact the log messages.
response.clear_data();
}
Ok(response)
}
async fn close_stdin(
@ -989,15 +1017,27 @@ impl agent_ttrpc::AgentService for AgentService {
"empty update interface request",
)?;
// For network devices passed on the pci bus, check for the network interface
// For network devices passed, check for the network interface
// to be available first.
if !interface.pciPath.is_empty() {
let pcipath = pci::Path::from_str(&interface.pciPath)
.map_ttrpc_err(|e| format!("Unexpected pci-path for network interface: {:?}", e))?;
wait_for_net_interface(&self.sandbox, &pcipath)
.await
.map_ttrpc_err(|e| format!("interface not available: {:?}", e))?;
if !interface.devicePath.is_empty() {
#[cfg(not(target_arch = "s390x"))]
{
let pcipath = pci::Path::from_str(&interface.devicePath).map_ttrpc_err(|e| {
format!("Unexpected pci-path for network interface: {:?}", e)
})?;
wait_for_pci_net_interface(&self.sandbox, &pcipath)
.await
.map_ttrpc_err(|e| format!("interface not available: {:?}", e))?;
}
#[cfg(target_arch = "s390x")]
{
let ccw_dev = ccw::Device::from_str(&interface.devicePath).map_ttrpc_err(|e| {
format!("Unexpected CCW path for network interface: {:?}", e)
})?;
wait_for_ccw_net_interface(&self.sandbox, &ccw_dev)
.await
.map_ttrpc_err(|e| format!("interface not available: {:?}", e))?;
}
}
self.sandbox
@ -1534,6 +1574,19 @@ impl agent_ttrpc::AgentService for AgentService {
Ok(Empty::new())
}
async fn add_swap_path(
&self,
ctx: &TtrpcContext,
req: protocols::agent::AddSwapPathRequest,
) -> ttrpc::Result<Empty> {
trace_rpc_call!(ctx, "add_swap_path", req);
is_allowed(&req).await?;
do_add_swap_path(&req).await.map_ttrpc_err(same)?;
Ok(Empty::new())
}
#[cfg(feature = "agent-policy")]
async fn set_policy(
&self,
@ -1850,6 +1903,8 @@ async fn remove_container_resources(sandbox: &mut Sandbox, cid: &str) -> Result<
sandbox.container_mounts.remove(cid);
sandbox.containers.remove(cid);
// Remove any host -> guest mappings for this container
sandbox.pcimap.remove(cid);
Ok(())
}
@ -2059,6 +2114,19 @@ async fn do_add_swap(sandbox: &Arc<Mutex<Sandbox>>, req: &AddSwapRequest) -> Res
Ok(())
}
async fn do_add_swap_path(req: &AddSwapPathRequest) -> Result<()> {
let c_str = CString::new(req.path.clone())?;
let ret = unsafe { libc::swapon(c_str.as_ptr() as *const c_char, 0) };
if ret != 0 {
return Err(anyhow!(
"libc::swapon get error {}",
io::Error::last_os_error()
));
}
Ok(())
}
// Setup container bundle under CONTAINER_BASE, which is cleaned up
// before removing a container.
// - bundle path is /<CONTAINER_BASE>/<cid>/
@ -2175,7 +2243,42 @@ fn is_sealed_secret_path(source_path: &str) -> bool {
.any(|suffix| source_path.ends_with(suffix))
}
async fn cdh_handler(oci: &mut Spec) -> Result<()> {
#[cfg(feature = "guest-pull")]
async fn cdh_handler_trusted_storage(oci: &mut Spec) -> Result<()> {
if !cdh::is_cdh_client_initialized().await {
return Ok(());
}
let linux = oci
.linux()
.as_ref()
.ok_or_else(|| anyhow!("Spec didn't contain linux field"))?;
if let Some(devices) = linux.devices() {
for specdev in devices.iter() {
if specdev.path().as_path().to_str() == Some(TRUSTED_IMAGE_STORAGE_DEVICE) {
let dev_major_minor = format!("{}:{}", specdev.major(), specdev.minor());
let secure_storage_integrity = AGENT_CONFIG.secure_storage_integrity.to_string();
info!(
sl(),
"trusted_store device major:min {}, enable data integrity {}",
dev_major_minor,
secure_storage_integrity
);
let options = std::collections::HashMap::from([
("deviceId".to_string(), dev_major_minor),
("encryptType".to_string(), "LUKS".to_string()),
("dataIntegrity".to_string(), secure_storage_integrity),
]);
cdh::secure_mount("BlockDevice", &options, vec![], KATA_IMAGE_WORK_DIR).await?;
break;
}
}
}
Ok(())
}
async fn cdh_handler_sealed_secrets(oci: &mut Spec) -> Result<()> {
if !cdh::is_cdh_client_initialized().await {
return Ok(());
}
@ -2232,33 +2335,6 @@ async fn cdh_handler(oci: &mut Spec) -> Result<()> {
}
}
let linux = oci
.linux()
.as_ref()
.ok_or_else(|| anyhow!("Spec didn't contain linux field"))?;
if let Some(devices) = linux.devices() {
for specdev in devices.iter() {
if specdev.path().as_path().to_str() == Some(TRUSTED_IMAGE_STORAGE_DEVICE) {
let dev_major_minor = format!("{}:{}", specdev.major(), specdev.minor());
let secure_storage_integrity = AGENT_CONFIG.secure_storage_integrity.to_string();
info!(
sl(),
"trusted_store device major:min {}, enable data integrity {}",
dev_major_minor,
secure_storage_integrity
);
let options = std::collections::HashMap::from([
("deviceId".to_string(), dev_major_minor),
("encryptType".to_string(), "LUKS".to_string()),
("dataIntegrity".to_string(), secure_storage_integrity),
]);
cdh::secure_mount("BlockDevice", &options, vec![], KATA_IMAGE_WORK_DIR).await?;
break;
}
}
}
Ok(())
}

View File

@ -95,6 +95,8 @@ impl StorageState {
}
}
pub type PciHostGuestMapping = HashMap<pci::Address, pci::Address>;
#[derive(Debug)]
pub struct Sandbox {
pub logger: Logger,
@ -118,7 +120,7 @@ pub struct Sandbox {
pub event_rx: Arc<Mutex<Receiver<String>>>,
pub event_tx: Option<Sender<String>>,
pub bind_watcher: BindWatcher,
pub pcimap: HashMap<pci::Address, pci::Address>,
pub pcimap: HashMap<String, PciHostGuestMapping>,
pub devcg_info: Arc<RwLock<DevicesCgroupInfo>>,
}

BIN
src/agent/testdata/initdata.img vendored Normal file

Binary file not shown.

View File

@ -2,20 +2,20 @@
name = "vsock-exporter"
version = "0.1.0"
authors = ["James O. D. Hunt <james.o.hunt@intel.com>"]
edition = "2018"
license = "Apache-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
edition.workspace = true
license.workspace = true
[dependencies]
nix = "0.24.2"
libc = "0.2.94"
thiserror = "1.0.26"
opentelemetry = { version = "0.14.0", features=["serialize"] }
serde = { version = "1.0.126", features = ["derive"] }
tokio-vsock = "0.3.1"
libc.workspace = true
thiserror.workspace = true
opentelemetry = { workspace = true, features = ["serialize"] }
tokio-vsock.workspace = true
bincode = "1.3.3"
byteorder = "1.4.3"
slog = { version = "2.5.2", features = ["dynamic-keys", "max_level_trace", "release_max_level_debug"] }
async-trait = "0.1.50"
tokio = "1.28.1"
slog = { workspace = true, features = [
"dynamic-keys",
"max_level_trace",
"release_max_level_debug",
] }
async-trait.workspace = true
tokio.workspace = true

View File

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "addr2line"
@ -238,22 +238,18 @@ dependencies = [
[[package]]
name = "crossbeam-channel"
version = "0.5.8"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200"
checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
dependencies = [
"cfg-if",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.16"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
dependencies = [
"cfg-if",
]
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "crypto-common"
@ -265,6 +261,13 @@ dependencies = [
"typenum",
]
[[package]]
name = "dbs-acpi"
version = "0.1.0"
dependencies = [
"vm-memory",
]
[[package]]
name = "dbs-address-space"
version = "0.3.0"
@ -303,6 +306,8 @@ name = "dbs-boot"
version = "0.4.0"
dependencies = [
"dbs-arch",
"dbs-device",
"device_tree",
"kvm-bindings",
"kvm-ioctls",
"lazy_static",
@ -350,6 +355,7 @@ version = "0.1.0"
dependencies = [
"byteorder",
"dbs-allocator",
"dbs-arch",
"dbs-boot",
"dbs-device",
"dbs-interrupt",
@ -364,6 +370,16 @@ dependencies = [
"vm-memory",
]
[[package]]
name = "dbs-tdx"
version = "0.1.0"
dependencies = [
"kvm-bindings",
"serde_json",
"thiserror",
"vmm-sys-util",
]
[[package]]
name = "dbs-upcall"
version = "0.3.0"
@ -385,6 +401,7 @@ dependencies = [
"libc",
"log",
"serde",
"serde_json",
"thiserror",
"timerfd",
"vmm-sys-util",
@ -446,6 +463,12 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "device_tree"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f18f717c5c7c2e3483feb64cccebd077245ad6d19007c2db0fd341d38595353c"
[[package]]
name = "digest"
version = "0.10.7"
@ -984,9 +1007,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.147"
version = "0.2.172"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
[[package]]
name = "libz-sys"
@ -1040,9 +1063,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.20"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "lz4"
@ -1096,9 +1119,9 @@ dependencies = [
[[package]]
name = "mio"
version = "0.8.8"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2"
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
dependencies = [
"libc",
"log",

View File

@ -9,34 +9,86 @@ repository = "https://github.com/kata-containers/kata-containers.git"
license = "Apache-2.0"
edition = "2018"
[workspace]
members = [
"dbs_acpi",
"dbs_address_space",
"dbs_allocator",
"dbs_arch",
"dbs_boot",
"dbs_device",
"dbs_interrupt",
"dbs_legacy_devices",
"dbs_pci",
"dbs_tdx",
"dbs_upcall",
"dbs_utils",
"dbs_virtio_devices",
]
resolver = "2"
[workspace.dependencies]
# Rust-VMM crates
event-manager = "0.2.1"
kvm-bindings = "0.6.0"
kvm-ioctls = "0.12.0"
linux-loader = "0.8.0"
seccompiler = "0.2.0"
vfio-bindings = "0.3.0"
vfio-ioctls = "0.1.0"
virtio-bindings = "0.1.0"
virtio-queue = "0.7.0"
vm-fdt = "0.2.0"
vm-memory = "0.10.0"
vm-superio = "0.5.0"
vmm-sys-util = "0.11.0"
# Local dependencies from Dragonball Sandbox crates
dbs-acpi = { path = "dbs_acpi" }
dbs-address-space = { path = "dbs_address_space" }
dbs-allocator = { path = "dbs_allocator" }
dbs-arch = { path = "dbs_arch" }
dbs-boot = { path = "dbs_boot" }
dbs-device = { path = "dbs_device" }
dbs-interrupt = { path = "dbs_interrupt" }
dbs-legacy-devices = { path = "dbs_legacy_devices" }
dbs-pci = { path = "dbs_pci" }
dbs-tdx = { path = "dbs_tdx" }
dbs-upcall = { path = "dbs_upcall" }
dbs-utils = { path = "dbs_utils" }
dbs-virtio-devices = { path = "dbs_virtio_devices" }
# Local dependencies from `src/lib`
test-utils = { path = "../libs/test-utils" }
[dependencies]
anyhow = "1.0.32"
arc-swap = "1.5.0"
bytes = "1.1.0"
dbs-address-space = { path = "./src/dbs_address_space" }
dbs-allocator = { path = "./src/dbs_allocator" }
dbs-arch = { path = "./src/dbs_arch" }
dbs-boot = { path = "./src/dbs_boot" }
dbs-device = { path = "./src/dbs_device" }
dbs-interrupt = { path = "./src/dbs_interrupt", features = ["kvm-irq"] }
dbs-legacy-devices = { path = "./src/dbs_legacy_devices" }
dbs-upcall = { path = "./src/dbs_upcall", optional = true }
dbs-utils = { path = "./src/dbs_utils" }
dbs-virtio-devices = { path = "./src/dbs_virtio_devices", optional = true, features = [
"virtio-mmio",
dbs-address-space = { workspace = true }
dbs-allocator = { workspace = true }
dbs-arch = { workspace = true }
dbs-boot = { workspace = true }
dbs-device = { workspace = true }
dbs-interrupt = { workspace = true, features = ["kvm-irq"] }
dbs-legacy-devices = { workspace = true }
dbs-upcall = { workspace = true, optional = true }
dbs-utils = { workspace = true }
dbs-virtio-devices = { workspace = true, optional = true, features = [
"virtio-mmio",
] }
dbs-pci = { path = "./src/dbs_pci", optional = true }
dbs-pci = { workspace = true, optional = true }
derivative = "2.2.0"
kvm-bindings = "0.6.0"
kvm-ioctls = "0.12.0"
kvm-bindings = { workspace = true }
kvm-ioctls = { workspace = true }
lazy_static = "1.2"
libc = "0.2.39"
linux-loader = "0.8.0"
linux-loader = {workspace = true}
log = "0.4.14"
nix = "0.24.2"
procfs = "0.12.0"
prometheus = { version = "0.13.0", features = ["process"] }
seccompiler = "0.2.0"
seccompiler = {workspace = true}
serde = "1.0.27"
serde_derive = "1.0.27"
serde_json = "1.0.9"
@ -44,18 +96,18 @@ slog = "2.5.2"
slog-scope = "4.4.0"
thiserror = "1"
tracing = "0.1.37"
vmm-sys-util = "0.11.0"
virtio-queue = { version = "0.7.0", optional = true }
vm-memory = { version = "0.10.0", features = ["backend-mmap"] }
vmm-sys-util = {workspace = true}
virtio-queue = { workspace = true, optional = true }
vm-memory = { workspace = true, features = ["backend-mmap"] }
crossbeam-channel = "0.5.6"
fuse-backend-rs = "0.10.5"
vfio-bindings = { version = "0.3.0", optional = true }
vfio-ioctls = { version = "0.1.0", optional = true }
vfio-bindings = { workspace = true, optional = true }
vfio-ioctls = { workspace = true, optional = true }
[dev-dependencies]
slog-async = "2.7.0"
slog-term = "2.9.0"
test-utils = { path = "../libs/test-utils" }
test-utils = { workspace = true }
[features]
acpi = []

View File

@ -35,7 +35,7 @@ vendor:
format:
@echo "INFO: rust fmt..."
# This is kinda dirty step here simply because cargo fmt --all will apply fmt to all dependencies of dragonball which will include /src/libs/protocols with some file generated during compilation time and could not be formatted when you use cargo fmt --all before building the whole project. In order to avoid this problem, we do fmt check in this following way.
rustfmt --edition 2018 ./src/dbs_address_space/src/lib.rs ./src/dbs_allocator/src/lib.rs ./src/dbs_arch/src/lib.rs ./src/dbs_boot/src/lib.rs ./src/dbs_device/src/lib.rs ./src/dbs_interrupt/src/lib.rs ./src/dbs_legacy_devices/src/lib.rs ./src/dbs_pci/src/lib.rs ./src/dbs_upcall/src/lib.rs ./src/dbs_utils/src/lib.rs ./src/dbs_virtio_devices/src/lib.rs ./src/lib.rs --check
rustfmt --edition 2018 ./dbs_address_space/src/lib.rs ./dbs_allocator/src/lib.rs ./dbs_arch/src/lib.rs ./dbs_boot/src/lib.rs ./dbs_device/src/lib.rs ./dbs_interrupt/src/lib.rs ./dbs_legacy_devices/src/lib.rs ./dbs_pci/src/lib.rs ./dbs_upcall/src/lib.rs ./dbs_utils/src/lib.rs ./dbs_virtio_devices/src/lib.rs ./src/lib.rs --check
clean:
cargo clean

View File

@ -20,19 +20,19 @@ and configuration process.
- vCPU: [vCPU Document](docs/vcpu.md)
- API: [API Document](docs/api.md)
- `Upcall`: [`Upcall` Document](docs/upcall.md)
- `dbs_acpi`: [`dbs_acpi` Document](src/dbs_acpi/README.md)
- `dbs_address_space`: [`dbs_address_space` Document](src/dbs_address_space/README.md)
- `dbs_allocator`: [`dbs_allocator` Document](src/dbs_allocator/README.md)
- `dbs_arch`: [`dbs_arch` Document](src/dbs_arch/README.md)
- `dbs_boot`: [`dbs_boot` Document](src/dbs_boot/README.md)
- `dbs_device`: [`dbs_device` Document](src/dbs_device/README.md)
- `dbs_interrupt`: [`dbs_interrput` Document](src/dbs_interrupt/README.md)
- `dbs_legacy_devices`: [`dbs_legacy_devices` Document](src/dbs_legacy_devices/README.md)
- `dbs_tdx`: [`dbs_tdx` Document](src/dbs_tdx/README.md)
- `dbs_upcall`: [`dbs_upcall` Document](src/dbs_upcall/README.md)
- `dbs_utils`: [`dbs_utils` Document](src/dbs_utils/README.md)
- `dbs_virtio_devices`: [`dbs_virtio_devices` Document](src/dbs_virtio_devices/README.md)
- `dbs_pci`: [`dbc_pci` Document](src/dbs_pci/README.md)
- `dbs_acpi`: [`dbs_acpi` Document](dbs_acpi/README.md)
- `dbs_address_space`: [`dbs_address_space` Document](dbs_address_space/README.md)
- `dbs_allocator`: [`dbs_allocator` Document](dbs_allocator/README.md)
- `dbs_arch`: [`dbs_arch` Document](dbs_arch/README.md)
- `dbs_boot`: [`dbs_boot` Document](dbs_boot/README.md)
- `dbs_device`: [`dbs_device` Document](dbs_device/README.md)
- `dbs_interrupt`: [`dbs_interrput` Document](dbs_interrupt/README.md)
- `dbs_legacy_devices`: [`dbs_legacy_devices` Document](dbs_legacy_devices/README.md)
- `dbs_tdx`: [`dbs_tdx` Document](dbs_tdx/README.md)
- `dbs_upcall`: [`dbs_upcall` Document](dbs_upcall/README.md)
- `dbs_utils`: [`dbs_utils` Document](dbs_utils/README.md)
- `dbs_virtio_devices`: [`dbs_virtio_devices` Document](dbs_virtio_devices/README.md)
- `dbs_pci`: [`dbc_pci` Document](dbs_pci/README.md)
Currently, the documents are still actively adding.
You could see the [official documentation](docs/) page for more details.

View File

@ -11,4 +11,4 @@ keywords = ["dragonball", "acpi", "vmm", "secure-sandbox"]
readme = "README.md"
[dependencies]
vm-memory = "0.9.0"
vm-memory = {workspace = true}

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