diff --git a/.golangci.yaml b/.golangci.yaml index a3b8244a8ec..d6718ebbc7d 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -4,6 +4,8 @@ run: build-tags: - test - sqlite + - libvirt + - libvirt_dlopen linters: default: none enable: @@ -194,6 +196,10 @@ linters: - pkg: google.golang.org/protobuf/proto alias: grpc_proto + # libvirt + - pkg: libvirt.org/go/libvirt + alias: virt + # woodpecker internal - pkg: go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types alias: backend_types diff --git a/.woodpecker/binaries.yaml b/.woodpecker/binaries.yaml index 5c1c6622c67..1c7e95094ef 100644 --- a/.woodpecker/binaries.yaml +++ b/.woodpecker/binaries.yaml @@ -42,9 +42,40 @@ steps: - apt install -y tree - make cross-compile-server environment: - PLATFORMS: linux|arm64/v8;linux|amd64;linux|riscv64;windows-10|amd64;freebsd|amd64 + PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;windows-10|amd64;freebsd|amd64' SQLITE_ENABLED: 'true' - TAGS: netgo + STATIC_BUILD: 'true' + TAGS: 'netgo' + ARCHIVE_IT: '1' + + cross-compile-agent: + depends_on: + - vendor + image: *xgo_image + pull: true + commands: + - apt update + - apt install -y tree + - make cross-compile-agent + environment: + PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;linux|arm/v7' + STATIC_BUILD: 'false' + LIBVIRT_ENABLED: 'true' + ARCHIVE_IT: '1' + + cross-compile-cli: + depends_on: + - vendor + image: *xgo_image + pull: true + commands: + - apt update + - apt install -y tree + - make cross-compile-cli + environment: + PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;linux|arm/v7' + STATIC_BUILD: 'false' + LIBVIRT_ENABLED: 'true' ARCHIVE_IT: '1' build-tarball: @@ -76,6 +107,8 @@ steps: build-deb-rpm: depends_on: - cross-compile-server + - cross-compile-agent + - cross-compile-cli - build-agent - build-cli image: *golang_image @@ -120,6 +153,8 @@ steps: checksums: depends_on: - cross-compile-server + - cross-compile-agent + - cross-compile-cli - build-agent - build-cli - build-deb-rpm diff --git a/.woodpecker/docker.yaml b/.woodpecker/docker.yaml index 5b76ded0baa..3b83ea570fb 100644 --- a/.woodpecker/docker.yaml +++ b/.woodpecker/docker.yaml @@ -98,6 +98,7 @@ steps: environment: &server_env PLATFORMS: 'linux|amd64' SQLITE_ENABLED: 'true' + STATIC_BUILD: 'true' TAGS: 'netgo' when: - event: [pull_request, pull_request_metadata] diff --git a/.woodpecker/test.yaml b/.woodpecker/test.yaml index a311950fd1a..3b0202e12cf 100644 --- a/.woodpecker/test.yaml +++ b/.woodpecker/test.yaml @@ -100,6 +100,7 @@ steps: - vendor image: *golang_image commands: + - apt update && apt install -y libvirt-dev - make test-lib when: - path: *when_path diff --git a/Makefile b/Makefile index 2874bffba07..49f4f22358e 100644 --- a/Makefile +++ b/Makefile @@ -37,9 +37,10 @@ else endif endif -# go build tags, feature flags like SQLITE_ENABLED add to them +# go build tags, feature flags like SQLITE_ENABLED and LIBVIRT_ENABLED add to them TAGS ?= LDFLAGS := -X go.woodpecker-ci.org/woodpecker/v3/version.Version=${VERSION} + STATIC_BUILD ?= true ifeq ($(STATIC_BUILD),true) LDFLAGS := -s -w -extldflags "-static" $(LDFLAGS) @@ -51,6 +52,27 @@ ifeq ($(shell hash go > /dev/null 2>&1 && echo 1),$(CGO_ENABLED)) endif CGO_CFLAGS ?= +# on non linux targets we force disable libvirt backend +ifneq ($(TARGETOS),linux) + override LIBVIRT_ENABLED := false +endif + +# enable libvirt by default if cgo is enabled +ifeq ($(CGO_ENABLED),1) + LIBVIRT_ENABLED ?= true +else + ifeq ($(LIBVIRT_ENABLED),true) + $(error wrong combination CGO_ENABLED must be '1' if LIBVIRT_ENABLED is 'true') + endif +endif +ifeq ($(LIBVIRT_ENABLED),true) + override TAGS += libvirt + ifneq ($(STATIC_BUILD),true) + # we have dynamic build so we can do dynamic so loading + override TAGS += libvirt_dlopen + endif +endif + # enable sqlite by default if cgo is enabled ifeq ($(CGO_ENABLED),1) SQLITE_ENABLED ?= true @@ -80,6 +102,8 @@ ifeq (in_docker,$(firstword $(MAKECMDGOALS))) -e TARGETOS="linux" \ -e TARGETARCH="$(TARGETARCH)" \ -e CGO_ENABLED="$(CGO_ENABLED)" \ + -e LIBVIRT_ENABLED="$(LIBVIRT_ENABLED)" \ + -e SQLITE_ENABLED="$(SQLITE_ENABLED)" \ -v $(PWD):/build --rm woodpecker/make:local make $(MAKE_ARGS) else @@ -204,21 +228,24 @@ lint-ui: ui-dependencies ## Lint UI code (cd web/; pnpm lint --quiet) test-agent: ## Test agent code - go test -race -cover -coverpkg=./... -coverprofile agent-coverage.out -timeout 60s -tags 'test $(TAGS)' go.woodpecker-ci.org/woodpecker/v3/cmd/agent go.woodpecker-ci.org/woodpecker/v3/agent/... + go test -race -cover -coverpkg=./... -coverprofile agent-coverage.out -timeout 60s -tags 'test' go.woodpecker-ci.org/woodpecker/v3/cmd/agent go.woodpecker-ci.org/woodpecker/v3/agent/... test-server: ## Test server code - go test -race -cover -coverpkg=./... -coverprofile server-coverage.out -timeout 60s -tags 'test $(TAGS)' go.woodpecker-ci.org/woodpecker/v3/cmd/server $(shell go list go.woodpecker-ci.org/woodpecker/v3/server/... | grep -v '/store') + # note: do not add 'sqlite_unlock_notify' to tags or test will hang + go test -race -cover -coverpkg=./... -coverprofile server-coverage.out -timeout 60s -tags 'test sqlite' go.woodpecker-ci.org/woodpecker/v3/cmd/server $(shell go list go.woodpecker-ci.org/woodpecker/v3/server/... | grep -v '/store') test-cli: ## Test cli code - go test -race -cover -coverpkg=./... -coverprofile cli-coverage.out -timeout 60s -tags 'test $(TAGS)' go.woodpecker-ci.org/woodpecker/v3/cmd/cli go.woodpecker-ci.org/woodpecker/v3/cli/... + go test -race -cover -coverpkg=./... -coverprofile cli-coverage.out -timeout 60s -tags 'test' go.woodpecker-ci.org/woodpecker/v3/cmd/cli go.woodpecker-ci.org/woodpecker/v3/cli/... # Migration tests reset the shared database, so datastore packages must run serially. test-server-datastore: ## Test server datastore - go test -p 1 -timeout 300s -tags 'test $(TAGS)' -run TestMigrate go.woodpecker-ci.org/woodpecker/v3/server/store/... - go test -p 1 -race -timeout 300s -tags 'test $(TAGS)' -skip TestMigrate go.woodpecker-ci.org/woodpecker/v3/server/store/... + # note: do not add 'sqlite_unlock_notify' to tags or test will hang + go test -p 1 -timeout 300s -tags 'test sqlite' -run TestMigrate go.woodpecker-ci.org/woodpecker/v3/server/store/... + go test -p 1 -race -timeout 300s -tags 'test sqlite' -skip TestMigrate go.woodpecker-ci.org/woodpecker/v3/server/store/... test-server-datastore-coverage: ## Test server datastore with coverage report - go test -race -cover -coverpkg=./... -coverprofile datastore-coverage.out -timeout 300s -tags 'test $(TAGS)' go.woodpecker-ci.org/woodpecker/v3/server/store/... + # note: do not add 'sqlite_unlock_notify' to tags or test will hang + go test -race -cover -coverpkg=./... -coverprofile datastore-coverage.out -timeout 300s -tags 'test sqlite' go.woodpecker-ci.org/woodpecker/v3/server/store/... test-ui: ui-dependencies ## Test UI code (cd web/; pnpm run lint) @@ -227,10 +254,10 @@ test-ui: ui-dependencies ## Test UI code (cd web/; pnpm run test) test-lib: ## Test lib code - go test -race -cover -coverpkg=./... -coverprofile coverage.out -timeout 60s -tags 'test $(TAGS)' $(shell go list ./... | grep -v '/cmd\|/agent\|/cli\|/server') + go test -race -cover -coverpkg=./... -coverprofile coverage.out -timeout 60s -tags 'test sqlite libvirt libvirt_dlopen' $(shell go list ./... | grep -v '/cmd\|/agent\|/cli\|/server') test-e2e: ## Test by running yaml config and compare expected result - go test -race -cover -coverpkg=./... -coverprofile e2e-coverage.out -timeout 60s -tags 'test $(TAGS)' ./e2e/... + go test -race -cover -coverpkg=./... -coverprofile e2e-coverage.out -timeout 60s -tags 'test sqlite' ./e2e/... .PHONY: test test: test-agent test-server test-server-datastore test-cli test-lib test-e2e ## Run all tests @@ -334,12 +361,8 @@ release-server: ## Create server binaries for release tar -cvzf ${DIST_DIR}/woodpecker-server_$(TARGETOS)_$(TARGETARCH).tar.gz -C ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH) woodpecker-server$(BIN_SUFFIX); \ fi -release-agent: ## Create agent binaries for release +release-agent: ## Create non-linux agent binaries for release (linux: cross-compile-agent) # compile - GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/linux_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/linux_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=linux GOARCH=riscv64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/linux_riscv64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=linux GOARCH=arm CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/linux_arm/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/windows_amd64/woodpecker-agent.exe go.woodpecker-ci.org/woodpecker/v3/cmd/agent GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/darwin_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/darwin_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent @@ -348,10 +371,6 @@ release-agent: ## Create agent binaries for release GOOS=openbsd GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/openbsd_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent GOOS=openbsd GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/openbsd_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent # tar binary files - tar -cvzf ${DIST_DIR}/woodpecker-agent_linux_amd64.tar.gz -C ${DIST_DIR}/agent/linux_amd64 woodpecker-agent - tar -cvzf ${DIST_DIR}/woodpecker-agent_linux_arm64.tar.gz -C ${DIST_DIR}/agent/linux_arm64 woodpecker-agent - tar -cvzf ${DIST_DIR}/woodpecker-agent_linux_riscv64.tar.gz -C ${DIST_DIR}/agent/linux_riscv64 woodpecker-agent - tar -cvzf ${DIST_DIR}/woodpecker-agent_linux_arm.tar.gz -C ${DIST_DIR}/agent/linux_arm woodpecker-agent tar -cvzf ${DIST_DIR}/woodpecker-agent_darwin_amd64.tar.gz -C ${DIST_DIR}/agent/darwin_amd64 woodpecker-agent tar -cvzf ${DIST_DIR}/woodpecker-agent_darwin_arm64.tar.gz -C ${DIST_DIR}/agent/darwin_arm64 woodpecker-agent tar -cvzf ${DIST_DIR}/woodpecker-agent_freebsd_amd64.tar.gz -C ${DIST_DIR}/agent/freebsd_amd64 woodpecker-agent @@ -362,12 +381,8 @@ release-agent: ## Create agent binaries for release rm -f ${DIST_DIR}/woodpecker-agent_windows_amd64.zip zip -j ${DIST_DIR}/woodpecker-agent_windows_amd64.zip ${DIST_DIR}/agent/windows_amd64/woodpecker-agent.exe -release-cli: ## Create cli binaries for release +release-cli: ## Create non-linux cli binaries for release (linux: cross-compile-cli) # compile - GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/linux_amd64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli - GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/linux_arm64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli - GOOS=linux GOARCH=riscv64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/linux_riscv64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli - GOOS=linux GOARCH=arm CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/linux_arm/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/windows_amd64/woodpecker-cli.exe go.woodpecker-ci.org/woodpecker/v3/cmd/cli GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/darwin_amd64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/darwin_arm64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli @@ -376,10 +391,6 @@ release-cli: ## Create cli binaries for release GOOS=openbsd GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/openbsd_amd64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli GOOS=openbsd GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${DIST_DIR}/cli/openbsd_arm64/woodpecker-cli go.woodpecker-ci.org/woodpecker/v3/cmd/cli # tar binary files - tar -cvzf ${DIST_DIR}/woodpecker-cli_linux_amd64.tar.gz -C ${DIST_DIR}/cli/linux_amd64 woodpecker-cli - tar -cvzf ${DIST_DIR}/woodpecker-cli_linux_arm64.tar.gz -C ${DIST_DIR}/cli/linux_arm64 woodpecker-cli - tar -cvzf ${DIST_DIR}/woodpecker-cli_linux_riscv64.tar.gz -C ${DIST_DIR}/cli/linux_riscv64 woodpecker-cli - tar -cvzf ${DIST_DIR}/woodpecker-cli_linux_arm.tar.gz -C ${DIST_DIR}/cli/linux_arm woodpecker-cli tar -cvzf ${DIST_DIR}/woodpecker-cli_darwin_amd64.tar.gz -C ${DIST_DIR}/cli/darwin_amd64 woodpecker-cli tar -cvzf ${DIST_DIR}/woodpecker-cli_darwin_arm64.tar.gz -C ${DIST_DIR}/cli/darwin_arm64 woodpecker-cli tar -cvzf ${DIST_DIR}/woodpecker-cli_freebsd_amd64.tar.gz -C ${DIST_DIR}/cli/freebsd_amd64 woodpecker-cli @@ -430,7 +441,7 @@ docs-dependencies: ## Install docs dependencies .PHONY: generate-docs generate-docs: ## Generate docs (currently only for the cli) - CGO_ENABLED=0 go generate cmd/cli/app.go + CGO_ENABLED=1 GOFLAGS="$(GOFLAGS) -tags=libvirt,libvirt_dlopen" go generate cmd/cli/app.go CGO_ENABLED=0 go generate cmd/server/openapi.go .PHONY: build-docs diff --git a/cli/exec/exec.go b/cli/exec/exec.go index 403242476a2..8c06e9f0337 100644 --- a/cli/exec/exec.go +++ b/cli/exec/exec.go @@ -35,6 +35,7 @@ import ( "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/docker" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/kubernetes" + "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/libvirt" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/local" backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" "go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/builder" @@ -61,6 +62,15 @@ var backends = []backend_types.Backend{ kubernetes.New(), docker.New(), local.New(), + libvirt.New(), +} + +func backendFlags(backends []backend_types.Backend) []cli.Flag { + var all []cli.Flag + for _, b := range backends { + all = append(all, b.Flags()...) + } + return all } func backendFlags(backends []backend_types.Backend) []cli.Flag { diff --git a/cmd/agent/main.go b/cmd/agent/main.go index b14903896cc..eadc2c6a4d8 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -22,6 +22,7 @@ import ( "go.woodpecker-ci.org/woodpecker/v3/cmd/agent/core" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/docker" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/kubernetes" + "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/libvirt" "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/local" backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" "go.woodpecker-ci.org/woodpecker/v3/shared/dot_env" @@ -32,6 +33,7 @@ var backends = []backend_types.Backend{ kubernetes.New(), docker.New(), local.New(), + libvirt.New(), } func main() { diff --git a/docker/Dockerfile.agent.alpine.multiarch b/docker/Dockerfile.agent.alpine.multiarch index 3ca24bd0259..ba36bc67abd 100644 --- a/docker/Dockerfile.agent.alpine.multiarch +++ b/docker/Dockerfile.agent.alpine.multiarch @@ -5,7 +5,7 @@ COPY . . ARG TARGETOS TARGETARCH CI_COMMIT_SHA CI_COMMIT_TAG CI_COMMIT_BRANCH RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg \ - CGO_ENABLED=0 make build-agent + CGO_ENABLED=0 LIBVIRT_ENABLED=false make build-agent FROM docker.io/alpine:3.24 diff --git a/docker/Dockerfile.agent.multiarch b/docker/Dockerfile.agent.multiarch index 1548c2ad206..2f86f67a0dc 100644 --- a/docker/Dockerfile.agent.multiarch +++ b/docker/Dockerfile.agent.multiarch @@ -14,7 +14,7 @@ COPY . . ARG TARGETOS TARGETARCH CI_COMMIT_SHA CI_COMMIT_TAG CI_COMMIT_BRANCH RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg \ - CGO_ENABLED=0 make build-agent + CGO_ENABLED=0 LIBVIRT_ENABLED=false make build-agent FROM scratch AS stage diff --git a/docker/Dockerfile.cli.alpine.multiarch.rootless b/docker/Dockerfile.cli.alpine.multiarch.rootless index 206d2953c5d..0221b2430d7 100644 --- a/docker/Dockerfile.cli.alpine.multiarch.rootless +++ b/docker/Dockerfile.cli.alpine.multiarch.rootless @@ -5,7 +5,7 @@ COPY . . ARG TARGETOS TARGETARCH CI_COMMIT_SHA CI_COMMIT_TAG CI_COMMIT_BRANCH RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg \ - CGO_ENABLED=0 make build-cli + CGO_ENABLED=0 LIBVIRT_ENABLED=false make build-cli FROM docker.io/alpine:3.24 diff --git a/docker/Dockerfile.cli.multiarch.rootless b/docker/Dockerfile.cli.multiarch.rootless index 2286afbc842..94aed5cdf8e 100644 --- a/docker/Dockerfile.cli.multiarch.rootless +++ b/docker/Dockerfile.cli.multiarch.rootless @@ -13,7 +13,7 @@ COPY . . ARG TARGETOS TARGETARCH CI_COMMIT_SHA CI_COMMIT_TAG CI_COMMIT_BRANCH RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/go/pkg \ - CGO_ENABLED=0 make build-cli + CGO_ENABLED=0 LIBVIRT_ENABLED=false make build-cli FROM scratch AS stage diff --git a/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md new file mode 100644 index 00000000000..f58f53d057b --- /dev/null +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -0,0 +1,206 @@ +# Libvirt + +:::warning +Woodpecker comes with experimental support for executing steps within a virtual machine. +::: + +This is achieved by utilizing [libvirt](https://libvirt.org/). + +## Architecture + +Libvirt is an abstraction over different hypervisors. Currently QEMU and bhyve +have been extensively tested. + +In order to fit virtual machines ("domains" in libvirt speak) into a docker-like workflow, +we had to make a couple of choices. Most of these prioritize portability. + +Some methods don't work well on some host platforms or hypervisors, so experience may +vary depending on the setup. + +### Command execution + +Commands are executed over an SSH session and fed into standard input. So there +should be no limitation for script size. Environment variables are injected directly +into the script. We do not rely on SSH's `AcceptEnv` feature. + +### Connecting to the VM + +Connections to the VMs are established via the [libvirt nss](https://libvirt.org/nss.html) +module (libvirt must be compiled with that feature). This maps the domain names to hostnames. + +Alternatively it is possible to specify the name of the guest internal interface on which +SSH is listening. See the [backend options](#backend-options) for more information. + +### Ephemeral execution and shared volumes + +Just like containers, we want the VM state to be gone after a step has finished. This is achieved +by copying the base image of the domain. + +Similarly, a new empty disk is created ad-hoc, formatted, connected to the VM and mounted +at `$CI_WORKSPACE`. +This has the side-effect that two VMs can't access the same disk at the same time without +filesystem corruption, so step parallelization does not work currently. We ensure only one +step is running at a time via mutex locks. + +An alternative to ad-hoc disks would be [virtiofs](https://virtio-fs.gitlab.io/). It has the advantage that we get shared access +to a directory on the host, but the disadvantage that it requires more configuration inside the guest +and is possibly less portable. + +After the workflow is finished, all the copied base images and shared disks are deleted, unless +the agent was started with `--backend-libvirt-keep-tmp`. + +### Domain definitions remain untouched + +Although we manipulate the domain XML to inject a shared disk, change the base image +and so on... none of these changes are persistent. + +## Prerequisites + +These are the requirements for the host that runs the woodpecker agent: + +- hardware that supports virtualization +- libvirt supported operating system +- libvirt C libraries installed +- agent built with cgo enabled (`CGO_ENABLED=1`) +- libvirtd service started and operational (including networking) +- sufficient privileges for the user running the agent to interact with libvirtd and write to the images store (`/var/lib/libvirt/images` by default) +- [libvirt nss](https://libvirt.org/nss.html) set up, so that we can connect to the machine by name + +:::note +The official agent and cli container images are built without the libvirt backend. +Run the agent binary directly on the libvirt host instead. +::: + +## VM creation + +Libvirt has an [ecosystem of tools](https://www.virt-tools.org/). + +To create a VM conveniently you can use [virt-manager's](https://virt-manager.org/) GUI. +It also provides a command line tool called `virt-install`. + +There is also more advanced methods like [cloud-init](https://cloud-init.io/). + +### Configuration for all VM guests + +Regardless of guest, you need an sshd server running, which must be configured to accept +password authentication. + +### Configuration for windows guests + +Make sure the login account is an admin account. It usually needs to be a local account with a password, not a pin. + +```cmd +net localgroup Administrators /add +``` + +OpenSSH server needs to be [installed and started](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse?tabs=gui&pivots=windows-11). + +Then we need some further configuration to allow remote SSH connections. + +Disable UAC remote token filtering: + +```powershell +New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" ` + -Name "LocalAccountTokenFilterPolicy" -Value 1 -PropertyType DWord -Force +``` + +Set your network to private: + +```powershell +Get-NetIPInterface +Set-NetConnectionProfile -InterfaceIndex -NetworkCategory Private +``` + +Start WinRM service: + +```powershell +winrm quickconfig +``` + +We also need to turn off bitlocker disk encryption. Windows 11 can break our shared +volumes by encrypting them without asking. + +```powershell +New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\BitLocker" ` + -Name "PreventDeviceEncryption" -Value 1 -PropertyType DWord -Force +``` + +## Backend options + +```yaml +backend_options: + libvirt: + # Setting this to 'true' will make the changes to the VM + # visible to other steps/workflows and break isolation. + # This can be useful however if VM creation is automated + # in some other way. + persistent: false + # This is optional and should only be used if the backend + # can't figure out how to create and format a disk as the + # shared volume. + shared_disk: + # The UUID is needed for mounting on linux. + # On windows we create a serial number on the fly and use + # that for mounting. + uuid: bd5ea041-e765-4d3a-9cda-083e4e52b187 + # The disk image to use. Must be a filename. Paths + # are ignored. Both qcow2 and raw img are fine. + disk_image: shared.qcow2 + # The SSH configuration. This is required. + ssh_config: + # required + username: root + # Optional. Timeout before giving up on connecting via ssh. If + # your VM needs a long time to start up, you may want to increase this. + # Takes a duration string, such as "2m" for two minutes. + timeout: 1m + # Optional. Only use this if libvirt NSS doesn't work. This + # must be the interface inside the guest on which we can connect to sshd. + interface: eth0 +``` + +The SSH password has to be configured via the environment variable `LIBVIRT_SSH_PW`, +so that we can use the `from_secret` feature. See the [example workflow](#example-workflow). + +## Example workflow + +```yaml +when: + - event: push + - event: manual + +labels: + hypervisor: qemu + +skip_clone: true + +steps: + - name: build + image: win11 + commands: + # install ghcup and msys2 + - Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { & ([ScriptBlock]::Create((Invoke-WebRequest https://raw.githubusercontent.com/haskell/ghcup-hs/refs/heads/no-pty/scripts/bootstrap/bootstrap-haskell.ps1 -UseBasicParsing))) -DisableCurl -Msys2Env CLANG64 -Minimal } catch { Write-Error $_ } + # clone the repository + - C:/ghcup/msys64/usr/bin/bash.exe --login -e -c "ls -lah && pwd && pacman --noconfirm -S --needed --overwrite '*' bash git && git clone ${CI_REPO_CLONE_URL} --branch ${CI_COMMIT_BRANCH} . && ghcup install ghc --set $env:GHC && ghcup install cabal --set $env:CABAL" + # build + - C:/ghcup/msys64/usr/bin/bash.exe --login -e .github/scripts/build.sh --ghc ghc-$env:GHC --verbose --os Windows --check-linking --strip + environment: + GHC: 9.10.3 + CABAL: 3.18.1.0 + CABAL_DIR: 'C:/cabal' + MSYSTEM: CLANG64 + CHERE_INVOKING: 1 + GHCUP_MSYS2_ENV: CLANG64 + GHCUP_INSTALL_BASE_PREFIX: 'C:/' + LIBVIRT_SSH_PW: + from_secret: win11_ssh_pw + backend_options: + libvirt: + ssh_config: + username: maerwald +``` + +## Caveats + +Plugins don't work. They are docker specific. That also means that automatic cloning +doesn't work and we always need `skip_clone: true`. diff --git a/docs/docs/30-administration/10-configuration/30-agent.md b/docs/docs/30-administration/10-configuration/30-agent.md index 12c4fc8fccf..a4098cee4c4 100644 --- a/docs/docs/30-administration/10-configuration/30-agent.md +++ b/docs/docs/30-administration/10-configuration/30-agent.md @@ -303,7 +303,7 @@ If set to 0 we are always blocking. - Name: `WOODPECKER_BACKEND` - Default: `auto-detect` -Configures the backend engine to run pipelines on. Possible values are `auto-detect`, `docker`, `local` or `kubernetes`. +Configures the backend engine to run pipelines on. Possible values are `auto-detect`, `docker`, `local`, `kubernetes` or `libvirt` (experimental). ### BACKEND_DOCKER\_\* @@ -321,6 +321,12 @@ See [Kubernetes backend configuration](./11-backends/20-kubernetes.md#environmen See [Local backend configuration](./11-backends/30-local.md#environment-variables) +--- + +### BACKEND_LIBVIRT\_\* + +See [Libvirt backend configuration](./11-backends/35-libvirt.md) + ### Advanced Settings :::warning diff --git a/flake.nix b/flake.nix index 45585a72acb..c2065ac9977 100644 --- a/flake.nix +++ b/flake.nix @@ -76,6 +76,7 @@ bash nushell powershell + libvirt ]; CFLAGS = "-I${pkgs.glibc.dev}/include"; LDFLAGS = "-L${pkgs.glibc}/lib"; diff --git a/go.mod b/go.mod index 1c6d2019ddf..4ee7090a8e5 100644 --- a/go.mod +++ b/go.mod @@ -8,13 +8,17 @@ require ( codeberg.org/6543/go-yaml2json/v2 v2.0.0 codeberg.org/6543/xyaml/v2 v2.0.1 codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v4 v4.0.1-0.20261121172830-0f7befc6b835 + darvaza.org/x/sync v0.6.1 gitea.dev/sdk v1.5.2 github.com/6543/logfile-open v1.2.1 github.com/adrg/xdg v0.5.3 + github.com/beevik/etree v1.8.1 github.com/bmatcuk/doublestar/v4 v4.10.7 github.com/cenkalti/backoff/v7 v7.0.3 github.com/containerd/errdefs v1.0.0 github.com/distribution/reference v0.6.0 + github.com/djherbis/buffer v1.2.1 + github.com/djherbis/nio/v3 v3.0.1 github.com/docker/cli v29.10.0+incompatible github.com/docker/go-connections v0.8.2 github.com/docker/go-units v0.5.0 @@ -30,11 +34,13 @@ require ( github.com/google/go-github/v93 v93.0.0 github.com/hashicorp/go-hclog v1.6.3 github.com/hashicorp/go-plugin v1.8.0 + github.com/jakobii/syncx v0.3.0 github.com/jellydator/ttlcache/v3 v3.4.1 github.com/joho/godotenv v1.5.1 github.com/kinbiko/jsonassert v1.2.0 github.com/lib/pq v1.12.3 github.com/mattn/go-sqlite3 v1.14.53 + github.com/melbahja/goph v1.5.2 github.com/migueleliasweb/go-github-mock v1.5.0 github.com/moby/moby/api v1.57.0 github.com/moby/moby/client v0.6.3 @@ -57,6 +63,7 @@ require ( gitlab.com/gitlab-org/api/client-go/v3 v3.56.0 go.uber.org/multierr v1.11.0 go.yaml.in/yaml/v4 v4.0.0 + golang.org/x/crypto v0.59.0 golang.org/x/image v0.48.0 golang.org/x/net v0.63.0 golang.org/x/oauth2 v0.38.0 @@ -69,6 +76,8 @@ require ( k8s.io/api v0.37.2 k8s.io/apimachinery v0.37.2 k8s.io/client-go v0.37.2 + libvirt.org/go/libvirt v1.12009.0 + libvirt.org/go/libvirtxml v1.12008.0 sigs.k8s.io/yaml v1.6.0 src.techknowlogick.com/xormigrate v1.8.0 xorm.io/builder v0.3.13 @@ -80,6 +89,7 @@ require ( charm.land/bubbletea/v2 v2.0.2 // indirect charm.land/lipgloss/v2 v2.0.1 // indirect codeberg.org/6543/xyaml v1.1.0 // indirect + darvaza.org/core v0.23.1 // indirect filippo.io/edwards25519 v1.2.0 // indirect github.com/42wim/httpsig v1.3.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect @@ -159,6 +169,7 @@ require ( github.com/json-iterator/go v1.1.12 // indirect github.com/julienschmidt/httprouter v1.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/kr/fs v0.1.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/lestrrat-go/dsig v1.4.0 // indirect @@ -180,6 +191,8 @@ require ( github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/sftp v1.13.11 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.0 // indirect @@ -211,7 +224,6 @@ require ( go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.6 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.59.0 // indirect golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 // indirect golang.org/x/mod v0.42.0 // indirect golang.org/x/sys v0.50.0 // indirect diff --git a/go.sum b/go.sum index 4c3fc24f927..077df19c5ce 100644 --- a/go.sum +++ b/go.sum @@ -16,6 +16,10 @@ codeberg.org/6543/xyaml/v2 v2.0.1 h1:GIkCLqf8TeUHjRqTbhCOGAmc8pzCuAFr4lWgLV+HgPc codeberg.org/6543/xyaml/v2 v2.0.1/go.mod h1:OiVkoPEUSJK4xUub8OuQvdnJM9SpM74oGxpGB045JVI= codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v4 v4.0.1-0.20261121172830-0f7befc6b835 h1:cQ8ztfth5tHfX3ULQ088LWAXfegI8BdWJhpn0GWwI4U= codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v4 v4.0.1-0.20261121172830-0f7befc6b835/go.mod h1:I0xTPH+VvZqcizH+kFM2Y7eGM/QGb6ibOlTfSBLGXjE= +darvaza.org/core v0.23.1 h1:0g/tgwZDXvJjNzAEWDmZPQl28sFiOGQ71dZVyhCsi7c= +darvaza.org/core v0.23.1/go.mod h1:J4e8C8EAiASH13I24EBzxlyuL5MbLJGmJFdUe4slLng= +darvaza.org/x/sync v0.6.1 h1:E8OjNOG6gCnmPFqk83b67lD14KehNnnHT5d+dA6hQOM= +darvaza.org/x/sync v0.6.1/go.mod h1:28nyxb83vcmSmlCBH+/tCqBSyDjCkt39CJBoIlhOP6c= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGqTOXqu2aRi/XEQxDCBwM8yJtE6s= @@ -42,6 +46,8 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= +github.com/beevik/etree v1.8.1 h1:MchsAnqPGCGsfQezhwcouHPlAHlcAOqWpyCVZoyWfjU= +github.com/beevik/etree v1.8.1/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmatcuk/doublestar/v4 v4.10.7 h1:zcFCzVP2tosKRCXLXISX2dQ9YWXAvB3u7bhc1CDLc64= @@ -112,6 +118,11 @@ github.com/denisenkom/go-mssqldb v0.12.3 h1:pBSGx9Tq67pBOTLmxNuirNTeB8Vjmf886Kx+ github.com/denisenkom/go-mssqldb v0.12.3/go.mod h1:k0mtMFOnU+AihqFxPMiF05rtiDrorD1Vrm1KEz5hxDo= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/djherbis/buffer v1.1.0/go.mod h1:VwN8VdFkMY0DCALdY8o00d3IZ6Amz/UNVMWcSaJT44o= +github.com/djherbis/buffer v1.2.1 h1:BCpd2M1ge0HbGwm8rM1obeRsONseQvSHvi76qeBv8WA= +github.com/djherbis/buffer v1.2.1/go.mod h1:fjnebbZjCUpPinBRD+TDwXSOeNQ7fPQWLfGQqiAiUyE= +github.com/djherbis/nio/v3 v3.0.1 h1:6wxhnuppteMa6RHA4L81Dq7ThkZH8SwnDzXDYy95vB4= +github.com/djherbis/nio/v3 v3.0.1/go.mod h1:Ng4h80pbZFMla1yKzm61cF0tqqilXZYrogmWgZxOcmg= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docker/cli v29.10.0+incompatible h1:lCL+clBUJnHsmjBCr6TwvfQFkmBidPxi5SkuXCoYxc0= @@ -276,6 +287,8 @@ github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09 github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jakobii/syncx v0.3.0 h1:MfqxrRlWI/ukuFMfn0FzvuD9lFT/gndtV2rKNN6AvN4= +github.com/jakobii/syncx v0.3.0/go.mod h1:/URnyzHSfMwBIPShV5biirGuRo5SrdHsU2zPq2bxMYs= github.com/jellydator/ttlcache/v3 v3.4.1 h1:bOdXmXiycyK6E6Qjyuj5vl+/vU3SCOoDs8a86NbHjAQ= github.com/jellydator/ttlcache/v3 v3.4.1/go.mod h1:j7LO12PNghFg5+0v9budMAT4rDK4JY969jb9vOdOBBk= github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94= @@ -294,6 +307,8 @@ github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLM github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -324,6 +339,8 @@ github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjc github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/mattn/go-sqlite3 v1.14.53 h1:mnTM0owzUMrKuLo+0w51NUiB0ir2Fo7kFXlPt/l3BGs= github.com/mattn/go-sqlite3 v1.14.53/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= +github.com/melbahja/goph v1.5.2 h1:2eoR45SLF3LyM6tnIhnpjakvXTjtQMJqOK/mp1PYojM= +github.com/melbahja/goph v1.5.2/go.mod h1:T+5uoB1PDP6EeK2qXerf5gRh7b6IF8u37GK2ckEi9FU= github.com/migueleliasweb/go-github-mock v1.5.0 h1:dIr6vgVz8QY9sDiDopWxk6pDw4d7K/xIcCk/NQe4ajM= github.com/migueleliasweb/go-github-mock v1.5.0/go.mod h1:/DUmhXkxrgVlDOVBqGoUXkV4w0ms5n1jDQHotYm135o= github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= @@ -375,6 +392,10 @@ github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgr github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE= +github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -621,6 +642,10 @@ k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3d k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +libvirt.org/go/libvirt v1.12009.0 h1:Y1snMW/TDVrFmHjz4bchNkVs8LtlzSBq0h7JhynrfV4= +libvirt.org/go/libvirt v1.12009.0/go.mod h1:1WiFE8EjZfq+FCVog+rvr1yatKbKZ9FaFMZgEqxEJqQ= +libvirt.org/go/libvirtxml v1.12008.0 h1:lxE2sL6vTrEeox76TWwAO3XCelA7QxptNf2hpPO+Ubw= +libvirt.org/go/libvirtxml v1.12008.0/go.mod h1:7Oq2BLDstLr/XtoQD8Fr3mfDNrzlI3utYKySXF2xkng= lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw= diff --git a/pipeline/backend/libvirt/backend_options.go b/pipeline/backend/libvirt/backend_options.go new file mode 100644 index 00000000000..36794bd17fa --- /dev/null +++ b/pipeline/backend/libvirt/backend_options.go @@ -0,0 +1,51 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "github.com/go-viper/mapstructure/v2" + + backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" +) + +// BackendOptions defines all the advanced options for the libvirt backend. +type BackendOptions struct { + SSHConfig SSHConfig `mapstructure:"ssh_config"` + SharedDisk SharedDisk `mapstructure:"shared_disk"` + Persistent bool `mapstructure:"persistent"` +} + +type SSHConfig struct { + User string `mapstructure:"username"` + GuestInterface string `mapstructure:"guest_interface"` + // takes a duration string, such as "2m" + Timeout string `mapstructure:"timeout"` +} + +type SharedDisk struct { + Disk string `mapstructure:"disk"` + UUID string `mapstructure:"uuid"` +} + +func parseBackendOptions(step *backend_types.Step) (BackendOptions, error) { + var result BackendOptions + if step == nil || step.BackendOptions == nil { + return result, nil + } + err := mapstructure.WeakDecode(step.BackendOptions[EngineName], &result) + return result, err +} diff --git a/pipeline/backend/libvirt/disk.go b/pipeline/backend/libvirt/disk.go new file mode 100644 index 00000000000..88e826c5a32 --- /dev/null +++ b/pipeline/backend/libvirt/disk.go @@ -0,0 +1,296 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "context" + "encoding/csv" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/rs/zerolog/log" +) + +func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS, domainType, diskSize, taskUUID string) (string, string, error) { + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + + var diskUUID string + var fstype string + if guestOS == "windows" { + fstype = "ntfs" + } else { // TODO: UFS for BSD? + fstype = "ext4" + } + + // create a disk from scratch based on the domain type + // kvm and qemu support qcow2, for everything else we use raw image + if (domainType == "kvm" || domainType == "qemu") && hasCommand("guestfish") && hasCommand("qemu-img") { // qemu with libguest stuff + disk := fmt.Sprintf("%s/shared_%s.qcow2", libvirtImgDir, taskUUID) + // create qcow2 image + + _, err := os.Stat(disk) + if err != nil { + // create the disk + { + cmd := exec.Command("qemu-img", "create", "-f", "qcow2", disk, diskSize) + log.Debug().Msgf("Create shared disk: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return "", "", cmdError(cmd, err) + } + } + + // Format the disk. + // On redhat systems, this will fail on 'ntfs', because they do not support ntfs inside libguest. + // On other systems, this may work if the host has the appropriate tools. + // May need 'libguestfs-winsupport' installed. + { + var cmd *exec.Cmd + if fstype == "ntfs" { + cmd = exec.Command( + "guestfish", "-a", disk, "--", "run", ":", + "part-init", "/dev/sda", "mbr", ":", // initialize MBR + "part-add", "/dev/sda", "p", "2048", "-1", ":", // create primary partition + "part-set-mbr-id", "/dev/sda", "1", "0x07", ":", // sets NTFS type + "mkfs", "ntfs", "/dev/sda1", // format NTFS + ) + } else { + cmd = exec.Command( + "guestfish", "-a", disk, "--", "run", ":", + "mkfs", fstype, "/dev/sda", // format + ) + } + log.Debug().Msgf("Format disk: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return "", "", cmdError(cmd, err) + } + } + } + + // get uuid + diskUUID, err = GetQemuDiskUUID(disk) + if err != nil { + return "", "", err + } + + return disk, diskUUID, nil + } else { // raw images (basic qemu without libguest, e.g. bhyve, etc.) + // this only works on a linux host! + if e.os != "linux" { + return "", "", fmt.Errorf("cannot automatically create raw disk images on %s. Either use a linux host or define 'disk' in the backend options", e.os) + } + + disk := fmt.Sprintf("%s/shared_%s.raw", libvirtImgDir, taskUUID) + var loopDev []byte + + _, statErr := os.Stat(disk) + if statErr != nil { + // create disk + { + cmd := exec.Command("truncate", "-s", diskSize, disk) + log.Debug().Msgf("Create shared disk: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return "", "", cmdError(cmd, err) + } + } + } + + // mount loop device + { + var err error + loopDev, err = MountLoopDev(disk) + if err != nil { + return "", "", err + } + } + + if statErr != nil { + // format + // TODO: this probably doesn't work for NTFS + { + cmd := CmdViaSudo(fmt.Sprintf("mkfs.%s", fstype), "-E", "lazy_itable_init=1,lazy_journal_init=1", string(loopDev)) + log.Debug().Msgf("Format device: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return "", "", cmdError(cmd, err) + } + } + } + + // Get disk UUID + { + var err error + diskUUID, err = GetBhyveDiskUUIDLoop(loopDev) + if err != nil { + return "", "", err + } + } + + // detach loop device + { + err := UnmountLoopDev(loopDev) + if err != nil { + return "", "", err + } + } + + return disk, diskUUID, nil + } +} + +func (e *libvirt) FromBaseImage(ctx context.Context, baseImage, targetImg string, overwrite bool) (string, error) { + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + libvirtImg := filepath.Join(libvirtImgDir, targetImg) + + if !overwrite { + _, err := os.Stat(libvirtImg) + if err == nil { + return libvirtImg, nil + } + } + + log.Debug().Msgf("Copying base image %s to %s ", baseImage, libvirtImg) + + if filepath.Ext(baseImage) == ".qcow2" { + cmd := exec.Command("qemu-img", "create", "-o", "backing_fmt=qcow2", "-b", baseImage, "-f", "qcow2", libvirtImg) + _, err := cmd.Output() + if err != nil { + log.Debug().Msgf("Error copying base image %s via qemu-img...falling back to manual copy", cmdError(cmd, err)) + err := CopyFile(baseImage, libvirtImg, false) + if err != nil { + return "", err + } + } + } else { // TODO: maybe other formats can be efficiently copied too? + err := CopyFile(baseImage, libvirtImg, false) + if err != nil { + return "", err + } + } + + return libvirtImg, nil +} + +func GetQemuDiskUUID(disk string) (diskUUID string, err error) { + cmd := exec.Command("virt-filesystems", "--long", "--csv", "-a", disk, "--uuid") + log.Debug().Msgf("Get UUID: %s", cmd.Args) + bytes, err := cmd.Output() + if err != nil { + return "", cmdError(cmd, err) + } + + r := csv.NewReader(strings.NewReader(string(bytes))) + header, err := r.Read() + if err != nil { + return "", fmt.Errorf("failed parsing CVS output for UUID: %w", err) + } + i := -1 + for ix, e := range header { + if e == "UUID" { + i = ix + } + } + + if i == -1 { + return "", fmt.Errorf("could not find UUID in: %s", header) + } + + data, err := r.Read() + if err != nil { + return "", fmt.Errorf("failed parsing CVS output for UUID: %w", err) + } + diskUUID = data[i] + + return diskUUID, nil +} + +func GetBhyveDiskUUIDLoop(loopDev []byte) (diskUUID string, err error) { + cmd := CmdViaSudo("blkid", "-o", "value", "--match-tag", "UUID", string(loopDev)) + log.Debug().Msgf("Get UUID: %s", cmd.Args) + bytes, err := cmd.Output() + if err != nil { + return "", cmdError(cmd, err) + } + + diskUUID = string(bytes) + + return diskUUID, nil +} + +func GetBhyveDiskUUID(disk string) (diskUUID string, err error) { + var loopDev []byte + // mount loop device + { + var err error + loopDev, err = MountLoopDev(disk) + if err != nil { + return "", err + } + } + + // Get disk UUID + { + var err error + diskUUID, err = GetBhyveDiskUUIDLoop(loopDev) + if err != nil { + return "", err + } + } + + // detach loop device + { + err = UnmountLoopDev(loopDev) + if err != nil { + return "", err + } + } + + return diskUUID, nil +} + +func MountLoopDev(disk string) ([]byte, error) { + cmd := CmdViaSudo("losetup", "--find", "--show", disk) + log.Debug().Msgf("Mount loop device: %s", cmd.Args) + out, err := cmd.Output() + if err != nil { + return nil, cmdError(cmd, err) + } + return out, nil +} + +func UnmountLoopDev(loopDev []byte) error { + cmd := CmdViaSudo("losetup", "--detach", string(loopDev)) + log.Debug().Msgf("Detach loop device: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return cmdError(cmd, err) + } + return nil +} + +func GetDiskUUID(disk, domainType string) (diskUUID string, err error) { + if (domainType == "kvm" || domainType == "qemu") && hasCommand("guestfish") && hasCommand("qemu-img") { // qemu with libguest stuff + return GetQemuDiskUUID(disk) + } else { + return GetBhyveDiskUUID(disk) + } +} diff --git a/pipeline/backend/libvirt/domain.go b/pipeline/backend/libvirt/domain.go new file mode 100644 index 00000000000..7c73fb13e76 --- /dev/null +++ b/pipeline/backend/libvirt/domain.go @@ -0,0 +1,446 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "context" + "encoding/xml" + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/beevik/etree" + "github.com/cenkalti/backoff/v7" + "github.com/rs/zerolog/log" + virt "libvirt.org/go/libvirt" + "libvirt.org/go/libvirtxml" + + pipeline_errors "go.woodpecker-ci.org/woodpecker/v3/pipeline/errors" +) + +func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]string, persistent bool, sharedDisk SharedDisk, taskUUID, stepUUID string) (outDomain *virt.Domain, newName, guestOS, uuid string, err error) { + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + domain, err := e.conn.LookupDomainByName(image) + if err != nil { + return nil, "", "", "", err + } + + // free the looked up domain, not the one created below + defer func(d *virt.Domain) { _ = d.Free() }(domain) + + guestOS, err = getGuestOS(domain) + if err != nil { + return nil, "", "", "", err + } + + // get the XML from the loaded domain + domXML, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) + if err != nil { + return nil, "", "", "", err + } + + domcfg := &libvirtxml.Domain{} + { + err := domcfg.Unmarshal(domXML) + if err != nil { + return nil, "", "", "", err + } + } + newName = fmt.Sprintf("%s-%s", image, stepUUID) + domcfg.Name = newName + domcfg.UUID = "" + + if domcfg.Devices == nil { + return nil, "", "", "", fmt.Errorf("no devices in domain") + } + + if !persistent { + log.Debug().Msgf("Setting up ephemeral disks") + // replacing all the disks with temporary ones + for ix, disk := range domcfg.Devices.Disks { + if disk.Target == nil { + continue + } + // get target to disambiguate + dev := disk.Target.Dev + + if disk.Source == nil || disk.Source.File == nil { + continue + } + // get source to disambiguate + file := disk.Source.File.File + + baseImgName := fmt.Sprintf(baseImagePattern, dev, taskUUID, stepUUID, filepath.Ext(file)) + newImg, err := e.FromBaseImage(ctx, file, baseImgName, false) + if err != nil { + return nil, "", "", "", err + } + + disk.Source.File.File = newImg + domcfg.Devices.Disks[ix].Source.File.File = newImg + } + + // replacing nvram, if any + if domcfg.OS != nil && domcfg.OS.NVRam != nil { + nvramDest := filepath.Join(libvirtImgDir, fmt.Sprintf(nvramImagePattern, taskUUID, stepUUID)) + err := CopyFile(domcfg.OS.NVRam.NVRam, nvramDest, false) + if err != nil { + return nil, "", "", "", err + } + domcfg.OS.NVRam.NVRam = nvramDest + } + + // generate random network macs + for ix, interf := range domcfg.Devices.Interfaces { + if interf.MAC != nil { + rmac, err := GenerateRandomMACAddress() + if err != nil { + return nil, "", "", "", err + } + domcfg.Devices.Interfaces[ix].MAC.Address = rmac + } + } + } + + domainType, err := GetDomainType(ctx, domain) + if err != nil { + return nil, "", "", "", err + } + + var disk string + var diskUUID string + + // insert the shared disk if any + if sharedDisk.Disk != "" { + // absolute paths will be ignored + _, diskFile := filepath.Split(sharedDisk.Disk) + diskPath := filepath.Join(libvirtImgDir, diskFile) + + disk, err = e.FromBaseImage(ctx, diskPath, fmt.Sprintf(sharedDiskPattern, taskUUID, filepath.Ext(sharedDisk.Disk)), false) + if err != nil { + return nil, "", "", "", err + } + + log.Debug().Msgf("Inserting shared disk: %s", sharedDisk.Disk) + + if sharedDisk.UUID != "" { + diskUUID = sharedDisk.UUID + } + } else { // in absence of a config, create a disk from scratch (ntfs for windows, ext4 otherwise) + diskSize, ok := env["LIBVIRT_DISK_SIZE"] + if !ok { + diskSize = "10G" + } + + disk, diskUUID, err = e.CreateSharedDisk(ctx, guestOS, domainType, diskSize, taskUUID) + if err != nil { + return nil, "", "", "", err + } + } + + // 20 is the max amount of chars allowed for the serial number + // on windows, so we just limit to that + serial := stepUUID[:20] + + // now cook up the domain config for the shared disk + var domainDisk libvirtxml.DomainDisk + zero := uint(0) + { + // It's better to attach the shared disk to an existing SATA controller + // otherwise the topology might change and cause boot loader issues (e.g. on mac). + // If we can't find one, we just omit it and libvirt will create one. + var firstSata *libvirtxml.DomainController + // get the first sata controller with the lowest index + for _, controller := range domcfg.Devices.Controllers { + if controller.Type == "sata" { + if firstSata == nil { + firstSata = &controller + } else if *firstSata.Index > *controller.Index { + firstSata = &controller + } + } + } + // find a free unit + var units []uint + for _, disk := range domcfg.Devices.Disks { + if disk.Address != nil && disk.Address.Drive != nil && disk.Address.Drive.Unit != nil { + if firstSata != nil && *disk.Address.Drive.Controller == *firstSata.Index { + units = append(units, *disk.Address.Drive.Unit) + } + } + } + var freeUnit uint + if len(units) > 0 { + freeUnit = slices.Max(units) + 1 + } + + if domainType == "kvm" || domainType == "qemu" { + domainDisk = libvirtxml.DomainDisk{ + XMLName: xml.Name{Local: "disk"}, + Device: "disk", + Driver: &libvirtxml.DomainDiskDriver{ + Name: "qemu", + Type: "qcow2", + }, + Source: &libvirtxml.DomainDiskSource{ + File: &libvirtxml.DomainDiskSourceFile{ + File: disk, + }, + }, + Target: &libvirtxml.DomainDiskTarget{ + Dev: "sdz", + Bus: "sata", + }, + Serial: serial, + } + } else { + domainDisk = libvirtxml.DomainDisk{ + XMLName: xml.Name{Local: "disk"}, + Device: "disk", + Driver: &libvirtxml.DomainDiskDriver{ + Name: "file", + Type: "raw", + }, + Source: &libvirtxml.DomainDiskSource{ + File: &libvirtxml.DomainDiskSourceFile{ + File: disk, + }, + }, + Target: &libvirtxml.DomainDiskTarget{ + Dev: "sdz", + Bus: "sata", + }, + Serial: serial, + } + } + + if firstSata != nil { + domainDisk.Address = &libvirtxml.DomainAddress{ + Drive: &libvirtxml.DomainAddressDrive{ + Controller: firstSata.Index, + Bus: &zero, + Target: &zero, + Unit: &freeUnit, + }, + } + } + } + + // on windows we mount via the serial, which is stepUUID + if guestOS == "windows" { + uuid = serial + } else { + // if we don't have a disk UUID by now, get it explicitly + if diskUUID == "" { + diskUUID, err = GetDiskUUID(disk, domainType) + if err != nil { + return nil, "", "", "", err + } + } + + // on unix we mount via the disk uuid, which we must discover + uuid = diskUUID + } + + // insert + domcfg.Devices.Disks = append(domcfg.Devices.Disks, domainDisk) + + newXMLdoc, err := domcfg.Marshal() + if err != nil { + return nil, "", "", "", err + } + + domain, err = e.conn.DomainCreateXML(newXMLdoc, virt.DOMAIN_NONE) + + return domain, newName, uuid, guestOS, err +} + +// Get the ip address we can SSH connect to. +func GetDomainIP(ctx context.Context, domain *virt.Domain, interfaceName string) (*virt.DomainIPAddress, error) { + var interfaces []virt.DomainInterface + var err error + + // DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT requires qemu-guest-agent + interfaces, err = domain.ListAllInterfaceAddresses(virt.DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT) + if err != nil { + log.Debug().Msgf("Failed to retrieve network interfaces via qemu-agent: %s", err.Error()) + // use lease as fallback + interfaces, err = domain.ListAllInterfaceAddresses(virt.DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE) + if err != nil { + return nil, err + } + } + for _, interFace := range interfaces { + log.Debug().Msgf("Checking interface %s ", interFace.Name) + if interFace.Name == interfaceName { + for _, address := range interFace.Addrs { + log.Debug().Msgf("Checking address %s ", address.Addr) + if address.Type == virt.IP_ADDR_TYPE_IPV4 { + return &address, nil + } + } + } + } + + return nil, &pipeline_errors.PipelineError{ + Message: fmt.Sprintf("Could not find an IPv4 address for the interface %s to connect via ssh to", interfaceName), + Type: pipeline_errors.PipelineErrorTypeGeneric, + } +} + +// Shut down the domain and free the pointer on success. +func ShutdownVM(ctx context.Context, domain *virt.Domain) error { + { + err := domain.Shutdown() + if err != nil { + return err + } + } + + // wait 2 minutes for clean shutdown + // otherwise force via 'Destroy()' + maxBackOff, _ := time.ParseDuration("45s") + log.Debug().Msgf("Checking if domain has shutdown for %.1f minutes", maxBackOff.Minutes()) + _, err := backoff.Retry(ctx, func() (any, error) { + info, err := domain.GetInfo() + if err != nil { + // sometimes we race and the domain is shut down already + if lverr, ok := errors.AsType[virt.Error](err); ok && lverr.Code == virt.ERR_NO_DOMAIN { + return nil, nil + } else { + return nil, err + } + } + switch info.State { + case virt.DOMAIN_RUNNING: + return nil, fmt.Errorf("VM still running, retrying") + case virt.DOMAIN_SHUTDOWN: + return nil, fmt.Errorf("VM is being shutdown, retrying") + case virt.DOMAIN_SHUTOFF: + return nil, nil + default: + return nil, backoff.Permanent(fmt.Errorf("unexpected state: %d", info.State)) + } + }, backoff.WithMaxElapsedTime(maxBackOff)) + if err != nil { + log.Debug().Msgf("Could not shut down domain gracefully... destroying cold. Error was: %s", err.Error()) + err := domain.Destroy() + if err != nil { + return err + } + } + + _ = domain.Free() + + return nil +} + +func getGuestOS(domain *virt.Domain) (string, error) { + // does not work on all hypervisors + guestInfo, err := domain.GetGuestInfo(virt.DOMAIN_GUEST_INFO_OS, 0) + if err != nil { + // read the XML metadata, which sometimes carries libosinfo stuff + domXML, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) + if err != nil { + return "", err + } + + // parse the XML into etree + doc := etree.NewDocument() + if err := doc.ReadFromString(domXML); err != nil { + return "", err + } + + // TODO: there should be a library parsing this properly + el := doc.FindElement("/domain/metadata/libosinfo:libosinfo/libosinfo:os") + if el == nil { + return "", fmt.Errorf("could not determine guest platform, add libosinfo metadata to the domain") + } + fileAttr := el.SelectAttr("id") + if fileAttr == nil { + return "", fmt.Errorf("could not determine guest platform, add libosinfo metadata to the domain") + } + switch { + case strings.Contains(fileAttr.Value, "/win/"): + return "windows", nil + case strings.Contains(fileAttr.Value, "linux"): + return "linux", nil + case strings.Contains(fileAttr.Value, "ubuntu"): + return "linux", nil + case strings.Contains(fileAttr.Value, "suse"): + return "linux", nil + case strings.Contains(fileAttr.Value, "slackware"): + return "linux", nil + case strings.Contains(fileAttr.Value, "fedora"): + return "linux", nil + case strings.Contains(fileAttr.Value, "redhat"): + return "linux", nil + case strings.Contains(fileAttr.Value, "popos"): + return "linux", nil + case strings.Contains(fileAttr.Value, "oracle"): + return "linux", nil + case strings.Contains(fileAttr.Value, "nixos"): + return "linux", nil + case strings.Contains(fileAttr.Value, "guix"): + return "linux", nil + case strings.Contains(fileAttr.Value, "mandriva"): + return "linux", nil + case strings.Contains(fileAttr.Value, "mageia"): + return "linux", nil + case strings.Contains(fileAttr.Value, "gentoo"): + return "linux", nil + case strings.Contains(fileAttr.Value, "debian"): + return "linux", nil + case strings.Contains(fileAttr.Value, "centos"): + return "linux", nil + case strings.Contains(fileAttr.Value, "apple"): + return "darwin", nil + case strings.Contains(fileAttr.Value, "openbsd"): + return "openbsd", nil + case strings.Contains(fileAttr.Value, "freebsd"): + return "freebsd", nil + case strings.Contains(fileAttr.Value, "netbsd"): + return "netbsd", nil + case strings.Contains(fileAttr.Value, "dragonflybsd"): + return "dragonflybsd", nil + default: + return "", fmt.Errorf("could not determine guest platform, add libosinfo metadata to the domain") + } + } else { + // TODO: what does 'ID' return? + return guestInfo.OS.ID, nil + } +} + +func GetDomainType(ctx context.Context, domain *virt.Domain) (string, error) { + domXML, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) + if err != nil { + return "", err + } + domcfg := &libvirtxml.Domain{} + { + err := domcfg.Unmarshal(domXML) + if err != nil { + return "", err + } + } + + return domcfg.Type, nil +} diff --git a/pipeline/backend/libvirt/flags.go b/pipeline/backend/libvirt/flags.go new file mode 100644 index 00000000000..352a5f88941 --- /dev/null +++ b/pipeline/backend/libvirt/flags.go @@ -0,0 +1,42 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "github.com/urfave/cli/v3" +) + +var Flags = []cli.Flag{ + &cli.StringFlag{ + Name: "backend-libvirt-uri", + Sources: cli.EnvVars("WOODPECKER_BACKEND_LIBVIRT_URI", "LIBVIRT_URI"), + Usage: "Connection URI", + Value: "qemu:///system", + }, + &cli.StringFlag{ + Name: "backend-libvirt-image-dir", + Sources: cli.EnvVars("WOODPECKER_BACKEND_LIBVIRT_IMG_DIR"), + Usage: "Directory in which libvirt disk images will be created in", + Value: "/var/lib/libvirt/images/", + }, + &cli.BoolFlag{ + Name: "backend-libvirt-keep-tmp", + Sources: cli.EnvVars("WOODPECKER_BACKEND_LIBVIRT_KEEP_TMP"), + Usage: "Whether to keep temporary VM images", + Value: false, + }, +} diff --git a/pipeline/backend/libvirt/libvirt.go b/pipeline/backend/libvirt/libvirt.go new file mode 100644 index 00000000000..17a7ed5a387 --- /dev/null +++ b/pipeline/backend/libvirt/libvirt.go @@ -0,0 +1,664 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sync" + "time" + + "darvaza.org/x/sync/mutex" + "github.com/cenkalti/backoff/v7" + "github.com/djherbis/buffer" + "github.com/djherbis/nio/v3" + "github.com/jakobii/syncx" + "github.com/melbahja/goph" + "github.com/rs/zerolog/log" + "github.com/urfave/cli/v3" + "golang.org/x/crypto/ssh" + "golang.org/x/text/encoding/unicode" + virt "libvirt.org/go/libvirt" + + backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" +) + +var ( + ErrUnsupportedStepType = errors.New("unsupported step type") + ErrUnsupportedCloning = errors.New("automatic cloning is not supported in libvirt, set 'skip_clone: true'") +) + +type libvirt struct { + conn *virt.Connect + commands sync.Map + domains sync.Map + pipesStdOut sync.Map + doneChannel sync.Map + guestOS sync.Map + stepLock syncx.Mutex + c *cli.Command + os, arch string +} + +type pipes struct { + pr *nio.PipeReader + pw *nio.PipeWriter +} + +const ( + EngineName = "libvirt" + baseImagePattern = "base_%s_%s_%s%s" + nvramImagePattern = "nvram_%s_%s" + sharedDiskPattern = "shared_%s%s" + defaultMaxTimeout = "2m" + defaultGuestInterface = "eth0" + sshPort = 22 + logBufferSize = 1024 * 1024 +) + +func New() backend_types.Backend { + return &libvirt{ + conn: nil, + commands: sync.Map{}, + domains: sync.Map{}, + pipesStdOut: sync.Map{}, + doneChannel: sync.Map{}, + guestOS: sync.Map{}, + stepLock: syncx.Mutex{}, + c: nil, + os: runtime.GOOS, + arch: runtime.GOARCH, + } +} + +func (e *libvirt) Name() string { + return EngineName +} + +func ConnectToLibvirt(ctx context.Context) (*virt.Connect, error) { + c, ok := ctx.Value(backend_types.CliCommand).(*cli.Command) + if !ok { + return nil, backend_types.ErrNoCliContextFound + } + libvirtURI := c.String("backend-libvirt-uri") + + conn, err := virt.NewConnect(libvirtURI) + if err != nil { + return nil, fmt.Errorf("libvirt backend is unavailable: %w", err) + } + return conn, nil +} + +// it's hard to figure out just the socket, so we attempt +// a basic connection and close it immediately. +func (e *libvirt) IsAvailable(ctx context.Context) bool { + conn, err := ConnectToLibvirt(ctx) + if err != nil { + return false + } else { + conn.Close() + return true + } +} + +func (e *libvirt) Flags() []cli.Flag { + return Flags +} + +func (e *libvirt) Load(ctx context.Context) (*backend_types.BackendInfo, error) { + c, ok := ctx.Value(backend_types.CliCommand).(*cli.Command) + if !ok { + return nil, backend_types.ErrNoCliContextFound + } + e.c = c + + conn, err := ConnectToLibvirt(ctx) + if err != nil { + return nil, err + } + e.conn = conn + + return &backend_types.BackendInfo{ + Platform: e.os + "/" + e.arch, + }, nil +} + +func (e *libvirt) SetupWorkflow(ctx context.Context, conf *backend_types.Config, taskUUID string) error { + return nil +} + +func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskUUID string) (retErr error) { + switch step.Type { + case backend_types.StepTypeClone: + return ErrUnsupportedCloning + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: + return ErrUnsupportedStepType + default: + return ErrUnsupportedStepType + } + + log.Debug().Msgf("Step %s is waiting for lock", step.Name) + + ok, err := mutex.SafeLockContext(ctx, &e.stepLock) + if !ok { + log.Debug().Msgf("Failed to acquire lock: %s", err.Error()) + return err + } + log.Debug().Msgf("Step %s acquired lock", step.Name) + + defer func() { + if retErr != nil { + e.unlockStep() + } + }() + + options, err := parseBackendOptions(step) + if err != nil { + log.Error().Err(err).Msg("could not parse backend options") + } + + domain, domainName, uuid, guestOS, err := e.LoadDomain(ctx, step.Image, step.Environment, options.Persistent, options.SharedDisk, taskUUID, step.UUID) + if err != nil { + return err + } + + e.domains.Store(step.UUID, domain) + e.guestOS.Store(step.UUID, guestOS) + + scriptIn, entry, err := GenerateSSHConf(step, guestOS) + if err != nil { + return err + } + cmd := entry[0] + args := entry[1:] + + // get the timeout duration for SSH + var maxBackOff time.Duration + if options.SSHConfig.Timeout != "" { + maxBackOff, err = time.ParseDuration(options.SSHConfig.Timeout) + if err != nil { + return err + } + } else { + // default + maxBackOff, _ = time.ParseDuration(defaultMaxTimeout) + } + + var sshAddr string + + if options.SSHConfig.GuestInterface != "" { + // Inspect the guest interface for the IP + ip, err := backoff.Retry(ctx, func() (*virt.DomainIPAddress, error) { + ip, err := GetDomainIP(ctx, domain, options.SSHConfig.GuestInterface) + if err != nil { + log.Debug().Msg("Retrying...") + return nil, err + } + return ip, nil + }, backoff.WithMaxElapsedTime(maxBackOff)) + if err != nil { + return err + } + sshAddr = ip.Addr + } else { + // we rely on libvirt NSS module + sshAddr = domainName + } + + sshPw, ok := step.Environment["LIBVIRT_SSH_PW"] + if !ok { + return errors.New("no SSH password set for libvirt guest, set LIBVIRT_SSH_PW via a secret") + } + + log.Debug().Msgf("Connecting to %s as user %s", sshAddr, options.SSHConfig.User) + client, err := backoff.Retry(ctx, func() (*goph.Client, error) { + return goph.NewConn(&goph.Config{ + User: options.SSHConfig.User, + Auth: goph.Password(sshPw), + Addr: sshAddr, + Port: sshPort, + Timeout: goph.DefaultTimeout, + Callback: ssh.InsecureIgnoreHostKey(), + }) + }, backoff.WithMaxElapsedTime(maxBackOff)) + if err != nil { + return err + } + + // mount the volume + switch guestOS { + case "windows": + encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() + cmd := "powershell" + exec := fmt.Sprintf("$mount = '%s' ; $ErrorActionPreference = 'Stop' ; New-Item -ItemType Directory -Path $mount ; $disk = Get-Disk | Where-Object { $_.SerialNumber -eq '%s' } ; $partition = Get-Partition -DiskNumber $disk.DiskNumber | Where-Object { $_.Type -in 'Basic', 'IFS' } ; Add-PartitionAccessPath -DiskNumber $disk.DiskNumber -PartitionNumber $partition.PartitionNumber -AccessPath $mount", step.WorkspaceBase, uuid) + utf16leBytes, err := encoder.Bytes([]byte(exec)) + if err != nil { + return err + } + + args := []string{"-noprofile", "-noninteractive", "-encodedcommand", base64.StdEncoding.EncodeToString(utf16leBytes)} + err = AdhocSSH(ctx, client, cmd, args, taskUUID, step.UUID) + if err != nil { + return err + } + case "freebsd": + // create dir + { + err := AdhocSSHElevated(ctx, client, "mkdir", []string{"-p", step.WorkspaceBase}, taskUUID, step.UUID) + if err != nil { + return err + } + } + + // mount + { + err := AdhocSSHElevated(ctx, client, "mount", []string{fmt.Sprintf("/dev/gptid/%s", uuid), step.WorkspaceBase}, taskUUID, step.UUID) + if err != nil { + return err + } + } + case "darwin": + // create dir + { + err := AdhocSSHElevated(ctx, client, "mkdir", []string{"-p", step.WorkspaceBase}, taskUUID, step.UUID) + if err != nil { + return err + } + } + + // mount + { + err := AdhocSSHElevated(ctx, client, "diskutil", []string{"mount", "-mountPoint", step.WorkspaceBase, uuid}, taskUUID, step.UUID) + if err != nil { + return err + } + } + default: + // create dir + { + err := AdhocSSHElevated(ctx, client, "mkdir", []string{"-p", step.WorkspaceBase}, taskUUID, step.UUID) + if err != nil { + return err + } + } + + // mount + { + mountSource := fmt.Sprintf("UUID=%s", uuid) + err := AdhocSSHElevated(ctx, client, "mount", []string{"-o", mountSource, step.WorkspaceBase}, taskUUID, step.UUID) + if err != nil { + return err + } + } + } + + sshCmd, err := client.Command(cmd, args...) + if err != nil { + return err + } + + e.commands.Store(step.UUID, sshCmd) + + // we need to create pipes and set Stdout here + // in TailStep it is potentially too late + pr, pw := nio.Pipe(buffer.New(logBufferSize)) + sshCmd.Stdout = nil // see comment below + sshCmd.Stderr = nil + + var wg sync.WaitGroup + + wg.Add(1) + stdoutR, err := sshCmd.StdoutPipe() + if err != nil { + return err + } + wg.Add(1) + stderrR, err := sshCmd.StderrPipe() + if err != nil { + return err + } + stdinWC, err := sshCmd.StdinPipe() + if err != nil { + return err + } + + go func() { + // We need to close the write end ourselves on EOF from the server + // otherwise the read side of our pipe never drains and Wait() deadlocks. + // If we assign 'sshCmd.Stdout = pw', the library internals only copy + // but never close pw, because they are oblivious to the fact that it's + // a pipe. So we need to implement the copy+close ourselves. There is no + // EOF callback. + _, _ = io.Copy(pw, stdoutR) + wg.Done() + }() + + go func() { + _, _ = io.Copy(pw, stderrR) + wg.Done() + }() + + go func() { + wg.Wait() + pw.Close() + log.Debug().Msg("Closing write pipe end") + }() + + e.pipesStdOut.Store(step.UUID, &pipes{pr, pw}) + + done := make(chan struct{}) + e.doneChannel.Store(step.UUID, done) + // and a go routine that watches the ctx and then triggers a signal + go func() { + select { + case <-ctx.Done(): + // ctx is canceled already, so only keep its values + err := e.TerminateSSHCommand(context.WithoutCancel(ctx), options, client, sshCmd, guestOS, taskUUID, step.UUID) + if err != nil { + log.Debug().Msgf("Failed to terminate SSH command gracefully. Closing session by force. Error was: %s", err) + } + sshCmd.Close() + case <-done: + } + time.Sleep(time.Second * 5) + log.Debug().Msg("Closing read pipe end") + _ = pr.Close() + }() + + err = sshCmd.Start() + if err != nil { + return err + } + + // now feed the actual command to stdin + go func() { + _, err := stdinWC.Write([]byte(scriptIn)) + if err != nil { + log.Debug().Msgf("Failed to write cmd to stdin: %s", err) + } + stdinWC.Close() + log.Debug().Msg("Closing stdin") + }() + + return nil +} + +func (e *libvirt) WaitStep(ctx context.Context, step *backend_types.Step, taskUUID string) (*backend_types.State, error) { + switch step.Type { + case backend_types.StepTypeClone: + return nil, ErrUnsupportedCloning + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: + return nil, ErrUnsupportedStepType + default: + return nil, ErrUnsupportedStepType + } + + defer e.unlockStep() + + sshCmd, ok := load[*goph.Cmd](&e.commands, step.UUID) + if !ok { + return nil, fmt.Errorf("could not find key %s for commands", step.UUID) + } + + done, ok := load[chan struct{}](&e.doneChannel, step.UUID) + if !ok { + return nil, fmt.Errorf("could not find key %s for doneChannel", step.UUID) + } + + sshErr := sshCmd.Wait() + close(done) + + domain, ok := load[*virt.Domain](&e.domains, step.UUID) + if !ok { + return nil, fmt.Errorf("could not find key %s for domains", step.UUID) + } + + // we need to shut down the VM here, because DestroyStep is less reliable + // in terms of timing and can lead to deadlocks when two steps are trying + // to acquire a lock + err := ShutdownVM(ctx, domain) + if err != nil { + return nil, err + } + e.domains.Delete(step.UUID) + + var exitMissingErr *ssh.ExitMissingError + var exitErr *ssh.ExitError + switch { + case errors.As(sshErr, &exitMissingErr): + return &backend_types.State{ + Exited: true, + ExitCode: -1, + OOMKilled: false, + }, sshErr + case errors.As(sshErr, &exitErr): + return &backend_types.State{ + Exited: true, + ExitCode: exitErr.ExitStatus(), + OOMKilled: false, + }, sshErr + case sshErr == nil: + return &backend_types.State{ + Exited: true, + ExitCode: 0, + OOMKilled: false, + }, sshErr + default: + return nil, sshErr + } +} + +// load returns the value of key in m if it has type T. +func load[T any](m *sync.Map, key string) (T, bool) { + v, _ := m.Load(key) + t, ok := v.(T) + return t, ok +} + +func (e *libvirt) unlockStep() { + err := mutex.SafeUnlock(&e.stepLock) + if err != nil { + log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) + } +} + +type closerFunc func() error + +func (f closerFunc) Close() error { return f() } + +func (e *libvirt) TailStep(ctx context.Context, step *backend_types.Step, taskUUID string) (io.ReadCloser, error) { + switch step.Type { + case backend_types.StepTypeClone: + return nil, ErrUnsupportedCloning + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: + return nil, ErrUnsupportedStepType + default: + return nil, ErrUnsupportedStepType + } + + pOut, ok := load[*pipes](&e.pipesStdOut, step.UUID) + if !ok { + return nil, fmt.Errorf("could not find key %s for pipesStdOut", step.UUID) + } + + rc := struct { + io.Reader + io.Closer + }{ + Reader: pOut.pr, + Closer: closerFunc(func() error { + log.Debug().Msgf("Done log streaming") + return nil + }), + } + + return rc, nil +} + +func (e *libvirt) DestroyStep(ctx context.Context, step *backend_types.Step, taskUUID string) error { + switch step.Type { + case backend_types.StepTypeClone: + // ignore cloning for now + return ErrUnsupportedCloning + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: + return ErrUnsupportedStepType + default: + return ErrUnsupportedStepType + } + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + + defer func() { + // release lock + e.unlockStep() + + keepTmp := e.c.Bool("backend-libvirt-keep-tmp") + + // clean up ephemeral image + if !keepTmp { + ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(baseImagePattern, "*", taskUUID, step.UUID, ".*")) + matches, err := filepath.Glob(ephemeralImgs) + if err != nil { + log.Debug().Msg(err.Error()) + } + + for _, m := range matches { + log.Debug().Msgf("Deleting base image: %s", m) + err := os.Remove(m) + if err != nil { + log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) + } + } + + nvram := filepath.Join(libvirtImgDir, fmt.Sprintf(nvramImagePattern, taskUUID, step.UUID)) + _, statErr := os.Stat(nvram) + if statErr == nil { + log.Debug().Msgf("Deleting nvram image: %s", nvram) + err := os.Remove(nvram) + if err != nil { + log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) + } + } + } + }() + + sshCmd, ok := load[*goph.Cmd](&e.commands, step.UUID) + if !ok { + return fmt.Errorf("could not find key %s for commands", step.UUID) + } + log.Debug().Msgf("Destroying ssh connection") + + // closing may return EOF, which we can ignore + _ = sshCmd.Close() + + e.commands.Delete(step.UUID) + + // the domain has already been shutdown in WaitStep + e.domains.Delete(step.UUID) + + return nil +} + +func (e *libvirt) DestroyWorkflow(ctx context.Context, conf *backend_types.Config, taskUUID string) error { + e.unlockStep() + + e.commands.Range(func(key, value any) bool { + if sshCmd, ok := value.(*goph.Cmd); ok { + _ = sshCmd.Close() + } + e.commands.Delete(key) + return true + }) + e.domains.Range(func(key, value any) bool { + if domain, ok := value.(*virt.Domain); ok { + err := ShutdownVM(ctx, domain) + if err != nil { + log.Debug().Msgf("Error while shutting down domain: %s", err.Error()) + } + } + e.domains.Delete(key) + return true + }) + + keepTmp := e.c.Bool("backend-libvirt-keep-tmp") + + // clean up shared disk + if !keepTmp { + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(sharedDiskPattern, taskUUID, ".*")) + matches, err := filepath.Glob(ephemeralImgs) + if err != nil { + return err + } + + for _, m := range matches { + err := os.Remove(m) + log.Debug().Msgf("Deleting shared image: %s", m) + if err != nil { + return err + } + } + } + + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + + // clean up ephemeral images + if !keepTmp { + { + ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(baseImagePattern, "*", taskUUID, "*", ".*")) + matches, err := filepath.Glob(ephemeralImgs) + if err != nil { + return err + } + + for _, m := range matches { + err := os.Remove(m) + log.Debug().Msgf("Deleting base image: %s", m) + if err != nil { + return err + } + } + } + + { + nvram := filepath.Join(libvirtImgDir, fmt.Sprintf(nvramImagePattern, taskUUID, "*")) + matches, err := filepath.Glob(nvram) + if err != nil { + return err + } + + for _, m := range matches { + err := os.Remove(m) + log.Debug().Msgf("Deleting nvram image: %s", m) + if err != nil { + return err + } + } + } + } + + return nil +} diff --git a/pipeline/backend/libvirt/libvirt_disabled.go b/pipeline/backend/libvirt/libvirt_disabled.go new file mode 100644 index 00000000000..2e0dc97855a --- /dev/null +++ b/pipeline/backend/libvirt/libvirt_disabled.go @@ -0,0 +1,52 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !cgo || !libvirt + +package libvirt + +import ( + "context" + "errors" + + "github.com/urfave/cli/v3" + + backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" +) + +const engineName = "libvirt" + +type stub struct { + backend_types.Backend +} + +func New() backend_types.Backend { + return &stub{} +} + +func (*stub) Name() string { + return engineName +} + +// IsAvailable is true if explizite selected, so Load can return error. +func (*stub) IsAvailable(ctx context.Context) bool { + c, ok := ctx.Value(backend_types.CliCommand).(*cli.Command) + return ok && c.String("backend-engine") == engineName +} + +func (*stub) Flags() []cli.Flag { return nil } + +func (*stub) Load(context.Context) (*backend_types.BackendInfo, error) { + return nil, errors.New("libvirt backend is not compiled in, compile backend with LIBVIRT_ENABLED=true") +} diff --git a/pipeline/backend/libvirt/prelude.go b/pipeline/backend/libvirt/prelude.go new file mode 100644 index 00000000000..bc6bfd3e454 --- /dev/null +++ b/pipeline/backend/libvirt/prelude.go @@ -0,0 +1,95 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "errors" + "fmt" + "io" + "math/rand" + "os" + "os/exec" + "time" +) + +func CmdViaSudo(cmd string, arg ...string) *exec.Cmd { + if hasCommand("sudo") { + return exec.Command("sudo", append([]string{cmd}, arg...)...) + } else { + return exec.Command(cmd, arg...) + } +} + +// cmdError adds the command and its stderr to err. +func cmdError(cmd *exec.Cmd, err error) error { + if exitErr, ok := errors.AsType[*exec.ExitError](err); ok { + return fmt.Errorf("command %s failed with %w and stderr: %s", cmd, err, exitErr.Stderr) + } + return fmt.Errorf("command %s failed with %w", cmd, err) +} + +func hasCommand(cmd string) bool { + _, err := exec.LookPath(cmd) + return err == nil +} + +func CopyFile(from, to string, overwrite bool) error { + fromFile, err := os.Open(from) + if err != nil { + return err + } + defer fromFile.Close() + + if !overwrite { + _, err := os.Stat(to) + if err == nil { + return fmt.Errorf("file %s already exists", to) + } + } + + toFile, err := os.Create(to) + if err != nil { + return err + } + defer toFile.Close() + + _, err = io.Copy(toFile, fromFile) + if err != nil { + return err + } + + return nil +} + +// derived from https://github.com/rprata/macgo/blob/85ffbfd9b6ec3c18bde5640302adf7521ef1c2c2/generator/generator.go#L11 +// MIT licensed. +func GenerateRandomMACAddress() (string, error) { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + + macBytes := make([]byte, 6) + + _, _ = r.Read(macBytes) // never fails + + // we want locally administered unicast + macBytes[0] |= 0x02 + macBytes[0] &^= 0x01 + + macAddress := fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", + macBytes[0], macBytes[1], macBytes[2], macBytes[3], macBytes[4], macBytes[5]) + + return macAddress, nil +} diff --git a/pipeline/backend/libvirt/prelude_test.go b/pipeline/backend/libvirt/prelude_test.go new file mode 100644 index 00000000000..c700ec86c28 --- /dev/null +++ b/pipeline/backend/libvirt/prelude_test.go @@ -0,0 +1,49 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "errors" + "os/exec" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCmdError(t *testing.T) { + t.Run("exit error", func(t *testing.T) { + cmd := exec.Command("sh", "-c", "echo broken >&2; exit 3") + _, err := cmd.Output() + require.Error(t, err) + + err = cmdError(cmd, err) + assert.ErrorContains(t, err, "and stderr: broken") + _, ok := errors.AsType[*exec.ExitError](err) + assert.True(t, ok) + }) + + t.Run("command not found", func(t *testing.T) { + cmd := exec.Command("woodpecker-command-that-does-not-exist") + _, err := cmd.Output() + require.Error(t, err) + + err = cmdError(cmd, err) + assert.ErrorContains(t, err, "command woodpecker-command-that-does-not-exist failed with") + assert.ErrorIs(t, err, exec.ErrNotFound) + }) +} diff --git a/pipeline/backend/libvirt/script.go b/pipeline/backend/libvirt/script.go new file mode 100644 index 00000000000..7d75eab6348 --- /dev/null +++ b/pipeline/backend/libvirt/script.go @@ -0,0 +1,54 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "maps" + + backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" +) + +func GenerateSSHConf(step *backend_types.Step, osType string) (stdin string, entry []string, err error) { + env := make(map[string]string) + maps.Copy(env, step.Environment) + var script string + if osType == "windows" { + env["SHELL"] = "powershell.exe" + env["CI_WRITE_PID"] = "yes" + + // The libvirt backend does not expose the CI_SCRIPT env var. + // Because we inject the `export CI_FOO=bar` expressions into the script itself, + // this would pose two problems: + // + // 1. CI_SCRIPT is now self-referencing + // 2. CI_SCRIPT would contain the secrets + script = generateScriptWindows(step.Commands, env, step.WorkingDir, step.UUID, true) + + entry = []string{"powershell", "-noprofile", "-noninteractive", "-command", "-"} + } else { + env["SHELL"] = "/bin/sh" + env["CI_WRITE_PID"] = "yes" + + // same comment as for windows applies + script = generateScriptPosix(step.Commands, env, step.WorkingDir, step.UUID, true) + + // cspell:disable-next-line + entry = []string{"/bin/sh", "-e"} + } + + return script, entry, nil +} diff --git a/pipeline/backend/libvirt/script_posix.go b/pipeline/backend/libvirt/script_posix.go new file mode 100644 index 00000000000..a163a55cfea --- /dev/null +++ b/pipeline/backend/libvirt/script_posix.go @@ -0,0 +1,112 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "bytes" + "encoding/base64" + "fmt" + "text/template" +) + +// generateScriptPosix is a helper function that generates a step script +// for a linux container using the given. +func generateScriptPosix(commands []string, env map[string]string, workDir, stepUUID string, injectEnv bool) string { + var buf bytes.Buffer + var envBuf bytes.Buffer + + if injectEnv { + for key, val := range env { + fmt.Fprintf( + &envBuf, + `export %s="$(printf '%%s' '%s' | b64decode)"; + `, + key, + base64.StdEncoding.EncodeToString([]byte(val)), + ) + } + } + + setupScriptTmpl, _ := template.New("").Parse(setupScriptProto) + + if err := setupScriptTmpl.Execute(&buf, map[string]string{ + "WorkDir": workDir, + "Pid": stepUUID, + "Env": envBuf.String(), + }); err != nil { + // should never happen but well we have an error to trace + return fmt.Sprintf("echo 'failed to generate posix script from commands: %s'; exit 1", err.Error()) + } + + for _, command := range commands { + fmt.Fprintf( + &buf, + traceScript, + command, + command, + ) + } + + return buf.String() +} + +// setupScriptProto is a helper script this is added to the step script to ensure +// a minimum set of environment variables are set correctly. +const setupScriptProto = ` +set +m + +b64decode() { + if echo "bG9sCg==" | base64 -d >/dev/null 2>&1 ; then + base64 -d + elif echo "bG9sCg==" | base64 -D >/dev/null 2>&1 ; then + base64 -D + else + openssl base64 -d -A + fi +} + +if [ -n "$CI_NETRC_MACHINE" ]; then +cat < $HOME/.netrc +machine $CI_NETRC_MACHINE +login $CI_NETRC_USERNAME +password $CI_NETRC_PASSWORD +EOF +chmod 0600 $HOME/.netrc +fi +unset CI_NETRC_USERNAME +unset CI_NETRC_PASSWORD +unset CI_SCRIPT +mkdir -p "{{.WorkDir}}" +cd "{{.WorkDir}}" +{{.Env}} +if [ -n "$CI_WRITE_PID" ]; then +{ + printf "%s" "$$" > "${TMPDIR:-/tmp}/woodpecker_{{.Pid}}.pid" || true +} +fi +` + +// traceScript is a helper script that is added to the step script +// to trace a command. +const traceScript = ` +cat <<'WOODPECKER_EOF' +▶ %s +WOODPECKER_EOF +{ + %s +} > $netrc; +"login $Env:CI_NETRC_USERNAME" >> $netrc; +"password $Env:CI_NETRC_PASSWORD" >> $netrc; +}; +[Environment]::SetEnvironmentVariable("CI_NETRC_PASSWORD",$null); +[Environment]::SetEnvironmentVariable("CI_SCRIPT",$null); +cd "{{.WorkDir}}"; +{{.Env}} +if ([Environment]::GetEnvironmentVariable('CI_WRITE_PID')) { $PID | Set-Content -Path "$env:TEMP\woodpecker_{{.Pid}}.pid" -NoNewline }; +` + +// traceScript is a helper script that is added to the step script +// to trace a command. +const traceScriptWin = ` +Write-Output @' +▶ %s +'@ + +& { + %s ; + if ($LASTEXITCODE) { exit $LASTEXITCODE } ; +} ; + +` diff --git a/pipeline/backend/libvirt/ssh.go b/pipeline/backend/libvirt/ssh.go new file mode 100644 index 00000000000..24576b7ffaf --- /dev/null +++ b/pipeline/backend/libvirt/ssh.go @@ -0,0 +1,260 @@ +// Copyright 2026 Julian Ospald +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build cgo && libvirt + +package libvirt + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "os" + "time" + + "github.com/cenkalti/backoff/v7" + "github.com/melbahja/goph" + "github.com/rs/zerolog/log" + "golang.org/x/crypto/ssh" + "golang.org/x/text/encoding/unicode" +) + +func AdhocSSH(ctx context.Context, client *goph.Client, cmd string, args []string, taskUUID, stepUUID string) error { + sshCmd, err := client.CommandContext(ctx, cmd, args...) + log.Debug().Msgf("Executing via ssh: %s %v", cmd, args) + if err != nil { + return err + } + sshCmd.Stdout = os.Stdout + sshCmd.Stderr = os.Stderr + err = sshCmd.Run() + + return err +} + +func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args []string, taskUUID, stepUUID string) error { + var out string + // first figure out if we have 'sudo' or 'doas', so we can have the right privilege escalation mechanism + { + cmd := "/bin/sh" + args := []string{"-c", `'if command -v sudo >/dev/null 2>&1 ; then printf "%s" "sudo" ; elif command -v doas >/dev/null 2>&1 ; then printf "%s" "doas" ; else exit 0 ; fi'`} + sshCmd, err := client.CommandContext(ctx, cmd, args...) + if err != nil { + return err + } + b, err := sshCmd.Output() + if err != nil { + return fmt.Errorf("failed to check for sudo: %w", err) + } + out = string(b) + } + + var command []string + switch out { + case "sudo": + command = append([]string{"sudo", cmd}, args...) + case "doas": + command = append([]string{"doas", cmd}, args...) + case "": + log.Debug().Msgf("Running as root") + command = append([]string{cmd}, args...) + default: + return fmt.Errorf("unexpected privilege escalation command: %s", out) + } + + // execute command + return AdhocSSH(ctx, client, command[0], command[1:], taskUUID, stepUUID) +} + +// This tries to terminate the command we spawned, not the SSH session itself. +// It does so, by: +// +// 1. Send SIGINT. If that does not work: +// 2. Send SIGTERM. If that does not work: +// 3. Execute 'kill -2 '. +// +// We could also try to attach to stdin and send 'Ctrl+c', but that opens up other issues (closing channel +// at the appropriate time etc.). +func (e *libvirt) TerminateSSHCommand(ctx context.Context, options BackendOptions, client *goph.Client, sshCmd *goph.Cmd, guestOS, taskUUID, stepUUID string) error { + pid, err := GetWoodpeckerPid(client, guestOS, stepUUID) + if err != nil { + return err + } + log.Debug().Msgf("PID: %s", pid) + + if guestOS == "windows" { + // on windows... we just do taskkill + // SIGINT works, but doesn't seem to kill the whole process group + rawCmd := fmt.Sprintf("taskkill /PID %s /F /T", pid) + encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() + utf16leBytes, err := encoder.Bytes([]byte(rawCmd)) + if err != nil { + return err + } + base64Cmd := base64.StdEncoding.EncodeToString(utf16leBytes) + sshCmd, err := client.Command("powershell.exe", "-noprofile", "-noninteractive", "-encodedcommand", base64Cmd) + if err != nil { + return err + } + err = sshCmd.Run() + if err != nil { + log.Debug().Msgf("Running taskkill failed with: %s", err) + } + + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) + if err != nil { + return err + } + if running { + return errors.New("all methods exhausted, failed to stop SSH process") + } + } else { + // try sigint first + log.Debug().Msg("Context canceled, sending SIGINT to remote process") + err := sshCmd.Signal(ssh.SIGINT) + if err != nil { + log.Debug().Msgf("Failed to send SIGINT to remote process: %s", err) + } + + // check if the process died + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) + if err != nil { + return err + } + // try SIGTERM + if running { + log.Debug().Msg("SIGINT didn't work, trying SIGTERM") + err := sshCmd.Signal(ssh.SIGTERM) + if err != nil { + log.Debug().Msgf("Failed to send SIGTERM to remote process: %s", err) + } + + // check if the process died + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) + if err != nil { + return err + } + + if running { + log.Debug().Msg("SIGTERM didn't work, sending kill -2 manually") + + // try kill -2 pid + sshCmd, err := client.Command("kill", "-2", pid) + if err != nil { + return err + } + err = sshCmd.Run() + if err != nil { + return err + } + + // check if the process died + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) + if err != nil { + return err + } + if running { + return errors.New("all methods exhausted, failed to stop SSH process") + } + } + } + } + + return nil +} + +func GetWoodpeckerPid(client *goph.Client, guestOS, stepUUID string) (string, error) { + var sshCmd *goph.Cmd + + // assembler the per-platform command to get the running pid + if guestOS == "windows" { + rawCmd := fmt.Sprintf("Get-Content -Path $env:TEMP\\woodpecker_%s.pid -Raw", stepUUID) + encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() + utf16leBytes, err := encoder.Bytes([]byte(rawCmd)) + if err != nil { + return "", err + } + base64Cmd := base64.StdEncoding.EncodeToString(utf16leBytes) + + sshCmd, err = client.Command("powershell.exe", "-noprofile", "-noninteractive", "-encodedcommand", base64Cmd) + if err != nil { + return "", err + } + } else { + var err error + sshCmd, err = client.Command("/bin/sh", "-c", fmt.Sprintf("'cat ${TMPDIR:-/tmp}/woodpecker_%s.pid'", stepUUID)) + if err != nil { + return "", err + } + } + + // extract stdout + bytes, err := sshCmd.Output() + if err != nil { + return "", err + } + return string(bytes), nil +} + +// (Re-)Check if the spawned process is still running with a timeout of 15s. +func CheckSSHPid(ctx context.Context, pid string, client *goph.Client, guestOS, stepUUID string) (bool, error) { + var sshCmd *goph.Cmd + maxBackOff, _ := time.ParseDuration("15s") + + // assemble the per-platform command to check for pid + if guestOS == "windows" { + rawCmd := fmt.Sprintf("Get-Process -Id %s", pid) + encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() + utf16leBytes, err := encoder.Bytes([]byte(rawCmd)) + if err != nil { + return true, err + } + base64Cmd := base64.StdEncoding.EncodeToString(utf16leBytes) + + sshCmd, err = client.Command("powershell.exe", "-noprofile", "-noninteractive", "-encodedcommand", base64Cmd) + if err != nil { + return true, backoff.Permanent(fmt.Errorf("error running command: %w", err)) + } + } else { + var err error + sshCmd, err = client.Command("kill", "-0", pid) + if err != nil { + return true, backoff.Permanent(fmt.Errorf("error running command: %w", err)) + } + } + + // run with exponential backoff + b, _ := backoff.Retry(ctx, func() (bool, error) { + sshErr := sshCmd.Run() + // if we can't figure out if it's running... assume it is + var exitMissingErr *ssh.ExitMissingError + var exitErr *ssh.ExitError + switch { + case errors.As(sshErr, &exitMissingErr): + log.Debug().Msgf("ExitMissingError in CheckSSHPid: %s", sshErr) + return true, nil + case errors.As(sshErr, &exitErr): + log.Debug().Msgf("ExitError in CheckSSHPid: %s", sshErr) + return false, nil + case sshErr == nil: + return true, fmt.Errorf("process still running") + default: + log.Debug().Msgf("Unexpected error in CheckSSHPid: %s", sshErr) + return true, nil + } + }, backoff.WithMaxElapsedTime(maxBackOff)) + + return b, nil +}